Graine AI

Kotlin Multiplatform SDK reference

Every public class, function, property, event and error of ai.graine:inapp-kmp 0.13.1 and ai.graine:inapp-kmp-compose 0.13.1, grouped by what you use it for: signatures, parameters, what each returns, the errors it raises, and what to expect.

Every public declaration of the Kotlin Multiplatform SDK — ai.graine:inapp-kmp 0.13.0, one API in shared code over Graine's Android and iOS SDKs, and ai.graine:inapp-kmp-compose 0.13.0, the SDK's own screens for Compose Multiplatform — grouped by what you use it for, with what 0.13.0 adds marked New in 0.13.0 (What's new in 0.13.0). Each entry says what it is for, then gives its signature, its parameters, what it returns, the errors it can raise and an example; each type lists its fields with what to expect. The same API across every platform, topic by topic, is the SDK reference; installing and setting up is Kotlin Multiplatform.

Requirements, install, permissions and initialisation

Artifactsai.graine:inapp-kmp:0.15.4 (the shared API) and ai.graine:inapp-kmp-compose:0.15.4 (the chat, the call screen and the voice bar for Compose Multiplatform), on Maven Central
RequiresKotlin 2.1.20 or newer; targets androidTarget, iosArm64, iosSimulatorArm64 and iosX64; Android 7.0 (API 24) and up; iOS 15 and up. Depends on kotlinx-coroutines and kotlinx-datetime only (and Compose, for the compose artifact)
How it worksOne API in shared code over the native SDKs: the Android SDK (ai.graine:inapp-android 0.13.1) comes with it; on iOS your app links the iOS SDK (GraineInApp 0.13.1) itself, so it is never in the app twice
In the dashboardAdd app:// to the agent's Allowed domains (Agent → Embed & Widgets); without it every request is refused

Gradle (Kotlin DSL) — shared/build.gradle.kts

kotlin {
    androidTarget()
    iosArm64(); iosSimulatorArm64(); iosX64()
    sourceSets {
        commonMain.dependencies {
            implementation("ai.graine:inapp-kmp:0.15.4")
            implementation("ai.graine:inapp-kmp-compose:0.15.4")
        }
    }
}
  • Android. The Android SDK's manifest comes with it — the microphone and notification permissions, the call screen, the call service — so there is nothing to copy (what it adds, and how to remove the calls entries from an app without calls, is on the Android reference). The library finds your application by itself, so Graine.configure(config) works from shared code. Ask for POST_NOTIFICATIONS on Android 13 and up during onboarding — without it the phone cannot ring. An activity that shows the voice bar or places calls forwards its permission answers to Graine.onRequestPermissionsResult(requestCode, grantResults). For calls Graine rings, add Firebase Cloud Messaging to the Android app (google-services.json, its Gradle plugin and com.google.firebase:firebase-messaging): the SDK registers for pushes itself. An app with a FirebaseMessagingService of its own, which outranks the SDK's, calls Graine.calls.onNewToken(token) and Graine.calls.handlePush(message.data) from it.
  • iOS. Add the iOS SDK to the app: with Swift Package Manager (https://github.com/GraineAI/inapp-ios, from 0.13.1) and your shared framework built static (isStatic = true, the Compose Multiplatform default), or with CocoaPods (pod 'GraineInApp'; with Kotlin's CocoaPods plugin and a dynamic framework, pod("GraineInApp") { version = "0.13.1"; linkOnly = true }). Add NSMicrophoneUsageDescription to Info.plist, and for calls Push Notifications and Background Modes → Audio and Voice over IP. Call Graine.calls.enableVoIPPushes() at every launch. Link GraineInApp 0.13.1, the version of this library: with an older one (0.7.0), booking is not available on iOS — bookingAvailable is false and presentBooking throws Unavailable — and everything else works.

Kotlin Multiplatform · Kotlin — commonMain

Graine.configure(GraineConfig(
    baseUrl = "https://www.graine.ai",
    publishableKey = "pk_live_…",          // Agent → Embed & Widgets → Install
    appVersion = "2.4.0",
))
Graine.calls.configure(GraineCallsConfig(displayName = "Acme"))
 
// Compose Multiplatform UI
Box(Modifier.fillMaxSize()) {
    AppContent()
    GraineAgentBar(Modifier.align(Alignment.BottomCenter).fillMaxWidth().height(180.dp))
}

Every function may be called from any thread; the suspending ones never block the main thread; the states are flows that always hold the latest value.

WebRTC calls (optional)

Native calls carry their audio over a WebSocket — in both directions: the person calling the agent (startCall, your “Call us” button) and the person answering a call Graine rang (a booked call, Ring now). Add each platform's WebRTC module to the app and they carry it over WebRTC instead. Nothing in shared code changes: the same ring, the same call screen, the same “Connecting…”, the same outcomes.

Gradle (Kotlin DSL) — shared/build.gradle.kts, the Android side

kotlin {
    sourceSets {
        androidMain.dependencies {
            implementation("ai.graine:inapp-android-rtc:0.15.4")   // the same version as ai.graine:inapp-android
        }
    }
}
  • Android. ai.graine:inapp-android-rtc, at the same version as the Android SDK this library brings (ai.graine:inapp-android 0.13.1) — in androidMain as above, or in the Android app's own dependencies. Its manifest adds ACCESS_NETWORK_STATE, a normal permission granted at install: nothing is asked. Its R8 rules ship inside it. Size per phone (an app bundle delivers one ABI): about 7.4 MB installed on 64-bit ARM (about 2.5–3.3 MB to download), 4.3 MB on 32-bit ARM, 8.2–8.4 MB on x86, and about 0.5 MB of classes.
  • iOS. The GraineInAppRTC package, added to the iOS app target beside GraineInApp, the same way and at the same version: with Swift Package Manager https://github.com/GraineAI/inapp-ios-rtc (its library GraineInAppRTC), or with CocoaPods pod 'GraineInAppRTC', :git => 'https://github.com/GraineAI/inapp-ios-rtc.git', :tag => '0.15.4'. No code, no Info.plist entry, no capability: the calls find the module by themselves. A build that strips code nothing references can call GraineRTC.install() at launch from the app's Swift code (import GraineInAppRTC); GraineRTCVersion.name is the module's version. About 12 MB more installed on an arm64 iPhone, about 6 MB more to download. If another package in the app pins the same WebRTC build at a different version, the two cannot be resolved together: leave the module out (calls stay on the WebSocket) or align the versions.
  • Choosing. GraineCallsConfig(callTransport = …), a GraineCallTransport: AUTO, the default — WebRTC when the module is in the app and the dashboard allows it, else the WebSocket; WEBSOCKET — always the WebSocket; WEBRTC — WebRTC wherever it can carry the call (the WebSocket only when the module is missing or WebRTC cannot set up this call).
  • The dashboard's switch. The agent's In-app call audio setting (agent → Calls & scheduling): WebRTC (recommended) or Standard. Standard moves every install's calls back to the WebSocket, whatever the app chose, from each app's next start — no app release.
  • What the person notices. On a weak or changing network the agent's voice holds up instead of stalling and catching up: a jitter buffer, loss concealment and the platform's echo canceller. The call is prepared at the tap, or while a ring is showing, so it connects as fast as before. Over WebRTC the agent's voice arrives at telephone bandwidth today: steadier through a weak network, narrower than the WebSocket's on a perfect one.
  • When WebRTC cannot set up a call before any audio flows — a network that blocks it, a server that turns it down, no answer within the time allowed (about 12 seconds in all) — the call continues on the WebSocket inside the same call: no second ring, no new call screen, no error; “Connecting…” shows a moment longer. A call the agent cannot take at all (no credit left, the agent switched off) ends with that reason, exactly as without the module. Once audio flows, a call never moves: a network drop is retried once, then the call ends as dropped. Graine.calls.state says which one carried a call — transport and transportFallbackReason (GraineCallInfo).
  • Licences. A prebuilt WebRTC library (Google's WebRTC, BSD 3-Clause, its symbols renamed so it never clashes with another copy in the app): list it in your app's open-source notices. Android: graine-inapp-rtc/THIRD-PARTY-NOTICES.md; iOS: the package's THIRD-PARTY-NOTICES.md.

Kotlin Multiplatform · Kotlin — commonMain

Graine.calls.configure(GraineCallsConfig(displayName = "Acme", callTransport = GraineCallTransport.AUTO))

Install and the first answer

Configure the SDK once at launch, then read the agent's settings when they arrive. Calling anything on Graine before configure throws IllegalStateException (“Graine.configure(GraineConfig(…)) has not been called. Call it once, at launch.”).

Graine.configure

Call it once at launch — in Application.onCreate on Android, the app's init on iOS — to start the agent.

fun configure(config: GraineConfig, name: String = DEFAULT_AGENT): GraineAgent

Without a name it starts the default agent, which everything on Graine belongs to. An app with several agents configures each under its own name and key (Several agents). Asking again for a name already set up gives you that same agent; the configuration passed the second time is ignored. On Android the SDK finds the application by itself; on iOS the agent is the iOS SDK's agent under that name — one the app already configured from Swift is used as it is.

ParameterTypeDefaultMeaning
configGraineConfigrequiredThe agent's publishable key, the base URL and the options (GraineConfig).
nameStringDEFAULT_AGENTThe name to configure the agent under — leave it out for the default agent, which is "default"; blank is the default too.

Returns — GraineAgent — the agent (GraineAgent).

Errors — IllegalStateException on Android when the application cannot be found (“Graine could not find the application. Keep ai.graine.inapp.kmp.GraineInitProvider in the manifest, or call Graine.configure(context, config) on Android.”), and on iOS when the iOS SDK cannot configure the agent.

Graine.configure(GraineConfig(baseUrl = "https://www.graine.ai", publishableKey = "pk_live_…"))

Graine.configure (Android, with a context)

Use it on Android only when your app removed GraineInitProvider from its manifest, so the SDK cannot find the application itself.

fun Graine.configure(context: Context, config: GraineConfig, name: String = Graine.DEFAULT_AGENT): GraineAgent

The same as Graine.configure(config, name), with the application taken from context. In androidMain only.

ParameterTypeDefaultMeaning
contextContextrequiredAny Android context of your app — the Application or an Activity.
configGraineConfigrequiredThe agent's key, base URL and options.
nameStringGraine.DEFAULT_AGENTThe name to configure the agent under; the default agent when left out.

Returns — GraineAgent.

Errors — none.

import android.app.Application
 
class AcmeApp : Application() {
    override fun onCreate() {
        super.onCreate()
        Graine.configure(this, GraineConfig(baseUrl = "https://www.graine.ai", publishableKey = "pk_live_…"))
    }
}

Graine

Use it for everything: it is the SDK, and the default agent.

object Graine

Configure it once at launch. Who the user is, this install, the memory choice, the screen and the phone's calls belong to the app and are shared by every agent; everything else on Graine is the default agent's.

What to expect — Every member may be called from any thread; calling anything but configure before it throws IllegalStateException. The flows always hold the latest value; events is not replayed.

PropertyTypeMeaning
const val DEFAULT_AGENT = "default"StringUse it to name the default agent explicitly — Graine.agent(Graine.DEFAULT_AGENT).
val agents: Map<String, GraineAgent>Map<String, GraineAgent>Read it to list every configured agent, by name, in the order they were configured.
val isConfigured: BooleanBooleanRead it to know whether the default agent has been configured — before calling anything else from code that may run first.
val session: StateFlow<GraineSession?>StateFlow<GraineSession?>Collect it to know when the default agent's settings have loaded (Graine.session); null before.
val theme: StateFlow<GraineThemeTokens?>StateFlow<GraineThemeTokens?>Collect it to draw UI of your own in the brand's design: the default agent's design tokens for the phone's light or dark appearance (Graine.theme); null before the settings load.
val events: SharedFlow<GraineEvent>SharedFlow<GraineEvent>Collect it, from app start, to hear what the default agent reports that is not a state (GraineEvent). Not replayed.
val chat: GraineChatGraineChatUse it to drive the default agent's chat (GraineChat).
val voice: GraineVoiceGraineVoiceUse it to drive the default agent's voice-bar call (GraineVoice).
val calls: GraineCallsGraineCallsUse it for native calls — the app's, whichever agent a call is with (GraineCalls).
val avatar: GraineAvatarGraineAvatar0.15.0. Use it to know when to show the agent's face on a call — the app's, whichever agent a call is with (GraineAvatar).
val schedulingRules: GraineSchedulingRulesGraineSchedulingRulesRead it to know what the default agent lets users book (GraineSchedulingRules); the defaults, with booking off, before the settings load.
val bookingAvailable: BooleanBooleanRead it to decide whether to offer booking for the default agent (Graine.bookingAvailable).
val bookingUnavailableReason: String?String?Read it to say why booking is not offered for the default agent — not_loaded, rings_not_set_up, scheduling_off or not_identified — or null when it is (Graine.bookingUnavailableReason). 0.14.0.
val bookingState: StateFlow<GraineBookingState>StateFlow<GraineBookingState>Collect it to show or hide your own booking button for the default agent as the answer changes (Graine.bookingState). 0.14.4.
val component: StateFlow<GraineComponent?>StateFlow<GraineComponent?>Collect it to draw, in a UI of your own, the component the default agent drew that waits for an answer; null when there is none (GraineAgent.component). 0.14.0.
val componentPending: StateFlow<Boolean>StateFlow<Boolean>Collect it to draw a loader while a component the default agent asked for is on its way (GraineAgent.component). 0.14.0.
val componentAwaitingReply: StateFlow<Boolean>StateFlow<Boolean>Collect it to show that the default agent is answering: true from the moment your app answers one of its components with a summary until the agent starts its reply, or 12 seconds pass (GraineAgent.component). 0.14.8.
val installId: StringStringRead it for this install's ID: a random UUID made on first launch and kept for as long as the app is installed; the same one the native SDKs use, for every agent.
val memoryEnabled: BooleanBooleanRead it to show the user's memory choice: their last choice on this install, else true.

Its functions: configure, agent, identify, setMemory, memories, forgetMemory, setVariables, currentVariables, registerAction, setScreen, updateField, removeField, clearScreen, track, tap, noteInteraction, presentBooking, bookingSlots, scheduleCall, scheduledCalls, cancelScheduledCall, onRequestPermissionsResult — each with its parameters, what it returns, its errors and an example.

Graine.session (the agent's settings)

Collect it to know when the agent's settings have loaded — before offering what depends on them, such as booking.

val session: StateFlow<GraineSession?>

null until the default agent's settings arrive from Graine (once per launch), then the GraineSession. Each agent has its own: GraineAgent.session. The same moment is also an event, GraineEvent.SessionReady.

Parameters — none.

Returns — StateFlow<GraineSession?>. Example value: GraineSession(agentId="a7c1…", memoryEnabled=true, identityField="user_id", devicesPerUser=2, schedulingRules=GraineSchedulingRules(usersCanBook=true, …), declaredActions=[open_screen]).

Errors — none.

var callMeVisible = false   // whether your "Call me" button shows
scope.launch {
    Graine.session.filterNotNull().first()
    callMeVisible = Graine.bookingAvailable
}

GraineConfig

Pass it to Graine.configure to say which agent to start and how.

data class GraineConfig(…)

Everything the SDK needs to know up front — the native SDKs' configuration, field for field.

What to expect — Made once, at launch. Optional fields have the defaults shown; nothing in it is sent to Graine except what the descriptions say.

FieldTypeDefaultMeaning
baseUrlStringrequiredWhere Graine is: "https://www.graine.ai" unless your workspace is self-hosted.
publishableKeyStringrequiredSelects the agent: its publishable key from Agent → Embed & Widgets. Not a secret, and it cannot place a call on its own.
variablesMap<String, Any?>emptyMap()Prompt variables your app knows at build time. Values from identify() and setVariables() take precedence over these.
appVersionString?nullUse it to tell builds apart: it lands on the call record.
endOnBackgroundBooleantrueEnds a live voice-bar conversation when the app goes to the background. Keep it on.
debugBooleanfalseTurn it on in debug builds to log the SDK's traffic with Graine — keys only, never values — to logcat (tag Graine) and the iOS console.
captureTapsBooleantrueLets the SDK notice taps on labelled controls (what a screen reader reads, a view's ID, a button's words) by itself, at most two a second and only while a screen is reported, so the agent knows what the user just pressed. It only watches.
transportGraineTransport?nullUse it to force how the voice bar's audio travels (GraineTransport); null lets the dashboard's Call audio setting decide.
chatSizeGraineChatSize?nullHow big the chat window opens in this app, over the dashboard's Window size (GraineChatSize); a size passed to chat.open(size) wins for that open.
chatCloseDelaySecondsInt15How long the chat stays connected once no screen shows it, in seconds: the conversation closes — as chat.close() closes it — this long after the last screen left it (or after its last message, whichever is later), unless a screen shows it again first, so a quick hop to the booking sheet or a component keeps it. 0 closes it as soon as the last screen leaves; kept within 0–300 (a negative value is 0). chat.closeDelaySeconds changes it while the app runs. On iOS it needs GraineInApp of this version. 0.14.3.
tokenProvider(suspend () -> String?)?nullServer tokens: returns a short-lived token your server mints for the signed-in user with POST /v2/client-tokens and your secret API key (the agent_id, the user_id your app passes to identify(), the scopes the app needs), or null when none can be had right now — a throw, or no answer within 15 seconds, counts as null. The SDK asks at start, again shortly before the token expires (in the background, with jitter, backing off after a failure, never while the app is in the background), when a call rings and when Graine refuses a token — one question at a time — and every request to Graine carries the newest one. A token that expires never ends, pauses or reconnects a live chat or call; a new conversation waits at most 10 seconds for a fresh one. Needed once the agent's Require server tokens is enforced; null sends none and changes nothing. On iOS it needs GraineInApp of this version. 0.14.4.

GraineSession

Read it to know what the agent's settings say once they have loaded — who the user is, the booking rules, the declared actions.

data class GraineSession(…)

From Graine.session (and GraineAgent.session, GraineEvent.SessionReady).

What to expect — Loaded once per launch; null in session until then. A setting an older server does not send means its default: the user_id trait, 2 devices per user, booking off.

FieldTypeDefaultMeaning
agentIdStringrequiredUse it in logs and support requests: the agent's ID in Graine.
memoryEnabledBoolean?requiredRead it to know whether the agent remembers its users; null when Graine does not say.
identityFieldString"user_id"Read it to know which trait names the user (Agent → Memory → Who is the user?): the one identify must carry for memory and booking to work.
devicesPerUserInt2How many devices one user may use the agent on (1–5); beyond it, device_limit.
schedulingRulesGraineSchedulingRulesGraineSchedulingRules()Read it for the booking rules and how Graine rings (GraineSchedulingRules).
declaredActionsSet<String>emptySet()Use it to check your handlers against the actions declared on the agent: one declared and not registered is refused when the agent asks for it.

GraineInitProvider

Leave it in your merged manifest on Android: it is how Graine.configure(config) finds the application from shared code.

class GraineInitProvider : ContentProvider()

Declared by the library and started by Android at process start, before Application.onCreate; it records the application and, from then on, the activity in front. It serves no data. An app that removes it calls Graine.configure(context, config) instead.

What to expect — Nothing to call. Android only.

Identity, memory and conversations that continue

Tell the agent who the user is, so it can remember them, ring them, and continue their conversation. Where the agent remembers its users, a signed-in user who comes back finds the chat where they left it: it opens with the earlier messages (restored, oldest first; an earlier call's as one “Voice call” row) and the agent continues from them. chat.newConversation() starts afresh. Who the user is belongs to the app: Graine.identify tells every agent.

With memory on, the agent reads what it remembers about the user at the start of each chat, Talk session or call — in-app calls in both directions included — and puts it in what the model reads: after the prompt for a prompt agent, in the flow's Briefing (which every step reads first) for a flow agent. During a conversation it looks again only when the user refers to an earlier one (“last time”, “I told you”), before it answers. New facts are ready about a minute after a conversation ends. What is kept, the settings and the prompt lines that make the agent use it: Memory.

Graine.identify

Call it after the user signs in, and with null when they sign out.

fun identify(traits: Map<String, Any?>?, memory: Boolean? = null, identityToken: String? = null)

The trait the agent's Who is the user? setting names (user_id unless the dashboard chose email, phone or a custom trait) is how Graine tells your users apart: it lets the agent remember a user and ring them. Send exactly that key — another key is no identity, and the conversation has no memory. Its value goes only to Graine and never becomes a prompt variable; every other trait is masked on the device and reaches the agent as a prompt variable, not as a memory. A placeholder ("guest", a masked value) identifies nobody. Call it before the chat or a call opens, at sign-in and at every launch: the SDK does not keep who is signed in between launches.

It applies to every agent; a voice call takes the identity at its start. null signs out everywhere: this device stops being one of the user's, and later conversations are anonymous. Identifying a different user does the same for the previous one.

A chat belongs to whoever was identified when it connected (from 0.14.0). When the identity changes while the chat is connected or connecting — signing in after it opened, another user, or signing out — that conversation is closed quietly (no “Disconnected”, no reconnect banner), its messages are cleared, a message typed and not yet sent stays and is sent next, and the chat connects again at once as the new identity — status reads CONNECTING, then ONLINE: a user's conversation continues, or the agent greets them. A chat that was not connected clears its messages the same way and connects at the next open. The same identity with other traits — or written another way, as Graine keys users (Asha@Example.com and asha@example.com, a phone with and without its country code) — or another memory choice, changes nothing on the open chat, and nobody is signed out. Identify before showing the chat where you can: the reconnect costs the user a moment. On iOS it needs GraineInApp of this version.

ParameterTypeDefaultMeaning
traitsMap<String, Any?>?requiredWho the user is, by trait name — mapOf("user_id" to user.id, "name" to user.firstName). null signs out.
memoryBoolean?nullfalse keeps this user's conversations out of memory — nothing is remembered or recalled, from the next conversation — and the choice is saved on this install for that user. null keeps their last choice — on until they make one.
identityTokenString?nullNew in 0.14.4. Proves the identity to an agent with Verified users on (Your app and your users): the HMAC your server computes over the identity value with the agent's user secret, or the ID token (JWT) of your own sign-in. Sent only inside the request's identity, beside the value it proves — never in variables, the screen context or a log — and held in memory only. Another user, or null traits, drops it (and the user pass Graine gave for it) in the same step; the same user without a token keeps theirs. On iOS it needs GraineInApp of this version.

Returns — nothing.

Errors — IllegalStateException before configure.

Graine.identify(mapOf("user_id" to user.id, "name" to user.firstName), memory = user.allowsMemory)
Graine.identify(mapOf("user_id" to user.id), identityToken = session.graineToken)   // an agent that verifies its users
Graine.identify(null)   // on sign-out

Graine.setMemory

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

fun setMemory(enabled: Boolean)

The same as identify with the same traits and memory = enabled, for every agent. Kept on this install for this user.

ParameterTypeDefaultMeaning
enabledBooleanrequiredtrue to remember this user's conversations, false to stop.

Returns — nothing.

Errors — IllegalStateException before configure.

Graine.setMemory(false)

Graine.memories

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

suspend fun memories(): List<GraineMemory>

What the default agent remembers about the signed-in user, newest first, at most 100, already redacted. Only from a device the user is using. GraineAgent.memories() asks another agent.

Parameters — none.

Returns — List<GraineMemory> (GraineMemory). Example value: [GraineMemory(id="m_31", text="Prefers a call after 6 PM", createdAt=2026-10-12T09:15:00Z, updatedAt=null)].

Waits for the agent's settings first.

Errors — throws GraineException: IdentityRequired when nobody is identified by the agent's trait (the message names it) or someone else was identified while the settings were loading, DeviceLimit from a device that is not one of the user's, RateLimited, Network, Unavailable, InvalidKey, OriginRefused.

val remembered = try { Graine.memories() } catch (e: GraineException) { emptyList() }

Graine.forgetMemory

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

suspend fun forgetMemory(): Int

Deletes everything the default agent remembers about the signed-in user — only from a device that user is using. Once it succeeds the chat on screen is cleared too; a refusal leaves it as it was.

Parameters — none.

Returns — Int — how many memories were deleted. Example value: 3.

Errors — throws GraineException: IdentityRequired, DeviceLimit, RateLimited, Network, Unavailable, InvalidKey, OriginRefused.

val deleted = Graine.forgetMemory()

GraineAgent.memories

Call it to show what one of your other agents remembers about the signed-in user.

suspend fun memories(): List<GraineMemory>

Graine.memories() for this agent: newest first, at most 100, already redacted.

Parameters — none.

Returns — List<GraineMemory>.

Errors — throws GraineException as Graine.memories(); IllegalStateException when this agent is not configured.

val remembered = Graine.agent("support")?.memories().orEmpty()

GraineAgent.forgetMemory

Call it to make one of your other agents forget the signed-in user.

suspend fun forgetMemory(): Int

Graine.forgetMemory() for this agent.

Parameters — none.

Returns — Int — how many memories were deleted.

Errors — throws GraineException as Graine.forgetMemory().

val deleted = Graine.agent("support")?.forgetMemory() ?: 0

GraineChat.newConversation

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

suspend fun newConversation()

The chat hangs up, Graine lets go of the conversation it kept for this agent and user (so the next chat does not continue it), and the messages on screen and any waiting to go are cleared; when the user was in the chat, a fresh chat opens with the welcome and the starters. Memories the agent keeps about the user stay as they are. With nobody signed in there is nothing kept to let go of, so only the screen is cleared. The SDK's chat window calls it from the New conversation button in its header, which it shows only while a conversation continued from before is on screen.

Parameters — none.

Returns — nothing, once the new conversation has started.

Errors — throws GraineException when Graine refused (DeviceLimit, Network, …); the chat is then as it was.

scope.launch { runCatching { Graine.chat.newConversation() } }

GraineChat.refreshPastSessions

Call it when a screen of the user's past conversations appears, or when they pull to refresh it.

fun refreshPastSessions()

0.14.3. Loads the first page of pastSessions — the user's most recent sessions with this agent, newest first — replacing what was loaded. While it loads, loading is true and what was loaded stays; once it answers, hasMore says whether loadMorePastSessions() has another page. With nobody signed in nothing is sent, and error is identity_required at once; a refusal keeps what was loaded, with error saying why. On iOS it needs GraineInApp of this version (an older one loads nothing).

Parameters — none.

Returns — nothing; the page arrives in pastSessions.

Errors — IllegalStateException when the agent is not configured; a refusal is pastSessions.error: identity_required, device_limit, rate_limited, unavailable or network.

LaunchedEffect(Unit) { Graine.chat.refreshPastSessions() }

GraineChat.loadMorePastSessions

Call it when the user scrolls to the end of their past sessions.

fun loadMorePastSessions()

0.14.3. Loads the next page of pastSessions and appends it — a session already listed is not listed twice. Nothing happens while a page is loading, or when there is no next page (hasMore false, or nothing loaded yet: refreshPastSessions() loads the first). After a refusal, calling it again asks for the same page.

Parameters — none.

Returns — nothing; the page arrives in pastSessions.

Errors — IllegalStateException when the agent is not configured; a refusal is pastSessions.error.

val past = Graine.chat.pastSessions.value
if (past.hasMore && !past.loading) Graine.chat.loadMorePastSessions()

GraineChat.sessionTranscript

Call it when the user opens one of their past sessions, to show what was said.

suspend fun sessionTranscript(id: String): GraineSessionTranscript

0.14.3. One past session's messages, oldest first, with the session as pastSessions lists it (GraineSessionTranscript). Only the signed-in user's own sessions: another user's, or one Graine does not know, is NotFound — and so is an answer that arrives after the identity changed. A blank id, or nobody signed in, is refused before anything is sent.

ParameterTypeDefaultMeaning
idStringrequiredThe session's id: GraineSessionSummary.id, from pastSessions — the id Execution History shows.

Returns — the GraineSessionTranscript. Example value: GraineSessionTranscript(id=ex-7a1c0001, startedAt=2026-10-21T12:00:05Z, endedAt=2026-10-21T12:04:41Z, durationSeconds=276, channel=CHAT, direction=null, status=completed, turns=[GraineSessionTurn(role=AGENT, text=Hi Meera, how can I help?, at=2026-10-21T12:00:05Z), …]).

Errors — throws GraineException: InvalidRequest (a blank id), IdentityRequired, NotFound, DeviceLimit, RateLimited, Unavailable (also with an iOS GraineInApp older than this version), Network; IllegalStateException when the agent is not configured.

scope.launch {
    val transcript = Graine.chat.sessionTranscript("ex-7a1c0001")
    transcript.turns.forEach { line -> println((if (line.role == GraineRole.USER) "You: " else "Agent: ") + line.text) }
}

GraineMemory

Read it to show one thing the agent remembers about the user.

data class GraineMemory(val id: String, val text: String, val createdAt: Instant? = null, val updatedAt: Instant? = null)

What to expect — From memories(): newest first, at most 100, already redacted. The times are moments; show them in the device's time zone.

FieldTypeDefaultMeaning
idStringrequiredUse it as a stable key when you list memories.
textStringrequiredShow it: what is remembered, in a sentence, already redacted.
createdAtInstant?nullWhen it was first remembered; null when Graine did not say.
updatedAtInstant?nullWhen it last changed; null when it never did or Graine did not say.

Your app and your users

New in 0.14.4. Two protections, each switched on per agent in the dashboard (Agent → Embed & Widgets → Install), each with a report-only stage before it refuses anything, and each off until you turn it on — with neither on, nothing changes. Your apps: every request says which app it is (Android: the package name and the SHA-256 of each signing certificate; iOS: the bundle id and Team ID), so Only my apps turns away any other app; Require a verified app also has the app prove it — Play Integrity on Android (the Android app adds implementation("com.google.android.play:integrity:1.4.0")), App Attest on iOS (the app target adds the App Attest capability). Verified users: the identity you give with identify is proven by an identity token — an HMAC-SHA256 your server computes over the identity value with the agent's user secret (64 hex characters; the secret never ships in the app), or the ID token (JWT) of your own sign-in.

The native SDKs do the work — the app's declaration on every request, the proofs, the passes (an app pass for 24 hours, a user pass for an hour), the token's place inside the identity — so a request never needs anything from you; what is here passes the token, proves the app early, and reads what Graine made of both. Development mode: a debug build sends a debug token instead of proving itself; register it under Agent → Embed & Widgets → Install → Development → Debug tokens. On iOS everything here needs GraineInApp of this version. Setting it up, step by step: the README's Secure your agent: your app and your users.

Graine.setIdentityToken

Call it when your sign-in renewed the user's identity token, to replace it without identifying anyone else. 0.14.4.

fun setIdentityToken(token: String?)

The token for the user identified now; null clears it. For every agent, as identify is. With nobody identified there is no one to attach it to — identify the user with their token instead. Held in memory only and sent only beside the identity value it proves.

ParameterTypeDefaultMeaning
tokenString?requiredThe fresh identity token — an HMAC from your server, or your sign-in's ID token; null clears the one held.

Returns — nothing.

Errors — IllegalStateException before configure.

auth.onTokenRenewed { idToken -> Graine.setIdentityToken(idToken) }

Graine.identityTokenRefresher

Set it to let the SDK ask your app for a fresh identity token whenever the one it holds runs out. 0.14.4.

var identityTokenRefresher: (suspend () -> String?)?

A suspending function returning a fresh token for the signed-in user — from your server, or your sign-in's SDK — or null to keep the token the SDK holds. The SDK calls it when Graine says the token expired, when a request is refused IdentityUnverified (that request is then sent once more with the new token), before a conversation starts with a JWT that has less than a minute left, and when a call rings — at most once every 30 seconds, never twice at once. It starts on the main thread, so make the network call suspend rather than block. Returning null, a blank token, or throwing keeps the token as it was. One for the whole app, like identify; it may be set before Graine.configure. null, the default: the SDK only ever sends the token it was given.

Returns — the refresher set, or null, when read.

Errors — none.

Graine.identityTokenRefresher = { api.graineIdentityToken() }   // a suspending call to your server

Graine.prepareAppVerification

Call it on first launch, after configure, so the first conversation never waits for the app's proof. 0.14.4.

suspend fun prepareAppVerification(): GraineAppVerdict

Proves the app now for the default agent and returns the verdict (GraineAppVerdict). Waits for the agent's settings first. Nothing is sent when the agent does not ask for a verified app (OFF), when an app pass with more than six hours left is held (its verdict), or in a build that uses a debug token (Graine.debugTokenMode: the verdict arrives with the next conversation). The SDK proves the app by itself too — after the settings arrive, and when the pass is due — so calling this is never required. A proof that failed is UNVERIFIED, never an exception, and the SDK tries again on its own (an install proven in the last 7 days keeps working while Apple or Google cannot be reached). GraineAgent.prepareAppVerification() proves the app for another agent.

Parameters — none.

Returns — GraineAppVerdict. Example value: GraineAppVerdict.VERIFIED.

Errors — IllegalStateException before configure.

appScope.launch { log("app verification: ${Graine.prepareAppVerification().word}") }

GraineAgent.prepareAppVerification

Call it to prove the app early for one of your other agents. 0.14.4.

suspend fun prepareAppVerification(): GraineAppVerdict

Graine.prepareAppVerification for this agent, with its own settings: an agent that does not ask for a verified app answers OFF.

Parameters — none.

Returns — GraineAppVerdict.

Errors — IllegalStateException when the agent is not configured.

Graine.agent("support")?.prepareAppVerification()

Graine.verification (what Graine has proven)

Collect it to see what Graine has proven about this app and its user — for logs, a support screen, or to notice a refused token. 0.14.4.

val verification: StateFlow<GraineVerification>

The default agent's GraineVerification, as it changes: app and user, each with Graine's reason when it is not proven. Both OFF until the agent's settings ask for them; the verdicts arrive with the agent's answers, so read them as what Graine said last. Never needed to make a request — the SDK proves the app and sends the token by itself. GraineAgent.verification answers for another agent.

Parameters — none.

Returns — StateFlow<GraineVerification>. Example value: GraineVerification(app=VERIFIED, appReason=null, user=INVALID, userReason=expired).

Errors — none.

Graine.verification.collect { v ->
    if (v.user == GraineUserVerdict.INVALID) log("identity token refused: ${v.userReason}")
}

GraineAgent.verification

Collect it to see what Graine has proven for one of your other agents. 0.14.4.

val verification: StateFlow<GraineVerification>

Graine.verification for this agent: each agent has its own settings, and so its own verdicts. Off and off before the agent is configured.

Parameters — none.

Returns — StateFlow<GraineVerification>.

Errors — none.

Graine.agent("support")?.verification?.collect { v -> render(v) }

GraineVerification

Read it from verification: what Graine has proven about this app and its user, for one agent. 0.14.4.

data class GraineVerification(val app: GraineAppVerdict = GraineAppVerdict.OFF, val appReason: String? = null, val user: GraineUserVerdict = GraineUserVerdict.OFF, val userReason: String? = null)
PropertyTypeMeaning
appGraineAppVerdictWhether Graine knows this app is yours (GraineAppVerdict).
appReasonString?Why app is UNVERIFIED, in Graine's word, when it said — missing, expired, invalid, wrong_app, test_build, not_configured, debug_token_unknown, debug_token_expired; null otherwise.
userGraineUserVerdictWhether Graine knows the signed-in user is who identify says (GraineUserVerdict).
userReasonString?Why user is UNVERIFIED or INVALID, in Graine's word, when it said — missing, expired, not_yet_valid, signature, audience, issuer, claim, mismatch, malformed, unknown_key, unavailable; null otherwise.
val v = Graine.verification.value
supportScreen.show("App: ${v.app.word} ${v.appReason.orEmpty()} · User: ${v.user.word} ${v.userReason.orEmpty()}")

GraineAppVerdict

Read it in GraineVerification.app and from prepareAppVerification: whether Graine knows this app is yours. 0.14.4.

enum class GraineAppVerdict(val word: String) { OFF("off"), CHECKING("checking"), VERIFIED("verified"), TEST_BUILD("testBuild"), DEBUG_TOKEN("debugToken"), UNVERIFIED("unverified") }

PropertyTypeMeaning
wordStringThe word every Graine SDK uses for it — off, checking, verified, testBuild, debugToken, unverified — for logs.
CaseMeaning
OFFThe agent does not ask for a verified app — or its settings have not arrived yet.
CHECKINGThe SDK is proving the app right now, and holds no app pass yet.
VERIFIEDProven: App Attest (iOS) or Play Integrity (Android) recognised this build, and Graine gave it an app pass.
TEST_BUILDA development build the agent accepts while its Allow development builds is on.
DEBUG_TOKENA debug build, accepted through a debug token registered on the agent (Graine.debugToken).
UNVERIFIEDNot proven: appReason says why when Graine said.

GraineUserVerdict

Read it in GraineVerification.user: whether Graine knows the signed-in user is who identify says. 0.14.4.

enum class GraineUserVerdict(val word: String) { OFF("off"), VERIFIED("verified"), TEST_USER("testUser"), UNVERIFIED("unverified"), INVALID("invalid") }

What to expect — Under Require verified users, a conversation with an identity that is neither VERIFIED nor TEST_USER still goes ahead, anonymously (no memory, no Call History name); memories, past sessions and booking are refused IdentityUnverified.

PropertyTypeMeaning
wordStringThe word every Graine SDK uses for it — off, verified, testUser, unverified, invalid — for logs.
CaseMeaning
OFFThe agent does not verify its users — or its settings have not arrived yet.
VERIFIEDProven by the identity token, or by the user pass Graine gave for it.
TEST_USEROne of the agent's test users, from an install whose debug token is registered on the agent. Counts as verified.
UNVERIFIEDNo identity token proved it — none was given (missing), or nobody is identified; userReason says why when Graine said.
INVALIDA token was sent and refused: userReason says why (expired, signature, mismatch…).

Graine.debugTokenMode (development mode)

Set it, before configure, to choose whether this build sends a debug token instead of proving itself. 0.14.4.

var debugTokenMode: GraineDebugTokenMode

For every agent (GraineDebugTokenMode): AUTOMATIC, the default, uses a debug token in a debug build and never in a release build; ALWAYS in any build (an internal QA build); NEVER in none. Set it before Graine.configure, so the first request already follows it — a mode set later reaches every agent at once. Read back, it is the mode you chose, else the native SDK's. A debug token counts only once an Admin registers it on the agent (Graine.debugToken).

Returns — GraineDebugTokenMode, when read.

Errors — none.

Graine.debugTokenMode = GraineDebugTokenMode.ALWAYS   // an internal QA build signed for release
Graine.configure(config)

Graine.debugToken

Read it to show this install's debug token on a debug screen, so a tester can register it on the agent. 0.14.4.

val debugToken: String?

This install's debug token while the build uses one (debugTokenMode), else null — a release build never makes one, and null before configure. Shaped gdt_ and 32 characters, made once per install and logged once by the native SDK: Graine debug token for this install: gdt_… — register it under Agent → Embed & Widgets → Install → Development → Debug tokens to use this build while "Require a verified app" is on. Registered there (30 days by default, 90 at most, revocable), this build counts as a verified app (DEBUG_TOKEN), and the agent's test users are accepted from it without an identity token.

Returns — String?. Example value: "gdt_…" (32 characters after the prefix).

Errors — none.

Graine.debugToken?.let { debugScreen.showCopyable("Debug token", it) }

GraineDebugTokenMode

Pass it to Graine.debugTokenMode: when this build sends a debug token instead of proving itself with App Attest or Play Integrity. 0.14.4.

enum class GraineDebugTokenMode(val word: String) { AUTOMATIC("automatic"), ALWAYS("always"), NEVER("never") }

What to expect — Simulators, emulators, sideloaded debug builds and CI cannot prove themselves; a debug token stands in for the proof, never alongside it. Whether a build is a debug build is the native SDK's answer.

PropertyTypeMeaning
wordStringThe word every Graine SDK uses for it — automatic, always, never — for logs.
CaseMeaning
AUTOMATICThe default: a debug build — on Android a debuggable one (every build Android Studio runs), on iOS one built with the Debug configuration or running on the Simulator — sends the debug token instead of proving itself; a release build never makes, logs or sends one.
ALWAYSThis build sends the debug token whatever its kind — an internal QA build signed for release, say.
NEVERNo debug token, even in a debug build: it proves itself like a release build (useful with Allow development builds).

Chat

The typed conversation with an agent: Graine.chat for the default agent, Graine.agent("support")?.chat for another. Show the SDK's own chat screen — GraineChat() in Compose, GraineViews.chat() in UIKit — or draw your own from turns, status, typing, upcomingCalls and quickReplies. Everything works as on a call: the agent sees the screen you report, runs your actions and draws its components. Only one conversation runs at a time — opening the chat ends a voice-bar call, and during a native call the chat waits until the call is over.

The agent can suggest replies to its message, drawn as chips (quickReplies), and end the conversation (ended), after which the chat window asks “How was this chat?” where the design does (rating, onRated). Your app can pin what the conversation is about (pin) and take attachments (onAttach). The SDK's chat window draws all of it in the brand's chat style, piece by piece (GraineThemeTokens.Chat); a chat of your own reads the same states and tokens. New in 0.13.0, all optional — the chat guide shows each from the user's side.

GraineChat

Use it to open, send to and follow one agent's chat.

class GraineChat

Graine.chat, or GraineAgent.chat for another agent. A message typed while the chat is not connected is shown at once and sent when it is; a dropped connection is made again on its own while the user is in the chat.

What to expect — Every flow always holds the latest value. turns empties when the identity changes — signing in after the chat opened, another user, signing out; a message typed and not yet sent stays (from 0.14.0) — after a successful forgetMemory(), on newConversation() and on clear(). quickReplies, ended and rating start over when the user sends a message, and on clear(), newConversation() and sign-out; pinned stays until you change it, also while the chat is closed. onRated and onAttach may be set before Graine.configure.

PropertyTypeMeaning
val turns: StateFlow<List<GraineChatTurn>>StateFlow<List<GraineChatTurn>>Collect it to draw the conversation, oldest first (GraineChatTurn).
val status: StateFlow<GraineChatStatus>StateFlow<GraineChatStatus>Collect it to show the connection — Online, Connecting… (GraineChatStatus).
val failed: StateFlow<Boolean>StateFlow<Boolean>true once the chat gave up — every retry spent, and it will not connect again by itself; back to false when the user sends a message or taps to try again (retry(), open()). Never for a conversation the agent ended (ended) or Graine closed (DISCONNECTED). 0.14.1. Deprecated in 0.14.5: status says it — FAILED — so read status.value == GraineChatStatus.FAILED; this stays for code that reads it.
val typing: StateFlow<Boolean>StateFlow<Boolean>Collect it to draw a typing indicator: true from the user's message until the agent's first words.
val upcomingCalls: StateFlow<List<GraineScheduledCall>>StateFlow<List<GraineScheduledCall>>Collect it to draw the SDK window's Upcoming calls card in a chat of your own: the user's calls still to come, soonest first, at most three (GraineScheduledCall). Fetched when the chat opens and after the agent finishes a reply (it may have just booked one), only where Graine rings this app; empty otherwise. On iOS it needs GraineInApp of this version; with an older one it stays empty.
val quickReplies: StateFlow<List<GraineQuickReply>>StateFlow<List<GraineQuickReply>>Collect it to draw, as chips of your own, the replies the agent suggests for its latest message (GraineQuickReply) — at most six, in the agent's order; send one with sendQuickReply(reply). Empty again once the user sends anything, the agent starts another message, an earlier conversation is restored, or the conversation ends. The SDK's chat window draws them itself. On iOS it needs GraineInApp of this version; with an older one it stays empty. New in 0.13.0.
val ended: StateFlow<Boolean>StateFlow<Boolean>Collect it to know the agent ended the conversation: the chat window then asks for a rating where the design does, and rate(style, value) takes one; once the conversation's connection closes, status is IDLE (from 0.14.0). Back to false as soon as the user sends anything — the conversation goes on. On iOS it needs GraineInApp of this version; with an older one it stays false. New in 0.13.0.
val rating: StateFlow<GraineChatRating?>StateFlow<GraineChatRating?>Collect it for the user's answer to “How was this chat?” — from the chat window's rating card or rate(style, value) — once given, one per conversation (GraineChatRating); null until then. On iOS it needs GraineInApp of this version; with an older one it stays null. New in 0.13.0.
val pinned: StateFlow<GraineChatPin?>StateFlow<GraineChatPin?>Collect it for the card your app pinned with pin(pin), cleaned as the chat window draws it (GraineChatPin); null when nothing is pinned. On iOS it needs GraineInApp of this version; with an older one it stays null. New in 0.13.0.
val newConversationBefore: StateFlow<List<String>>StateFlow<List<String>>Collect it to draw where Graine began a new conversation under earlier lines: the IDs of the messages a “Disconnected · new conversation” row goes before, oldest first; empty when there are none. Pass it to GraineChatRows.build(turns, newConversationBefore), which places the rows (GraineChatRow). The rows are never messages — turns does not change for them — and newConversation() or clear() takes them away with the messages. On iOS it needs GraineInApp of this version; with an older one it stays empty. 0.14.0.
val sessionId: StateFlow<String?>StateFlow<String?>Collect it for the id of the chat's current session — this connection's run, the id Execution Logs shows for it — from Graine as the connection starts; null until it arrives (each new connection starts without one), and with a server that sends none. A message said now carries it (GraineChatTurn.session). On iOS it needs GraineInApp of this version; with an older one it stays null. 0.14.0.
val sessions: StateFlow<List<GraineChatSession>>StateFlow<List<GraineChatSession>>Collect it for a “past conversations” list or session dividers of your own: the sessions the conversation on screen holds, oldest first — each run of consecutive turns said in the same session, a chat connection's or a call's, the current one marked (GraineChatSession). Turns kept before sessions were recorded make one with no id; with a server that sends none, the whole conversation is one session with no id. Updates with turns and sessionId. 0.14.0.
val pastSessions: StateFlow<GrainePastSessions>StateFlow<GrainePastSessions>Collect it to draw the user's earlier sessions with this agent — their past chats, talks and calls, newest first, as the dashboard's Execution History lists them: sessions, loading, hasMore, error (GrainePastSessions). Empty until refreshPastSessions(); loadMorePastSessions() appends the next page, and sessionTranscript(id) answers one session's messages. Only for the user identify names, from a device bound to them — error says why not — and cleared when the identity changes (another user, or nobody). The session open now is never in it. On iOS it needs GraineInApp of this version; with an older one it stays empty. 0.14.3.
var closeDelaySeconds: IntIntRead or set how long the conversation stays connected once no screen shows it, in seconds: it closes — as close() closes it, never DISCONNECTED — this long after the last screen left it, or after the last message either way when that came later; a screen showing it again before then continues it. Starts as GraineConfig.chatCloseDelaySeconds (15 unless set); 0 closes it as soon as the last screen leaves; kept within 0–300 (a negative value is 0). Set it after Graine.configure (before, it throws IllegalStateException); a close already waiting takes the new delay. On iOS it needs GraineInApp of this version. 0.14.3: it closes 15 seconds after it leaves every screen; it was 5 minutes of quiet in 0.14.0–0.14.1.
var onRated: ((GraineChatRating) -> Unit)?((GraineChatRating) -> Unit)?Set it to hear the user's rating — from the chat window's rating card or rate(style, value) — on the main thread, once for each rating. The rating is also recorded on the conversation, and rating holds it. null, the default: nothing is called. On iOS it needs GraineInApp of this version. New in 0.13.0.
var onAttach: (() -> Unit)?(() -> Unit)?Set it to take attachments: while it is set, the chat window's composer shows its paperclip where the design has one (GraineThemeTokens.Chat.Composer.attach), and a tap calls it, on the main thread. The SDK sends nothing itself — pick and upload the file, then tell the agent about it as you would about anything the user did (Graine.track, Graine.setScreen). null, the default: no paperclip. On iOS it needs GraineInApp of this version; with an older one no paperclip shows. New in 0.13.0.
Graine.chat.onRated = { rating -> analytics.log("chat_rated", rating.value, rating.scale) }   // your analytics
Graine.chat.onAttach = { openFilePicker() }   // your picker: upload the file, then Graine.track("file_attached")

Its functions: open, close, shown, send, retry, clear, newConversation, refreshUpcomingCalls, cancelUpcomingCall, sendQuickReply, rate, pin, answerWidget, dismissWidget, refreshPastSessions, loadMorePastSessions, sessionTranscript — each with its parameters, what it returns, its errors and an example.

GraineChat.open

Call it when the user goes into the chat, so it connects and stays connected.

fun open(size: GraineChatSize? = null)

Ends a call the voice bar holds. A voice bar on screen moves to its chat and draws it at size — this open's own, until close(); null follows GraineConfig.chatSize, then the dashboard's Window size.

ParameterTypeDefaultMeaning
sizeGraineChatSize?nullHow big the chat opens this time: COMPACT, LARGE or FULL.

Returns — nothing.

Errors — IllegalStateException when the agent is not configured.

Graine.chat.open(GraineChatSize.LARGE)

GraineChat.close

Call it when the user leaves the chat.

fun close()

The chat hangs up and stays down; what was said stays.

Parameters — none.

Returns — nothing.

Errors — IllegalStateException when the agent is not configured.

Graine.chat.close()

GraineChat.shown

Call it from a chat screen of your own when it comes on screen (true) and when it leaves (false), so the conversation lives as the SDK's own chat's does. 0.14.0.

fun shown(visible: Boolean)

While a screen shows it the chat is connected. When none does, the conversation stays connected for closeDelaySeconds — 15 seconds unless you set another — counted from when the last screen left, or from the last message either way when that came later, and then closes as close() closes it; a screen showing it again within that time continues the same connection, with nothing new on screen and no second welcome, so a quick hop to the booking sheet or a component changes nothing. Opened later, it connects again, and a signed-in user's conversation continues from Graine's history (0.14.3; it closed after 5 minutes of quiet in 0.14.0–0.14.1). When Graine ends an idle conversation itself, the chat does not reconnect on its own: status is DISCONNECTED until the user opens the chat or writes again. Say it in pairs — one false for each true. The SDK's GraineChat() and GraineViews.chat() say it themselves; a chat nobody reports stays connected until Graine's own idle limit. close() still ends the conversation at once. On iOS it needs GraineInApp of this version; an older one connects on open() as before.

ParameterTypeDefaultMeaning
visibleBooleanrequiredtrue when your chat screen appears, false when it goes.

Returns — nothing.

Errors — IllegalStateException when the agent is not configured.

@Composable
fun MyChatScreen() {
    DisposableEffect(Unit) {
        Graine.chat.shown(true)
        onDispose { Graine.chat.shown(false) }
    }
    // … your own messages and composer
}

GraineChat.send

Call it to send the user's message from a chat screen of your own.

fun send(text: String)

Shown at once, and sent now or as soon as the chat is connected. Blank messages are ignored.

ParameterTypeDefaultMeaning
textStringrequiredWhat the user typed.

Returns — nothing.

Errors — IllegalStateException when the agent is not configured.

Graine.chat.send("Where is my order?")

GraineChat.retry

Call it from a “Try again” control when the chat is offline or a message failed.

fun retry()

Connects now and sends what could not be sent.

Parameters — none.

Returns — nothing.

Errors — IllegalStateException when the agent is not configured.

Graine.chat.retry()

GraineChat.clear

Call it to empty the chat on screen — a new topic, a tidy screen.

fun clear()

Only the screen: the conversation goes on — connected stays connected — a message still waiting for the connection is still sent, and nothing Graine keeps is touched: the conversation that continues comes back with the next history, and what the agent remembers stays. newConversation() starts over; forgetMemory() forgets. On iOS it needs GraineInApp of this version; an older one ignores it.

Parameters — none.

Returns — nothing; turns is empty.

Errors — IllegalStateException when the agent is not configured.

Graine.chat.clear()

GraineChat.refreshUpcomingCalls

Call it after the user booked a call outside the chat, so the Upcoming calls card of your own chat shows it.

fun refreshUpcomingCalls()

Fetches upcomingCalls again. The chat refreshes them by itself when it opens and after each of the agent's replies, so most apps never call it. On iOS it needs GraineInApp of this version; an older one does nothing.

Parameters — none.

Returns — nothing; upcomingCalls changes when Graine answers.

Errors — IllegalStateException when the agent is not configured.

Graine.chat.refreshUpcomingCalls()

GraineChat.cancelUpcomingCall

Call it from the Cancel control on a row of your own Upcoming calls card.

fun cancelUpcomingCall(id: String)

The call leaves upcomingCalls once Graine has called it off; if Graine refuses, it stays in the list. A blank id is ignored. To learn the outcome yourself, call Graine.cancelScheduledCall(id) instead (Graine.cancelScheduledCall). On iOS it needs GraineInApp of this version; an older one does nothing.

ParameterTypeDefaultMeaning
idStringrequiredThe call's id, from upcomingCalls.

Returns — nothing.

Errors — IllegalStateException when the agent is not configured.

Graine.chat.upcomingCalls.value.firstOrNull { it.canCancel }?.let { Graine.chat.cancelUpcomingCall(it.id) }

GraineChat.sendQuickReply

Call it when the user taps one of the agent's suggested replies in a chat screen of your own.

fun sendQuickReply(reply: GraineQuickReply)

Sends the reply's text as the user's own message — a real message, exactly as if typed with send(text): shown at once, and sent now or as soon as the chat is connected. The suggested replies then go. A reply whose text is blank is ignored. The SDK's chat window does this itself when a chip is tapped. New in 0.13.0.

ParameterTypeDefaultMeaning
replyGraineQuickReplyrequiredOne of quickReplies (GraineQuickReply).

Returns — nothing.

Errors — IllegalStateException when the agent is not configured.

val replies by Graine.chat.quickReplies.collectAsState()
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
    replies.forEach { reply ->
        OutlinedButton(onClick = { Graine.chat.sendQuickReply(reply) }) { Text(reply.label) }
    }
}

GraineChat.rate

Call it from a rating of your own to record the user's answer to “How was this chat?”.

fun rate(style: String, value: Int)

Taken once per conversation, and only after the agent ended it (ended): recorded on the conversation, then held in rating and handed to onRated. Before the end, or a second time, it is ignored. A style other than stars or emoji counts as thumbs; a value out of range is brought into it. An answer given after the conversation has closed still reaches rating and onRated, but is no longer recorded on it. The SDK's chat window does this itself when the user picks a choice on its rating card. On iOS it needs GraineInApp of this version; an older one does nothing. New in 0.13.0.

ParameterTypeDefaultMeaning
styleStringrequiredThe rating you asked with: "thumbs", "stars" or "emoji" — the design's is GraineThemeTokens.Chat.Rating.style.
valueIntrequiredThe answer: thumbs 1 (up) or 0 (down); stars and faces 1–5.

Returns — nothing; rating holds the answer once it is taken.

Errors — IllegalStateException when the agent is not configured.

if (Graine.chat.ended.value && Graine.chat.rating.value == null) {
    Graine.chat.rate("stars", 4)
}

GraineChat.pin

Call it to show what the conversation is about — the item, request or account the user is looking at — at the top of the chat window.

fun pin(pin: GraineChatPin?)

The chat window draws it as a bar under its header or as a card at the top of the conversation, as the design says (GraineThemeTokens.Chat.Header.contextCard), and draws nothing for a design that hides it. pin(null) takes it away; otherwise it stays until you pin another, also while the chat is closed. Each line is cleaned to one line — line breaks, control and text-direction characters become spaces, a run of spaces one — and cut to its length in whole characters: the title at 60, the subtitle at 80, the badge at 24. A pin whose title is blank is no pin: the same as pin(null). pinned has it once the chat window does. Never sent to the agent: tell the agent about the screen with setScreen, as always. On iOS it needs GraineInApp of this version; an older one does nothing. New in 0.13.0.

ParameterTypeDefaultMeaning
pinGraineChatPin?requiredWhat to show (GraineChatPin), or null to take it away.

Returns — nothing.

Errors — IllegalStateException when the agent is not configured.

Graine.chat.pin(GraineChatPin("Request #4821", subtitle = "Opened today", badge = "Active"))
Graine.chat.pin(null)   // take it away

GraineChatTurn

Read it to draw one message of the chat.

data class GraineChatTurn(…)

What to expect — One per message, oldest first. The agent's message updates in place (same id) while live, then stops. A user's message typed while the chat is not connected is SENDING and goes as soon as it is; FAILED means it could not reconnect — retry() tries again. Restored turns arrive once, when the chat opens, for a signed-in user on an agent with memory on: at most 50, oldest first, delivered, never live, with their original times; the welcome is not sent then.

FieldTypeDefaultMeaning
idStringrequiredUse it as a stable key: it stays the same while the message grows.
roleGraineRolerequiredWho said it: USER or AGENT (GraineRole).
textStringrequiredWhat was said; an agent's message may be only a component.
atInstantrequiredWhen the message began; show it in the device's time zone.
deliveryGraineDelivery?nullWhere a user's message is (GraineDelivery); null for the agent's.
proactiveBooleanfalseUse it to badge a closed chat: the agent spoke up without being asked.
componentGraineComponent?nullThe component the agent drew with this message, when the platform ties one to it (GraineComponent).
liveBooleanfalseDraw the words as provisional while true: the agent's message is still arriving.
restoredBooleanfalsetrue for a message from an earlier conversation, restored when the chat opened: draw it as history, not as said just now.
channelGraineChatChannelGraineChatChannel.CHATWhere it was said (GraineChatChannel): typed, or on a call — only a restored message can be from a call.
sessionString?nullThe id of the session it was said in — a chat connection's run, or a call's id for a voice message, as Execution Logs shows it. A restored message keeps the one Graine kept; a message said now carries the chat's sessionId (one typed before the chat connected, the session of the connection that sends it). null for messages kept before sessions were recorded, and with a server that sends none. On iOS it needs GraineInApp of this version. 0.14.0.

GraineChatSession

Read it to list the chat's sessions — a “past conversations” list, or dividers of your own. 0.14.0.

data class GraineChatSession(val id: String?, val startedAt: Instant, val endedAt: Instant, val channel: GraineChatChannel, val turns: Int, val current: Boolean)

From Graine.chat.sessions, oldest first: each run of consecutive turns said in the same session. A session is a chat connection's run (Graine names it as the chat connects) or a call.

FieldTypeDefaultMeaning
idString?requiredThe session's id, as Execution Logs shows it; null for turns kept before sessions were recorded, and with a server that sends none.
startedAtInstantrequiredWhen its first turn was said.
endedAtInstantrequiredWhen its last turn was said.
channelGraineChatChannelrequiredVOICE when every turn of it was said on a call, else CHAT.
turnsIntrequiredHow many turns it holds.
currentBooleanrequiredtrue for the chat's current session: its id is Graine.chat.sessionId. Never for a session with no id.
val sessions by Graine.chat.sessions.collectAsState()
LazyColumn {
    items(sessions.reversed()) { s ->                       // newest first
        SessionRow(
            title = if (s.channel == GraineChatChannel.VOICE) "Call" else "Chat",
            subtitle = "${s.turns} messages",
            current = s.current,
            id = s.id,                                       // what Execution Logs shows; null for older turns
        )
    }
}

GrainePastSessions

Read it to draw a screen of the user's past sessions with this agent — a history like the dashboard's Execution History, in your own app.

data class GrainePastSessions(val sessions: List<GraineSessionSummary> = emptyList(), val loading: Boolean = false, val hasMore: Boolean = false, val error: String? = null)

0.14.3. Graine.chat.pastSessions: the sessions loaded so far, newest first, whether a page is loading, whether there is another, and why the last one did not come.

What to expect — Empty until refreshPastSessions(), which loads the first page; loadMorePastSessions() appends the next while hasMore is true. Only the signed-in user's own sessions, from a device bound to them; the session open now is never in it. Cleared — sessions, hasMore and error — when the identity changes (another user, or nobody), and a page still on its way for the one before is never shown.

FieldTypeDefaultMeaning
sessionsList<GraineSessionSummary>emptyList()The sessions loaded so far, newest first (GraineSessionSummary); a session is never listed twice.
loadingBooleanfalseA page is on its way — draw a spinner; what was loaded stays meanwhile.
hasMoreBooleanfalseThere is another page: loadMorePastSessions() appends it.
errorString?nullWhy the last page did not come, as a word (GraineErrorCode's wire): identity_required (nobody signed in), device_limit (this device is not one of the user's), rate_limited, unavailable, network; null once a page comes.
@Composable
fun History() {
    val past by Graine.chat.pastSessions.collectAsState()
    LaunchedEffect(Unit) { Graine.chat.refreshPastSessions() }
    LazyColumn {
        items(past.sessions, key = { it.id }) { s -> Text(s.preview.ifEmpty { s.channel.wire }) }
        item { if (past.hasMore) LaunchedEffect(past.sessions.size) { Graine.chat.loadMorePastSessions() } }
    }
}

GraineSessionSummary

Read it to draw one row of the user's past sessions.

data class GraineSessionSummary(val id: String, val startedAt: Instant, val endedAt: Instant? = null, val durationSeconds: Int? = null, val channel: GraineSessionChannel = GraineSessionChannel.CHAT, val direction: GraineSessionDirection? = null, val status: String = "", val turns: Int = 0, val preview: String = "")

0.14.3. One of the user's earlier sessions with this agent, in Graine.chat.pastSessions. Open its messages with sessionTranscript(id).

What to expect — Made by the SDK, newest first. A field Graine did not send has its default; status is passed on as Graine says it, so show a word you do not know as it is.

FieldTypeDefaultMeaning
idStringrequiredThe session's id — the id Execution History shows; pass it to sessionTranscript(id).
startedAtInstantrequiredWhen it started.
endedAtInstant?nullWhen it ended; null when Graine did not say.
durationSecondsInt?nullHow long it lasted, in whole seconds; null when Graine did not say.
channelGraineSessionChannelCHATTyped, talked in the app, or a call (GraineSessionChannel).
directionGraineSessionDirection?nullWho started a call or a talk (GraineSessionDirection); null for a chat, and when Graine did not say.
statusString""How it ended, in plain words — completed, missed, failed, …
turnsInt0How many messages it holds.
previewString""The user's first line, at most 120 characters; empty when there is none.
val row = GraineSessionSummary("ex-7a1c0001", Clock.System.now(), durationSeconds = 276, status = "completed", turns = 9, preview = "Can I move my check-in call to Friday?")

GraineSessionChannel

Read it to label a past session as a chat, a talk or a call.

enum class GraineSessionChannel(val wire: String)

0.14.3. Where a past session happened; wire is the word Graine uses (chat, voice, call).

What to expect — Anything Graine says other than voice or call is CHAT.

CaseMeaning
CHATTyped, in the chat.
VOICETalked with the agent in the app.
CALLA call with the agent — direction says who rang whom.

GraineSessionDirection

Read it to say who started a past call or talk.

enum class GraineSessionDirection(val wire: String)

0.14.3. wire is the word Graine uses (inbound, outbound); GraineSessionSummary.direction is null when there is none.

CaseMeaning
INBOUNDThe user reached the agent.
OUTBOUNDThe agent reached the user.

GraineSessionTranscript

Read it to draw what was said in one of the user's past sessions.

data class GraineSessionTranscript(val id: String, val startedAt: Instant? = null, val endedAt: Instant? = null, val durationSeconds: Int? = null, val channel: GraineSessionChannel = GraineSessionChannel.CHAT, val direction: GraineSessionDirection? = null, val status: String = "", val turns: List<GraineSessionTurn> = emptyList())

0.14.3. What Graine.chat.sessionTranscript(id) answers: the session as pastSessions lists it, and every message said in it, oldest first.

What to expect — A field Graine did not send has its default.

FieldTypeDefaultMeaning
idStringrequiredThe session's id.
startedAtInstant?nullWhen it started; null when Graine did not say.
endedAtInstant?nullWhen it ended; null when Graine did not say.
durationSecondsInt?nullHow long it lasted, in whole seconds; null when Graine did not say.
channelGraineSessionChannelCHATTyped, talked in the app, or a call.
directionGraineSessionDirection?nullWho started a call or a talk; null for a chat.
statusString""How it ended, in plain words.
turnsList<GraineSessionTurn>emptyList()What was said, oldest first (GraineSessionTurn).
val saidByThem = transcript.turns.count { it.role == GraineRole.USER }

GraineSessionTurn

Read it to draw one message of a past session.

data class GraineSessionTurn(val role: GraineRole, val text: String, val at: Instant)

0.14.3. One message in GraineSessionTranscript.turns.

FieldTypeDefaultMeaning
roleGraineRolerequiredWho said it: USER or AGENT — which side to draw the bubble on (GraineRole).
textStringrequiredWhat was said.
atInstantrequiredWhen it was said.
val line = GraineSessionTurn(GraineRole.AGENT, "Done: Friday at 10:00.", Clock.System.now())

GraineDelivery

Read it to show where one of the user's messages is.

enum class GraineDelivery { SENDING, SENT, FAILED }

What to expect — Only on the user's messages; the agent's are null.

CaseMeaning
SENDINGWaiting for the connection: typed while the chat was not connected, sent as soon as it is. Draw it as pending.
SENTOn its way to the agent. Draw it as sent.
FAILEDThe chat could not reconnect to send it. Offer a retry: GraineChat.retry().

GraineChatChannel

Read it to tell a typed message from one said on a call.

enum class GraineChatChannel(val wire: String)

What to expect — A chat window draws a run of VOICE messages as one “Voice call” row, never their words.

PropertyTypeMeaning
wireStringThe word Graine uses: chat or voice — for logs.
CaseMeaning
CHATTyped in the chat.
VOICESaid on a call with the agent — only a restored message is.

GraineChatStatus

Read it to show where the chat is — in the words every Graine SDK uses.

enum class GraineChatStatus(val wire: String)

What to expect — IDLE → CONNECTING → CONNECTED; a drop — or a first try that failed — goes to RECONNECTING and back; FAILED when the chat gave up; DISCONNECTED when Graine ended an idle conversation, until the user opens the chat or writes again; OFFLINE while a message waits and nothing connects it; back to IDLE when the agent ended the conversation (ended) and its connection closed — the user's next message starts over. When several apply, the first of CONNECTED, RECONNECTING, CONNECTING, DISCONNECTED, FAILED, OFFLINE, IDLE is the one you get. Use an else branch in a when: more may come.

Changed in 0.14.5 — the status says the same words as every Graine SDK: CONNECTED is what ONLINE was, and GraineChatStatus.ONLINE still compiles, as a deprecated alias of CONNECTED (an ONLINE -> branch matches a connected chat). A chat that gave up says FAILED, where it said OFFLINE beside GraineChat.failed; OFFLINE now means a message waiting with nothing connecting it. A when over every case without an else needs the two new ones.

PropertyTypeMeaning
val wire: StringStringThe word every Graine SDK uses: idle, connecting, connected, reconnecting, offline, failed, disconnected — for logs, analytics, or a screen shared with your other apps. 0.14.5.

GraineChatStatus.of(wire) gives the status for one of those words (any case), null for any other. 0.14.5.

CaseMeaning
IDLEThe chat is not in use — never opened, left by the user, or the app is in the background. Show nothing. Also after the agent ended the conversation (ended is true) and its connection closed: the agent's goodbye is not a failure (from 0.14.0, the same on both platforms).
CONNECTINGBeing connected. Show “Connecting…”.
CONNECTEDConnected: messages go out as they are typed. Show “Online”. ONLINE before 0.14.5.
RECONNECTINGThe chat is being connected again — after a drop, or after a first try that failed. Messages wait.
OFFLINEA message of the user's is waiting to go and nothing is connecting it — the app in the background, or a native call holding the chat. It goes once the chat connects. Show “Offline · messages send when you're back”. (Before 0.14.5 this said what FAILED says.)
FAILEDThe chat gave up: every reconnect failed, the server closed the conversation, or Graine refused it. Offer “Couldn’t connect · tap to retry”: a message, retry() or open() connects again. Never for a conversation the agent ended — that is IDLE. 0.14.5.
DISCONNECTEDGraine ended the conversation itself — idle for 5 minutes, or at the session's time limit — and it does not reconnect on its own. The messages stay; show “Disconnected”. Opening the chat or a message connects again — continued when Graine can continue it, else under a “Disconnected · new conversation” row (newConversationBefore). On iOS it needs GraineInApp 0.14.0 or later; an older one says FAILED. 0.14.0.

GraineChatSize

Pass it to choose how big the chat window opens.

enum class GraineChatSize(val wire: String)

What to expect — Which size wins: the size passed to chat.open(size), then GraineConfig.chatSize, then the agent's Window size in the dashboard, else compact. On a phone, large is a sheet over most of the screen and full the whole screen; on a tablet both open a panel in the corner.

PropertyTypeMeaning
wireStringThe design's word for it — compact, large or full — for logs.
CaseMeaning
COMPACTThe window above the voice bar.
LARGEOn a phone, a sheet covering most of the screen; on a tablet, a panel in the corner.
FULLThe whole screen.

GraineRole

Read it to know who said a line.

enum class GraineRole { USER, AGENT }

CaseMeaning
USERThe person using your app.
AGENTThe agent.

GraineQuickReply

Read it to draw one reply the agent suggests, and pass it to GraineChat.sendQuickReply when the user taps it.

data class GraineQuickReply(val label: String, val text: String)

What to expect — From GraineChat.quickReplies: at most six for a message, in the agent's order, blanks and repeats left out; each label is one line of at most 40 characters, each text at most 200. New in 0.13.0.

FieldTypeDefaultMeaning
labelStringrequiredThe words on the chip: draw them.
textStringrequiredWhat a tap sends as the user's own message — the label itself when the agent gave no other words.

GraineChatRating

Read it for the user's answer to “How was this chat?”.

data class GraineChatRating(val value: Int, val scale: Int, val style: String)

What to expect — Thumbs are value 1 (up) or 0 (down) of scale 1; stars and faces are 1–5 of 5 — report it as value out of scale. From GraineChat.rating and GraineChat.onRated. New in 0.13.0.

FieldTypeDefaultMeaning
valueIntrequiredThe answer: thumbs 1 (up) or 0 (down); stars and faces 1–5.
scaleIntrequiredThe highest value can be: 1 for thumbs, 5 for stars and faces.
styleStringrequiredHow it was asked: "thumbs", "stars" or "emoji" (five faces).

GraineChatPin (the pinned card)

Pass it to GraineChat.pin to show what the conversation is about.

data class GraineChatPin(val title: String, val subtitle: String? = null, val imageUrl: String? = null, val badge: String? = null)

What to expect — Drawn as a bar under the chat window's header or as a card at the top of the conversation, as the design says; never sent to the agent. Each line is drawn on one line and cut to its length: the title at 60 characters, the subtitle at 80, the badge at 24. GraineChat.pinned hands it back cleaned that way. New in 0.13.0.

FieldTypeDefaultMeaning
titleStringrequiredWhat the conversation is about — an item, a request, an account. A blank title pins nothing.
subtitleString?nullA second, quieter line under the title.
imageUrlString?nullThe address of a picture for the thumbnail (https://…), filled and cropped; null — or an address that is not a web address — draws the title's first letter instead.
badgeString?nullA short word at the trailing end, such as “Active” or “2 items”.

GraineChat (Compose)

Use it to show the SDK's own chat screen in a Compose Multiplatform UI.

@Composable
expect fun GraineChat(modifier: Modifier = Modifier, onClose: (() -> Unit)? = null, agent: String = Graine.DEFAULT_AGENT)

In ai.graine:inapp-kmp-compose. The chat as a whole screen, drawn in the agent's design: the header, one bubble per reply, the components the agent draws, the composer — and, where Graine rings this phone, the user's booked calls with Book a call (Booking with the SDK's sheet). It draws the chat style chosen in the Garage — Classic, the chat as it has always looked and the default, or Soft, Bold, Glass, Minimal, Crisp, Cozy, Calm, Compact or Lively — every piece as the design tunes it (GraineThemeTokens.Chat): the replies the agent suggests as chips, a rating card once the agent ends the conversation, the card your app pins (Graine.chat.pin), a paperclip while your app takes attachments (Graine.chat.onAttach) and, where the design has one and the agent takes calls, a button that calls the agent. A design saved before chat styles draws exactly as it did. It connects when it appears; after it leaves the screen the conversation stays connected for Graine.chat.closeDelaySeconds (15 seconds unless you set another), so opening it again in that time continues it (0.14.3; 5 idle minutes before), and when Graine ends an idle conversation the header says Disconnected until the user opens the chat or writes again. A conversation that continues opens on its earlier messages — under day separators, an earlier call as one “Voice call” row, no starters — with New conversation in the header. On Android it hosts the Android SDK's chat view; on iOS the iOS SDK's chat screen, inside Compose's accessibility tree so VoiceOver reaches it. Nothing is drawn before Graine.configure, or for an agent that is not configured.

ParameterTypeDefaultMeaning
modifierModifierModifierWhere and how big the chat is drawn.
onClose(() -> Unit)?nullCalled when the user taps the header's close control. null: on iOS no close control is drawn and your navigation closes it.
agentStringGraine.DEFAULT_AGENTWhich configured agent's chat to show.

Returns — nothing (a composable).

Errors — none.

@Composable
fun ChatScreen(onBack: () -> Unit) {
    GraineChat(Modifier.fillMaxSize(), onClose = onBack)   // onBack: your navigation's back
}
 
@Composable
fun HelpScreen() {
    GraineChat(Modifier.fillMaxSize(), agent = "support")
}

GraineViews

Use it on iOS to present the SDK's own screens as UIKit view controllers.

object GraineViews

In iosMain. For an app that presents UIKit itself; Compose Multiplatform apps use GraineChat(), GraineCallScreen() and GraineAgentBar(), which host these.

What to expect — Each function throws IllegalStateException before Graine.configure (or for an agent that is not configured).

Its functions: chat, voiceBar, callScreen, avatarView — each with its parameters, what it returns, its errors and an example.

GraineViews.chat

Call it on iOS to get an agent's chat as a view controller to present.

fun chat(onClose: (() -> Unit)? = null, agent: String = Graine.DEFAULT_AGENT): UIViewController

The iOS SDK's chat screen, drawn in the agent's design — its chat style, suggested replies, rating card, pinned card and paperclip exactly as GraineChat() draws them — with the user's booked calls and Book a call where Graine rings this phone.

ParameterTypeDefaultMeaning
onClose(() -> Unit)?nullCalled when the user taps the header's close control; null draws none — your navigation closes it.
agentStringGraine.DEFAULT_AGENTWhich configured agent's chat.

Returns — UIViewController.

Errors — IllegalStateException when the agent is not configured.

import platform.UIKit.UIViewController
 
fun showChat(from: UIViewController) {
    val chat = GraineViews.chat(onClose = { from.dismissViewControllerAnimated(true, completion = null) })
    from.presentViewController(chat, animated = true, completion = null)
}

GraineChatRows

Use it to lay out a chat screen of your own the way the SDK's chat window does.

object GraineChatRows

The rule every Graine SDK draws its own chat window by: a bubble per typed message; one “Voice call · 6:05 PM” row for a run of voice messages on one day; a day separator — Today, Yesterday, a date — before the first row when it is not from today, and wherever the device's day changes between rows; and, given Graine.chat.newConversationBefore, a “Disconnected · new conversation” row where Graine began a new conversation under earlier lines. A conversation all from today draws exactly as before.

PropertyTypeMeaning
const val NEW_CONVERSATION = "Disconnected · new conversation"StringThe words of the row where a new conversation began (GraineChatRow NewConversation) — draw it like a day separator. 0.14.0.
const val NEW_CONVERSATION_SPOKEN = "Disconnected. A new conversation started."StringWhat a screen reader says for that row. 0.14.0.

Its functions: build, dayLabel, callLabel, offersStarters, offersNewConversation — each with its parameters, what it returns, its errors and an example.

GraineChatRows.build

Call it to turn the chat's messages into the rows to draw, in order.

fun build(turns: List<GraineChatTurn>, now: Instant = Clock.System.now(), zone: TimeZone = TimeZone.currentSystemDefault()): List<GraineChatRow>
fun build(turns: List<GraineChatTurn>, newConversationBefore: Collection<String>, now: Instant = Clock.System.now(), zone: TimeZone = TimeZone.currentSystemDefault()): List<GraineChatRow>

With newConversationBefore (0.14.0.), a NewConversation row goes before each message whose ID is in it — after that message's day separator, and only under earlier rows: with nothing drawn before it there is nothing to set apart. A marked voice message starts a call row of its own.

ParameterTypeDefaultMeaning
turnsList<GraineChatTurn>requiredThe messages, oldest first — Graine.chat.turns.value.
newConversationBeforeCollection<String>requiredThe IDs a “Disconnected · new conversation” row goes before — Graine.chat.newConversationBefore.value. 0.14.0.
nowInstantClock.System.now()The moment “today” is counted from; now when left out.
zoneTimeZoneTimeZone.currentSystemDefault()The time zone whose days separate the rows; the device's when left out.

Returns — List<GraineChatRow> (GraineChatRow). Example value: [Day(TODAY, 2026-10-15, …), Turn(turn, 0), NewConversation("t4", 1), Turn(turn, 1), VoiceCall("voice-t2", …, 2, 3)].

Errors — none.

val rows = GraineChatRows.build(Graine.chat.turns.value, Graine.chat.newConversationBefore.value)

GraineChatRows.dayLabel

Call it to write a day separator's words.

fun dayLabel(row: GraineChatRow.Day, now: Instant = Clock.System.now(), zone: TimeZone = TimeZone.currentSystemDefault()): String
ParameterTypeDefaultMeaning
rowGraineChatRow.DayrequiredThe separator to label.
nowInstantClock.System.now()The moment “today” is counted from.
zoneTimeZoneTimeZone.currentSystemDefault()The time zone of the days.

Returns — String — “Today”, “Yesterday”, else the date, “Sat 10 Oct”, with the year when it is not this one (“Wed 31 Dec 2025”). Example value: "Yesterday".

Errors — none.

val separators = GraineChatRows.build(Graine.chat.turns.value)
    .filterIsInstance<GraineChatRow.Day>()
    .map { GraineChatRows.dayLabel(it) }   // ["Yesterday", "Today"]

GraineChatRows.callLabel

Call it to write an earlier call's row.

fun callLabel(clock: String): String
ParameterTypeDefaultMeaning
clockStringrequiredWhen the call's first message was said, in the device's short time format — “6:05 PM”.

Returns — String — “Voice call · 6:05 PM”. Example value: "Voice call · 6:05 PM".

Errors — none.

val words = GraineChatRows.callLabel("6:05 PM")

GraineChatRows.offersStarters

Call it to decide whether to show the brand's conversation starters.

fun offersStarters(turns: List<GraineChatTurn>): Boolean

Starters appear only in a fresh chat: they go once the user says something, and a continued conversation never shows them.

ParameterTypeDefaultMeaning
turnsList<GraineChatTurn>requiredThe messages, oldest first.

Returns — Boolean. Example value: true.

Errors — none.

val showStarters = GraineChatRows.offersStarters(Graine.chat.turns.value)

GraineChatRows.offersNewConversation

Call it to decide whether to offer “New conversation” in your chat's header.

fun offersNewConversation(turns: List<GraineChatTurn>): Boolean

Offered while restored messages are on screen — a conversation that continues.

ParameterTypeDefaultMeaning
turnsList<GraineChatTurn>requiredThe messages, oldest first.

Returns — Boolean. Example value: false.

Errors — none.

val offer = GraineChatRows.offersNewConversation(Graine.chat.turns.value)

GraineChatRow

Read it to draw one row of a chat laid out by GraineChatRows.build.

sealed class GraineChatRow

What to expect — Draw Day as a separator, VoiceCall as one row that a call happened (never its words), Turn as a bubble, and NewConversation like a separator with its label.

PropertyTypeMeaning
abstract val key: StringStringUse it as the row's stable key while the conversation grows: a separator by its date, a call by its first message, a bubble by its message, a new conversation's row by the message it goes before (fresh-<id>).
NewConversation · val label: StringStringDraw it as the row's words: “Disconnected · new conversation” (GraineChatRows.NEW_CONVERSATION). 0.14.0.
NewConversation · val spoken: StringStringGive it to screen readers: “Disconnected. A new conversation started.” 0.14.0.
CaseMeaning
Day(day: GraineChatDay, date: LocalDate, at: Instant)A day separator: which day (GraineChatDay), the device's date, and the first message's time on it. Label it with GraineChatRows.dayLabel.
VoiceCall(id: String, at: Instant, first: Int, last: Int)An earlier call as one row: when its first message was said, and which messages (first to last, positions in the conversation) it stands for. Label it with GraineChatRows.callLabel.
Turn(turn: GraineChatTurn, index: Int)A message bubble: the message, and its position in the conversation.
NewConversation(before: String, index: Int)Where Graine began a new conversation under earlier lines: the ID of the message it goes before (before) and that message's position (index). Drawn like a day separator, in caption type, muted, with label; never a message, and never sent. Built only by build(turns, newConversationBefore). 0.14.0.

GraineChatDay

Read it to know which day a separator names.

enum class GraineChatDay { TODAY, YESTERDAY, DATE }

CaseMeaning
TODAYToday, in the device's time zone.
YESTERDAYYesterday.
DATEAny earlier day: show the date.

The voice bar

The agent talking inside your app, beside the screen it talks about. Show the bar with GraineAgentBar() (Compose) or GraineViews.voiceBar() (UIKit); it places and ends the call itself, draws captions, the connection's state and the chat beside the call, all in the agent's design. Graine.voice is for an app that draws its own controls. The device asks the user for the microphone when the first call starts.

GraineVoice

Use it to start and end the voice bar's call from controls of your own.

class GraineVoice

Graine.voice, or GraineAgent.voice for another agent.

PropertyTypeMeaning
val state: StateFlow<GraineVoiceInfo>StateFlow<GraineVoiceInfo>Collect it to draw the call's state, what has been said and the captions switch (GraineVoiceInfo).

Its functions: start, end, setMuted, setCaptionsOn, clearCaptions — each with its parameters, what it returns, its errors and an example.

GraineVoice.start

Call it from your own “Talk” control to place the voice bar's call.

fun start()

Mounts the voice engine first if nothing has (on Android, in the activity in front). One conversation at a time: it ends the chat, and it cannot start while a native call is live.

Parameters — none.

Returns — nothing.

Errors — IllegalStateException when the agent is not configured. A refused microphone is the event GraineEvent.MicrophoneDenied.

Graine.voice.start()

GraineVoice.end

Call it from your own hang-up control.

fun end()

Parameters — none.

Returns — nothing.

Errors — IllegalStateException when the agent is not configured.

Graine.voice.end()

GraineVoice.setMuted

Call it from your own mute control.

fun setMuted(muted: Boolean)

Stops sending the user's voice without ending the call.

ParameterTypeDefaultMeaning
mutedBooleanrequiredtrue to stop sending the user's voice, false to send it again.

Returns — nothing.

Errors — IllegalStateException when the agent is not configured.

Graine.voice.setMuted(true)

GraineVoice.setCaptionsOn

Call it from your own captions (CC) control.

fun setCaptionsOn(on: Boolean)

Moves the captions switch, GraineVoiceInfo.captionsOn. While it is off the SDK's voice bar hides the line being said; the call goes on, and what was said is still kept in captions. On by default. On iOS it needs GraineInApp of this version; with an older one the captions stay on.

ParameterTypeDefaultMeaning
onBooleanrequiredtrue to show the captions, false to hide them.

Returns — nothing.

Errors — IllegalStateException when the agent is not configured.

Graine.voice.setCaptionsOn(!Graine.voice.state.value.captionsOn)

GraineVoice.clearCaptions

Call it to forget what has been said on the call — a fresh transcript for your own captions view.

fun clearCaptions()

Empties GraineVoiceInfo.captions without ending the call; the next line starts the list again. On iOS it needs GraineInApp of this version; an older one does nothing.

Parameters — none.

Returns — nothing.

Errors — IllegalStateException when the agent is not configured.

Graine.voice.clearCaptions()

GraineVoiceInfo

Read it to draw the voice bar's call in controls of your own.

data class GraineVoiceInfo(val connected: Boolean = false, val connecting: Boolean = false, val muted: Boolean = false, val captionsOn: Boolean = true, val captions: List<GraineCaption> = emptyList(), val status: GraineVoiceStatus = GraineVoiceStatus.IDLE, val error: String? = null, val agentLevel: Float = 0f, val micLevel: Float = 0f, val transport: GraineTransport? = null, val transportFallbackReason: String? = null)

FieldTypeDefaultMeaning
connectedBooleanfalseShow the call as live: the agent and the user can hear each other.
connectingBooleanfalseShow “Connecting…”: the call is being placed.
mutedBooleanfalseShow the mute control as on: nothing the user says is sent.
captionsOnBooleantrueShow your captions (CC) control as on: the SDK's bar shows the line being said only while it is. On by default — a caption nobody asked to hide is an accessibility default. setCaptionsOn moves it.
captionsList<GraineCaption>emptyList()What has been said this call, oldest first: the last 12 lines, a live one replaced as its words arrive (GraineCaption). A new call starts empty. Kept whether the captions are on or off; clearCaptions() forgets them.
statusGraineVoiceStatusGraineVoiceStatus.IDLEThe call in one word — what the SDK's bar says (GraineVoiceStatus): connecting, listening, thinking, speaking, muted, reconnecting, failed, ended. 0.14.0.
errorString?nullWhy the call could not work, as a sentence, while status is FAILED — a setting someone must fix, or a call nothing could carry (“The call could not be connected.”, and start() tries again); null otherwise. 0.14.0.
agentLevelFloat0fThe agent's voice level as it is heard, 0–1, for a meter or visualiser of your own: about five times a second while the call is live, 0f otherwise. On iOS it needs GraineInApp 0.14.0 or later; on Android, from 0.14.1. 0.14.0.
micLevelFloat0fThe user's microphone level, 0–1, for a “you are being heard” meter: about five times a second while the call is live; 0f while muted and with no call. On iOS it needs GraineInApp 0.14.0 or later; on Android, from 0.14.1. 0.14.0.
transportGraineTransport?nullWhat the call runs on — WEBRTC or WEBSOCKET (GraineTransport) — once the call is placed; null before. 0.14.0.
transportFallbackReasonString?nullWhy a call that asked for WebRTC runs on the WebSocket (mint_failed, no_answer, ice_timeout, …); null when it did not fall back. 0.14.0.

GraineVoiceStatus

Read it to label the voice bar's call in controls of your own, as the SDK's bar does. 0.14.0.

enum class GraineVoiceStatus(val wire: String)

What to expect — First match wins, in the bar's own order: a failure, reconnecting, connecting, muted, thinking, speaking, listening; with no call, ENDED once a call has ended (until the next starts), else IDLE.

PropertyTypeMeaning
val wire: StringStringThe word every Graine SDK uses: idle, connecting, listening, thinking, speaking, reconnecting, muted, failed, ended.
CaseMeaning
IDLENo call. Show “Tap to talk”.
CONNECTINGThe call is being placed. Show “Connecting…”.
LISTENINGThe agent is waiting for the user. Show “Listening”.
THINKINGThe user finished a sentence and the agent has not answered yet. Show “Thinking…”.
SPEAKINGThe agent is talking. Show “Speaking”.
RECONNECTINGThe network dropped the call and it is being made again. Show “Reconnecting…”.
MUTEDOn the call with the microphone off. Show “Muted”.
FAILEDThe call could not work: GraineVoiceInfo.error says why. Show it, and offer start() again.
ENDEDA call ended and no other has started.
FunctionReturnsMeaning
companion · fun of(word: String?): GraineVoiceStatus?GraineVoiceStatus?Call it to read a status from its word, any case; null for any other word.
val talk by Graine.voice.state.collectAsState()
Text(when (talk.status) {
    GraineVoiceStatus.IDLE, GraineVoiceStatus.ENDED -> "Tap to talk"
    GraineVoiceStatus.CONNECTING -> "Connecting…"
    GraineVoiceStatus.LISTENING -> "Listening"
    GraineVoiceStatus.THINKING -> "Thinking…"
    GraineVoiceStatus.SPEAKING -> "Speaking"
    GraineVoiceStatus.MUTED -> "Muted"
    GraineVoiceStatus.RECONNECTING -> "Reconnecting…"
    GraineVoiceStatus.FAILED -> talk.error ?: "Couldn't connect"
})

GraineCaption

Read it to show the line being said on a call.

data class GraineCaption(val role: GraineRole, val text: String, val live: Boolean)

The last line of a native call (GraineCallInfo.caption). The voice bar's lines arrive as the event GraineEvent.Caption and are kept, the last 12, in GraineVoiceInfo.captions; the captions switch (captionsOn) hides the bar's caption, never the list.

FieldTypeDefaultMeaning
roleGraineRolerequiredWho is speaking: the agent's words as they are spoken, the user's as they are heard.
textStringrequiredThe words so far.
liveBooleanrequiredDraw it as provisional while true: the line is still arriving.

GraineTransport

Pass it in GraineConfig.transport only to force how the voice bar's audio travels.

enum class GraineTransport(val wire: String)

What to expect — Leave transport null and the dashboard's Call audio setting decides.

PropertyTypeMeaning
wireStringThe setting's word: ws or rtc.
CaseMeaning
WEBSOCKETThe standard path: the audio on the conversation's own connection. Works everywhere.
WEBRTCHigh-quality audio, with a jitter buffer and the device's echo canceller; falls back to WEBSOCKET.

GraineAgentBar

Use it to show the voice bar in a Compose Multiplatform UI.

@Composable
expect fun GraineAgentBar(modifier: Modifier = Modifier, name: String? = null, onClose: (() -> Unit)? = null, agent: String = Graine.DEFAULT_AGENT)

In ai.graine:inapp-kmp-compose. It takes up the whole space you give it and draws the bar along the bottom edge, so place it in a strip at the bottom of your layout. It mounts the voice engine itself; on iOS VoiceOver reaches into it. The chat opens at the size passed to Graine.chat.open(size); failing that, at GraineConfig.chatSize; failing that, at the dashboard's setting — large and full open over the app, as a sheet or the whole screen. Nothing is drawn before Graine.configure.

ParameterTypeDefaultMeaning
modifierModifierModifierThe area the bar is drawn in, at its bottom.
nameString?nullThe name beside the status; null shows the dashboard's heading.
onClose(() -> Unit)?nullCalled when the user hung up, or closed the bar with no call — hide the bar there.
agentStringGraine.DEFAULT_AGENTWhich configured agent the bar talks to.

Returns — nothing (a composable).

Errors — none.

@Composable
fun HomeScreen() {
    var showBar by remember { mutableStateOf(true) }
    Box(Modifier.fillMaxSize()) {
        AppContent()
        if (showBar) GraineAgentBar(Modifier.align(Alignment.BottomCenter).fillMaxWidth().height(180.dp), onClose = { showBar = false })
    }
}

GraineViews.voiceBar

Call it on iOS to get an agent's voice bar as a view controller.

fun voiceBar(name: String? = null, onClose: (() -> Unit)? = null, agent: String = Graine.DEFAULT_AGENT): UIViewController

The bar is drawn at the bottom of the view it fills.

ParameterTypeDefaultMeaning
nameString?nullThe name beside the status; null shows the dashboard's heading.
onClose(() -> Unit)?nullCalled when the user hung up, or closed the bar with no call.
agentStringGraine.DEFAULT_AGENTWhich configured agent the bar talks to.

Returns — UIViewController.

Errors — IllegalStateException when the agent is not configured.

import platform.UIKit.*   // UIViewController and its child-controller calls
 
fun showVoiceBar(parent: UIViewController) {
    lateinit var bar: UIViewController
    bar = GraineViews.voiceBar(onClose = {        // the user hung up, or closed the bar
        bar.view.removeFromSuperview()
        bar.removeFromParentViewController()
    })
    parent.addChildViewController(bar)
    bar.view.setFrame(parent.view.bounds)         // the bar draws along the bottom of this frame
    parent.view.addSubview(bar.view)
    bar.didMoveToParentViewController(parent)
}

Graine.onRequestPermissionsResult

Call it from an Android activity's onRequestPermissionsResult when that activity shows the voice bar or places calls.

fun Graine.onRequestPermissionsResult(requestCode: Int, grantResults: IntArray): Boolean

The SDK asks for the microphone from the activity in front; forwarding the answer lets the call go ahead once it is granted. In androidMain only.

ParameterTypeDefaultMeaning
requestCodeIntrequiredAs Android passes it to your activity.
grantResultsIntArrayrequiredAs Android passes them to your activity.

Returns — Boolean — true when the request was the SDK's (and handled). Example value: true.

Errors — none.

override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
    if (Graine.onRequestPermissionsResult(requestCode, grantResults)) return
    super.onRequestPermissionsResult(requestCode, permissions, grantResults)
}

Several agents in one app

A support agent in Help, another agent elsewhere — each with its own publishable key, configured under its own name. Each agent has its own settings, chat, voice bar, actions, and scheduling and memory requests; who the user is, the install ID, the memory choice, the screen and the phone's calls are the app's and shared. Across all agents, only one conversation runs at a time. Graine itself is the default agent; the views take an agent name (GraineChat(agent = "support"), GraineAgentBar(agent = …), GraineViews.chat(agent = …)), and Graine.calls.startCall(agent = …) calls a named one.

Graine.configure(GraineConfig(baseUrl = "https://www.graine.ai", publishableKey = "pk_live_support…"), name = "support")
val support = Graine.agent("support")!!
support.chat.open()
Graine.calls.startCall(reason = "billing", agent = "support")

Graine.agent (by name)

Call it to reach an agent you configured under a name.

fun agent(name: String = DEFAULT_AGENT): GraineAgent?
ParameterTypeDefaultMeaning
nameStringDEFAULT_AGENTThe name it was configured under; the default agent when left out.

Returns — GraineAgent? — the agent, or null when nothing is configured under that name. Example value: GraineAgent(name="support").

Errors — none.

val support = Graine.agent("support") ?: return

GraineAgent

Use it to work with one particular agent — its chat, voice bar, actions, bookings and memory.

class GraineAgent

Returned by Graine.configure and Graine.agent. Graine is the default agent's; this is any agent's.

What to expect — Calling a function before this agent is configured throws IllegalStateException (“The agent "support" is not configured: call Graine.configure(config, name = "support") first.”).

PropertyTypeMeaning
val name: StringStringRead it to know which agent this is: the name it was configured under, "default" for the default agent.
val session: StateFlow<GraineSession?>StateFlow<GraineSession?>Collect it to know when this agent's settings have loaded; null before.
val theme: StateFlow<GraineThemeTokens?>StateFlow<GraineThemeTokens?>Collect it to draw UI of your own in this agent's design (GraineThemeTokens), for the phone's light or dark appearance — or the brand's fixed scheme — changing when the phone switches. null before its settings load, and when they carry no design. On iOS it needs GraineInApp of this version.
val events: SharedFlow<GraineEvent>SharedFlow<GraineEvent>Collect it to hear what this agent reports (GraineEvent). Not replayed.
val chat: GraineChatGraineChatUse it to drive this agent's chat.
val voice: GraineVoiceGraineVoiceUse it to drive this agent's voice-bar call.
val schedulingRules: GraineSchedulingRulesGraineSchedulingRulesRead it to know what this agent lets users book; the defaults (no booking) before its settings load.
val isConfigured: BooleanBooleanRead it to know whether this agent has been configured.
val bookingAvailable: BooleanBooleanRead it to decide whether to offer booking with this agent (GraineAgent.bookingAvailable).
val bookingUnavailableReason: String?String?Read it to say why booking with this agent is not offered; null when it is (GraineAgent.bookingUnavailableReason). 0.14.0.
val bookingState: StateFlow<GraineBookingState>StateFlow<GraineBookingState>Collect it to follow whether this agent can be booked as the answer changes (GraineAgent.bookingState). 0.14.4.
val component: StateFlow<GraineComponent?>StateFlow<GraineComponent?>Collect it to draw the component this agent drew that waits for an answer (GraineAgent.component). 0.14.0.
val componentPending: StateFlow<Boolean>StateFlow<Boolean>Collect it to draw a loader while a component this agent asked for is on its way (GraineAgent.component). 0.14.0.
val componentAwaitingReply: StateFlow<Boolean>StateFlow<Boolean>Collect it to show that this agent is answering a component your app answered: true until the agent starts its reply, or 12 seconds pass (GraineAgent.component). 0.14.8.

Its functions: setVariables, currentVariables, registerAction, memories, forgetMemory, presentBooking, bookingSlots, scheduleCall, scheduledCalls, cancelScheduledCall, startCall — each with its parameters, what it returns, its errors and an example.

Screen context, actions and components

Tell the agent what the user is looking at, and let it act in your app through handlers you register. The screen is the app's: every agent hears it while it has a live conversation. Values are masked on the device before anything leaves it; report real values. The agent's components (product lists, choices, time slots) are drawn by the SDK's views; an app that draws its own hears them as GraineEvent.Component.

Graine.setScreen

Call it on every meaningful change of what the user can see, so the agent talks about the right thing.

fun setScreen(screen: GraineScreen?)

An unchanged screen is not sent again; the first change goes at once and later ones at most every 400 ms. After a pause, the agent names a field that is INVALID or EMPTY instead of asking “need a hand?”. null clears it.

ParameterTypeDefaultMeaning
screenGraineScreen?requiredWhat the user can see now (GraineScreen), or null.

Returns — nothing.

Errors — IllegalStateException before configure.

val postalCode = "560001"   // what the user typed: the real value, masked on the device
Graine.setScreen(GraineScreen(
    screen = "checkout_address", title = "Delivery address",
    journey = GraineScreen.Journey("Checkout", step = 2, of = 3, next = "Payment"),
    fields = listOf(GraineField("postal_code", label = "Postal code", value = postalCode,
        status = GraineFieldStatus.INVALID, error = "We don't deliver there yet")),
))

Graine.updateField

Call it when one field changes, so a screen described once need not be described again on every keystroke.

fun updateField(field: GraineField)

Merged by name into the current screen (added when it is new) and sent like any screen change. Nothing happens before a screen is set.

ParameterTypeDefaultMeaning
fieldGraineFieldrequiredThe field as it is now (GraineField).

Returns — nothing.

Errors — IllegalStateException before configure.

val postalCode = "560034"   // what the user typed now
Graine.updateField(GraineField("postal_code", value = postalCode, status = GraineFieldStatus.FILLED))

Graine.removeField

Call it when a field leaves the screen.

fun removeField(name: String)

Nothing happens when it was never reported.

ParameterTypeDefaultMeaning
nameStringrequiredThe field's name.

Returns — nothing.

Errors — IllegalStateException before configure.

Graine.removeField("coupon")

Graine.clearScreen

Call it when the user leaves a screen — in the screen's teardown.

fun clearScreen(screenId: String? = null)

With screenId, only if that screen is still the one described — a screen closing late must not erase the one that replaced it. null clears whatever is there.

ParameterTypeDefaultMeaning
screenIdString?nullThe screen's screen ID, to clear only that one.

Returns — nothing.

Errors — IllegalStateException before configure.

Graine.clearScreen("checkout_address")

Graine.track

Call it to tell the agent about something the user did that informs without interrupting — a coupon applied, a filter changed.

fun track(name: String, data: Map<String, Any?> = emptyMap())

It rides along with the next screen update, among the user's recent events (the last ten are kept). Blank names are ignored. Masked on the device.

ParameterTypeDefaultMeaning
nameStringrequiredThe event's name, such as "coupon_applied".
dataMap<String, Any?>emptyMap()Details of the event, by name.

Returns — nothing.

Errors — IllegalStateException before configure.

Graine.track("coupon_applied", mapOf("code_length" to 8))

Graine.reportEvent

Call it when something happened that is worth the agent speaking up about — it may speak first. 0.14.4.

fun reportEvent(name: String, detail: String? = null, data: Map<String, Any?> = emptyMap())

Told to the default agent's live conversation: the user opened the chat from a reminder, and the agent opens with its check-in question. Which one hears it: on iOS a native call with the agent, once it is connected (0.14.5, with GraineInApp 0.14.5), else the chat, else the voice bar's call; on Android the voice bar's call, else the chat — a native call on Android does not hear it yet. With none live it is dropped, never kept for later — open the chat and wait for Graine.chat.status to be CONNECTED first. The agent paces itself: 20 seconds apart and 3 per conversation by default. track informs without making the agent speak. Blank names are ignored. On iOS it needs GraineInApp 0.14.4 or later; an older one drops it. GraineAgent.reportEvent tells another agent's conversation.

At most 8 KB (0.14.5) — Graine.REPORT_EVENT_MAX_BYTES, 8192 bytes: the event — its name, detail, the pacing keys and data — as JSON, in UTF-8. A bigger event is never sent, on any conversation or platform: Graine would close the conversation it was sent on. Graine.events hears a GraineEvent.Error that says so, with the event's size. Send what the agent needs to speak up — an ID it can look up, not the whole record.

ParameterTypeDefaultMeaning
nameStringrequiredThe event's name, such as "reminder_opened".
detailString?nullWhat happened, in a sentence the agent reads as the situation to help with.
dataMap<String, Any?>emptyMap()Details by name. cooldown_seconds (seconds before the agent may speak up again), max_per_session (how many times per conversation) and quiet = true (record it without speaking) change the pacing, at the event's own level; everything else rides under the event's data — a name or detail key there never replaces the event's own.

Returns — nothing.

Errors — IllegalStateException before configure. An event over 8 KB throws nothing: it is not sent, and Graine.events hears why.

Graine.chat.open()
Graine.chat.status.first { it == GraineChatStatus.CONNECTED }
Graine.reportEvent("reminder_opened", "The user came from the breakfast reminder")

GraineAgent.reportEvent

Call it to tell one of your other agents' live conversations something worth speaking up about. 0.14.4.

fun reportEvent(name: String, detail: String? = null, data: Map<String, Any?> = emptyMap())

Graine.reportEvent for this agent's chat or call.

Returns — nothing.

Errors — IllegalStateException when this agent is not configured.

Graine.agent("support")?.reportEvent("plan_viewed", "The user opened the Plans screen")

Graine.tap

Call it to tell the agent the user tapped a control the SDK cannot name by itself — a custom-drawn button, say.

fun tap(name: String)

Reported as tap:<name> among the screen's recent events, at most twice a second, and only while a screen is set. Labelled controls are noticed by themselves (GraineConfig.captureTaps).

ParameterTypeDefaultMeaning
nameStringrequiredThe control's name as the agent should read it; at most 40 characters are kept.

Returns — nothing.

Errors — IllegalStateException before configure.

Graine.tap("Apply coupon")

Graine.noteInteraction

Call it when the user does something that is not a field edit — scrolls a list, opens a picker — so the SDK does not think they are stuck.

fun noteInteraction()

Restarts the clock that notices a user stuck on a step. Field edits do not count: someone typing one character every forty seconds is exactly who is stuck.

Parameters — none.

Returns — nothing.

Errors — IllegalStateException before configure.

Graine.noteInteraction()

Graine.setVariables

Call it when your app learns something the default agent's prompt uses — a plan, a cart total.

fun setVariables(values: Map<String, Any?>?)

Merged over what is there: null under a key removes it, null for the whole map clears them all. Masked on the device; reaches the next conversation. GraineAgent.setVariables sets another agent's.

ParameterTypeDefaultMeaning
valuesMap<String, Any?>?requiredPrompt variables by name; numbers and booleans are written out as text, nested maps and lists are dropped.

Returns — nothing.

Errors — IllegalStateException before configure.

Graine.setVariables(mapOf("plan" to "gold", "cart_total" to 42))

Mapping your user's fields to the names the agent's prompt reads, at sign-in and sign-out, for every agent: Send your user's details to the agent.

GraineAgent.setVariables

Call it to set prompt variables for one of your other agents.

fun setVariables(values: Map<String, Any?>?)

Graine.setVariables for this agent.

ParameterTypeDefaultMeaning
valuesMap<String, Any?>?requiredPrompt variables by name; null under a key removes it, null clears all.

Returns — nothing.

Errors — IllegalStateException when this agent is not configured.

Graine.agent("support")?.setVariables(mapOf("ticket_count" to 2))

Graine.currentVariables

Call it to see exactly which prompt variables the default agent's next conversation will carry — on a debug screen, or before a support request.

fun currentVariables(): Map<String, String>

Every variable the agent will receive, merged in precedence order: the dashboard's defaults, GraineConfig.variables, setVariables, then who is signed in (identify's traits, the identity trait itself withheld). What the next conversation carries, as text; values are masked as they leave the device. A copy: changing it changes nothing. GraineAgent.currentVariables() reads another agent's. On iOS it needs GraineInApp of this version; an older one answers an empty map.

Parameters — none.

Returns — Map<String, String>. Example value: {plan=gold, cart_total=42, name=Asha}.

Errors — IllegalStateException before configure.

val vars = Graine.currentVariables()   // {plan=gold, cart_total=42, name=Asha}

GraineAgent.currentVariables

Call it to see the prompt variables one of your other agents will receive.

fun currentVariables(): Map<String, String>

Graine.currentVariables() for this agent: its dashboard defaults, its configuration's variables, its setVariables, then who is signed in.

Parameters — none.

Returns — Map<String, String> — a copy.

Errors — IllegalStateException when this agent is not configured.

val vars = Graine.agent("support")?.currentVariables().orEmpty()

Graine.registerAction

Call it to let the default agent do one thing in your app — open a screen, apply a filter, change a setting.

fun registerAction(name: String, handler: suspend (args: Map<String, Any?>) -> GraineActionResult): () -> Unit

Declare the action on the agent in the dashboard too: a handler with no declaration is never offered, and a declared action with no handler is refused when the agent asks for it. The handler starts on the main thread (it will usually touch your UI) and may suspend — a network call, a confirmation the user taps — continuing on the main thread. It must answer within six seconds, or the agent is told it was not done. A handler that throws answers error with its message; one cancelled answers error with “The action was cancelled.”. Defining an action again under the same name replaces its handler. GraineAgent.registerAction registers with another agent.

ParameterTypeDefaultMeaning
nameStringrequiredThe action's name, exactly as it is declared on the agent.
handlersuspend (args: Map<String, Any?>) -> GraineActionResultrequiredRuns the action with the agent's arguments and says how it went (GraineActionResult). Tell the truth: the agent speaks about exactly this.

Returns — () -> Unit — call it to unregister this handler.

Errors — IllegalStateException before configure.

val unregister = Graine.registerAction("open_screen") { args ->
    val screen = args["screen"] as? String ?: return@registerAction GraineActionResult.refused("No screen was named.")
    router.open(screen)
    GraineActionResult.ok("Opened $screen.")
}

GraineAgent.registerAction

Call it to give one of your other agents an action.

fun registerAction(name: String, handler: suspend (args: Map<String, Any?>) -> GraineActionResult): () -> Unit

Graine.registerAction for this agent: the same six seconds, the same rules.

ParameterTypeDefaultMeaning
nameStringrequiredThe action's name, as declared on this agent.
handlersuspend (args: Map<String, Any?>) -> GraineActionResultrequiredRuns the action and says how it went.

Returns — () -> Unit — call it to unregister.

Errors — IllegalStateException when this agent is not configured.

Graine.agent("support")?.registerAction("open_ticket") { args -> openTicket(args["id"] as String); GraineActionResult.ok() }

GraineScreen

Pass it to Graine.setScreen to describe what the user can see.

data class GraineScreen(…)

What to expect — Values are masked on the device before they leave it — report real ones; a screen that pre-redacts only blinds the agent.

FieldTypeDefaultMeaning
screenStringrequiredA stable ID for the screen, such as "checkout_address"; keep it constant, since friction rules and clearScreen match on it.
titleString?nullThe screen's title as the user sees it — what the agent calls the screen.
journeyJourney?nullWhere the screen sits in a flow (GraineScreen.Journey), so the agent can say “step 2 of 3”.
fieldsList<GraineField>emptyList()The inputs on the screen (GraineField): what lets the agent name the field that is wrong.
errorString?nullA screen-level error banner, as shown — distinct from a field's own.
dataMap<String, Any?>emptyMap()Anything else the agent should know about the screen: strings, numbers, booleans, and lists and maps of them.
availableActionsList<String>?nullWhich registered actions work on this screen: null allows every action this build registered, an empty list allows none.

GraineScreen.Journey

Pass it in GraineScreen.journey to say where a screen sits in a flow.

data class Journey(val name: String, val step: Int? = null, val of: Int? = null, val next: String? = null)

FieldTypeDefaultMeaning
nameStringrequiredThe flow's name, such as "Checkout".
stepInt?nullWhich step this screen is, counting from 1.
ofInt?nullHow many steps the flow has.
nextString?nullWhat comes next, such as "Payment" — so the agent can say what is left.

GraineField

Pass it in GraineScreen.fields (or to updateField) to describe one input.

data class GraineField(…)

What to expect — Its status is what lets the agent name the field that is wrong.

FieldTypeDefaultMeaning
nameStringrequiredA stable ID for the field, by which updateField and removeField find it.
labelString?nullThe label the user sees — what the agent calls the field.
valueString?nullThe real value; it is masked on the device on its way out. Never pre-redact it.
statusGraineFieldStatus?nullWhere the field stands (GraineFieldStatus).
errorString?nullThe validation message the user sees, so the agent can help them fix it.
optionalBooleanfalsetrue when leaving it blank is fine, so the agent does not count it as work left.

GraineFieldStatus

Use it to say where a field stands.

enum class GraineFieldStatus(val wire: String)

What to expect — INVALID and EMPTY are what make the agent speak up about a field.

PropertyTypeMeaning
wireStringThe word sent to the agent: empty, filled, invalid, pending or locked.
CaseMeaning
EMPTYNothing entered yet.
FILLEDEntered and accepted.
INVALIDEntered and refused — set error to the message shown.
PENDINGBeing checked (a code being verified, an upload in progress).
LOCKEDNot the user's to change — the agent does not ask them to.

GraineActionResult

Return it from an action handler to tell the agent what happened.

data class GraineActionResult(val status: Status, val message: String = "", val data: Map<String, Any?> = emptyMap())

What to expect — The agent speaks about exactly this, so tell the truth: ok only when it really happened.

FieldTypeDefaultMeaning
statusStatusrequiredHow it went (GraineActionResult.Status).
messageString""What the agent is told — not shown to the user; the agent decides how to say it.
dataMap<String, Any?>emptyMap()Structured details the agent can use in its reply.

Its functions: ok, refused, error — each with its parameters, what it returns, its errors and an example.

GraineActionResult.Status

Read it to know how an action went.

enum class Status(val wire: String) { OK("ok"), REFUSED("refused"), ERROR("error") }

PropertyTypeMeaning
wireStringThe word sent to the agent: ok, refused or error.
CaseMeaning
OKIt happened; the agent tells the user it is done.
REFUSEDThe action will not be done, with the reason — often the most helpful thing to tell the agent.
ERRORIt was tried and failed.

GraineActionResult.ok

Return it when the action happened.

fun ok(message: String = "", data: Map<String, Any?> = emptyMap()): GraineActionResult
ParameterTypeDefaultMeaning
messageString""What the agent is told happened.
dataMap<String, Any?>emptyMap()A structured result for the agent.

Returns — GraineActionResult with status OK.

Errors — none.

GraineActionResult.ok("The app is now in Spanish.")

GraineActionResult.refused

Return it when the action will not happen, and say why.

fun refused(message: String): GraineActionResult
ParameterTypeDefaultMeaning
messageStringrequiredWhy not, for the agent to explain.

Returns — GraineActionResult with status REFUSED.

Errors — none.

GraineActionResult.refused("There is no order with that number.")

GraineActionResult.error

Return it when the action was tried and failed.

fun error(message: String): GraineActionResult
ParameterTypeDefaultMeaning
messageStringrequiredWhat went wrong, for the agent.

Returns — GraineActionResult with status ERROR.

Errors — none.

GraineActionResult.error("The network is unavailable.")

GraineComponent

Read it to draw a component the agent sent, in an interface of your own.

data class GraineComponent(val id: String, val kind: String?, val title: String?, val payload: Map<String, Any?>)

Carried by GraineChatTurn.component and the event GraineEvent.Component. The SDK's own views draw components themselves — from 0.14.9 one built from blocks too, on iOS and Android; one you draw yourself is answered with Graine.chat.answerWidget (GraineChat.answerWidget). From 0.14.8 it carries everything the dashboard's Web components page sets, for drawing it in your own design: its look (style), what a tap does in your app (onSelect, filled by tapFor), and, for a component built from blocks, its blocks (blocks).

FieldTypeDefaultMeaning
idStringrequiredThe component's ID: what an answer to it refers to.
kindString?requiredWhat it is — product_list, plan_comparison, choices, quick_actions, calendar_slots, info_card, blank (built from blocks) — or a newer kind; draw a fallback for one you do not know.
titleString?requiredIts title, when it has one.
payloadMap<String, Any?>requiredThe whole component as it arrived — items, choices, slots — to draw from. From 0.14.8 a picture in its data that the dashboard gave as a path on its own site (/samples/car.png) is a full URL on the agent's origin, as the SDK's own views draw it.
PropertyTypeMeaning
val data: Map<String, Any?>Map<String, Any?>Read it for what the component shows — its items, options or slots, as the agent sent them (the payload's data); empty when it carries none. Its pictures are full URLs (from 0.14.8: a root-relative one is on the agent's origin, GraineConfig.baseUrl). 0.14.0.
val fallbackText: String?String?Show it where you cannot draw the component's kind: the words the agent sent for that (the payload's fallback_text); null when it has none. 0.14.0.
val style: GraineComponentStyleGraineComponentStyleRead it to draw the component in your own design, in the shape the dashboard gave it: its Look & feel (the payload's style) resolved for its kind — preset, picture size, button, columns, where it goes on screen, one choice or several (GraineComponentStyle). A component with no look of its own is Cards, in the place its kind takes. 0.14.8.
val onSelect: GraineComponentTap?GraineComponentTap?Read it to know what a tap does in your app — the component's When they tap: open a screen or run an action (GraineComponentTap); null when a tap only tells the agent, the default. Fill it for the item tapped with tapFor. 0.14.8.
val blocks: List<GraineComponentBlock>List<GraineComponentBlock>Draw them for a component built from blocks (Start blank in the dashboard, kind blank): its headings, text, images, dividers and buttons, in order (GraineComponentBlock). Empty for any other kind. 0.14.8.

GraineComponent.tapFor

Call it when the user taps an item of a component you draw yourself, before you answer: it tells you what your app does for that tap. 0.14.8.

fun tapFor(item: Map<String, Any?>, summary: String? = null): GraineComponentTapCall?

The component's When they tap (onSelect), filled for the item tapped: the action your app runs — the component's own action, or open_screen for a screen path — its arguments with each placeholder ({id}, {title}, {price}, {summary}…) filled from the item, and the sentence to answer with instead of yours. Do what the SDK's own views do: run it in your app first — what your open_screen handler, or the action it names, does — without waiting for it, then answer with Graine.chat.answerWidget(id, data, call.say ?: summary). After it navigates, your app reports the new screen with Graine.setScreen, which is how the agent learns where the user now is.

ParameterTypeDefaultMeaning
itemMap<String, Any?>requiredThe tapped item's fields — usually the data you answer with: an item's id, title, price…, and when several are picked at once ids and titles, each comma-separated, as the SDK's views send them.
summaryString?nullThe sentence you would answer with; it fills {summary}. null: the item's own summary, if it has one.

Returns — a GraineComponentTapCall, or null when a tap only tells the agent (onSelect is null). Its say is null when the tap sets none, or it fills to nothing: answer with your own sentence then. A placeholder the item does not have is filled with nothing, never left as {sku}.

Errors — none.

fun onPicked(component: GraineComponent, data: Map<String, Any?>, summary: String) {
    val call = component.tapFor(data, summary)
    if (call != null) when (call.action) {
        GraineComponentTap.NAVIGATE_ACTION -> navigator.open(call.args["path"].orEmpty())   // what your open_screen handler does
        else -> myActions.run(call.action, call.args)                                     // the action the component names
    }
    Graine.chat.answerWidget(component.id, data, call?.say ?: summary)
}

GraineComponentTap

Read it to know what a tap on a component does in your app, as GraineComponent.onSelect. 0.14.8.

data class GraineComponentTap(val path: String?, val action: String?, val args: Map<String, String>, val say: String?)

The component's When they tap in the dashboard: Open a screen (path, run through the one open_screen handler your app registers) or Run an action (action, one your app registered), with args built from the tapped item. Tell the agent is no tap at all — onSelect is null — as the choice is then only a turn of the conversation. GraineComponent.tapFor fills it for an item.

What to expect — Only what every Graine SDK can read is kept: an action name of lowercase letters, digits and underscores that starts with a letter, at most 64 characters (written any case, it is read in lowercase); a path, each argument and say at most 200 characters, trimmed; at most 10 arguments, each a word, a number (written as 2, 19.5) or a yes or no — a list, a map or nothing is left out. A tap with neither an action nor a path is no tap.

FieldTypeDefaultMeaning
pathString?nullOpen a screen: a path your app's navigator understands — a route, a screen name, a deep link — with placeholders such as {id}. null when it runs an action only.
actionString?nullRun an action: the name your app registered. null for a path alone, which goes to NAVIGATE_ACTION.
argsMap<String, String>emptyThe action's arguments as the dashboard wrote them, placeholders and all.
sayString?nullWhat the agent is told instead of your own sentence, with the same placeholders; null: your sentence, which is usually right.
ConstantTypeMeaning
const val NAVIGATE_ACTION: StringStringopen_screen: the one handler an app registers so Open a screen can open any screen — its path argument is the screen. Registered once, every screen a component opens is a field in the dashboard, with no app release.

GraineComponentTapCall

Read it to run one tap's work in your app, as GraineComponent.tapFor returns it. 0.14.8.

data class GraineComponentTapCall(val action: String, val args: Map<String, String>, val say: String?)

FieldTypeDefaultMeaning
actionStringrequiredThe action your app runs for this tap: the component's own, or open_screen for a screen path.
argsMap<String, String>requiredIts arguments, each placeholder filled from the tapped item; a screen path travels as args["path"] either way.
sayString?requiredThe sentence to answer with instead of yours (answerWidget's summary); null: yours.

GraineComponentBlock

Read it to draw one block of a component built from blocks, as GraineComponent.blocks lists them. 0.14.8.

data class GraineComponentBlock(val id: String, val type: GraineComponentBlockType, val content: String?, val imageUrl: String?)

A component made with Start blank in the dashboard (kind blank) is a column of blocks: headings, text, images, dividers and buttons, in order. From 0.14.9 the SDK's own chat and call screen draw them themselves, in the component's look; read them for a design of your own.

What to expect — Only what can be drawn is listed: a block of a type this version does not know, a heading, text or button without words, an image without a picture, and anything that is not a block are left out, as the dashboard's own preview draws nothing for them. Each block keeps only its own field — words for a heading, text or button, a picture for an image. Each id is the block's own, or — when it has none, or an earlier block has it — block-<n>, its place in the list, so ids are unique keys for your list. An image's picture is a full URL: a root-relative one is on the agent's origin.

FieldTypeDefaultMeaning
idStringrequiredA key unique within the component.
typeGraineComponentBlockTyperequiredWhat it is (GraineComponentBlockType).
contentString?nullThe words of a heading, a text or a button, trimmed; null for an image or a divider.
imageUrlString?nullAn image's picture; null for any other block.
Column {
    for (block in component.blocks) when (block.type) {
        GraineComponentBlockType.HEADING -> Text(block.content.orEmpty(), style = MaterialTheme.typography.titleMedium)
        GraineComponentBlockType.TEXT -> Text(block.content.orEmpty())
        GraineComponentBlockType.IMAGE -> AsyncImage(model = block.imageUrl, contentDescription = null)
        GraineComponentBlockType.DIVIDER -> HorizontalDivider()
        GraineComponentBlockType.BUTTON -> Button(onClick = {
            Graine.chat.answerWidget(component.id, mapOf("action" to block.content), block.content.orEmpty())
        }) { Text(block.content.orEmpty()) }
    }
}

GraineComponentBlockType

Read it to know what a block is, as GraineComponentBlock.type. 0.14.8.

enum class GraineComponentBlockType(val wire: String)

PropertyTypeMeaning
wireStringThe dashboard's word for it — heading, text, image, divider or button — for logs.
CaseMeaning
HEADINGA heading: its content.
TEXTA paragraph: its content.
IMAGEA picture as wide as the component: its imageUrl.
DIVIDERA line between blocks.
BUTTONA button labelled with its content. A tap answers the component as the dashboard's preview does: Graine.chat.answerWidget(id, mapOf("action" to content), content).

GraineComponentStyle

Read it to draw a component in your own design, in the shape the dashboard gave it. 0.14.8.

data class GraineComponentStyle(val preset: GraineComponentPreset, val imageSize: GraineComponentImageSize, val density: GraineComponentDensity, val button: GraineComponentButton, val facts: Boolean, val columns: Int, val surface: GraineComponentSurface, val radius: Int?, val accent: String?, val platform: GraineComponentPlatform, val select: GraineComponentSelect, val maxSelect: Int)

Carried by every component as GraineComponent.style: the look the component was given in the dashboard (its Look & feel), resolved the way every Graine SDK resolves it — the preset's defaults, then each choice made on top of them, then where it goes on screen for its kind. The SDK's own views draw a component exactly this way, so a component you draw from it matches theirs in shape while it stays in your design.

What to expect — A component with no look of its own is Cards — medium pictures, filled buttons, one column — in the place its kind takes. Only words this version knows are read: a preset or a value it does not know is left out, never guessed, so a newer preset draws as Cards rather than as nothing. radius and accent are null unless the component sets them: draw it in the agent's design then — theme.colors.accent, and the corners of theme.chat.cards (GraineThemeTokens). Reading it never throws.

FieldTypeDefaultMeaning
presetGraineComponentPresetCARDSThe whole look in one word (GraineComponentPreset).
imageSizeGraineComponentImageSizeMEDIUMHow big each item's picture is: the preset's own — LARGE for Gallery and Spotlight, MEDIUM for Cards, SMALL for List and Compact — unless the dashboard chose a size (GraineComponentImageSize).
densityGraineComponentDensityCOMFORTABLEHow much room each item takes (GraineComponentDensity).
buttonGraineComponentButtonFILLEDWhat an item's button looks like: the preset's own — FILLED for Gallery, Cards and Spotlight, ROW for List, OUTLINE for Compact — unless the dashboard chose one (GraineComponentButton).
factsBooleantrueWhether to show each item's fact chips.
columnsInt1Items side by side: 2 only for Gallery and Cards when the dashboard chose two columns.
surfaceGraineComponentSurfaceCARDWhere it goes on screen: the dashboard's choice, else the rule for its kind — product_list takes the screen; plan_comparison, choices, quick_actions and calendar_slots a sheet; info_card, and any kind this version does not know, a card (GraineComponentSurface).
radiusInt?nullIts corner radius, 0–24 dp (points on iOS), when the component sets one; null: the agent's design's.
accentString?nullIts accent colour, #RRGGBB, when the component sets one; null: the agent's design's.
platformGraineComponentPlatformAUTOWhose design grammar to follow; AUTO follows the phone (GraineComponentPlatform).
selectGraineComponentSelectONEONE: a tap answers it. MANY: the user ticks several and answers once (GraineComponentSelect).
maxSelectInt3With select MANY, the most the user may choose: 2–8.
@Composable
fun MyComponent(component: GraineComponent) {
    val theme by Graine.theme.collectAsState()
    val look = component.style
    val accent = look.accent ?: theme?.colors?.accent   // null: your app's own colour
    when (look.surface) {
        GraineComponentSurface.SCREEN -> MyListScreen(component, columns = look.columns, accent = accent)
        GraineComponentSurface.SHEET -> MyChoiceSheet(component, pickMany = look.select == GraineComponentSelect.MANY, most = look.maxSelect)
        GraineComponentSurface.CARD -> MyCard(component, accent = accent)
    }
}

GraineComponentPreset

Read it to know a component's look in one word, as GraineComponentStyle.preset. 0.14.8.

enum class GraineComponentPreset(val wire: String)

PropertyTypeMeaning
wireStringThe dashboard's word for it — gallery, cards, list, spotlight or compact — for logs.
CaseMeaning
GALLERYThe picture on top, one item to a row, a full-width button.
CARDSA thumbnail beside the item's facts, about three to a screen. The default.
LISTDense rows, each row the button — for long results.
SPOTLIGHTOne item at a time, the picture on top, swiped to compare — for two to five items.
COMPACTOne line each, with no picture, and outlined buttons.

GraineComponentImageSize

Read it to size an item's picture, as GraineComponentStyle.imageSize. 0.14.8.

enum class GraineComponentImageSize(val wire: String)

PropertyTypeMeaning
wireStringThe dashboard's word for it — small, medium or large — for logs.
CaseMeaning
SMALLA small thumbnail: List's and Compact's.
MEDIUMA medium thumbnail: Cards'.
LARGEA large picture: Gallery's and Spotlight's.

GraineComponentDensity

Read it to space a component's items, as GraineComponentStyle.density. 0.14.8.

enum class GraineComponentDensity(val wire: String)

PropertyTypeMeaning
wireStringThe dashboard's word for it — comfortable or compact — for logs.
CaseMeaning
COMFORTABLEThe usual room around and between items. The default.
COMPACTTighter: less room around and between items.

GraineComponentButton

Read it to draw an item's button, as GraineComponentStyle.button. 0.14.8.

enum class GraineComponentButton(val wire: String)

PropertyTypeMeaning
wireStringThe dashboard's word for it — filled, outline or row — for logs.
CaseMeaning
FILLEDFilled with the accent.
OUTLINEAn outline in the accent.
ROWNo button: the whole row is tapped.

GraineComponentSurface

Read it to know where a component goes on screen, as GraineComponentStyle.surface. 0.14.8.

enum class GraineComponentSurface(val wire: String)

PropertyTypeMeaning
wireStringThe dashboard's word for it — screen, sheet or card — for logs.
CaseMeaning
SCREENThe component is the screen: pictures, several items to compare.
SHEETIt slides over the app: a choice to finish, then back to the app.
CARDA card beside the conversation: a fact, or a kind you cannot draw — show its fallbackText.

GraineComponentPlatform

Read it to know whose design grammar a component follows, as GraineComponentStyle.platform. 0.14.8.

enum class GraineComponentPlatform(val wire: String)

PropertyTypeMeaning
wireStringThe dashboard's word for it — auto, ios, material or oneui — for logs.
CaseMeaning
AUTOFollow the phone: Apple's grammar on iPhone, Material on Android, One UI on a Samsung. The default.
IOSApple's grammar on every phone: 12-point corners, tag chips, soft buttons, inset dividers.
MATERIALMaterial 3 on every phone: 16 dp corners, outlined chips, pill buttons, full-width dividers.
ONEUISamsung's One UI on every phone: 26 dp corners, pill chips and buttons, roomier padding.

GraineComponentSelect

Read it to know whether the user picks one item or several, as GraineComponentStyle.select. 0.14.8.

enum class GraineComponentSelect(val wire: String)

PropertyTypeMeaning
wireStringThe dashboard's word for it — one or many — for logs.
CaseMeaning
ONEA tap is the answer. The default.
MANYA tick on each item and one button at the end: answer once, with everything chosen in data and a summary that names them (“Compare: Basic and Plus”), at most maxSelect.

GraineAgent.component

Collect it to draw the component on screen in a UI of your own — what the SDK's renderer draws. 0.14.0.

val component: StateFlow<GraineComponent?>
val componentPending: StateFlow<Boolean>
val componentAwaitingReply: StateFlow<Boolean>   // 0.14.8

component is the component the agent drew that waits for an answer, in the chat or on the voice bar's call: its id, kind, data and fallbackText, and — from 0.14.8 — everything the dashboard set on it: its look (style), what a tap does in your app (onSelect, filled by tapFor) and the blocks of one built from blocks (blocks) (GraineComponent). componentPending is true while one the agent asked for is still loading — draw a loader where it will appear. componentAwaitingReply (0.14.8) is true from the moment your app answers a component with a summary until the agent starts its reply — draw a “thinking” mark beside the choice you keep on screen, so a tap never looks unheard. Graine.component, Graine.componentPending and Graine.componentAwaitingReply are the default agent's.

What to expect — componentPending goes true when the agent asks for a component, and false when it arrives, when its conversation is over, or after 12 seconds with nothing — the SDK's renderer gives up then too. component is set when the component arrives, and goes back to null when it is answered (Graine.chat.answerWidget), closed (Graine.chat.dismissWidget), or replaced by the next one, when the voice bar's call ends, and when the chat connects again (a component from an earlier connection cannot be answered). Each component also arrives as the event GraineEvent.Component. componentAwaitingReply goes true when your app answers with Graine.chat.answerWidget and a summary — an answer without one does not move the conversation, so nothing is awaited — and false at the agent's first words (in the chat, or its voice or a caption on the voice bar's call), at its next component or that component's loader, when the conversation is over, on Graine.chat.dismissWidget, or after 12 seconds with no reply — the SDK's renderer stops waiting then too. Only your app's answers set it: the SDK's own views show their own wait.

Errors — none: before configure they hold null, false and false.

val component by Graine.component.collectAsState()
val loading by Graine.componentPending.collectAsState()
val thinking by Graine.componentAwaitingReply.collectAsState()
when {
    component != null -> MyComponentView(component!!)   // draw its style and blocks; on a tap run tapFor's call, then answerWidget; close with dismissWidget
    loading -> MyLoader()
    thinking -> MyTypingDots()                          // beside the answer you keep on screen
}

GraineChat.answerWidget

Call it when the user answers a component the agent drew that you draw yourself — a choice tapped, a slot picked.

fun answerWidget(id: String, data: Map<String, Any?>, summary: String)

Sends the answer on the conversation that is live with that agent — the chat, else the voice bar's call. data is the structured answer, for your webhook; summary is the sentence that becomes the user's turn (“The blue one, please”) — without it the conversation does not move. The SDK's own views answer for themselves. component lets the component go, and with a summary, componentAwaitingReply is true until the agent starts its reply (0.14.8; GraineAgent.component). When the component's tap does something in your app (onSelect), run tapFor's call first and answer with its say when it has one (0.14.8). On iOS it needs GraineInApp of this version; an older one does nothing.

ParameterTypeDefaultMeaning
idStringrequiredThe component's id (GraineComponent).
dataMap<String, Any?>requiredThe answer as data — strings, numbers, booleans, and lists and maps of them.
summaryStringrequiredThe answer in the user's words, said as their turn.

Returns — nothing.

Errors — IllegalStateException when the agent is not configured.

// Your own `choices` view calls this when the user taps one.
fun onChoiceTapped(component: GraineComponent, choice: String, label: String) {
    Graine.chat.answerWidget(component.id, mapOf("choice" to choice), summary = label)
}

GraineChat.dismissWidget

Call it when the user closes a component you draw yourself without choosing — your close button. 0.14.0.

fun dismissWidget(id: String)

What the close of the SDK's component view does: the agent is told quietly, so it does not go on about options nobody can see and does not speak up because a card was closed, and component lets it go. Nothing is awaited after it: componentAwaitingReply is false (0.14.8). A blank id is ignored. On iOS it needs GraineInApp of this version; with an older one only component lets it go.

ParameterTypeDefaultMeaning
idStringrequiredThe component's id (GraineComponent).

Returns — nothing; component is null when it was that component.

Errors — IllegalStateException when the agent is not configured.

IconButton(onClick = { Graine.chat.dismissWidget(component.id) }) { Icon(Icons.Default.Close, "Close") }

Calls the user places

Calls like WhatsApp, on the phone's own call screen and over the lock screen, going on with the screen off: the user calls the agent with startCall; the agent can also ring the user (Calls Graine rings). Only one call can be live: a ring that arrives during a call is reported as missed, reason busy.

What a call does on each platform. Both platforms start a call at once on the agent's settings already kept on the device, and refresh them behind the call.

  • Android (the Android SDK's engine): opening the call has 15 seconds — “The call could not connect within 15 seconds.” Once connected, nothing at all arriving for 50 seconds (two 25-second keep-alive periods) ends the call: it ends ENDED with reason failed, and the SDK's call screen says “Call failed”. Sending never holds a call up on a slow network: at most 300 ms of the user's audio waits, the oldest dropped first. Hanging up lets go of the microphone at once, and a close the network cannot carry is forced within about a second.
  • iOS (the iOS SDK's engine, under CallKit): everything before the conversation opens — loading the agent, connecting — has one 20-second deadline: “The call could not connect within 20 seconds.” (the connection itself gives up after 15 seconds of trying to open: “The conversation did not open within 15 seconds.”). Once the conversation is open, the call's audio comes from CallKit; if it does not arrive, the SDK waits 3 seconds, starts the audio itself once, and waits 3 seconds more — then the call fails: “The call's audio could not start.”

A call that never connected reaches Graine.calls.outcomes as FAILED with these sentences in reason; the call screen says “Call failed”.

WebRTC. With the platform's WebRTC module in the app (WebRTC calls), calls in both directions carry their audio over WebRTC, as GraineCallsConfig.callTransport and the agent's In-app call audio setting allow. A call WebRTC cannot set up within about 12 seconds continues on the WebSocket inside the same call — “Connecting…” shows a moment longer — and Graine.calls.state says which one carried it (transport, transportFallbackReason, GraineCallInfo).

scope.launch {
    val call = Graine.calls.state.first { it.state == GraineCallState.ACTIVE }
    if (call.transportFallbackReason != null) println("Call ${call.callId} is on the WebSocket: ${call.transportFallbackReason}")
}

GraineCalls

Use it for native calls: configure them, place one, control it, and follow its state and outcomes.

class GraineCalls

Graine.calls — the app's one call engine, whichever agent a call is with. Its functions may be called from any thread.

What to expect — state always holds the latest value; outcomes and incoming are not replayed, so collect them from app start.

PropertyTypeMeaning
val state: StateFlow<GraineCallInfo>StateFlow<GraineCallInfo>Collect it to draw a call screen of your own, or to know when to show GraineCallScreen() (GraineCallInfo).
val phase: StateFlow<GraineCallPhase>StateFlow<GraineCallPhase>Collect it for where the call is in one word — the word every Graine SDK uses: IDLE, RINGING, CALLING, CONNECTING, ACTIVE, RECONNECTING, ENDED or MISSED (GraineCallPhase); state.value.phase, as it changes. 0.14.5.
val outcomes: SharedFlow<GraineCallOutcome>SharedFlow<GraineCallOutcome>Collect it from app start to send each call's outcome to your server (GraineCallOutcome).
val incoming: SharedFlow<GraineIncomingCall>SharedFlow<GraineIncomingCall>Collect it to know when an agent's call starts ringing on this device (GraineIncomingCall).
var showsAvatar: BooleanBoolean0.15.0. Set it to let the SDK's call screen draw the agent's face. Off by default (GraineCalls.showsAvatar).
val callPermissions: GraineCallPermissionsGraineCallPermissionsRead it for the call permissions the phone holds now (GraineCalls.callPermissions).
val callSetupProblems: List<GraineCallSetupProblem>List<GraineCallSetupProblem>Read it for what the app's setup still lacks for calls, each with its fix (GraineCalls.callSetupProblems).

Its functions: configure, startCall, end, setMuted, setSpeaker, speakerByDefault, answer, decline, callBack, dismissMissedCall, enableVoIPPushes, onNewToken, handlePush, requestCallPermissions, openCallSettings — each with its parameters, what it returns, its errors and an example.

GraineCalls.configure

Call it once at launch to set how calls ring and what they show.

fun configure(config: GraineCallsConfig)

On iOS, call it before enableVoIPPushes(). On Android it also creates the notification channels for rings, ongoing calls and missed calls.

ParameterTypeDefaultMeaning
configGraineCallsConfigrequiredThe calls' name, ring time, ringtone and icons (GraineCallsConfig).

Returns — nothing.

Errors — IllegalStateException before Graine.configure.

Graine.calls.configure(GraineCallsConfig(displayName = "Acme", ringTimeoutSeconds = 30))

GraineCallsConfig

Pass it to Graine.calls.configure to set how calls ring and what they show.

data class GraineCallsConfig(…)

What to expect — Set once at launch. Each field applies on the platforms its description names.

Graine.calls.configure(GraineCallsConfig(
    displayName = "Acme Assistant",
    androidCallActivity = "com.acme.app.CallActivity",   // Android: your own call screen; iOS ignores it
))
FieldTypeDefaultMeaning
displayNameString""The name a call rings with and shows when the ring names nobody; empty uses the agent's call name, else the app's own name.
ringTimeoutSecondsInt30How long a call from your own server rings before it is missed (on Android, held to 5–300 seconds). A call Graine rang rings for the agent's own ring time.
ringtoneString?nullThe ring: on Android a content URI, on iOS a sound file in the app's bundle; null uses the phone's ringtone.
smallIconInt0Android: a monochrome drawable resource for the status-bar icon; 0 uses the platform's call icon.
includeInRecentsBooleanfalseOn iOS, show these calls in the Phone app's Recents list.
callTransportGraineCallTransportGraineCallTransport.AUTOHow calls carry their audio, in both directions — calls the user places and calls Graine rings (GraineCallTransport): AUTO, WebRTC when the app includes the platform's WebRTC module, else the WebSocket; WEBSOCKET; or WEBRTC. The agent's In-app call audio setting can still move every call to the WebSocket.
androidCallActivityString?nullAndroid: your app's own call screen — the full class name of an Activity of your app ("com.acme.app.CallActivity"), declared in its manifest. The SDK opens it instead of its own for a ring, a call placed or answered, and a missed call; it draws from Graine.calls.state (your composable, or GraineCallScreen), calls the same functions as the SDK's screen, and forwards its permission answers to Graine.onRequestPermissionsResult. null, or a name that is not an Activity of your app (a warning in the log), uses the SDK's call screen. Ignored on iOS, where your screen draws over CallKit's. 0.14.0.

GraineCallTransport

Pass it in GraineCallsConfig.callTransport to choose how native calls carry their audio; read it back in GraineCallInfo.transport.

enum class GraineCallTransport(val wire: String) { AUTO("auto"), WEBSOCKET("websocket"), WEBRTC("webrtc") }

It applies to calls in both directions: one the user places (startCall, callBack) and one Graine rang (a booked call, Ring now). WebRTC needs the platform's WebRTC module in the app (WebRTC calls). Mapped to each platform SDK's own setting.

What to expect — The agent's In-app call audio setting wins over the app: Standard keeps every call on the WebSocket, whatever callTransport says, from each app's next start. A call that tried WebRTC and could not use it before any audio flowed continues on the WebSocket inside the same call, and GraineCallInfo.transport says WEBSOCKET, with transportFallbackReason saying why. AUTO is only something you choose; a call's transport is WEBRTC or WEBSOCKET.

PropertyTypeMeaning
wireStringThe platform SDKs' word: auto, websocket or webrtc — for logs.
CaseMeaning
AUTOThe default: WebRTC when the app includes the WebRTC module and the dashboard allows it; else the WebSocket.
WEBSOCKETAlways the WebSocket — as a call's transport, the call's audio runs on the WebSocket.
WEBRTCWebRTC wherever it can carry the call; the WebSocket only when the module is missing or WebRTC cannot set up this call — as a call's transport, the call's audio runs on WebRTC.

Its functions: ofCall — each with its parameters, what it returns, its errors and an example.

GraineCalls.startCall

Call it from a “Call us” button to let the user call the agent.

fun startCall(reason: String? = null, variables: Map<String, Any?> = emptyMap(), agent: String? = null): String?

The call screen opens and the call connects. reason becomes the prompt's call_reason; variables are this call's own prompt variables, over the SDK's (masked on the device). It answers on the spot.

ParameterTypeDefaultMeaning
reasonString?nullWhy the user is calling — the agent hears it as call_reason. Blank is none.
variablesMap<String, Any?>emptyMap()Prompt variables for this call only.
agentString?nullWhich configured agent to call, by name; null for the default agent.

Returns — String? — the call's ID, which every outcome carries; null when another call is live or, on Android, when no screen of the app is in front to start it from. Example value: "call_6f1c2a9e-7d1b-4c47-9a6e-2f0d8b1c5e44".

Errors — IllegalStateException when the agent is not configured. A call that cannot connect is a FAILED outcome, not an exception.

val callId = Graine.calls.startCall(reason = "billing_help") ?: return showBusy()

A call's own variables beside the ones your app set for the user: Send your user's details to the agent.

GraineCalls.prepareCall

Call it when a screen with your "Call" button appears — and each time it reappears — so that tapping the button only dials.

fun prepareCall(reason: String? = null, variables: Map<String, Any?> = emptyMap(), agent: String? = null)

Prepares the agent's next call over WebRTC: the connection is made ready and signed in, but nothing is dialled, no conversation starts and nothing is billed — and the microphone stays off until the customer taps Call. A startCall with the same reason, variables and agent within 4 minutes then dials at once; anything different and the call is set up at the tap, as before. Calling it again while a prepared call is fresh sends nothing, so it is safe on every appearance of the screen. The prepared call is let go when the app goes to the background, when the signed-in customer, their memory choice or the phone's time zone changes, after 4 minutes, or when a call rings. It does nothing without the WebRTC module, when calls use the WebSocket, before the agent's session has loaded, or while a call rings or is live. Optional: without it, startCall sets the call up at the tap, as always.

ParameterTypeDefaultMeaning
reasonString?nullWhy the customer is calling — pass what you will pass to startCall.
variablesMap<String, Any?>emptyMap()Prompt variables — the same ones you will pass to startCall.
agentString?nullThe agent's name in your app; the default agent when it is left out.

Returns — nothing.

Errors — none thrown. On iOS it needs GraineInApp 0.11.0; with an older one it does nothing.

Graine.calls.prepareCall(reason = "support_help", agent = "support")   // when the screen appears
val callId = Graine.calls.startCall(reason = "support_help", agent = "support")   // on the tap

GraineAgent.startCall

Call it to let the user call one of your other agents.

fun startCall(reason: String? = null, variables: Map<String, Any?> = emptyMap()): String?

A shortcut for Graine.calls.startCall(reason, variables, agent = name), with this agent's name filled in.

ParameterTypeDefaultMeaning
reasonString?nullWhy the user is calling — the agent's call_reason.
variablesMap<String, Any?>emptyMap()Prompt variables for this call only.

Returns — String? — the call's ID, or null when another call is live.

Errors — IllegalStateException when this agent is not configured.

Graine.agent("support")?.startCall(reason = "billing_help")

GraineAgent.prepareCall

Call it when a screen with your "Call" button appears — and each time it reappears — so that tapping the button only dials.

fun prepareCall(reason: String? = null, variables: Map<String, Any?> = emptyMap())

This agent's next call, ready before the tap — the same as Graine.calls.prepareCall(reason, variables, agent = name): see GraineCalls.prepareCall. The microphone stays off until the customer taps Call.

Returns — nothing.

Errors — none thrown.

Graine.agent("support").prepareCall(reason = "support_help")

GraineCalls.end

Call it from your own hang-up control.

fun end()

Hangs up — or, while the call rings, declines it.

Parameters — none.

Returns — nothing.

Errors — none.

Graine.calls.end()

GraineCalls.setMuted

Call it from your own mute control.

fun setMuted(muted: Boolean)

Stops sending the user's voice without ending the call.

ParameterTypeDefaultMeaning
mutedBooleanrequiredtrue to stop sending the user's voice, false to send it again.

Returns — nothing.

Errors — none.

Graine.calls.setMuted(true)

GraineCalls.setSpeaker

Call it from your own loudspeaker control.

fun setSpeaker(on: Boolean)

Turning it off sends the audio back to a connected headset, or to the earpiece when there is none. The user's choice for this call, over speakerByDefault.

ParameterTypeDefaultMeaning
onBooleanrequiredtrue for the loudspeaker.

Returns — nothing.

Errors — none.

Graine.calls.setSpeaker(true)

GraineCalls.speakerByDefault

Set it to choose where calls start: on the loudspeaker, or the earpiece. 0.14.0.

var speakerByDefault: Boolean

true, the default: every call — placed by the user or rung by Graine — starts on the loudspeaker, where an agent's voice is heard with the phone in the hand, unless a headset is connected (Bluetooth or plugged in), which takes the call; one connected during the call takes it too. setSpeaker still moves it, and GraineCallInfo.speakerOn says where it went. false: calls start on the earpiece (or a headset), as before 0.14.0. Read when a call's audio starts, so set it before the call; it may be set before Graine.configure. On iOS a car or AirPlay route also keeps the call, and it needs GraineInApp of this version (an older one keeps its own route).

Returns — Boolean, when read.

Errors — none.

Graine.calls.speakerByDefault = false   // the earpiece first, as before 0.14.0

GraineCallInfo

Read it to draw a call screen: the call's state, who is calling, the controls and what has been said.

data class GraineCallInfo(…)

Graine.calls.state.

What to expect — Every field has a value at every moment; with no call, state is IDLE and the rest are empty — except missedCall, kept until it is called back or dismissed.

FieldTypeDefaultMeaning
stateGraineCallStateGraineCallState.IDLERead it to know which moment to draw: ringing, connecting, on the call (GraineCallState).
callIdString?nullThe call's ID — the one its outcomes carry; null with no call.
callerNameString?nullThe name to show: the ring's caller name, else the agent's call name or the app's display name.
incomingBooleanfalsetrue when the agent rang (a push); false for a call the user placed.
hostedBooleanfalsetrue when Graine rang it — a call booked by the agent, the user or your team; the ring says “Scheduled call”.
mutedBooleanfalseShow the mute control as on.
speakerOnBooleanfalseShow the loudspeaker control as on: the call is heard on the loudspeaker — the route as the phone has it, by default from 0.14.0 (GraineCalls.speakerByDefault) — otherwise a headset, if one is connected, or the earpiece.
agentSpeakingBooleanfalseAnimate the agent's avatar while true: its voice is being heard.
captionGraineCaption?nullThe last line said, while a call is live (GraineCaption).
missedCallGraineMissedCall?nullThe last ring nobody answered, until it is called back or dismissed (GraineMissedCall) — show “Missed call” with Call back.
agentString?nullWhich agent the call is with, by the name it was configured under ("default" for the default agent); null with no call.
transportGraineCallTransport?nullWhat carries the call's audio, in either direction: WEBRTC or WEBSOCKET (GraineCallTransport). null with no call, before a transport is decided, and from a platform SDK older than WebRTC. Read it once the call is ACTIVE.
transportFallbackReasonString?nullWhy a call that tried WebRTC runs on the WebSocket — one of the values below; null for a call that did not fall back. Read it once the call is ACTIVE.
reconnectingBooleanfalsetrue while a connected call recovers a dropped connection — its audio is being restored; show “Reconnecting…”. false again once the audio is back, and always false from a platform SDK that predates it. New in 0.12.0.
reasonString?nullWhy the call is happening — the ring's reason, or startCall's — when it has one; null with no call. On iOS it needs GraineInApp of this version. 0.14.0.
endReasonString?nullWhile state is ENDED: local (this app hung up), remote (the agent did) or failed (the connection was lost); null otherwise. 0.14.0.
endCauseString?nullWhile state is ENDED: who or what ended it, in GraineCallOutcome.endCause's words; null otherwise. 0.14.0.
agentLevelFloat0fThe agent's voice level, 0–1, as it is heard — what the call screen's visualiser follows: about five times a second over WebRTC, ten over the WebSocket while the agent's audio plays; 0f with no call. On iOS it needs GraineInApp of this version. 0.14.0.
startedAtInstant?nullWhen the call connected: count the call screen's duration from it. null before (and with no call). On iOS it needs GraineInApp of this version. 0.14.0.
connectionGraineCallConnection?nullHow the call is connecting — the same facts as its Connection in Execution Logs, growing as the call goes (GraineCallConnection); null with no call and before its first fact. Its outcome carries the last of it. On iOS it needs GraineInApp of this version. 0.14.0.
captionsList<GraineCaption>emptyList()The call's live transcript, as the call screen draws it: what has been said, oldest first — the agent's lines as they are spoken, the user's as they are heard (GraineCaption), a live line replaced as its words arrive (caption is the last of them); the last 12. Kept through ENDED, empty with no call. 0.14.1.
PropertyTypeMeaning
val showsCallScreen: BooleanBooleanRead it to decide whether to show a call screen: there is a call, or a missed ring to call back.
val phase: GraineCallPhaseGraineCallPhaseRead it for which moment to draw, in the word every Graine SDK uses (GraineCallPhase) — from state, incoming, reconnecting and missedCall. 0.14.5.

Why a call is on the WebSocket — the values of transportFallbackReason. Log them; the person sees nothing different, only “Connecting…” a moment longer.

ValueMeans
mint_failedThe call's WebRTC session could not be set up: refused, rate-limited or unreachable.
register_failedGraine's media service did not accept the connection, or never answered it.
no_responseThe call got no reply at all.
no_answerReplies came; the answer did not.
ice_timeoutAnswered, but the audio path never connected — usually a network that blocks WebRTC.
errorAnything else before the audio flowed.
dashboardAndroid only, for a call that would have used WebRTC: the agent's In-app call audio is Standard.
unavailableAndroid only, when the app chose WEBRTC: this build has no WebRTC module, or the device cannot run it.

GraineCallState

Read it to know where the one native call is.

enum class GraineCallState { IDLE, RINGING, CONNECTING, ACTIVE, ENDED }

What to expect — IDLE → RINGING (the agent rings) or CONNECTING (the user called) → ACTIVE → ENDED, then IDLE again once reported.

CaseMeaning
IDLENo call.
RINGINGThe agent is calling the user; show Answer and Decline.
CONNECTINGThe call was answered, or placed by the user, and is connecting.
ACTIVEThe agent and the user can hear each other.
ENDEDOver — reported once, then IDLE.

GraineCallPhase

Read it to know which moment of a native call to draw — the one word every Graine SDK uses for it. 0.14.5.

enum class GraineCallPhase(val wire: String)

Graine.calls.phase, and GraineCallInfo.phase.

What to expect — the user's call: CALLING → ACTIVE → ENDED → IDLE; an agent's call: RINGING → CONNECTING (answered) → ACTIVE → ENDED → IDLE, or MISSED when nobody answered — until the user calls back (callBack()), dismisses it (dismissMissedCall()), or another call rings or is placed. RECONNECTING and back to ACTIVE while a connected call recovers its connection. Use an else branch in a when: more may come.

PropertyTypeMeaning
val wire: StringStringThe word every Graine SDK uses: idle, ringing, calling, connecting, active, reconnecting, ended, missed.

GraineCallPhase.of(state, incoming, reconnecting, missed) maps the call's five states the way every SDK does: IDLE is MISSED while a missed ring is kept; CONNECTING is CALLING for the user's own call; ACTIVE is RECONNECTING while the connection is recovered.

CaseMeaning
IDLENo call.
RINGINGAn agent's call is ringing on this device; show Answer and Decline.
CALLINGThe user's call, before the agent answers. Show “Calling…”.
CONNECTINGAn answered ring, connecting. Show “Connecting…”.
ACTIVEOn the call: the agent and the user can hear each other.
RECONNECTINGOn the call, its connection being recovered. Show “Reconnecting…”.
ENDEDThe call is over — its last moment on screen.
MISSEDA ring nobody answered; show “Missed call” with Call back (missedCall says who rang).
Graine.calls.phase.collect { phase ->
    statusLine.text = when (phase) {
        GraineCallPhase.CALLING -> "Calling…"
        GraineCallPhase.RECONNECTING -> "Reconnecting…"
        GraineCallPhase.MISSED -> "Missed call"
        else -> ""
    }
}

GraineCallOutcome

Read it to send what became of a call to your server.

data class GraineCallOutcome(…)

From Graine.calls.outcomes, as it happens.

What to expect — One call reports RINGING (an agent's call), then ANSWERED followed by ENDED or FAILED; or DECLINED, MISSED or FAILED alone. hosted means Graine rang it, and the SDK has already told Graine. Do not rely on its order relative to state.

FieldTypeDefaultMeaning
callIdStringrequiredUse it to match the outcome to the call: the push's call_id, Graine's for a ring it sent, or the ID startCall returned.
outcomeKindrequiredWhat became of it (GraineCallOutcome.Kind).
reasonString?nullWhy: for MISSED, no_answer or busy (another call was live); for ENDED, local (this app hung up), remote (the agent did) or failed (the connection was lost); for FAILED, the sentence saying why (at most 200 characters).
durationSecondsInt?nullHow long a call that connected lasted, in whole seconds — with ENDED.
hostedBooleanfalsetrue when Graine rang it — a call booked by the agent, the user or your team.
agentString?nullWhich agent the call was with, by the name it was configured under; null when the platform does not know (a ring refused as busy).
connectionGraineCallConnection?nullHow the call connected, as it stood when it ended — with ENDED and FAILED (GraineCallConnection); null otherwise, for a call that never got as far as connecting, and from a platform SDK that predates it. Send it to your own analytics if you like: timings and network figures only. 0.14.0.
endCauseString?nullWho or what ended the call — with ENDED and FAILED: local_end (your app or the user hung up — or answered a cellular call), remote_bye (the agent's side hung up), media_drop (the audio path dropped and did not recover), audio_watch (the SDK's own watch ended it — on Android nothing arrived for too long, on iOS the call's audio never started), failed (anything else), and on iOS provider_reset (the system reset CallKit). null otherwise, and from a platform SDK that predates it. Finer than reason; send it to your analytics with the call's ID. 0.14.0.

GraineCallOutcome.Kind

Read it to branch on what became of a call.

enum class Kind(val wire: String)

PropertyTypeMeaning
wireStringOne word for your server: ringing, answered, declined, missed, failed or ended.
CaseMeaning
RINGINGAn agent's call is ringing on this device.
ANSWEREDThe user picked up; ENDED or FAILED follows.
DECLINEDThe user declined it.
MISSEDThe ring went unanswered (no_answer), or the user was already on another call (busy).
FAILEDIt never connected; reason says why.
ENDEDA call that connected is over; reason says who ended it and durationSeconds how long it lasted.

GraineCallConnection

Read it to show how a call connected — in a call screen of your own, or your analytics. 0.14.0.

data class GraineCallConnection(…)

The same facts as the call's Connection in Execution Logs: live while the call goes (Graine.calls.state.value.connection) and final on its outcome (GraineCallOutcome.connection). Timings and network figures only — nothing personal.

What to expect — Each fact is null until it is known: the transport and the tap's wait once the call connects, the agent's first words when they are heard, the audio about once a second on WebRTC while the call is live and at its end. A call carried over the WebSocket has no audio. The tap's wait, in order: setupMs, loginMs, answerMs, firstWordsMs; tapToVoiceMs is all of it, as the user felt it.

FieldTypeDefaultMeaning
transportGraineCallTransport?nullWhat carried the call: WEBRTC or WEBSOCKET (GraineCallTransport).
preparedBoolean?nulltrue when the call was ready before the tap (prepareCall, or a ring's, ready by its answer); false when it was set up after the tap.
preparedAgeSecondsLong?nullHow long before the tap a prepared call was ready, in seconds.
credentialString?nullWhere the call's credential came from: direct (issued directly, on WebRTC) or web (issued through the web).
setupMsLong?nullFrom the tap to the call being placed — the credential, the microphone and the network path — without the login, on a call set up after the tap.
loginMsLong?nullThe device signing in to the call server, inside the setup; null for a prepared call, which logged in before the tap.
answerMsLong?nullFrom the call being placed to it being answered.
firstWordsMsLong?nullFrom the answer to the agent's voice reaching the phone.
tapToVoiceMsLong?nullFrom the tap to the agent's voice: the wait the user felt.
audioAudio?nullThe audio as the phone measured it (GraineCallConnection.Audio). WebRTC only.
recoveriesInt0How many times the connection recovered on its own.
val c = Graine.calls.state.value.connection
val waited = c?.tapToVoiceMs?.let { "Agent spoke ${it / 1000.0} s after the tap" }

GraineCallConnection.Audio

Read it for how a call's audio held up. 0.14.0.

data class Audio(val lossPct: Double? = null, val jitterAvgMs: Long? = null, val jitterPeakMs: Long? = null, val rttMs: Long? = null, val quality: String? = null)

FieldTypeDefaultMeaning
lossPctDouble?nullPackets lost of all the far side sent, in percent, to two decimals.
jitterAvgMsLong?nullThe jitter, on average, in milliseconds.
jitterPeakMsLong?nullThe worst jitter measured.
rttMsLong?nullThe round trip, on average.
qualityString?nullIn a word, as Execution Logs says it: poor at 8% loss, 80 ms jitter or a 400 ms round trip; fair at 2%, 30 ms or 150 ms; else good. null when nothing was measured.

GraineCallScreen

Use it to show the SDK's call screen in a Compose Multiplatform UI while there is a call.

@Composable
expect fun GraineCallScreen(modifier: Modifier = Modifier)

In ai.graine:inapp-kmp-compose. The ring (Answer, Decline — “Scheduled call” for a call Graine rang), connecting, the call with its controls, and a missed ring with Call back, in the agent's design. Show it whenever Graine.calls.state.value.showsCallScreen is true. On iOS it is drawn in place, and VoiceOver reaches into it. On Android the SDK's call screen is a full-screen activity that also covers the lock screen and opens by itself when a call rings or is placed; composing this brings it to the front.

ParameterTypeDefaultMeaning
modifierModifierModifierWhere the call screen is drawn (iOS).

Returns — nothing (a composable).

Errors — none.

val call by Graine.calls.state.collectAsState()
if (call.showsCallScreen) GraineCallScreen(Modifier.fillMaxSize())

GraineViews.callScreen

Call it on iOS to get the call screen as a view controller, for while the app is open.

fun callScreen(): UIViewController

The ring, the call, and a missed ring with Call back — the app's, whichever agent calls.

Parameters — none.

Returns — UIViewController.

Errors — IllegalStateException before Graine.configure.

import platform.UIKit.UIViewController
 
fun showCallScreen(from: UIViewController) {
    from.presentViewController(GraineViews.callScreen(), animated = true, completion = null)
}

Calls Graine rings

Graine rings your users itself — a call the agent booked in a conversation, one the user booked, or one your team booked — once your push credentials are uploaded (Workspace settings → In-app calling). On iOS, call enableVoIPPushes() at every launch; on Android, add Firebase Cloud Messaging to the app and the SDK registers for pushes itself (an app with a messaging service of its own forwards its token and data messages to onNewToken and handlePush). The SDK registers the device, rings each call on the phone's own call screen (“Scheduled call”), and reports what became of it. Your own server can ring the same way, with a push of type agent_call.

A call the person answers carries its audio exactly as one they place: over WebRTC when the app includes the platform's WebRTC module and GraineCallsConfig.callTransport and the agent's In-app call audio setting allow it (WebRTC calls) — prepared while the ring shows, so answering connects as fast as before — and Graine.calls.state reports transport and transportFallbackReason for it too.

The push your server sends (data only, nothing personal): type: "agent_call", call_id (required — every outcome carries it back), reason (the prompt's call_reason), caller_name (what the ring shows), variables (a JSON object as a string: more prompt variables), and agent_id (which of the app's agents the call is with).

GraineCalls.enableVoIPPushes

Call it at every launch on iOS, so the agent's calls can ring a closed app.

fun enableVoIPPushes()

iOS wakes a closed app for a VoIP push and hands it over once this has run; the SDK registers the token with Graine when Graine rings this app. Call configure first. Android: does nothing — with Firebase in the app the SDK registers for pushes itself (see onNewToken and handlePush for an app with its own messaging service).

Parameters — none.

Returns — nothing.

Errors — IllegalStateException before Graine.configure.

Graine.calls.enableVoIPPushes()

GraineCalls.onNewToken

Call it on Android from a FirebaseMessagingService of your own, in onNewToken. Without one, the SDK's own messaging service receives each new token, and the SDK reads the current one when it starts.

fun onNewToken(token: String)

The token is kept and registered with Graine when Graine rings this app. It works before Graine.configure, as a messaging service may start first. iOS: does nothing — the VoIP token comes through enableVoIPPushes().

ParameterTypeDefaultMeaning
tokenStringrequiredThe new Firebase Cloud Messaging token.

Returns — nothing.

Errors — none.

override fun onNewToken(token: String) = Graine.calls.onNewToken(token)

GraineCalls.handlePush

Call it on Android first thing in the onMessageReceived of a FirebaseMessagingService of your own. Without one, the SDK's own messaging service calls it for every message.

fun handlePush(data: Map<String, String>): Boolean

When the message is a call — Graine's own ring, or one your server sent — the SDK rings it and the answer is true; your own messages answer false. iOS: always false — a VoIP push reaches the SDK by itself.

ParameterTypeDefaultMeaning
dataMap<String, String>requiredThe message's data, exactly as the messaging service received it.

Returns — Boolean — true when it was a call and you should do nothing more with it. Example value: true.

Errors — none.

override fun onMessageReceived(message: RemoteMessage) {
    if (Graine.calls.handlePush(message.data)) return
    // …your own messages
}

GraineCalls.answer

Call it from a call screen of your own to pick up the ringing call.

fun answer()

The SDK's own call screen does this itself.

Parameters — none.

Returns — nothing.

Errors — none.

Graine.calls.answer()

GraineCalls.decline

Call it from a call screen of your own to decline the ringing call.

fun decline()

Reported as DECLINED. For a call Graine rang, nothing rings that user again for 6 hours.

Parameters — none.

Returns — nothing.

Errors — none.

Graine.calls.decline()

GraineCalls.callBack

Call it from a missed-call screen's “Call back”.

fun callBack(): String?

Returns the last missed call: the user calls the agent back, with the missed call's reason and its agent. On Android it starts from the screen in front.

Parameters — none.

Returns — String? — the new call's ID, or null when it could not start (another call is live, or no screen is in front). Example value: "call_8a20d3c1-…".

Errors — none.

Graine.calls.callBack()

GraineCalls.dismissMissedCall

Call it when the user has seen the missed call, so a call screen can go.

fun dismissMissedCall()

Clears GraineCallInfo.missedCall.

Parameters — none.

Returns — nothing.

Errors — none.

Graine.calls.dismissMissedCall()

GraineIncomingCall

Read it to know an agent's call started ringing on this device — for your own UI or analytics.

data class GraineIncomingCall(…)

From Graine.calls.incoming. The SDK shows the ring itself.

What to expect — It carries only what the ring shows: nothing personal.

FieldTypeDefaultMeaning
callIdStringrequiredThe call's ID, which its outcomes carry.
callerNameString?requiredRead it for the name on the ring: the push's caller name when it has one, otherwise the agent's call name or the app's display name.
reasonString?requiredWhy the agent is calling, when the push said; a call Graine rang keeps its reason with Graine.
hostedBooleanrequiredtrue when Graine rang it.
agentString?nullWhich configured agent is ringing; null when the platform does not say.

GraineMissedCall

Read it to show a missed call with “Call back”.

data class GraineMissedCall(…)

GraineCallInfo.missedCall: the last ring nobody answered, kept until callBack() or dismissMissedCall(). A ring refused because another call was live is not kept.

FieldTypeDefaultMeaning
callIdStringrequiredThe missed call's ID.
callerNameString?requiredWho called, as the ring showed it.
reasonString?requiredWhy, when the ring said.
hostedBooleanrequiredtrue when Graine rang it.
atInstantrequiredWhen it was missed; show it in the device's time zone.

The agent's face (Avatar)

0.15.0. When the agent has Avatar turned on in the dashboard, a call can show the agent's live talking face, speaking with the agent's own voice. Place GraineAvatarFace() (in ai.graine:inapp-kmp-compose) where the face goes and collect Graine.avatar.state. The voice moves to the face at a pause, never mid-sentence, and comes back to the call at once if the face's connection drops for 2 seconds, it cannot be shown, or the view leaves the screen: the user never hears the agent twice, and never hears nothing. With no avatar view on screen nothing is connected, and the call is voice only, exactly as before.

  • Assistant-bar calls draw the face with the SDK alone, inside GraineAvatarFace(). 0.15.4: whatever you compose above it — captions, buttons, GraineAgentBar — is drawn over the face. GraineAvatarStage draws the call over the face for you.
  • Native calls draw it with the platform's WebRTC module — ai.graine:inapp-android-rtc on Android, GraineInAppRTC on iOS — on a call carried over WebRTC; otherwise the state's reason is unsupported and the call is voice only. The SDK's own call screen draws the face when you set GraineCalls.showsAvatar.
  • On iOS, link GraineInApp and GraineInAppRTC 0.15.0: an older iOS SDK simply has no face (the state stays OFF and GraineAvatarFace() draws nothing).

GraineAvatar

Read it to know when to show the agent's face: Graine.avatar.

class GraineAvatar — the agent's face on the call in progress, for the whole app: one call at a time, so one face at a time, whichever call has it. 0.15.0.

What to expect — state is OFF with no call, and on a call whose agent has no face. When a face is ready it becomes AVAILABLE: show GraineAvatarFace(). Once it is on screen and the face plays, it is LIVE and the face carries the agent's voice. It goes back to OFF, with a reason, when the face stops — the call goes on with its own voice.

PropertyTypeMeaning
val state: StateFlow<GraineAvatarState>StateFlow<GraineAvatarState>Collect it to show the face while there is one: off, available (show your avatar view) or live (it carries the voice). See GraineAvatarState.
@Composable
fun AgentPicture() {
    val face by Graine.avatar.state.collectAsState()
    Box(Modifier.size(220.dp, 275.dp).clip(RoundedCornerShape(24.dp))) {
        Image(painterResource(Res.drawable.agent), null, contentScale = ContentScale.Crop)   // drawn when there is no face
        if (face.showsFace) GraineAvatarFace(Modifier.matchParentSize())
    }
}

GraineAvatarState

Read it to draw the face's moment: off, available or live, and why it is off.

data class GraineAvatarState(val phase: Phase, val reason: String? = null) — Graine.avatar.state. 0.15.0.

What to expect — reason is set only when phase is OFF and a call's agent has a face that is not shown: busy (every face is in use at a busy moment), error, off (the agent has none), ended, failed (it could not connect), stalled (its connection dropped), no_voice, blocked (the network does not allow it) or unsupported (this call cannot show one: a native call without the platform's WebRTC module, or on the WebSocket). Treat any other word as off: more may come.

FieldTypeDefaultMeaning
val phase: PhaseGraineAvatarState.Phase—Where the face is. See GraineAvatarState.Phase.
val reason: String?String?nullWhy there is no face, while phase is OFF; null otherwise.
val showsFace: BooleanBoolean—A face to draw: AVAILABLE or LIVE.
GraineAvatarState.OFFGraineAvatarState—No face, no reason: the state with no call.

GraineAvatarState.Phase

Read it to tell the three moments of the face apart.

CaseMeaning
OFFNo face on this call, or no call.
AVAILABLEA face is ready: show GraineAvatarFace().
LIVEThe face is on screen and carries the agent's voice.

GraineAvatarFace (Compose)

Place it where the agent's face goes.

@Composable
fun GraineAvatarFace(modifier: Modifier = Modifier)

In ai.graine:inapp-kmp-compose. A square or portrait area reads best; size and clip it with modifier. Transparent when there is no face, so put your own picture of the agent behind it. During a call whose agent has a face, the face plays here; taking it off screen gives the voice back to the call at once. On Android it hosts the Android SDK's GraineAvatarView; on iOS the iOS SDK's, inside Compose's accessibility tree — nothing is drawn there before Graine.configure. 0.15.0.

Parameters — modifier: its size, shape and place.

Returns — nothing (a composable).

Errors — none.

val face by Graine.avatar.state.collectAsState()
if (face.showsFace) GraineAvatarFace(Modifier.size(220.dp, 275.dp).clip(RoundedCornerShape(24.dp)))

GraineViews.avatarView

Call it on iOS to get the agent's face as a UIKit view.

fun avatarView(): UIView?

In iosMain, for an app that lays out UIKit itself (Compose apps use GraineAvatarFace()). The iOS SDK's GraineAvatarView: transparent when there is no face. null when the app links an iOS SDK from before the face. 0.15.0.

Parameters — none.

Returns — UIView?.

Errors — IllegalStateException before Graine.configure.

GraineViews.avatarView()?.let { face -> pictureView.addSubview(face) }

GraineCalls.showsAvatar

Set it to let the SDK's own call screen draw the agent's face.

var showsAvatar: Boolean

Off by default. On, and with the agent's face turned on in the dashboard, the call screen (GraineCallScreen(), and the platform's own) draws the face where the agent's picture goes, and the face carries the voice. Needs the platform's WebRTC module and a call on WebRTC; otherwise the call is voice only, as it is with this off. It may be set before Graine.configure. On a call screen of your own, place GraineAvatarFace() instead. 0.15.0.

Returns — Boolean, when read.

Errors — none.

Graine.calls.showsAvatar = true

The face stage

0.15.4. The agent's face edge to edge, with the call drawn over it — the name and role, the LIVE mark and the clock at the top; the line being said, the component the agent drew and the call's buttons at the bottom. GraineAvatarStage() draws all of it. Everything it draws is public state on Graine.stage, and the face draws inside GraineAvatarFace(), so a screen of your own over the face needs nothing else:

@Composable
fun AgentCall() {
    val stage by Graine.stage.state.collectAsState()
    var now by remember { mutableStateOf(0L) }
    LaunchedEffect(stage.live) { while (stage.live) { now = Clock.System.now().toEpochMilliseconds(); delay(1000) } }
    Box(Modifier.fillMaxSize()) {
        GraineAvatarFace(Modifier.fillMaxSize())                       // the face, under everything you draw
        Column(Modifier.fillMaxSize().padding(20.dp)) {
            Row {
                Text(stage.name)
                Spacer(Modifier.weight(1f))
                Text(if (stage.live) "LIVE " + stage.clock(now) else stage.status)
            }
            Spacer(Modifier.weight(1f))
            stage.caption?.let { Text(it.text) }
            Row {
                for (control in stage.controls) Button(
                    enabled = stage.canUse(control),
                    onClick = {
                        when (control) {
                            GraineStageControl.CALL -> Graine.stage.call()
                            GraineStageControl.ANSWER -> Graine.stage.answer()
                            GraineStageControl.END -> Graine.stage.end()
                            GraineStageControl.MUTE -> Graine.stage.setMuted(!stage.muted)
                            GraineStageControl.SPEAKER -> Graine.stage.setSpeaker(!stage.speaker)
                            GraineStageControl.CHAT -> Graine.stage.openChat()
                        }
                    },
                ) { Text(if (control == GraineStageControl.END) stage.endLabel else control.wire) }
            }
        }
    }
}

GraineAvatarStage (Compose)

Show it where the agent's face and the call go — a whole screen reads best.

@Composable
fun GraineAvatarStage(
    modifier: Modifier = Modifier,
    name: String? = null,
    role: String? = null,
    calls: GraineStageCalls = GraineStageCalls.VOICE,
    onChat: (() -> Unit)? = null,
    onClose: (() -> Unit)? = null,
)

In ai.graine:inapp-kmp-compose. The agent's face edge to edge, the brand's picture of the agent in its place until the face's first frame and on a call without one, and over it the header, the line being said, the agent's component and the call's buttons — Call, then Mute, Chat, End (Cancel while the call is being placed, Decline while one rings) and Speaker. White on dark scrims in every design, the brand's typeface and its colours for Call and End. It places the default agent's voice bar call (calls = GraineStageCalls.NATIVE places native calls), follows a native call that rings or is placed, and mounts the voice engine itself. It never ends a call by going away. On Android it hosts the Android SDK's GraineAvatarStageView; on iOS the iOS SDK's GraineAvatarStage — nothing is drawn there before Graine.configure. 0.15.4.

ParameterTypeDefaultMeaning
modifierModifierModifierIts size and place.
nameString?nullThe header's name. Null: the dashboard chat header's title, else the voice bar's name.
roleString?nullThe line under the name ("AI care assistant"). Null: the chat header's subtitle, else none.
callsGraineStageCallsVOICEWhat the Call button places.
onChat(() -> Unit)?nullYour chat. The Chat button is drawn only with one; a tap calls it.
onClose(() -> Unit)?nullA close control leading the header, for a stage shown full screen. It never ends a call: take the stage away there (Graine.stage.end() first if leaving should hang up).

Returns — nothing (a composable).

Errors — none.

composable("agent") { GraineAvatarStage(Modifier.fillMaxSize(), role = "AI care assistant", onChat = { nav.navigate("chat") }) }

GraineViews.avatarStage

Call it on iOS to get the face stage as a UIKit view controller.

fun avatarStage(name: String? = null, role: String? = null, calls: GraineStageCalls = GraineStageCalls.VOICE, onChat: (() -> Unit)? = null, onClose: (() -> Unit)? = null): UIViewController?

In iosMain, for an app that lays out UIKit itself (Compose apps use GraineAvatarStage()). null when the app links an iOS SDK from before 0.15.4. 0.15.4.

Returns — UIViewController?.

Errors — IllegalStateException before Graine.configure.

GraineViews.avatarStage(role = "AI care assistant")?.let { presentViewController(it, animated = true, completion = null) }

GraineStage

Use it to draw the call over the agent's face yourself: Graine.stage.

class GraineStage — the default agent's face stage, as state. state is decided by the platform SDK from what it already publishes: a native call while it rings, is being placed or is on, else the voice bar's call, with the face, the component and the header's words. The same rule decides it on every Graine SDK. Its settings may be set before Graine.configure. 0.15.4.

MemberTypeMeaning
val state: StateFlow<GraineStageState>StateFlow<GraineStageState>What the stage shows now. See GraineStageState.
var name: String?String?The header's name; null uses the dashboard's.
var role: String?String?The header's second line; null uses the dashboard chat header's subtitle, else none.
var calls: GraineStageCallsGraineStageCallsWhat call() places; VOICE by default.
var onChat: (() -> Unit)?(() -> Unit)?Your chat: with one, controls includes CHAT and openChat() calls it.
fun call()—Places the call the stage is for: the voice bar's (mounting the engine first if nothing has) or a native call.
fun answer()—Takes the native call that is ringing.
fun end()—Hangs up, cancels a call being placed, or declines a ring — whichever the stage shows.
fun setMuted(muted: Boolean)—The microphone of the call the stage shows.
fun setSpeaker(on: Boolean)—The loudspeaker (true) or the earpiece of the call the stage shows — with no call, of the next one.
fun openChat()—Calls onChat.
GraineStage.clock(elapsedMs: Long): StringStringThe clock's words: m:ss under an hour, h:mm:ss after; below zero reads as zero.

GraineStageState

Read it to draw each piece of the stage.

data class GraineStageState — Graine.stage.state. 0.15.4.

What to expect — call is NATIVE while a native call rings, is being placed or is on; else VOICE while the voice bar's call is being placed or is on, or has just ended or failed; else NATIVE for a native call that just ended; else NONE. status is empty while live (draw the LIVE mark and the clock) and while idle. caption is never an empty line.

FieldTypeDefaultMeaning
val call: GraineStageCallGraineStageCallNONEWhich call the stage shows.
val phase: GraineStagePhaseGraineStagePhaseIDLEWhere that call is.
val status: StringString""The words beside the name: "Incoming call", "Connecting…", "Reconnecting…", "Call ended", "Couldn’t connect"; empty while live and idle.
val live: BooleanBooleanfalseDraw the LIVE mark and the clock.
val startedAt: Long?Long?nullWhen the call went live (ms since 1970), while it is live or coming back.
val caption: GraineStageCaption?GraineStageCaption?nullThe line being said, while the call is on.
val muted: BooleanBooleanfalseThe call's microphone is off.
val speaker: BooleanBooleantrueThe call's audio is on the loudspeaker.
val controls: List<GraineStageControl>List<GraineStageControl>[CALL]The buttons, left to right.
val enabled: List<GraineStageControl>List<GraineStageControl>[CALL]The buttons that can act now — the microphone waits until the call is on.
val endLabel: StringString"End"What End is called: "Cancel" while a call is being placed, "Decline" while one rings.
val face: GraineAvatarStateGraineAvatarStateOFFThe agent's face (Graine.avatar.state).
val name: StringString"Assistant"The header's name.
val role: String?String?nullThe header's second line.
val componentId: String?String?nullThe id of the component on show.
val componentPending: BooleanBooleanfalseA component is on its way.
fun shows(control: GraineStageControl): BooleanBoolean—Whether control is drawn.
fun canUse(control: GraineStageControl): BooleanBoolean—Whether control can act now.
fun clock(nowMs: Long): StringString—The clock's words at nowMs; "" when the call is not live or coming back.

GraineStageCall

Read it to know which call the stage shows. wire is the word every Graine SDK uses.

CaseMeaning
NONENo call.
VOICEThe voice bar's call.
NATIVEA native call (Graine.calls).
val wire: StringThe case's word: none, voice, native.

GraineStagePhase

Read it to draw the moment of the call. wire is the word every Graine SDK uses.

CaseMeaning
IDLENo call: Call is the button.
RINGINGA native call is ringing: Decline and Answer.
CONNECTINGA call is being placed or connecting: End reads Cancel, the microphone waits.
LIVEThe call is on: the LIVE mark and the clock.
RECONNECTINGThe call is coming back from a drop: the clock and the line stay.
ENDEDThe call is over: Call again.
FAILEDThe voice bar's call could not start or go on: Call tries again.
val wire: StringThe case's word.

GraineStageControl

Read it to draw the stage's buttons. wire is the word every Graine SDK uses.

CaseMeaning
CALLPlace a call: Graine.stage.call().
ANSWERTake the ringing call: Graine.stage.answer().
MUTEThe microphone: Graine.stage.setMuted(…).
CHATYour chat: Graine.stage.openChat().
ENDHang up, cancel or decline: Graine.stage.end().
SPEAKERThe loudspeaker: Graine.stage.setSpeaker(…).
val wire: StringThe case's word.

GraineStageCalls

Set it to choose what the stage's Call button places.

CaseMeaning
VOICEThe voice bar's call — the default.
NATIVEA native call (Graine.calls).
val wire: StringThe case's word: voice, native.

GraineStageCaption

Read it to draw the line being said.

data class GraineStageCaption(val who: GraineRole, val text: String, val final: Boolean) — GraineStageState.caption. 0.15.4.

FieldTypeMeaning
val who: GraineRoleGraineRoleWho is saying it: AGENT or USER.
val text: StringStringThe words.
val final: BooleanBooleanSettled; draw a line still arriving a little faint.

Graine.stage

Read it for the face stage's state and buttons.

val stage: GraineStage

The default agent's face stage. 0.15.4.

Returns — the GraineStage.

Errors — none.

val stage by Graine.stage.state.collectAsState()

Permissions and the setup check

What a call needs from the phone, and from your app's setup, in one place — read from the platform SDKs, the same on both. The SDK never asks on its own at launch: it asks for the microphone when a call starts without it, and requestCallPermissions() asks earlier, when your app chooses (on Android from a transparent screen of the SDK's own, over the app's screen in front). callSetupProblems says what your setup still lacks; the platform SDK logs each problem once from configure on. A problem is never an exception: calls still work where they can. On iOS these need GraineInApp of this version.

GraineCalls.callPermissions

Read it to see which call permissions the phone holds now.

val callPermissions: GraineCallPermissions

The microphone, and on Android the ring's notifications (13+ asks) and the full-screen ring (14+, Settings only); on iOS those two are NOT_NEEDED — CallKit rings and draws its own screen.

Returns — a GraineCallPermissions. Read it again when the app returns to the foreground: the user may have changed Settings.

Errors — IllegalStateException before Graine.configure.

if (!Graine.calls.callPermissions.allGranted) showFinishSetupCard()

GraineCalls.requestCallPermissions

Call it at a moment you choose — onboarding, a "Call me" screen — to ask for what a call needs.

suspend fun requestCallPermissions(): GraineCallPermissions

Asks for the call permissions the system's dialog can still ask for — the microphone, and notifications on Android 13+ — and returns them as they stand after; suspends until the user answers (at once when there is nothing to ask). The full-screen ring has no dialog: openCallSettings(GraineCallPermission.FULL_SCREEN) opens its page.

Returns — a GraineCallPermissions.

Errors — IllegalStateException before Graine.configure.

scope.launch {
    val p = Graine.calls.requestCallPermissions()
    if (p.fullScreen == GraineCallPermissionStatus.BLOCKED) Graine.calls.openCallSettings(GraineCallPermission.FULL_SCREEN)
}

GraineCalls.openCallSettings

Call it to send the user to the Settings page that changes a call permission.

fun openCallSettings(item: GraineCallPermission): Boolean

Opens, on Android, the full-screen ring's own page (14+) or the app's notification settings, from the screen in front; otherwise the app's page, where the microphone is.

ParameterTypeDefaultMeaning
itemGraineCallPermissionrequiredThe permission the user should change.

Returns — Boolean: true when a page opened.

Errors — IllegalStateException before Graine.configure.

Graine.calls.openCallSettings(GraineCallPermission.MICROPHONE)

GraineCalls.callSetupProblems

Read it to learn what your app's setup still lacks for calls, in plain words.

val callSetupProblems: List<GraineCallSetupProblem>

What the app's setup still lacks for calls, read now — each a stable code and a sentence with the exact fix; empty when nothing is missing. The codes: iOS microphone_usage_missing, background_audio_missing, background_voip_missing (Info.plist), push_entitlement_missing, voip_pushes_not_enabled (no enableVoIPPushes() 15 seconds after configure), no_voip_token, ios_sdk_older (Xcode links an older GraineInApp than this library is built for); Android manifest_entry_missing, no_push_token (no push token 15 seconds after configure: Firebase missing or not set up in the app, or no onNewToken from an app with its own messaging service), notifications_not_allowed, full_screen_not_allowed; both microphone_blocked and hosted_ringing_off (no push credentials uploaded for this platform: Graine can't ring this phone).

Returns — List<GraineCallSetupProblem>.

Errors — IllegalStateException before Graine.configure.

Graine.calls.callSetupProblems.forEach { println("${it.code}: ${it.message}") }

GraineCallPermission

Use it to name a call permission.

enum class GraineCallPermission(val wire: String) { MICROPHONE("microphone"), NOTIFICATIONS("notifications"), FULL_SCREEN("fullScreen") }

What to expect — Three permissions, the same on every SDK. On iOS only the microphone is ever asked for.

PropertyTypeMeaning
wireStringThe word every Graine SDK uses for it.
CaseMeaning
MICROPHONEThe user's voice.
NOTIFICATIONSA call that rings while the app is closed (Android; 13+ asks). iOS rings through CallKit, which needs none.
FULL_SCREENA ring that fills a locked screen (Android 14+, allowed in Settings). iOS: CallKit's own screen.
companion object { fun of(word: String?): GraineCallPermission? }

GraineCallPermission.of(word) reads one by its word — microphone, notifications, fullScreen (full_screen and any case too); null for any other.

GraineCallPermissionStatus

Read it to tell whether a call permission is allowed, can still be asked for, or only Settings can change it.

enum class GraineCallPermissionStatus(val wire: String) { GRANTED("granted"), DENIED("denied"), BLOCKED("blocked"), NOT_NEEDED("notNeeded") }

What to expect — GRANTED and NOT_NEEDED need nothing; DENIED means requestCallPermissions() can ask; BLOCKED means only Settings can change it — offer openCallSettings.

PropertyTypeMeaning
wireStringThe word every Graine SDK uses for it.
isSatisfiedBooleanGranted, or nothing to grant.
CaseMeaning
GRANTEDAllowed.
DENIEDNot allowed yet: requestCallPermissions() can ask for it.
BLOCKEDRefused for good, or only allowed in Settings.
NOT_NEEDEDThis phone needs no such permission.
companion object { fun of(word: String?): GraineCallPermissionStatus }

GraineCallPermissionStatus.of(word) reads one from a platform's word; anything it does not know is DENIED, never granted.

GraineCallPermissions

Read it to see every call permission at once.

data class GraineCallPermissions(val microphone: GraineCallPermissionStatus, val notifications: GraineCallPermissionStatus, val fullScreen: GraineCallPermissionStatus)

What to expect — A snapshot: read callPermissions again for the latest. allGranted is the one check before offering calls; permissions[GraineCallPermission.MICROPHONE] reads one by name.

PropertyTypeMeaning
microphoneGraineCallPermissionStatusThe microphone.
notificationsGraineCallPermissionStatusThe ring's notifications — NOT_NEEDED on iOS.
fullScreenGraineCallPermissionStatusThe full-screen ring — NOT_NEEDED on iOS.
allGrantedBooleanEvery permission is granted or not needed: calls can ring and connect.

GraineCallSetupProblem

Read it to show or log what your app's setup still lacks.

data class GraineCallSetupProblem(val code: String, val message: String)

What to expect — The code is stable and the same on every SDK (the list is under GraineCalls.callSetupProblems); the message is a sentence for the developer, with the exact fix.

PropertyTypeMeaning
codeStringStable: act on it, or count it.
messageStringWhat is missing and how to fix it, in plain words.

Booking with the SDK's sheet

“Call me at…” with no screen of your own: presentBooking shows the native SDK's booking sheet in the agent's design, and Graine rings this phone at the time the user picks.

What the sheet shows. A header, “Book a call”, with “{call name} will call you” under it — the agent's call name, else its chat title, else its 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”. Time: Android's own time picker in spinner mode (inside the SDK's own dialog) or iOS's time wheel, both in 5-minute steps, held to the times the chosen day offers between earliest(now) (rounded up to the next 5 minutes) and latest(now). The phone's time zone and the chosen time, such as “Asia/Kolkata · Tue 14 Oct, 6:00 PM”. What's it about? (optional): one line, at most 120 characters. Book call, with a spinner while it books; then “Booked — {call name} will call you on {day}, {time}” and Done. A sheet up from the bottom on a phone, a centred panel on a tablet.

A refusal stays in the sheet as one line under the button:

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, singular for one (“1 minute”). An agent that cannot be booked now opens a sheet that says why (the scheduling_off or identity_required line) and books nothing.

In the chat. The SDK's chat windows (GraineChat(), GraineViews.chat()) show the user's booked calls in their Upcoming calls card, with Book a call under them where booking is available — or alone in the card's place when none are booked; never when the design hides the booked-calls card. A booking refreshes the card.

Graine.bookingAvailable

Read it to decide whether to show your own “Call me” button.

val bookingAvailable: Boolean

true when Graine rings this phone (the workspace's In-app calling is on, for this platform), the default agent lets users book, and the user is identified with the trait the agent's Who is the user? setting names. The native SDK's own rule, read as it is now; false before configure, and on iOS with a GraineInApp older than this library (0.7.0). Check it again after identify and after the agent's settings have loaded. GraineAgent.bookingAvailable answers for another agent.

Parameters — none.

Returns — Boolean. Example value: true.

Errors — none.

val session by Graine.session.collectAsState()   // composes again when the settings load
if (session != null && Graine.bookingAvailable) {
    Button(onClick = { scope.launch { Graine.presentBooking() } }) { Text("Call me") }
}

Graine.bookingUnavailableReason

Read it to say why your own “Call me” button is not offered. 0.14.0.

val bookingUnavailableReason: String?

The first part of bookingAvailable's rule that fails, as a word; null when booking is available. GraineAgent.bookingUnavailableReason answers for another agent.

ValueMeans
not_loadedThe agent's settings have not loaded yet — or configure was not called. Read it again once Graine.session has a value.
rings_not_set_upGraine does not ring this phone: the workspace's In-app calling is off, or not for this platform or this app (no push credentials for its bundle ID or package name).
scheduling_offThe agent does not let users book calls.
not_identifiedNobody is identified with the trait the agent's Who is the user? setting names — call identify.

On iOS it needs GraineInApp of this version; an older one answers not_loaded until booking is available.

Parameters — none.

Returns — String?. Example value: "not_identified".

Errors — none.

val why = Graine.bookingUnavailableReason
if (why == "not_identified") Text("Sign in to book a call")

Graine.bookingState

Collect it to show or hide your own booking button as the answer changes — the way to read booking, rather than reading bookingAvailable once. 0.14.4.

val bookingState: StateFlow<GraineBookingState>

bookingAvailable and bookingUnavailableReason together (GraineBookingState), read again from the native SDK when the agent's settings arrive or change, after identify and setMemory (signing in and out), and when the settings could not be loaded. Until the settings have arrived it is never available: GraineBookingState(available = false, reason = "not_loaded") — "not yet", never a final no — while a user you identified waits for them, or when nothing is known yet; with nobody identified, the settings the last launch kept on the device may already answer rings_not_set_up, scheduling_off or not_identified. It moves on by itself: an app that reads it before the settings load still sees it end at available = true when the user can book. GraineAgent.bookingState answers for another agent.

Parameters — none.

Returns — StateFlow<GraineBookingState>. Example value: GraineBookingState(available=true, reason=null).

Errors — none.

val booking by Graine.bookingState.collectAsState()
if (booking.available) {
    Button(onClick = { scope.launch { Graine.presentBooking() } }) { Text("Call me") }
}

GraineBookingState

Read it from bookingState: whether an agent can be booked from the app now, and why not. 0.14.4.

data class GraineBookingState(val available: Boolean, val reason: String?)
PropertyTypeMeaning
availableBooleanbookingAvailable: Graine rings this phone, the agent lets users book, and the user is identified with the trait the agent's Who is the user? setting names.
reasonString?bookingUnavailableReason: not_loaded (not yet — the agent's settings have not arrived), rings_not_set_up, scheduling_off or not_identified; null when available.
when (Graine.bookingState.value.reason) {
    null -> showBookButton()
    "not_identified" -> showSignInHint()
    else -> hideBookButton()      // not_loaded: wait for the next value
}

Graine.bookingSlots

Call it to fill a time picker of your own with the times the SDK's booking sheet would offer. 0.14.0.

fun bookingSlots(day: LocalDate): List<Instant>

Every 5 minutes on day, in the phone's time zone, from the soonest the agent's rules allow (earliest(now), rounded up to the next 5 minutes) to the latest (latest(now)), oldest first — the same times as the sheet. When the agent has a calling window (schedulingRules.callingWindow), only the times inside it: its days, from its start up to, not including, its end, on the phone's clock — a day it leaves out has none (from 0.14.1). Book the one picked with scheduleCall. Graine checks the time again when it is booked, with what only it knows — the calls already booked — and refuses with too_many_pending (or outside_window, should the agent's hours change in the meantime). GraineAgent.bookingSlots answers for another agent. On iOS it needs GraineInApp of this version; an older one offers none.

ParameterTypeDefaultMeaning
dayLocalDaterequiredThe day, in the phone's time zone.

Returns — List<Instant> — empty for a day outside the rules, and before configure. Example value: [2026-10-22T04:30:00Z, 2026-10-22T04:35:00Z, …].

Errors — none.

val today = Clock.System.todayIn(TimeZone.currentSystemDefault())
val times = Graine.bookingSlots(today.plus(1, DateTimeUnit.DAY))   // tomorrow's
scope.launch { Graine.scheduleCall(times.first(), reason = "Talk through my order") }

Graine.presentBooking

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

suspend fun presentBooking(reason: String? = null): GraineScheduledCall?

Shows the booking sheet (above) for the default agent and returns once it closes. On Android it opens over the activity in front; on iOS over the key window's top view controller. One sheet at a time.

ParameterTypeDefaultMeaning
reasonString?nullFills What's it about?; the user may change it. Kept with the call for the agent and never put in the push that rings it.

Returns — GraineScheduledCall? — the booked call (GraineScheduledCall), or null when the user closed the sheet without booking, a sheet is already open, or (Android) no activity is in front. Example value: GraineScheduledCall(id="6f1c2a9e-…", at=2026-10-16T12:30:00Z, status=Scheduled, source=App, reason="Talk through my order").

Errors — IllegalStateException before configure. On iOS with a GraineInApp older than this library: GraineException Unavailable — “This app links a GraineInApp without the booking sheet. Link GraineInApp 0.8.0, the version of this library.”. Refusals stay in the sheet: it does not throw them.

scope.launch {
    if (!Graine.bookingAvailable) return@launch
    val call = Graine.presentBooking(reason = "Talk through my order") ?: return@launch
    showToast("We'll call you then.")
}

GraineAgent.bookingAvailable

Read it to decide whether to offer booking with one of your other agents.

val bookingAvailable: Boolean

Graine.bookingAvailable for this agent: Graine rings this phone, this agent lets users book, and the user is identified with this agent's identity trait. false before the agent is configured.

Parameters — none.

Returns — Boolean.

Errors — none.

val canBook = Graine.agent("support")?.bookingAvailable == true

GraineAgent.presentBooking

Call it to show the booking sheet for one of your other agents.

suspend fun presentBooking(reason: String? = null): GraineScheduledCall?

Graine.presentBooking for this agent, in its design and with its rules.

ParameterTypeDefaultMeaning
reasonString?nullFills What's it about?.

Returns — GraineScheduledCall? — the booked call, or null when nothing was booked.

Errors — IllegalStateException when this agent is not configured; on iOS with an older GraineInApp, GraineException Unavailable, as Graine.presentBooking.

val call = Graine.agent("support")?.presentBooking()

GraineAgent.bookingUnavailableReason

Read it to say why booking with one of your other agents is not offered. 0.14.0.

val bookingUnavailableReason: String?

Graine.bookingUnavailableReason for this agent — not_loaded, rings_not_set_up, scheduling_off or not_identified — or null when it can be booked. not_loaded before the agent is configured.

Parameters — none.

Returns — String?.

Errors — none.

val why = Graine.agent("support")?.bookingUnavailableReason

GraineAgent.bookingState

Collect it to follow whether one of your other agents can be booked. 0.14.4.

val bookingState: StateFlow<GraineBookingState>

Graine.bookingState for this agent: read again when its settings arrive or fail, and after identify and setMemory, which are every agent's. GraineBookingState(available = false, reason = "not_loaded") before the agent is configured.

Parameters — none.

Returns — StateFlow<GraineBookingState>.

Errors — none.

Graine.agent("support")?.bookingState?.collect { state -> supportBookButton.isVisible = state.available }

GraineAgent.bookingSlots

Call it for the times the booking sheet would offer with one of your other agents. 0.14.0.

fun bookingSlots(day: LocalDate): List<Instant>

Graine.bookingSlots for this agent, with its rules. Empty before the agent is configured.

ParameterTypeDefaultMeaning
dayLocalDaterequiredThe day, in the phone's time zone.

Returns — List<Instant>.

Errors — none.

val times = Graine.agent("support")?.bookingSlots(LocalDate(2026, 10, 22)).orEmpty()

The scheduled-calls list

Book calls from your own interface, list the user's upcoming calls and cancel one — the same calls the sheet and the chat's card show. Graine rings this device at the booked time.

GraineSchedulingRules

Read it to build your own booking screen — which times the agent accepts, and whether users may book at all.

data class GraineSchedulingRules(…)

Graine.schedulingRules (or GraineAgent.schedulingRules, GraineSession.schedulingRules).

What to expect — From the agent's settings once they load; before that the defaults hold, with booking off. scheduleCall refuses on the device first — SchedulingOff, TooSoon (before earliest(now)), TooFar (after latest(now)) — and Graine then checks the calling hours and the calls already waiting. The booking sheet and bookingSlots offer only the times inside callingWindow, so a time picked from them is never outside it.

FieldTypeDefaultMeaning
usersCanBookBooleanfalseRead it to know whether users may book calls from the app at all; false when the settings say nothing.
minLeadMinutesInt5The least notice a booking needs, in minutes — use it with earliest().
maxDaysAheadInt14How far ahead a booking may be, in days — use it with latest().
maxPendingPerUserInt3How many upcoming calls a user may have at once; beyond it, TooManyPending.
ringTimeoutSecondsInt45How long a call Graine rings keeps ringing before it is missed, 20–60 seconds.
callNameString?nullThe name the agent's calls ring with; null uses the app's display name.
hostedRingingBooleanfalseRead it to know whether Graine rings this workspace's users itself (its push credentials are uploaded).
platformsList<GrainePlatform>emptyList()The phones Graine rings (GrainePlatform); empty means every platform.
callingWindowGraineCallingWindow?nullThe agent's calling window (GraineCallingWindow): the booking sheet and bookingSlots offer only the times inside it. null when the agent has none — every time from earliest() to latest() is offered. 0.14.1.

Its functions: earliest, latest — each with its parameters, what it returns, its errors and an example.

GraineSchedulingRules.earliest

Call it for the soonest time a booking is accepted, to start your time picker there.

fun earliest(now: Instant = Clock.System.now()): Instant
ParameterTypeDefaultMeaning
nowInstantClock.System.now()The moment to count from; now when left out.

Returns — Instant — now plus minLeadMinutes. Example value: 2026-10-15T12:05:00Z.

Errors — none.

val first = Graine.schedulingRules.earliest()

GraineSchedulingRules.latest

Call it for the latest time a booking is accepted, to end your time picker there.

fun latest(now: Instant = Clock.System.now()): Instant
ParameterTypeDefaultMeaning
nowInstantClock.System.now()The moment to count from; now when left out.

Returns — Instant — now plus maxDaysAhead days. Example value: 2026-10-29T12:00:00Z.

Errors — none.

val last = Graine.schedulingRules.latest()

GraineCallingWindow

Read it to know the hours the agent may ring a booked call — to say them beside a time picker of your own. 0.14.1.

data class GraineCallingWindow(val start: String, val end: String, val days: List<Int>)

GraineSchedulingRules.callingWindow: the agent's calling window, as booking applies it. The booking sheet and bookingSlots offer only the times inside it, and Graine checks a booked time against it again.

What to expect — Read on the phone's clock, in its own time zone, as Graine checks a booking: a time is inside when its weekday is in days and start ≤ its time of day < end. A window never crosses midnight. null (no GraineCallingWindow) when the agent has none, or when the session's window cannot be read. The same on Android and iOS.

FieldTypeDefaultMeaning
startStringrequiredThe first time of day offered, "HH:MM" in 24-hour time — "09:00". 0.14.1.
endStringrequiredWhen the window closes, "HH:MM" — never offered itself: with "21:00" the last time offered is 20:55. 0.14.1.
daysList<Int>requiredThe days it is open, 0 Monday … 6 Sunday, each once, in order — [0, 1, 2, 3, 4] for weekdays. 0.14.1.
val window = Graine.schedulingRules.callingWindow
val hours = window?.let { "Calls between ${it.start} and ${it.end}" } ?: "Any time"

GrainePlatform

Read it in GraineSchedulingRules.platforms to know which phones Graine rings.

enum class GrainePlatform(val wire: String) { IOS("ios"), ANDROID("android") }

PropertyTypeMeaning
wireStringThe platform's word: ios or android.
CaseMeaning
IOSiPhones and iPads.
ANDROIDAndroid phones and tablets.

Graine.scheduleCall

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

suspend fun scheduleCall(at: Instant, reason: String? = null): GraineScheduledCall

Books a call from the default agent for the signed-in user (or, with nobody signed in, this install) at at — “call me tomorrow at 6”; Graine rings this device then. It waits for the agent's settings (at most 20 seconds), then refuses on the device — before anything is sent — what the rules already settle, in the booking sheet's words: SchedulingOff, “Booking a call isn't available right now”; TooSoon, “Pick a time at least N minutes from now”; TooFar, “Pick a time within N days” (N singular for one: “1 minute”, “1 day”). Graine then checks its own: the calling hours, in this device's time zone, and the calls already waiting. reason is trimmed to 120 characters, kept with the call for the agent, and never put in the push that rings it. An open chat's Upcoming calls card shows the booking at once. GraineAgent.scheduleCall books with another agent.

ParameterTypeDefaultMeaning
atInstantrequiredWhen the call should ring: between schedulingRules.earliest() and latest().
reasonString?nullWhat the call is about, at most 120 characters — the agent hears it when it rings.

Returns — GraineScheduledCall — the booked call (GraineScheduledCall), status Scheduled. Example value: GraineScheduledCall(id="6f1c2a9e-…", at=2026-10-16T12:30:00Z, status=Scheduled, source=App, reason="Talk through my order").

Errors — throws GraineException — on the device: SchedulingOff, TooSoon, TooFar; from Graine: OutsideWindow, TooManyPending, IdentityRequired, DeviceLimit, InvalidRequest, RateLimited, Network, Unavailable (“The booking was accepted but not described.” when Graine booked it without describing it).

try {
    val call = Graine.scheduleCall(Clock.System.now() + 1.hours, reason = "Talk through my order")
    showToast("Booked for ${call.at}")
} catch (e: GraineException) {
    showMessage(e.message.orEmpty())
}

GraineAgent.scheduleCall

Call it to book a call with one of your other agents.

suspend fun scheduleCall(at: Instant, reason: String? = null): GraineScheduledCall

Graine.scheduleCall for this agent, checked against this agent's rules.

ParameterTypeDefaultMeaning
atInstantrequiredWhen the call should ring.
reasonString?nullWhat it is about, at most 120 characters.

Returns — GraineScheduledCall.

Errors — throws GraineException as Graine.scheduleCall.

val call = Graine.agent("support")?.scheduleCall(Clock.System.now() + 2.hours, reason = "Renewal questions")

Graine.scheduledCalls

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

suspend fun scheduledCalls(): List<GraineScheduledCall>

The calls the default agent has booked for the signed-in user (or this install) that are still to come, soonest first.

Parameters — none.

Returns — List<GraineScheduledCall>. Example value: [GraineScheduledCall(id="6f1c2a9e-…", at=2026-10-16T12:30:00Z, status=Scheduled, source=Agent, reason=null)].

Errors — throws GraineException: Network, RateLimited, Unavailable, InvalidKey, OriginRefused.

val upcoming = Graine.scheduledCalls()

GraineAgent.scheduledCalls

Call it to list the calls one of your other agents has booked for the user.

suspend fun scheduledCalls(): List<GraineScheduledCall>

Parameters — none.

Returns — List<GraineScheduledCall>, soonest first.

Errors — throws GraineException as Graine.scheduledCalls.

val upcoming = Graine.agent("support")?.scheduledCalls().orEmpty()

Graine.cancelScheduledCall

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

suspend fun cancelScheduledCall(id: String): GraineCallStatus

Only a call booked for this user or install; any other is NotFound.

ParameterTypeDefaultMeaning
idStringrequiredThe call's id, from scheduleCall, scheduledCalls or presentBooking.

Returns — GraineCallStatus — its status afterwards, Cancelled. Example value: GraineCallStatus.Cancelled.

Errors — throws GraineException: InvalidRequest (“No call id.”) for a blank id, NotFound, Network, RateLimited, Unavailable.

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

GraineAgent.cancelScheduledCall

Call it to call off a call one of your other agents booked.

suspend fun cancelScheduledCall(id: String): GraineCallStatus
ParameterTypeDefaultMeaning
idStringrequiredThe call's id.

Returns — GraineCallStatus — Cancelled.

Errors — throws GraineException as Graine.cancelScheduledCall.

Graine.agent("support")?.cancelScheduledCall("6f1c2a9e-7d1b-4c47-9a6e-2f0d8b1c5e44")

GraineScheduledCall

Read it to show a booked call: when it rings, where it is, and whether it can still be cancelled.

data class GraineScheduledCall(…)

What to expect — From scheduleCall (status Scheduled), scheduledCalls and presentBooking. at is a moment: show it in the device's time zone. A status or source newer than the SDK arrives as Unknown, carrying its word.

FieldTypeDefaultMeaning
idStringrequiredUse it to cancel the call — Graine's ID for it, a UUID.
atInstant?requiredWhen it rings; null only when Graine's time could not be read.
statusGraineCallStatusrequiredWhere it is (GraineCallStatus).
sourceGraineCallSource?nullWho booked it (GraineCallSource); null when Graine does not say.
reasonString?nullWhat it is about, when Graine shares it — at most 120 characters.
PropertyTypeMeaning
val isUpcoming: BooleanBooleanUse it to keep a call in an upcoming list: true while it is Scheduled or Ringing.
val canCancel: BooleanBooleanUse it to show a Cancel control: true while it is Scheduled, before it rings.

GraineCallStatus

Read it to show where a booked call is.

sealed class GraineCallStatus(val wire: String)

What to expect — Scheduled → Ringing → Answered → Completed; or Declined, Missed, Failed, Cancelled, Expired, NoDevice. A status newer than this SDK arrives as Unknown(raw): give every when an else.

PropertyTypeMeaning
wireStringGraine's word for the status — scheduled, no_device, … — for logs and your server.
CaseMeaning
ScheduledBooked, waiting for its time; it can still be cancelled.
RingingRinging the user now.
AnsweredThe user picked up.
CompletedThe call took place and is over.
DeclinedThe user declined it; nothing rings them again for 6 hours.
MissedIt rang out unanswered.
FailedIt could not be placed.
CancelledCalled off before it rang.
ExpiredIts time passed while it could not ring — more than 10 minutes late, or no opening left in the calling hours.
NoDeviceNothing could be rung: the user has no device registered for calls in the last 30 days.
Unknown(raw)A status newer than this SDK, carrying Graine's word in raw.

Its functions: from — each with its parameters, what it returns, its errors and an example.

GraineCallSource

Read it to show who booked a call.

sealed class GraineCallSource(val wire: String)

What to expect — A source newer than this SDK arrives as Unknown(raw).

PropertyTypeMeaning
wireStringGraine's word for the source — sdk for App.
CaseMeaning
AgentThe agent booked it in a conversation.
AppYour app booked it (scheduleCall, the booking sheet).
DashboardYour team booked it in the dashboard.
ApiYour server booked it through the API.
Unknown(raw)A source newer than this SDK, carrying Graine's word.

Its functions: from — each with its parameters, what it returns, its errors and an example.

Workflows your app starts

Start one of your outreach workflows for the user your app 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 user, never for anyone the data names, and it never sends to an address your app gives: a user the agent knows by phone or email, and verified, is reached there.

Graine.startWorkflow

Call it when something in your app should start a workflow for the signed-in user, from the default agent.

suspend fun startWorkflow(workflow: String, data: Map<String, Any?> = emptyMap(), idempotencyKey: String? = null): GraineWorkflowRun

The default agent's GraineAgent.startWorkflow: the platform SDK (Android's GraineInApp.startWorkflow, iOS's through its Objective-C interface) waits for the agent's settings, checks — refusing with IdentityRequired when someone else was identified meanwhile, so a run is never started for a user who did not ask for it — sends and retries.

ParameterTypeDefaultMeaning
workflowStringrequiredThe workflow's exact name, or its id (owf_…); at most 120 characters.
dataMap<String, Any?>emptyMap()The contact fields the workflow allows: text (at most 200 characters), numbers and yes/no; at most 12 (on iOS the first 12 by name, on Android in the map's order). Anything else is left out, never refused — and never a phone number, an email address or another field a step sends to.
idempotencyKeyString?null8 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 — GraineWorkflowRun. Example value: GraineWorkflowRun(runId=oex_2c9e8f1a7b3d4c5e6f7a8b9c, workflowId=owf_8a1d4e7c2b90f1a2b3c4d5e6, alreadyRunning=false).

Errors — throws GraineException — on the device: InvalidRequest (no workflow name, a key that isn't one), IdentityRequired (nobody identified); from Graine: NotAllowed, NotVerified, RateLimited (retryAfterSeconds), Unavailable (no credit, or the workflow's agent is switched off), InvalidRequest (the workflow needs a field your app may not send), and the agent's checks on your app and users as their own words (Unknown); Network when no answer came twice.

val run = Graine.startWorkflow("Welcome call", mapOf("plan" to "gold"))

GraineAgent.startWorkflow

Call it to start a workflow from one agent of several.

suspend fun startWorkflow(workflow: String, data: Map<String, Any?> = emptyMap(), idempotencyKey: String? = null): GraineWorkflowRun

As Graine.startWorkflow, from this agent (its own publishable key).

Parameters — as Graine.startWorkflow.

Returns — GraineWorkflowRun.

Errors — as Graine.startWorkflow.

val run = Graine.agent("support")?.startWorkflow("Callback", idempotencyKey = "ticket-4471")

GraineWorkflowRun

Read it to know which run started.

What startWorkflow started — or the run the user already had under way.

What to expect — runId is the run's id (oex_…), as the workflow's Runs list shows it. alreadyRunning is true when the user already had a run of this workflow under way: that run comes back, never a second one. workflowId is the workflow's id (owf_…); null only when Graine's answer did not say.

FieldTypeDefaultMeaning
val runId: StringStringrequiredThe run's id (oex_…).
val workflowId: String?String?requiredThe workflow's id (owf_…); null when Graine's answer did not say.
val alreadyRunning: BooleanBooleanrequiredTrue when the user already had a run of this workflow under way: that run, never a second.

Design

The SDK's own screens — the chat, the voice bar, the call screen and the booking sheet — draw the design the brand chose in the Garage: colours, typefaces, corners, the launcher's look, the chat window's style, the call screen's look, light and dark. The last design is kept on the device, so a call that wakes a closed app is drawn in it too. An app that draws UI of its own in the brand's design reads the same tokens from shared code: Graine.theme (each agent's theme), a GraineThemeTokens.

Graine.theme

Collect it to draw UI of your own — a card, a button, a screen around the agent — in the brand's design.

val theme: StateFlow<GraineThemeTokens?>

The default agent's design tokens: the colours, type, corners, depth, motion and icons the SDK's own screens draw with, and the chat window's and the call screen's tokens, for the phone's current light or dark appearance — or the brand's fixed scheme. It changes when the phone switches between light and dark. null before the agent's settings load, and when they carry no design. Each agent has its own: GraineAgent.theme. On iOS it needs GraineInApp of this version; with an older one it stays null.

Parameters — none.

Returns — StateFlow<GraineThemeTokens?> (GraineThemeTokens). Example value: GraineThemeTokens(v=1, preset="graine-classic", scheme="light", colors=Colors(background="#F7F7F5", …), …).

Errors — none.

val t = Graine.theme.value ?: return   // null before the settings load, or without a design
val accent = t.colors.accent           // "#318CE7"
val corner = t.shape.radius.lg         // 18.0, in dp (points on iOS)
val heading = t.font.heading           // "DM Sans", or "system" for the platform's own font

GraineThemeTokens

Read it to draw UI of your own in the brand's design.

data class GraineThemeTokens(…)

One scheme's design tokens — the design contract every Graine SDK draws from, the same values as React Native's useGraineTheme(), iOS theme, Android themeTokens() and Flutter tokens — as plain numbers and #RRGGBB strings. Lengths are dp (points on iOS), type sizes sp. From Graine.theme and each agent's theme.

What to expect — Resolved by the native SDK from the agent's design when the settings load, for the phone's light or dark appearance (or the brand's fixed scheme); reading them never throws. A design without a complete set of colours is no design: theme is null. The words — "outline", "spring", "window" — are the design's own: compare against them, and keep a default branch, since a newer design can send a word this build does not know.

FieldTypeMeaning
vIntThe token format's version, for logs.
presetStringThe design style the brand started from — informational: the tokens are already resolved.
schemeStringWhich of the design's two sets this is: light or dark.
colorsColorsEvery colour a surface is drawn in (GraineThemeTokens.Colors).
fontFontThe typefaces, sizes, weights, letter spacing and line heights (GraineThemeTokens.Font).
shapeShapeCorner radii, outline width and the launcher's outline (GraineThemeTokens.Shape).
spacingSpacingThe spacing unit, card padding and gap (GraineThemeTokens.Spacing).
elevationElevationHow depth is drawn: soft shadows, or a hard offset (GraineThemeTokens.Elevation).
motionMotionHow long and how things move (GraineThemeTokens.Motion).
iconsIconsThe icons' style and stroke, and the launcher's glyph (GraineThemeTokens.Icons).
glassGlass?Translucent surfaces (GraineThemeTokens.Glass); null for opaque ones.
bubblesStringHow chat messages sit on the page: filled, outline or minimal.
chromeStringnone, or window: the chat, the caption and components open as desktop windows.
chatChat?The chat window's own tokens — its words, its colours and every piece of the brand's chat style (GraineThemeTokens.Chat); null from a server that predates them — draw from colors.
callCall?The call screen's tokens (GraineThemeTokens.Call); null from a server that predates them.
PropertyTypeMeaning
val isDark: BooleanBooleanRead it to know these are the dark tokens (scheme == "dark").

GraineThemeTokens.Colors

Read it to colour your own UI exactly as the agent's design does. data class Colors(…), as GraineThemeTokens.colors: seventeen colours, each #RRGGBB.

FieldTypeMeaning
backgroundStringThe page behind everything in the chat window — your own full-screen backgrounds.
surfaceStringThe voice bar, the chat header and sheets — your own bars and panels.
surfaceRaisedStringCards, the message field and unselected chips — anything that sits on a surface.
textStringMain text.
textMutedStringSecondary text: captions, labels, times.
borderStringHairlines and outlines.
accentStringThe brand colour: primary buttons, the launcher, the send button, anything selected.
onAccentStringText and icons drawn on the accent.
accentSoftStringThe accent at low strength: chips, selected rows, the focus halo.
successStringGood news: online dots, confirmations.
warningStringCautions.
dangerStringErrors, the end-call button, a refusal line.
userBubbleStringThe user's chat bubbles.
userBubbleTextStringText in the user's bubbles.
agentBubbleStringThe agent's chat bubbles.
agentBubbleTextStringText in the agent's bubbles.
scrimStringWhat dims the app behind a sheet or dialog, drawn at 40 %.

GraineThemeTokens.Font

Read it to set your own text in the design's typefaces, sizes and weights. data class Font(…), as GraineThemeTokens.font.

FieldTypeMeaning
bodyStringThe body text's family: system is the platform's own UI font; any other name is a family your app may bundle.
headingStringThe titles' family, read the same way.
scaleScaleThe type sizes, in sp (GraineThemeTokens.Font.Scale).
weightsWeightsThe weights (GraineThemeTokens.Font.Weights).
letterSpacingPairLetter spacing for body text and titles, in em (GraineThemeTokens.Font.Pair).
lineHeightPairLine height for body text and titles, as a multiple of the size.

GraineThemeTokens.Font.Scale

Read it to size your own text on the design's scale. data class Scale(val caption: Double, val body: Double, val title: Double, val display: Double), in sp.

FieldTypeMeaning
captionDoubleSmall text: captions, labels and times.
bodyDoubleBody text and chat messages.
titleDoubleTitles, such as a header's.
displayDoubleThe largest text, such as the call screen's name.

GraineThemeTokens.Font.Weights

Read it to weight your own text the way the design does. data class Weights(val body: Int, val strong: Int, val title: Int): CSS weights, 100–900 — 400 is regular, 600 semibold.

FieldTypeMeaning
bodyIntBody text.
strongIntEmphasis: labels and buttons.
titleIntTitles.

GraineThemeTokens.Font.Pair

Read it for a value that differs between body text and titles. data class Pair(val body: Double, val title: Double) — letter spacing in em, or line height as a multiple of the size, as its field says.

FieldTypeMeaning
bodyDoubleThe value for body text.
titleDoubleThe value for titles.

GraineThemeTokens.Shape

Read it for the design's corners, outline width and launcher shape. data class Shape(val radius: Radius, val borderWidth: Double, val launcher: String), as GraineThemeTokens.shape.

FieldTypeMeaning
radiusRadiusThe corner radii (GraineThemeTokens.Shape.Radius).
borderWidthDoubleThe width of every outline, in dp.
launcherStringThe launcher's outline: circle, squircle, rounded-square, square or pill.

GraineThemeTokens.Shape.Radius

Read it to round your own corners the way the design does. data class Radius(val sm: Double, val md: Double, val lg: Double, val xl: Double), in dp.

FieldTypeMeaning
smDoubleSmall corners: chips, a square launcher.
mdDoubleButtons and text fields.
lgDoubleCards, and a rounded-square launcher.
xlDoubleThe roundest corners: pill-shaped chips, sheets, the voice bar.

GraineThemeTokens.Spacing

Read it to space your own UI on the design's rhythm. data class Spacing(val unit: Double, val cardPadding: Double, val gap: Double), in dp.

FieldTypeMeaning
unitDoubleThe base step: other spacing is a multiple of it.
cardPaddingDoubleThe padding inside a card.
gapDoubleThe gap between items in a list or a row.

GraineThemeTokens.Elevation

Read it to give your own cards and floating views the design's depth. data class Elevation(val card: Shadow?, val floating: Shadow?, val hardOffset: Offset?), as GraineThemeTokens.elevation.

FieldTypeMeaning
cardShadow?The shadow under cards (GraineThemeTokens.Shadow); null for none.
floatingShadow?The shadow under what floats — the voice bar, the launcher, sheets; null for none.
hardOffsetOffset?A solid offset drawn instead of soft shadows (GraineThemeTokens.Offset); null unless the design draws depth that way.

GraineThemeTokens.Shadow

Read it to draw one of the design's soft shadows. data class Shadow(val y: Double, val blur: Double, val spread: Double, val opacity: Double, val color: String), used by GraineThemeTokens.Elevation.

FieldTypeMeaning
yDoubleHow far down the shadow falls, in dp.
blurDoubleHow soft it is: the blur radius, in dp.
spreadDoubleHow far it grows past the shape, in dp.
opacityDoubleHow dark it is, 0–1, applied to color.
colorStringThe shadow's colour, #RRGGBB.

GraineThemeTokens.Offset

Read it to draw the solid, offset shadow some designs use instead of a soft one. data class Offset(val x: Double, val y: Double): the shape repeated behind itself, drawn in colors.text, as GraineThemeTokens.elevation.hardOffset.

FieldTypeMeaning
xDoubleHow far right it sits, in dp (negative: left).
yDoubleHow far down it sits, in dp (negative: up).

GraineThemeTokens.Motion

Read it to move your own UI at the design's pace — or not at all. data class Motion(val durationMs: Int, val easing: String, val bounce: Double), as GraineThemeTokens.motion. The phone's own reduce-motion setting wins over any number here.

FieldTypeMeaning
durationMsIntHow long a transition runs, in milliseconds; 0 means no transition at all.
easingStringThe curve: standard, emphasized, spring, linear or none (no movement).
bounceDoubleHow much a spring overshoots, 0–1.

GraineThemeTokens.Icons

Read it to match the design's icon style and the launcher's glyph. data class Icons(val style: String, val stroke: Double, val launcher: Glyph?), as GraineThemeTokens.icons.

FieldTypeMeaning
styleStringThe style of the SDK's icons: outline, filled, duotone or sharp.
strokeDoubleThe line width of icons and stroked glyphs, in dp.
launcherGlyph?The launcher's glyph (GraineThemeTokens.Glyph); null when the launcher shows the brand's logo.

GraineThemeTokens.Glyph

Read it to draw the brand's launcher glyph yourself, from its path. data class Glyph(val id: String, val path: String, val stroke: Boolean), as GraineThemeTokens.icons.launcher.

FieldTypeMeaning
idStringThe glyph's name, such as waveform.
pathStringThe drawing: SVG path data on a 24 × 24 grid.
strokeBooleantrue: draw it as a line icons.stroke wide; false: fill it.

GraineThemeTokens.Glass

Read it to draw translucent surfaces the way a glass design does. data class Glass(val blur: Double, val surfaceOpacity: Double), as GraineThemeTokens.glass — null for an opaque design.

FieldTypeMeaning
blurDoubleHow much what is behind a translucent surface is blurred, in dp, where the platform can.
surfaceOpacityDoubleThe opacity colors.surface is drawn at over that blur, 0–1.

GraineThemeTokens.Chat

Read it to draw a chat window of your own the way the agent's design does. data class Chat(…), as GraineThemeTokens.chat: the Garage's chat window, resolved. Colours are #RRGGBB; an empty word means the SDK's own default.

From preset on — new in 0.13.0 — every piece of the window, as the chat style chosen in the Garage resolved it (The Garage → The chat window): a style — Classic (the chat as it has always looked, and the default), Soft, Bold, Glass, Minimal, Crisp, Cozy, Calm, Compact or Lively — sets them all at once, and each piece can then be tuned on its own. They arrive worked out: lengths in dp (points on iOS), and every text colour already reads on what it sits on — at least 4.5:1, or 3:1 for words on the accent. They are read the same way on Android and iOS and never throw: a value the server left out or sent malformed takes the classic chat's value, a word this build does not know reads as the first one listed for it on this page, and a number outside its range is brought into it. From a server that predates chat styles, every piece is the classic chat these same tokens imply — the chat as it has always been drawn — and preset is classic. A Chat you construct yourself, in a preview or a test, carries Graine Classic's pieces unless you pass others.

FieldTypeMeaning
titleStringThe header's title; empty: the agent's heading.
subtitleStringThe header's second line while online; empty: “Online”.
avatarStringThe header's mark: logo, glyph or none.
placeholderStringThe message field's placeholder, such as “Message…”.
showTimestampsBooleanWhether each message shows its time.
suggestionsList<String>Up to four replies offered before the user has said anything; a tap sends one.
backgroundStringBehind the messages.
patternStringnone, or dots over the messages in patternColor.
patternColorStringThe dots' colour.
headerBackgroundStringThe header's fill.
headerTextStringThe header's title colour.
headerSubtextStringThe header's second line's colour.
composerBackgroundStringThe message field's fill.
composerTextStringThe message field's text colour.
composerPlaceholderStringThe placeholder's colour.
composerBorderStringThe message field's outline.
sizeGraineChatSize?How big the window opens — the dashboard's Window size (GraineChatSize); null for a word this build does not know: draw it compact.
showUpcomingCallsBooleanWhether the Upcoming calls card — and Book a call — shows at the top of the chat (Booked calls in the dashboard).
upcomingTitleStringThat card's title; empty: “Upcoming call” or “Upcoming calls”.
showHistoryBooleanWhether the conversation kept from before is shown (Earlier messages); off, the agent still has it.
newConversationBooleanWhether the header offers New conversation; off, chat.newConversation() still works.
presetStringThe chat style the pieces below came from: classic, soft, bold, glass, minimal, crisp, cozy, calm, compact or lively — or a style added later. For information only: every piece is already worked out, so never derive a look from this name.
headerHeaderThe header: its fill, alignment and status line, and where a pinned card goes (GraineThemeTokens.Chat.Header).
bubblesBubblesThe message bubbles: shape, corners, grouping, width, shadow and each side's colours (GraineThemeTokens.Chat.Bubbles).
timestampsTimestampsWhich messages show their time, where, and the sent marks (GraineThemeTokens.Chat.Timestamps).
wallpaperWallpaperWhat is behind the messages: a colour, a gradient or a pattern (GraineThemeTokens.Chat.Wallpaper).
chipsChipsThe look and place of the brand's conversation starters and the agent's suggested replies (GraineThemeTokens.Chat.Chips).
cardsCardsThe cards in the conversation: the agent's components, the upcoming-calls card, a pinned card and the rating card (GraineThemeTokens.Chat.Cards).
composerComposerThe message field, its buttons and what is behind them (GraineThemeTokens.Chat.Composer).
typingTypingThe typing indicator (GraineThemeTokens.Chat.Typing).
densityDensityThe conversation's spacing (GraineThemeTokens.Chat.Density).
welcomeWelcomeHow a new conversation opens, and how its starters are shown (GraineThemeTokens.Chat.Welcome).
ratingRatingWhether, and how, the window asks “How was this chat?” once the agent ends the conversation (GraineThemeTokens.Chat.Rating).
escalationEscalationWhere a button that calls the agent goes, if anywhere (GraineThemeTokens.Chat.Escalation).
glassGlass?Frosted pieces (GraineThemeTokens.Chat.Glass); null for solid ones.
val chat = Graine.theme.value?.chat ?: return    // null before the settings load, or from a server that predates it
val agent = chat.bubbles.agent                   // the agent's bubbles
val fill = agent.color                           // null: no fill — the wallpaper shows through
val corner = chat.bubbles.radius                 // in dp (points on iOS)
val askRating = chat.rating.show && Graine.chat.ended.value

GraineThemeTokens.Chat.Header

Read it to draw the chat window's header as the brand styled it. data class Header(val style: String, val align: String, val status: String, val typingStatus: Boolean, val contextCard: String, val fill: Fill, val dot: String, val divider: Boolean), as GraineThemeTokens.chat.header. The status line, first match wins: “Connecting…” while connecting; “Reconnecting…” while reconnecting; the typing words while the agent types and typingStatus is on; no line for status none; otherwise the dot and the subtitle (online) or the words alone (text).

FieldTypeMeaning
styleStringThe header's fill: surface (colors.surface), accent (fill.color), gradient (from fill.color at the leading edge to fill.colorTo at the trailing edge, mirrored for right-to-left) or plain (no fill: the wallpaper runs under it).
alignStringstart (the avatar, title and status at the leading edge) or center (the avatar, title and status centred across the header, its buttons still at the edges).
statusStringThe line under the title: online (a dot in dot, then chat.subtitle or “Online”), text (the words without the dot) or none (no line; the title centres).
typingStatusBooleantrue: while the agent types a reply, the status line says so (chat.typing.text, or “Typing…”), even where status is none.
contextCardStringWhere a card pinned with Graine.chat.pin goes: bar (under the header), card (at the top of the conversation, scrolling with it) or none (not drawn).
fillFillThe header's fill and the title and status colours on it (GraineThemeTokens.Chat.Fill).
dotStringThe online dot's colour.
dividerBooleantrue: a hairline in colors.border under the header.

GraineThemeTokens.Chat.Fill

Read it for a fill — one colour or a gradient — and the text colours that read on all of it. data class Fill(val color: String, val colorTo: String?, val text: String, val textMuted: String), as GraineThemeTokens.chat.header.fill; a hero welcome is drawn in it too, its gradient running top to bottom.

FieldTypeMeaning
colorStringThe fill, or a gradient's near end.
colorToString?The gradient's far end; null for one solid colour.
textStringWords on the fill, such as the title; it reads on all of the fill.
textMutedStringQuieter words on it, such as the status line.

GraineThemeTokens.Chat.Bubbles

Read it to draw the message bubbles as the brand styled them. data class Bubbles(val shape: String, val radius: Double, val tightRadius: Double, val grouping: Boolean, val maxWidth: Double, val shadow: Shadow?, val user: BubbleSide, val agent: BubbleSide), as GraineThemeTokens.chat.bubbles. The user's bubbles sit on the trailing side and the agent's on the leading side, both mirrored for right-to-left; the SDK's chat window groups messages in a row from one side, each within two minutes of the one before.

FieldTypeMeaning
shapeStringrounded (every corner radius, the bottom corner nearest the speaker tightRadius), squircle (continuous corners where the platform has them), tail (as squircle, with a tail at the speaker's bottom corner of a lone bubble or a group's last) or flat (every corner radius).
radiusDoubleThe corners, in dp.
tightRadiusDoubleThe tighter corner nearest the speaker, and a group's inner corners, in dp.
groupingBooleantrue: messages in a row from one side are drawn as one group — chat.density.groupGap apart, their inner corners tight.
maxWidthDoubleThe widest a bubble may be, as a share of the conversation's width: 0.6–0.92.
shadowShadow?A shadow under each bubble (GraineThemeTokens.Shadow); null for none.
userBubbleSideThe user's bubbles (GraineThemeTokens.Chat.BubbleSide).
agentBubbleSideThe agent's bubbles, read the same way.

GraineThemeTokens.Chat.BubbleSide

Read it for one side's bubble colours. data class BubbleSide(val color: String?, val colorTo: String?, val text: String, val textMuted: String, val border: String?, val bare: Boolean, val link: String), as GraineThemeTokens.chat.bubbles.user and .agent.

FieldTypeMeaning
colorString?The fill; null for none (transparent).
colorToString?A gradient's bottom colour, from color at the top; null for a solid fill.
textStringThe words.
textMutedStringA time or a mark drawn inside the bubble (chat.timestamps.style inside).
borderString?An outline in this colour, shape.borderWidth wide and at least 1 dp; null for none.
bareBooleantrue: no bubble at all — no fill, outline or shadow; the words sit straight on the wallpaper, and their time goes below them.
linkStringLinks in the words, always underlined.

GraineThemeTokens.Chat.Timestamps

Read it to know which messages show their time, and where. data class Timestamps(val show: String, val style: String, val ticks: Boolean), as GraineThemeTokens.chat.timestamps. A time is the device's short time format; a component carries none.

FieldTypeMeaning
showStringnever, group (the last message of each group) or always (every message).
styleStringbelow the bubble, in chat.wallpaper.textMuted, or inside it on a line under the words, in the side's textMuted.
ticksBooleantrue: a mark beside each of the user's times — waiting for the connection, sent, or not sent.

GraineThemeTokens.Chat.Wallpaper

Read it to draw what is behind the messages. data class Wallpaper(val style: String, val color: String, val colorTo: String?, val pattern: String, val patternColor: String, val intensity: Double, val text: String, val textMuted: String), as GraineThemeTokens.chat.wallpaper: one surface from the window's top to its bottom, also under a plain header and a floating composer. A pattern stays still while the messages scroll, and never mirrors for right-to-left.

FieldTypeMeaning
styleStringsolid (color), gradient (color at the top to colorTo at the bottom) or pattern (pattern over color).
colorStringThe colour, or the gradient's top.
colorToString?The gradient's bottom; null unless style is gradient.
patternStringdots, grid, diagonal (lines) or none, drawn in patternColor.
patternColorStringThe pattern's colour.
intensityDoubleHow strong the gradient or the pattern is, 0–1 — already applied to the colours, for information.
textStringWords straight on the wallpaper, such as the welcome's title.
textMutedStringQuieter words on it: day separators and times under the bubbles.

GraineThemeTokens.Chat.Chips

Read it to draw the brand's conversation starters and the agent's suggested replies — one look for both. data class Chips(…), as GraineThemeTokens.chat.chips. A tap sends the chip's words as the user's own message (Graine.chat.sendQuickReply for a suggested reply); starters go for the rest of the conversation once the user says something, suggested replies once the user sends anything or the agent offers new ones.

FieldTypeMeaning
styleStringoutline, filled, soft or elevated (raised, and frosted where chat.glass is set).
placementStringWhere they go: both (starters docked above the composer, suggested replies in the conversation under the message they follow), inline (starters at the end of the welcome, suggested replies under their message) or above-composer (both docked above the composer).
scrollStringwrap (rows that wrap) or row (one row that scrolls sideways).
heightDoubleA chip's height, in dp; it grows with the text size.
radiusDoubleIts corners, in dp.
fillStringIts fill.
textStringIts words.
borderString?Its outline; null for none.
borderWidthDoubleThe outline's width, in dp.
shadowShadow?Its shadow (GraineThemeTokens.Shadow); null for none.

GraineThemeTokens.Chat.Cards

Read it to draw the cards in the conversation — the agent's components, the upcoming-calls card, a pinned card and the rating card — on colors.surfaceRaised. data class Cards(…), as GraineThemeTokens.chat.cards.

FieldTypeMeaning
radiusDoubleThe corners, in dp.
shadowShadow?The shadow (GraineThemeTokens.Shadow); null for none.
hardBooleantrue: the design's hard offset (elevation.hardOffset) instead of a shadow.
borderBooleantrue: an outline in colors.border.
imageStringA component's large image: auto (its own height), square (as tall as wide), landscape (three quarters as tall as wide) or wide (nine sixteenths as tall as wide) — always 100–260 dp tall.
buttonStringA component's main button, where its own look says filled: filled, outline, tonal or text. A component's own style still wins.
buttonFillString?That button's fill; null for none.
buttonTextStringThat button's words.
buttonBorderString?That button's outline; null for none.

GraineThemeTokens.Chat.Composer

Read it to draw the message field and its buttons as the brand styled them. data class Composer(…), as GraineThemeTokens.chat.composer. The microphone and the call button show only where the agent takes calls and a call can start from the chat; the paperclip only while your app takes attachments (Graine.chat.onAttach).

FieldTypeMeaning
styleStringbar (a strip across the bottom), floating (a raised capsule over the conversation, which scrolls under it) or pill (the send button inside the field).
micBooleantrue: while the field is empty, the send button is a microphone, and a tap calls the agent.
attachBooleantrue: a paperclip, where your app takes attachments.
sendStringThe send button: circle, rounded or icon (no fill).
fillStringThe field's fill.
textStringThe field's words.
placeholderStringThe placeholder's colour; its words are chat.placeholder.
borderStringThe field's outline.
stripString?The strip behind the field; null for none — the conversation shows through.
shadowShadow?The composer's shadow (GraineThemeTokens.Shadow); null for none.
heightDoubleThe field's height, in dp.
radiusDoubleThe field's corners, in dp.
sendFillString?The send button's fill; null for none.
sendIconStringThe send icon's colour.
iconStringThe paperclip's and the call button's colour.

GraineThemeTokens.Chat.Typing

Read it to draw the typing indicator, shown while Graine.chat.typing is true. data class Typing(val style: String, val text: String, val color: String), as GraineThemeTokens.chat.typing.

FieldTypeMeaning
styleStringloader (the design's loader in a bubble), dots (three fading dots in a bubble), wave (three rising dots in a bubble) or text (the words alone).
textStringThe words for text, and for the header's status line while the agent types; empty says “Typing…”.
colorStringThe dots' or the words' colour.

GraineThemeTokens.Chat.Density

Read it for the conversation's spacing. data class Density(val name: String, val gap: Double, val groupGap: Double, val padX: Double, val padY: Double, val edge: Double), as GraineThemeTokens.chat.density.

FieldTypeMeaning
nameStringcomfortable, compact or spacious — for information: the numbers below are what to draw.
gapDoubleBetween rows, in dp.
groupGapDoubleBetween two messages of one group, in dp.
padXDoubleInside a bubble, left and right, in dp.
padYDoubleInside a bubble, top and bottom, in dp.
edgeDoubleThe conversation's side margins, in dp.

GraineThemeTokens.Chat.Welcome

Read it to open a new conversation as the brand styled it — only one that began here: a restored conversation has no welcome. data class Welcome(val layout: String, val starters: String), as GraineThemeTokens.chat.welcome.

FieldTypeMeaning
layoutStringcentered (the empty chat, before any message), card (a card at the top of the conversation), hero (a full-width block in the header's fill) or minimal (none: the agent's greeting comes first). A card or a hero stays at the top as the conversation grows.
startersStringThe brand's conversation starters (chat.suggestions) as chips or as a list of full-width rows.

GraineThemeTokens.Chat.Rating

Read it to know whether, and how, to ask “How was this chat?”. data class Rating(val show: Boolean, val style: String, val prompt: String), as GraineThemeTokens.chat.rating. Asked once the agent ends the conversation (Graine.chat.ended), as a card at the end of it; the answer of a rating of your own goes to Graine.chat.rate.

FieldTypeMeaning
showBooleantrue: ask, once the agent ends the conversation.
styleStringthumbs, stars or emoji (five faces).
promptStringThe question; empty says “How was this chat?”.

GraineThemeTokens.Chat.Escalation

Read it to know where a button that calls the agent goes. data class Escalation(val call: String), as GraineThemeTokens.chat.escalation.

FieldTypeMeaning
callStringnone, header (in the header) or composer (beside the field; not drawn while composer.mic already calls). Shown only where the agent takes calls and a call can start from the chat.

GraineThemeTokens.Chat.Glass

Read it to draw the chat's frosted pieces. data class Glass(val blur: Double, val opacity: Double), as GraineThemeTokens.chat.glass — null for solid ones. The header (surface or plain), the composer, the chips and every agent bubble with a fill are their colour at opacity, over the wallpaper blurred by blur where the platform can.

FieldTypeMeaning
blurDoubleHow much the wallpaper behind is blurred, in dp.
opacityDoubleHow opaque the frosted pieces are, 0–1.

GraineThemeTokens.Call

Read it to draw a call screen of your own the way the agent's design does. data class Call(…), as GraineThemeTokens.call: the Garage's call screen, resolved — the flat colours every version has drawn, and the look: the backdrop, layout, ring, buttons, the agent's voice, the caption and a look per moment. Colours are #RRGGBB. From a platform SDK that does not hand the look over, each look field is what the flat colours describe: the screen as it has always been drawn.

FieldTypeMeaning
backgroundStringThe screen's fill — the gradient's top when backgroundTo is set.
backgroundToString?The gradient's bottom; null for a solid background.
textStringThe name and the agent's caption.
textMutedStringThe status line, button labels and the user's caption.
avatarStringWhat the avatar shows: logo, glyph or initials.
avatarShapeStringcircle, squircle or rounded-square.
avatarFillStringBehind a glyph or initial.
avatarTextStringThe glyph or initial.
buttonFillStringA control's fill (mute, loudspeaker).
buttonIconStringA control's icon.
buttonActiveFillStringA control's fill while it is on (muted, the loudspeaker).
buttonActiveIconStringA control's icon while it is on.
endFillStringThe end-call button's fill.
endIconStringThe end-call button's icon.
endShapeStringThe end-call button: round or pill.
acceptFillStringThe Answer button's fill.
acceptIconStringThe Answer button's icon.
declineFillStringThe Decline button's fill.
declineIconStringThe Decline button's icon.
callbackFillStringThe Call back button's fill, on a missed call.
callbackIconStringThe Call back button's icon.
captionsBooleanWhether the screen shows the line being said.
timerBooleanWhether it shows how long the call has lasted.
controlsList<String>The in-call controls, in order, from mute, speaker, chat and end.
ringtoneStringThe ring: system (the phone's), graine or soft.
statusTextStatusTextThe screen's words (GraineThemeTokens.Call.StatusText).
presetStringThe ready look the design started from: classic (the call screen as it has always been), aurora, midnight, glass, orbit, daylight, bloom, studio, minimal or mono.
layoutStringHow the screen is laid out: classic, full-bleed, card, orb or minimal.
backdropBackdropThe screen's fill (GraineThemeTokens.Call.Backdrop); background and backgroundTo are its nearest single colours.
inkStringlight when text is light: light status-bar icons go with it.
avatarSizeDoubleThe avatar's size in dp before its layout's share; 112 unless the design says otherwise.
ringsMap<String, String>The ring the avatar wears in each of MOMENTS: none, pulse, ripple or glow — by default a pulse while it rings and nothing otherwise.
avatarRingColorStringThe ring's colour.
buttonStyleStringsolid, glass or outline; Answer, Decline, End and Call back are always filled.
buttonShapeStringcircle, squircle or pill; a pill toggle squares its corners while on.
buttonSizeDoubleThe call's buttons, in dp (64 by default); the ring's and the missed call's are 9/8 of it.
buttonLabelsStringbelow (labels under the buttons) or none; a screen reader still reads them.
actionsMap<String, Action>Every button's colours (GraineThemeTokens.Call.Action), by ACTIONS.
visualizerStringHow the agent's voice is drawn on a connected call: none, bars, wave or orb.
visualizerColorStringThe voice's colour.
visualizerSensitivityDoubleFrom 0 to 1: how quiet a voice still moves it.
captionStyleStringHow the line being said is drawn: plain, card, subtitle or bubble.
captionPositionStringWhere it sits: middle (under the status) or bottom (above the buttons).
captionFillStringBehind a card, subtitle or bubble caption: the ink's opposite, so it only adds contrast.
captionFillAlphaDoublecaptionFill's opacity, 0–1; 0 for a plain caption.
nameSizeDoubleThe name's size; the layout's own unless the design says otherwise.
nameWeightIntThe name's weight, 100–900, in the design's heading family.
statusSizeDoubleThe status line's size; 16 unless the design says otherwise.
statusWeightIntThe status line's weight, 100–900, in the design's body family.
statesMap<String, Look>A moment's own look where it differs from the screen's, keyed by moment (GraineThemeTokens.Call.Look); a moment not listed draws look.
lookLookThe screen's own look: everything drawn in a colour.
fun lookFor(moment: String): Look
companion object { val MOMENTS: List<String>; val ACTIONS: List<String> }

call.lookFor(moment) is what a moment is drawn in: its own look from states, else look. GraineThemeTokens.Call.MOMENTS lists the eight moments a call screen shows — incoming, scheduled, outgoing, connecting, connected, reconnecting, ended, missed — and GraineThemeTokens.Call.ACTIONS every button: answer, decline, end, callback, mute, speaker, chat, close (the missed call's Close).

GraineThemeTokens.Call.StatusText

Read it for the brand's words on the call screen. data class StatusText(val ringing: String, val connecting: String, val ended: String, val scheduled: String?, val missed: String?, val outgoing: String? = null, val reconnecting: String? = null).

FieldTypeMeaning
ringingStringWhile an agent's call rings, such as “Incoming call”.
connectingStringWhile the call connects, such as “Connecting…”.
endedStringOnce a call is over, such as “Call ended”.
scheduledString?While a call Graine rang at a booked time rings; null where the design leaves the SDK's own, “Scheduled call”.
missedString?For a ring nobody answered; null where the design leaves the SDK's own, “Missed call”.
outgoingString?While a call the user placed connects; null where the design leaves it to the connecting words.
reconnectingString?While a connected call recovers its connection; null where the design leaves the SDK's own, “Reconnecting…”.

GraineThemeTokens.Call.Stop

Read it for one colour of the call screen's backdrop. data class Stop(val color: String, val at: Double), in GraineThemeTokens.Call.Backdrop.stops.

FieldTypeMeaning
colorStringThe colour, #RRGGBB.
atDoubleWhere it sits along the backdrop, from 0 (the start) to 1 (the end).

GraineThemeTokens.Call.Backdrop

Read it to fill a call screen of your own the way the agent's design does. data class Backdrop(val type: String, val stops: List<Stop>, val angle: Double = 180.0, val motion: String = "none", val intensity: Double = 0.5, val scrim: Double = 1.0), as GraineThemeTokens.call.backdrop.

FieldTypeMeaning
typeStringsolid (the first colour), linear, radial, mesh (soft glows of each colour) or blurred-avatar (the avatar blurred under the colours).
stopsList<Stop>The colours, in order of at (GraineThemeTokens.Call.Stop): one for solid, 2 to 5 otherwise.
angleDoubleA linear gradient's direction (and the scrim's over a blurred avatar), in degrees as CSS reads them: 180 runs top to bottom.
motionStringnone, drift or breathe. Nothing moves when the design's motion is off or the device asks for reduced motion.
intensityDoubleFrom 0 to 1: how far the motion moves, how far a radial glow reaches, how much of a blurred avatar shows.
scrimDoubleA blurred avatar's colours are drawn over it at this opacity, so the text stays readable over the brightest avatar; 1 for every other type.
companion object { fun flat(background: String, backgroundTo: String?): Backdrop }

GraineThemeTokens.Call.Backdrop.flat(background, backgroundTo) is the fill a call screen drew before the look existed: solid with one colour, or linear from background at the top to backgroundTo at the bottom.

GraineThemeTokens.Call.Action

Read it to colour one button of a call screen of your own. data class Action(val fill: String, val fillAlpha: Double, val icon: String, val stroke: String?, val activeFill: String, val activeIcon: String), in GraineThemeTokens.call.actions.

FieldTypeMeaning
fillStringThe button's colour.
fillAlphaDouble1: filled with fill. Between 0 and 1: glass, fill at this opacity over the backdrop, blurred behind it where the platform can. 0: an outline with nothing inside.
iconStringThe icon's colour.
strokeString?An outline in this colour, 1.5 dp wide; null for none.
activeFillStringMute and speaker while on: the fill, always opaque. For the other buttons, the same as fill.
activeIconStringMute and speaker while on: the icon's colour.
companion object { fun flat(buttonFill: String, buttonIcon: String, buttonActiveFill: String, buttonActiveIcon: String, endFill: String, endIcon: String, acceptFill: String, acceptIcon: String, declineFill: String, declineIcon: String, callbackFill: String, callbackIcon: String): Map<String, Action> }

GraineThemeTokens.Call.Action.flat(…) is every button filled in one colour, as the flat colours of GraineThemeTokens.Call describe them — what actions holds when the look is not handed over.

GraineThemeTokens.Call.Look

Read it to draw one moment of a call screen of your own — ringing, connecting, on the call, ended — in the colours the design gives it. data class Look(val backdrop: Backdrop, val ink: String, val text: String, val textMuted: String, val avatarRingColor: String, val actions: Map<String, Action>, val visualizerColor: String, val captionFill: String, val captionFillAlpha: Double), from GraineThemeTokens.call.lookFor(moment).

FieldTypeMeaning
backdropBackdropThe moment's fill.
inkStringlight or dark: whether text is light.
textStringThe name and the agent's caption; at least 4.5:1 against every colour of the backdrop.
textMutedStringThe status line, button labels and the user's caption; at least 4.5:1 against every colour of the backdrop.
avatarRingColorStringThe ring around the avatar.
actionsMap<String, Action>Every button's colours, by GraineThemeTokens.Call.ACTIONS.
visualizerColorStringThe agent's voice, drawn on a connected call.
captionFillStringBehind a card, subtitle or bubble caption.
captionFillAlphaDoublecaptionFill's opacity; 0 for a plain caption.

Going live

  • Debug logging. GraineConfig(debug = true) in debug builds logs the SDK's traffic with Graine — keys only, never values — to logcat (tag Graine) and the iOS console. Leave it off in release builds.
  • Android, Google Play. On Android 14 and up, Play asks apps that declare USE_FULL_SCREEN_INTENT or the microphone foreground service to justify them; the call screen needs both. An app that never uses calls removes them from its manifest (see the Android reference).
  • iOS. Calls need the Voice over IP and Audio background modes and push notifications; Graine rings only once your VoIP credentials are uploaded in Workspace settings → In-app calling.
  • The version. GraineKmpVersion.NAME says which build of the library the app runs; include it when you ask for support.

GraineKmpVersion

Read it to know which version of the library your app runs — include it when you ask for support.

object GraineKmpVersion

What to expect — The same on Android and iOS.

PropertyTypeMeaning
const val NAME: StringStringThe library's version: "0.13.1" in this release.

Events and listeners

The states are flows that always hold the latest value — Graine.session, Graine.theme, Graine.chat.turns, Graine.chat.status, Graine.chat.upcomingCalls, Graine.voice.state, Graine.calls.state — and the moments are shared flows that are not replayed: Graine.events (each agent's own events), Graine.calls.outcomes and Graine.calls.incoming. Collect the shared flows from app start for what you log or count.

val unread = MutableStateFlow(0)          // the badge on your chat button
val chatOpen = MutableStateFlow(false)    // true while your chat screen shows
scope.launch {
    Graine.events.collect { event ->
        when (event) {
            is GraineEvent.Error -> println("Graine: ${event.message}")   // for your team's logs, never the user
            is GraineEvent.ChatMessage -> if (event.turn.proactive && !chatOpen.value) unread.value += 1
            else -> Unit
        }
    }
}

GraineEvent

Collect it from Graine.events to hear what the agent reports that is not a state.

sealed class GraineEvent

What to expect — Not replayed. A when over it needs an else, so an event added later does not break your build.

CaseMeaning
SessionReady(session: GraineSession)The agent's settings arrived (also in Graine.session) — offer what depends on them.
Caption(role: GraineRole, text: String, live: Boolean)A line of the voice bar's call: the agent's as it is spoken, the user's as it is heard; live while it is still arriving.
VoiceEndedThe voice bar's call is over, however it ended.
Component(component: GraineComponent)The agent drew a component, in the chat or on a call — for an app that draws components itself.
ComponentPending(hint: Map<String, Any?>)A component is on its way and its content is loading — draw a loader.
ChatMessage(turn: GraineChatTurn)The agent finished a message in the chat; turn.proactive means it spoke up unasked — badge your chat if it is closed.
ActionRequested(name: String)The agent asked for one of your actions.
ActionCompleted(name: String, result: GraineActionResult)What one of your actions answered the agent — your handler's result, or the SDK's when it was late or unknown.
Friction(name: String, screen: String?, detail: String)The user seems stuck (stalled_on_step): during a live conversation they have stayed on one screen for a while with a field still to fill. The agent has already been told; badge a control or count it.
MicrophoneDenied(reason: String)The microphone was refused, so the agent cannot hear the user — explain how to allow it.
Error(message: String)Something is misconfigured (a key, an allowed domain). Log it for your team; it is never the user's problem and is not shown to them.

Errors

A suspending function that asks Graine on the user's behalf throws GraineException carrying a GraineErrorCode. Branch on the code; show the message, which is written for the user and never carries the identifier, traits or a push token. Calling anything before Graine.configure throws IllegalStateException instead — a mistake in the app, not a refusal.

GraineException

Catch it around a request to Graine to decide what to do about a refusal.

class GraineException(val code: GraineErrorCode, message: String, val retryAfterSeconds: Int? = null, val reason: String? = null) : Exception(message)

What to expect — code is the stable part — branch on it, never on the message. A refusal made on the device before anything was sent carries the same codes.

PropertyTypeMeaning
val code: GraineErrorCodeGraineErrorCodeBranch on it: the reason in one stable word.
messageStringShow it: Graine's sentence when it sent one, written for the user.
val retryAfterSeconds: Int?Int?Use it to wait before trying again: how long Graine asked (Retry-After), with RateLimited; null when it did not say.
val reason: String?String?Read it for Graine's one word beside the code, when it gave one — which part of a server token failed: scope, user, agent with TokenScope; malformed, signature, unknown_key, issuer, not_yet_valid with TokenInvalid. 0.14.4.

GraineErrorCode

Read it to branch on why a request was refused.

sealed class GraineErrorCode(val wire: String)

What to expect — A code newer than this SDK arrives as Unknown(raw), with Graine's word in it.

PropertyTypeMeaning
wireStringGraine's word for the code — too_soon, network, … — for logs.
CaseMeaning
InvalidKeyThe publishable key was refused. Check it against Embed & Widgets.
OriginRefusedThe agent does not allow apps yet: add app:// to its Allowed domains.
RateLimitedToo many requests; retryAfterSeconds says when to try again, when Graine said.
InvalidRequestA field was missing or malformed — a blank call ID, say.
IdentityRequiredNobody is signed in: identify() the user with the trait the agent's Who is the user? setting names.
DeviceLimitThe user has already reached the agent's limit of devices.
SchedulingOffBooking is switched off for this agent (Calls & scheduling).
TooSoonSooner than the agent's minimum notice.
TooFarFurther ahead than the agent allows.
OutsideWindowThe time falls outside the agent's calling hours, in the user's time zone.
TooManyPendingThe user has already booked the most calls the agent allows.
NotAllowedstartWorkflow: no such workflow, Your app can start this is off for it, or it isn't published.
NotVerifiedstartWorkflow: this device isn't one of the user's signed-in devices, or the agent requires a verified user.
NotFoundNo such booking for this user or install.
UnavailableGraine could not answer just now. Worth trying again later.
NetworkNothing came back: the phone is offline, or Graine could not be reached. Worth trying again.
AppNotAllowedNew in 0.14.4. This app is not one of the agent's apps (Only my apps), or it did not say which app it is. Final: never retried.
AppNotVerifiedNew in 0.14.4. The agent requires a verified app and this install holds no valid app pass; the SDK already proved the app and sent the request once more.
IdentityUnverifiedNew in 0.14.4. The agent requires verified users and the identity sent is not verified; the SDK already asked identityTokenRefresher (when set) and sent the request once more.
TokenRequiredThe agent requires a server token and none came with the request: set GraineConfig.tokenProvider. The SDK already asked it again and tried once more. 0.14.4.
TokenInvalidThe server token could not be checked; reason says why (malformed, signature, unknown_key, issuer, not_yet_valid). Already asked for again and tried once more. 0.14.4.
TokenExpiredThe server token expired, and a fresh one did not come in time. 0.14.4.
TokenScopeThe server token is another agent's (agent) or another user's (user), or lacks the scope this needs (scope) — reason. Never retried. 0.14.4.
KeyRevokedThis publishable key was revoked: update the app with the agent's new key. Never retried. 0.14.4.
BotCheckFailedA website's bot check did not pass. Apps never see it. 0.14.4.
Unknown(raw)A code newer than this SDK, or none at all ("unknown"), carrying the word.

Its functions: from — each with its parameters, what it returns, its errors and an example.

CodewireHTTPMeansRaised byFix
InvalidKeyinvalid_key401The publishable key is not one, or belongs to no agentEvery request to GraineCopy the key again from Agent → Embed & Widgets → Install
OriginRefusedorigin_refused403app:// is missing from the agent's Allowed domainsEvery requestAdd app://
RateLimitedrate_limited429Too many requests from this install, key or addressEvery requestWait retryAfterSeconds, then retry
InvalidRequestinvalid_request400, 422A field is missing or malformedscheduleCall, cancelScheduledCallFix the request
IdentityRequiredidentity_required400Nobody is identified, or the identifier is a placeholdermemories, forgetMemory, bookings that need a useridentify() with the identifier first
DeviceLimitdevice_limit403This install is not one of the user's allowed devicesmemories, forgetMemory, newConversation, scheduleCallSign out on another device, raise Devices per user, or Reset devices for the user
SchedulingOffscheduling_off403 (on the device first)Users may not book from the appscheduleCallTurn it on, or hide booking when bookingAvailable is false
TooSoontoo_soon400 (on the device first)Earlier than earliest(now)scheduleCallOffer times from earliest(now)
TooFartoo_far400 (on the device first)Later than latest(now)scheduleCallOffer times up to latest(now)
OutsideWindowoutside_window400The time falls outside the agent's calling hours, in the user's time zonescheduleCallShow the message (it names a time that works); offer another time
TooManyPendingtoo_many_pending409The user already has the most calls waitingscheduleCallCancel one first
NotAllowednot_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
NotVerifiednot_verified403This device isn't one of the user's signed-in devices, or the agent requires a verified userstartWorkflowSign the user in on this device, raise Devices per user, or verify the user
NotFoundnot_found404No such booking for this user or installcancelScheduledCallRead scheduledCalls() again
Unavailableunavailable502, 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 creditEvery requestRetry with backoff; check the agent is on and the workspace has credit
Networknetwork—No answer came back: offline, or the connection droppedEvery requestRetry when online
AppNotAllowedapp_not_allowed403Only my apps is on and this app (package or bundle id, signing certificate or Team ID) is not listedEvery requestAdd the app under the agent's Your apps; never retried
AppNotVerifiedapp_not_verified403Require a verified app is enforced and this install could not prove itselfEvery request but the agent's settingsAdd Play Integrity (Android) or the App Attest capability (iOS) and check the setup, or register this build's debug token
IdentityUnverifiedidentity_unverified403Require verified users is enforced and the identity sent is not verifiedmemories, forgetMemory, past sessions, bookingsPass identityToken to identify, or set identityTokenRefresher
TokenRequiredtoken_required401Server tokens are enforced and no token cameEvery request, the chat, callsSet GraineConfig.tokenProvider; check it answers for the signed-in user
TokenInvalidtoken_invalid401The token is malformed, wrongly signed, from an unknown key or issuer, or not yet valid (reason)Every request, the chat, callsMint it with POST /v2/client-tokens; pass it as it came
TokenExpiredtoken_expired401The token expired and no fresh one came in timeEvery request, the chat, callsCheck your provider answers within a few seconds
TokenScopetoken_scope403Another agent's or user's token, or one without the scope this needs (reason: agent, user, scope)Every request, the chat, callsMint it for this agent, the user identify() names, and the scopes the app uses
KeyRevokedkey_revoked401The publishable key was revokedEvery request, the chat, callsShip the agent's new key
Unknown(raw)the wordotherA code newer than the SDKEvery requestLog the code and message; show the message

When Graine refuses a server token or the key, a suspending request throws the code; a chat that cannot connect fails (GraineChat.failed) and does not retry by itself; a call that cannot start fails with the code in its error (at its start: "key_revoked: …").

When the bar or chat cannot start, the reason arrives as GraineEvent.Error, not as an exception: key_missing, key_malformed (publishable keys start with pk_live_), key_unknown (copy the key again), no_origin (add app://), no_domains_configured (the list is empty), origin_not_allowed, and not_configured (high-quality audio is not enabled for the workspace; calls use the standard path). A refused microphone arrives as GraineEvent.MicrophoneDenied.

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 user3 by default (1–10)At most this many upcoming calls per user
Devices per user2 by default (1–5)Devices per user; idle devices free their place after 30 days
Rings per user per day3 by default (1–10)Ring each user at most, in the user's own day
Quiet period after a decline6 hoursNo ring for that user
Notice and horizon5 minutes (2–1440) · 14 days (1–30)With at least this much notice · Booked at most this far ahead
Ring time · re-ring45 s (20–60) · once after 10 min (0–120)Ring for · After a missed call, ring once more after
Lateness10 minutesA booked call more than 10 minutes late is not rung
Booking reason · variables120 characters · 12 variables, about 1 KBBookings and calls
Memories listedAt most 100, newest firstmemories()
Conversation kept50 messages, 7 days after the lastConversations that continue
Action handlers6 secondsAfter that, the agent is told the action was not done

Lower-level building blocks

Reading Graine's own words into the SDK's types — for a server or a bridge that passes them around. An integration does not need them.

GraineCallStatus.from

Call it to turn a status word from Graine (or your server) into a GraineCallStatus.

fun from(wire: String?): GraineCallStatus

Case and surrounding spaces do not matter. No word at all reads as Scheduled, as the native SDKs read it.

ParameterTypeDefaultMeaning
wireString?requiredGraine's word, such as "no_device".

Returns — GraineCallStatus — a known status, or Unknown(raw). Example value: GraineCallStatus.NoDevice.

Errors — none.

val status = GraineCallStatus.from("completed")

GraineCallSource.from

Call it to turn a source word from Graine into a GraineCallSource.

fun from(wire: String?): GraineCallSource?

sdk and app are App; case does not matter.

ParameterTypeDefaultMeaning
wireString?requiredGraine's word, such as "sdk".

Returns — GraineCallSource? — null for no word at all. Example value: GraineCallSource.App.

Errors — none.

val source = GraineCallSource.from("dashboard")

GraineErrorCode.from

Call it to turn an error word from Graine (or a native SDK) into a GraineErrorCode.

fun from(wire: String?): GraineErrorCode

Case does not matter; a blank word is Unknown("unknown").

ParameterTypeDefaultMeaning
wireString?requiredThe word, such as "too_soon".

Returns — GraineErrorCode — a known code, or Unknown(raw). Example value: GraineErrorCode.TooSoon.

Errors — none.

val code = GraineErrorCode.from("rate_limited")

GraineCallTransport.ofCall

Call it to turn a platform SDK's word for what carried a call into a GraineCallTransport — the way GraineCallInfo.transport is read.

fun ofCall(wire: String?): GraineCallTransport?

Case does not matter. Only what a call can run on is read: auto is something an app chooses, never what carried a call.

ParameterTypeDefaultMeaning
wireString?requiredThe word, such as "webrtc".

Returns — GraineCallTransport? — WEBRTC or WEBSOCKET; null for any other word, or none. Example value: GraineCallTransport.WEBRTC.

Errors — none.

val transport = GraineCallTransport.ofCall("websocket")

What's new in 0.13.0

  • Chat window v2. GraineChat() (and GraineViews.chat() on iOS) draws the chat style chosen in the Garage — Classic, the chat as it has always looked and the default, or Soft, Bold, Glass, Minimal, Crisp, Cozy, Calm, Compact or Lively — with every piece tunable: the header, bubbles, times, wallpaper, chips, cards, composer, typing indicator, welcome, the end-of-chat rating and a call button. They are the Android and iOS SDKs' own windows, so nothing changes in your app, and a design saved before draws exactly as it did (The Garage → The chat window).
  • New chat members, all optional — each agent's chat has its own: quickReplies and sendQuickReply(reply), the replies the agent suggests for its message (GraineQuickReply); ended, the agent ended the conversation; rating, rate(style, value) and onRated, the user's end-of-chat rating, recorded on the conversation and heard once per rating (GraineChatRating); pin(pin), pin(null) and pinned, what the conversation is about, drawn under the header or atop the conversation as the design says and never sent to the agent (GraineChatPin); onAttach, the composer's paperclip, shown where the design has one and only while it is set. What each looks like to the user is in the chat guide.
  • Every piece of the chat window, for UI of your own: GraineThemeTokens.Chat gains preset, header, bubbles, timestamps, wallpaper, chips, cards, composer, typing, density, welcome, rating, escalation and glass, as the chat style resolved them — the same values on Android and iOS. A design from before chat styles carries the classic chat its own colours imply; a GraineThemeTokens.Chat made by hand carries Graine Classic's.
  • On iOS, link GraineInApp of this version: with an older one the new states stay empty and the new controls do nothing.
  • The full list of changes is in the Changelog.

What's new in 0.9.0

  • WebRTC calls. Add each platform's WebRTC module to the app and native calls — the ones the person places and the ones Graine rings — carry their audio over WebRTC: steadier on a weak network, with the same ring, call screen and outcomes. GraineCallsConfig(callTransport = …) chooses (GraineCallTransport); GraineCallInfo.transport and transportFallbackReason say which one carried a call (WebRTC calls).
  • The brand's design tokens in shared code: Graine.theme (and each agent's theme), a GraineThemeTokens, following the phone between light and dark.
  • Graine.currentVariables() (and each agent's): every prompt variable the next conversation carries, merged in precedence order.
  • The chat: clear() empties the screen only; upcomingCalls, refreshUpcomingCalls() and cancelUpcomingCall(id) give a chat of your own the Upcoming calls card; answerWidget(id, data, summary) answers a component you draw yourself.
  • What was said on a voice-bar call, and the captions switch: Graine.voice.state carries captions (the last 12 lines) and captionsOn; setCaptionsOn(on) and clearCaptions().
  • On Android, chat.status is RECONNECTING whenever the Android SDK is making the chat again — after a first try that failed too, as on iOS.
  • scheduleCall's own refusals say the booking sheet's words: “Booking a call isn't available right now”, “Pick a time at least 5 minutes from now”, “Pick a time within 14 days”.
  • On iOS, link GraineInApp of this version (and GraineInAppRTC at the same version): with an older one the new chat, voice-bar, design and variables members stay empty or do nothing.
  • The full list of changes is in the Changelog.

What's new in 0.8.0

  • Booking a call, drawn by the SDK. Graine.presentBooking(reason) (and GraineAgent.presentBooking) shows the native SDK's booking sheet — the day, the time (each platform's own time picker), the phone's time zone, What's it about? (optional) and Book call — in the agent's design, and returns the booked call, or null when the user closed it without booking. Refusals stay in the sheet as one line.
  • bookingAvailable, on Graine and each agent: Graine rings this phone, the agent lets users book, and the user is identified. Show your own “Call me” button only then.
  • On iOS the sheet is GraineInApp's, so link GraineInApp 0.8.0: with an older one, bookingAvailable is false and presentBooking throws Unavailable, and the app keeps running.
  • On iOS, VoiceOver now reaches into GraineChat(), GraineCallScreen() and GraineAgentBar().
  • The SDK's chat windows (GraineChat(), GraineViews.chat()) offer Book a call in their Upcoming calls card by the same rule.
  • Calls hold up on weak networks (the native SDKs, 0.8.0): on Android a slow uplink no longer holds the call up, hanging up lets go of the microphone at once, and a connection that has gone silent for 50 seconds ends the call; on iOS a call that cannot connect fails within 20 seconds, and one whose audio never starts says so.
  • The full list of changes is in the Changelog.

Every symbol, A to Z

Every public symbol of the Kotlin Multiplatform SDK — 1039 in all — by name, each linked to where this page documents it: a type or function first, then its members.

On this page

Requirements, install, permissions and initialisationWebRTC calls (optional)Install and the first answerGraine.configureGraine.configure (Android, with a context)GraineGraine.session (the agent's settings)GraineConfigGraineSessionGraineInitProviderIdentity, memory and conversations that continueGraine.identifyGraine.setMemoryGraine.memoriesGraine.forgetMemoryGraineAgent.memoriesGraineAgent.forgetMemoryGraineChat.newConversationGraineChat.refreshPastSessionsGraineChat.loadMorePastSessionsGraineChat.sessionTranscriptGraineMemoryYour app and your usersGraine.setIdentityTokenGraine.identityTokenRefresherGraine.prepareAppVerificationGraineAgent.prepareAppVerificationGraine.verification (what Graine has proven)GraineAgent.verificationGraineVerificationGraineAppVerdictGraineUserVerdictGraine.debugTokenMode (development mode)Graine.debugTokenGraineDebugTokenModeChatGraineChatGraineChat.openGraineChat.closeGraineChat.shownGraineChat.sendGraineChat.retryGraineChat.clearGraineChat.refreshUpcomingCallsGraineChat.cancelUpcomingCallGraineChat.sendQuickReplyGraineChat.rateGraineChat.pinGraineChatTurnGraineChatSessionGrainePastSessionsGraineSessionSummaryGraineSessionChannelGraineSessionDirectionGraineSessionTranscriptGraineSessionTurnGraineDeliveryGraineChatChannelGraineChatStatusGraineChatSizeGraineRoleGraineQuickReplyGraineChatRatingGraineChatPin (the pinned card)GraineChat (Compose)GraineViewsGraineViews.chatGraineChatRowsGraineChatRows.buildGraineChatRows.dayLabelGraineChatRows.callLabelGraineChatRows.offersStartersGraineChatRows.offersNewConversationGraineChatRowGraineChatDayThe voice barGraineVoiceGraineVoice.startGraineVoice.endGraineVoice.setMutedGraineVoice.setCaptionsOnGraineVoice.clearCaptionsGraineVoiceInfoGraineVoiceStatusGraineCaptionGraineTransportGraineAgentBarGraineViews.voiceBarGraine.onRequestPermissionsResultSeveral agents in one appGraine.agent (by name)GraineAgentScreen context, actions and componentsGraine.setScreenGraine.updateFieldGraine.removeFieldGraine.clearScreenGraine.trackGraine.reportEventGraineAgent.reportEventGraine.tapGraine.noteInteractionGraine.setVariablesGraineAgent.setVariablesGraine.currentVariablesGraineAgent.currentVariablesGraine.registerActionGraineAgent.registerActionGraineScreenGraineScreen.JourneyGraineFieldGraineFieldStatusGraineActionResultGraineActionResult.StatusGraineActionResult.okGraineActionResult.refusedGraineActionResult.errorGraineComponentGraineComponent.tapForGraineComponentTapGraineComponentTapCallGraineComponentBlockGraineComponentBlockTypeGraineComponentStyleGraineComponentPresetGraineComponentImageSizeGraineComponentDensityGraineComponentButtonGraineComponentSurfaceGraineComponentPlatformGraineComponentSelectGraineAgent.componentGraineChat.answerWidgetGraineChat.dismissWidgetCalls the user placesGraineCallsGraineCalls.configureGraineCallsConfigGraineCallTransportGraineCalls.startCallGraineCalls.prepareCallGraineAgent.startCallGraineAgent.prepareCallGraineCalls.endGraineCalls.setMutedGraineCalls.setSpeakerGraineCalls.speakerByDefaultGraineCallInfoGraineCallStateGraineCallPhaseGraineCallOutcomeGraineCallOutcome.KindGraineCallConnectionGraineCallConnection.AudioGraineCallScreenGraineViews.callScreenCalls Graine ringsGraineCalls.enableVoIPPushesGraineCalls.onNewTokenGraineCalls.handlePushGraineCalls.answerGraineCalls.declineGraineCalls.callBackGraineCalls.dismissMissedCallGraineIncomingCallGraineMissedCallThe agent's face (Avatar)GraineAvatarGraineAvatarStateGraineAvatarState.PhaseGraineAvatarFace (Compose)GraineViews.avatarViewGraineCalls.showsAvatarThe face stageGraineAvatarStage (Compose)GraineViews.avatarStageGraineStageGraineStageStateGraineStageCallGraineStagePhaseGraineStageControlGraineStageCallsGraineStageCaptionGraine.stagePermissions and the setup checkGraineCalls.callPermissionsGraineCalls.requestCallPermissionsGraineCalls.openCallSettingsGraineCalls.callSetupProblemsGraineCallPermissionGraineCallPermissionStatusGraineCallPermissionsGraineCallSetupProblemBooking with the SDK's sheetGraine.bookingAvailableGraine.bookingUnavailableReasonGraine.bookingStateGraineBookingStateGraine.bookingSlotsGraine.presentBookingGraineAgent.bookingAvailableGraineAgent.presentBookingGraineAgent.bookingUnavailableReasonGraineAgent.bookingStateGraineAgent.bookingSlotsThe scheduled-calls listGraineSchedulingRulesGraineSchedulingRules.earliestGraineSchedulingRules.latestGraineCallingWindowGrainePlatformGraine.scheduleCallGraineAgent.scheduleCallGraine.scheduledCallsGraineAgent.scheduledCallsGraine.cancelScheduledCallGraineAgent.cancelScheduledCallGraineScheduledCallGraineCallStatusGraineCallSourceWorkflows your app startsGraine.startWorkflowGraineAgent.startWorkflowGraineWorkflowRunDesignGraine.themeGraineThemeTokensGraineThemeTokens.ColorsGraineThemeTokens.FontGraineThemeTokens.Font.ScaleGraineThemeTokens.Font.WeightsGraineThemeTokens.Font.PairGraineThemeTokens.ShapeGraineThemeTokens.Shape.RadiusGraineThemeTokens.SpacingGraineThemeTokens.ElevationGraineThemeTokens.ShadowGraineThemeTokens.OffsetGraineThemeTokens.MotionGraineThemeTokens.IconsGraineThemeTokens.GlyphGraineThemeTokens.GlassGraineThemeTokens.ChatGraineThemeTokens.Chat.HeaderGraineThemeTokens.Chat.FillGraineThemeTokens.Chat.BubblesGraineThemeTokens.Chat.BubbleSideGraineThemeTokens.Chat.TimestampsGraineThemeTokens.Chat.WallpaperGraineThemeTokens.Chat.ChipsGraineThemeTokens.Chat.CardsGraineThemeTokens.Chat.ComposerGraineThemeTokens.Chat.TypingGraineThemeTokens.Chat.DensityGraineThemeTokens.Chat.WelcomeGraineThemeTokens.Chat.RatingGraineThemeTokens.Chat.EscalationGraineThemeTokens.Chat.GlassGraineThemeTokens.CallGraineThemeTokens.Call.StatusTextGraineThemeTokens.Call.StopGraineThemeTokens.Call.BackdropGraineThemeTokens.Call.ActionGraineThemeTokens.Call.LookGoing liveGraineKmpVersionEvents and listenersGraineEventErrorsGraineExceptionGraineErrorCodeRate limits and quotasLower-level building blocksGraineCallStatus.fromGraineCallSource.fromGraineErrorCode.fromGraineCallTransport.ofCallWhat's new in 0.13.0What's new in 0.9.0What's new in 0.8.0Every symbol, A to Z