@d-id/client-sdk 2.0.10-staging.411 → 3.0.0-staging.412

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 (49) hide show
  1. package/README.md +53 -264
  2. package/dist/{index-BgmEitAw.js → index-BLrKDuV_.js} +3002 -2825
  3. package/dist/index.js +23 -31
  4. package/dist/index.umd.cjs +5 -5
  5. package/dist/{livekit-manager-CgErNpNN.js → livekit-manager-Cfb9x2ei.js} +53 -50
  6. package/dist/src/api/agents.d.ts +1 -1
  7. package/dist/src/api/apiClient.d.ts +1 -1
  8. package/dist/src/api/knowledge.d.ts +1 -1
  9. package/dist/src/api/streams/streamApi.d.ts +1 -1
  10. package/dist/src/api/streams/streamsApiV2.d.ts +1 -1
  11. package/dist/src/errors/base-error.d.ts +170 -1
  12. package/dist/src/errors/chat/chat-creation-failed.d.ts +24 -0
  13. package/dist/src/errors/chat/chat-mode-downgraded.d.ts +29 -0
  14. package/dist/src/errors/http-error.d.ts +67 -5
  15. package/dist/src/errors/index.d.ts +1 -0
  16. package/dist/src/errors/network-error.d.ts +62 -8
  17. package/dist/src/errors/request-meta.d.ts +12 -0
  18. package/dist/src/errors/stream-error.d.ts +32 -0
  19. package/dist/src/errors/validation-error.d.ts +62 -1
  20. package/dist/src/errors/ws-error.d.ts +29 -0
  21. package/dist/src/index.d.ts +18 -4
  22. package/dist/src/public-api.test.d.ts +1 -0
  23. package/dist/src/services/agent-manager/index.d.ts +46 -6
  24. package/dist/src/services/chat/intial-messages.test.d.ts +1 -0
  25. package/dist/src/services/streaming-manager/common.d.ts +8 -3
  26. package/dist/src/types/auth.d.ts +78 -6
  27. package/dist/src/types/entities/agents/agent.d.ts +152 -6
  28. package/dist/src/types/entities/agents/chat.d.ts +384 -12
  29. package/dist/src/types/entities/agents/manager.d.ts +795 -215
  30. package/dist/src/types/entities/avatar.d.ts +21 -0
  31. package/dist/src/types/entities/index.d.ts +1 -1
  32. package/dist/src/types/entities/knowledge/document.d.ts +7 -8
  33. package/dist/src/types/entities/knowledge/knowledge.d.ts +20 -0
  34. package/dist/src/types/entities/knowledge/record.d.ts +8 -0
  35. package/dist/src/types/entities/knowledge/retrival.d.ts +4 -0
  36. package/dist/src/types/stream/api/clip.d.ts +8 -9
  37. package/dist/src/types/stream/api/talk.d.ts +8 -9
  38. package/dist/src/types/stream/rtc.d.ts +54 -4
  39. package/dist/src/types/stream/stream.d.ts +553 -34
  40. package/dist/src/types/stream/streams-v2.d.ts +12 -0
  41. package/dist/src/types/stream-script.d.ts +92 -19
  42. package/dist/src/types/voice/stt.d.ts +12 -0
  43. package/dist/src/types/voice/tts.d.ts +149 -64
  44. package/dist/src/utils/analytics.d.ts +2 -2
  45. package/dist/src/utils/content-parser.d.ts +31 -0
  46. package/dist/src/utils/tool-calls.d.ts +21 -2
  47. package/dist/src/version.d.ts +6 -0
  48. package/package.json +7 -3
  49. package/dist/src/types/entities/video.d.ts +0 -6
@@ -1,13 +1,14 @@
1
1
  import { STTTokenResponse } from '../..';
2
2
  import { Auth } from '../../auth';
3
- import { AgentActivityState, ClientToolHandler, CompatibilityMode, ConnectionState, ConnectivityState, PublicDataChannelTopic, SendStreamPayloadResponse, StreamEvents, StreamType, StreamingState } from '../../stream';
3
+ import { AgentActivityState, ClientToolHandler, CompatibilityMode, ConnectionState, ConnectivityState, PublicDataChannelTopic, SendStreamPayloadResponse, StreamCreatedInfo, StreamEvents, StreamType, StreamingState } from '../../stream';
4
4
  import { SupportedStreamScript } from '../../stream-script';
5
- import { ManagerCallbacks as StreamManagerCallbacks } from '../../stream/stream';
5
+ import { StreamingManagerCallbacks as StreamManagerCallbacks } from '../../stream/stream';
6
6
  import { Agent } from './agent';
7
7
  import { ChatMode, ChatResponse, Interrupt, Message, RatingEntity, SubmitFeedbackResponse } from './chat';
8
8
 
9
9
  /**
10
10
  * Types of events provided in Chat Progress Callback
11
+ * @internal Implementation type; not part of the public SDK surface.
11
12
  */
12
13
  export declare enum ChatProgress {
13
14
  /**
@@ -35,282 +36,861 @@ export declare enum ChatProgress {
35
36
  */
36
37
  Complete = "done"
37
38
  }
39
+ /**
40
+ * Callback signature for {@link ChatProgress} events emitted internally during a chat exchange.
41
+ * @internal Implementation type; not part of the public SDK surface.
42
+ */
38
43
  export type ChatProgressCallback = (progress: ChatProgress | StreamEvents, data: any) => void;
39
- export type ConnectionStateChangeCallback = (state: ConnectionState) => void;
40
- export type VideoStateChangeCallback = (state: StreamingState, data: any) => void;
41
- interface ManagerCallbacks {
42
- /**
43
- * Optional callback will be triggered each time the RTC connection changes state
44
- * @param state
45
- * @param reason - a `StreamEndReason` when the server ended the stream, otherwise a diagnostic string
46
- */
47
- onConnectionStateChange?(state: ConnectionState, reason?: string): void;
48
- /**
49
- * Optional callback function that will be triggered each time video events happen
50
- * @param state
51
- */
52
- onVideoStateChange?(state: StreamingState): void;
53
- /**
54
- * Callback function that will be triggered each time the video stream starts or stops to update html element on webpage
55
- * Required callback for SDK
56
- * @param srcObject
44
+ /**
45
+ * Handlers the SDK calls as the connection, the video stream and the chat change state.
46
+ *
47
+ * Pass the object as {@link AgentManagerOptions.callbacks}. Only
48
+ * {@link AgentManagerCallbacks.onSrcObjectReady | onSrcObjectReady} is required — without it there
49
+ * is nothing to render the agent into. Every handler is called from the SDK's own event handling,
50
+ * so keep the work inside short.
51
+ *
52
+ * The handlers fall into four groups: the connection
53
+ * ({@link AgentManagerCallbacks.onConnectionStateChange | onConnectionStateChange},
54
+ * {@link AgentManagerCallbacks.onConnectivityStateChange | onConnectivityStateChange},
55
+ * {@link AgentManagerCallbacks.onError | onError}), the video stream
56
+ * ({@link AgentManagerCallbacks.onSrcObjectReady | onSrcObjectReady},
57
+ * {@link AgentManagerCallbacks.onStreamCreated | onStreamCreated},
58
+ * {@link AgentManagerCallbacks.onVideoStateChange | onVideoStateChange},
59
+ * {@link AgentManagerCallbacks.onAgentActivityStateChange | onAgentActivityStateChange},
60
+ * {@link AgentManagerCallbacks.onInterruptibleChange | onInterruptibleChange}), the chat
61
+ * ({@link AgentManagerCallbacks.onNewChat | onNewChat}, {@link AgentManagerCallbacks.onNewMessage | onNewMessage},
62
+ * {@link AgentManagerCallbacks.onModeChange | onModeChange}) and client tools
63
+ * ({@link AgentManagerCallbacks.onToolEvent | onToolEvent},
64
+ * {@link AgentManagerCallbacks.onRunningToolCallsChange | onRunningToolCallsChange}). A handler that
65
+ * lives outside the object can be typed with an indexed access such as
66
+ * `AgentManagerCallbacks['onNewMessage']`.
67
+ *
68
+ * @category Callbacks & Events
69
+ */
70
+ export interface AgentManagerCallbacks {
71
+ /**
72
+ * Called every time the connection to the agent's stream changes state.
73
+ *
74
+ * Triggered by {@link AgentManager.connect | connect()},
75
+ * {@link AgentManager.reconnect | reconnect()} and
76
+ * {@link AgentManager.disconnect | disconnect()}.
77
+ * {@link ConnectionState.Connected | 'connected'} is the point at which
78
+ * {@link AgentManager.chat | chat()} and {@link AgentManager.speak | speak()} can be called.
79
+ *
80
+ * @param state - The state just reached: one of `new`, `connecting`, `connected`, `completed`,
81
+ * `disconnecting`, `disconnected`, `closed` or `fail`. See {@link ConnectionState}.
82
+ * @param reason - Why that state was reached. On `disconnected` it is a
83
+ * {@link StreamEndReason} value when the server ended the stream on purpose, which is how you
84
+ * tell a deliberate end from a dropped connection. Talks (V2) and Clips (V3) agents report
85
+ * only `ok`, `unknown_error`, `network_issue` and `inactivity`; `message_limit`, `time_limit`
86
+ * and `ended_by_agent` come from Expressive (V4) agents. A close reason the SDK does not
87
+ * recognise is forwarded as-is, so compare `reason` against the enum rather than parsing it;
88
+ * any other value is an opaque transport diagnostic.
89
+ * {@link AgentManager.reconnect | reconnect()} still works after a deliberate end; it starts a
90
+ * new stream rather than resuming the old one.
57
91
  * @example
58
- * const videoRef = useRef<HTMLVideoElement>(null);
59
- * onSrcObjectReady(value) { videoRef.current.srcObject = value }
60
- */
61
- onSrcObjectReady(srcObject: MediaStream): void;
62
- /**
63
- * Optional callback function that will be triggered each time new message is received
64
- * @param messages - array of messages
65
- */
66
- onNewMessage?(messages: Message[], type: 'answer' | 'partial' | 'user'): void;
67
- /**
68
- * Optional callback function that will be triggered each time new chat is created
69
- * @param chatId - id of the new chat
70
- */
71
- onNewChat?(chatId: string): void;
72
- /**
73
- * Optional callback function that will be triggered each time the chat mode changes
74
- * @param mode - ChatMode
75
- */
76
- onModeChange?(mode: ChatMode): void;
77
- /**
78
- * Optional callback function that will be triggered each time the user internet connectivity state change by realtime estimated bitrate
79
- * @param state - ConnectivityState
80
- */
81
- onConnectivityStateChange?(state: ConnectivityState): void;
82
- /**
83
- * Optional callback function that will be triggered on fetch request errors
84
- */
85
- onError?: (error: Error, errorData?: object) => void;
86
- /**
87
- * Optional callback function that will be triggered each time the agent activity state changes
88
- * @param state - AgentActivityState
89
- */
90
- onAgentActivityStateChange?(state: AgentActivityState): void;
91
- /**
92
- * Optional callback function that will be triggered each time a new stream is created
93
- * @param stream - object containing stream_id, session_id and agent_id
94
- */
95
- onStreamCreated?: StreamManagerCallbacks['onStreamCreated'];
96
- /**
97
- * Optional callback function that will be triggered when tool-call events occur during the call
98
- * (tool-call/started, tool-call/done, tool-call/error).
99
- * The payload shape is discriminated by the event argument.
92
+ * ```ts
93
+ * onConnectionStateChange(state, reason) {
94
+ * console.log('onConnectionStateChange(): ', state, reason);
95
+ *
96
+ * if (state === 'connected') {
97
+ * console.log("I'm ready to go!");
98
+ * }
99
+ * }
100
+ * ```
101
+ */
102
+ onConnectionStateChange?: (state: ConnectionState, reason?: string) => void;
103
+ /**
104
+ * Called when the streamed video starts and stops, so the video element can switch source.
105
+ *
106
+ * Triggered by {@link AgentManager.chat | chat()} and {@link AgentManager.speak | speak()}. On
107
+ * `STOP` point the element at the agent's idle video ({@link Agent.idle_video}); on `START` put
108
+ * the stream handed to {@link AgentManagerCallbacks.onSrcObjectReady | onSrcObjectReady} back
109
+ * on it.
110
+ *
111
+ * @param state - {@link StreamingState.Start | START} while the agent is speaking,
112
+ * {@link StreamingState.Stop | STOP} once it has finished.
113
+ * @example
114
+ * ```ts
115
+ * onVideoStateChange(state) {
116
+ * console.log('onVideoStateChange(): ', state);
117
+ *
118
+ * if (state === 'STOP') {
119
+ * videoElement.srcObject = undefined;
120
+ * videoElement.src = agentManager.agent.idle_video ?? '';
121
+ * } else {
122
+ * videoElement.src = '';
123
+ * videoElement.srcObject = srcObject;
124
+ * }
125
+ * }
126
+ * ```
127
+ */
128
+ onVideoStateChange?: (state: StreamingState) => void;
129
+ /**
130
+ * Called with the media stream carrying the agent's video and audio. Required.
131
+ *
132
+ * This is the one callback the SDK cannot work without: assign the value to the `srcObject` of
133
+ * your `<video>` element, and keep a reference to it, because
134
+ * {@link AgentManagerCallbacks.onVideoStateChange | onVideoStateChange} has to put it back
135
+ * after the idle video has been shown. Triggered by
136
+ * {@link AgentManager.connect | connect()}, {@link AgentManager.reconnect | reconnect()} and
137
+ * {@link AgentManager.disconnect | disconnect()}.
138
+ *
139
+ * @param srcObject - The live media stream to render.
140
+ * @example
141
+ * ```ts
142
+ * let srcObject;
143
+ *
144
+ * const callbacks = {
145
+ * onSrcObjectReady(value) {
146
+ * videoElement.srcObject = value;
147
+ * srcObject = value;
148
+ * },
149
+ * };
150
+ * ```
151
+ */
152
+ onSrcObjectReady: (srcObject: MediaStream) => void;
153
+ /**
154
+ * Called with the whole chat transcript every time a message is added or updated.
155
+ *
156
+ * Triggered by {@link AgentManager.chat | chat()}, by {@link AgentManager.speak | speak()} for
157
+ * text scripts, and as the agent's answer streams in. It also fires once while the manager is
158
+ * created, with whatever {@link AgentManagerOptions.initialMessages | initialMessages} were
159
+ * given, and again on every {@link AgentManager.connect | connect()} after the first — both
160
+ * with type `answer`. The array is a fresh copy on each call, oldest message first; every
161
+ * {@link Message} carries an `id`, a `role` of `user` or `assistant` (the agent), its `content`
162
+ * and a `created_at` timestamp.
163
+ *
164
+ * @param messages - The chat so far.
165
+ * @param type - `partial` while the agent's answer is still streaming in, `answer` for the full
166
+ * answer spoken in the streamed video, `user` when the message just added is the user's own
167
+ * (a message passed to {@link AgentManager.chat | chat()}, or a transcribed utterance).
168
+ * @example
169
+ * ```ts
170
+ * onNewMessage(messages, type) {
171
+ * console.log(messages, type);
172
+ *
173
+ * if (type === 'answer') {
174
+ * console.log(messages[messages.length - 1].content);
175
+ * }
176
+ * }
177
+ * ```
178
+ */
179
+ onNewMessage?: (messages: Message[], type: 'answer' | 'partial' | 'user') => void;
180
+ /**
181
+ * Called when a chat is created for this session.
182
+ *
183
+ * A chat is created while {@link AgentManager.connect | connect()} runs, and lazily on the
184
+ * first {@link AgentManager.chat | chat()} when none exists yet. Store the id if you want to
185
+ * correlate the conversation with your own records.
186
+ *
187
+ * @param chatId - Id of the chat that was just created.
188
+ */
189
+ onNewChat?: (chatId: string) => void;
190
+ /**
191
+ * Called when the chat mode changes.
192
+ *
193
+ * Fires after {@link AgentManager.changeMode | changeMode()}, and when the server answers with
194
+ * a different mode than the one requested (for example {@link ChatMode.Maintenance}).
195
+ *
196
+ * @param mode - The {@link ChatMode} now in effect.
197
+ */
198
+ onModeChange?: (mode: ChatMode) => void;
199
+ /**
200
+ * Called when the quality of the user's internet connection changes.
201
+ *
202
+ * The state is derived from jitter-buffer delay and freeze count on the video stream for
203
+ * Talks (V2) and Clips (V3) agents, and from LiveKit's reported connection quality for
204
+ * Expressive (V4) agents, so it reflects what the session is actually getting rather than the
205
+ * browser's online flag.
206
+ *
207
+ * @param state - {@link ConnectivityState.Strong | STRONG},
208
+ * {@link ConnectivityState.Weak | WEAK} or {@link ConnectivityState.Unknown | UNKNOWN}.
209
+ * @example
210
+ * ```ts
211
+ * onConnectivityStateChange(state) {
212
+ * console.log('onConnectivityStateChange(): ', state);
213
+ * }
214
+ * ```
215
+ */
216
+ onConnectivityStateChange?: (state: ConnectivityState) => void;
217
+ /**
218
+ * Called when the SDK fails, so the application can surface the problem.
219
+ *
220
+ * Receives failures from the Agents API requests, the stream and the web socket — an
221
+ * {@link HttpError} when a request comes back non-2xx, a {@link NetworkError} when it never
222
+ * reaches the server, a {@link WsError} when the web socket itself fails, and also
223
+ * {@link ChatModeDowngraded} and {@link StreamError}. Two errors do not arrive here:
224
+ * {@link ValidationError} and {@link ChatCreationFailed} are thrown to whoever called the
225
+ * method ({@link AgentManager.chat | chat()}, {@link AgentManager.speak | speak()} and the
226
+ * rating methods), so they surface as a rejected promise rather than through this callback.
227
+ *
228
+ * @param error - The error that occurred.
229
+ * @param errorData - Extra context about the failure, such as the request URL and options.
230
+ * @example
231
+ * ```ts
232
+ * onError(error, errorData) {
233
+ * console.log('Error:', error, 'Error Data', errorData);
234
+ * }
235
+ * ```
236
+ */
237
+ onError?: (error: Error, errorData?: Record<string, unknown>) => void;
238
+ /**
239
+ * Called when the agent moves between idle, loading, talking and running a tool.
240
+ *
241
+ * Use it to drive a typing indicator or to disable input while the agent is busy. The full set
242
+ * of states is reported for Expressive (V4) agents only. Talks (V2) and Clips (V3) agents
243
+ * report just {@link AgentActivityState.Talking | Talking} and
244
+ * {@link AgentActivityState.Idle | Idle}, and only on fluent streams, plus a final
245
+ * {@link AgentActivityState.Idle | Idle} when the connection closes.
246
+ *
247
+ * @param state - The {@link AgentActivityState} the agent has moved to.
248
+ */
249
+ onAgentActivityStateChange?: (state: AgentActivityState) => void;
250
+ /**
251
+ * Called once per session when the stream has been created on the server.
252
+ *
253
+ * Fires before the connection reaches {@link ConnectionState.Connected | 'connected'}. The ids
254
+ * are useful when correlating a session with D-ID support or with your own logs.
255
+ *
256
+ * @param stream - The new stream's `stream_id`, `session_id` and `agent_id`.
257
+ */
258
+ onStreamCreated?: (stream: StreamCreatedInfo) => void;
259
+ /**
260
+ * Called when the agent starts, finishes or fails a tool call.
261
+ *
262
+ * Expressive (V4) agents only. The handler takes two arguments and returns nothing: `event`,
263
+ * one of {@link StreamEvents.ToolCallStarted}, {@link StreamEvents.ToolCallDone} or
264
+ * {@link StreamEvents.ToolCallError}; and `data`, the payload that event narrows to —
265
+ * {@link ToolCallStartedPayload}, {@link ToolCallDonePayload} or
266
+ * {@link ToolCallErrorPayload} respectively. The overloads that do the narrowing are on
267
+ * {@link ToolEventCallback}, with an example handler.
100
268
  */
101
269
  onToolEvent?: StreamManagerCallbacks['onToolEvent'];
102
270
  /**
103
- * Optional callback function that will be triggered when the interruptible state changes
104
- * @param interruptible - Whether the agent can be interrupted by the user
271
+ * Called when the agent becomes interruptible, or stops being interruptible.
272
+ *
273
+ * Expressive (V4) agents only, and about whether interrupting is allowed *right now*: it goes
274
+ * `false` while a `blocking` client tool call is outstanding, because the agent is suspended
275
+ * waiting for it, and back to `true` when the call finishes. That is a different question from
276
+ * {@link AgentManager.getIsInterruptAvailable | getIsInterruptAvailable()}, which says whether
277
+ * the session supports interrupting at all. Use this one to enable or disable an interrupt
278
+ * button. Talks (V2) and Clips (V3) agents never report a change.
105
279
  */
106
280
  onInterruptibleChange?: StreamManagerCallbacks['onInterruptibleChange'];
107
281
  /**
108
- * Optional callback function that will be triggered when the set of running tool calls changes,
109
- * including an empty array on disconnect.
110
- * @param calls - The tool calls currently running
282
+ * Called whenever the set of tool calls running in the session changes.
283
+ *
284
+ * Expressive (V4) agents only. Fires with an empty array on disconnect, so a spinner driven by
285
+ * this callback always clears. Each entry is a {@link RunningToolCall}.
111
286
  */
112
287
  onRunningToolCallsChange?: StreamManagerCallbacks['onRunningToolCallsChange'];
113
288
  }
114
- interface StreamOptions {
289
+ /**
290
+ * Transport settings applied when the stream is created.
291
+ *
292
+ * Talks (V2) and Clips (V3) agents only. Expressive (V4) agents manage transport settings
293
+ * automatically and ignore these options. Pass the object as
294
+ * {@link AgentManagerOptions.streamOptions}; every field is optional.
295
+ *
296
+ * @category Streaming Options
297
+ */
298
+ export interface StreamOptions {
115
299
  /**
116
- * Defines the video codec to be used in the stream.
117
- * When set to on: VP8 will be used.
118
- * When set to off: H264 will be used
119
- * When set to auto the codec will be selected according to the browser.
300
+ * Which video codec the stream negotiates.
301
+ *
302
+ * See {@link CompatibilityMode}.
303
+ *
120
304
  * @default auto
121
305
  */
122
306
  compatibilityMode?: CompatibilityMode;
123
307
  /**
124
- * Whether to stream wamrup video on the connection.
125
- * If set to true, will stream a warmup video when connection is established.
126
- * At the end of the warmup video, a message containing "stream/ready" will be sent on the data channel.
308
+ * Whether the stream plays a warmup video while the connection settles.
309
+ *
310
+ * With it on the server plays a short warmup video as soon as the connection is up, and the
311
+ * SDK holds back {@link ConnectionState.Connected | 'connected'} — and so the resolution of
312
+ * {@link AgentManager.connect | connect()} — until that video has played out. Without it,
313
+ * `'connected'` is reported as soon as the data channel opens. The application sees nothing of
314
+ * the warmup video itself beyond the delay; it is not distinguishable from any other. A fluent
315
+ * stream ignores the option — the warmup only runs on legacy streams (see
316
+ * {@link StreamOptions.fluent | fluent}).
317
+ *
127
318
  * @default false
128
319
  */
129
320
  streamWarmup?: boolean;
130
321
  /**
131
- * Maximum duration (in seconds) between messages before session times out.
132
- * Can only be used with proper permissions
133
- * @maximum 300
134
- * @example 180
322
+ * How long the session may sit idle between messages before the server ends it, in seconds.
323
+ *
324
+ * Up to 300, and only for accounts whose plan allows it. When the session does time out,
325
+ * {@link AgentManagerCallbacks.onConnectionStateChange | onConnectionStateChange} reports
326
+ * {@link ConnectionState.Disconnected | 'disconnected'} with the reason
327
+ * {@link StreamEndReason.Inactivity | 'inactivity'}. Leave it out and the server decides.
135
328
  */
136
329
  sessionTimeout?: number;
137
330
  /**
138
- * Desired stream resolution for the session
139
- * @minimum 150
140
- * @maximum 1080
141
- */
142
- outputResolution?: number;
143
- /**
144
- * Whether to request fluent stream.
331
+ * Whether to request a fluent stream.
332
+ *
333
+ * `true` streams one video for both the idle and talking states; `false` uses the legacy mode,
334
+ * where the application swaps between two video elements. Clips (V3) agents built on a Pro
335
+ * avatar; always on for Expressive (V4). A fluent stream is also what makes
336
+ * {@link AgentManager.interrupt | interrupt()} available.
337
+ *
145
338
  * @default false
146
339
  */
147
340
  fluent?: boolean;
148
341
  }
342
+ /**
343
+ * Everything {@link createAgentManager} needs to reach an agent and report back to the application.
344
+ *
345
+ * {@link AgentManagerOptions.auth | auth} and {@link AgentManagerOptions.callbacks | callbacks} are
346
+ * required; the rest have defaults that suit a browser application talking to D-ID production.
347
+ *
348
+ * @category Agent Manager
349
+ */
149
350
  export interface AgentManagerOptions {
150
- auth: Auth;
151
- callbacks: ManagerCallbacks;
152
- mode?: ChatMode;
153
- baseURL?: string;
154
- wsURL?: string;
155
- debug?: boolean;
156
- verbose?: boolean;
157
- /**
158
- * Whether to enable analytics (Mixpanel) tracking.
159
- * @default true
160
- * @deprecated Use `enableAnalytics` instead. This misspelled prop is kept for backwards compatibility.
161
- */
162
- enableAnalitics?: boolean;
163
- /**
164
- * Whether to enable analytics (Mixpanel) tracking.
165
- * Takes precedence over the deprecated `enableAnalitics` prop when both are set.
166
- * @default true
167
- */
168
- enableAnalytics?: boolean;
169
- mixpanelKey?: string;
170
- mixpanelAdditionalProperties?: Record<string, any>;
171
- externalId?: string;
172
- streamOptions?: StreamOptions;
173
- initialMessages?: Message[];
174
- persistentChat?: boolean;
175
- microphoneStream?: MediaStream;
176
- }
177
- export interface AgentManager {
178
351
  /**
179
- * Agent instance you are working with.
180
- * To know more about agents go to https://docs.d-id.com/reference/agents
352
+ * Credentials used for every request the SDK makes on the application's behalf.
353
+ *
354
+ * Use `{ type: 'key', clientKey }` in a browser: a client key is scoped to one agent and to
355
+ * the domains you allowed, so it is the only shape that is safe to ship in a page. See
356
+ * {@link Auth}.
181
357
  */
182
- agent: Agent;
183
- /**
184
- * Get the current stream type of the agent
185
- */
186
- getStreamType: () => StreamType | undefined;
187
- /**
188
- * Get if the stream supports interrupt
189
- */
190
- getIsInterruptAvailable: () => boolean;
191
- /**
192
- * Array of starter messages that will be sent to the agent when the chat starts
193
- */
194
- starterMessages: string[];
195
- /**
196
- * Get a token for the Speech to Text service
197
- * Only available after a chat has started and the agent has been connected
198
- */
199
- getSTTToken: () => Promise<STTTokenResponse | undefined>;
200
- /**
201
- * Method to connect to stream and chat
202
- */
203
- connect: () => Promise<void>;
204
- /**
205
- * Method to reconnect to stream and continue chat
206
- */
207
- reconnect: () => Promise<void>;
358
+ auth: Auth;
208
359
  /**
209
- * Method to close all connections with agent, stream and web socket
360
+ * Handlers the SDK calls as the connection, the video stream and the chat change state.
361
+ *
362
+ * See {@link AgentManagerCallbacks}.
363
+ * {@link AgentManagerCallbacks.onSrcObjectReady | onSrcObjectReady} is mandatory — it is what
364
+ * connects the streamed media to your video element; the rest are optional.
210
365
  */
211
- disconnect: () => Promise<void>;
366
+ callbacks: AgentManagerCallbacks;
212
367
  /**
213
- * Publish a microphone stream to the data channel
214
- * Can be called after connection to add microphone input
215
- * @param stream The MediaStream containing the microphone audio track
216
- * supported only for livekit manager
368
+ * How the agent answers: with a streamed video, as text only, or not at all.
369
+ *
370
+ * See {@link ChatMode}. It can be changed later with
371
+ * {@link AgentManager.changeMode | changeMode()}. {@link ChatMode.Off} and
372
+ * {@link ChatMode.DirectPlayback} are supported on Talks (V2) and Clips (V3) agents only.
373
+ *
374
+ * @default ChatMode.Functional
375
+ * @throws {@link ValidationError} From {@link createAgentManager}, when the agent is Expressive
376
+ * (V4) and the mode is {@link ChatMode.Off} or {@link ChatMode.DirectPlayback}.
217
377
  */
218
- publishMicrophoneStream?: (stream: MediaStream) => Promise<void>;
378
+ mode?: ChatMode;
219
379
  /**
220
- * Unpublish the currently published microphone stream
221
- * Can be called after connection to remove microphone input
222
- * supported only for livekit manager
380
+ * Base URL of the D-ID Agents API. Used by D-ID to point the SDK at a test environment.
381
+ *
382
+ * @internal
223
383
  */
224
- unpublishMicrophoneStream?: () => Promise<void>;
384
+ baseURL?: string;
225
385
  /**
226
- * Replace the live microphone track on the current publication without
227
- * unpublishing. Preserves the LiveKit publication (SSRC, trackSid) so the
228
- * server sees continuous audio across mic device swaps. Resolves once
229
- * LiveKit has switched the underlying RTCRtpSender's track.
230
- * Rejects if there is no active publication — callers should fall back to
231
- * `publishMicrophoneStream` in that case.
232
- * Supported only for the LiveKit streaming manager.
386
+ * URL of the D-ID notifications web socket. Used by D-ID to point the SDK at a test environment.
387
+ *
388
+ * @internal
233
389
  */
234
- replaceMicrophoneTrack?: (track: MediaStreamTrack) => Promise<void>;
390
+ wsURL?: string;
235
391
  /**
236
- * Publish a camera video stream to the LiveKit room.
237
- * Can be called after connection to enable vision.
238
- * supported only for livekit manager
392
+ * Whether the SDK logs its streaming lifecycle to the browser console.
393
+ *
394
+ * It is also switched on for everyone when the agent's `ui_debug_mode` advanced setting is
395
+ * enabled, regardless of the value passed here.
396
+ *
397
+ * @default false
239
398
  */
240
- publishCameraStream?: (stream: MediaStream) => Promise<void>;
399
+ debug?: boolean;
241
400
  /**
242
- * Unpublish the currently published camera stream.
243
- * Can be called after connection to disable vision.
244
- * supported only for livekit manager
401
+ * Whether the stream is created in verbose mode, which logs more server-side detail.
402
+ *
403
+ * Independent of {@link AgentManagerOptions.debug | debug}: this one is sent to the streaming
404
+ * service rather than controlling console output. Expressive (V4) agents only.
405
+ *
406
+ * @default false
245
407
  */
246
- unpublishCameraStream?: () => Promise<void>;
408
+ verbose?: boolean;
247
409
  /**
248
- * Method to send a chat message to existing chat with the agent
249
- * @param messages
410
+ * Whether the SDK reports usage analytics. Set it to `false` to send nothing.
411
+ *
412
+ * It is on unless you turn it off. The SDK posts an event to Mixpanel for each step of a
413
+ * session — connect, reconnect and disconnect, every message sent and answered, every
414
+ * {@link AgentManager.speak | speak()}, mode change, rating, feedback, tool call, video start
415
+ * and stop, interrupt and error. Each event carries the agent id, the visitor id derived from
416
+ * {@link AgentManagerOptions.externalId | externalId}, the page URL, the screen size, the user
417
+ * agent, the SDK version and whatever
418
+ * {@link AgentManagerOptions.mixpanelAdditionalProperties | mixpanelAdditionalProperties}
419
+ * added. Conversation text is included too: the agent's answer on `agent-message-received`,
420
+ * and the script on `agent-speak`.
421
+ *
422
+ * The events go to D-ID's own Mixpanel project unless
423
+ * {@link AgentManagerOptions.mixpanelKey | mixpanelKey} points them at yours. Events that fail
424
+ * to post are buffered in memory (at most 50) and retried when the tab comes back online or
425
+ * becomes visible.
426
+ *
427
+ * @default true
250
428
  */
251
- chat: (userMessage: string) => Promise<ChatResponse>;
429
+ enableAnalytics?: boolean;
252
430
  /**
253
- * Method to rate the answer in chat
254
- * @param score: 1 | -1 - score of the answer. 1 for positive, -1 for negative
255
- * @param matches - array of matches that were used to find the answer
256
- * @param id - id of Rating entity. Leave it empty to create a new, one or pass it to work with the existing one
431
+ * Mixpanel project token the SDK's analytics events are sent to.
432
+ *
433
+ * Defaults to D-ID's own project. Set it to send the SDK's events to your Mixpanel project
434
+ * instead.
257
435
  */
258
- rate: (messageId: string, score: 1 | -1, rateId?: string) => Promise<RatingEntity>;
436
+ mixpanelKey?: string;
259
437
  /**
260
- * Method to delete rating from answer in chat
261
- * @param id - id of Rating entity.
438
+ * Extra properties merged into every analytics event the SDK sends.
439
+ *
440
+ * A flat object — use it to tag events with your own identifiers. More properties can be added
441
+ * later with {@link AgentManager.enrichAnalytics | enrichAnalytics()}.
262
442
  */
263
- deleteRate: (id: string) => Promise<RatingEntity>;
443
+ mixpanelAdditionalProperties?: Record<string, unknown>;
264
444
  /**
265
- * Method to submit end-of-call feedback for the chat
266
- * @param rating - integer score from 1 to 5
267
- * @param answer - optional free-text answer
445
+ * Your own identifier for the end user.
446
+ *
447
+ * It is stored in `localStorage`, sent as part of the `type: 'key'` authorization header and
448
+ * attached to analytics, so the same visitor is recognised across page loads. When it is
449
+ * omitted the SDK generates an id and reuses it.
268
450
  */
269
- submitFeedback: (rating: number, answer?: string) => Promise<SubmitFeedbackResponse>;
451
+ externalId?: string;
270
452
  /**
271
- * Method to make your agent read the text you provide or reproduce sound
272
- * @param payload
453
+ * Transport settings applied when the stream is created.
454
+ *
455
+ * See {@link StreamOptions}. Talks (V2) and Clips (V3) agents only. Expressive (V4) agents
456
+ * manage transport settings automatically.
273
457
  */
274
- speak: (payload: SupportedStreamScript | string) => Promise<SendStreamPayloadResponse>;
458
+ streamOptions?: StreamOptions;
275
459
  /**
276
- * Method to change the mode of the chat
277
- * @param mode - ChatMode
460
+ * Messages the chat starts with, for example a transcript restored from your own storage.
461
+ *
462
+ * They are delivered to {@link AgentManagerCallbacks.onNewMessage | onNewMessage} so the UI can
463
+ * render them. On Talks (V2) and Clips (V3) agents they are also sent as context with the next
464
+ * {@link AgentManager.chat | chat()} request. See {@link Message}.
465
+ *
466
+ * {@link Message.parts | parts} is a required field, but it does not have to be filled: pass an
467
+ * empty array and the SDK builds the parts from `content` with {@link parseMessageParts}, so a
468
+ * transcript restored from `content` alone still renders. A non-empty array is kept as given.
469
+ *
470
+ * @example Restoring rows that carry only the message text
471
+ * ```ts
472
+ * const initialMessages = stored.map(({ id, role, content }) => ({ id, role, content, parts: [] }));
473
+ * ```
278
474
  */
279
- changeMode(mode: ChatMode): void;
475
+ initialMessages?: Message[];
280
476
  /**
281
- * Method to enrich analytics properties
282
- * @param properties flat json object with properties that will be added to analytics events fired from the sdk
477
+ * Whether the server keeps the chat so it can be resumed in a later session.
478
+ *
479
+ * Without persistence a chat lives only as long as the connection.
480
+ * {@link AgentManager.reconnect | reconnect()} normally continues the same chat either way —
481
+ * see the caveat there for Expressive (V4) agents.
482
+ *
483
+ * Off unless you set it, on every agent type.
484
+ *
485
+ * @default false
283
486
  */
284
- enrichAnalytics: (properties: Record<string, any>) => void;
487
+ persistentChat?: boolean;
488
+ }
489
+ /**
490
+ * A live connection to one agent: its profile, its chat, and the video stream it answers on.
491
+ *
492
+ * Created by {@link createAgentManager}. Nothing happens on the wire until
493
+ * {@link AgentManager.connect | connect()} resolves; after that
494
+ * {@link AgentManager.chat | chat()} makes the agent answer with its own LLM and
495
+ * {@link AgentManager.speak | speak()} makes it say exactly what you give it. Call
496
+ * {@link AgentManager.disconnect | disconnect()} when the user leaves.
497
+ *
498
+ * Two properties, {@link AgentManager.agent | agent} and
499
+ * {@link AgentManager.starterMessages | starterMessages}, are readable as soon as the manager
500
+ * exists; everything else is a method. Some methods work only with some avatar types: each one
501
+ * says so, and {@link AgentAvatar} is where the session's tier is read from.
502
+ *
503
+ * Every method that reaches the Agents API can reject with an {@link HttpError} when the request
504
+ * comes back non-2xx, or a {@link NetworkError} when it never reaches the server; the individual
505
+ * `@throws` entries below name the errors that are specific to each method.
506
+ *
507
+ * @category Agent Manager
508
+ */
509
+ export interface AgentManager {
285
510
  /**
286
- * Method to interrupt the current video stream
287
- * Only available for Fluent streams and when there's an active video to interrupt
511
+ * The agent this manager is connected to, as the Agents API returned it.
512
+ *
513
+ * Fetched once while the manager is created, so it is available before
514
+ * {@link AgentManager.connect | connect()}. Useful for rendering the agent's name, thumbnail
515
+ * and {@link Agent.idle_video | idle_video}. See {@link Agent}.
288
516
  */
289
- interrupt: (interrupt: Interrupt) => void;
517
+ agent: Agent;
290
518
  /**
291
- * Switch the STT language mid-session
292
- * Only available for Expressive (V4) agents
293
- * @param language - Language name or BCP-47 code (e.g. "English" or "en-US")
519
+ * Returns the kind of stream the current session negotiated.
520
+ *
521
+ * @returns {@link StreamType.Fluent} for a fluent stream (one video for the idle and talking
522
+ * states), {@link StreamType.Legacy} for the two-element legacy mode, or `undefined` before
523
+ * {@link AgentManager.connect | connect()} has established a session.
294
524
  */
295
- setSttLanguage: (language: string) => Promise<void>;
525
+ getStreamType(): StreamType | undefined;
296
526
  /**
297
- * Send a JSON payload to the agent over a data-channel topic
298
- * Only available for Expressive (V4) agents
299
- * @param topic - Data-channel topic to send on (see `PublicDataChannelTopic`)
300
- * @param payload - Plain object, serialized as JSON
527
+ * Returns whether the current stream supports interrupting the agent mid-answer.
528
+ *
529
+ * True on a fluent stream — a Clips (V3) agent built on a Pro avatar, or any Expressive (V4)
530
+ * agent — once connected. This says the stream supports interrupting at all;
531
+ * {@link AgentManagerCallbacks.onInterruptibleChange | onInterruptibleChange} says whether
532
+ * interrupting is allowed right now.
533
+ *
534
+ * @returns `true` when {@link AgentManager.interrupt | interrupt()} can do anything.
301
535
  */
302
- sendDataChannelMessage: (topic: PublicDataChannelTopic, payload: Record<string, unknown>) => Promise<void>;
536
+ getIsInterruptAvailable(): boolean;
303
537
  /**
304
- * Register a handler for a client tool. When the agent's LLM calls this tool,
305
- * the handler executes on the client and returns the result to the LLM.
306
- * @param name - Tool name (must match the tool name defined in the agent config)
307
- * @param handler - Async function receiving args, must return a JSON string (max 15KiB)
538
+ * The agent's starter messages.
539
+ *
540
+ * Suggested openers to offer the user as buttons; empty when the agent defines none. Available
541
+ * before {@link AgentManager.connect | connect()}.
308
542
  */
309
- registerClientTool: (name: string, handler: ClientToolHandler) => void;
543
+ starterMessages: string[];
310
544
  /**
311
- * Remove a previously registered client tool handler.
312
- * @param name - Tool name to unregister
313
- */
314
- unregisterClientTool: (name: string) => void;
545
+ * Fetches a short-lived token for the D-ID speech-to-text service.
546
+ *
547
+ * The SDK sends the request whenever it is called, connected or not; the service decides
548
+ * whether to issue a token for the agent.
549
+ *
550
+ * @returns The {@link STTTokenResponse} for this agent.
551
+ * @throws {@link HttpError} When the service does not answer with a token, or the request comes
552
+ * back non-2xx for any other reason.
553
+ * @throws {@link NetworkError} When the request never reaches the server.
554
+ */
555
+ getSTTToken(): Promise<STTTokenResponse>;
556
+ /**
557
+ * Opens a new session with the agent: a new WebRTC connection, a new web socket and a new chat.
558
+ *
559
+ * Resolves once the connection reaches {@link ConnectionState.Connected | 'connected'}, by
560
+ * which point {@link AgentManagerCallbacks.onSrcObjectReady | onSrcObjectReady} has been called
561
+ * with the media stream to render. Calling it again starts a fresh conversation; to keep the
562
+ * current one use {@link AgentManager.reconnect | reconnect()}.
563
+ *
564
+ * @returns Resolves when the agent is connected and ready.
565
+ * @throws {@link HttpError} When creating the stream or the chat comes back non-2xx — a client
566
+ * key that is not authorized for the agent or the calling domain, or an account out of
567
+ * credits. The SDK tries the initialization up to three times first, except on `429` and on an
568
+ * out-of-credits response.
569
+ * @throws {@link NetworkError} When those requests never reach the server.
570
+ * @example
571
+ * ```ts
572
+ * await agentManager.connect();
573
+ * ```
574
+ */
575
+ connect(): Promise<void>;
576
+ /**
577
+ * Reopens the stream when the session expires, and continues the conversation on the same chat.
578
+ *
579
+ * The chat id normally does not change, so the agent keeps its context. It starts a new stream
580
+ * — including after the server ended the previous one deliberately — rather than resuming the
581
+ * old one. On Expressive (V4) agents the transport is asked to reconnect first; if that fails
582
+ * the SDK falls back to a disconnect and a fresh connect, which starts a new chat id.
583
+ *
584
+ * @returns Resolves when the new stream is connected.
585
+ * @throws {@link HttpError} When creating the new stream comes back non-2xx.
586
+ * @throws {@link NetworkError} When that request never reaches the server.
587
+ */
588
+ reconnect(): Promise<void>;
589
+ /**
590
+ * Closes the existing connection and chat with the agent: the stream and the web socket.
591
+ *
592
+ * Call it when the user leaves the page or the conversation, so the session does not keep
593
+ * running. After it resolves, {@link AgentManager.connect | connect()} is needed before the
594
+ * agent can be used again.
595
+ *
596
+ * @returns Resolves once everything is closed.
597
+ */
598
+ disconnect(): Promise<void>;
599
+ /**
600
+ * Publishes a microphone audio track to the session so the agent can hear the user.
601
+ *
602
+ * Call it after {@link AgentManager.connect | connect()} to enable voice input. Expressive (V4)
603
+ * agents only; on Talks (V2) and Clips (V3) agents, and before `connect()`, the returned
604
+ * promise rejects with a {@link ValidationError}.
605
+ *
606
+ * @param stream - A `MediaStream` whose audio track is published to the session.
607
+ * @returns Resolves once the track is published.
608
+ * @throws {@link ValidationError} When the session is not an Expressive (V4) one, or
609
+ * {@link AgentManager.connect | connect()} has not run yet.
610
+ * @example
611
+ * ```ts
612
+ * const micStream = await navigator.mediaDevices.getUserMedia({ audio: true });
613
+ * await agentManager.publishMicrophoneStream(micStream);
614
+ * ```
615
+ */
616
+ publishMicrophoneStream(stream: MediaStream): Promise<void>;
617
+ /**
618
+ * Stops and removes the currently published microphone track from the session.
619
+ *
620
+ * The counterpart of {@link AgentManager.publishMicrophoneStream | publishMicrophoneStream()} —
621
+ * use it to mute the user for the rest of the session. Expressive (V4) agents only; on Talks
622
+ * (V2) and Clips (V3) agents, and when nothing is published, it resolves without doing
623
+ * anything.
624
+ *
625
+ * @returns Resolves once the track is removed.
626
+ * @example
627
+ * ```ts
628
+ * await agentManager.unpublishMicrophoneStream();
629
+ * ```
630
+ */
631
+ unpublishMicrophoneStream(): Promise<void>;
632
+ /**
633
+ * Swaps the live microphone track without unpublishing it.
634
+ *
635
+ * Use it when the user picks a different input device: the publication is preserved — its
636
+ * LiveKit publication id (SID) and SSRC stay the same, though the `MediaStreamTrack` id
637
+ * changes — so the server sees continuous audio across the swap rather than a stop and a
638
+ * restart. Rejects with a plain `Error` from the transport when there is no active publication
639
+ * — fall back to {@link AgentManager.publishMicrophoneStream | publishMicrophoneStream()} in
640
+ * that case. Expressive (V4) agents only; on Talks (V2) and Clips (V3) agents, and before
641
+ * {@link AgentManager.connect | connect()}, the returned promise rejects with a
642
+ * {@link ValidationError}.
643
+ *
644
+ * @param track - The audio track to send from now on.
645
+ * @returns Resolves once the transport has switched to the new track.
646
+ * @throws {@link ValidationError} When the session is not an Expressive (V4) one, or
647
+ * {@link AgentManager.connect | connect()} has not run yet.
648
+ */
649
+ replaceMicrophoneTrack(track: MediaStreamTrack): Promise<void>;
650
+ /**
651
+ * Publishes a camera video track to the session so the agent can see the user.
652
+ *
653
+ * Call it after {@link AgentManager.connect | connect()} to enable vision. Expressive (V4)
654
+ * agents only; on Talks (V2) and Clips (V3) agents, and before `connect()`, the returned
655
+ * promise rejects with a {@link ValidationError}.
656
+ *
657
+ * @param stream - A `MediaStream` whose video track is published to the session.
658
+ * @returns Resolves once the track is published.
659
+ * @throws {@link ValidationError} When the session is not an Expressive (V4) one, or
660
+ * {@link AgentManager.connect | connect()} has not run yet.
661
+ */
662
+ publishCameraStream(stream: MediaStream): Promise<void>;
663
+ /**
664
+ * Stops and removes the currently published camera track from the session.
665
+ *
666
+ * Call it to disable vision. Expressive (V4) agents only; on Talks (V2) and Clips (V3) agents,
667
+ * and when nothing is published, it resolves without doing anything.
668
+ *
669
+ * @returns Resolves once the track is removed.
670
+ */
671
+ unpublishCameraStream(): Promise<void>;
672
+ /**
673
+ * Sends a message to the agent and gets a streamed video based on its answer (LLM).
674
+ *
675
+ * The answer arrives through {@link AgentManagerCallbacks.onNewMessage | onNewMessage} — first
676
+ * as `partial` chunks, then as the full `answer` — while the video plays it. The chat is
677
+ * created on the first call if the session does not have one yet.
678
+ *
679
+ * @param userMessage - The user's message text to send to the agent.
680
+ * @returns The {@link ChatResponse} for this turn.
681
+ * @throws {@link ValidationError} When the message is empty or too long, when the chat mode has
682
+ * chat disabled or is in maintenance, or when the manager is not connected yet.
683
+ * @throws {@link ChatCreationFailed} On Talks (V2) and Clips (V3) agents, when the session has
684
+ * no chat yet and the Agents API answers the creation request without one.
685
+ * @throws {@link HttpError} On Talks (V2) and Clips (V3) agents, and in
686
+ * {@link ChatMode.Playground}, when the message request comes back non-2xx. Expressive (V4)
687
+ * agents send the message over the data channel instead, so no HTTP request is made.
688
+ * @throws {@link NetworkError} On Talks (V2) and Clips (V3) agents, and in
689
+ * {@link ChatMode.Playground}, when that request never reaches the server.
690
+ * @example
691
+ * ```ts
692
+ * const chat = await agentManager.chat('What is the distance to the moon?');
693
+ * ```
694
+ */
695
+ chat(userMessage: string): Promise<ChatResponse>;
696
+ /**
697
+ * Rates one of the agent's answers in the chat, for future analytics and insights.
698
+ *
699
+ * Pass `rateId` to change a rating the user already gave instead of adding another.
700
+ *
701
+ * @param messageId - Id of the message being rated.
702
+ * @param score - 1 for a positive rating, -1 for a negative one.
703
+ * @param rateId - Id of an existing rating to update; omit to create a new one.
704
+ * @returns The created or updated {@link RatingEntity}.
705
+ * @throws {@link ValidationError} When no chat has started, or when no message with that id is
706
+ * in the transcript.
707
+ * @throws {@link HttpError} When the rating request comes back non-2xx.
708
+ * @throws {@link NetworkError} When the rating request never reaches the server.
709
+ */
710
+ rate(messageId: string, score: 1 | -1, rateId?: string): Promise<RatingEntity>;
711
+ /**
712
+ * Removes a rating the user gave to an answer in the chat.
713
+ *
714
+ * @param id - Id of the rating to remove, as returned by
715
+ * {@link AgentManager.rate | rate()}.
716
+ * @returns The {@link RatingEntity} that was deleted.
717
+ * @throws {@link ValidationError} When no chat has started.
718
+ * @throws {@link HttpError} When the delete request comes back non-2xx.
719
+ * @throws {@link NetworkError} When the delete request never reaches the server.
720
+ */
721
+ deleteRate(id: string): Promise<RatingEntity>;
722
+ /**
723
+ * Submits end-of-call feedback for the whole conversation.
724
+ *
725
+ * Separate from {@link AgentManager.rate | rate()}, which scores a single answer. Collect it
726
+ * when the user ends the call, using the agent's end-of-call feedback configuration.
727
+ *
728
+ * @param rating - The user's score for the conversation, a whole number from 1 to 5.
729
+ * @param answer - The user's free-text answer to the follow-up question, when one was asked.
730
+ * @returns The stored {@link SubmitFeedbackResponse}.
731
+ * @throws {@link ValidationError} When no chat has started.
732
+ * @throws {@link HttpError} When the feedback request comes back non-2xx.
733
+ * @throws {@link NetworkError} When the feedback request never reaches the server.
734
+ */
735
+ submitFeedback(rating: number, answer?: string): Promise<SubmitFeedbackResponse>;
736
+ /**
737
+ * Makes the agent stream back a video based on the text or audio file you provide.
738
+ *
739
+ * Unlike {@link AgentManager.chat | chat()} the agent's LLM is not involved, so this is how you
740
+ * script greetings and canned lines. Pass a plain string as a shorthand for a text script. See
741
+ * {@link SupportedStreamScript}, {@link TextStreamScript} and {@link AudioStreamScript}. Text
742
+ * scripts also accept an optional `sentiment`, for Expressive (V4) agents only; if the
743
+ * requested sentiment is not supported by the agent, the default sentiment is used.
744
+ *
745
+ * @see [Create a video stream](https://docs.d-id.com/reference/createvideoagentstream) — the request
746
+ * sent for Talks (V2) and Clips (V3) agents.
747
+ * @see [Control the Agent](https://docs.d-id.com/docs/livekit-commands) — the `did.speak` command
748
+ * sent over the data channel for Expressive (V4) agents.
749
+ * @param payload - A text or audio script, or a string treated as the text to speak.
750
+ * @returns The {@link SendStreamPayloadResponse} for the video that was produced, or the same
751
+ * response with `duration` `0` and an empty `video_id` when the call produced no discrete video
752
+ * — on Expressive (V4) agents, and in a text-only chat mode.
753
+ * @throws {@link ValidationError} When the manager is not connected to a stream yet.
754
+ * @throws {@link HttpError} On Talks (V2) and Clips (V3) agents, when the Agents API answers
755
+ * the request non-2xx. Expressive (V4) agents send the script over the data channel instead,
756
+ * so no HTTP request is made.
757
+ * @throws {@link NetworkError} On Talks (V2) and Clips (V3) agents, when that request never
758
+ * reaches the server.
759
+ * @example Text
760
+ * ```ts
761
+ * const speak = await agentManager.speak({
762
+ * type: 'text',
763
+ * input: "Hi! I'm Alice!",
764
+ * });
765
+ * ```
766
+ * @example Text with sentiment (Expressive (V4) agents)
767
+ * ```ts
768
+ * const speak = await agentManager.speak({
769
+ * type: 'text',
770
+ * input: "Hi! I'm Alice!",
771
+ * sentiment: 'friendly',
772
+ * });
773
+ * ```
774
+ * @example Audio file
775
+ * ```ts
776
+ * const speak = await agentManager.speak({
777
+ * type: 'audio',
778
+ * audio_url: 'https://www.yourwebsite.com/audio.mp3',
779
+ * });
780
+ * ```
781
+ */
782
+ speak(payload: SupportedStreamScript | string): Promise<SendStreamPayloadResponse>;
783
+ /**
784
+ * Switches the chat to another mode.
785
+ *
786
+ * Anything other than {@link ChatMode.Functional} disconnects the stream, since those modes do
787
+ * not produce video, which is why this is asynchronous: the returned promise resolves once that
788
+ * disconnect has finished. {@link AgentManagerCallbacks.onModeChange | onModeChange} fires once
789
+ * the change has been applied; passing the mode already in effect does nothing.
790
+ *
791
+ * @param mode - The {@link ChatMode} to switch to.
792
+ * @returns A promise resolved when the mode is in effect and any disconnect it caused has
793
+ * completed.
794
+ * @throws {@link ValidationError} Rejects on Expressive (V4) agents for {@link ChatMode.Off} and
795
+ * {@link ChatMode.DirectPlayback}, which those agents do not support.
796
+ */
797
+ changeMode(mode: ChatMode): Promise<void>;
798
+ /**
799
+ * Adds properties to every analytics event the SDK sends from now on.
800
+ *
801
+ * The same thing
802
+ * {@link AgentManagerOptions.mixpanelAdditionalProperties | mixpanelAdditionalProperties} does
803
+ * at creation time, for values you only learn later.
804
+ *
805
+ * @param properties - A flat JSON object whose properties are added to every analytics event
806
+ * the SDK sends from now on.
807
+ */
808
+ enrichAnalytics(properties: Record<string, unknown>): void;
809
+ /**
810
+ * Interrupts the current video stream mid-playback, so the user can talk over the agent.
811
+ *
812
+ * Supported on a fluent stream — a Clips (V3) agent built on a Pro avatar, or any Expressive
813
+ * (V4) agent. It never throws: on every agent type it returns without doing anything when
814
+ * interrupting is not available for the session, when it is not allowed right now, and — on
815
+ * Talks (V2) and Clips (V3) agents — when the stream is not a fluent stream or no video is
816
+ * playing. Check {@link AgentManager.getIsInterruptAvailable | getIsInterruptAvailable()}
817
+ * before offering the control at all; on Expressive (V4) agents
818
+ * {@link AgentManagerCallbacks.onInterruptibleChange | onInterruptibleChange} tracks whether it
819
+ * is allowed right now.
820
+ *
821
+ * The interrupted message is marked as such in the next
822
+ * {@link AgentManagerCallbacks.onNewMessage | onNewMessage} — but only when an interrupt was
823
+ * actually sent. A call that finds nothing to interrupt leaves the message untouched and fires
824
+ * no callback.
825
+ *
826
+ * @param interrupt - What caused the interruption, as an {@link Interrupt}: `text`, `audio`,
827
+ * `click` or `manual`. Expressive (V4) agents drop `text` interrupts, because the orchestrator
828
+ * does not cancel the in-flight answer for them.
829
+ */
830
+ interrupt(interrupt: Interrupt): void;
831
+ /**
832
+ * Switches the speech-to-text language in the middle of a session.
833
+ *
834
+ * Expressive (V4) agents only, after {@link AgentManager.connect | connect()}; otherwise the
835
+ * returned promise rejects with a {@link ValidationError}.
836
+ *
837
+ * @param language - The language to transcribe in, as a name or a BCP-47 code — `"English"` or
838
+ * `"en-US"`.
839
+ * @returns Resolves once the new language has been sent to the agent. A room that has dropped
840
+ * since {@link AgentManager.connect | connect()} reports a {@link StreamError} through
841
+ * {@link AgentManagerCallbacks.onError | onError} and the promise still resolves.
842
+ * @throws {@link ValidationError} When the session is not an Expressive (V4) one, or
843
+ * {@link AgentManager.connect | connect()} has not run yet.
844
+ */
845
+ setSttLanguage(language: string): Promise<void>;
846
+ /**
847
+ * Sends a JSON payload to the agent over a data-channel topic.
848
+ *
849
+ * Use it for application-specific messages that are not speech, such as telling a presentation
850
+ * to change slide. Expressive (V4) agents only, after {@link AgentManager.connect | connect()};
851
+ * otherwise the returned promise rejects with a {@link ValidationError}.
852
+ *
853
+ * @param topic - Data-channel topic to send on. {@link PublicDataChannelTopic} is exported from
854
+ * the package root and lists every topic this method accepts.
855
+ * @param payload - A plain object, sent as JSON.
856
+ * @returns Resolves once the payload has been sent. A room that has dropped since
857
+ * {@link AgentManager.connect | connect()} reports a {@link StreamError} through
858
+ * {@link AgentManagerCallbacks.onError | onError} and the promise still resolves.
859
+ * @throws {@link ValidationError} When the session is not an Expressive (V4) one, or
860
+ * {@link AgentManager.connect | connect()} has not run yet.
861
+ * @example
862
+ * ```ts
863
+ * import { PublicDataChannelTopic } from '@d-id/client-sdk';
864
+ *
865
+ * await agentManager.sendDataChannelMessage(PublicDataChannelTopic.Presentation, {
866
+ * type: 'navigate',
867
+ * slide: 3,
868
+ * });
869
+ * ```
870
+ */
871
+ sendDataChannelMessage(topic: PublicDataChannelTopic, payload: Record<string, unknown>): Promise<void>;
872
+ /**
873
+ * Registers a handler for a client tool, run in the browser when the agent's LLM calls it.
874
+ *
875
+ * The handler executes on the client and its result is returned to the LLM. Register the
876
+ * handlers before {@link AgentManager.connect | connect()} so the agent can call
877
+ * them from the moment the session starts; registering the same name again replaces the
878
+ * handler. Progress is reported through
879
+ * {@link AgentManagerCallbacks.onToolEvent | onToolEvent}.
880
+ *
881
+ * @param name - Name of the tool, which must match the one defined in the agent's
882
+ * configuration.
883
+ * @param handler - The function that runs when the agent calls the tool. It receives the
884
+ * arguments the LLM produced and must resolve to a JSON string of at most 15 KiB. See
885
+ * {@link ClientToolHandler}.
886
+ */
887
+ registerClientTool(name: string, handler: ClientToolHandler): void;
888
+ /**
889
+ * Removes a previously registered client tool handler.
890
+ *
891
+ * After this the agent's calls to that tool fail rather than reaching your code.
892
+ *
893
+ * @param name - Name of the tool whose handler should be removed.
894
+ */
895
+ unregisterClientTool(name: string): void;
315
896
  }
316
- export {};