@memberjunction/ai 5.40.2 → 5.42.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,538 @@
1
+ import { BaseModel } from "./baseModel.js";
2
+ /**
3
+ * A JSON-serializable value. Used to type open configuration bags and JSON-schema
4
+ * objects at the Core layer without resorting to `any`.
5
+ */
6
+ export type JSONValue = string | number | boolean | null | JSONValue[] | {
7
+ [key: string]: JSONValue;
8
+ };
9
+ /**
10
+ * A JSON object — the common shape for a JSON-schema document or an open,
11
+ * provider-specific configuration bag.
12
+ */
13
+ export type JSONObject = {
14
+ [key: string]: JSONValue;
15
+ };
16
+ /**
17
+ * Base class for real-time, full-duplex, tool-calling models.
18
+ *
19
+ * `BaseRealtimeModel` is the lowest-level primitive for streaming, bidirectional models
20
+ * (e.g. Google Gemini Live, OpenAI GPT Realtime, and — as a fast-follow — the Eleven Labs
21
+ * stack). It is a sibling of {@link BaseModel}-derived capability classes such as `BaseLLM`
22
+ * and `BaseAudioGenerator`, and is resolved through the MemberJunction `ClassFactory` by
23
+ * `AIModelType` + `DriverClass`.
24
+ *
25
+ * The contract is deliberately **modality-agnostic** — *streaming, full-duplex, tool-calling* —
26
+ * so the same primitive covers voice now and video later. It is distinct from
27
+ * `BaseAudioGenerator`, which is request/response STT/TTS (a different shape, not the
28
+ * real-time path).
29
+ *
30
+ * **Driver registration:** Concrete drivers ship in the respective `@memberjunction/ai-*`
31
+ * provider packages and self-register via the class factory, e.g.
32
+ * `@RegisterClass(BaseRealtimeModel, 'GeminiRealtime')`. The associated `MJ: AI Models`
33
+ * are typed with the `AIModelType` value **`Realtime`**.
34
+ *
35
+ * ## DRIVER AUTHOR OBLIGATIONS
36
+ *
37
+ * Hard-won, provider-independent rules every server-side realtime driver (and its
38
+ * client-direct twin — see `BaseRealtimeClient` in `@memberjunction/ai-realtime-client`)
39
+ * MUST honor. Most were paid for in live debugging; do not relearn them:
40
+ *
41
+ * 1. **Silent exit from "speaking" after a tool call.** When the model emits a tool call,
42
+ * the host typically shows its own busy ("thinking") indicator while the tool executes.
43
+ * A driver that surfaces UI state must leave any "speaking" state *silently* (no state
44
+ * emission) at tool-call time so the turn's trailing frames don't clobber the host's
45
+ * indicator.
46
+ * 2. **Busy-flag release on tool-call emission (deadlock guard).** A tool-call frame means
47
+ * the model has yielded the floor pending the result. Any internal "response active" /
48
+ * busy flag MUST be cleared at that point — otherwise the eventual `SendToolResult` (or
49
+ * a queued send) deadlocks waiting for a turn boundary that will never arrive until
50
+ * after the result is sent.
51
+ * 3. **Playback flush + honest playback reporting on interruption.** On a true barge-in the
52
+ * driver (or its client twin) must flush any locally-owned audio playback and report
53
+ * "audio playing = false" promptly — stale queued audio after an interruption is a
54
+ * product bug, not a nicety.
55
+ * 4. **Text injection must NOT echo a user transcript.** A "send typed text" capability
56
+ * must not synthesize a user-role transcript event for the injected text — the host owns
57
+ * the local echo and would render the message twice.
58
+ * 5. **Tool-result delivery invariant.** Every tool result fed back via
59
+ * {@link IRealtimeSession.SendToolResult} must EVENTUALLY be voiced/processed by the
60
+ * model and must never be dropped. If the provider rejects overlapping generation
61
+ * triggers, the driver queues the result's trigger behind the in-flight response and
62
+ * flushes it at the next turn boundary.
63
+ * 6. **Token/credential expiry surfaces as a FATAL error.** When the session's credential
64
+ * dies (ephemeral token expiry, auth revocation), the driver must surface it through
65
+ * {@link IRealtimeSession.OnError} with `Fatal: true` so the consumer finalizes cleanly
66
+ * instead of idling forever on a dead socket.
67
+ * 7. **"Ready" only after the session config is applied.** A driver (or client twin) must
68
+ * not report the session as live/listening until the server-built session config
69
+ * (system prompt + tools) has actually been applied to the provider socket — otherwise
70
+ * early turns run against an unconfigured model.
71
+ * 8. **`SessionConfig` is a private pact.** The {@link ClientRealtimeSessionConfig.SessionConfig}
72
+ * payload a server driver mints is consumed ONLY by the same-keyed client driver. Hosts
73
+ * and intermediaries treat it as an opaque blob; its shape may change between the two
74
+ * driver halves without notice.
75
+ *
76
+ * @abstract
77
+ */
78
+ export declare abstract class BaseRealtimeModel extends BaseModel {
79
+ /**
80
+ * Opens a stateful duplex session with the provider.
81
+ *
82
+ * The returned {@link IRealtimeSession} is the long-lived handle that streams media and
83
+ * transcripts in both directions, surfaces tool calls and usage telemetry, and reports
84
+ * provider-detected interruptions (barge-in). The caller is responsible for closing the
85
+ * session via {@link IRealtimeSession.Close}.
86
+ *
87
+ * @param params Configuration for the session (system prompt, tools, initial context, model, and an open config bag).
88
+ * @returns A promise resolving to the live session handle.
89
+ */
90
+ abstract StartSession(params: RealtimeSessionParams): Promise<IRealtimeSession>;
91
+ /**
92
+ * Whether this driver can mint an ephemeral, server-scoped client credential for a
93
+ * **client-direct** realtime session (the browser opens its own provider socket using a
94
+ * short-lived token the server minted).
95
+ *
96
+ * Defaults to `false`. Providers that support browser-direct sessions override this to `true`
97
+ * and implement {@link CreateClientSession}. The server-bridged topology (where the provider
98
+ * socket lives on the server, via {@link StartSession}) is supported by every driver regardless
99
+ * of this flag.
100
+ *
101
+ * @returns `true` if {@link CreateClientSession} is supported; `false` otherwise.
102
+ */
103
+ get SupportsClientDirect(): boolean;
104
+ /**
105
+ * Mints an ephemeral, server-scoped client credential plus a provider-native session config for
106
+ * a **client-direct** realtime session.
107
+ *
108
+ * In the client-direct topology the browser owns the provider socket (e.g. WebRTC), but the
109
+ * **server** still controls the prompt and tool set: it mints a short-lived token and hands back
110
+ * a {@link ClientRealtimeSessionConfig} whose `SessionConfig` the matching client driver applies
111
+ * when it opens its socket. This keeps prompt/tool authority server-side even though the media
112
+ * plane is client-direct.
113
+ *
114
+ * Not every provider supports this (some only expose a server-bridged socket), so this is a
115
+ * concrete method that throws by default rather than an abstract one — that would force every
116
+ * existing and future driver to implement it. Providers that support it override
117
+ * {@link SupportsClientDirect} to `true` and override this method.
118
+ *
119
+ * @param _params The session parameters (system prompt, tools, model, config bag).
120
+ * @returns A promise resolving to the minted {@link ClientRealtimeSessionConfig}.
121
+ * @throws Always, unless overridden by a provider that supports client-direct sessions.
122
+ */
123
+ CreateClientSession(_params: RealtimeSessionParams): Promise<ClientRealtimeSessionConfig>;
124
+ /**
125
+ * Whether this driver's sessions carry a **video** track in addition to audio — i.e. the model
126
+ * accepts video input (it can "see" the user's camera) and/or emits video output (a talking-head
127
+ * avatar / generated video), in sync with audio.
128
+ *
129
+ * Defaults to `false` (audio-only — today's realtime models). Video-capable drivers (a native
130
+ * multimodal realtime model, or an avatar provider) override this to `true`. The session's media
131
+ * plane is media-tagged ({@link IRealtimeSession.SendInput} takes a {@link RealtimeMediaKind};
132
+ * {@link IRealtimeSession.OnVideoOutput} delivers video-out), so a video session reuses the entire
133
+ * realtime contract — only the media frames gain a `video` kind. Resolution prefers a video-capable
134
+ * model when an agent requests video, and degrades to audio-only otherwise.
135
+ *
136
+ * @returns `true` if sessions can carry video; `false` (audio-only) otherwise.
137
+ */
138
+ get SupportsVideo(): boolean;
139
+ /**
140
+ * The provider-native voice ids this model can speak with (e.g. OpenAI `alloy`/`echo`/`shimmer`). The
141
+ * model/driver is the authoritative owner of "what voices do I support", so each driver declares its
142
+ * own — used to populate the dev voice picker. Default empty (a driver that hasn't declared voices
143
+ * yields no picker options, falling back to the configured/default voice).
144
+ *
145
+ * NOTE: this is the near-term, driver-owned source of truth. Long term this should move to metadata so
146
+ * providers that let users add their OWN voices (e.g. ElevenLabs) can be enumerated dynamically.
147
+ *
148
+ * @returns The supported voice ids (id + human label), or `[]` when none are declared.
149
+ */
150
+ get SupportedVoices(): RealtimeVoiceOption[];
151
+ }
152
+ /** A selectable provider-native voice — `ID` is sent to the provider, `Name` is the human label. */
153
+ export interface RealtimeVoiceOption {
154
+ /** The provider-native voice id (e.g. `echo`) — what gets written to the session config. */
155
+ ID: string;
156
+ /** The human-friendly label for the picker (e.g. `Echo`). */
157
+ Name: string;
158
+ }
159
+ /**
160
+ * The media plane a realtime frame belongs to. The realtime contract is otherwise media-agnostic — a
161
+ * `video` session reuses every method (tools, transcript, usage, turn-taking); only the media frames
162
+ * carry this tag so audio and video can be disambiguated on the same session.
163
+ */
164
+ export type RealtimeMediaKind = 'audio' | 'video';
165
+ /**
166
+ * The server-minted configuration a browser needs to open a **client-direct** realtime session.
167
+ *
168
+ * Returned by {@link BaseRealtimeModel.CreateClientSession}. The browser authenticates to the
169
+ * provider with {@link ClientRealtimeSessionConfig.EphemeralToken} and hands
170
+ * {@link ClientRealtimeSessionConfig.SessionConfig} to the matching client driver — so the server
171
+ * retains control of the prompt and tool set even though the browser owns the socket.
172
+ *
173
+ * **`SessionConfig` is a private pact between same-keyed driver halves.** The server driver that
174
+ * minted it (selected by {@link ClientRealtimeSessionConfig.Provider}) and the client driver
175
+ * registered under the same key are the ONLY parties that understand its shape. Hosts and any
176
+ * transport in between must treat it as an opaque, serializable blob — never inspect, edit, or
177
+ * depend on its fields.
178
+ */
179
+ export interface ClientRealtimeSessionConfig {
180
+ /**
181
+ * The provider that minted the credential (e.g. `'openai'`). Lets the browser select the
182
+ * correct provider-direct client implementation.
183
+ */
184
+ Provider: string;
185
+ /**
186
+ * The provider realtime model id the session is scoped to (e.g. `gpt-realtime`).
187
+ */
188
+ Model: string;
189
+ /**
190
+ * The short-lived client secret the browser presents to the provider to authenticate its
191
+ * direct session. Server-scoped and expiring (see {@link ClientRealtimeSessionConfig.ExpiresAt}).
192
+ */
193
+ EphemeralToken: string;
194
+ /**
195
+ * ISO-8601 timestamp at which {@link ClientRealtimeSessionConfig.EphemeralToken} expires.
196
+ */
197
+ ExpiresAt: string;
198
+ /**
199
+ * The provider-native session config the matching client driver applies when it opens its
200
+ * socket (instructions/system prompt, tools, audio formats, turn detection). Because the server
201
+ * builds this, prompt and tool authority stay server-side even in the client-direct topology.
202
+ * Typed as a JSON object so it stays serializable across the server→client boundary — but its
203
+ * SHAPE is a private pact between the same-keyed server and client drivers; hosts must treat it
204
+ * opaquely and never read or rewrite its fields.
205
+ */
206
+ SessionConfig: JSONObject;
207
+ }
208
+ /**
209
+ * A long-lived, full-duplex session handle returned by {@link BaseRealtimeModel.StartSession}.
210
+ *
211
+ * All `On*` methods register a single handler invoked as the corresponding provider events
212
+ * arrive. Drivers must be written against this interface so a mock provider socket can be
213
+ * substituted for deterministic, network-free testing.
214
+ */
215
+ export interface IRealtimeSession {
216
+ /**
217
+ * The PCM sample rate (Hz) this model **consumes** on {@link IRealtimeSession.SendInput} — its audio
218
+ * INPUT format. Optional; consumers default to 24000 (OpenAI Realtime). **Gemini Live = 16000.** A
219
+ * server-bridged host (LiveKit/Zoom/Teams) MUST resample inbound room audio to this rate or the model
220
+ * receives mis-rated audio it can't parse (the symptom: the agent never responds on the bridge while
221
+ * the same model works client-direct, where the browser negotiates the rate itself).
222
+ */
223
+ InputSampleRate?: number;
224
+ /**
225
+ * The PCM sample rate (Hz) this model **emits** on {@link IRealtimeSession.OnOutput} — its audio OUTPUT
226
+ * format. Optional; consumers default to 24000 (both OpenAI and Gemini Live emit 24 kHz today).
227
+ */
228
+ OutputSampleRate?: number;
229
+ /**
230
+ * Sends a client media frame to the model.
231
+ *
232
+ * Fire-and-forget: frames are streamed straight to the provider with no JSON intermediation. The
233
+ * optional `kind` tags the media plane — `'audio'` (default, back-compatible: existing callers and
234
+ * audio-only drivers need not pass or read it) or `'video'` for a camera frame to a video-capable
235
+ * model (one that {@link BaseRealtimeModel.SupportsVideo}). Audio-only drivers ignore `'video'`
236
+ * frames.
237
+ *
238
+ * @param chunk A raw media frame as an `ArrayBuffer`.
239
+ * @param kind The media plane the frame belongs to. Defaults to `'audio'`.
240
+ */
241
+ SendInput(chunk: ArrayBuffer, kind?: RealtimeMediaKind): void;
242
+ /**
243
+ * Registers the set of tools the model may call, translating them into the provider's
244
+ * native function-calling format.
245
+ *
246
+ * The Core-level {@link RealtimeToolDefinition} is intentionally minimal: `BaseRealtimeModel`
247
+ * lives in the lowest AI layer and cannot depend on the richer tool metadata defined in
248
+ * higher packages (the agent layer) — doing so would create an illegal upward/circular
249
+ * dependency. The agent layer is responsible for **mapping its richer tool metadata down**
250
+ * to this Core type before calling `RegisterTools`, and the concrete driver maps this Core
251
+ * type **up** to the provider's native function-calling schema.
252
+ *
253
+ * Note that some providers (e.g. Eleven Labs) bind to a pre-declared tool set on a
254
+ * server-side agent configuration; for those, the driver maps these definitions onto the
255
+ * pre-declared tool names rather than registering arbitrary schemas at session start.
256
+ *
257
+ * **Idempotency rule:** a post-start registration of a set IDENTICAL to the set supplied at
258
+ * connect time (via {@link RealtimeSessionParams.Tools}) MUST be a no-op. Providers that bind
259
+ * their tool set at connect time and cannot re-declare schemas on an open session MUST no-op
260
+ * (and may log) rather than degrade the conversation — e.g. by injecting schema text into the
261
+ * conversation as content. A genuinely DIFFERENT post-start set on such a provider is
262
+ * unsupported and should be surfaced as a warning, not silently mangled.
263
+ *
264
+ * @param tools The tools to expose to the model.
265
+ */
266
+ RegisterTools(tools: RealtimeToolDefinition[]): Promise<void>;
267
+ /**
268
+ * Registers a handler for model **audio** output frames (the audio media plane).
269
+ *
270
+ * @param handler Invoked with each output audio frame as an `ArrayBuffer`.
271
+ */
272
+ OnOutput(handler: (chunk: ArrayBuffer) => void): void;
273
+ /**
274
+ * Registers a handler for model **video** output frames — the talking-head avatar / generated
275
+ * video a video-capable model emits, in sync with {@link IRealtimeSession.OnOutput}'s audio.
276
+ *
277
+ * Optional: audio-only drivers (the default) don't implement it, and consumers must call it
278
+ * null-safely (`session.OnVideoOutput?.(...)`). A video-capable driver
279
+ * ({@link BaseRealtimeModel.SupportsVideo}) implements it; the consumer (bridge / client) maps these
280
+ * frames onto its `video-out` track exactly as it maps audio.
281
+ *
282
+ * @param handler Invoked with each output video frame as an `ArrayBuffer`.
283
+ */
284
+ OnVideoOutput?(handler: (chunk: ArrayBuffer) => void): void;
285
+ /**
286
+ * Registers a handler for transcript events (the text stream).
287
+ *
288
+ * Consumers typically forward these to the control plane and persist them as
289
+ * `ConversationDetail` records.
290
+ *
291
+ * @param handler Invoked with each {@link RealtimeTranscript} (partial or final).
292
+ */
293
+ OnTranscript(handler: (t: RealtimeTranscript) => void): void;
294
+ /**
295
+ * Registers a handler for model tool-call requests.
296
+ *
297
+ * Consumers execute the requested tool (under the session's context user) and feed the
298
+ * result back to the model.
299
+ *
300
+ * @param handler Invoked with each {@link RealtimeToolCall}.
301
+ */
302
+ OnToolCall(handler: (call: RealtimeToolCall) => void): void;
303
+ /**
304
+ * Send the result of an executed tool/function call back to the model so it can continue the
305
+ * turn. `output` is the JSON-stringified tool result. Called by the agent layer after it handles
306
+ * an {@link IRealtimeSession.OnToolCall}.
307
+ *
308
+ * @param callID The `CallID` from the originating {@link RealtimeToolCall}, used to correlate the result.
309
+ * @param output The tool's result as a JSON-stringified string.
310
+ * @returns A promise that resolves once the result has been sent to the provider.
311
+ */
312
+ SendToolResult(callID: string, output: string): Promise<void>;
313
+ /**
314
+ * **Optional capability** — injects background context (e.g. delegated-run progress, freshly
315
+ * retrieved data, or a state change the model should be aware of) into the model's
316
+ * conversation **without** forcing a spoken reply. The model simply has the note available
317
+ * the next time it speaks.
318
+ *
319
+ * This is the server-side counterpart of the client-direct `BaseRealtimeClient.SendContextNote`
320
+ * capability: in the server-bridged topology, the agent layer (e.g. a session runner observing
321
+ * a delegated agent run) calls this to keep the realtime model informed of long-running work
322
+ * so it can narrate naturally when asked or when it next takes the floor.
323
+ *
324
+ * Optionality models **capability**, not laziness: not every provider supports injecting
325
+ * conversation items into an already-open session (some only accept media frames and tool
326
+ * results mid-session). Drivers that cannot inject mid-session omit the member entirely, and
327
+ * callers must feature-detect (`if (session.SendContextNote) { ... }`) rather than assume it.
328
+ *
329
+ * @param text The context note to append to the conversation (plain text; the caller owns any
330
+ * prefixing/framing policy such as "[progress]" markers).
331
+ */
332
+ SendContextNote?(text: string): void;
333
+ /**
334
+ * **Optional capability** — asks the model to voice **one brief interim update** following the
335
+ * given instructions (e.g. "In one short sentence, tell the user the report agent has finished
336
+ * gathering data and is now drafting"). Used by the agent layer to narrate delegated-run
337
+ * progress while a long-running tool/agent call is still in flight.
338
+ *
339
+ * Implementations **must not collide with an in-flight model response**: providers reject or
340
+ * garble overlapping generation requests. A driver must either queue the request until the
341
+ * current response completes or skip it outright — skipping is explicitly acceptable because
342
+ * interim updates are disposable by contract (a stale "still working…" line has no value once
343
+ * the real result lands; the next update or the final result supersedes it).
344
+ *
345
+ * Like {@link IRealtimeSession.SendContextNote}, this is optional because it models provider
346
+ * capability: drivers whose provider cannot trigger an instructed, one-off spoken response
347
+ * mid-session omit the member, and callers must feature-detect before invoking.
348
+ *
349
+ * @param instructions Instructions for the single spoken update (tone, brevity, content).
350
+ */
351
+ RequestSpokenUpdate?(instructions: string): void;
352
+ /**
353
+ * Registers a handler for provider-detected interruptions (barge-in).
354
+ *
355
+ * **True barge-in only:** the handler fires ONLY when user speech interrupts ACTIVE model
356
+ * output — NOT on every user utterance. A user simply taking their normal turn while the
357
+ * model is idle is not an interruption, and drivers must not report it as one (e.g. a raw
358
+ * "speech started" frame must be gated on whether a model response is actually in flight).
359
+ *
360
+ * Turn detection / VAD is owned by the provider. The agent layer uses this hook to cancel
361
+ * the model's current turn **and** to fire the `cancellationToken` of any in-flight
362
+ * delegated agent run — a stale delegated result must never be narrated into a conversation
363
+ * that has moved on.
364
+ *
365
+ * @param handler Invoked when the provider reports a true barge-in interruption.
366
+ */
367
+ OnInterruption(handler: () => void): void;
368
+ /**
369
+ * Registers a handler for session errors.
370
+ *
371
+ * Fatality semantics mirror the client-side `BaseRealtimeClient` contract:
372
+ * - `Fatal: true` — the session is unusable (transport/socket failure, credential/token
373
+ * expiry, unexpected connection loss). The consumer should finalize the session (e.g.
374
+ * `RealtimeSessionRunner` calls `Stop()`) instead of idling forever on a dead socket.
375
+ * - `Fatal: false` — a provider-reported, recoverable error frame; the session stays open
376
+ * and the consumer should log and continue.
377
+ *
378
+ * @param handler Invoked with each {@link RealtimeSessionError}.
379
+ */
380
+ OnError(handler: (error: RealtimeSessionError) => void): void;
381
+ /**
382
+ * **Optional capability** — registers a handler invoked when the underlying provider
383
+ * connection closes WITHOUT the consumer having called {@link IRealtimeSession.Close}
384
+ * (provider-side hangup, network drop). Not fired for a consumer-initiated `Close()` —
385
+ * the caller already knows about that one.
386
+ *
387
+ * Optional because not every provider surface exposes a close signal cheaply; callers
388
+ * must feature-detect (`if (session.OnClose) { ... }`). An unexpected close is typically
389
+ * ALSO surfaced as a `Fatal` {@link IRealtimeSession.OnError}, which is the signal
390
+ * consumers should drive finalization from.
391
+ *
392
+ * @param handler Invoked when the provider connection closes unexpectedly.
393
+ */
394
+ OnClose?(handler: () => void): void;
395
+ /**
396
+ * Registers a handler for usage/telemetry updates.
397
+ *
398
+ * Usage is checkpointed incrementally by the agent layer (debounced onto the prompt run) so
399
+ * partial usage is never lost if the session is force-closed after a crash.
400
+ *
401
+ * @param handler Invoked with each {@link RealtimeUsage} update.
402
+ */
403
+ OnUsage(handler: (u: RealtimeUsage) => void): void;
404
+ /**
405
+ * Closes the session and releases the underlying provider connection.
406
+ *
407
+ * @returns A promise that resolves once the session is fully closed.
408
+ */
409
+ Close(): Promise<void>;
410
+ }
411
+ /**
412
+ * Parameters used to open a {@link IRealtimeSession} via {@link BaseRealtimeModel.StartSession}.
413
+ */
414
+ export interface RealtimeSessionParams {
415
+ /**
416
+ * The API name of the realtime model to use (the `MJ: AI Model Vendors` API name for the
417
+ * driver's provider).
418
+ */
419
+ Model: string;
420
+ /**
421
+ * The system prompt that establishes the model's persona and behavior for the session.
422
+ */
423
+ SystemPrompt: string;
424
+ /**
425
+ * Optional set of tools to register at session start. Equivalent to calling
426
+ * {@link IRealtimeSession.RegisterTools} immediately after the session opens; drivers may
427
+ * register these eagerly when the provider accepts tool schemas at session start.
428
+ */
429
+ Tools?: RealtimeToolDefinition[];
430
+ /**
431
+ * Optional initial context to seed the conversation (e.g. the prior conversation history
432
+ * and retrieved memory) so the model starts with the same context a loop agent assembles.
433
+ */
434
+ InitialContext?: string;
435
+ /**
436
+ * Optional open, provider-specific configuration bag (e.g. voice, language, turn-taking
437
+ * settings, or per-conversation override fields). Typed as a JSON object rather than `any`
438
+ * so it stays serializable and inspectable.
439
+ */
440
+ Config?: JSONObject;
441
+ }
442
+ /**
443
+ * A transcript event emitted by the model for either the user's speech or the assistant's
444
+ * response.
445
+ */
446
+ export interface RealtimeTranscript {
447
+ /**
448
+ * Whose turn this transcript belongs to.
449
+ */
450
+ Role: 'user' | 'assistant';
451
+ /**
452
+ * The transcribed text. For `IsFinal: false` events this is the incremental **DELTA** for
453
+ * the in-flight turn (drivers emit each new fragment, not a re-send of the accumulated
454
+ * text); for `IsFinal: true` it is the complete turn text.
455
+ */
456
+ Text: string;
457
+ /**
458
+ * Whether this is the final transcript for the turn (`true`) or an interim delta (`false`).
459
+ */
460
+ IsFinal: boolean;
461
+ }
462
+ /**
463
+ * An error surfaced by a realtime session via {@link IRealtimeSession.OnError}.
464
+ *
465
+ * Mirrors the client-side `RealtimeClientError` shape: `Fatal: true` means the session is
466
+ * unusable (transport failure, credential expiry, unexpected close) and the consumer should
467
+ * finalize; `Fatal: false` is a provider-reported, recoverable error frame.
468
+ */
469
+ export interface RealtimeSessionError {
470
+ /** Human-readable error message. */
471
+ Message: string;
472
+ /** Optional provider-specific error code. */
473
+ Code?: string;
474
+ /** Whether the error terminated the session. */
475
+ Fatal: boolean;
476
+ }
477
+ /**
478
+ * A tool-call request emitted by the model.
479
+ */
480
+ export interface RealtimeToolCall {
481
+ /**
482
+ * Provider-assigned identifier for this call, used to correlate the eventual tool result.
483
+ */
484
+ CallID: string;
485
+ /**
486
+ * The name of the tool the model is requesting to invoke.
487
+ */
488
+ ToolName: string;
489
+ /**
490
+ * The arguments for the call as a JSON string, exactly as the provider emitted them.
491
+ * Consumers parse this into the tool's expected parameter shape.
492
+ */
493
+ Arguments: string;
494
+ }
495
+ /**
496
+ * Incremental usage/telemetry reported during a realtime session.
497
+ *
498
+ * This is the realtime-specific counterpart to Core's request/response `ModelUsage`. Because a
499
+ * realtime session is long-lived and usage is reported in increments (and checkpointed
500
+ * incrementally), this type carries the token deltas a provider emits over the life of the
501
+ * session rather than a single final tally.
502
+ */
503
+ export interface RealtimeUsage {
504
+ /**
505
+ * Number of input tokens reported in this usage update.
506
+ */
507
+ InputTokens: number;
508
+ /**
509
+ * Number of output tokens reported in this usage update.
510
+ */
511
+ OutputTokens: number;
512
+ }
513
+ /**
514
+ * Minimal, Core-level definition of a tool exposed to a realtime model.
515
+ *
516
+ * This type lives in the lowest AI layer and is intentionally provider- and agent-agnostic.
517
+ * The agent layer maps its richer tool metadata **down** to this type before registering tools,
518
+ * and each concrete driver maps this type **up** to the provider's native function-calling
519
+ * schema. Keeping the Core type minimal avoids an illegal upward dependency from Core onto the
520
+ * agent packages.
521
+ */
522
+ export interface RealtimeToolDefinition {
523
+ /**
524
+ * The tool's name, used to match provider tool-call frames back to MJ tool execution.
525
+ */
526
+ Name: string;
527
+ /**
528
+ * A human-readable description of what the tool does. Surfaced to the model so it can decide
529
+ * when to call the tool.
530
+ */
531
+ Description: string;
532
+ /**
533
+ * A JSON-schema object describing the tool's parameters. Drivers translate this into the
534
+ * provider's native function-parameter schema.
535
+ */
536
+ ParametersSchema: JSONObject;
537
+ }
538
+ //# sourceMappingURL=baseRealtime.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"baseRealtime.d.ts","sourceRoot":"","sources":["../../src/generic/baseRealtime.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAExC;;;GAGG;AACH,MAAM,MAAM,SAAS,GACf,MAAM,GACN,MAAM,GACN,OAAO,GACP,IAAI,GACJ,SAAS,EAAE,GACX;IAAE,CAAC,GAAG,EAAE,MAAM,GAAG,SAAS,CAAA;CAAE,CAAC;AAEnC;;;GAGG;AACH,MAAM,MAAM,UAAU,GAAG;IAAE,CAAC,GAAG,EAAE,MAAM,GAAG,SAAS,CAAA;CAAE,CAAC;AAEtD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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