npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@sphoro/voice-web

v1.3.0

Published

Browser client for Sphoro Voice: a conversation with an agent, or a headless softphone for a dialler inside your own product

Readme

@sphoro/voice-web

Voice in the browser, two ways.

startCall — a live conversation with an agent. A call button on a website, in about five lines.

createHandset — a telephone. Dials numbers, rings when somebody calls back, holds one call and knows what it is doing. This is what a dialler inside a CRM is built on, and it is headless on purpose: no DOM, no styles, no markup, because a dialler in your product has to look like your product.

Underneath both is the audio client the platform's own operator console runs on. Microphone capture, anti-aliased downsampling to the 8 kHz the media path speaks, μ-law, 20 ms framing, playback paced by the audio clock, barge-in, in-band DTMF for the keypad, and an AudioWorklet with a working fallback for the browsers where worklets do not load. Zero dependencies, no build step, and no asset to host.

npm install @sphoro/voice-web

The whole integration

Your server — one route, so your API key never reaches a page:

app.post('/api/voice-token', async (req, res) => {
  await requireSignedIn(req)                     // however you already do this

  const minted = await fetch('https://your-deployment/v1/realtime/tokens', {
    method: 'POST',
    headers: {
      Authorization: `Bearer ${process.env.VOICEAI_API_KEY}`,
      'Content-Type': 'application/json',
    },
    // Forward what the page sent, then decide the agent yourself. The page's body carries
    // `client` — which client library and version is placing the call — and that is what
    // puts "SDK · @sphoro/voice-web/1.3.0" in your call history instead of a bare row.
    // Nothing in it can be trusted, which is why `agent_id` is set after the spread.
    body: JSON.stringify({
      ...req.body,
      agent_id: 'agt_5c6388e49199af91775dd45b',
    }),
  })
  res.status(minted.status).json(await minted.json())
})

Your page:

import { startCall } from '@sphoro/voice-web'

const call = await startCall({ tokenUrl: '/api/voice-token' })

call.on('transcript', ({ speaker, text }) => console.log(speaker, text))
hangUpButton.onclick = () => call.hangUp()

That is the integration. startCall resolves once the session is live, so the line after it can render a call that is genuinely running.

Or without a build step at all

<script type="module"
        src="https://your-deployment/v1/embed/widget.js"
        data-token-url="/api/voice-token"></script>

A call button in the corner of the page, with a transcript, mute and hang-up. Same server route. type="module" is required. See the widget below.


Why the token endpoint

A browser cannot hold an API key — shipping it to the page ships it to everyone who loads the page. POST /v1/realtime/tokens exists so it does not have to: your server calls it with your key, and what comes back is a credential that

  • names one call, which already exists, so it cannot start conversations on your account,
  • carries calls:write and nothing else, so it cannot read an agent, a transcript, or another call,
  • expires in five minutes by default, and
  • is refused on every path but the realtime socket itself.

Return that response to your page unchanged. Its url already carries the credential.

What ends up in your call history

Every call minted here is recorded with source: "sdk", because that is what this endpoint is for — a browser client that cannot hold a key. It is derived from the endpoint you reached and the credential you used, not from anything the request claims, so a call placed from the platform's own console is app and one your backend places directly is sdk or api, and no integration can file itself under the wrong one.

The version is the part you have to hand over. startCall puts client: "@sphoro/voice-web/1.3.0" in the body it POSTs to your token route; forward that body — the spread above — and the call names the exact release that placed it. Drop it and the call is still sdk, just without the version, which is the difference between "one of our browser integrations" and "the one we shipped on Tuesday" when something starts going wrong.

Set tokenBody: { client: 'checkout-widget/3.1' } to name your own application instead, or tokenBody: { client: null } to send nothing — the field is added to the body your page POSTs, and a route that validates its input strictly would rather be told than surprised.

The other route, place on a handset, goes to POST /v1/calls with your own key, and there the User-Agent is what names the client. Placing those through @sphoro/voice records them as sdk; a bare fetch records them as api.


API

startCall(options): Promise<Call>

| Option | | |---|---| | tokenUrl | Your route, POSTed to. The usual choice. | | agentId | Sent as agent_id, for a page that picks between agents. | | tokenBody | Merged into the POST body. Set client to name your own application in call history. | | token | A RealtimeToken, or an async function returning one, if you fetch it yourself. | | url | A realtime URL that already carries its credential. | | on | Handlers attached before connecting, so nothing between start and subscribe is missed. | | workletUrl | Where to fetch the audio worklet. Only needed under a CSP that refuses this package's origin. | | timeoutMs | How long to wait for the session. Default 20000. |

Rejects with a VoiceError if the session does not start — an expired token, an agent that does not exist, a deployment with no realtime service, or the timeout.

Call

call.on('transcript', ({ speaker, text, final }) => {})  // speaker: 'caller' | 'agent'
call.on('state',      (state, detail) => {})             // connecting | ringing | live | ended | failed
call.on('activity',   (a) => {})                         // idle | listening | thinking | speaking
call.on('level',      (v) => {})                         // 0–1 mic level, ~50×/second
call.on('tool',       (name) => {})                      // a tool the agent called
call.on('error',      (message) => {})                   // a sentence. Not fatal on its own.

call.mute(); call.unmute()
call.say('are you open on saturday?')   // a typed turn
call.hangUp()                           // lets the server write the transcript first
call.dispose()                          // the component unmounted; drop everything now

on returns its own unsubscribe function, so a component can clean up.

call.agent carries the agent's name and language when the mint response included them — enough to label the call without a second request needing a stronger credential.


Things that will bite you if this were hand-written

Listed because they are the reasons to use this rather than the protocol directly. Each one was a bug here first.

Playback has to be paced. Audio written to a sink as fast as it arrives finishes instantly: a nine-second greeting handed over in three milliseconds ends the speaking state before the caller has heard a word, and barge-in — which only applies while the agent is speaking — silently stops working. Playback is drained by the audio clock.

Barge-in needs a local flush. Sending interrupt abandons the turn on the server, but the agent keeps talking for as long as the already-buffered audio lasts. The buffer is dropped locally at the same moment, which is the half the caller actually hears.

Filter before you decimate. Dropping five samples in six on the way to 8 kHz folds everything above 4 kHz back into the speech band. It does not sound muffled, it sounds like a robot gargling, and nothing downstream can undo it.

AudioWorklet.addModule can hang. Not reject — hang, with the promise never settling, on environments where the audio rendering thread never starts. A client that awaits it plays nothing, hears nothing, and reports no error. The wait here is bounded and falls through to a ScriptProcessorNode graph.

The microphone is optional. Playback is built before capture, so a declined permission prompt leaves a call the visitor can still hear, read and type into, rather than no call.

Formats are negotiated, not assumed. The encoding and sample rate are read from session.created. A client that hardcodes them plays noise the day a deployment changes.


The widget

<script type="module"
        src="https://your-deployment/v1/embed/widget.js"
        data-token-url="/api/voice-token"
        data-agent="agt_5c6388e49199af91775dd45b"
        data-label="Talk to us"
        data-title="Acme support"
        data-position="bottom-right"
        data-accent="#4f46e5"></script>

| Attribute | | |---|---| | data-token-url | Required. Your route. Nothing renders without it. | | data-agent | Sent as agent_id. Omit if your route decides. | | data-label | The button. Default "Talk to us". | | data-title | The panel heading. Replaced by the agent's name once connected. | | data-position | bottom-right or bottom-left. | | data-accent | Any CSS colour. | | data-auto-open | true starts a call on load. Off by default — a page that opens a microphone before the visitor asked is a page nobody trusts. |

It renders in a shadow root, so your stylesheet cannot reach in and it cannot leak out. It follows the visitor's light/dark preference.

The widget is deliberately not themeable beyond this. Anything more should use startCall and draw its own interface — a widget with forty options is a worse version of the SDK it is built on.

Serving it from your deployment (/v1/embed/widget.js) rather than a CDN is what keeps the client and the protocol in step: the page always loads the client that matches the server it is about to talk to.


Frameworks

There is no React package and there does not need to be one:

useEffect(() => {
  let call
  startCall({ tokenUrl: '/api/voice-token', on: { transcript: append, state: setState } })
    .then((c) => { call = c })
    .catch((err) => setError(err.message))
  // dispose, not hangUp: an unmount is not a hang-up, and hangUp waits for the server.
  return () => call?.dispose()
}, [])

For a component that owns its own state, WebCall is the engine underneath, taking a handler object rather than events. import { WebCall } from '@sphoro/voice-web'.


Browser support

Anything with AudioWorklet and getUserMedia — every current browser. Where the worklet cannot load, capture and playback fall back to ScriptProcessorNode and scheduled AudioBuffers automatically; the wire is identical either way.

A secure context is required. getUserMedia is unavailable on plain http:// except on localhost. This is the browser's rule, not ours, and it is the most common reason a call that works locally is silent on a staging server.


Not in a browser?

The realtime protocol is a plain WebSocket, documented in docs/realtime.md, and the token endpoint above is how any client gets a credential for it — a native app, a kiosk, an embedded device. The Go, Node and Java SDKs all speak it server-side.


A telephone: createHandset

startCall above opens one conversation whose far end is a model. It is not a telephone: it cannot dial a number, nothing rings on it, and there is no second call.

This is the telephone.

import { createHandset } from '@sphoro/voice-web'

const phone = createHandset(
  {
    place:   '/api/voice/calls',
    token:   (id) => `/api/voice/calls/${id}/token`,
    ringing: '/api/voice/ringing',
  },
  // Your own name for whoever is holding this handset. Only this one is a browser's to
  // send — the member id that decides which lines may be answered comes from your server,
  // on the two routes above. See "two names for one person" below.
  { participant: currentUser.id },
)

phone.on('state', (s) => render(s))       // idle · dialling · ringing · live · ended · failed
phone.on('incoming', (call) => offer(call))
phone.on('level', (l) => meter(l))

callButton.onclick  = () => phone.dial('+919109099359')
answerButton.onclick = () => phone.answer()
hangUpButton.onclick = () => phone.hangUp()
keypad.onpress = (digit) => phone.sendDigit(digit)

That is the whole client. There is no interface in this package — you draw the phone, and this owns the parts that are genuinely hard and identical everywhere: the audio, the protocol, the call lifecycle, and the race when two people answer one call.

If you want the interface too, embed the platform's own console instead — one script tag, see /v1/embed/dialer.js. This is for the other case, which is the one people ask for second and want more.

Your three routes

A browser cannot hold an account API key — anything the page can read, everyone who loads the page can read. So each endpoint above is a route on your server that authenticates your user however you already do and forwards to the platform with your key. With @sphoro/voice that is a few lines each:

import { SphoroVoice } from '@sphoro/voice'
const voice = new SphoroVoice({ apiKey: process.env.SPHORO_VOICE_API_KEY })

// Place a call the telecaller will speak on.
app.post('/api/voice/calls', async (req, res) => {
  const user = await requireSignedIn(req)
  if (!mayDial(user, req.body.to)) return res.sendStatus(403)   // your rule, your data

  const call = await voice.calls.create({
    agentId: process.env.DIALER_AGENT_ID,   // an agent whose autonomy is "simple"
    to: req.body.to,
    direction: 'outbound',
    memberId: user.voiceMemberId,           // so the caller ID is their own line
  })
  const token = await voice.calls.token(call.id, user.id)
  res.json({ ...token, id: call.id })       // both in one response saves a round trip
})

// Join a call — answering a ringing one, or reconnecting to your own.
app.post('/api/voice/calls/:id/token', async (req, res) => {
  const user = await requireSignedIn(req)
  res.json(await voice.calls.token(req.params.id, user.id, {
    memberId: user.sphoroMemberId,             // see "two names for one person" below
  }))
})

// What is ringing. One upstream connection per telecaller.
app.get('/api/voice/ringing', async (req, res) => {
  const user = await requireSignedIn(req)
  const upstream = await voice.calls.ringing({ memberId: user.sphoroMemberId })
  res.setHeader('Content-Type', 'text/event-stream')
  res.setHeader('Cache-Control', 'no-cache, no-transform')
  res.setHeader('X-Accel-Buffering', 'no')       // or nginx holds the whole stream
  Readable.fromWeb(upstream.body).pipe(res)
})

Two names for one person

Both routes above pass two identifiers, and the difference is the one thing worth reading this section for.

participant is yours — a user id, an email, a desk number. It is stored verbatim on the call record and never interpreted, which is what makes "whose call was this" answerable inside your product months later.

memberId is the same person as this platform knows them: the member id the portal shows. It is the only one a permission check can use, because that is the vocabulary a number's assignment is written in. A number that is one telecaller's direct line is assigned to a member id; your own label for that person means nothing to it.

Send both wherever any number on the account is a direct line, and send the same member id to both routes. Send it to only one and you get the confusing half-working state this is here to prevent: the feed offers a telecaller their own calls and the join route refuses every one of them with "that call is to somebody else's direct line". Send it to neither and a direct line never rings at all — a watcher who has not said who they are is not "everybody", and is shown no assigned number's calls.

Both come from your server, never from the page. A browser that can name the member it is answering as can name somebody else's, which is the entire thing an assignment prevents.

If every number on the account is shared across the whole team, none of this applies and memberId can be left out.

Your server is also where the decisions live that only it can make: which of your users may dial at all, which numbers they may dial, and which of them a given inbound call should be offered to. None of that is expressible in a browser, and a check in one is not a check.

Pipe the ringing stream through untouched. It carries two kinds of event: the unnamed frames your handset renders, and a heartbeat every five seconds carrying the full list of what is ringing right now. The heartbeat is what makes an inbound call reliable rather than likely — see why the feed heals itself — and a proxy that filters, batches, or rewrites the stream takes that away. Readable.fromWeb(...).pipe(res) above is the whole correct implementation; the X-Accel-Buffering header matters for the same reason.

The handset

| | | |---|---| | dial(to) | Ring a number in E.164. Resolves once the call is up — the session is live and the far end is ringing, not that anybody answered. | | answer(id?) | Answer a ringing call, or the only one ringing. The race between two people is decided by the platform; the loser gets an error, which is an ordinary outcome. | | ignore(id) | Take a call off this screen. Local only — it does not end the caller's leg. | | hangUp() | End the call, letting the server write the record first. | | mute() / unmute() / muted | | | sendDigit(d) | 0-9, *, #. In-band, which is what an IVR is listening for. | | watch() / unwatch() | Listen for inbound calls. On by default when you pass ringing. The stream is watched for silence and replaced when it dies — see below. | | dispose() | Drop the call, the stream and the listeners. | | state | idle · dialling · ringing · live · ended · failed | | call | The call in progress: {id, number, direction, line}, or null. | | incoming | A Map of calls ringing and not yet answered. |

Events: state, incoming, settled, call, level, keypress, error.

Why the feed heals itself

An inbound call that rings on one handset and not another — and a different one each time — is the complaint this design exists to answer. It has two causes, and neither leaves a trace.

A feed that falls behind loses frames. The platform will not stall a live call's media path for a slow browser, so a subscriber that stops reading has its overflow discarded, and what gets discarded is whatever arrived next. Sometimes that is the ringing call.

A feed can also die without saying so. A laptop that slept, a NAT that timed the flow out, a proxy that stopped forwarding: the connection stays open as far as the page is concerned. No bytes, no error, no reconnect. EventSource cannot reconnect from something it was never told about.

Nothing in a stream of ringing frames can tell "no frame arrived" from "no call is ringing", so the handset does not try. Every five seconds the platform restates the whole truth — everything this watcher should have a telephone on screen for — as a named heartbeat event. The handset reconciles against it, so a ring lost to either cause is recovered on the next beat instead of for the length of the call. And because something now arrives on a schedule even when the account is idle, silence is diagnostic: twenty seconds of it means the stream is gone whatever it claims, and the handset replaces it.

You get all of this by passing ringing and leaving the stream alone. Two consequences worth knowing:

  • A settled event may carry the reason no_longer_ringing. It means the platform stopped offering the call and this handset never saw why — a frame went missing and the heartbeat corrected for it. Treat it as an ending you have no detail about.
  • ignore(id) is remembered until the platform stops listing the call, so a dismissed call is not put back on screen by the next heartbeat.

The heartbeat is a named SSE event, which means onmessage never sees it. A client written against this feed before heartbeats existed is unaffected.

Two things that catch people

ringing means two different things. The handset's ringing state is the far end's telephone ringing on a call you placed. A call ringing at you is inbound and unanswered — that is the incoming event, and it does not move the state, because you may be on another call while a second one rings.

Time out on ringsForMs, never on a deadline. An absolute timestamp is only as good as the clock reading it, and that clock belongs to whatever laptop your page is open on. A browser an hour fast sees every call as already expired and never rings.

Only a call a person answers

The platform refuses a token for anything else. An agentic call already has both ends, and a webrtc call is a rendezvous between two browsers rather than a leg carrying audio — joining either connects, reports itself live, and carries no audio in either direction. Place dialler calls on an agent whose autonomy is "simple".