@sts-ai/sdk 1.0.0 → 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -76,6 +76,23 @@ export function createChat(sts) {
76
76
  }
77
77
  const MAX_CAPTIONS = 20;
78
78
  const LEVEL_INTERVAL_MS = 100;
79
+ /** A plain reason the visitor can act on when the browser won't give the call a microphone. */
80
+ function micErrorMessage(error) {
81
+ // No mediaDevices at all: the page isn't secure (http on a real domain), so no browser offers a mic.
82
+ if (typeof navigator !== 'undefined' && !navigator.mediaDevices)
83
+ return 'The microphone needs a secure (https) page.';
84
+ // DOMException isn't an Error subclass in every browser, so read the name directly.
85
+ const raw = error && typeof error === 'object' ? error.name : undefined;
86
+ const name = typeof raw === 'string' ? raw : '';
87
+ if (name === 'NotAllowedError' || name === 'SecurityError' || name === 'PermissionDeniedError') {
88
+ return 'Microphone is blocked. Allow it for this site (the icon in the address bar), then try again.';
89
+ }
90
+ if (name === 'NotFoundError' || name === 'OverconstrainedError')
91
+ return 'No microphone was found.';
92
+ if (name === 'NotReadableError' || name === 'AbortError')
93
+ return 'The microphone is busy in another app.';
94
+ return errorMessage(error);
95
+ }
79
96
  /**
80
97
  * Voice AI as a service: a real-time call with the business's AI over WebRTC (LiveKit is
81
98
  * included). Your orb, call button and captions are yours; call `start()` from a click.
@@ -86,6 +103,8 @@ export function createVoice(sts) {
86
103
  let callTimer = null;
87
104
  let levelTimer = null;
88
105
  let audioEls = [];
106
+ /** Bumped by every start and stop, so a hang-up cancels a call that is still connecting. */
107
+ let attempt = 0;
89
108
  function upsertCaption(caption) {
90
109
  state.set((s) => {
91
110
  const index = s.captions.findIndex((item) => item.id === caption.id);
@@ -94,6 +113,7 @@ export function createVoice(sts) {
94
113
  });
95
114
  }
96
115
  async function stop() {
116
+ attempt++;
97
117
  if (callTimer)
98
118
  clearTimeout(callTimer);
99
119
  if (levelTimer)
@@ -111,45 +131,90 @@ export function createVoice(sts) {
111
131
  async function start(participantName) {
112
132
  if (room || state.get().state === 'connecting')
113
133
  return;
114
- state.set({ state: 'connecting', error: null, captions: [] });
134
+ const current = ++attempt;
135
+ const cancelled = () => current !== attempt;
136
+ state.set({ state: 'connecting', error: null, captions: [], muted: false });
137
+ let next = null;
138
+ let mic = null;
139
+ // This attempt's agent audio: only handed to the call once it is live, removed otherwise.
140
+ const attemptAudio = [];
115
141
  try {
116
- const [{ Room, RoomEvent, Track }, details] = await Promise.all([import('livekit-client'), sts.speak.connect(participantName)]);
117
- const next = new Room();
118
- next.on(RoomEvent.TrackSubscribed, (track) => {
119
- if (track.kind !== Track.Kind.Audio)
142
+ const livekit = await import('livekit-client');
143
+ // Hung up while livekit-client loaded: don't ask for the mic at all.
144
+ if (cancelled())
145
+ return;
146
+ const { Room, RoomEvent, Track } = livekit;
147
+ // The microphone comes first: when it is blocked, no call room is opened and no agent is
148
+ // sent into one to wait for a visitor who can't be heard.
149
+ mic = await livekit.createLocalAudioTrack().catch((error) => {
150
+ throw new Error(micErrorMessage(error));
151
+ });
152
+ if (cancelled())
153
+ return void mic.stop();
154
+ const details = await sts.speak.connect(participantName);
155
+ if (cancelled())
156
+ return void mic.stop();
157
+ const joining = new Room();
158
+ next = joining;
159
+ // A cancelled attempt's room must not play audio or write captions into a newer call.
160
+ joining.on(RoomEvent.TrackSubscribed, (track) => {
161
+ if (cancelled() || track.kind !== Track.Kind.Audio)
120
162
  return;
121
163
  const element = track.attach();
122
164
  element.style.display = 'none';
123
165
  document.body.appendChild(element);
124
- audioEls.push(element);
166
+ attemptAudio.push(element);
125
167
  });
126
- next.on(RoomEvent.ActiveSpeakersChanged, (speakers) => {
127
- state.set({ isAgentSpeaking: speakers.some((speaker) => speaker.identity !== next.localParticipant.identity) });
168
+ joining.on(RoomEvent.ActiveSpeakersChanged, (speakers) => {
169
+ if (cancelled())
170
+ return;
171
+ state.set({ isAgentSpeaking: speakers.some((speaker) => speaker.identity !== joining.localParticipant.identity) });
172
+ });
173
+ // Only the live call ends the call: a room dropped while cancelling must not stop a newer one.
174
+ joining.on(RoomEvent.Disconnected, () => {
175
+ if (room === joining)
176
+ void stop();
128
177
  });
129
- next.on(RoomEvent.Disconnected, () => void stop());
130
178
  // The voice agent publishes what both sides say on the "lk.transcription" text stream.
131
- next.registerTextStreamHandler('lk.transcription', async (reader, participant) => {
179
+ joining.registerTextStreamHandler('lk.transcription', async (reader, participant) => {
132
180
  const attributes = reader.info.attributes ?? {};
133
181
  const id = attributes['lk.segment_id'] || reader.info.id;
134
- const speaker = participant.identity === next.localParticipant.identity ? 'visitor' : 'agent';
182
+ const speaker = participant.identity === joining.localParticipant.identity ? 'visitor' : 'agent';
135
183
  let text = '';
136
184
  for await (const chunk of reader) {
185
+ if (cancelled())
186
+ return;
137
187
  text += chunk;
138
188
  upsertCaption({ id, speaker, text, final: false });
139
189
  }
190
+ if (cancelled())
191
+ return;
140
192
  upsertCaption({ id, speaker, text, final: true });
141
193
  });
142
- await next.connect(details.serverUrl, details.participantToken);
143
- await next.localParticipant.setMicrophoneEnabled(true);
144
- room = next;
194
+ await joining.connect(details.serverUrl, details.participantToken);
195
+ if (cancelled())
196
+ throw new Error('cancelled');
197
+ await joining.localParticipant.publishTrack(mic);
198
+ if (cancelled())
199
+ throw new Error('cancelled');
200
+ room = joining;
201
+ // Same array: audio the agent publishes later in the call lands here too, and stop() clears it.
202
+ audioEls = attemptAudio;
145
203
  levelTimer = setInterval(() => {
146
- const agent = [...next.remoteParticipants.values()][0];
204
+ const agent = [...joining.remoteParticipants.values()][0];
147
205
  state.set({ agentLevel: agent ? Math.min(1, agent.audioLevel) : 0 });
148
206
  }, LEVEL_INTERVAL_MS);
149
207
  state.set({ state: 'live' });
150
208
  callTimer = setTimeout(() => void stop(), details.maxCallMinutes * 60000);
151
209
  }
152
210
  catch (error) {
211
+ // Never leave a half-joined room behind (disconnecting also stops a published mic).
212
+ mic?.stop();
213
+ attemptAudio.forEach((el) => el.remove());
214
+ if (next && room !== next)
215
+ await next.disconnect().catch(() => undefined);
216
+ if (cancelled())
217
+ return;
153
218
  state.set({ state: 'error', error: errorMessage(error) });
154
219
  await stop();
155
220
  }
package/dist/core.js CHANGED
@@ -9,12 +9,32 @@ async function readJson(response) {
9
9
  function toError(response, body) {
10
10
  return new StsError(body.error || `Request failed (${response.status})`, body.code || 'REQUEST_FAILED', response.status, body.fieldId ?? null);
11
11
  }
12
+ /**
13
+ * apiBase is where sts-ai runs, never the website itself. Same origin almost always means the
14
+ * site and a local sts-ai were both given localhost:3000, so every call 404s on the website.
15
+ */
16
+ function warnIfSameOrigin(apiBase) {
17
+ if (typeof window === 'undefined' || !window.location?.origin)
18
+ return;
19
+ let origin;
20
+ try {
21
+ origin = new URL(apiBase, window.location.href).origin;
22
+ }
23
+ catch {
24
+ return;
25
+ }
26
+ if (origin !== window.location.origin)
27
+ return;
28
+ console.error(`[sts-ai] apiBase is ${apiBase}, the same address as this website, so every call goes to the website instead of sts-ai. ` +
29
+ 'Set apiBase to where sts-ai runs: https://sudotechserve.com, or a local sts-ai on another port (e.g. http://localhost:3001).');
30
+ }
12
31
  /**
13
32
  * Framework-agnostic STS-AI client. One instance per site.
14
33
  * Handles the site-key → session exchange and refreshes the session before it expires.
15
34
  */
16
35
  export function createSts(options) {
17
36
  const apiBase = options.apiBase.replace(/\/$/, '');
37
+ warnIfSameOrigin(apiBase);
18
38
  let session = null;
19
39
  let pending = null;
20
40
  async function openSession() {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sts-ai/sdk",
3
- "version": "1.0.0",
3
+ "version": "1.0.2",
4
4
  "description": "One package for every sts-ai service on your own website: Chat AI, Voice AI, Form, Tour and business details. Your design, our services. React, Vue/Nuxt or plain JavaScript.",
5
5
  "license": "MIT",
6
6
  "type": "module",