@talqing/sdk 0.1.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.
Files changed (108) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +193 -0
  3. package/dist/browser.d.ts +153 -0
  4. package/dist/browser.d.ts.map +1 -0
  5. package/dist/browser.js +440 -0
  6. package/dist/browser.js.map +1 -0
  7. package/dist/client.d.ts +101 -0
  8. package/dist/client.d.ts.map +1 -0
  9. package/dist/client.js +88 -0
  10. package/dist/client.js.map +1 -0
  11. package/dist/gen/apiVersion.d.ts +3 -0
  12. package/dist/gen/apiVersion.d.ts.map +1 -0
  13. package/dist/gen/apiVersion.js +4 -0
  14. package/dist/gen/apiVersion.js.map +1 -0
  15. package/dist/gen/client/client.gen.d.ts +3 -0
  16. package/dist/gen/client/client.gen.d.ts.map +1 -0
  17. package/dist/gen/client/client.gen.js +217 -0
  18. package/dist/gen/client/client.gen.js.map +1 -0
  19. package/dist/gen/client/index.d.ts +11 -0
  20. package/dist/gen/client/index.d.ts.map +1 -0
  21. package/dist/gen/client/index.js +7 -0
  22. package/dist/gen/client/index.js.map +1 -0
  23. package/dist/gen/client/types.gen.d.ts +121 -0
  24. package/dist/gen/client/types.gen.d.ts.map +1 -0
  25. package/dist/gen/client/types.gen.js +3 -0
  26. package/dist/gen/client/types.gen.js.map +1 -0
  27. package/dist/gen/client/utils.gen.d.ts +38 -0
  28. package/dist/gen/client/utils.gen.d.ts.map +1 -0
  29. package/dist/gen/client/utils.gen.js +231 -0
  30. package/dist/gen/client/utils.gen.js.map +1 -0
  31. package/dist/gen/client.gen.d.ts +13 -0
  32. package/dist/gen/client.gen.d.ts.map +1 -0
  33. package/dist/gen/client.gen.js +4 -0
  34. package/dist/gen/client.gen.js.map +1 -0
  35. package/dist/gen/core/auth.gen.d.ts +26 -0
  36. package/dist/gen/core/auth.gen.d.ts.map +1 -0
  37. package/dist/gen/core/auth.gen.js +15 -0
  38. package/dist/gen/core/auth.gen.js.map +1 -0
  39. package/dist/gen/core/bodySerializer.gen.d.ts +26 -0
  40. package/dist/gen/core/bodySerializer.gen.d.ts.map +1 -0
  41. package/dist/gen/core/bodySerializer.gen.js +58 -0
  42. package/dist/gen/core/bodySerializer.gen.js.map +1 -0
  43. package/dist/gen/core/params.gen.d.ts +44 -0
  44. package/dist/gen/core/params.gen.d.ts.map +1 -0
  45. package/dist/gen/core/params.gen.js +110 -0
  46. package/dist/gen/core/params.gen.js.map +1 -0
  47. package/dist/gen/core/pathSerializer.gen.d.ts +34 -0
  48. package/dist/gen/core/pathSerializer.gen.d.ts.map +1 -0
  49. package/dist/gen/core/pathSerializer.gen.js +107 -0
  50. package/dist/gen/core/pathSerializer.gen.js.map +1 -0
  51. package/dist/gen/core/queryKeySerializer.gen.d.ts +19 -0
  52. package/dist/gen/core/queryKeySerializer.gen.d.ts.map +1 -0
  53. package/dist/gen/core/queryKeySerializer.gen.js +93 -0
  54. package/dist/gen/core/queryKeySerializer.gen.js.map +1 -0
  55. package/dist/gen/core/serverSentEvents.gen.d.ts +72 -0
  56. package/dist/gen/core/serverSentEvents.gen.d.ts.map +1 -0
  57. package/dist/gen/core/serverSentEvents.gen.js +133 -0
  58. package/dist/gen/core/serverSentEvents.gen.js.map +1 -0
  59. package/dist/gen/core/types.gen.d.ts +84 -0
  60. package/dist/gen/core/types.gen.d.ts.map +1 -0
  61. package/dist/gen/core/types.gen.js +3 -0
  62. package/dist/gen/core/types.gen.js.map +1 -0
  63. package/dist/gen/core/utils.gen.d.ts +20 -0
  64. package/dist/gen/core/utils.gen.d.ts.map +1 -0
  65. package/dist/gen/core/utils.gen.js +88 -0
  66. package/dist/gen/core/utils.gen.js.map +1 -0
  67. package/dist/gen/index.d.ts +3 -0
  68. package/dist/gen/index.d.ts.map +1 -0
  69. package/dist/gen/index.js +3 -0
  70. package/dist/gen/index.js.map +1 -0
  71. package/dist/gen/sdk.gen.d.ts +2330 -0
  72. package/dist/gen/sdk.gen.d.ts.map +1 -0
  73. package/dist/gen/sdk.gen.js +4320 -0
  74. package/dist/gen/sdk.gen.js.map +1 -0
  75. package/dist/gen/types.gen.d.ts +17288 -0
  76. package/dist/gen/types.gen.d.ts.map +1 -0
  77. package/dist/gen/types.gen.js +3 -0
  78. package/dist/gen/types.gen.js.map +1 -0
  79. package/dist/index.d.ts +6 -0
  80. package/dist/index.d.ts.map +1 -0
  81. package/dist/index.js +6 -0
  82. package/dist/index.js.map +1 -0
  83. package/dist/vocabulary.d.ts +67 -0
  84. package/dist/vocabulary.d.ts.map +1 -0
  85. package/dist/vocabulary.js +12 -0
  86. package/dist/vocabulary.js.map +1 -0
  87. package/package.json +67 -0
  88. package/src/browser.tsx +675 -0
  89. package/src/client.ts +189 -0
  90. package/src/gen/apiVersion.ts +4 -0
  91. package/src/gen/client/client.gen.ts +277 -0
  92. package/src/gen/client/index.ts +27 -0
  93. package/src/gen/client/types.gen.ts +218 -0
  94. package/src/gen/client/utils.gen.ts +316 -0
  95. package/src/gen/client.gen.ts +16 -0
  96. package/src/gen/core/auth.gen.ts +48 -0
  97. package/src/gen/core/bodySerializer.gen.ts +82 -0
  98. package/src/gen/core/params.gen.ts +178 -0
  99. package/src/gen/core/pathSerializer.gen.ts +171 -0
  100. package/src/gen/core/queryKeySerializer.gen.ts +117 -0
  101. package/src/gen/core/serverSentEvents.gen.ts +242 -0
  102. package/src/gen/core/types.gen.ts +110 -0
  103. package/src/gen/core/utils.gen.ts +140 -0
  104. package/src/gen/index.ts +4 -0
  105. package/src/gen/sdk.gen.ts +5008 -0
  106. package/src/gen/types.gen.ts +18418 -0
  107. package/src/index.ts +13 -0
  108. package/src/vocabulary.ts +134 -0
@@ -0,0 +1,440 @@
1
+ "use client";
2
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
3
+ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
4
+ import { ParticipantKind, Room, RpcError, TokenSource, Track, setLogLevel, LogLevel, } from "livekit-client";
5
+ import { RoomAudioRenderer, SessionProvider, VideoTrack, useAgent, useParticipantTracks, useRemoteParticipants, useSession, useSessionContext, useSessionMessages, useTrackToggle, useVoiceAssistant, } from "@livekit/components-react";
6
+ export class TalqingRpcError extends Error {
7
+ constructor(code, message, data) {
8
+ super(message);
9
+ this.name = "TalqingRpcError";
10
+ this.code = code;
11
+ this.data = data;
12
+ }
13
+ }
14
+ export function createTalqingTokenSource(client, agentId, options = {}, onTokenDetails) {
15
+ // Carry the contact across reconnects. POST /v1/calls/token mints a key when
16
+ // none is supplied, so re-running this without pinning it would file every
17
+ // reconnect as a different person.
18
+ let resolvedContactKey = options.contact_key ?? null;
19
+ // `useSession` fetches a token twice off one click — once to warm the
20
+ // connection, once to connect. Unserialised they race: both go out before
21
+ // either resolves, so neither carries a key, the API mints one per request,
22
+ // and a single call is filed against two different contacts. Concurrent
23
+ // callers share one request.
24
+ //
25
+ // This coalesces, it does not cache: the promise is dropped once it settles,
26
+ // so every later connect still mints a fresh token. That matters — a token
27
+ // bakes in {agent version, room}, so a reused one silently runs a stale
28
+ // version after a republish, and reconnects into a dead room.
29
+ let inFlight = null;
30
+ return TokenSource.literal(async () => {
31
+ if (inFlight)
32
+ return inFlight;
33
+ const request = (async () => {
34
+ const details = await client.calls.token({
35
+ tokenRequest: { ...options, agent_id: agentId, contact_key: resolvedContactKey },
36
+ });
37
+ resolvedContactKey = details.contact_key;
38
+ onTokenDetails?.(details);
39
+ return {
40
+ serverUrl: details.server_url,
41
+ participantToken: details.participant_token,
42
+ };
43
+ })();
44
+ inFlight = request;
45
+ try {
46
+ return await request;
47
+ }
48
+ finally {
49
+ inFlight = null;
50
+ }
51
+ });
52
+ }
53
+ /* Echo cancellation is what stops the agent hearing its own speech through the
54
+ * caller's microphone and interrupting itself. It is a default rather than
55
+ * something each app remembers, because a call without it is broken in a way
56
+ * that sounds like a bad model. Pass `roomOptions.audioCaptureDefaults` to
57
+ * override. */
58
+ export const TALQING_AUDIO_CAPTURE_DEFAULTS = {
59
+ echoCancellation: true,
60
+ noiseSuppression: true,
61
+ autoGainControl: true,
62
+ };
63
+ export function useTalqingSession({ client, agentId, roomOptions, callOptions, onTokenDetails, }) {
64
+ const tokenSource = useMemo(() => createTalqingTokenSource(client, agentId, callOptions, onTokenDetails), [client, agentId, callOptions, onTokenDetails]);
65
+ const room = useMemo(() => new Room({ audioCaptureDefaults: TALQING_AUDIO_CAPTURE_DEFAULTS, ...roomOptions }), [roomOptions]);
66
+ return useSession(tokenSource, { room });
67
+ }
68
+ export function TalqingSessionProvider({ session, children, audio = true, }) {
69
+ return (_jsxs(SessionProvider, { session: session, children: [children, audio ? _jsx(RoomAudioRenderer, {}) : null] }));
70
+ }
71
+ export function useTalqingConnection() {
72
+ const ctx = useSessionContext();
73
+ return {
74
+ isConnected: ctx.isConnected,
75
+ connectionState: ctx.connectionState,
76
+ room: ctx.room,
77
+ start: ctx.start,
78
+ end: ctx.end,
79
+ };
80
+ }
81
+ export async function setTalqingUserdata(room, patch, responseTimeout = 3) {
82
+ const agent = [...room.remoteParticipants.values()].find((participant) => participant.kind === ParticipantKind.AGENT);
83
+ if (!agent)
84
+ return { ok: false, error: "agent participant is not connected" };
85
+ const response = await room.localParticipant.performRpc({
86
+ destinationIdentity: agent.identity,
87
+ method: "talqing.client.userdata_set",
88
+ payload: JSON.stringify(patch),
89
+ responseTimeout,
90
+ });
91
+ return JSON.parse(response || "{}");
92
+ }
93
+ export async function getTalqingUserdata(room, keys, responseTimeout = 3) {
94
+ const agent = [...room.remoteParticipants.values()].find((participant) => participant.kind === ParticipantKind.AGENT);
95
+ if (!agent)
96
+ throw new Error("agent participant is not connected");
97
+ const response = await room.localParticipant.performRpc({
98
+ destinationIdentity: agent.identity,
99
+ method: "talqing.client.userdata_get",
100
+ payload: JSON.stringify(keys ? { keys } : {}),
101
+ responseTimeout,
102
+ });
103
+ const parsed = JSON.parse(response || "{}");
104
+ if (parsed.ok === false) {
105
+ throw new Error(String(parsed.error || "userdata RPC failed"));
106
+ }
107
+ return parsed;
108
+ }
109
+ export function useTalqingUserdata() {
110
+ const { room } = useTalqingConnection();
111
+ return useMemo(() => ({
112
+ get: (keys, responseTimeout) => {
113
+ if (!room)
114
+ throw new Error("room is not connected");
115
+ return getTalqingUserdata(room, keys, responseTimeout);
116
+ },
117
+ set: (patch, responseTimeout) => {
118
+ if (!room)
119
+ throw new Error("room is not connected");
120
+ return setTalqingUserdata(room, patch, responseTimeout);
121
+ },
122
+ }), [room]);
123
+ }
124
+ /* ── images ───────────────────────────────────────────────────────────────
125
+ *
126
+ * A caller attaches a photo on a web voice or video call and the agent sees
127
+ * it. The bytes go over a LiveKit byte stream on the `talqing.images` topic,
128
+ * addressed to the agent; the agent answers on an RPC back, and the id
129
+ * `sendFile` returns is the id that ack carries, so there is nothing to
130
+ * correlate by hand.
131
+ *
132
+ * The agent deliberately does NOT speak when a photo lands — the caller is
133
+ * mid-conversation and about to say what it is for. The image is in the
134
+ * model's view for their next turn.
135
+ */
136
+ export const TALQING_IMAGE_TOPIC = "talqing.images";
137
+ /** Decoded size the server refuses above. The downscale below keeps a phone
138
+ * photo far under it; this is the belt for a file that is not a photo. */
139
+ export const TALQING_IMAGE_MAX_BYTES = 10 * 1024 * 1024;
140
+ /** Longest side the server stores. Downscaling to it before sending is a
141
+ * courtesy to the data channel, which is ordered and reliable and will
142
+ * happily spend a minute pushing 10 MB past a call's audio. */
143
+ export const TALQING_IMAGE_MAX_EDGE_PX = 1568;
144
+ const TALQING_IMAGE_TYPES = ["image/jpeg", "image/png", "image/webp"];
145
+ /** How long to wait for the agent's ack before saying we do not know. Without
146
+ * it a thumbnail sits on "sending" for the rest of the call when the worker
147
+ * dies mid-upload. */
148
+ const TALQING_IMAGE_ACK_TIMEOUT_MS = 30000;
149
+ /** Refuse what the browser can see is wrong, instantly and with no round trip.
150
+ * Returns the sentence to show, or null when the file is fine. The server
151
+ * re-validates everything regardless — this exists so the common mistakes cost
152
+ * nothing to catch. */
153
+ export function talqingImageRejection(file) {
154
+ if (!TALQING_IMAGE_TYPES.includes(file.type)) {
155
+ return "that file is not a JPEG, PNG or WebP";
156
+ }
157
+ if (file.size > TALQING_IMAGE_MAX_BYTES)
158
+ return "images are 10 MB or smaller";
159
+ return null;
160
+ }
161
+ /** Downscale to the longest edge the server keeps, re-encoding as JPEG or PNG.
162
+ *
163
+ * Also what normalizes whatever the OS handed the file input — this is how a
164
+ * Safari HEIC becomes a JPEG. Throws if the image cannot be decoded, which is
165
+ * the third dropzone check. */
166
+ export async function talqingDownscaleImage(file) {
167
+ const bitmap = await createImageBitmap(file);
168
+ try {
169
+ const longest = Math.max(bitmap.width, bitmap.height);
170
+ const scale = longest > TALQING_IMAGE_MAX_EDGE_PX ? TALQING_IMAGE_MAX_EDGE_PX / longest : 1;
171
+ const canvas = document.createElement("canvas");
172
+ canvas.width = Math.max(1, Math.round(bitmap.width * scale));
173
+ canvas.height = Math.max(1, Math.round(bitmap.height * scale));
174
+ const context = canvas.getContext("2d");
175
+ if (!context)
176
+ throw new Error("this browser cannot resize images");
177
+ context.drawImage(bitmap, 0, 0, canvas.width, canvas.height);
178
+ // PNG keeps transparency; everything else becomes a JPEG, including the
179
+ // HEIC the OS decoded for us.
180
+ const type = file.type === "image/png" ? "image/png" : "image/jpeg";
181
+ const blob = await new Promise((resolve) => canvas.toBlob(resolve, type, 0.85));
182
+ if (!blob)
183
+ throw new Error("that image could not be read");
184
+ return blob;
185
+ }
186
+ finally {
187
+ bitmap.close();
188
+ }
189
+ }
190
+ /** Validate and downscale a file into the `data:` URL a text message carries.
191
+ *
192
+ * `createTextMessage` takes `images: [{data_url, filename}]`; this produces the
193
+ * `data_url`. It doubles as the thumbnail's `src`, so there is no object URL to
194
+ * create and revoke. Throws the sentence to show if the file is refused. */
195
+ export async function talqingImageDataUrl(file) {
196
+ const rejection = talqingImageRejection(file);
197
+ if (rejection)
198
+ throw new Error(rejection);
199
+ const blob = await talqingDownscaleImage(file);
200
+ return await new Promise((resolve, reject) => {
201
+ const reader = new FileReader();
202
+ reader.onerror = () => reject(new Error("that image could not be read"));
203
+ reader.onload = () => resolve(String(reader.result));
204
+ reader.readAsDataURL(blob);
205
+ });
206
+ }
207
+ /** Send images to the agent on this call, and follow what became of each.
208
+ *
209
+ * `send` resolves once the bytes are on their way; the outcome arrives on the
210
+ * returned list, which is what a thumbnail should render.
211
+ *
212
+ * Takes the `Room` rather than reading it from the session context: a byte
213
+ * stream and an RPC handler are room-level things, and passing the room keeps
214
+ * this usable from a surface that manages its own connection —
215
+ * `useTalqingConnection().room` inside a provider, or the Room you built. */
216
+ export function useTalqingImages(room) {
217
+ const [sent, setSent] = useState([]);
218
+ const timers = useRef(new Map());
219
+ const settle = useCallback((streamId, patch) => {
220
+ const timer = timers.current.get(streamId);
221
+ if (timer) {
222
+ clearTimeout(timer);
223
+ timers.current.delete(streamId);
224
+ }
225
+ setSent((images) => images.map((image) => (image.streamId === streamId ? { ...image, ...patch } : image)));
226
+ }, []);
227
+ useEffect(() => {
228
+ if (!room)
229
+ return;
230
+ room.registerRpcMethod("talqing.image_result", async (data) => {
231
+ const { stream_id, ok, error } = JSON.parse(data.payload || "{}");
232
+ settle(stream_id, {
233
+ status: ok ? "sent" : "failed",
234
+ error: ok ? undefined : error || "that image was not accepted",
235
+ });
236
+ return "{}";
237
+ });
238
+ return () => room.unregisterRpcMethod("talqing.image_result");
239
+ }, [room, settle]);
240
+ const pending = timers.current;
241
+ useEffect(() => () => {
242
+ pending.forEach(clearTimeout);
243
+ pending.clear();
244
+ }, [pending]);
245
+ const send = useCallback(async (file) => {
246
+ if (!room)
247
+ throw new Error("the call is not connected");
248
+ const agent = [...room.remoteParticipants.values()].find((participant) => participant.kind === ParticipantKind.AGENT);
249
+ if (!agent)
250
+ throw new Error("agent participant is not connected");
251
+ const rejection = talqingImageRejection(file);
252
+ if (rejection)
253
+ throw new Error(rejection);
254
+ const blob = await talqingDownscaleImage(file);
255
+ // Addressed to the agent, never broadcast: on video the avatar worker is
256
+ // a participant too, and a broadcast sends the bytes twice.
257
+ const { id } = await room.localParticipant.sendFile(new File([blob], file.name, { type: blob.type }), {
258
+ topic: TALQING_IMAGE_TOPIC,
259
+ mimeType: blob.type,
260
+ destinationIdentities: [agent.identity],
261
+ });
262
+ const image = {
263
+ streamId: id,
264
+ name: file.name,
265
+ previewUrl: URL.createObjectURL(blob),
266
+ status: "sending",
267
+ };
268
+ setSent((images) => [...images, image]);
269
+ timers.current.set(id, setTimeout(() => settle(id, {
270
+ status: "unknown",
271
+ // Four states, not two: the one people forget is the agent going
272
+ // away mid-upload, where no ack is ever coming.
273
+ error: "we did not hear back — the agent may not have received it",
274
+ }), TALQING_IMAGE_ACK_TIMEOUT_MS));
275
+ return image;
276
+ }, [room, settle]);
277
+ const clear = useCallback(() => {
278
+ setSent((images) => {
279
+ images.forEach((image) => URL.revokeObjectURL(image.previewUrl));
280
+ return [];
281
+ });
282
+ }, []);
283
+ return { send, sent, clear };
284
+ }
285
+ export function useTalqingAgent() {
286
+ const agent = useAgent();
287
+ return {
288
+ state: agent.state,
289
+ isFinished: agent.isFinished,
290
+ };
291
+ }
292
+ export function useTalqingMessages() {
293
+ const messages = useSessionMessages();
294
+ return {
295
+ messages: messages.messages,
296
+ send: messages.send,
297
+ isSending: messages.isSending,
298
+ };
299
+ }
300
+ /* Screen share, with the four settings that decide whether the agent can read
301
+ * what is on it.
302
+ *
303
+ * Only the first is obvious, and every one of them is upstream of anything we
304
+ * could do on our side:
305
+ *
306
+ * - `contentHint: "text"` tells the encoder to preserve spatial detail. The
307
+ * default for a screen share on an SVC codec is `motion`, which trades
308
+ * exactly that away — the wrong trade for reading code, and no JPEG quality
309
+ * setting downstream recovers it.
310
+ * - `videoCodec: "h264"` is what keeps that hint. `livekit-client` forces
311
+ * `contentHint = "motion"` on screen shares published as vp9 or av1,
312
+ * together with `scalabilityMode: "L1T3"`. **Publishing on an SVC codec will
313
+ * cost you legibility**, and it is the first thing to check if the agent
314
+ * starts misreading identifiers.
315
+ * - `screenShareEncoding.maxFramerate: 1` is the frame-rate cap that actually
316
+ * binds. `resolution.frameRate` reaches `getDisplayMedia` as a bare number,
317
+ * which WebRTC reads as `ideal` — a wish, not a limit. The default publish
318
+ * ceiling is 15 fps, and every delivered frame is copied into the agent's
319
+ * process before it can be dropped, so this is the single biggest lever on
320
+ * what a call costs the worker. One frame a second is ample: the agent is
321
+ * handed the newest frame at the end of each turn, and turns are seconds
322
+ * apart.
323
+ * - `resolution` is set explicitly rather than inherited. The default is 1080p
324
+ * by `ideal`, which is a strong hint and not a guarantee.
325
+ *
326
+ * The picker cannot be opened for the person — `getDisplayMedia` requires a
327
+ * transient user activation — so `start()` must be called from a click. The
328
+ * agent asking out loud is what prompts it; there is no version of this where
329
+ * the agent turns sharing on.
330
+ */
331
+ export const TALQING_SCREEN_SHARE_CAPTURE = {
332
+ resolution: { width: 1920, height: 1080, frameRate: 1 },
333
+ contentHint: "text",
334
+ };
335
+ export const TALQING_SCREEN_SHARE_PUBLISH = {
336
+ videoCodec: "h264",
337
+ screenShareEncoding: { maxBitrate: 1000000, maxFramerate: 1 },
338
+ };
339
+ export function useTalqingScreenShare() {
340
+ const { toggle, enabled, pending } = useTrackToggle({
341
+ source: Track.Source.ScreenShare,
342
+ captureOptions: TALQING_SCREEN_SHARE_CAPTURE,
343
+ publishOptions: TALQING_SCREEN_SHARE_PUBLISH,
344
+ });
345
+ return useMemo(() => ({
346
+ /** Whether a screen is being shared right now. */
347
+ enabled,
348
+ /** True while the browser picker is open or the track is publishing. */
349
+ pending,
350
+ /** Opens the browser's share picker. Must be called from a user gesture. */
351
+ start: () => toggle(true),
352
+ /** Stops sharing. The agent is told it can no longer see on the next turn. */
353
+ stop: () => toggle(false),
354
+ }), [enabled, pending, toggle]);
355
+ }
356
+ export function useTalqingAvatarTrack() {
357
+ const { agent } = useVoiceAssistant();
358
+ const remoteParticipants = useRemoteParticipants();
359
+ const worker = remoteParticipants.find((participant) => participant.kind === ParticipantKind.AGENT &&
360
+ participant.attributes["lk.publish_on_behalf"] === agent?.identity);
361
+ const agentTracks = useParticipantTracks([Track.Source.Camera, Track.Source.ScreenShare], agent?.identity);
362
+ const workerTracks = useParticipantTracks([Track.Source.Camera, Track.Source.ScreenShare], worker?.identity);
363
+ return (workerTracks.find((track) => track.source === Track.Source.Camera) ??
364
+ workerTracks.find((track) => track.source === Track.Source.ScreenShare) ??
365
+ agentTracks.find((track) => track.source === Track.Source.Camera) ??
366
+ agentTracks.find((track) => track.source === Track.Source.ScreenShare));
367
+ }
368
+ export function TalqingVideoTrack({ track, className, }) {
369
+ return (_jsx(VideoTrack, { trackRef: track, width: track.publication.dimensions?.width ?? 0, height: track.publication.dimensions?.height ?? 0, className: className }));
370
+ }
371
+ export function useTalqingRpcHandlers(handlers, enabled = true) {
372
+ const { room, isConnected } = useTalqingConnection();
373
+ useEffect(() => {
374
+ if (!enabled || !room || !isConnected)
375
+ return;
376
+ room.registerRpcMethod("talqing.frontend_rpc", async (data) => {
377
+ try {
378
+ const envelope = JSON.parse(data.payload || "{}");
379
+ const isWildcard = handlers[envelope.method] === undefined;
380
+ const handler = handlers[envelope.method] ?? handlers["*"];
381
+ if (!handler) {
382
+ throw new TalqingRpcError(1404, `No frontend RPC handler registered for ${envelope.method}`);
383
+ }
384
+ return await handler({
385
+ payload: isWildcard
386
+ ? JSON.stringify(envelope)
387
+ : envelope.payload === undefined
388
+ ? "{}"
389
+ : JSON.stringify(envelope.payload),
390
+ responseTimeout: data.responseTimeout,
391
+ callerIdentity: data.callerIdentity,
392
+ });
393
+ }
394
+ catch (error) {
395
+ if (error instanceof TalqingRpcError) {
396
+ throw new RpcError(error.code, error.message, error.data);
397
+ }
398
+ throw new RpcError(1500, error instanceof Error ? error.message : "RPC handler failed");
399
+ }
400
+ });
401
+ return () => {
402
+ room.unregisterRpcMethod("talqing.frontend_rpc");
403
+ };
404
+ }, [enabled, handlers, isConnected, room]);
405
+ }
406
+ export function useTalqingFrontendRpcs(enabled = true) {
407
+ const [actions, setActions] = useState({});
408
+ const handlers = useMemo(() => ({
409
+ "*": async (data) => {
410
+ const payload = JSON.parse(data.payload || "{}");
411
+ const method = String(payload.method || "");
412
+ if (method) {
413
+ setActions((current) => ({
414
+ ...current,
415
+ [method]: {
416
+ payload: payload.payload,
417
+ at: Date.now(),
418
+ },
419
+ }));
420
+ }
421
+ return "ok";
422
+ },
423
+ }), []);
424
+ useTalqingRpcHandlers(handlers, enabled);
425
+ return {
426
+ actions,
427
+ clear: () => setActions({}),
428
+ };
429
+ }
430
+ export function setTalqingBrowserLogLevel(level) {
431
+ const levels = {
432
+ debug: LogLevel.debug,
433
+ info: LogLevel.info,
434
+ warn: LogLevel.warn,
435
+ error: LogLevel.error,
436
+ silent: LogLevel.silent,
437
+ };
438
+ setLogLevel(levels[level]);
439
+ }
440
+ //# sourceMappingURL=browser.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"browser.js","sourceRoot":"","sources":["../src/browser.tsx"],"names":[],"mappings":"AAAA,YAAY,CAAC;;AAEb,OAAc,EAAE,WAAW,EAAE,SAAS,EAAE,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAC;AACjF,OAAO,EACL,eAAe,EACf,IAAI,EACJ,QAAQ,EACR,WAAW,EACX,KAAK,EACL,WAAW,EACX,QAAQ,GAIT,MAAM,gBAAgB,CAAC;AACxB,OAAO,EACL,iBAAiB,EACjB,eAAe,EACf,UAAU,EACV,QAAQ,EACR,oBAAoB,EACpB,qBAAqB,EACrB,UAAU,EACV,iBAAiB,EACjB,kBAAkB,EAClB,cAAc,EACd,iBAAiB,GAIlB,MAAM,2BAA2B,CAAC;AAoCnC,MAAM,OAAO,eAAgB,SAAQ,KAAK;IAIxC,YAAY,IAAY,EAAE,OAAe,EAAE,IAAa;QACtD,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,iBAAiB,CAAC;QAC9B,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,IAAI,G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AAC;QACd,CAAC;KACF,CAAC,EACF,EAAE,CACH,CAAC;IAEF,qBAAqB,CAAC,QAAQ,EAAE,OAAO,CAAC,CAAC;IAEzC,OAAO;QACL,OAAO;QACP,KAAK,EAAE,GAAG,EAAE,CAAC,UAAU,CAAC,EAAE,CAAC;KAC5B,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,yBAAyB,CACvC,KAAqD;IAErD,MAAM,MAAM,GAAG;QACb,KAAK,EAAE,QAAQ,CAAC,KAAK;QACrB,IAAI,EAAE,QAAQ,CAAC,IAAI;QACnB,IAAI,EAAE,QAAQ,CAAC,IAAI;QACnB,KAAK,EAAE,QAAQ,CAAC,KAAK;QACrB,MAAM,EAAE,QAAQ,CAAC,MAAM;KACxB,CAAC;IACF,WAAW,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC;AAC7B,CAAC"}
@@ -0,0 +1,101 @@
1
+ /** The hand-written half of the SDK: everything the OpenAPI document cannot say.
2
+ *
3
+ * The API surface itself is generated into `./gen` from `openapi/openapi.json`
4
+ * and is never edited here. What is left is the client object that carries
5
+ * credentials, the error type, the two browser-redirect URLs that are
6
+ * deliberately absent from the document, and a pagination helper.
7
+ */
8
+ import { TalqingApi } from "./gen/index.js";
9
+ import type { Client } from "./gen/client/index.js";
10
+ import type { ErrorResponse } from "./gen/types.gen.js";
11
+ export type JsonPrimitive = string | number | boolean | null;
12
+ export type JsonValue = JsonPrimitive | JsonValue[] | {
13
+ [key: string]: JsonValue;
14
+ };
15
+ export type JsonObject = {
16
+ [key: string]: unknown;
17
+ };
18
+ type Awaitable<T> = T | Promise<T>;
19
+ type TokenProvider = string | (() => Awaitable<string | null | undefined>);
20
+ /** A page of results. The document spells each instantiation out by hand
21
+ * (`PageAgentResponse`) because OpenAPI has no generics; TypeScript is
22
+ * structural, so those satisfy this and generic helpers still work. */
23
+ export interface Page<T> {
24
+ items: T[];
25
+ has_more: boolean;
26
+ limit: number;
27
+ offset: number;
28
+ }
29
+ /**
30
+ * Every generated method, with the `| undefined` that `throwOnError` makes
31
+ * impossible removed.
32
+ *
33
+ * The generator emits `<ThrowOnError extends boolean = false>` on every method,
34
+ * so a client configured to throw still returns `T | undefined` at the type
35
+ * level and every call site would need a `!`. There is no setting for it. This
36
+ * re-types the whole tree once instead.
37
+ *
38
+ * `Exclude<R, undefined>` rather than `NonNullable<R>`: the latter turns the
39
+ * `void` of a 204 into `{}`. `...args: infer A` rather than named parameters:
40
+ * it keeps each method's optional-argument arity, so `agents.list()` with no
41
+ * argument still compiles.
42
+ */
43
+ type Throwing<T> = {
44
+ [K in keyof T]: T[K] extends (...args: infer A) => Promise<infer R> ? (...args: A) => Promise<Exclude<R, undefined>> : Throwing<T[K]>;
45
+ };
46
+ /** Every error this API returns, in the one shape it returns them in. */
47
+ export declare class TalqingApiError extends Error {
48
+ readonly name = "TalqingApiError";
49
+ readonly status: number;
50
+ /** Per-field problems, when the failure had more than one. Always present. */
51
+ readonly errors: string[];
52
+ readonly response: Response;
53
+ constructor(body: ErrorResponse, response: Response);
54
+ }
55
+ export interface TalqingClientOptions {
56
+ /** Base URL of the Talqing API, e.g. `https://api.example.com`. Required,
57
+ * with no default: a bundler inlines this at build time, so a localhost
58
+ * fallback would silently ship a production bundle calling nothing. */
59
+ baseUrl: string;
60
+ /** A personal access token, or a function returning one. Server-side use. */
61
+ token?: TokenProvider;
62
+ /** `"include"` for the dashboard's cookie session. */
63
+ credentials?: RequestCredentials;
64
+ headers?: Record<string, string>;
65
+ fetch?: typeof fetch;
66
+ /**
67
+ * Called when the API answers 401. The credentials are gone, so every other
68
+ * call will fail identically — this is a session-level fact, not a per-call
69
+ * one, and handling it here keeps every caller from re-deriving it. The error
70
+ * is still thrown afterwards.
71
+ */
72
+ onUnauthorized?: (error: TalqingApiError) => void;
73
+ }
74
+ interface TalqingClientExtras {
75
+ readonly baseUrl: string;
76
+ /** The underlying transport, for interceptors and one-off requests. */
77
+ readonly http: Client;
78
+ /** Where to send the browser to start Google sign-in. */
79
+ googleLoginUrl(): string;
80
+ /** Where to send the browser to authorize an integration. */
81
+ oauthStartUrl(provider: string, integrationId?: string): string;
82
+ }
83
+ export interface TalqingClient extends Throwing<TalqingApi>, TalqingClientExtras {
84
+ }
85
+ export declare const TalqingClient: new (options: TalqingClientOptions) => TalqingClient;
86
+ /**
87
+ * Walk every page of a list endpoint.
88
+ *
89
+ * for await (const agent of paginate((q) => talqing.agents.list(q))) { … }
90
+ *
91
+ * Replaces the one-off `listAllAgents` the previous client carried: the page
92
+ * shape is the same on all 28 list endpoints, so the helper is too.
93
+ */
94
+ export declare function paginate<T>(page: (query: {
95
+ limit: number;
96
+ offset: number;
97
+ }) => Promise<Page<T>>, { limit }?: {
98
+ limit?: number;
99
+ }): AsyncGenerator<T>;
100
+ export {};
101
+ //# sourceMappingURL=client.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAE5C,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,uBAAuB,CAAC;AACpD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AAYxD,MAAM,MAAM,aAAa,GAAG,MAAM,GAAG,MAAM,GAAG,OAAO,GAAG,IAAI,CAAC;AAC7D,MAAM,MAAM,SAAS,GAAG,aAAa,GAAG,SAAS,EAAE,GAAG;IAAE,CAAC,GAAG,EAAE,MAAM,GAAG,SAAS,CAAA;CAAE,CAAC;AACnF,MAAM,MAAM,UAAU,GAAG;IAAE,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAA;CAAE,CAAC;AAEpD,KAAK,SAAS,CAAC,CAAC,IAAI,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;AACnC,KAAK,aAAa,GAAG,MAAM,GAAG,CAAC,MAAM,SAAS,CAAC,MAAM,GAAG,IAAI,GAAG,SA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D;AAED,UAAU,mBAAmB;IAC3B,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,uEAAuE;IACvE,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,yDAAyD;IACzD,cAAc,IAAI,MAAM,CAAC;IACzB,6DAA6D;IAC7D,aAAa,CAAC,QAAQ,EAAE,MAAM,EAAE,aAAa,CAAC,EAAE,MAAM,GAAG,MAAM,CAAC;CACjE;AAED,MAAM,WAAW,aAAc,SAAQ,QAAQ,CAAC,UAAU,CAAC,EAAE,mBAAmB;CAAG;AAwDnF,eAAO,MAAM,aAAa,EAAmC,KAC3D,OAAO,EAAE,oBAAoB,KAC1B,aAAa,CAAC;AAOnB;;;;;;;GAOG;AACH,wBAAuB,QAAQ,CAAC,CAAC,EAC/B,IAAI,EAAE,CAAC,KAAK,EAAE;IAAE,KAAK,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,EACpE,EAAE,KAAW,EAAE,GAAE;IAAE,KAAK,CAAC,EAAE,MAAM,CAAA;CAAO,GACvC,cAAc,CAAC,CAAC,CAAC,CAMnB"}
package/dist/client.js ADDED
@@ -0,0 +1,88 @@
1
+ /** The hand-written half of the SDK: everything the OpenAPI document cannot say.
2
+ *
3
+ * The API surface itself is generated into `./gen` from `openapi/openapi.json`
4
+ * and is never edited here. What is left is the client object that carries
5
+ * credentials, the error type, the two browser-redirect URLs that are
6
+ * deliberately absent from the document, and a pagination helper.
7
+ */
8
+ import { TalqingApi } from "./gen/index.js";
9
+ import { createClient, createConfig } from "./gen/client/index.js";
10
+ /** Every error this API returns, in the one shape it returns them in. */
11
+ export class TalqingApiError extends Error {
12
+ constructor(body, response) {
13
+ super(body.detail.message);
14
+ this.name = "TalqingApiError";
15
+ this.status = response.status;
16
+ this.errors = body.detail.errors;
17
+ this.response = response;
18
+ }
19
+ }
20
+ class TalqingClientImpl extends TalqingApi {
21
+ constructor(options) {
22
+ // Types do not reach a JavaScript caller, or a value that is `string` but empty.
23
+ if (!options?.baseUrl?.trim()) {
24
+ throw new Error("TalqingClient requires a baseUrl (e.g. https://api.in.talqing.com)");
25
+ }
26
+ const baseUrl = options.baseUrl.replace(/\/+$/, "");
27
+ const http = createClient(createConfig({
28
+ baseUrl,
29
+ throwOnError: true,
30
+ responseStyle: "data",
31
+ credentials: options.credentials,
32
+ headers: options.headers,
33
+ ...(options.fetch ? { fetch: options.fetch } : {}),
34
+ ...(options.token ? { auth: () => resolveToken(options.token) } : {}),
35
+ }));
36
+ // The transport throws the parsed error body — a plain object with no
37
+ // status and no stack. Replacing it here is what makes `catch (e)` see a
38
+ // real Error everywhere, including inside the generated methods.
39
+ http.interceptors.error.use((error, response) => {
40
+ // No response means the request never completed — a DNS failure, an
41
+ // abort, an offline tab. There is no status to carry, so the transport's
42
+ // own error is already the truthful one.
43
+ if (!response)
44
+ return error;
45
+ const failure = new TalqingApiError(error, response);
46
+ if (failure.status === 401)
47
+ options.onUnauthorized?.(failure);
48
+ return failure;
49
+ });
50
+ super({ client: http });
51
+ this.baseUrl = baseUrl;
52
+ this.http = http;
53
+ }
54
+ googleLoginUrl() {
55
+ return `${this.baseUrl}/v1/auth/google/start`;
56
+ }
57
+ oauthStartUrl(provider, integrationId) {
58
+ const url = new URL(`${this.baseUrl}/v1/integrations/oauth/${encodeURIComponent(provider)}/start`);
59
+ if (integrationId)
60
+ url.searchParams.set("integration_id", integrationId);
61
+ return url.toString();
62
+ }
63
+ }
64
+ /* `Throwing` is a type-level narrowing of the same object — the runtime value
65
+ * is the generated class, unchanged — so the constructor is re-typed rather
66
+ * than the 155 methods being re-declared. */
67
+ export const TalqingClient = TalqingClientImpl;
68
+ async function resolveToken(token) {
69
+ const value = typeof token === "function" ? await token() : token;
70
+ return value ?? undefined;
71
+ }
72
+ /**
73
+ * Walk every page of a list endpoint.
74
+ *
75
+ * for await (const agent of paginate((q) => talqing.agents.list(q))) { … }
76
+ *
77
+ * Replaces the one-off `listAllAgents` the previous client carried: the page
78
+ * shape is the same on all 28 list endpoints, so the helper is too.
79
+ */
80
+ export async function* paginate(page, { limit = 200 } = {}) {
81
+ for (let offset = 0;; offset += limit) {
82
+ const result = await page({ limit, offset });
83
+ yield* result.items;
84
+ if (!result.has_more)
85
+ return;
86
+ }
87
+ }
88
+ //# sourceMappingURL=client.js.map