@memberjunction/ai-inworld 0.0.1 → 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,2 @@
1
+ export * from './inworldRealtime.js';
2
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,cAAc,mBAAmB,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,3 @@
1
+ // Inworld Realtime API — realtime (voice) driver. BaseRealtimeModel implementation.
2
+ export * from './inworldRealtime.js';
3
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,oFAAoF;AACpF,cAAc,mBAAmB,CAAC"}
@@ -0,0 +1,514 @@
1
+ import { BaseRealtimeModel, type IRealtimeSession, type RealtimeSessionParams, type RealtimeToolDefinition, type RealtimeTranscript, type RealtimeToolCall, type RealtimeUsage, type RealtimeSessionError, type JSONObject, type JSONValue } from '@memberjunction/ai';
2
+ /** The Inworld Realtime API WebSocket endpoint. Auth rides as a `?token=` query parameter. */
3
+ export declare const INWORLD_REALTIME_WS_URL = "wss://api.inworld.ai/v1/realtime";
4
+ /**
5
+ * Default underlying LLM Inworld brokers when {@link RealtimeSessionParams.Model} is empty. Inworld
6
+ * selects the reasoning model via `modelId` (e.g. `anthropic/claude-sonnet-4-6`); the STT engine and
7
+ * TTS voice are configured independently in the audio block.
8
+ */
9
+ export declare const INWORLD_DEFAULT_MODEL_ID = "anthropic/claude-sonnet-4-6";
10
+ /**
11
+ * Default semantic-VAD eagerness applied to turn-taking when the caller supplies none. Inworld's
12
+ * turn detection is semantic VAD with adjustable eagerness; `medium` balances responsiveness against
13
+ * premature turn-ends. Overridable via `Config.turn_detection.eagerness` (or the whole block).
14
+ */
15
+ export declare const INWORLD_DEFAULT_VAD_EAGERNESS = "medium";
16
+ /**
17
+ * A parsed inbound Inworld Realtime WebSocket frame.
18
+ *
19
+ * The Inworld protocol multiplexes server events on a `type` discriminator (mirroring the
20
+ * `session.update` request shape it accepts), so a single interface carries every inbound field the
21
+ * driver reads. Fields are optional because which ones are present depends on `type`.
22
+ *
23
+ * @remarks Wire-format binding point — the precise inbound `type` strings and field names are mapped
24
+ * to the documented protocol shape and centralized in {@link InworldRealtimeSession.classifyServerEvent};
25
+ * verify the exact discriminators against a live Inworld endpoint.
26
+ */
27
+ export interface InworldServerEvent {
28
+ /** The event discriminator (e.g. `session.updated`, `output_audio.delta`, `response.done`). */
29
+ type?: string;
30
+ /** Provider-assigned session id, surfaced on the session-ready frame. */
31
+ session_id?: string;
32
+ /** A base64-encoded chunk of synthesized output audio (Realtime TTS-2). */
33
+ audio?: string;
34
+ /** Transcribed text for a transcript frame (user STT or assistant TTS transcript). */
35
+ text?: string;
36
+ /** A correlation id for a tool call, echoed back on the tool result. */
37
+ call_id?: string;
38
+ /** The tool name on a tool-call frame. */
39
+ name?: string;
40
+ /**
41
+ * Tool-call arguments. Inworld may emit these either pre-parsed (object) or as a JSON string; the
42
+ * driver normalizes both to the Core contract's JSON-string `Arguments` shape.
43
+ */
44
+ arguments?: JSONValue;
45
+ /** Provider error code on an error frame. */
46
+ code?: string;
47
+ /** Human-readable message on an error frame. */
48
+ message?: string;
49
+ /** Whether the provider classified an error frame as fatal (transport/credential death). */
50
+ fatal?: boolean;
51
+ /** Incremental input-token count on a usage frame. */
52
+ input_tokens?: number;
53
+ /** Incremental output-token count on a usage frame. */
54
+ output_tokens?: number;
55
+ }
56
+ /** The minimal outbound surface of the realtime WebSocket the session depends on. */
57
+ export interface InworldRealtimeSocket {
58
+ /** Sends one JSON-serialized client frame. */
59
+ send(data: string): void;
60
+ /** Terminates the underlying connection. */
61
+ close(): void;
62
+ }
63
+ /**
64
+ * Arguments handed to {@link InworldRealtime.connectRealtimeSocket}: the authenticated URL plus the
65
+ * lifecycle callbacks. The seam owns the entire WebSocket dance so tests substitute it wholesale with
66
+ * an in-memory fake — no network, no real socket.
67
+ */
68
+ export interface InworldConnectArgs {
69
+ /** The full `wss://…?token=…` URL. */
70
+ Url: string;
71
+ /** Invoked with each parsed inbound frame. */
72
+ OnMessage: (event: InworldServerEvent) => void;
73
+ /** Invoked on a WebSocket-level error (fatal — the session is unusable). */
74
+ OnError: (message: string) => void;
75
+ /** Invoked when the WebSocket closes. */
76
+ OnClose: (code?: number, reason?: string) => void;
77
+ }
78
+ /**
79
+ * Real-time, full-duplex driver for the **Inworld Realtime API**, implementing the Core
80
+ * {@link BaseRealtimeModel} primitive. Registers as `InworldRealtime` and is resolved for
81
+ * `MJ: AI Models` typed `Realtime` (API-key env alias: `AI_VENDOR_API_KEY__InworldRealtime`).
82
+ *
83
+ * **What the provider is:** a single-WebSocket speech-to-speech stack. Sessions initialize with a
84
+ * `session.update` frame carrying model selection, instructions, audio settings, STT/TTS config, and
85
+ * tools; components are swappable mid-session without reconnect. Input is streamed audio (server-side
86
+ * STT with voice profiling); output is synthesized speech (Realtime TTS-2) supporting inline steering
87
+ * tags like `[laugh]`. Turn-taking is semantic VAD with adjustable eagerness, handling barge-in.
88
+ *
89
+ * **Model resolution:** Inworld brokers hundreds of LLMs; the reasoning model is selected via
90
+ * `modelId` (e.g. `anthropic/claude-sonnet-4-6`) carried from {@link RealtimeSessionParams.Model}
91
+ * (falling back to {@link INWORLD_DEFAULT_MODEL_ID}). STT engine and TTS voice are configured
92
+ * independently via `Config`.
93
+ *
94
+ * **Topology:** server-bridged only ({@link StartSession}) — the driver opens the WebSocket, sends the
95
+ * session config, and resolves only once the provider confirms the config is applied (driver
96
+ * obligation #7). Inworld does not expose a documented ephemeral-token mint for browser-direct
97
+ * sessions, so {@link SupportsClientDirect} stays `false` (inherited).
98
+ *
99
+ * **Tool calling:** "fluent tool calling" — functions declared at startup (or added mid-session via
100
+ * {@link IRealtimeSession.RegisterTools}) and executed mid-conversation; results fed back via
101
+ * {@link IRealtimeSession.SendToolResult} complete the loop.
102
+ */
103
+ export declare class InworldRealtime extends BaseRealtimeModel {
104
+ /**
105
+ * Opens a server-bridged session: connects the realtime WebSocket authenticated with the API
106
+ * key, sends the full session config as the FIRST frame (`session.update` — model, instructions,
107
+ * audio/STT/TTS, tools, semantic-VAD turn-taking), and resolves only once the provider's
108
+ * session-ready confirmation arrives (driver obligation #7 — "ready only after the config is
109
+ * applied"). Mic frames sent before that would be dropped by the provider, and `StartSession`
110
+ * not resolving until ready makes that unrepresentable for consumers.
111
+ *
112
+ * @param params Session configuration (model, system prompt, tools, initial context, config bag).
113
+ * @returns A promise resolving to the live {@link IRealtimeSession} handle, post-ready.
114
+ */
115
+ StartSession(params: RealtimeSessionParams): Promise<IRealtimeSession>;
116
+ /**
117
+ * Builds the authenticated WebSocket URL. Auth rides as a `?token=` query parameter (the
118
+ * server-side API key for the server-bridged topology).
119
+ *
120
+ * @returns The full `wss://…?token=…` connect URL.
121
+ * @remarks Wire-format binding point — confirm the auth query-parameter name (`token`) against a
122
+ * live Inworld endpoint; some deployments authenticate via an `Authorization` header instead.
123
+ */
124
+ protected buildConnectUrl(): string;
125
+ /**
126
+ * Transport seam for the realtime WebSocket. Production speaks the raw Inworld Realtime protocol
127
+ * over the platform-global `WebSocket` (browsers / Node 22+) and resolves once the socket is
128
+ * OPEN. Unit tests override this to return an in-memory fake — no network.
129
+ *
130
+ * @param args The authenticated URL plus inbound-message / error / close callbacks.
131
+ * @returns A promise resolving to the connected {@link InworldRealtimeSocket} once open.
132
+ */
133
+ protected connectRealtimeSocket(args: InworldConnectArgs): Promise<InworldRealtimeSocket>;
134
+ /**
135
+ * Maps a Core {@link RealtimeToolDefinition} up to an Inworld realtime `function` tool schema —
136
+ * the shape Inworld's "fluent tool calling" `tools[]` slot accepts. Shared by the initial
137
+ * `session.update` and by mid-session {@link IRealtimeSession.RegisterTools} so both expose
138
+ * byte-for-byte identical tool schemas.
139
+ *
140
+ * @param tool The Core tool definition to map.
141
+ * @returns The Inworld realtime function-tool object.
142
+ */
143
+ static MapToolToFunction(tool: RealtimeToolDefinition): JSONObject;
144
+ /**
145
+ * Canonical, order-insensitive fingerprint of a tool set (same scheme as the OpenAI / Gemini /
146
+ * AssemblyAI realtime drivers) — used by {@link InworldRealtimeSession.RegisterTools} to no-op
147
+ * identical re-registrations per the contract's idempotency rule.
148
+ *
149
+ * @param tools The tool set to fingerprint.
150
+ * @returns A stable string fingerprint independent of tool ordering.
151
+ */
152
+ static ToolSetFingerprint(tools: RealtimeToolDefinition[]): string;
153
+ }
154
+ /**
155
+ * Concrete {@link IRealtimeSession} backed by a raw Inworld Realtime WebSocket.
156
+ *
157
+ * Owns the inbound translation (Inworld wire events → Core events) and the outbound translation
158
+ * (Core calls → wire frames). Created by {@link InworldRealtime.StartSession}; never instantiated
159
+ * directly by consumers.
160
+ *
161
+ * Provider-behavior notes (the contract deltas a consumer should know):
162
+ * - **`session.update` is the universal config channel.** Model, instructions, audio/STT/TTS, tools,
163
+ * and turn-taking are all carried by `session.update` — at connect time AND mid-session. Components
164
+ * are swappable without reconnect, so {@link RegisterTools} and {@link SendContextNote} are native
165
+ * config writes (never interrupting generation).
166
+ * - **Semantic VAD owns turn detection / barge-in.** A raw "speech started" is NOT an interruption;
167
+ * the provider's true-barge-in signal (it tracks its own output emission) is surfaced only when it
168
+ * cuts off an ACTIVE response, gated on {@link responseActive} per the base contract.
169
+ * - **Output supports inline steering tags** (e.g. `[laugh]`) — passed through verbatim in
170
+ * instructions; the driver does not parse or strip them.
171
+ * - **Tool results must reach the model.** `SendToolResult` is sent immediately (the provider owns the
172
+ * spoken continuation) and marks a response active eagerly so a queued narration can't slip ahead.
173
+ * - **{@link RequestSpokenUpdate} queues behind an in-flight response** per the collision rule; a
174
+ * `tool.call` clears the busy flag WITHOUT draining the queue (deadlock guard, obligation #2).
175
+ */
176
+ export declare class InworldRealtimeSession implements IRealtimeSession {
177
+ private socket;
178
+ private outputHandler;
179
+ private transcriptHandler;
180
+ private toolCallHandler;
181
+ private interruptionHandler;
182
+ private usageHandler;
183
+ private errorHandler;
184
+ private closeHandler;
185
+ /** True once {@link Close} ran — an expected close must not surface as a fatal error. */
186
+ private closedByConsumer;
187
+ /** Resolves when the session-ready frame arrives; rejects on transport death. */
188
+ private readyPromise;
189
+ private resolveReady;
190
+ private rejectReady;
191
+ private readyReceived;
192
+ /** The session params the connect-time `session.update` is built from. */
193
+ private params;
194
+ /** The base system prompt (with InitialContext folded in) — context notes append to it. */
195
+ private basePrompt;
196
+ /** Accumulated {@link SendContextNote} texts, re-sent with the full prompt each time. */
197
+ private contextNotes;
198
+ /**
199
+ * Whether a model response is currently in flight. Set when output audio / a response-started
200
+ * frame arrives (and eagerly when this session triggers its own response); cleared on a
201
+ * response-done frame; a tool-call clears it WITHOUT draining (deadlock guard). Consumed by
202
+ * {@link enqueueOrRun} so a native {@link RequestSpokenUpdate} never collides with an active
203
+ * response, and by {@link handleSpeechStarted} to gate true-barge-in.
204
+ */
205
+ private responseActive;
206
+ /** Sends deferred while a response is in flight; drained in order at the next boundary. */
207
+ private queuedSends;
208
+ /**
209
+ * Fingerprint of the tool set currently declared on the session; {@link RegisterTools} compares
210
+ * against it to no-op identical re-registrations.
211
+ */
212
+ private currentToolsFingerprint;
213
+ /**
214
+ * @param params The session parameters (model, system prompt, tools, initial context, config bag).
215
+ */
216
+ constructor(params: RealtimeSessionParams);
217
+ /** Binds the underlying socket. Called by the driver once the WebSocket is open. */
218
+ AttachSocket(socket: InworldRealtimeSocket): void;
219
+ /**
220
+ * Sends the initial `session.update` frame carrying the full server-authored session config
221
+ * (model, instructions, audio/STT/TTS, tools, semantic-VAD turn-taking). Always the FIRST client
222
+ * frame — the provider drops audio sent before the session is configured.
223
+ */
224
+ SendSessionUpdate(): void;
225
+ /**
226
+ * Resolves once the provider's session-ready confirmation arrives (its acknowledgment that the
227
+ * session config is applied); rejects if the transport dies first. Awaited by
228
+ * {@link InworldRealtime.StartSession} so the session is never handed to a consumer before it is
229
+ * actually configured (driver obligation #7).
230
+ *
231
+ * @returns A promise resolving on session-ready and rejecting on pre-ready transport death.
232
+ */
233
+ WaitForReady(): Promise<void>;
234
+ /** @inheritdoc — streams one client media frame as a base64 input audio-append frame. */
235
+ SendInput(chunk: ArrayBuffer): void;
236
+ /**
237
+ * @inheritdoc
238
+ *
239
+ * Inworld's `tools` are a MUTABLE `session.update` field (components are swappable mid-session
240
+ * without reconnect), so re-declaration is native: an identical set (order-insensitively) is a
241
+ * silent no-op per the contract's idempotency rule; a genuinely different set is applied to the
242
+ * live session immediately.
243
+ *
244
+ * @param tools The tools to expose to the model.
245
+ */
246
+ RegisterTools(tools: RealtimeToolDefinition[]): Promise<void>;
247
+ /** @inheritdoc */
248
+ OnOutput(handler: (chunk: ArrayBuffer) => void): void;
249
+ /** @inheritdoc */
250
+ OnTranscript(handler: (t: RealtimeTranscript) => void): void;
251
+ /** @inheritdoc */
252
+ OnToolCall(handler: (call: RealtimeToolCall) => void): void;
253
+ /** @inheritdoc */
254
+ OnInterruption(handler: () => void): void;
255
+ /** @inheritdoc */
256
+ OnUsage(handler: (u: RealtimeUsage) => void): void;
257
+ /** @inheritdoc */
258
+ OnError(handler: (error: RealtimeSessionError) => void): void;
259
+ /** @inheritdoc */
260
+ OnClose(handler: () => void): void;
261
+ /**
262
+ * @inheritdoc
263
+ *
264
+ * Completes the tool-call loop: sends a tool-result frame correlated by `call_id`. Sent
265
+ * IMMEDIATELY (never queued) — the provider asked for it and owns the spoken continuation. The
266
+ * busy flag is set eagerly so a queued narration can't slip in before the spoken result (driver
267
+ * obligation #5 — the result must EVENTUALLY be voiced and never be dropped).
268
+ *
269
+ * @param callID The `CallID` from the originating {@link RealtimeToolCall}.
270
+ * @param output The tool's result as a JSON-stringified string.
271
+ */
272
+ SendToolResult(callID: string, output: string): Promise<void>;
273
+ /**
274
+ * @inheritdoc
275
+ *
276
+ * EMULATED via the mutable system prompt: Inworld has no purpose-built non-interrupting context
277
+ * channel, but `session.update` may rewrite instructions mid-session WITHOUT triggering
278
+ * generation. The note is appended under a "Background updates" heading and the full prompt is
279
+ * re-sent — a config write, so it never interrupts and is sent immediately even mid-response. The
280
+ * model sees the notes the next time it speaks.
281
+ *
282
+ * @param text The context note to append to the conversation.
283
+ */
284
+ SendContextNote(text: string): void;
285
+ /**
286
+ * @inheritdoc
287
+ *
288
+ * Triggers ONE short spoken update via a response-create frame carrying per-response
289
+ * instructions. **Collision behavior: queue.** A response-create sent mid-response would collide
290
+ * with the in-flight generation (the provider rejects overlapping triggers), so the send is
291
+ * deferred until the active response completes and drained at the next boundary.
292
+ *
293
+ * @param instructions Instructions for the single spoken update.
294
+ */
295
+ RequestSpokenUpdate(instructions: string): void;
296
+ /**
297
+ * @inheritdoc
298
+ *
299
+ * Closes the session: sends a session-close frame BEFORE closing the socket so the provider
300
+ * tears the session down promptly rather than holding it, then releases the socket and drops all
301
+ * handlers so no stale callback fires afterward.
302
+ */
303
+ Close(): Promise<void>;
304
+ /**
305
+ * Entry point for an inbound WebSocket frame. Classifies the raw frame to a semantic kind via
306
+ * {@link classifyServerEvent}, then routes to a focused per-concern handler so each translation
307
+ * unit stays small and testable.
308
+ *
309
+ * @param event The parsed Inworld server event.
310
+ */
311
+ HandleServerEvent(event: InworldServerEvent): void;
312
+ /** Resolves the ready wait so {@link InworldRealtime.StartSession} can hand back the session. */
313
+ private handleReady;
314
+ /** Decodes one base64 output-audio frame, marks a response active, and forwards the raw bytes. */
315
+ private handleOutputAudio;
316
+ /**
317
+ * Surfaces a `tool.call` to the consumer. The model has yielded the floor pending the result, so
318
+ * the busy flag is cleared (deadlock guard — driver obligation #2) WITHOUT draining the queue (a
319
+ * queued narration must not trigger a response between the tool call and its result; it drains at
320
+ * the next real response boundary). Inworld may emit `arguments` pre-parsed or as a JSON string;
321
+ * {@link normalizeToolArguments} normalizes both to the Core contract's JSON-string shape.
322
+ *
323
+ * @param event The inbound tool-call frame.
324
+ */
325
+ private handleToolCall;
326
+ /**
327
+ * A raw "speech started" frame. Per the base contract this is NOT itself an interruption — a user
328
+ * taking their normal turn while the model is idle must not be reported. It is surfaced as a
329
+ * true barge-in only when a model response is actually in flight (semantic VAD owns turn
330
+ * detection; {@link responseActive} is the server-bridged proxy for "model output in flight").
331
+ */
332
+ private handleSpeechStarted;
333
+ /**
334
+ * Surfaces a TRUE barge-in: user speech that cut off active model output. Fires the interruption
335
+ * handler, then releases the floor and drains queued sends. (Reached either from an explicit
336
+ * provider interruption frame or from a `responseActive`-gated speech-started.)
337
+ */
338
+ private handleInterruption;
339
+ /** Translates an incremental usage frame into a {@link RealtimeUsage} update. */
340
+ private handleUsage;
341
+ /**
342
+ * Classifies a provider error frame's fatality and forwards it. The provider's own `fatal` flag
343
+ * (when present) is authoritative — a fatal frame means credential/transport death (driver
344
+ * obligation #6) and the consumer should finalize; otherwise it is a recoverable error frame and
345
+ * the session stays open (`Fatal: false`).
346
+ *
347
+ * @param event The inbound error frame.
348
+ */
349
+ private handleProviderError;
350
+ /**
351
+ * Surfaces a WebSocket-level failure as a FATAL session error — the transport is gone, so the
352
+ * consumer should finalize cleanly instead of idling on a dead socket (driver obligation #6).
353
+ *
354
+ * @param message The transport error message.
355
+ */
356
+ HandleTransportError(message: string): void;
357
+ /**
358
+ * Surfaces an UNEXPECTED socket close as a fatal error (expected closes — the consumer called
359
+ * {@link Close} — are silent). The provider hard-closes at token expiry and when it ends the
360
+ * session itself, so this is also how credential / session death reaches the consumer. The close
361
+ * handler fires after the error so consumers driving finalization from either signal converge.
362
+ *
363
+ * @param code Optional WebSocket close code.
364
+ * @param reason Optional WebSocket close reason.
365
+ */
366
+ HandleTransportClose(code?: number, reason?: string): void;
367
+ /**
368
+ * Builds the initial `session.update` frame: model selection, instructions, audio settings, STT
369
+ * engine, TTS voice, tools, and semantic-VAD turn-taking with adjustable eagerness. Recognized
370
+ * `Config` keys pass through to their wire slots; the whole `Config` bag also spreads onto the
371
+ * session so a per-conversation override can replace any block.
372
+ *
373
+ * @param tools The tools to declare at connect time.
374
+ * @returns The `session.update` client frame.
375
+ * @remarks Wire-format binding point — the `session.update` envelope and the exact key names for
376
+ * `model` / `instructions` / `audio` / `voice` / `stt` / `turn_detection.eagerness` are mapped to
377
+ * Inworld's documented protocol shape; verify each key against a live Inworld endpoint.
378
+ */
379
+ private buildSessionUpdateFrame;
380
+ /**
381
+ * Builds the audio block (input STT + output TTS voice). Recognized shorthand `Config` keys:
382
+ * `voice` → `output.voice`, `stt` → `input.model`, `language` → `input.language`.
383
+ *
384
+ * @param config The caller's config bag.
385
+ * @returns The wire `audio` config object.
386
+ * @remarks Wire-format binding point — the `audio.{input,output}` sub-shape is mapped to the
387
+ * documented STT-in / TTS-2-out description; verify exact key names against a live endpoint.
388
+ */
389
+ private buildAudioConfig;
390
+ /**
391
+ * Builds the semantic-VAD turn-detection block. If the caller supplies a full `turn_detection`
392
+ * object it is used verbatim; otherwise an `eagerness` shorthand (or the default) is applied.
393
+ *
394
+ * @param config The caller's config bag.
395
+ * @returns The wire `turn_detection` object.
396
+ * @remarks Wire-format binding point — `turn_detection.type = 'semantic_vad'` and the `eagerness`
397
+ * field are mapped to the documented "semantic VAD with adjustable eagerness"; verify exact key
398
+ * names / allowed values against a live endpoint.
399
+ */
400
+ private buildTurnDetection;
401
+ /**
402
+ * Spreads caller-supplied raw `Config` overrides onto the session object, skipping the shorthand
403
+ * keys already consumed by {@link buildAudioConfig} / {@link buildTurnDetection} so they don't
404
+ * double-write. Lets a per-conversation config replace a whole block (e.g. a fully-specified
405
+ * `audio` object) while shorthands stay convenient.
406
+ *
407
+ * @param session The session object being built (mutated in place).
408
+ * @param config The caller's config bag.
409
+ */
410
+ private applyRawConfigOverrides;
411
+ /**
412
+ * Builds an input audio-append frame from a raw media chunk (base64-encoded over the single WS,
413
+ * full-duplex).
414
+ *
415
+ * @param chunk The raw media frame.
416
+ * @returns The audio-append client frame.
417
+ * @remarks Wire-format binding point — the `input_audio.append` type and the `audio` base64 key
418
+ * are mapped to the documented full-duplex streamed-audio input; verify against a live endpoint.
419
+ */
420
+ private buildAudioAppendFrame;
421
+ /**
422
+ * Builds a mid-session `session.update` frame that re-declares only the tools (components are
423
+ * swappable without reconnect).
424
+ *
425
+ * @param tools The new tool set to declare.
426
+ * @returns The tools-only `session.update` client frame.
427
+ * @remarks Wire-format binding point — re-declaring tools via a partial `session.update` follows
428
+ * the documented "components swappable mid-session" model; verify the partial-update semantics
429
+ * against a live endpoint.
430
+ */
431
+ private buildToolsUpdateFrame;
432
+ /**
433
+ * Builds a tool-result frame correlated by `call_id`. The Core contract's `output` is already a
434
+ * JSON string, which is passed through verbatim in the `result` slot.
435
+ *
436
+ * @param callID The originating call id.
437
+ * @param output The tool result as a JSON string.
438
+ * @returns The tool-result client frame.
439
+ * @remarks Wire-format binding point — the `tool.result` type and the `call_id` / `result` keys
440
+ * are mapped to the documented fluent-tool-calling result flow; verify against a live endpoint.
441
+ */
442
+ private buildToolResultFrame;
443
+ /**
444
+ * Builds a response-create frame carrying one-off per-response instructions (the instructed
445
+ * spoken update). Output supports inline steering tags like `[laugh]`, which pass through in the
446
+ * instructions verbatim.
447
+ *
448
+ * @param instructions Instructions for the single spoken response.
449
+ * @returns The response-create client frame.
450
+ * @remarks Wire-format binding point — the `response.create` type and the `instructions` key are
451
+ * mapped to the documented instructed-response capability; verify against a live endpoint.
452
+ */
453
+ private buildResponseCreateFrame;
454
+ /**
455
+ * Builds the non-interrupting context-item frame. Emulated via the mutable instructions: the full
456
+ * prompt (base + accumulated notes) is re-sent via `session.update`, which never triggers
457
+ * generation.
458
+ *
459
+ * @param fullPrompt The full instructions (base prompt + background-update notes).
460
+ * @returns The context-item client frame (a `session.update` that rewrites instructions).
461
+ * @remarks Wire-format binding point — using a partial `session.update` of `instructions` as the
462
+ * non-interrupting context channel follows the documented "components swappable mid-session"
463
+ * model; verify against a live endpoint.
464
+ */
465
+ private buildContextItemFrame;
466
+ /**
467
+ * Builds the session-close frame sent before the socket is torn down.
468
+ *
469
+ * @returns The session-close client frame.
470
+ * @remarks Wire-format binding point — the `session.close` type is mapped to a graceful teardown;
471
+ * verify against a live endpoint (some deployments rely on the socket close alone).
472
+ */
473
+ private buildSessionCloseFrame;
474
+ /**
475
+ * Classifies a raw inbound frame to a semantic kind the dispatcher routes on. Centralizing the
476
+ * `type`-string mapping here keeps {@link HandleServerEvent} stable even if the precise wire
477
+ * discriminators differ from the assumed shape.
478
+ *
479
+ * @param event The parsed inbound frame.
480
+ * @returns The semantic kind for {@link HandleServerEvent}.
481
+ * @remarks Wire-format binding point — the inbound `type` strings (e.g. `session.updated`,
482
+ * `output_audio.delta`, `input_audio_transcription.delta`, `response.done`, `tool.call`,
483
+ * `input_audio.speech_started`, `interrupted`, `usage`, `error`) are mapped to the documented
484
+ * protocol shape; verify the exact discriminators against a live Inworld endpoint.
485
+ */
486
+ private classifyServerEvent;
487
+ /** Resolves the underlying LLM id Inworld brokers (param model, falling back to the default). */
488
+ private resolveModelId;
489
+ /** Emits a transcript event (drops empty/whitespace-only text so no blank turns are persisted). */
490
+ private emitTranscript;
491
+ /** Response boundary: releases the busy flag and drains queued sends in order. */
492
+ private completeResponse;
493
+ /** Runs a send immediately when idle; otherwise queues it for the next response boundary. */
494
+ private enqueueOrRun;
495
+ /** The base prompt plus every accumulated context note under a "Background updates" heading. */
496
+ private composePromptWithNotes;
497
+ /** JSON-serializes and sends one client frame (throws if the socket was never attached). */
498
+ private sendFrame;
499
+ /** Rejects a still-pending ready wait (transport death / consumer close during startup). */
500
+ private failReadyWait;
501
+ /** Drops all registered handlers + queued sends so a closed session can't fire stale callbacks. */
502
+ private clearHandlers;
503
+ /** Folds optional prior context into the system prompt (Inworld has no separate history channel). */
504
+ private static composeSystemPrompt;
505
+ /**
506
+ * Normalizes tool-call arguments to the Core contract's JSON-string shape. Inworld may emit them
507
+ * pre-parsed (object) or already as a JSON string; both are coerced to a JSON string so consumers
508
+ * always parse the same shape.
509
+ */
510
+ private static normalizeToolArguments;
511
+ /** Decodes a base64 audio payload into a freshly-allocated `ArrayBuffer`. */
512
+ private static base64ToArrayBuffer;
513
+ }
514
+ //# sourceMappingURL=inworldRealtime.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"inworldRealtime.d.ts","sourceRoot":"","sources":["../src/inworldRealtime.ts"],"names":[],"mappings":"AAuBA,OAAO,EACH,iBAAiB,EACjB,KAAK,gBAAgB,EACrB,KAAK,qBAAqB,EAC1B,KAAK,sBAAsB,EAC3B,KAAK,kBAAkB,EACvB,KAAK,gBAAgB,EACrB,KAAK,aAAa,EAClB,KAAK,oBAAoB,EACzB,KAAK,UAAU,EACf,KAAK,SAAS,EACjB,MAAM,oBAAoB,CAAC;AAG5B,8FAA8F;AAC9F,eAAO,MAAM,uBAAuB,qCAAqC,CAAC;AAE1E;;;;GAIG;AACH,eAAO,MAAM,wBAAwB,gCAAgC,CAAC;AAEtE;;;;GAIG;AACH,eAAO,MAAM,6BAA6B,WAAW,CAAC;AAEtD;;;;;;;;;;GAUG;AACH,MAAM,WAAW,kBAAkB;IAC/B,+FAA+F;IAC/F,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,yEAAyE;IACzE,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,2EAA2E;IAC3E,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,sFAAsF;IACtF,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,wEAAwE;IACxE,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,0CAA0C;IAC1C,IAAI,CAAC,EAAE,MAAM,CAAC;IACd;;;OAGG;IACH,SAAS,CAAC,EAAE,SAAS,CAAC;IACtB,6CAA6C;IAC7C,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,gDAAgD;IAChD,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,4FAA4F;IAC5F,KAAK,CAAC,EAAE,OAAO,CAAC;IAChB,sDAAsD;IACtD,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,uDAAuD;IACvD,aAAa,CAAC,E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