@guava-ai/guava-sdk 0.37.0 → 0.39.0

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.
@@ -0,0 +1,497 @@
1
+ import { type ConnectingTone, JingleTone, LeavingTone, type Tone } from "./tones.ts";
2
+
3
+ export { type ConnectingTone, JingleTone, RingbackTone, LeavingTone, type Tone } from "./tones.ts";
4
+
5
+ export type CallState =
6
+ | "not-started" // start() hasn't been called yet.
7
+ | "starting" // Starting the call. Do not play a Ringback yet.
8
+ | "waiting-for-permission" // We're waiting for the Microphone permission prompt. You may show a reminder UI here.
9
+ | "connecting" // The call is now connection to the remote. This is where you can play a ringback or other connecting tone.
10
+ | "connected" // The call is now connected and the audio channel is established.
11
+ | "ended"; // The call has ended.
12
+
13
+ export type CallErrorCode =
14
+ | "MICROPHONE_ACCESS_FAILED"
15
+ | "CONNECTION_FAILED"
16
+ | "AUTHENTICATION_FAILED"
17
+ | "PROTOCOL_ERROR" // The server sent an unexpected message.
18
+ | "SERVER_ERROR" // The server sent an error message.
19
+ | "REMOTE_HANGUP" // The remote hung up before the call connected.
20
+ | "CONNECTION_TIMEOUT"; // The call didn't connect within connectionTimeoutMs.
21
+
22
+ export class CallError extends Error {
23
+ readonly code: CallErrorCode;
24
+
25
+ constructor(code: CallErrorCode, message: string, options?: ErrorOptions) {
26
+ super(message, options);
27
+ this.name = "CallError";
28
+ this.code = code;
29
+ }
30
+ }
31
+
32
+ // Used if the server doesn't send ICE servers with the auth reply.
33
+ const DEFAULT_ICE_SERVERS: RTCIceServer[] = [
34
+ { urls: ["stun:stun.l.google.com:19302", "stun:stun.sipgate.net:10000"] },
35
+ ];
36
+
37
+ const SOCKET_PROTOCOLS: Record<string, string> = {
38
+ "http:": "ws:",
39
+ "https:": "wss:",
40
+ "ws:": "ws:",
41
+ "wss:": "wss:",
42
+ };
43
+
44
+ // Messages received on the signaling socket. See junkswitch/junkswitch/webrtcsocket.py.
45
+ type SignalingMessage =
46
+ | {
47
+ type: "auth";
48
+ body: "OK" | "FAIL";
49
+ reason?: string;
50
+ ice_servers?: RTCIceServer[];
51
+ }
52
+ | { type: "desc"; body: RTCSessionDescriptionInit }
53
+ | { type: "candidate"; body: RTCIceCandidateInit }
54
+ | { type: "hangup" }
55
+ | { type: "error"; body?: string }
56
+ | { type: "transfer" };
57
+
58
+ export class Call {
59
+ private _state: CallState = "not-started";
60
+ private _error?: CallError;
61
+ private readonly _stateHandlers = new Set<(state: CallState) => void>();
62
+ private readonly _remoteStreamHandlers = new Set<(stream: MediaStream) => void>();
63
+ private readonly _messageHandlers = new Set<(payload: Record<string, unknown>) => void>();
64
+ private readonly _webrtcCode: string;
65
+ private readonly _sockUrl: URL;
66
+
67
+ private readonly _remoteAudio: HTMLAudioElement;
68
+ private readonly _connectingTone?: ConnectingTone;
69
+ private readonly _leavingTone?: Tone;
70
+ private readonly _connectionTimeoutMs?: number;
71
+ private readonly _customPayload: Record<string, unknown>;
72
+ private _connectionTimer?: ReturnType<typeof setTimeout>;
73
+ private _sock?: WebSocket;
74
+
75
+ private readonly _chatSockUrl: URL;
76
+ // Links the chat socket to this call's session on the server.
77
+ private readonly _chatSessionId = crypto.randomUUID();
78
+ private _chatSock?: WebSocket;
79
+ private _chatReady = false;
80
+ // Messages sent before the chat socket is ready.
81
+ private _pendingChatMessages: string[] = [];
82
+
83
+ private _localStream?: MediaStream;
84
+ private _peerConnection?: RTCPeerConnection;
85
+ private _remoteStream?: MediaStream;
86
+ private _iceServers?: RTCIceServer[];
87
+ // Settles the promise returned by start().
88
+ private _pendingStart?: { resolve: () => void; reject: (error: CallError) => void };
89
+
90
+ constructor({
91
+ webrtcCode,
92
+ baseUrl = "https://app.goguava.ai/",
93
+ connectingTone = new JingleTone(),
94
+ leavingTone = new LeavingTone(),
95
+ connectionTimeoutMs = 30_000,
96
+ customPayload = {},
97
+ }: {
98
+ /** Code used to authenticate with the signaling server. */
99
+ webrtcCode: string;
100
+ /** Base URL of the Guava server. Defaults to `https://app.goguava.ai/`. */
101
+ baseUrl?: string;
102
+ /** Played while the call is in the "connecting" state. Defaults to {@link JingleTone}. */
103
+ connectingTone?: ConnectingTone | "disabled";
104
+ /** Played when the call ends. Defaults to {@link LeavingTone}. */
105
+ leavingTone?: Tone | "disabled";
106
+ /** Max time in the "connecting" state before the call fails with CONNECTION_TIMEOUT. Defaults to 30 seconds. */
107
+ connectionTimeoutMs?: number | "disabled";
108
+ /** A custom payload that is forwarded to the agent at the start of the call. */
109
+ customPayload?: Record<string, unknown>;
110
+ }) {
111
+ this._webrtcCode = webrtcCode;
112
+ this._customPayload = customPayload;
113
+ if (connectingTone !== "disabled") {
114
+ this._connectingTone = connectingTone;
115
+ }
116
+ if (leavingTone !== "disabled") {
117
+ this._leavingTone = leavingTone;
118
+ }
119
+ if (connectionTimeoutMs !== "disabled") {
120
+ this._connectionTimeoutMs = connectionTimeoutMs;
121
+ }
122
+
123
+ this._sockUrl = new URL("/webrtc/", baseUrl);
124
+ const sockProtocol = SOCKET_PROTOCOLS[this._sockUrl.protocol];
125
+ if (sockProtocol === undefined) {
126
+ throw new Error(`Unsupported baseUrl protocol: ${this._sockUrl.protocol}`);
127
+ }
128
+ this._sockUrl.protocol = sockProtocol;
129
+ this._chatSockUrl = new URL("/webrtc-chat/", this._sockUrl);
130
+
131
+ this._remoteAudio = document.createElement("audio");
132
+ this._remoteAudio.autoplay = true;
133
+ }
134
+
135
+ get state(): CallState {
136
+ return this._state;
137
+ }
138
+
139
+ // Set if the call ended due to a failure.
140
+ get error(): CallError | undefined {
141
+ return this._error;
142
+ }
143
+
144
+ // Set once the remote audio track arrives, which happens before the call reaches "connected".
145
+ get remoteStream(): MediaStream | undefined {
146
+ return this._remoteStream;
147
+ }
148
+
149
+ // Returns a function that unregisters the handler.
150
+ onStateChange(handler: (state: CallState) => void): () => void {
151
+ this._stateHandlers.add(handler);
152
+ return () => {
153
+ this._stateHandlers.delete(handler);
154
+ };
155
+ }
156
+
157
+ // Fires whenever the remote stream is replaced, including the first time it arrives.
158
+ // Returns a function that unregisters the handler.
159
+ onRemoteStream(handler: (stream: MediaStream) => void): () => void {
160
+ this._remoteStreamHandlers.add(handler);
161
+ return () => {
162
+ this._remoteStreamHandlers.delete(handler);
163
+ };
164
+ }
165
+
166
+ /**
167
+ * Registers a handler for messages the agent sends with `call.send_webrtc_message()`.
168
+ * @param handler - Called with each message's payload.
169
+ * @returns A function that unregisters the handler.
170
+ */
171
+ onMessage(handler: (payload: Record<string, unknown>) => void): () => void {
172
+ this._messageHandlers.add(handler);
173
+ return () => {
174
+ this._messageHandlers.delete(handler);
175
+ };
176
+ }
177
+
178
+ private _setState(state: CallState) {
179
+ if (state === this._state) {
180
+ return;
181
+ }
182
+
183
+ if (state === "ended") {
184
+ this._leavingTone?.play();
185
+ }
186
+
187
+ this._state = state;
188
+ if (state === "connecting") {
189
+ this._connectingTone?.start();
190
+ if (this._connectionTimeoutMs !== undefined) {
191
+ this._connectionTimer = setTimeout(() => {
192
+ this._send({ type: "hangup" });
193
+ this._end(new CallError("CONNECTION_TIMEOUT", "Timed out connecting the call."));
194
+ }, this._connectionTimeoutMs);
195
+ }
196
+ } else {
197
+ this._connectingTone?.stop();
198
+ clearTimeout(this._connectionTimer);
199
+ this._connectionTimer = undefined;
200
+ }
201
+ for (const handler of this._stateHandlers) {
202
+ handler(state);
203
+ }
204
+ }
205
+
206
+ async start() {
207
+ if (this._state !== "not-started") {
208
+ throw new Error(`start() was already called.`);
209
+ }
210
+ this._setState("starting");
211
+
212
+ // Add the audio element.
213
+ document.body.appendChild(this._remoteAudio);
214
+
215
+ // We start by requesting device permissions first. The idea is that, after permission has been granted,
216
+ // it makes sence to play a ringback, but it doesn't make sense to do so during the permission prompt.
217
+
218
+ const permissionTimer = setTimeout(() => {
219
+ this._setState("waiting-for-permission");
220
+ }, 500);
221
+
222
+ try {
223
+ this._localStream = await navigator.mediaDevices.getUserMedia({ audio: true, video: false });
224
+ } catch (error) {
225
+ const callError = new CallError("MICROPHONE_ACCESS_FAILED", "Failed to access microphone.", {
226
+ cause: error,
227
+ });
228
+ this._end(callError);
229
+ throw callError;
230
+ } finally {
231
+ clearTimeout(permissionTimer);
232
+ }
233
+
234
+ // hangup() was called during the permission prompt.
235
+ if (this.state === "ended") {
236
+ this._teardown();
237
+ return;
238
+ }
239
+
240
+ // Now open and authenticate the signaling socket.
241
+ this._setState("connecting"); // UI can start playing rinback tones here.
242
+ const started = new Promise<void>((resolve, reject) => {
243
+ this._pendingStart = { resolve, reject };
244
+ });
245
+
246
+ this._sock = new WebSocket(this._sockUrl);
247
+ this._sock.onopen = () => {
248
+ this._send({
249
+ type: "auth",
250
+ body: JSON.stringify({
251
+ webrtc_code: this._webrtcCode,
252
+ chat_session_id: this._chatSessionId,
253
+ }),
254
+ });
255
+ };
256
+ this._sock.onmessage = (event) => {
257
+ this._onMessage(JSON.parse(event.data) as SignalingMessage);
258
+ };
259
+ this._sock.onclose = () => {
260
+ this._end(new CallError("CONNECTION_FAILED", "Signaling connection closed."));
261
+ };
262
+
263
+ await started;
264
+ }
265
+
266
+ /**
267
+ * Sends a message to the agent, delivered to its `on_webrtc_message` handler.
268
+ * Messages sent before the message channel is ready are queued.
269
+ * @param payload - A JSON-serializable object.
270
+ */
271
+ sendMessage(payload: Record<string, unknown>) {
272
+ if (this._state === "not-started" || this._state === "ended") {
273
+ throw new Error(`sendMessage() called while the call is ${this._state}.`);
274
+ }
275
+ const message = JSON.stringify({ type: "webrtc-message", payload });
276
+ if (this._chatReady && this._chatSock !== undefined) {
277
+ this._chatSock.send(message);
278
+ } else {
279
+ this._pendingChatMessages.push(message);
280
+ }
281
+ }
282
+
283
+ private _openChatSocket() {
284
+ this._chatSock = new WebSocket(this._chatSockUrl);
285
+ this._chatSock.onopen = () => {
286
+ this._chatSock?.send(
287
+ JSON.stringify({ webrtc_code: this._webrtcCode, chat_session_id: this._chatSessionId }),
288
+ );
289
+ };
290
+ this._chatSock.onmessage = (event) => {
291
+ const message = JSON.parse(event.data) as {
292
+ type?: string;
293
+ command_type?: string;
294
+ payload?: Record<string, unknown>;
295
+ };
296
+ // The server sends "ready" once the call session is found.
297
+ if (message.type === "ready" && !this._chatReady) {
298
+ this._chatReady = true;
299
+ for (const pending of this._pendingChatMessages) {
300
+ this._chatSock?.send(pending);
301
+ }
302
+ this._pendingChatMessages = [];
303
+ } else if (message.command_type === "send-webrtc-message") {
304
+ for (const handler of this._messageHandlers) {
305
+ handler(message.payload ?? {});
306
+ }
307
+ }
308
+ };
309
+ }
310
+
311
+ async hangup() {
312
+ if (this._state === "not-started") {
313
+ throw new Error(`hangup() called before start().`);
314
+ }
315
+ if (this._state === "ended") {
316
+ return;
317
+ }
318
+ this._send({ type: "hangup" });
319
+ this._end();
320
+ }
321
+
322
+ private _send(message: { type: string; body?: unknown }) {
323
+ if (this._sock !== undefined && this._sock.readyState === WebSocket.OPEN) {
324
+ this._sock.send(JSON.stringify(message));
325
+ }
326
+ }
327
+
328
+ private _onMessage(message: SignalingMessage) {
329
+ switch (message.type) {
330
+ case "auth":
331
+ if (message.body !== "OK") {
332
+ this._end(
333
+ new CallError("AUTHENTICATION_FAILED", message.reason || "Authentication failed."),
334
+ );
335
+ return;
336
+ }
337
+ this._iceServers = message.ice_servers;
338
+ this._openChatSocket();
339
+ this._send({ type: "connect", body: { custom_payload: this._customPayload } });
340
+ void this._connectPeer();
341
+ break;
342
+ case "desc":
343
+ if (!this._peerConnection) {
344
+ this._end(
345
+ new CallError(
346
+ "PROTOCOL_ERROR",
347
+ "Received desc before the peer connection was created.",
348
+ ),
349
+ );
350
+ return;
351
+ }
352
+ this._peerConnection.setRemoteDescription(message.body).catch((error) => {
353
+ this._end(
354
+ new CallError("CONNECTION_FAILED", "Failed to set remote description.", {
355
+ cause: error,
356
+ }),
357
+ );
358
+ });
359
+ break;
360
+ case "candidate":
361
+ if (!this._peerConnection) {
362
+ this._end(
363
+ new CallError(
364
+ "PROTOCOL_ERROR",
365
+ "Received candidate before the peer connection was created.",
366
+ ),
367
+ );
368
+ return;
369
+ }
370
+ this._peerConnection.addIceCandidate(message.body).catch((error) => {
371
+ console.warn("Failed to add ICE candidate:", error);
372
+ });
373
+ break;
374
+ case "hangup":
375
+ if (this._state === "connected") {
376
+ this._end();
377
+ } else {
378
+ this._end(
379
+ new CallError("REMOTE_HANGUP", "The remote hung up before the call connected."),
380
+ );
381
+ }
382
+ break;
383
+ case "error":
384
+ this._end(new CallError("SERVER_ERROR", message.body || "Unknown server error."));
385
+ break;
386
+ case "transfer":
387
+ this._end(new CallError("PROTOCOL_ERROR", "Transfers are not supported."));
388
+ break;
389
+ default:
390
+ console.warn("Unknown signaling message:", message);
391
+ }
392
+ }
393
+
394
+ private async _connectPeer() {
395
+ if (!this._localStream) {
396
+ return;
397
+ }
398
+ this._peerConnection = new RTCPeerConnection({
399
+ iceServers: this._iceServers ?? DEFAULT_ICE_SERVERS,
400
+ });
401
+ this._peerConnection.onicecandidate = (event) => {
402
+ if (event.candidate) {
403
+ this._send({ type: "candidate", body: event.candidate });
404
+ }
405
+ };
406
+ this._peerConnection.ontrack = (event) => {
407
+ this._remoteStream = new MediaStream([event.track]);
408
+ this._remoteAudio.srcObject = this._remoteStream;
409
+ for (const handler of this._remoteStreamHandlers) {
410
+ handler(this._remoteStream);
411
+ }
412
+ };
413
+ this._peerConnection.onconnectionstatechange = () => {
414
+ if (this._peerConnection === undefined) {
415
+ return;
416
+ }
417
+ // "disconnected" is often transient, so wait for "failed" before ending the call.
418
+ if (this._peerConnection.connectionState === "connected") {
419
+ this._setState("connected");
420
+ if (this._pendingStart !== undefined) {
421
+ this._pendingStart.resolve();
422
+ this._pendingStart = undefined;
423
+ }
424
+ } else if (this._peerConnection.connectionState === "failed") {
425
+ this._end(new CallError("CONNECTION_FAILED", "Peer connection failed."));
426
+ }
427
+ };
428
+ for (const track of this._localStream.getAudioTracks()) {
429
+ this._peerConnection.addTrack(track);
430
+ }
431
+
432
+ try {
433
+ await this._peerConnection.setLocalDescription();
434
+ } catch (error) {
435
+ this._end(new CallError("CONNECTION_FAILED", "Failed to create offer.", { cause: error }));
436
+ return;
437
+ }
438
+
439
+ // The call may have ended while creating the offer.
440
+ if (this.state === "ended") {
441
+ return;
442
+ }
443
+ this._send({ type: "desc", body: this._peerConnection.localDescription });
444
+ }
445
+
446
+ private _end(error?: CallError) {
447
+ if (this._state === "ended") {
448
+ return;
449
+ }
450
+ this._error = error;
451
+ this._teardown();
452
+ this._setState("ended");
453
+
454
+ // If start() is still pending, it rejects on failure and resolves on hangup().
455
+ if (this._pendingStart !== undefined) {
456
+ if (error) {
457
+ this._pendingStart.reject(error);
458
+ } else {
459
+ this._pendingStart.resolve();
460
+ }
461
+ this._pendingStart = undefined;
462
+ }
463
+ }
464
+
465
+ private _teardown() {
466
+ // Close the signaling socket.
467
+ if (this._sock) {
468
+ // Don't fire close handlers for a socket we closed ourselves.
469
+ this._sock.onclose = null;
470
+ this._sock.close();
471
+ this._sock = undefined;
472
+ }
473
+
474
+ // Close the chat socket.
475
+ if (this._chatSock) {
476
+ this._chatSock.close();
477
+ this._chatSock = undefined;
478
+ }
479
+ this._chatReady = false;
480
+ this._pendingChatMessages = [];
481
+
482
+ // Close the peer connection.
483
+ if (this._peerConnection !== undefined) {
484
+ this._peerConnection.close();
485
+ this._peerConnection = undefined;
486
+ }
487
+ for (const track of this._localStream?.getTracks() ?? []) {
488
+ track.stop();
489
+ }
490
+ this._localStream = undefined;
491
+ this._remoteStream = undefined;
492
+
493
+ // Remove the audio element.
494
+ this._remoteAudio.srcObject = null;
495
+ this._remoteAudio.remove();
496
+ }
497
+ }