Masheev Developers

Open Markdown · Agent index

@masheev/embed-sdk

Developer SDK access is beta. Start with an existing chat inbox from the dashboard. For guided implementation, use Integrate with AI. See authentication for signed customer identity and business tools for backend access.

Embeddable chat widget for any website. Available as a script tag, React hook, or headless API with full control over the UI.

Installation

pnpm add @masheev/embed-sdk

Or load via script tag (no build step):

<script src="https://unpkg.com/@masheev/embed-sdk"></script>

Entry Points

Import pathUse case
@masheev/embed-sdk/jsVanilla JS — iframe widget with postMessage API
@masheev/embed-sdk/reactReact — hook wrapper around the iframe widget
@masheev/embed-sdk/headlessReact and React Native — direct WebSocket API, bring your own UI
@masheev/embed-sdk/headless/turnstileWeb only — Cloudflare Turnstile verification for the headless provider

Quick Start

Script Tag

<script src="https://unpkg.com/@masheev/embed-sdk"></script>
<script>
  Masheev.init({
    inboxId: "your-inbox-id",
    mode: "chat-widget",
    position: "right",
    agentName: "Support",
  });

  Masheev.on("message", function (msg) {
    console.log(msg.role, msg.content);
  });
</script>

React (iframe)

import { useEffect } from "react";
import { useMasheev } from "@masheev/embed-sdk/react";

function App() {
  const { open, isReady, on } = useMasheev({
    inboxId: "your-inbox-id",
    mode: "chat-widget",
    position: "right",
    agentName: "Support",
  });

  useEffect(() => {
    const unsub = on("message", ({ role, content }) => {
      console.log(role, content);
    });
    return unsub;
  }, [on]);

  return (
    <button onClick={open} disabled={!isReady}>
      Chat with us
    </button>
  );
}

Headless (custom UI)

import { MasheevProvider, useMasheev } from "@masheev/embed-sdk/headless";

function Chat() {
  const { messages, sendMessage, isLoading } = useMasheev();

  return (
    <div>
      {messages.map((m) => (
        <div key={m.id} className={m.role}>
          {m.content}
          {m.isLoading && <span>Typing...</span>}
        </div>
      ))}
      <input
        onKeyDown={(e) => {
          if (e.key === "Enter") {
            sendMessage(e.currentTarget.value);
            e.currentTarget.value = "";
          }
        }}
      />
    </div>
  );
}

function App() {
  return (
    <MasheevProvider
      inboxId="your-inbox-id"
      turnstileSiteKey="your-site-key"
      customerInfo={{ name: "Jane", email: "jane@example.com" }}
    >
      <Chat />
    </MasheevProvider>
  );
}

JS SDK API

When loaded via script tag the global Masheev object exposes these methods. The same functions are available from @masheev/embed-sdk/js.

init(config)

Initialize the widget. Creates an iframe and attaches it to the page.

Masheev.init({
  inboxId: "inbox_abc", // required
  mode: "chat-widget", // "chat-widget" | "prompt-input" | "embedded"
  position: "right", // "left" | "right"
  baseUrl: "https://iframe.masheev.com",
  placeholder: "Ask anything...",
  agentName: "Support Bot",
  agentTitle: "AI Assistant",
  questions: ["How do I get started?", "Pricing?"],
  privacyUrl: "https://example.com/privacy",
  requireConsent: false, // true to show consent gate (regulated industries)
  user: {
    name: "Jane Doe",
    email: "jane@example.com",
    phone: "+1234567890",
    userId: "usr_123",
    company: "Acme Inc",
    customAttributes: { plan: "pro" },
  },
});

open() / close() / toggle()

Control widget visibility.

Masheev.open();
Masheev.close();
Masheev.toggle();

sendMessage(text)

Send a message programmatically.

Masheev.sendMessage("I need help with billing");

updateContext(context)

Update user context mid-conversation.

Masheev.updateContext({ name: "Jane Doe", email: "jane@acme.com" });

identify(user) / logout()

Attach a signed-in user of your app, or forget the visitor when they sign out. userHash is HMAC-SHA256 of userId, computed on your server with the inbox's identity secret (see Signed widget identity).

Masheev.identify({ userId: "u_42", userHash, name: "Jane Doe", email: "jane@acme.com" });

// On sign-out: the widget clears its stored visitor and conversation,
// and the next message starts as a new contact.
Masheev.logout();

Both calls are queued until the widget is ready and replayed in call order. The identity is sent again if the widget frame reloads.

setQuestions(questions)

Replace the list of suggested questions.

Masheev.setQuestions(["How does pricing work?", "Do you offer a free trial?"]);

on(event, callback) / off(event, callback)

Subscribe to widget events. on() returns an unsubscribe function.

const unsub = Masheev.on("message", (msg) => {
  console.log(msg.role, msg.content);
});

// later
unsub();

isReady()

Returns true once the iframe has loaded and is accepting commands.

destroy()

Remove the iframe and clean up all listeners.

version

SDK version string (matches the installed package version).

Protocol version

The SDK adds sdkv (its version), proto (the host protocol, currently 2) and hvw (the page's viewport width) to the widget URL. The widget reports the protocol it speaks in the ready event, available afterwards as sdk.protocol (1 for widgets that predate it). Either side ignores messages it does not know.


Configuration

MasheevConfig

PropertyTypeDefaultDescription
inboxIdstring—Required. Inbox to connect to.
modeWidgetMode"chat-widget"Display mode (see below).
position"left" | "right""right"Bubble position (chat-widget mode only).
colorScheme"light" | "dark" | "auto""light"Light or dark appearance. "auto" follows the host page (.dark / .light class or data-theme), then the OS setting. Change it after init with updateColorScheme().
themeWidgetTheme—Appearance overrides (see WidgetTheme). Ignored when the inbox has a saved theme.
baseUrlstring"https://iframe.masheev.com"Widget iframe host.
placeholderstring—Input placeholder text.
agentNamestring—Agent display name in the header.
agentTitlestring—Agent role / title.
questionsstring[]—Suggested questions shown to the user.
privacyUrlstring—Your privacy policy. Overrides the URL in the inbox settings. With neither, the widget names your business instead and never links to Masheev's policy.
requireConsentbooleanfalseShow a consent gate before any chat session starts, in every mode (see AI Disclosure & Consent).
hideHeaderbooleanfalseHide the chat header (embedded mode only). Useful when you provide your own header.
containerIdstring—DOM element ID to mount the iframe into (default: document.body). Useful for embedded mode.
userUserContext—Pre-fill user identity (see below).
toolsClientToolDefinition[]—Client-side tools the AI can invoke (see Agent Actions).
instructionsstring—Instructions for the AI explaining how to use registered tools.
greetingstring—Static opening message shown instantly, without waiting for the model. Use it for fixed openers in guided flows.
localestringpage languageLanguage of the widget's own text: en, fr, es or de (fr-CA works). Defaults to the page's <html lang>, then the browser language, then English. Your greeting and agent name are shown as you wrote them.
containerHTMLElement—Element to mount the iframe into. Takes precedence over containerId.
sessionMode"persistent" | "ephemeral" | "workflow""persistent""persistent" resumes conversations across page loads; "ephemeral" starts a fresh one each time.
workflowWorkflowConfig—Guided multi-step flow (see Workflows).
debugbooleanfalseLog postMessage traffic and state transitions to the console.

WidgetTheme

Every field is optional. Fields you leave out come from the template preset.

PropertyTypeDefaultDescription
template"minimal" | "modern" | "corporate" | "playful" | "dark" | "custom""modern"Preset palette. The fields below override individual values on top of it.
primaryColorstringfrom templateSend button, focus ring, unread indicator, selected chips.
backgroundColorstringfrom templatePanel background. The widget derives its surfaces and hairlines from this colour.
textColorstringfrom templateBody text. Adjusted automatically if it does not reach 4.5:1 against the background.
userBubbleColorstringprimaryColorBackground of the visitor's own messages.
userBubbleTextColorstringderivedText inside the visitor's messages. Contrast is enforced the same way as textColor.
fontFamilystringsystem stackFont stack for the whole widget. See the caveat below.
fontSize"sm" | "base" | "lg""base"Body text size. Every other size in the widget scales from it.
messageStyle"plain" | "bubble""plain""plain" renders AI replies as text on the panel surface. "bubble" keeps them inside a bubble.
launcherStyle"solid" | "surface""solid""solid" fills the launcher with primaryColor. "surface" raises it on the canvas with a hairline and draws the glyph in primaryColor, so a dark launcher stays visible on a dark host.
logoUrlstring—Image shown in the header instead of the default agent avatar.
headerTitlestringagent nameHeader title text.
poweredBybooleantrueShow the "Powered by Masheev" line in the footer.
Masheev.init({
  inboxId: "your-inbox-id",
  colorScheme: "auto",
  theme: {
    template: "minimal",
    primaryColor: "#2563eb",
    userBubbleColor: "#2563eb",
    fontSize: "base",
    messageStyle: "plain",
  },
});

Precedence. The theme saved on the inbox in the Masheev dashboard wins. The theme you pass here applies only when the inbox has no saved theme, so a customer's own appearance settings are never overridden by embed code.

Dark mode. Each template ships a light and a dark preset. When the resolved scheme is dark the widget uses the template's dark preset. Colours you set explicitly are used as given in both schemes — they are not recoloured for dark mode. Set the colours you want for dark yourself, or use colorScheme: "light" to pin the widget to one scheme.

fontFamily caveat. The widget runs in an iframe that does not load web fonts. Only fonts already installed on the visitor's device and the generic families (sans-serif, serif, monospace) render. Anything else falls back to the system stack. The value is sanitized before use, so url(), braces and semicolons are stripped.

Appearance editor. The same fields are editable per inbox in the dashboard under the inbox's appearance settings, with a live preview of the widget in light and dark.

UserContext

PropertyTypeDescription
namestringUser name
emailstringUser email
phonestringUser phone
userIdstringYour external user ID
companystringCompany name
customAttributesRecord<string, string | number | boolean>Arbitrary metadata

Widget Modes

The SDK creates and owns the widget's <iframe>. It sizes the frame itself: small while closed, large while open, and again whenever the widget posts a resize message (for example when the on-screen keyboard appears). The host page sets no dimensions and should not style the frame — apart from embedded mode, where the container you provide defines the available space.

chat-widget (default)

A floating launcher in the corner of the page. Tapping it opens a chat panel above the launcher; on small screens the panel fills the viewport. The position prop puts the launcher on the left or the right.

prompt-input

A single input pill docked at the bottom of the page, no launcher. Focusing it reveals suggested questions; sending a message opens a transcript panel above the pill, and the pill stays as the composer. Good for AI-first pages where chat is the primary action.

embedded

Fills 100% of its parent container. Use this when you want to place the widget inside a specific element rather than floating it over the page. The parent must have defined dimensions.

Mobile keyboard: in embedded mode the host owns the container's size, so the on-screen keyboard does not automatically shrink the widget. If you embed it full-screen on mobile, size the container against the visual viewport (e.g. height: 100dvh or a window.visualViewport listener) so the composer stays above the keyboard, or use chat-widget / prompt-input mode, which dock above the keyboard automatically.


Masheev tells end users that they are talking to an AI assistant. This helps you meet AI-disclosure rules such as Article 50 of the EU AI Act and US state chatbot laws, but you remain responsible for any other notice your use requires.

How Disclosure Works

When an AI agent is configured on an inbox, the server builds the AI identity notice for each channel:

  • Chat widget — disclosure is shown as a note above the conversation, before the greeting (screen readers announce it first), and the header names the agent as "AI agent". The prompt-input footer starts with "AI-powered ·". AI-written messages carry data-ai-generated="true" in the page. The greeting message itself stays conversational.
  • Headless SDK / API — disclosure is returned with every session when an AI agent is configured; show it before the conversation. Unless the session request sends disclosureRendered: true (only do this if your UI shows the disclosure), Masheev also adds it to the start of the first AI reply.
  • SMS: every AI reply begins with the disclosure.
  • WhatsApp and Instagram: the first AI reply in each conversation begins with the disclosure.
  • Email: every AI reply ends with a disclosure footer.
  • Voice: the call opens with the disclosure and a transcription notice, before your greeting.

The notice names the AI agent and your organization. You can add your own text after it per channel in the AI Agent settings (Dashboard > AI Agents > Disclosure tab). You cannot remove or replace it.

Your added text supports the {{agentName}} and {{orgName}} variables.

For regulated industries that require explicit data-processing consent before a conversation, set requireConsent: true:

Masheev.init({
  inboxId: "inbox_abc",
  requireConsent: true,
  privacyUrl: "https://example.com/privacy",
});

When enabled, the widget shows a consent gate before the chat UI, in every mode. The user must check a consent checkbox and click "Start Chat" to proceed. No session is created and no visitor identifier is stored until then.

Consent is stored only on Masheev's servers, on the contact record (for GDPR Art. 7(1) proof): the contact's consent.dataProcessing and consent.dataProcessingAt fields. The browser stores no consent flag. A returning visitor whose browser still holds its visitor identifier is not asked again while the consent wording is unchanged. See Privacy and cookies for everything the widget stores and when.

When the widget sends consent data, it is included in the session creation request:

{
  "inboxId": "string",
  "consent": { "timestamp": "2025-01-15T10:30:00.000Z", "version": "ai-conversations-v1" }
}

The server merges the consent into the contact's existing consent record without overwriting other consent fields.


Agent Actions

Agent Actions let the AI call functions in your app during a conversation. Register tools with the SDK, and the AI agent can invoke them to perform actions like creating accounts, navigating pages, or fetching app state — with results flowing back to the AI for multi-step workflows.

Script Tag (JSON Schema)

<script src="https://unpkg.com/@masheev/embed-sdk"></script>
<script>
  Masheev.init({
    inboxId: "inbox_abc",
    tools: [
      {
        name: "register_org",
        description: "Register a new organization account",
        parameters: {
          type: "object",
          properties: {
            name: { type: "string", description: "Organization name" },
            email: { type: "string", description: "Admin email" },
            plan: { type: "string", enum: ["free", "pro", "enterprise"] },
          },
          required: ["name", "email"],
        },
        needsApproval: true,
        execute: async function (args, options) {
          options.onProgress("Creating organization...");
          var org = await myApp.createOrg(args);
          return { success: true, data: { orgId: org.id } };
        },
      },
    ],
    instructions:
      "You can help users register organizations. Ask for the org name, email, and plan, then use register_org to create it.",
  });
</script>

React / Headless (Zod schemas)

The headless SDK supports Zod schemas for full TypeScript inference on tool arguments:

import { MasheevProvider, useMasheev } from "@masheev/embed-sdk/headless";
import { clientTool } from "@masheev/embed-sdk/headless";
import { z } from "zod";

const registerOrg = clientTool({
  name: "register_org",
  description: "Register a new organization account",
  parameters: z.object({
    name: z.string().describe("Organization name"),
    email: z.string().email().describe("Admin email"),
    plan: z.enum(["free", "pro", "enterprise"]).describe("Billing plan"),
  }),
  needsApproval: true,
  execute: async (args, { onProgress }) => {
    // args is fully typed: { name: string; email: string; plan: "free" | "pro" | "enterprise" }
    onProgress("Creating organization...");
    const org = await createOrg(args);
    return { success: true, data: { orgId: org.id } };
  },
});

function App() {
  return (
    <MasheevProvider
      inboxId="inbox_abc"
      tools={[registerOrg]}
      instructions="You can help users register organizations."
    >
      <Chat />
    </MasheevProvider>
  );
}

Zod v4+ is required as a peer dependency when using Zod tool definitions. The SDK uses Zod's native toJSONSchema() for schema conversion — no additional libraries needed.

Tool Definition

PropertyTypeRequiredDescription
namestringYesTool name (alphanumeric + underscores, max 64 chars).
descriptionstringYesWhat the tool does (max 500 chars). Helps the AI decide when to use it.
parametersobjectYesJSON Schema object describing the input, or a Zod schema (headless only).
needsApprovalbooleanNoWhen true, the AI asks the user for confirmation before executing.
executefunctionYesAsync function called when the AI invokes the tool. Receives (args, options).

Tool Result

The execute function must return a ClientToolResult:

interface ClientToolResult {
  success: boolean;
  data?: Record<string, unknown>; // Structured data for the AI
  error?: string; // Human-readable error message
  display?: "text" | "card" | "silent"; // UI hint (default: "text")
}

Progress Reporting

The execute function receives an onProgress callback to report status during long-running operations:

execute: async (args, { onProgress }) => {
  onProgress("Validating input...");
  await validate(args);
  onProgress("Creating account...");
  const result = await createAccount(args);
  return { success: true, data: result };
};

Progress messages are shown as typing indicators in the chat.

Dynamic Tool Updates

Add or remove tools during a session with updateTools():

// JS SDK
Masheev.updateTools([/* new tool definitions */]);

// React hook
const { updateTools } = useMasheev({ inboxId: "..." });
updateTools([/* new tool definitions */]);

// Headless
const { updateTools } = useMasheev();
await updateTools([/* new tool definitions */]);

Instructions

The instructions field tells the AI how and when to use your tools. It is appended to the AI agent's system prompt:

Masheev.init({
  inboxId: "inbox_abc",
  tools: [addToCartTool, getInventoryTool],
  instructions: `You are a shopping assistant. When the user asks about product availability,
    use get_inventory first. When they want to buy something, use add_to_cart.
    Always confirm the item and quantity before adding to cart.`,
});

Error Handling

ScenarioWhat happens
Tool throws an errorSDK catches it and sends { success: false, error: "..." } back to the AI
Tool times out (iframe: 60s default, per-tool timeout; headless: 25s)SDK sends a timeout error; AI responds gracefully
Unknown tool nameSDK sends an error result immediately
Network failure posting resultSDK retries once after 2s; server has a 30s fallback timeout

All errors are sent back to the AI as tool results, so it can self-correct or respond to the user.

Limits

LimitValue
Max tools per session10
Tool name length64 characters
Description length500 characters
Max parameters per tool20
Result data size50 KB (truncated if larger)
Error message length1000 characters
Tool result rate limit30/min per session
Tool update rate limit5/min per session

Security

  • Tool definitions are validated server-side (name pattern, limits, schema structure)
  • Tool results are sanitized (data truncated at 50 KB, error at 1000 chars)
  • instructions are placed after guardrails in the system prompt hierarchy — they cannot override the agent's identity or security rules
  • Tool results are treated as data, not instructions — prompt injection defenses apply
  • No PII is logged server-side (only tool name + invocation ID)

Workflows

Guide AI conversations through structured, multi-step flows. Add a workflow config to init() or useMasheev().

Masheev.init({
  inboxId: "your-inbox-id",
  workflow: {
    id: "onboarding",
    name: "New User Onboarding",
    steps: [
      { id: "welcome", name: "Welcome", instructions: "Greet the user." },
      { id: "setup", name: "Setup", instructions: "Help configure their workspace." },
    ],
    context: { userName: "Alex" },
  },
});

Workflows provide step-by-step AI guidance, per-step tool filtering, analytics funnels, and context interpolation ({{context.KEY}}).

See the full Workflows guide for defineWorkflow(), useWorkflow(), events, analytics dashboard, and security details.


Events

EventPayloadFires when
ready{ protocol?: number }Widget iframe has loaded
open—Widget panel is opened
close—Widget panel is closed
message{ role: "user" | "ai", content: string }A message is sent or received
error{ message: string, code?: string }An error occurs
action:invoke{ invocationId, toolName, args }AI invokes a client tool
action:result{ invocationId, result }Tool execution completes
action:progress{ invocationId, status }Tool reports progress

All event subscriptions are type-safe:

Masheev.on("message", (payload) => {
  // payload is typed as { role: "user" | "ai"; content: string }
});

React Hook API

useMasheev(config)

import { useMasheev } from "@masheev/embed-sdk/react";

const {
  open, // () => void
  close, // () => void
  toggle, // () => void
  sendMessage, // (text: string) => void
  on, // (event, callback) => () => void  (returns unsubscribe)
  off, // (event, callback) => void
  updateTools, // (tools: ClientToolDefinition[]) => void
  isReady, // boolean
} = useMasheev({ inboxId: "..." });

The hook creates the SDK on mount and destroys it on unmount. It re-initialises when inboxId or baseUrl change.


Headless API

The headless entry point gives you direct access to the conversation over WebSocket. No iframe is created — you build the UI yourself.

<MasheevProvider>

Wrap your chat UI with the provider.

PropTypeDefaultDescription
inboxIdstring—Required. Inbox to connect to.
apiBasestring"https://api.masheev.com"API base URL.
getVerificationToken() => Promise<string | undefined>—Returns a bot-verification token for each new session (see Bot Protection).
turnstileSiteKeystring—Web only. Loads Cloudflare Turnstile on demand. Prefer getVerificationToken with useTurnstileVerification; ignored when that is set.
customerInfo{ name?, email?, phone?, userId?, userHash? }—Pre-fill customer identity. userId + userHash (HMAC-SHA256 of userId, computed on your server) make it a signed identity.
toolsClientToolDefinition[]—Client-side tools the AI can invoke (see Agent Actions).
instructionsstring—Instructions for the AI on how to use tools.
storage"persistent" | "session" | "none" | HeadlessStorageAdapter"persistent"Where the visitor identity is kept: localStorage, sessionStorage, nowhere, or your own adapter (see Storage). On React Native without an adapter, "persistent" keeps it in memory; on a server nothing is stored. Nothing is stored before the first session.
requireConsentbooleanfalseStart no session until you call giveConsent().
rendersDisclosurebooleanfalseYour UI shows disclosure before the conversation. Otherwise the server adds it to the start of the first AI reply.

useMasheev() (headless)

Must be called inside <MasheevProvider>.

const {
  // Session
  session, // WidgetSession | null
  greeting, // string | null: show before the first message
  disclosure, // string | null: AI disclosure, show before the conversation
  isResumed, // boolean: an earlier conversation continued; its messages are loaded
  isConnected, // boolean
  connectionStatus, // "connecting" | "connected" | "disconnected" | "error" | "gave_up"
  error, // string | null

  // Messages
  messages, // Message[]
  sendMessage, // (content: string) => Promise<void>
  isLoading, // boolean

  // Live reply
  isStreaming, // boolean: a reply's text is arriving
  turnStatus, // TurnStatus | null: status of the newest reply in progress

  // UI state
  isOpen, // boolean
  setOpen, // (open: boolean) => void

  // Tools
  updateTools, // (tools: ClientToolDefinition[]) => Promise<void>

  // Manual session creation
  createSession, // () => Promise<WidgetSession | null>
  triggerAiTurn, // () => Promise<void>: the AI speaks first in a new, empty conversation

  // Consent (with requireConsent)
  hasConsent, // boolean
  giveConsent, // () => void, call from your own consent UI
} = useMasheev();

Lower-level hooks

HookReturnsUse case
useWidgetChat(){ messages, sendMessage, isLoading, isStreaming, turnStatus, error }Chat operations only
useWidgetSession(){ session, error, isLoading, createSession }Session management
useWidgetSocket(){ status }Connection indicator

Message

interface Message {
  id: string;
  role: "user" | "ai";
  content: string;
  timestamp: Date;
  isLoading?: boolean; // true until the reply's final text is in
  isStreaming?: boolean; // true while text arrives; content grows word by word
  turnStatus?: TurnStatus; // "reading" | "searching" | "checking" | "handoff" | "thinking" | "tool_use" | "responding" | ...
  currentStep?: string; // the running tool step, while turnStatus is "tool_use"
  senderName?: string; // a human agent's name
  serverMessageId?: string; // the server's id for an AI or agent reply
}

When a returning visitor's session resumes their open conversation, messages starts with its transcript (the latest 50 messages).

Render content whenever it is non-empty, and show turnStatus (or a typing indicator) while a reply is loading with no text yet.

WidgetSession

interface WidgetSession {
  sessionToken: string; // replaced when the server refreshes it (X-Session-Token)
  visitorId: string;
  visitorToken: string; // signed grant that lets this visitor resume
  conversationId: string;
  greeting?: string;
  disclosure?: string; // AI disclosure: show it before the conversation
  isResumed?: boolean;
  agentName?: string;
  agentDescription?: string;
  orgName?: string;
  privacyPolicyUrl?: string;
  consent?: { timestamp: string; version?: string } | null;
  workflowRunState?: WorkflowRunState | null;
}

Storage

storage accepts any object with getItem, setItem and removeItem. Each may return a value or a promise, so both localStorage and asynchronous stores work:

import AsyncStorage from "@react-native-async-storage/async-storage";

<MasheevProvider inboxId="your-inbox-id" storage={AsyncStorage}>

The SDK stores one entry per inbox, masheev_visitor_{inboxId}, holding the server-issued visitor id and its signed grant. It is deleted after 13 months unused.

React Native and other non-browser runtimes

@masheev/embed-sdk/headless imports nothing browser-only. React Native (Metro with package exports, Expo SDK 53 and later by default) resolves a build without Turnstile through the react-native export condition; Node, Electron and SSR load the standard build, which imports Turnstile only when turnstileSiteKey is used.

The runtime needs fetch, WebSocket and AbortController, which React Native provides, and the zod peer dependency. crypto.randomUUID is used when present; without it ids come from crypto.getRandomValues (add react-native-get-random-values for it) or Math.random.

import AsyncStorage from "@react-native-async-storage/async-storage";
import { MasheevProvider, useMasheev } from "@masheev/embed-sdk/headless";

export function SupportChat() {
  return (
    <MasheevProvider inboxId="your-inbox-id" storage={AsyncStorage} rendersDisclosure>
      <ChatScreen />
    </MasheevProvider>
  );
}

function ChatScreen() {
  const { messages, sendMessage, greeting, disclosure } = useMasheev();
  // Render with your own native components.
}

React Native cannot run the Turnstile challenge, so a native app passes no getVerificationToken and its session requests carry no token. They are admitted only while visitor verification is off for the deployment, as it currently is on api.masheev.com. If verification is switched on, these requests are rejected with 403 Verification required until you supply a token from a native verification provider through getVerificationToken.

Read-aloud (readAloud.play) needs the browser's Audio; elsewhere it does nothing. Fetch GET /api/widget/tts/{messageId} with the session token and play it with a native audio player instead.


How It Works

Iframe SDK (JS / React)

  1. init() creates a hidden <iframe> pointing to https://iframe.masheev.com/widget/{inboxId}.
  2. Communication happens via window.postMessage with strict origin validation.
  3. Commands issued before the iframe is ready are queued and flushed on the ready event.
  4. The SDK owns the iframe's size. It resizes the frame when the widget opens or closes and whenever the widget posts a resize message.

Headless SDK

  1. A session is created lazily on the first sendMessage() call (or explicitly via createSession()). The visitor identity is stored only after that, as set by storage (see Privacy and cookies).
  2. The provider opens a WebSocket to wss://api.masheev.com/ws/conversation/{conversationId}.
  3. Messages from the AI arrive in real-time over the socket.
  4. Reconnection uses exponential backoff (1 s initial, 30 s max, 10 attempts, 30% jitter).
  5. A ping is sent every 30 s to keep the connection alive.
  6. A returning visitor's session asks for the transcript (includeHistory), and the provider loads it into messages.
  7. A reply that is accepted but not seen on the socket is recovered by reading GET /api/widget/history?operationId=…; the message is never posted twice.
  8. When a response carries X-Session-Token, the provider uses that token from then on.

Bot Protection

The headless provider asks getVerificationToken for a token each time it creates a session and sends it as turnstileToken. On the web, use the Turnstile helper; it embeds an invisible challenge when a session is first requested, not on page load:

import { MasheevProvider } from "@masheev/embed-sdk/headless";
import { useTurnstileVerification } from "@masheev/embed-sdk/headless/turnstile";

function App() {
  const turnstile = useTurnstileVerification("your-site-key");
  return (
    <MasheevProvider inboxId="your-inbox-id" getVerificationToken={turnstile.getVerificationToken}>
      {turnstile.element}
      <Chat />
    </MasheevProvider>
  );
}

turnstileSiteKey keeps working on the web and does the same. Without either prop, or when the function rejects, the session request carries no token and the server decides: it is admitted when verification is off for the deployment and rejected with 403 Verification required otherwise.

Turnstile

When verification is on, POST /api/widget/session requires a Cloudflare Turnstile token. A request without one is rejected with 403 Verification required, so the widget waits for the invisible challenge to resolve before it creates a session, and never sends an unverified request.

The challenge is served from https://challenges.cloudflare.com. If your site sends a Content Security Policy, allow that origin in both directives:

Content-Security-Policy: script-src https://challenges.cloudflare.com; frame-src https://challenges.cloudflare.com

If the challenge cannot load — blocked by CSP, blocked by a privacy extension, or a missing site key — the widget treats it as a startup failure rather than a message failure. Visitors see nothing at all while it retries in the background; on a development host, or with debug: true / ?masheev_debug=1, you get a card naming the cause.


REST Endpoints (headless internals)

These are called internally by the headless provider. You only need them if you are building a non-React integration from scratch.

POST /api/widget/session

Create a chat session.

Request:

{
  "inboxId": "string",
  "visitorId": "string",
  "visitorToken": "string",
  "customerInfo": { "name": "string", "email": "string", "phone": "string" },
  "userId": "string",
  "userHash": "string",
  "turnstileToken": "string",
  "consent": { "timestamp": "ISO-8601 string", "version": "ai-conversations-v1" },
  "disclosureRendered": false,
  "includeHistory": true,
  "clientTools": [{ "name": "string", "description": "string", "parameters": {} }],
  "instructions": "string"
}
  • visitorId — optional. Send only the identifier a previous session returned, together with its visitorToken; the server issues a new one otherwise.
  • userId, userHash — optional. A signed identity; userHash is HMAC-SHA256 of userId computed on your server.
  • includeHistory — optional. Return the conversation's latest 50 messages as history, and the greeting even when the session resumes.
  • consent — optional. Records dataProcessing: true and the timestamp on the contact record for GDPR Art. 7(1) compliance.
  • disclosureRendered — optional. Send true only if your UI shows disclosure before the conversation. Otherwise the disclosure is added to the start of the first AI reply.
  • clientTools — optional. Registers client-side tool definitions for the session (see Agent Actions).
  • instructions — optional. Instructions for the AI on how to use the registered tools.

Response:

{
  "sessionToken": "string",
  "visitorId": "string",
  "visitorToken": "string",
  "conversationId": "string",
  "greeting": "string",
  "disclosure": "string",
  "agentName": "string",
  "orgName": "string",
  "privacyPolicyUrl": "string",
  "isResumed": false,
  "history": { "messages": [], "hasMore": false, "agentLastReadAt": null }
}
  • visitorId, visitorToken — store both and send them with the next session to resume the visitor's conversation.
  • greeting — the agent's conversational greeting (e.g. "Hello! How can I help you today?"). Absent for resumed sessions unless includeHistory is set.
  • history — only with includeHistory: messages oldest first, each { id, role: "contact" | "ai" | "agent", content, status, senderName?, createdAt }.
  • disclosure — the AI disclosure to show before the chat (e.g. "You're chatting with Alex, an AI assistant for Acme Corp."). Returned whenever an AI agent is configured, resumed sessions included.
  • orgName, privacyPolicyUrl — the business name and its privacy policy from the inbox settings, for your privacy link. privacyPolicyUrl is absent if none is set.
  • isResumed — true when continuing an existing conversation.

POST /api/widget/message

Send a message. Requires Authorization: Bearer {sessionToken}.

Request:

{ "content": "string", "operationId": "string", "timezone": "Europe/Paris" }

operationId (up to 512 of A-Z a-z 0-9 . _ : -) makes the send idempotent: a retry with the same id is answered from the first acceptance, never posted twice.

Or trigger an AI-first turn (the AI speaks first with no user message). Use initial:{conversationId} as the operation so a repeat replays the same turn:

{ "trigger": true, "triggerReason": "initial", "operationId": "initial:{conversationId}" }

Response when an AI turn is accepted:

{
  "status": "processing",
  "operationId": "string",
  "turnId": "string",
  "terminalMessageId": "string",
  "deadlineAt": 1760000000000
}

The reply arrives over the WebSocket (message.stream.*, then message.new or message.stream.end for terminalMessageId), not in the HTTP response. If the socket misses it, read GET /api/widget/history?operationId={operationId}.

When a person handles the conversation the response is { "status": "human_pending", "operationId", "userMessageId", "receiptMessageId"? } and no AI reply follows. Either response may carry newSession: { sessionToken, conversationId } when the message started a new conversation; use it from then on.

Session refresh: When the session token is close to expiring (<2 hours remaining), responses from /message and /history include an X-Session-Token header with a refreshed token. The headless provider adopts it; other clients should update their stored token.

POST /api/widget/tool-result

Submit the result of a client-side tool invocation. Requires Authorization: Bearer {sessionToken}.

Request:

{
  "invocationId": "string",
  "result": { "success": true, "data": {} }
}

Response:

{ "success": true }

POST /api/widget/update-tools

Update tool definitions mid-session. Requires Authorization: Bearer {sessionToken}.

Request:

{
  "clientTools": [{ "name": "string", "description": "string", "parameters": {} }],
  "instructions": "string"
}

Response:

{ "success": true }

GET /api/widget/history

Read the conversation transcript. Requires Authorization: Bearer {sessionToken}.

Query params: limit (1–100, default 50), cursor (a message id: return older messages), operationId (also report that send's acceptance).

Response:

{
  "messages": [
    {
      "id": "msg_…",
      "role": "contact",
      "content": "string",
      "status": "delivered",
      "createdAt": "ISO-8601 string"
    }
  ],
  "hasMore": false,
  "agentLastReadAt": null,
  "acceptedOperation": {
    "status": "processing",
    "operationId": "string",
    "terminalMessageId": "string",
    "turnId": "string"
  }
}

Messages are oldest first. role is contact (the visitor), ai or agent (a person; senderName is set). An AI reply is final once its status is delivered, read or failed. acceptedOperation (or pendingOperation with status: "human_pending") appears only for a matching operationId.

WebSocket /ws/conversation/{conversationId}

Query params: ?token={sessionToken}&source=widget

Send the text ping every 30 s; the server answers pong. Every other frame is JSON { "type", "payload" }:

typepayloadMeaning
message.new{ messageId, content, sender: { type, name? } }A complete message. Ignore sender.type: "contact" (the visitor's own). agent is a person; name is set.
message.stream.start{ messageId, operationId?, turnId?, content? }A reply starts streaming. After a reconnect content holds the text so far.
message.stream.delta{ messageId, delta, index? }Append delta. index counts from 1; drop an index you already applied.
message.stream.end{ messageId, content, operationId?, conversationId?, revision? }Final text, replacing what streamed. A higher revision corrects an earlier final text.
ai.turn.started, ai.turn.thinking, ai.turn.tool_use, ai.turn.responding, ai.turn.completed, ai.turn.error{ status, turnId?, messageId?, operationId?, conversationId?, currentStep? }Where the reply is. status may also be reading, searching, checking or handoff; currentStep names the running tool.
client_tool.invoke{ invocationId, toolName, args }Run a registered client tool and post /api/widget/tool-result.
workflow.step_complete, workflow.complete{ workflowId, stepId?, outcome?, data? }Workflow progress.

Unknown types may be added; ignore them.

Example:

{
  "type": "message.new",
  "payload": {
    "messageId": "string",
    "content": "string",
    "sender": { "type": "ai" }
  }
}

When Agent Actions are registered, the server also sends tool invocation events:

{
  "type": "client_tool.invoke",
  "payload": {
    "invocationId": "string",
    "toolName": "string",
    "args": {}
  }
}

Constants

import { SDK_VERSION, DEFAULT_API_BASE, DEFAULT_WIDGET_BASE } from "@masheev/embed-sdk/js";

SDK_VERSION; // installed package version, e.g. "0.5.1"
DEFAULT_API_BASE; // "https://api.masheev.com"
DEFAULT_WIDGET_BASE; // "https://iframe.masheev.com"