@escapeaihq/client-core 0.8.0 → 0.12.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.
- package/README.md +22 -3
- package/dist/api.d.ts +114 -0
- package/dist/api.d.ts.map +1 -1
- package/dist/api.js +62 -47
- package/dist/api.js.map +1 -1
- package/dist/graphSchema.d.ts +72 -0
- package/dist/graphSchema.d.ts.map +1 -0
- package/dist/graphSchema.js +105 -0
- package/dist/graphSchema.js.map +1 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -0
- package/dist/index.js.map +1 -1
- package/dist/reactor/abortUtils.d.ts +16 -0
- package/dist/reactor/abortUtils.d.ts.map +1 -0
- package/dist/reactor/abortUtils.js +26 -0
- package/dist/reactor/abortUtils.js.map +1 -0
- package/dist/reactor/applyScenePrompt.d.ts +75 -0
- package/dist/reactor/applyScenePrompt.d.ts.map +1 -0
- package/dist/reactor/applyScenePrompt.js +60 -0
- package/dist/reactor/applyScenePrompt.js.map +1 -0
- package/dist/reactor/heliosCommandDispatcher.d.ts.map +1 -1
- package/dist/reactor/heliosCommandDispatcher.js +10 -15
- package/dist/reactor/heliosCommandDispatcher.js.map +1 -1
- package/dist/reactor/index.d.ts +2 -0
- package/dist/reactor/index.d.ts.map +1 -1
- package/dist/reactor/index.js +2 -0
- package/dist/reactor/index.js.map +1 -1
- package/dist/reactor/sceneEntry.d.ts +40 -6
- package/dist/reactor/sceneEntry.d.ts.map +1 -1
- package/dist/reactor/sceneEntry.js +63 -24
- package/dist/reactor/sceneEntry.js.map +1 -1
- package/dist/reactor/seedImageOrchestrator.d.ts +45 -2
- package/dist/reactor/seedImageOrchestrator.d.ts.map +1 -1
- package/dist/reactor/seedImageOrchestrator.js +174 -4
- package/dist/reactor/seedImageOrchestrator.js.map +1 -1
- package/dist/timeFormat.d.ts +10 -0
- package/dist/timeFormat.d.ts.map +1 -1
- package/dist/timeFormat.js +12 -0
- package/dist/timeFormat.js.map +1 -1
- package/dist/toolSchemas.d.ts +370 -0
- package/dist/toolSchemas.d.ts.map +1 -0
- package/dist/toolSchemas.js +182 -0
- package/dist/toolSchemas.js.map +1 -0
- package/dist/vision/VisionPublisher.d.ts +115 -0
- package/dist/vision/VisionPublisher.d.ts.map +1 -0
- package/dist/vision/VisionPublisher.js +475 -0
- package/dist/vision/VisionPublisher.js.map +1 -0
- package/dist/vision/credentials.d.ts +22 -0
- package/dist/vision/credentials.d.ts.map +1 -0
- package/dist/vision/credentials.js +34 -0
- package/dist/vision/credentials.js.map +1 -0
- package/dist/vision/index.d.ts +14 -0
- package/dist/vision/index.d.ts.map +1 -0
- package/dist/vision/index.js +11 -0
- package/dist/vision/index.js.map +1 -0
- package/dist/vision/startVisionPublisher.d.ts +38 -0
- package/dist/vision/startVisionPublisher.d.ts.map +1 -0
- package/dist/vision/startVisionPublisher.js +44 -0
- package/dist/vision/startVisionPublisher.js.map +1 -0
- package/dist/vision/types.d.ts +95 -0
- package/dist/vision/types.d.ts.map +1 -0
- package/dist/vision/types.js +12 -0
- package/dist/vision/types.js.map +1 -0
- package/dist/vision/visionScheduler.d.ts +63 -0
- package/dist/vision/visionScheduler.d.ts.map +1 -0
- package/dist/vision/visionScheduler.js +67 -0
- package/dist/vision/visionScheduler.js.map +1 -0
- package/dist/websocket.d.ts +122 -0
- package/dist/websocket.d.ts.map +1 -1
- package/dist/websocket.js +179 -1
- package/dist/websocket.js.map +1 -1
- package/package.json +11 -1
- package/src/__tests__/api-pollers.test.ts +100 -0
- package/src/__tests__/chat-auth.test.ts +91 -0
- package/src/__tests__/graphSchema.test.ts +117 -0
- package/src/__tests__/reactor/applyScenePrompt.test.ts +192 -0
- package/src/__tests__/reactor/heliosCommandDispatcher.test.ts +4 -3
- package/src/__tests__/reactor/sceneEntry.test.ts +134 -10
- package/src/__tests__/reactor/seedImageOrchestrator.test.ts +51 -16
- package/src/__tests__/timeFormat.test.ts +22 -1
- package/src/__tests__/toolSchemas.test.ts +57 -0
- package/src/__tests__/websocket-vision.test.ts +265 -0
- package/src/api.ts +160 -47
- package/src/graphSchema.ts +149 -0
- package/src/index.ts +3 -0
- package/src/reactor/abortUtils.ts +22 -0
- package/src/reactor/applyScenePrompt.ts +136 -0
- package/src/reactor/heliosCommandDispatcher.ts +10 -18
- package/src/reactor/index.ts +2 -0
- package/src/reactor/sceneEntry.ts +104 -33
- package/src/reactor/seedImageOrchestrator.ts +201 -4
- package/src/timeFormat.ts +13 -0
- package/src/toolSchemas.ts +225 -0
- package/src/vision/VisionPublisher.ts +553 -0
- package/src/vision/__tests__/VisionPublisher.kvs.test.ts +244 -0
- package/src/vision/__tests__/VisionPublisher.test.ts +301 -0
- package/src/vision/__tests__/startVisionPublisher.test.ts +251 -0
- package/src/vision/__tests__/toVisionRtcCredentials.test.ts +113 -0
- package/src/vision/__tests__/visionScheduler.test.ts +149 -0
- package/src/vision/credentials.ts +39 -0
- package/src/vision/index.ts +31 -0
- package/src/vision/startVisionPublisher.ts +64 -0
- package/src/vision/types.ts +101 -0
- package/src/vision/visionScheduler.ts +102 -0
- package/src/websocket.ts +259 -1
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Public types for the framework-agnostic vision publisher.
|
|
3
|
+
*
|
|
4
|
+
* Wire-shape source of truth: `shared/vision_protocol.py` (Python Pydantic
|
|
5
|
+
* models) — TS interfaces here MUST stay in lockstep with the snake_case
|
|
6
|
+
* field names on the wire. Internally we use camelCase; serialization to
|
|
7
|
+
* snake_case happens at the WebSocket boundary in `websocket.ts`.
|
|
8
|
+
*
|
|
9
|
+
* Spec: `specs/2026-05-22-phase-2-multimodal-watch.md`.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import type { ChatWebSocket } from '../websocket';
|
|
13
|
+
|
|
14
|
+
export interface VisionPublisherConfig {
|
|
15
|
+
/** Encoded-frame cadence, in frames per second. Clamped server-side to
|
|
16
|
+
* the persona's allowed range (0.5–3.0 fps). Defaults to 1.0 fps. */
|
|
17
|
+
fps?: number;
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* ICE servers (STUN / TURN) for the underlying `RTCPeerConnection`.
|
|
21
|
+
*
|
|
22
|
+
* **Default:** `[{ urls: 'stun:stun.l.google.com:19302' }]` — see
|
|
23
|
+
* `VisionPublisher.DEFAULT_ICE_SERVERS`. The browser uses this to gather
|
|
24
|
+
* server-reflexive (`srflx`) candidates, which local-dev needs because
|
|
25
|
+
* aiortc binds to all interfaces and may not advertise a candidate the
|
|
26
|
+
* browser can route to directly.
|
|
27
|
+
*
|
|
28
|
+
* **Pass `iceServers: []` to skip STUN entirely** — appropriate when
|
|
29
|
+
* the caller passes a `VisionRtcCredentials` whose `iceServers` already
|
|
30
|
+
* carries KVS-managed STUN + TURN URIs (kvs mode). In that case the
|
|
31
|
+
* publisher uses `credentials.iceServers` and this default is dead
|
|
32
|
+
* code; passing `[]` here just makes that explicit.
|
|
33
|
+
*/
|
|
34
|
+
iceServers?: RTCIceServer[];
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Backend → client telemetry shape that drives the vision HUD. Camel-case
|
|
39
|
+
* here; the wire payload uses snake_case (`buffered_frames`,
|
|
40
|
+
* `processing_paused`) and is converted at the `ChatWebSocket` boundary
|
|
41
|
+
* before reaching the listener.
|
|
42
|
+
*
|
|
43
|
+
* `lastInferenceMs` is not part of the protocol — the receiver has no
|
|
44
|
+
* way to know when the dispatcher finishes a vision-augmented inference,
|
|
45
|
+
* so the field would always be 0. Re-introducing it requires a callback
|
|
46
|
+
* from the dispatcher; tracked in `specs/technical-debt.md` (Issue #153).
|
|
47
|
+
*/
|
|
48
|
+
export interface VisionStatus {
|
|
49
|
+
bufferedFrames: number;
|
|
50
|
+
processingPaused: boolean;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export type VisionStatusListener = (status: VisionStatus) => void;
|
|
54
|
+
export type VisionErrorListener = (error: Error) => void;
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Mode + connection-establishment bundle returned by the chat-API's
|
|
58
|
+
* `POST /api/v1/chat/vision-rtc/credentials` endpoint. The frontend
|
|
59
|
+
* passes this to the publisher unchanged.
|
|
60
|
+
*
|
|
61
|
+
* In `local` mode the publisher uses the existing chat-WS
|
|
62
|
+
* `vision_offer` / `vision_ice` / `vision_close` protocol — no AWS
|
|
63
|
+
* dependency, used by `.env.local`.
|
|
64
|
+
*
|
|
65
|
+
* In `kvs` mode the publisher dynamically imports the Amazon KVS
|
|
66
|
+
* WebRTC SDK and opens the signed wss:// URL directly. The
|
|
67
|
+
* `iceServers` field carries KVS-managed STUN + short-term TURN
|
|
68
|
+
* credentials; never includes raw AWS IAM creds.
|
|
69
|
+
*/
|
|
70
|
+
export interface VisionRtcCredentials {
|
|
71
|
+
mode: 'local' | 'kvs';
|
|
72
|
+
iceServers: RTCIceServer[];
|
|
73
|
+
/** kvs mode only — SigV4-presigned wss:// URL for VIEWER. */
|
|
74
|
+
signedSignalingUrl?: string | null;
|
|
75
|
+
/** kvs mode only — KVS signaling channel ARN. Informational. */
|
|
76
|
+
channelArn?: string | null;
|
|
77
|
+
/** kvs mode only — unique VIEWER ClientId KVS uses to scope the session. */
|
|
78
|
+
clientId?: string | null;
|
|
79
|
+
/** kvs mode only — AWS region for the signaling channel. The KVS
|
|
80
|
+
* WebRTC JS SDK uses this when SigV4-signing follow-up ICE
|
|
81
|
+
* candidate messages. */
|
|
82
|
+
region?: string | null;
|
|
83
|
+
/** Seconds until the credentials expire. Browser should re-fetch
|
|
84
|
+
* before this elapses if a session outlives the TTL. */
|
|
85
|
+
expiresIn: number;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export interface VisionPublisherOptions {
|
|
89
|
+
ws: ChatWebSocket;
|
|
90
|
+
/** A single video track, or a `MediaStream` whose first video track is
|
|
91
|
+
* picked. */
|
|
92
|
+
track: MediaStreamTrack | MediaStream;
|
|
93
|
+
config?: VisionPublisherConfig;
|
|
94
|
+
/**
|
|
95
|
+
* Credentials from `/api/v1/chat/vision-rtc/credentials`. When omitted,
|
|
96
|
+
* the publisher falls back to local-mode signaling (chat-WS protocol)
|
|
97
|
+
* with the configured STUN servers — the legacy path that predates
|
|
98
|
+
* KVS support. New code should always pass this.
|
|
99
|
+
*/
|
|
100
|
+
credentials?: VisionRtcCredentials;
|
|
101
|
+
}
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pure scheduling helper for the vision publisher.
|
|
3
|
+
*
|
|
4
|
+
* Inputs: the current target fps + the most recent `vision_status` event
|
|
5
|
+
* from the backend. Output: the fps the publisher should now encode at.
|
|
6
|
+
*
|
|
7
|
+
* The heuristic is deliberately tiny — no timers, no sockets, no state
|
|
8
|
+
* beyond the last-known fps. The publisher (or its React/Vue hook) is
|
|
9
|
+
* responsible for actually applying the new fps to its RTCRtpSender
|
|
10
|
+
* encodings (`sender.setParameters({ ...p, encodings: [{ maxFramerate }]
|
|
11
|
+
* })`) or, for the v1 stub backend, just remembering it for the next
|
|
12
|
+
* offer.
|
|
13
|
+
*
|
|
14
|
+
* Backpressure principle (mirrors `~/projects/live-vlm-webui`):
|
|
15
|
+
* - When the backend reports `processingPaused` (inference is behind),
|
|
16
|
+
* halve fps so we stop queuing stale frames.
|
|
17
|
+
* - When the buffer is empty (consumer is keeping up perfectly), gently
|
|
18
|
+
* bump fps so we use the available headroom.
|
|
19
|
+
* - Otherwise leave fps alone.
|
|
20
|
+
*
|
|
21
|
+
* Earlier drafts also gated the bump-up branch on
|
|
22
|
+
* `status.lastInferenceMs <= FAST_INFERENCE_MS`; that field is absent
|
|
23
|
+
* from `VisionStatus` because the receiver has no way to populate it
|
|
24
|
+
* (see Issue #153). Using only `bufferedFrames === 0` as the bump signal
|
|
25
|
+
* is a reasonable proxy for "consumer is keeping up": if the buffer
|
|
26
|
+
* drained while not paused, inference completed before the next frame
|
|
27
|
+
* arrived, which is exactly the headroom we want to use.
|
|
28
|
+
*
|
|
29
|
+
* Spec: `specs/2026-05-22-phase-2-multimodal-watch.md`.
|
|
30
|
+
*/
|
|
31
|
+
|
|
32
|
+
import type { VisionStatus, VisionStatusListener } from './types';
|
|
33
|
+
|
|
34
|
+
export interface ComputeNextFpsInput {
|
|
35
|
+
currentFps: number;
|
|
36
|
+
status: VisionStatus;
|
|
37
|
+
minFps: number;
|
|
38
|
+
maxFps: number;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
const UP_NUDGE = 0.25;
|
|
42
|
+
|
|
43
|
+
const clamp = (value: number, min: number, max: number): number =>
|
|
44
|
+
Math.min(max, Math.max(min, value));
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Pure decision function — no side effects, no state. Returns the next
|
|
48
|
+
* target fps given the current fps and the most recent status report.
|
|
49
|
+
*/
|
|
50
|
+
export const computeNextFps = (input: ComputeNextFpsInput): number => {
|
|
51
|
+
const { currentFps, status, minFps, maxFps } = input;
|
|
52
|
+
const safeCurrent = clamp(currentFps, minFps, maxFps);
|
|
53
|
+
|
|
54
|
+
if (status.processingPaused) {
|
|
55
|
+
return clamp(safeCurrent / 2, minFps, maxFps);
|
|
56
|
+
}
|
|
57
|
+
if (status.bufferedFrames === 0) {
|
|
58
|
+
return clamp(safeCurrent + UP_NUDGE, minFps, maxFps);
|
|
59
|
+
}
|
|
60
|
+
return safeCurrent;
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
export interface VisionSchedulerOptions {
|
|
64
|
+
initialFps: number;
|
|
65
|
+
minFps: number;
|
|
66
|
+
maxFps: number;
|
|
67
|
+
/** Invoked when the scheduler decides to change fps. Only fires when
|
|
68
|
+
* the new fps differs from the previous fps. */
|
|
69
|
+
onFpsChange: (fps: number) => void;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export interface VisionScheduler {
|
|
73
|
+
/** Feed a status event into the scheduler. Triggers `onFpsChange` iff
|
|
74
|
+
* the new fps differs from the current. */
|
|
75
|
+
handleStatus: VisionStatusListener;
|
|
76
|
+
/** Last fps the scheduler decided on. */
|
|
77
|
+
getFps: () => number;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Stateful adapter on top of {@link computeNextFps}. Wires nicely to
|
|
82
|
+
* `VisionPublisher.onStatus(scheduler.handleStatus)`.
|
|
83
|
+
*/
|
|
84
|
+
export const createVisionScheduler = (
|
|
85
|
+
options: VisionSchedulerOptions,
|
|
86
|
+
): VisionScheduler => {
|
|
87
|
+
const { minFps, maxFps, onFpsChange } = options;
|
|
88
|
+
let currentFps = clamp(options.initialFps, minFps, maxFps);
|
|
89
|
+
|
|
90
|
+
const handleStatus: VisionStatusListener = (status) => {
|
|
91
|
+
const nextFps = computeNextFps({ currentFps, status, minFps, maxFps });
|
|
92
|
+
if (nextFps !== currentFps) {
|
|
93
|
+
currentFps = nextFps;
|
|
94
|
+
onFpsChange(nextFps);
|
|
95
|
+
}
|
|
96
|
+
};
|
|
97
|
+
|
|
98
|
+
return {
|
|
99
|
+
handleStatus,
|
|
100
|
+
getFps: () => currentFps,
|
|
101
|
+
};
|
|
102
|
+
};
|
package/src/websocket.ts
CHANGED
|
@@ -225,6 +225,57 @@ export interface WebSocketMessage {
|
|
|
225
225
|
export type MessageHandler = (message: WebSocketMessage) => void;
|
|
226
226
|
export type BinaryHandler = (data: ArrayBuffer) => void;
|
|
227
227
|
|
|
228
|
+
/**
|
|
229
|
+
* Vision signaling event names routed through the typed `on()` / `off()`
|
|
230
|
+
* dispatcher. The wire payload is snake_case (`vision_answer`,
|
|
231
|
+
* `vision_ice`, `vision_status`) and matches `shared/vision_protocol.py`;
|
|
232
|
+
* we use the snake_case names here too because they double as the
|
|
233
|
+
* incoming `type`/`action` discriminator.
|
|
234
|
+
*
|
|
235
|
+
* Spec: `specs/2026-05-22-phase-2-multimodal-watch.md`.
|
|
236
|
+
*/
|
|
237
|
+
export type ChatWsTypedEvent = 'vision_answer' | 'vision_ice' | 'vision_status';
|
|
238
|
+
|
|
239
|
+
/** Inbound `vision_answer` payload from the backend after it processes
|
|
240
|
+
* the publisher's offer. */
|
|
241
|
+
export interface VisionAnswerEvent {
|
|
242
|
+
type: 'vision_answer';
|
|
243
|
+
sdp: string;
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/** Inbound `vision_ice` payload from the backend's trickle-ICE stream.
|
|
247
|
+
* Wire shape uses snake_case (`sdp_mid` / `sdp_m_line_index`); the
|
|
248
|
+
* dispatcher converts to camel-case before invoking listeners. */
|
|
249
|
+
export interface VisionIceEvent {
|
|
250
|
+
action: 'vision_ice';
|
|
251
|
+
candidate: string | null;
|
|
252
|
+
sdpMid: string | null;
|
|
253
|
+
sdpMLineIndex: number | null;
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
/** Inbound `vision_status` HUD telemetry. Camel-case here (`bufferedFrames`,
|
|
257
|
+
* `processingPaused`); wire shape is snake_case and is converted in the
|
|
258
|
+
* dispatcher. `lastInferenceMs` is not part of the protocol — see
|
|
259
|
+
* `specs/technical-debt.md` Issue #153. */
|
|
260
|
+
export interface VisionStatusEvent {
|
|
261
|
+
type: 'vision_status';
|
|
262
|
+
bufferedFrames: number;
|
|
263
|
+
processingPaused: boolean;
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
export type ChatWsTypedEventPayload<E extends ChatWsTypedEvent> =
|
|
267
|
+
E extends 'vision_answer'
|
|
268
|
+
? VisionAnswerEvent
|
|
269
|
+
: E extends 'vision_ice'
|
|
270
|
+
? VisionIceEvent
|
|
271
|
+
: E extends 'vision_status'
|
|
272
|
+
? VisionStatusEvent
|
|
273
|
+
: never;
|
|
274
|
+
|
|
275
|
+
export type TypedEventHandler<E extends ChatWsTypedEvent = ChatWsTypedEvent> = (
|
|
276
|
+
payload: ChatWsTypedEventPayload<E>,
|
|
277
|
+
) => void | Promise<void>;
|
|
278
|
+
|
|
228
279
|
export interface ChatWebSocketOptions {
|
|
229
280
|
url: string;
|
|
230
281
|
/**
|
|
@@ -272,6 +323,15 @@ export class ChatWebSocket {
|
|
|
272
323
|
private ws: WebSocket | null = null;
|
|
273
324
|
private messageHandlers: MessageHandler[] = [];
|
|
274
325
|
private binaryHandlers: BinaryHandler[] = [];
|
|
326
|
+
/**
|
|
327
|
+
* Typed event-emitter storage for the vision signaling channel. Keyed
|
|
328
|
+
* by `ChatWsTypedEvent`; values are lists of camel-case-payload
|
|
329
|
+
* listeners. The raw `messageHandlers` list above is unchanged and
|
|
330
|
+
* still fires for every inbound message — typed listeners are
|
|
331
|
+
* additive, not a replacement.
|
|
332
|
+
*/
|
|
333
|
+
private typedEventHandlers: Map<ChatWsTypedEvent, TypedEventHandler[]> =
|
|
334
|
+
new Map();
|
|
275
335
|
private url: string;
|
|
276
336
|
private authToken?: string;
|
|
277
337
|
private fetchToken?: () => Promise<string>;
|
|
@@ -382,7 +442,15 @@ export class ChatWebSocket {
|
|
|
382
442
|
this.ws.onmessage = async (event) => {
|
|
383
443
|
try {
|
|
384
444
|
if (typeof event.data === 'string') {
|
|
385
|
-
const
|
|
445
|
+
const raw = JSON.parse(event.data) as Record<string, unknown>;
|
|
446
|
+
// Vision signaling messages bypass the legacy
|
|
447
|
+
// `WebSocketMessage` shape — they're snake_case on the wire
|
|
448
|
+
// and have their own typed dispatcher. Fire those first;
|
|
449
|
+
// they also flow through `messageHandlers` cast as
|
|
450
|
+
// `WebSocketMessage` so existing observers keep seeing
|
|
451
|
+
// them (back-compat).
|
|
452
|
+
this._dispatchVisionEvent(raw);
|
|
453
|
+
const message = raw as unknown as WebSocketMessage;
|
|
386
454
|
this.messageHandlers.forEach((handler) => handler(message));
|
|
387
455
|
return;
|
|
388
456
|
}
|
|
@@ -501,6 +569,196 @@ export class ChatWebSocket {
|
|
|
501
569
|
);
|
|
502
570
|
}
|
|
503
571
|
|
|
572
|
+
/**
|
|
573
|
+
* Send the WebRTC SDP offer that opens a vision session. The
|
|
574
|
+
* `VisionPublisher` calls this after `pc.createOffer()` /
|
|
575
|
+
* `setLocalDescription()`. Wire shape exactly matches
|
|
576
|
+
* `shared/vision_protocol.py::VisionOfferMessage`.
|
|
577
|
+
*/
|
|
578
|
+
sendVisionOffer(payload: {
|
|
579
|
+
action: 'vision_offer';
|
|
580
|
+
sdp: string;
|
|
581
|
+
fps: number;
|
|
582
|
+
}): void {
|
|
583
|
+
this._sendVisionJson(payload);
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
/**
|
|
587
|
+
* Send a single trickle-ICE candidate from the publisher. The TS
|
|
588
|
+
* payload uses camel-case (`sdpMid`, `sdpMLineIndex`); the wire form
|
|
589
|
+
* is snake_case (`sdp_mid`, `sdp_m_line_index`) to match
|
|
590
|
+
* `shared/vision_protocol.py::VisionIceMessage`. Conversion happens
|
|
591
|
+
* here so callers don't need to remember the dialect boundary.
|
|
592
|
+
* A `candidate === null` payload signals end-of-candidates.
|
|
593
|
+
*/
|
|
594
|
+
sendVisionIce(payload: {
|
|
595
|
+
action: 'vision_ice';
|
|
596
|
+
candidate: string | null;
|
|
597
|
+
sdpMid?: string | null;
|
|
598
|
+
sdpMLineIndex?: number | null;
|
|
599
|
+
}): void {
|
|
600
|
+
this._sendVisionJson({
|
|
601
|
+
action: payload.action,
|
|
602
|
+
candidate: payload.candidate,
|
|
603
|
+
sdp_mid: payload.sdpMid ?? null,
|
|
604
|
+
sdp_m_line_index: payload.sdpMLineIndex ?? null,
|
|
605
|
+
});
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
/**
|
|
609
|
+
* Tell the backend the publisher is done with this vision session so
|
|
610
|
+
* it can tear down its `FrameBuffer` and aiortc receiver. Fire-and-
|
|
611
|
+
* forget — if the socket is already closed, the backend will GC on
|
|
612
|
+
* disconnect, so a swallow-and-return is safe.
|
|
613
|
+
*/
|
|
614
|
+
sendVisionClose(): void {
|
|
615
|
+
this._sendVisionJson({ action: 'vision_close' });
|
|
616
|
+
}
|
|
617
|
+
|
|
618
|
+
/**
|
|
619
|
+
* KVS-mode only: bind this chat-WS session to the KVS viewer
|
|
620
|
+
* ClientId the browser received from `/vision-rtc/credentials`. The
|
|
621
|
+
* backend uses the ClientId to look up the right `FrameBuffer` in
|
|
622
|
+
* `VisionSessionRouter` when serving chat turns; without this call
|
|
623
|
+
* the dispatcher can't find any vision frames in KVS mode.
|
|
624
|
+
*
|
|
625
|
+
* Local mode never sends this — receivers live on `session.vision_buffer`
|
|
626
|
+
* and the chat WS already knows about them via the existing
|
|
627
|
+
* `vision_offer` handler.
|
|
628
|
+
*/
|
|
629
|
+
sendVisionAttach(payload: { action: 'vision_attach'; clientId: string }): void {
|
|
630
|
+
this._sendVisionJson({
|
|
631
|
+
action: payload.action,
|
|
632
|
+
// The wire field is camelCase `clientId` — the backend reads
|
|
633
|
+
// `message.get("clientId")` in ws.py's vision_attach handler.
|
|
634
|
+
// Do NOT "normalize" this to snake_case `client_id`: that would
|
|
635
|
+
// make the backend read None and silently break KVS attach.
|
|
636
|
+
clientId: payload.clientId,
|
|
637
|
+
});
|
|
638
|
+
}
|
|
639
|
+
|
|
640
|
+
/**
|
|
641
|
+
* KVS-mode only: release the per-ClientId receiver + FrameBuffer in
|
|
642
|
+
* `VisionSessionRouter`. Sent from `VisionPublisher.stop()` in kvs
|
|
643
|
+
* mode. The backend also cleans up on WS disconnect, so this is
|
|
644
|
+
* fire-and-forget; the explicit detach just frees resources slightly
|
|
645
|
+
* sooner during long-lived chat sessions.
|
|
646
|
+
*/
|
|
647
|
+
sendVisionDetach(): void {
|
|
648
|
+
this._sendVisionJson({ action: 'vision_detach' });
|
|
649
|
+
}
|
|
650
|
+
|
|
651
|
+
/**
|
|
652
|
+
* Register a typed listener for a vision-signaling event. Returns
|
|
653
|
+
* void (matches the `messageHandlers` pattern); unsubscribe via
|
|
654
|
+
* `off(event, handler)`.
|
|
655
|
+
*/
|
|
656
|
+
on<E extends ChatWsTypedEvent>(event: E, handler: TypedEventHandler<E>): void {
|
|
657
|
+
const list = this.typedEventHandlers.get(event) ?? [];
|
|
658
|
+
list.push(handler as TypedEventHandler);
|
|
659
|
+
this.typedEventHandlers.set(event, list);
|
|
660
|
+
}
|
|
661
|
+
|
|
662
|
+
/** Remove a previously-registered typed listener. */
|
|
663
|
+
off<E extends ChatWsTypedEvent>(event: E, handler: TypedEventHandler<E>): void {
|
|
664
|
+
const list = this.typedEventHandlers.get(event);
|
|
665
|
+
if (!list) return;
|
|
666
|
+
this.typedEventHandlers.set(
|
|
667
|
+
event,
|
|
668
|
+
list.filter((h) => h !== handler),
|
|
669
|
+
);
|
|
670
|
+
}
|
|
671
|
+
|
|
672
|
+
/**
|
|
673
|
+
* Best-effort JSON send for vision signaling. Vision messages are
|
|
674
|
+
* fire-and-forget; if the socket isn't OPEN we drop silently (the
|
|
675
|
+
* publisher will tear down when its connection state changes).
|
|
676
|
+
*/
|
|
677
|
+
private _sendVisionJson(payload: Record<string, unknown>): void {
|
|
678
|
+
if (this.ws?.readyState !== WebSocket.OPEN) return;
|
|
679
|
+
this.ws.send(JSON.stringify(payload));
|
|
680
|
+
}
|
|
681
|
+
|
|
682
|
+
/**
|
|
683
|
+
* Inspect an inbound parsed message and, if it's one of the three
|
|
684
|
+
* vision signaling events, fan it out to the typed listeners. Owns
|
|
685
|
+
* the snake_case → camel_case conversion for `vision_ice` and
|
|
686
|
+
* `vision_status` so listeners see the camel-cased payloads declared
|
|
687
|
+
* in the `Vision*Event` interfaces.
|
|
688
|
+
*/
|
|
689
|
+
private _dispatchVisionEvent(raw: Record<string, unknown>): void {
|
|
690
|
+
const t = raw['type'] as string | undefined;
|
|
691
|
+
const action = raw['action'] as string | undefined;
|
|
692
|
+
if (t === 'vision_answer') {
|
|
693
|
+
this._fireTyped('vision_answer', {
|
|
694
|
+
type: 'vision_answer',
|
|
695
|
+
sdp: String(raw['sdp'] ?? ''),
|
|
696
|
+
});
|
|
697
|
+
return;
|
|
698
|
+
}
|
|
699
|
+
if (t === 'vision_status') {
|
|
700
|
+
// Wire shape is snake_case; surface camel-case to listeners.
|
|
701
|
+
const bufferedFrames =
|
|
702
|
+
(raw['bufferedFrames'] as number | undefined) ??
|
|
703
|
+
(raw['buffered_frames'] as number | undefined) ??
|
|
704
|
+
0;
|
|
705
|
+
const processingPaused =
|
|
706
|
+
(raw['processingPaused'] as boolean | undefined) ??
|
|
707
|
+
(raw['processing_paused'] as boolean | undefined) ??
|
|
708
|
+
false;
|
|
709
|
+
this._fireTyped('vision_status', {
|
|
710
|
+
type: 'vision_status',
|
|
711
|
+
bufferedFrames,
|
|
712
|
+
processingPaused,
|
|
713
|
+
});
|
|
714
|
+
return;
|
|
715
|
+
}
|
|
716
|
+
if (action === 'vision_ice') {
|
|
717
|
+
const sdpMid =
|
|
718
|
+
(raw['sdpMid'] as string | null | undefined) ??
|
|
719
|
+
(raw['sdp_mid'] as string | null | undefined) ??
|
|
720
|
+
null;
|
|
721
|
+
const sdpMLineIndex =
|
|
722
|
+
(raw['sdpMLineIndex'] as number | null | undefined) ??
|
|
723
|
+
(raw['sdp_m_line_index'] as number | null | undefined) ??
|
|
724
|
+
null;
|
|
725
|
+
this._fireTyped('vision_ice', {
|
|
726
|
+
action: 'vision_ice',
|
|
727
|
+
candidate: (raw['candidate'] as string | null) ?? null,
|
|
728
|
+
sdpMid,
|
|
729
|
+
sdpMLineIndex,
|
|
730
|
+
});
|
|
731
|
+
}
|
|
732
|
+
}
|
|
733
|
+
|
|
734
|
+
private _fireTyped<E extends ChatWsTypedEvent>(
|
|
735
|
+
event: E,
|
|
736
|
+
payload: ChatWsTypedEventPayload<E>,
|
|
737
|
+
): void {
|
|
738
|
+
const list = this.typedEventHandlers.get(event);
|
|
739
|
+
if (!list) return;
|
|
740
|
+
for (const handler of list) {
|
|
741
|
+
try {
|
|
742
|
+
const result = handler(payload);
|
|
743
|
+
// Async handlers (the publisher's onAnswer/onIce are both
|
|
744
|
+
// `async`) return a Promise. `void` would swallow rejections
|
|
745
|
+
// into the unhandled-rejection channel where they're invisible
|
|
746
|
+
// to ChatWebSocket consumers. Catch + log so async failures
|
|
747
|
+
// show up alongside sync ones.
|
|
748
|
+
if (result instanceof Promise) {
|
|
749
|
+
result.catch((err) => {
|
|
750
|
+
console.error(
|
|
751
|
+
`ChatWebSocket typed handler for ${event} rejected:`,
|
|
752
|
+
err,
|
|
753
|
+
);
|
|
754
|
+
});
|
|
755
|
+
}
|
|
756
|
+
} catch (err) {
|
|
757
|
+
console.error(`ChatWebSocket typed handler for ${event} threw:`, err);
|
|
758
|
+
}
|
|
759
|
+
}
|
|
760
|
+
}
|
|
761
|
+
|
|
504
762
|
/**
|
|
505
763
|
* Send a binary microphone frame (tagged with TAG_MIC)
|
|
506
764
|
*/
|