@rydhm/sdk
v0.6.0
Published
The Rydhm API from your server: voice and chat experts, the Onboarding coach, and rep calls with live transcripts, suggestions and AI voicemail. Typed, fetch-only, Node 18+ and edge runtimes.
Maintainers
Readme
@rydhm/sdk
The Rydhm API from your server, typed end to end: voice and chat experts, the Onboarding coach inside your app, and rep calls (a human rep on the phone from the browser, Rydhm transcribing, suggesting and leaving AI voicemails).
fetchonly, no runtime dependencies: Node 18+, Deno, Bun, Cloudflare Workers, Vercel Edge.- ESM and CommonJS, full TypeScript types (every request, response and event).
- Typed errors with the API's code and request id; retries with backoff; timeouts.
- Live event streams (Server-Sent Events) as async iterators that reconnect by themselves.
npm install @rydhm/sdkRydhm is in early access: until launch, pass
baseUrl: 'https://api-staging.rydhm.ai'(the default,https://api.rydhm.ai, is the launch address).
Contents
- Set up
- Quickstart: Onboarding coach
- Quickstart: rep calls
- Connect with Rydhm (a Connect button for your customers)
- Live events
- Lists and pages
- Errors
- Retries and timeouts
- Webhooks
- Everything else: experts, knowledge, chat, voice, meetings
- Reference: methods and scopes
Set up
Create a secret API key in the Rydhm app: Developers → API keys. Give it only the scopes it needs (the reference lists them). Keep it on your server.
import { Rydhm } from '@rydhm/sdk';
const rydhm = new Rydhm(); // reads RYDHM_API_KEY
// or: new Rydhm({ apiKey: 'rydhm_live_…', baseUrl: 'https://api-staging.rydhm.ai' })| Option | Default | |
| --- | --- | --- |
| apiKey | process.env.RYDHM_API_KEY | A secret key, rydhm_live_…. A publishable key (rydhm_pk_…) is refused with a hint: that one is for @rydhm/web. |
| baseUrl | https://api.rydhm.ai | Another host (staging, your proxy). A base path is kept. |
| timeoutMs | 30000 | Per request. Streams: until they start. |
| maxRetries | 2 | See Retries. |
| retryOnRateLimit | true | Wait out a 429's Retry-After (up to 60 s) and try again. |
| defaultHeaders | {} | Sent on every request. |
| fetch | global fetch | Your own (tests, proxies, tracing). |
| dangerouslyAllowBrowser | false | The SDK refuses to run in a browser, where anyone could read your key. |
Every method takes per-call options last: { timeoutMs, maxRetries, signal, headers, idempotencyKey }.
Quickstart: Onboarding coach
The coach lives in your web app through @rydhm/web (a script tag or npm). From
your server you sign users, and keep the coach's guides and page map in code.
1. A publishable key for your website (experts:write):
const { key } = await rydhm.engine.publishableKeys.create(expertId, {
name: 'Production',
allowedOrigins: ['https://app.example.com'],
requireSignedUser: true,
});
// In the page: Rydhm.init({ key, user: { id, hash } }) (see @rydhm/web)2. Sign your users so nobody can claim another user's progress. The secret is the workspace's user-signing secret (Rydhm app, admins); the hash goes to the page with the id:
import { signUserId } from '@rydhm/sdk';
app.get('/api/rydhm-user', requireLogin, (req, res) => {
res.json({ id: req.user.id, hash: signUserId(process.env.RYDHM_ENGINE_USER_SECRET!, req.user.id), name: req.user.name });
});3. Guides and the page map, as code (experts:write):
await rydhm.engine.pageTargets.sync(expertId, [
{ name: 'Invite button', selector: '[data-test=invite]', textHint: 'Invite', pagePattern: '/settings/team' },
{ name: 'New project', selector: '#new-project' },
]);
await rydhm.engine.guides.create(expertId, {
name: 'Invite your team',
nudge: 'Want me to show you how to invite your team?',
trigger: { type: 'first_visit' },
steps: [
{ id: 'open', title: 'Open Team settings', instruction: 'Take them to Settings, then Team.',
pagePattern: '/settings/team', completeWhen: { type: 'page', value: '/settings/team' } },
{ id: 'invite', title: 'Send an invite', instruction: 'Show the Invite button and let them type the email.',
target: 'Invite button', completeWhen: { type: 'event', value: 'invite_sent' } },
],
});
await rydhm.engine.announcements.create(expertId, { title: 'Dark mode is here', body: 'Want me to show you?', ctaLabel: 'Show me' });4. See how it goes (experts:read):
const stats = await rydhm.engine.analytics(expertId, { days: 30 });
for (const g of stats.guides) console.log(g.name, `${g.completed}/${g.started}`);
for await (const user of rydhm.engine.endUsers.list(expertId, { q: 'acme' })) {
const detail = await rydhm.engine.endUsers.get(expertId, user.id);
console.log(user.externalId, detail.progress.map((p) => `${p.guideName}: ${p.status}`));
}Quickstart: rep calls
Rep calls are in preview: the routes are live for early-access workspaces (
https://api-staging.rydhm.ai); small changes are still possible before launch.
Your SDR app's server drives the call with a key that has calls:write and calls:read; the rep
talks from the browser with @rydhm/web's Softphone.
// 1. The signed-in person's phone: hand the whole reply to their browser. The first time, Rydhm adds
// them as a rep (by your user id), so there is no separate step.
const token = await rydhm.reps.softphoneToken('usr_4821', { name: 'Maya Patel' }); // { url, token, presenceRoom, expiresAt }
// 2. Dial. No `from`: Rydhm picks one of your numbers for sales calls. Hand `call.join` to the browser:
// softphone.join(call). `rep` may also be { id, name } to add the rep with the call.
const call = await rydhm.repCalls.create(
{
rep: 'usr_4821',
to: '+14155550199',
externalRef: 'act_77120', // your activity id: echoed on every event and webhook
suggestions: true, // suggest the next question after each prospect turn
context: { prospect: { name: 'Dana Kim', title: 'VP Sales', company: 'Acme' }, goal: 'Book a demo' },
},
{ idempotencyKey: 'act_77120' }, // a retried request never dials twice
);
// 3. Follow it live; leave an AI voicemail when a machine answers.
for await (const e of rydhm.repCalls.events(call.id)) {
switch (e.type) {
case 'call.answered':
if (e.data.by === 'machine') await rydhm.repCalls.leaveVoicemail(call.id); // AI waits for the beep, speaks, hangs up
break;
case 'call.transcript':
if (e.data.final) console.log(`${e.data.speaker}: ${e.data.text}`);
break;
case 'call.suggestion':
console.log('Ask:', e.data.text);
break;
case 'call.summary':
console.log(e.data.outcome, e.data.summary, e.data.callbackAt);
break; // the stream ends after the summary
}
}
await rydhm.repCalls.hangup(call.id); // safe to repeatRecordings: pass record: true; whether a call is recorded follows your workspace's recording policy and
the prospect's state (call.recording says so live). Webhooks stay thin: on call.recording.ready, fetch a
signed link (10 minutes).
const rec = await rydhm.repCalls.recording(callId);
if (rec.status === 'ready') console.log(rec.url, rec.durationSeconds);
await rydhm.repCalls.deleteRecording(callId); // safe to repeatVoices: the AI voicemail and the recording notice are spoken in one voice per call, chosen in this order:
the voicemail's voice, the rep's voicemailVoice, the workspace's default (Sales calls → Settings),
Rydhm's own (Blake). voices.list() fills a voice picker (calls:read).
const { default: fallback, items } = await rydhm.voices.list(); // fallback.source: 'workspace' | 'rydhm'
for (const v of items) console.log(v.name, v.description, v.sampleUrl); // sampleUrl: a static MP3, free to play
await rydhm.reps.upsert('usr_4821', { name: 'Maya Patel', voicemailVoice: items[1].id }); // null: the workspace default
await rydhm.repCalls.leaveVoicemail(callId, { voice: items[2].id }); // this voicemail onlyCallbacks: put numbers in a pool and route calls back to them to the rep.
const pool = await rydhm.numberPools.create({
name: 'West coast',
strategy: 'local_presence', // a number in the prospect's area code first
dailyCapPerNumber: 80,
callbackRouting: { order: ['rep_browser', 'rep_mobile', 'voicemail'], ringSeconds: 20 },
});
// Then put numbers in it in the app (Sales calls -> Numbers, inbound mode "rep"). Phone-number routes
// are session-only today: rydhm.phoneNumbers.update(numberId, { poolId, inboundMode }) needs an admin session.
// One stream per rep: every event of their calls, and call.incoming when a callback rings them.
for await (const e of rydhm.events.stream({ repId: 'usr_4821' })) {
if (e.type === 'call.incoming') notifyRep(e.data.from, e.data.externalRef);
}Connect with Rydhm
Building an app other teams use, like a CRM? Give them a Connect Rydhm button instead of asking for API keys: the admin signs in to Rydhm and clicks Allow, and your server gets a key for their workspace (and the signing secret of a webhook endpoint Rydhm adds for your app). Register the app in the Rydhm app under Developers → Connect with Rydhm to get its client id and secret.
import { oauth, Rydhm } from '@rydhm/sdk';
// The button: remember the verifier and the state (session or an httpOnly cookie), send the admin to Rydhm.
const { codeVerifier, codeChallenge } = await oauth.pkce();
const state = crypto.randomUUID();
res.redirect(oauth.authorizeUrl({ clientId: RYDHM_CLIENT_ID, redirectUri: REDIRECT_URI, state, codeChallenge }));
// The callback: check `state`, then swap the one-time code (10 minutes, once) for their key.
const t = await oauth.exchangeCode({
code, redirectUri: REDIRECT_URI, codeVerifier, clientId: RYDHM_CLIENT_ID, clientSecret: process.env.RYDHM_CLIENT_SECRET,
});
// t.accessToken (rydhm_live_…), t.workspace, t.webhookSecret: store them encrypted.
const rydhm = new Rydhm({ apiKey: t.accessToken });
const { workspace, salesCalls } = await rydhm.oauth.connection(); // "Connected to AIX Staging · calls go out from …"
await rydhm.oauth.disconnect(); // your own Disconnect buttonUntil launch, pass baseUrl: 'https://staging.rydhm.ai' to authorizeUrl and baseUrl:
'https://api-staging.rydhm.ai' to exchangeCode. The key works until someone disconnects (in Rydhm or from
your app); a 401 on it means: show Connect again.
Live events
repCalls.events(callId) and events.stream({ repId }) return an EventStream: an async iterable of
EngineEvents, discriminated by type, so e.data is typed in each branch.
- Reconnects by itself after a drop, with backoff and the server's
retry:hint, and resumes withLast-Event-ID: nothing is missed, and duplicates are dropped by event id. - Heartbeats (
: ping) are skipped; nothing at all forheartbeatTimeoutMs(60 s) counts as a dead connection and reconnects. - A call's stream ends after
call.summary(until: 'ended'stops atcall.ended,'never'keeps it open). A 4xx (a wrong id, a missing scope) is thrown at once. types: ['call.transcript', 'call.suggestion']keeps only those (and narrows the type).stream.close(),break, or asignalstops it;stream.lastEventIdresumes later ({ lastEventId }).
const stream = rydhm.repCalls.events(callId, { types: ['call.transcript'], signal: AbortSignal.timeout(10 * 60_000) });
for await (const line of stream) ui.upsert(`${line.data.speaker}:${line.data.startMs}`, line.data.text, line.data.final);The event types: call.ringing, call.answered { by }, call.screening, call.voicemail_detected,
call.beep, call.transcript { speaker, text, final, startMs }, call.suggestion { text },
call.voicemail_left { text, voice }, call.ended { outcome, durationSec },
call.summary { summary, outcome, callbackAt?, facts }, call.incoming { callId, from, repId, externalRef?, join, ringSeconds },
and for the coach guide.*, announcement.*, tool.called, target.missing,
coach.issue { kind, question? } and answer.sources { sources }. The same shape travels on the
browser's rydhm.events topic.
Lists and pages
Paged routes return a PagePromise: await it for one page, or for await it for every item.
const page = await rydhm.repCalls.list({ rep: 'usr_4821', limit: 50 });
page.items;
if (page.hasNextPage()) await page.getNextPage();
for await (const call of rydhm.repCalls.list({ status: 'completed' })) console.log(call.id);
const everyone = await rydhm.engine.endUsers.list(expertId).toArray();Errors
Everything thrown is a RydhmError with status, code (the API's stable code), message,
requestId (quote it to support) and the parsed body.
import { PermissionDeniedError, RateLimitError, RydhmError } from '@rydhm/sdk';
try {
await rydhm.repCalls.create({ rep: 'usr_4821', to: '+14155550199' });
} catch (e) {
if (e instanceof PermissionDeniedError) console.log('Add these scopes to the key:', e.missingScopes);
else if (e instanceof RateLimitError) console.log('Try again in', e.retryAfterSeconds, 's');
else if (e instanceof RydhmError) console.log(e.status, e.code, e.message, e.requestId);
else throw e;
}| Class | When |
| --- | --- |
| BadRequestError | 400: the message says what is wrong |
| AuthenticationError | 401: the key is missing, wrong, disabled or expired |
| PaymentRequiredError | 402: out of credits (upgradeHint) |
| PermissionDeniedError | 403: a missing scope (missingScopes), an expert the key may not use, a session-only route |
| NotFoundError | 404 |
| ConflictError | 409: a duplicate name, or stale_edit |
| UnprocessableEntityError | 422 |
| RateLimitError | 429 after the SDK's own retries (retryAfterSeconds) |
| InternalServerError | 5xx after retries |
| RydhmConnectionError | The API could not be reached (status 0) |
| RydhmTimeoutError | No answer within timeoutMs (status 0) |
A call you cancel with your own signal rejects with your abort reason, not a RydhmError.
Retries and timeouts
Up to maxRetries (2) more tries, with exponential backoff (0.5 s, 1 s, 2 s… with jitter) or the
server's Retry-After:
- 429 with Retry-After (the rate limiter) on any call: nothing was done. Not when
retryOnRateLimit: false, or when Retry-After is over 60 s. A 429 without Retry-After (pool_exhausted,concurrency_limit) won't pass by waiting, so only calls safe to repeat retry it. - 5xx, 408, timeouts and dropped connections only on calls that are safe to repeat: reads,
PUT,DELETE, the naturally idempotent actions (hangup,decline,revoke,reorder,meetings.leave), and any call with anidempotencyKey. Starting a call or sending a message is never repeated by accident: pass anidempotencyKeyto make it retryable.
Webhooks
Verify a delivery and get the event, typed (the Rydhm Engine events have typed data):
import { verifyWebhook } from '@rydhm/sdk';
app.post('/webhooks/rydhm', express.raw({ type: 'application/json' }), (req, res) => {
let event;
try {
event = verifyWebhook(process.env.RYDHM_WEBHOOK_SECRET!, req.headers, req.body); // the RAW body
} catch {
return res.status(400).send('bad signature');
}
if (event.type === 'call.summary.ready') crm.log(event.data.call.external_ref, event.data.summary.snippet);
res.sendStatus(204);
});Standard Webhooks signatures (whsec_…), both secrets during a rotation, a 5-minute replay window.
Everything else: experts, knowledge, chat, voice, meetings
const experts = await rydhm.experts.list();
const { answer, conversationId } = await rydhm.chat.ask(experts[0].id, 'What can you help with?');
await rydhm.chat.ask(experts[0].id, 'And pricing?', { conversationId }); // the same conversation
// Or stream a reply as it is written: send the turn, then read the stream (ask() already read its own).
await rydhm.chat.send(conversationId, 'Do you offer a free trial?');
for await (const frame of rydhm.stream(conversationId)) if (frame.type === 'delta') process.stdout.write(frame.content);
await rydhm.knowledge.add(expertId, { filename: 'faq.md', content: '# FAQ\n…' });
const hits = await rydhm.knowledge.search(expertId, 'refund policy');
const voice = await rydhm.voice.session(expertId); // for your own LiveKit frontend
await rydhm.meetings.join({ joinUrl: 'https://meet.google.com/abc-defg-hij', agentId: expertId }, { idempotencyKey: 'evt-123' });
await rydhm.request('GET', '/v1/analytics/usage', { query: { from: '2026-11-01', to: '2026-11-08' } }); // any routeReference: methods and scopes
| Method | Scope |
| --- | --- |
| experts.list / get | experts:read |
| experts.create / update | experts:write |
| engine.publishableKeys.list, engine.guides.list / get, engine.pageTargets.list, engine.announcements.list, engine.endUsers.list / get, engine.analytics | experts:read |
| engine.publishableKeys.create / update / revoke, engine.guides.create / update / delete / reorder, engine.pageTargets.create / update / delete / sync, engine.announcements.create / update / delete | experts:write |
| reps.upsert / delete / softphoneToken, repCalls.create / leaveVoicemail / hangup / decline / deleteRecording, numberPools.create / update / delete (a key not limited to some experts) | calls:write (preview) |
| oauth.connection / disconnect | the key Connect with Rydhm gave your app |
| reps.get / list, repCalls.get / list / transcript / recording / events, events.stream, numberPools.list / get, voices.list | calls:read (preview) |
| phoneNumbers.list / update | session-only today (403 for every key): put numbers in pools in the app |
| conversations.list / get | conversations:read |
| conversations.delete | conversations:write |
| knowledge.list / search | knowledge:read |
| knowledge.add / addFile / remove | knowledge:write |
| chat.start / send / reply / ask, stream | chat:write |
| voice.session | voice_sessions:write |
| meetings.list / get | meetings:read |
| meetings.join | meetings:join |
| meetings.leave | meetings:write |
| phone.call | session-only today (403 for every key), kept for when a phone scope exists |
signUserId(secret, userId), verifyWebhook(secret, headers, body) and the oauth helpers (pkce,
authorizeUrl, exchangeCode) need no key.
Development
pnpm --filter @tony/shared build # the API description and the shared types
pnpm --filter @rydhm/sdk generate # src/types.gen.ts from the OpenAPI document
pnpm --filter @rydhm/sdk typecheck # also checks the SDK's types against @tony/shared (test/parity.ts)
pnpm --filter @rydhm/sdk test
pnpm --filter @rydhm/sdk build # dist/ (ESM) and dist/cjs/ (CommonJS)The rep-call methods live in src/rep-calls/ (types and resources). test/parity.ts checks every
DTO (field names included) against the API's own types in @tony/shared, so a change to a route's
shape fails typecheck here until the SDK follows.
