@gravity-rail/sdk
TypeScript SDK for Gravity Rail — the AI-native operating system for organizations that communicate with people at scale.
Build AI assistants that handle voice calls, SMS, web chat, email, Discord, and Slack — all backed by configurable workflows, structured data collection, and real-time streaming. One SDK, every channel.
Installation
npm install @gravity-rail/sdk
# or
yarn add @gravity-rail/sdk
# or
pnpm add @gravity-rail/sdk
Zod schemas are available as an optional peer dependency:
npm install zod # optional, for runtime validation
Quick Start
Create an account or organization API key with the scopes your integration needs. See Authentication for key reach, OAuth, and step-up requirements. Keep credentials in your server's environment or secrets manager; do not embed an API key in a public browser bundle.
import { GravityRailClient } from '@gravity-rail/sdk';
const client = new GravityRailClient(
process.env.GRAVITY_RAIL_API_KEY,
'https://api.gravityrail.com'
);
const workspaces = await client.getWorkspaces({ page: 1, pageSize: 20, search: 'clinic' });
// Read workspaces.items; request the next page explicitly when needed.
if (workspaces.items.length === 0) throw new Error('No workspace on this page; search or request another page');
const workspaceId = workspaces.items[0].uuid;
const workflows = await client.getWorkflows(workspaceId);
const chats = await client.getChats(workspaceId);
Use Creating Members to select the appropriate creation/import endpoint and role. A direct SDK call uses the request type's wire names:
const roleId = Number(process.env.GRAVITY_RAIL_MEMBER_ROLE_ID);
if (!Number.isInteger(roleId) || roleId <= 0) {
throw new Error('Set GRAVITY_RAIL_MEMBER_ROLE_ID to an authorized role ID');
}
const member = await client.createWorkspaceMember(workspaceId, {
name: 'Integration Test',
email: 'integration-test@example.com',
memberRoleId: roleId, // an authorized role selected for the new Member
});
Handle API errors
import { ApiError } from '@gravity-rail/sdk';
try {
await client.getWorkflows(workspaceId);
} catch (error) {
if (error instanceof ApiError && error.statusCode === 403) {
// Check the acting identity and scopes for this workspace.
}
throw error;
}
See Error Handling for status codes and safe reporting. The SDK Reference and GravityRailClient reference document methods and types. This package README also supplies the canonical SDK usage guide.
Authentication
API Key
Create an account or organization API key with the required permissions:
const client = new GravityRailClient(
'your-api-key',
'https://api.gravityrail.com'
);
Select the required scopes and expiry using the granular scope system. Key reach depends on the issuing account or organization; a key created in workspace settings is not inherently limited to that workspace.
OAuth2 with PKCE
For browser-based applications on your own origin, complete the PKCE flow and pass the access token it returns as the client's credential — it is sent as Authorization: Bearer:
const client = new GravityRailClient(accessToken, 'https://api.gravityrail.com');
// Handle step-up authentication when the API requires it
client.setEnhancedAuthHandler(async (authInfo) => {
// Redirect to login or show auth modal; resolve with the new token
});
Same-origin session
A client built without a credential is a same-origin session client: it sends no Authorization header and fetches with credentials: 'same-origin', so the browser presents the httpOnly session cookie of the origin the page is on, and only to that origin. It never reads a cookie to build a credential. This is how Gravity Rail's own web app calls the API (it serves /api/v2 on its own origin); point baseUrl at the page's origin:
const client = new GravityRailClient(undefined, window.location.origin);
A cross-origin baseUrl with no credential makes unauthenticated calls.
An organization authentication challenge (WWW-Authenticate: Bearer realm="org") calls your setOrgAuthHandler handler. A bearer handler returns an opaque organization session candidate; it must not call setOrgSession during the handler:
client.setOrgAuthHandler(async ({ orgUuid, authUrl, acrValues }) => {
const session = await signInToOrganization({ orgUuid, authUrl, acrValues });
return { session, orgUuid, source: 'new' };
});
source: 'new' means the server issued this session during the attempt; it does not establish MFA or reset its authentication time. A handler may return source: 'cache' only for a previously saved candidate, before sessionRejected is true. It may supply onRejected to remove that exact candidate from its cache. Compare the stored credential before removal so an old rejection cannot erase a newer login.
The SDK adopts a result only while the handler still owns its original credential context. It sends the candidate as X-Org-Session for server validation. A newly issued candidate gets one retry. A bearer request that starts without an org session may validate a cache candidate first, then make one new sign-in attempt if rejected. An empty cache does not permit two new sign-ins. Account MFA recovery has its own one-attempt budget. A concurrent login supersedes an older handler; its failure or delayed result cannot clear the newer credential. setOrgSession remains available for configuration outside a handler.
A same-origin cookie handler may resolve without a result after sign-in sets the httpOnly org cookie; the SDK retries once with that cookie.
acrValues reports the server's requested authentication context. The SDK and CLI do not forward Gravity Rail's urn:gravity:mfa value as a provider-specific OIDC hint. For SSO with required MFA, configure the identity provider to require MFA and return verified authentication methods. An insufficient newly issued session fails with guidance to complete Account MFA or check the identity provider configuration; the SDK does not repeat interactive sign-in.
Core Concepts
Every Gravity Rail workspace is a self-contained environment with isolated data, workflows, and configuration. The SDK organizes its 500+ methods by domain:
| Domain | What it covers |
|---|---|
| Workflows | Multi-step conversational processes with branching logic, task assignment, and templates |
| Assistants | AI personas with configurable models, voices, and a two-tier supervisor system |
| Agents | Autonomous AI workspace members with their own identity, config, and multi-channel presence |
| Chats | Conversations across all channels — labels, filters, summaries, message history, and export |
| Members | Contacts and team — roles, labels, filters, custom fields, import/export, anonymous resolution |
| Data Types | Schema-driven forms (14 field types) with computed fields and conversational collection |
| Events | Trigger-based automation with CEL expressions |
| Calendars | Scheduling, availability, event types, Google Calendar sync, and iCal feeds |
| Files | Folder hierarchy with semantic search, role-based sharing, and public access |
| Sites | Customer-facing portals with custom domains, managed pages, and source applications |
| Communications | Phone numbers, SMS, email inboxes, and notification rules |
| Org Domains | Register org-owned domains, verify ownership, verify email MX/DKIM/SPF, and verify site CNAMEs |
| Toolkits | Custom tools, MCP server integrations, and AI model configuration |
| Operator Groups | Live human routing with presence tracking and configurable strategies |
| Qualifications | Skills evaluation with expression-based and rubric-based scoring |
| Billing | API keys, subscriptions, and usage reports (AI, voice, SMS, storage) |
| Integrations | Discord, Slack, Monday.com, FHIR, and OAuth app connections |
Usage Examples
Workflows & Assistants
// Create a multi-step workflow
const workflow = await client.createWorkflow(workspaceId, {
name: 'Customer Onboarding',
description: 'Guide new customers through setup',
});
// Create an AI assistant
const assistant = await client.createAssistant(workspaceId, {
name: 'Onboarding Guide',
model: 'aws:bedrock:claude-5-5-sonnet',
bio: 'A friendly assistant that helps new customers get started.',
});
// Add a supervisor for quality assurance
const supervisor = await client.createSupervisor(workspaceId, {
name: 'QA Reviewer',
model: 'aws:bedrock:claude-5-5-sonnet',
instructions: 'Review assistant responses for accuracy and tone.',
});
// Build from templates
const templates = await client.getWorkflowTemplates(workspaceId);
await client.createWorkflowFromTemplate(workspaceId, {
template_id: templates[0].id,
});
Chat Operations
// Get conversations across all channels
const chats = await client.getChats(workspaceId);
// Full message history with tool calls
const messages = await client.getChatMessages(workspaceId, chatId);
const toolCalls = await client.getChatToolCallMessages(workspaceId, chatId);
// Trigger an AI response
await client.sendAssistantMessage(workspaceId, chatId);
// Direct messaging between members
const dm = await client.findOrCreateDMChat(workspaceId, { member_id: targetMemberId });
await client.sendChatMessage(workspaceId, dm.id, { content: 'Hey!' });
// Export for analysis
const exported = await client.exportChat(workspaceId, chatId);
// Organize with labels and filters
await client.createChatLabel(workspaceId, { name: 'VIP', color: '#FFD700' });
await client.createChatFilter(workspaceId, { name: 'Unresolved', conditions: { needs_response: true } });
Structured Data Collection
Forms are DataType schemas in the API. Create a Form in your Workspace, then
read its schema by slug or ID. This server-side example expects an existing
loads Form with the field slugs reference and status; use your own slugs:
import { GravityRailClient } from '@gravity-rail/sdk';
const client = new GravityRailClient(
process.env.GRAVITY_RAIL_TOKEN!,
'https://api.gravityrail.com',
);
const workspace = client.workspace(process.env.GRAVITY_RAIL_WORKSPACE_UUID!);
const form = await workspace.getDataTypeBySlug('loads');
const record = await workspace.createDataRecord(form.id, {
dataTypeId: form.id,
fieldValues: { reference: 'LOAD-001', status: 'queued' },
});
const page = await workspace.getDataRecords(form.id, { page: 1, pageSize: 20 });
// Read page.items; request another page when needed.
// Upsert uses a stable external ID, not a field name.
await workspace.upsertDataRecord(form.id, 'dispatch-load-002', {
fieldValues: { reference: 'LOAD-002', status: 'queued' },
});
Field values use field slugs, not display names. Read, write, row, and field permissions still apply. Writes can return a value-free receipt when read access is absent; use an authorized record read to display stored values. For app-side loading, editing, and navigation, use the React Forms and records example.
Communication Channels
// Email — manage inboxes and threads
const inboxes = await client.getInboxes(workspaceId);
const threads = await client.getInboxThreads(workspaceId, inboxes[0].id);
const emails = await client.getThreadEmails(workspaceId, inboxes[0].id, threadId);
// Notifications
await client.createNotificationRule(workspaceId, {
name: 'New chat alert',
event_type: 'chat.created',
channel: 'email',
});
Organization Domains
// Register an org-owned domain and publish the returned TXT proof.
const orgDomain = await client.registerOrgDomain(orgId, 'example.com');
console.log(orgDomain.ownershipDnsRecord);
// Verify domain ownership.
await client.verifyOrgDomainOwnership(orgId, orgDomain.uuid);
// Enable and verify email DNS, including MX.
const emailConfig = await client.enableOrgDomainEmail(orgId, orgDomain.uuid);
console.log(emailConfig.dnsRecords);
await client.verifyOrgDomainEmail(orgId, orgDomain.uuid);
// Enable and verify custom site routing through CNAME.
const siteConfig = await client.enableOrgDomainSite(orgId, orgDomain.uuid);
console.log(siteConfig.dnsRecords);
await client.verifyOrgDomainSite(orgId, orgDomain.uuid);
// Or host many sites under one domain: the customer publishes a single
// `*.example.com` CNAME, and each host beneath it needs no DNS of its own.
await client.enableOrgDomainSite(orgId, orgDomain.uuid, { childHosting: true });
await client.verifyOrgDomainSite(orgId, orgDomain.uuid);
Toolkits & MCP Servers
// Connect an MCP server for custom AI tool capabilities
const server = await client.createMcpServer(workspaceId, {
name: 'Internal Tools',
url: 'https://tools.example.com/mcp',
});
await client.testMcpServerConnection(workspaceId, server.id);
// Discover tools, resources, and prompts
const tools = await client.getMcpServerTools(workspaceId, server.id);
const resources = await client.getMcpServerResources(workspaceId, server.id);
// Or build custom tools directly
await client.createCustomTool(workspaceId, toolkitId, {
name: 'lookup_order',
description: 'Look up an order by ID',
input_schema: {
type: 'object',
properties: { order_id: { type: 'string' } },
required: ['order_id'],
},
});
Calendar & Scheduling
const calendar = await client.createCalendar(workspaceId, { name: 'Appointments' });
// Check availability and book
const slots = await client.getAvailableSlots(workspaceId, calendar.id, {
start_date: '2025-03-01',
end_date: '2025-03-07',
duration_minutes: 30,
});
await client.createCalendarEvent(workspaceId, calendar.id, {
title: 'Consultation',
start_time: slots[0].start,
end_time: slots[0].end,
attendees: [{ member_id: memberId }],
});
// Sync with Google Calendar
await client.linkCalendarToGoogle(workspaceId, calendar.id, {
google_calendar_id: 'primary',
});
Event Automation
// Trigger-based automation with CEL conditions
await client.createEventRule(workspaceId, {
name: 'VIP Follow-up',
trigger: 'task.exited',
condition: '"vip" in member.labels',
actions: [{
type: 'send_ai_message',
delay_minutes: 60,
config: { message: 'Thank you for your time today.' },
}],
});
// Scheduled events (CRON)
const event = await client.createEvent(workspaceId, {
name: 'Daily Check-in',
schedule: '0 9 * * *',
target_filter: { labels: ['active'] },
});
// Trigger manually
await client.runEvent(workspaceId, event.id);
Operator Groups & Live Handoff
// Route conversations to live human operators
const group = await client.createOperatorGroup(workspaceId, {
name: 'Support Team',
routing_strategy: 'round_robin',
timeout_seconds: 30, // falls back to AI if no one accepts
});
await client.addGroupMember(workspaceId, group.id, { member_id: agentMemberId });
const operators = await client.getLiveOperators(workspaceId);
Sites & Portals
Choose Site visibility, the roles that can sign in, and record access separately. Create a private source Site with no record scope opt-ins, then set its role audience. This example runs on your server; replace the environment variables with your OAuth token, workspace UUID, and the Member Role UUID from that workspace (not its numeric ID):
import { AccessLevel, GravityRailClient } from '@gravity-rail/sdk';
const client = new GravityRailClient(
process.env.GRAVITY_RAIL_TOKEN!,
'https://api.gravityrail.com'
);
const workspace = client.workspace(process.env.GRAVITY_RAIL_WORKSPACE_UUID!);
const memberRoleUuid = process.env.GRAVITY_RAIL_MEMBER_ROLE_UUID!;
const site = await workspace.createSite({
name: 'Operations',
theme: 'source-site',
isPublic: false,
allowSignup: false,
allowedScopes: [],
});
await workspace.updateSiteSharing(site.id, {
access: AccessLevel.PRIVATE,
shareable: false,
grants: [],
audience: [memberRoleUuid],
});
// A Site admin enables only the operations this app needs.
await workspace.updateSite(site.id, {
allowedScopes: ['records:read', 'records:write'],
});
The empty grants above apply to a new Site. To change an existing Site, read
getSiteSharing(site.id) first and preserve the access, shareability, grants,
and audience entries you are not changing. The update replaces the submitted
sharing lists.
| Setting | What it controls |
|---|---|
isPublic | Whether visitors can open the Site; public visibility does not make records public. |
Sharing audience | The Member Role UUIDs whose Members can sign in through the Site. |
allowedScopes | Record read, write, or admin operations allowed through a Site session. Defaults to []. |
allowSignup / signupMemberRoleId | Whether new Members may join and the numeric role ID assigned to them. |
A Site session is still limited by the Member's current role and Form, record,
and field permissions. Read and write opt-ins are independent. Existing own-Form
submission permissions still apply. records:admin is an explicit opt-in for
record administration, including deletion; enable it only for an app that needs
it and Members whose roles already permit it. A workspace UUID supplies context,
not authentication. A 403 needs a permission check, not a broader allowlist.
Record writes may return a successful value-free receipt (fieldValues is
empty and Member identifiers are null) when the caller cannot read stored
values. Load values with a permitted record read after saving. Customer sign-in
policies remain separate from record scopes.
Managed themes use workspace.createPage with title and a TipTap
contentBlocks document for pages. slug is optional and derived from the title
when omitted. Page create and update requests reject contentHtml,
contentMarkdown, and contentAMP. Source Sites define application routes in their
React code; creating a managed Page does not register a React route. For a
verified custom domain, use
customDomain in createSite or updateSite, following the
Site domain setup.
The React guide
shows real page and record paths, Forms, data loading, and persistent navigation.
Workspace Management
Workspace and organization directories return { items, page, pageSize, total, totalPages }. Read
items instead of treating the response as an array. Pass page, pageSize (at
most 100), and search to request a page. This applies to getWorkspaces,
getDeviceAdmissibleWorkspaces, getPublicWorkspaces, getMyOrganizations, and
getOrganizationWorkspaceSummaries.
getOrganizationWorkspaceSummaries also accepts label, an organization label
slug. It combines with search before pagination and requires org:read or
org:webhooks. Unknown slugs return an empty page. The filter preserves
organization and workspace membership limits.
Organization member details no longer embed workspace lists; request organization
workspace summary pages instead.
getMyOrganizations also accepts organizationSlug for exact host resolution
and organizationUuids (at most 100 UUIDs) for a bounded membership lookup. These
filters only narrow the current account's memberships.
getWorkspaceOrganizationDirectory({ page, pageSize, search, organizationUuid })
returns one page of organizations reached through either an organization membership
or a ready workspace membership. Search includes organization name, slug, exact UUID,
and matching workspace name, slug or exact UUID. Each organization appears once.
organizationUuid limits results to that organization within the account's visible directory.
matchesOrganizationSearch identifies entries whose organization fields match,
so their workspace pages can stay unfiltered. Entries without an organization
membership have role: null; reading the directory
does not grant organization access. The default page size is 25, with a maximum of 100.
Account and device workspace totals count eligible global membership candidates;
workspace admission can make a page sparse or empty. Use pagination metadata to
reach later candidates.
getOrgWorkspaceUsage(orgUuid, { page, pageSize, search }) returns a bounded
workspaces list with page, pageSize, total, and totalPages metadata.
Organization usage totals remain global and can be null when measurement coverage
is incomplete. Do not sum the visible cards to calculate an organization total.
// Workspaces this credential can reach
const workspaces = await client.getWorkspaces({ page: 1, pageSize: 20, search: 'clinic' });
// Read workspaces.items; request the next page explicitly when needed.
// Companion-device picker (Lantern): compact rows for only the
// workspaces a paired device could enter — no device credential needed
const deviceWorkspaces = await client.getDeviceAdmissibleWorkspaces({
page: 1, pageSize: 20, search: 'clinic',
});
// Read deviceWorkspaces.items; a sparse page can still have later candidates.
// Public workspace directory
const publicWorkspaces = await client.getPublicWorkspaces({
page: 1, pageSize: 20, search: 'clinic',
});
// Read publicWorkspaces.items and use total/page/pageSize for pagination.
// Export/import full workspace configuration
const config = await client.exportWorkspace(workspaceId);
const preview = await client.previewWorkspaceImport(targetId, config);
await client.importWorkspace(targetId, config);
// White-label: provision an existing client workspace
await client.provisionClientWorkspace(workspaceId, existingClientWorkspaceId);
Export Workflow revisions
Workspace JSON and ZIP exports default to active snapshots. Request
revisionMode: 'all' to include historical revisions and drafts. The version 2.0 archive carries isolated
workflowRevisions graphs and requires a revision-aware server for import. Import
it as new Workflows to preserve active and draft roles; an existing Workflow match
is refused before writes. Legacy version 1.0 imports keep their existing behavior.
const archive = await client.exportWorkspace(workspaceUuid, undefined, undefined, undefined, {
revisionMode: 'all',
});
const selected = await client.exportWorkspace(workspaceUuid, workflowId, undefined, undefined, {
revisionId: 87,
});
const active = await client.exportWorkspace(workspaceUuid, undefined, undefined, undefined, {
revisionMode: 'active',
});
The same options apply to exportWorkspaceZip. A selected revision requires a
Workflow ID and cannot be combined with active mode. Selected and active snapshots
import into an editable draft and do not change an existing active revision.
The public workspace export API supports only the channels exclusion in every
revision mode. All-revision archives preserve that exclusion. Other public
exclusion values are rejected.
The SDK throws when a legacy server returns an active-only snapshot for an
all-revision or selected export.
JSON validation checks selection metadata and internal Workflow/revision identities.
ZIP validation checks provenance headers generated from the actual exported data,
before reading the archive. It adds no archive size limit or permission requirement.
Deploy a server with ZIP provenance headers before releasing this client update;
servers with revision-aware JSON alone still fail the ZIP guard. Explicit
revisionMode: 'active' exports remain compatible with legacy servers.
ZIP provenance uses X-Gravityrail-Export-Version (2.0 for all revisions,
1.0 for active and selected snapshots) and X-Gravityrail-Export-Selection
(active, all, or selected). A selected ZIP also includes nonempty
X-Gravityrail-Export-Revision-Uuid and X-Gravityrail-Export-Workflow-Uuid.
These values come from the exported artifact. Explicit active exports do not
require these headers.
Shared dependency definitions are current exported Forms, files, and integrations, not historical snapshots of those resources.
Chat history (@gravity-rail/sdk/agui)
mergeChatHistoryWindow(existing, fetched) merges an authoritative chronological
history window into an existing transcript. If the first fetched ID appears in
the existing transcript, the helper retains only the earlier prefix and replaces
the covered tail. It removes prefix entries whose IDs also appear in the fetched
window; it does not remove repeated IDs within the retained prefix. If the first
ID is unknown, or the fetched window is empty, the result is the fetched window alone.
Message text does not identify a message. Fetch the needed history pages before
calling this helper; it does not fetch or filter messages.
import { mergeChatHistoryWindow } from '@gravity-rail/sdk/agui';
const messages = mergeChatHistoryWindow(existingMessages, fetchedMessages);
Helpers (@gravity-rail/sdk/helpers)
Small compound operations built on the client methods, for the common "register → populate a form → enroll → verify webhooks" integration flow:
import {
// member resolution + enrollment
resolveMemberId, // { memberId | phone | externalId } → member id
findOrCreateMemberLabels, // idempotent label lookup/create → ids
upsertDataRecordForMember,// idempotent member-scoped record write
enrollMemberInJourney, // resolve member → tag → enroll (already enrolled is a no-op)
// outbound calling
findMemberByPhone,
resolveOutboundPhoneNumberId,
resolveOutboundWorkflowId,
// webhook signatures (isomorphic HMAC-SHA256; verify the RAW body)
verifyWebhookSignature,
signWebhookPayload,
WEBHOOK_SIGNATURE_HEADER,
} from '@gravity-rail/sdk/helpers';
// Enroll into a journey by any identifier, applying cohort labels:
await enrollMemberInJourney(client, workspaceUuid, {
externalId: 'patient-123',
journeyId,
labels: ['pilot-cohort'],
});
// Verify an inbound webhook in your POST handler:
const result = await verifyWebhookSignature(
rawBody,
request.headers.get(WEBHOOK_SIGNATURE_HEADER),
signingSecret,
);
if (!result.ok) return new Response(result.reason, { status: 401 });
Type System
Full TypeScript types for every API entity:
import type {
Workspace, Member, Chat, Task, WorkflowRevision, Assistant,
DataType, DataRecord, EventRule, Calendar, Site,
PhoneNumber, Inbox, OperatorGroup, Qualification,
Subscription, ApiKey, Agent, MemberRole,
} from '@gravity-rail/sdk';
Zod Schemas
Runtime validation schemas via a separate import (requires zod):
import { taskSchema, memberSchema, workflowSchema } from '@gravity-rail/sdk/schemas';
const task = taskSchema.parse(apiResponse);
const result = memberSchema.safeParse(formData);
if (!result.success) {
console.error(result.error.flatten());
}
Scopes & Permissions
The SDK includes the complete scope system for building OAuth apps and managing API key permissions:
import { SCOPES, ScopeCategory, ScopeManager, SCOPE_PRESETS } from '@gravity-rail/sdk';
// Browse available scopes by category
const chatScopes = Object.values(SCOPES).filter(
(s) => s.category === ScopeCategory.CHATS
);
22 scope categories covering every domain: workspace, members, chats, DMs, assistants, workflows, assignments, automations, data types, records, files, sites, agents, calendars, inboxes, phones, webhooks, apps, labels, analytics, operator, and org.
Error Handling
import { GravityRailClient, ApiError } from '@gravity-rail/sdk';
try {
const task = await client.getTask(workspaceId, taskId);
} catch (error) {
if (error instanceof ApiError) {
console.error('Gravity Rail request failed', error.statusCode);
// 403 → check API key scopes
// 404 → verify workspace and entity IDs
// 429 → rate limited, back off
}
}
Security and PHI Use
The SDK provides scoped API access to workspace-isolated resources. Those technical properties do not by themselves authorize PHI use or establish HIPAA compliance. Before sending PHI, obtain a signed BAA and confirmation from Gravity Rail that the intended organization, workspaces, and services are configured for that use.
Related
@gravity-rail/cli— Command-line interface for interactive workspace management- Developer Docs — Full API reference and guides
License
MIT
Changing interaction mode within a Chat
A Chat retains its transport while an interaction session selects text, push-to-talk, or realtime bidirectional voice. Keep one controller per client session and Chat; independent devices should use separate controllers.
import { ChatInteractionController } from '@gravity-rail/sdk';
const interaction = new ChatInteractionController(client, workspaceId, chatId);
const textSession = await interaction.ensure('text');
const recordedVoiceSession = await interaction.ensure('push_to_talk');
Pass the selected session's id as interactionSessionId and a new UUID as
interactionTurnId on an AG-UI user turn. Send both fields together. The server
checks the Chat and authenticated actor and derives the mode from the stored
session. The controller serializes transitions and reuses request IDs after
uncertain network failures. Session metadata does not itself open a microphone
or establish a realtime connection.
New browser Chat creation accepts interactionMode: 'realtime' for an initial
voice greeting while retaining channel: 'web-chat'. browserChannel remains a
deprecated create-only alias. Omit both provenance fields for legacy AG-UI
clients; historical Messages are not assigned a mode by guessing from channel
or content. Message responses expose nullable interactionSessionId,
interactionMode, and interactionTurnId so audio and transcript components
can follow the same logical turn.
Converting a Start Task opening message
The workflow client exposes the conservative, draft-only opening conversion. Inspect eligibility first, then pass the reported rule id back as an optimistic concurrency guard:
const report = await client.getWorkflowOpeningTurnConversionReport(workspaceId, workflowId);
if (report.canConvert && report.convertibleRuleId !== null) {
await client.convertWorkflowStartTaskOpeningMessage(
workspaceId,
workflowId,
report.convertibleRuleId
);
}
Conversion refuses multiple emitters, conditional or templated messages, direction variants, conflicting Greeting defaults, and other shapes that cannot be moved without changing behavior.