@byokit/realtime 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +13 -0
- package/LICENSE +202 -0
- package/README.md +41 -0
- package/dist/adapter.d.ts +13 -0
- package/dist/adapter.js +1 -0
- package/dist/catalogue.d.ts +14 -0
- package/dist/catalogue.js +2 -0
- package/dist/catalogue.json +6 -0
- package/dist/chatgpt.d.ts +10 -0
- package/dist/chatgpt.js +146 -0
- package/dist/child.d.ts +1 -0
- package/dist/child.js +50 -0
- package/dist/client.d.ts +8 -0
- package/dist/client.js +276 -0
- package/dist/frames.d.ts +107 -0
- package/dist/frames.js +188 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +6 -0
- package/dist/node.d.ts +22 -0
- package/dist/node.js +163 -0
- package/dist/policy.d.ts +7 -0
- package/dist/policy.js +24 -0
- package/dist/prose.d.ts +7 -0
- package/dist/prose.js +42 -0
- package/dist/providers/gemini.d.ts +6 -0
- package/dist/providers/gemini.js +429 -0
- package/dist/providers/openai.d.ts +6 -0
- package/dist/providers/openai.js +313 -0
- package/dist/providers/xai.d.ts +6 -0
- package/dist/providers/xai.js +542 -0
- package/dist/rn-webrtc.d.ts +5 -0
- package/dist/rn-webrtc.js +12 -0
- package/dist/tools.d.ts +30 -0
- package/dist/tools.js +93 -0
- package/dist/types.d.ts +106 -0
- package/dist/types.js +12 -0
- package/dist/webrtc.d.ts +24 -0
- package/dist/webrtc.js +133 -0
- package/dist/words.d.ts +8 -0
- package/dist/words.js +5 -0
- package/dist/words.json +8 -0
- package/package.json +56 -0
package/dist/types.d.ts
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import type { RealtimeClientFrame, RealtimeHostFrame, RealtimeAppAction } from './frames.ts';
|
|
2
|
+
export type RealtimeProviderId = 'chatgpt' | 'openai' | 'gemini' | 'xai';
|
|
3
|
+
export type RealtimeTool = {
|
|
4
|
+
name: string;
|
|
5
|
+
description: string;
|
|
6
|
+
parameters: object;
|
|
7
|
+
};
|
|
8
|
+
export type RealtimeUsage = {
|
|
9
|
+
seconds: number;
|
|
10
|
+
basis: 'tokens' | 'minutes' | 'subscription';
|
|
11
|
+
inputTokens?: number;
|
|
12
|
+
outputTokens?: number;
|
|
13
|
+
audioInTokens?: number;
|
|
14
|
+
audioOutTokens?: number;
|
|
15
|
+
cachedTokens?: number;
|
|
16
|
+
};
|
|
17
|
+
export type RealtimeAuth = {
|
|
18
|
+
kind: 'key';
|
|
19
|
+
key: string;
|
|
20
|
+
} | {
|
|
21
|
+
kind: 'plan';
|
|
22
|
+
access(signal?: AbortSignal): Promise<{
|
|
23
|
+
access: string;
|
|
24
|
+
accountId: string;
|
|
25
|
+
}>;
|
|
26
|
+
};
|
|
27
|
+
export type RealtimeConfig = {
|
|
28
|
+
instructions?: string;
|
|
29
|
+
model?: string;
|
|
30
|
+
voice?: string;
|
|
31
|
+
tools?: RealtimeTool[];
|
|
32
|
+
};
|
|
33
|
+
export type RealtimeErrorCode = 'signed-out' | 'resting' | 'not-included' | 'rate-limited' | 'network' | 'bad-key' | 'expired' | 'protocol' | 'mic-blocked' | 'mic-busy' | 'unsupported';
|
|
34
|
+
export declare class RealtimeError extends Error {
|
|
35
|
+
readonly name = "RealtimeError";
|
|
36
|
+
readonly code: RealtimeErrorCode;
|
|
37
|
+
readonly detail?: Record<string, unknown>;
|
|
38
|
+
readonly until?: number;
|
|
39
|
+
constructor(code: RealtimeErrorCode, options?: {
|
|
40
|
+
cause?: unknown;
|
|
41
|
+
detail?: Record<string, unknown>;
|
|
42
|
+
until?: number;
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
export type RealtimeToolCall = {
|
|
46
|
+
callId: string;
|
|
47
|
+
name: string;
|
|
48
|
+
args: unknown;
|
|
49
|
+
delegated?: boolean;
|
|
50
|
+
};
|
|
51
|
+
export type AudioPorts = {
|
|
52
|
+
microphone: {
|
|
53
|
+
acquire(): Promise<void>;
|
|
54
|
+
release(): void;
|
|
55
|
+
};
|
|
56
|
+
capture(rate: number, onData: (base64: string) => void): Promise<{
|
|
57
|
+
pending: string[];
|
|
58
|
+
release(): Promise<void>;
|
|
59
|
+
}>;
|
|
60
|
+
player: {
|
|
61
|
+
ensure(rate: number): void;
|
|
62
|
+
bind(sink: PlaybackSink): void;
|
|
63
|
+
unbind(sink: PlaybackSink): void;
|
|
64
|
+
admit(base64: string): 'ok' | 'malformed' | 'overflow';
|
|
65
|
+
clear(): void;
|
|
66
|
+
finish(onDrained?: () => void): boolean;
|
|
67
|
+
afterDrain(kind: 'connected' | 'speech', run: () => void): boolean;
|
|
68
|
+
stop(): void;
|
|
69
|
+
release(): void;
|
|
70
|
+
};
|
|
71
|
+
route(): Promise<void>;
|
|
72
|
+
unroute(): Promise<void>;
|
|
73
|
+
};
|
|
74
|
+
export type PlaybackSink = {
|
|
75
|
+
send(frame: RealtimeClientFrame): boolean;
|
|
76
|
+
};
|
|
77
|
+
export type RealtimeStream = PlaybackSink & {
|
|
78
|
+
onFrame(fn: (frame: RealtimeHostFrame) => void): void;
|
|
79
|
+
onClose(fn: (reason?: string) => void): void;
|
|
80
|
+
start(): void;
|
|
81
|
+
close(): void;
|
|
82
|
+
};
|
|
83
|
+
export type RealtimeClientOptions = {
|
|
84
|
+
open(): Promise<RealtimeStream>;
|
|
85
|
+
audio: AudioPorts;
|
|
86
|
+
/** Transport closures retry by default. Return false for intentional or terminal closures. */
|
|
87
|
+
retryableClose?(reason?: string): boolean;
|
|
88
|
+
webrtc?: (options: import('./webrtc.ts').WebRtcOptions) => Promise<import('./webrtc.ts').WebRtcHandle>;
|
|
89
|
+
onStatus(status: 'connecting' | 'connected' | 'thinking' | 'speaking' | 'disconnected', reason?: string): void;
|
|
90
|
+
onTurn(role: 'user' | 'agent', text: string): void;
|
|
91
|
+
onActivity?(): void;
|
|
92
|
+
onLevel?(direction: 'input' | 'output', base64: string): void;
|
|
93
|
+
onStats?(stats: {
|
|
94
|
+
micCaptured: number;
|
|
95
|
+
micSent: number;
|
|
96
|
+
micQueued: number;
|
|
97
|
+
micDropped: number;
|
|
98
|
+
transportReconnects: number;
|
|
99
|
+
providerReconnects: number;
|
|
100
|
+
}): void;
|
|
101
|
+
onUsage?(usage: RealtimeUsage): void;
|
|
102
|
+
onAppRequest?(action: RealtimeAppAction, target?: string): Promise<{
|
|
103
|
+
ok: boolean;
|
|
104
|
+
text: string;
|
|
105
|
+
}>;
|
|
106
|
+
};
|
package/dist/types.js
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
export class RealtimeError extends Error {
|
|
2
|
+
name = 'RealtimeError';
|
|
3
|
+
code;
|
|
4
|
+
detail;
|
|
5
|
+
until;
|
|
6
|
+
constructor(code, options = {}) {
|
|
7
|
+
super(code, { cause: options.cause });
|
|
8
|
+
this.code = code;
|
|
9
|
+
this.detail = options.detail;
|
|
10
|
+
this.until = options.until;
|
|
11
|
+
}
|
|
12
|
+
}
|
package/dist/webrtc.d.ts
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import type { AudioPorts } from './types.ts';
|
|
2
|
+
export type WebRtcHandle = {
|
|
3
|
+
acceptAnswer(sdp: string): Promise<void>;
|
|
4
|
+
sendData(data: string): boolean;
|
|
5
|
+
setMuted(muted: boolean): void;
|
|
6
|
+
stop(): void;
|
|
7
|
+
};
|
|
8
|
+
export type WebRtcOptions = {
|
|
9
|
+
label: string;
|
|
10
|
+
audio: Pick<AudioPorts, 'microphone' | 'route' | 'unroute'>;
|
|
11
|
+
signal?: AbortSignal;
|
|
12
|
+
platform?: {
|
|
13
|
+
createPeer(): RTCPeerConnection;
|
|
14
|
+
getUserMedia(): Promise<MediaStream>;
|
|
15
|
+
};
|
|
16
|
+
onOffer(sdp: string): void;
|
|
17
|
+
onData(data: string): void;
|
|
18
|
+
onRemoteAudio(active: boolean): void;
|
|
19
|
+
onConnectionState(state: 'connecting' | 'connected' | 'disconnected'): void;
|
|
20
|
+
onInterruption(active: boolean): void;
|
|
21
|
+
onError(error: Error): void;
|
|
22
|
+
};
|
|
23
|
+
/** One peer per handle. Microphone permission/service readiness precedes media capture. */
|
|
24
|
+
export declare function webRtcPeer(options: WebRtcOptions): Promise<WebRtcHandle>;
|
package/dist/webrtc.js
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
import { MAX_REALTIME_SDP_BYTES, MAX_REALTIME_WEBRTC_DATA_BYTES } from "./frames.js";
|
|
2
|
+
function sdp(value) {
|
|
3
|
+
if (typeof value !== 'string' || !value.startsWith('v=0') || value.includes('\0') || new TextEncoder().encode(value).length > MAX_REALTIME_SDP_BYTES)
|
|
4
|
+
throw new Error('Invalid voice connection answer.');
|
|
5
|
+
return value;
|
|
6
|
+
}
|
|
7
|
+
/** One peer per handle. Microphone permission/service readiness precedes media capture. */
|
|
8
|
+
export async function webRtcPeer(options) {
|
|
9
|
+
if (!/^[A-Za-z0-9._-]{1,64}$/.test(options.label))
|
|
10
|
+
throw new Error('Invalid voice channel.');
|
|
11
|
+
const platform = options.platform ?? { createPeer: () => new RTCPeerConnection({ bundlePolicy: 'max-bundle', rtcpMuxPolicy: 'require' }), getUserMedia: () => navigator.mediaDevices.getUserMedia({ audio: true, video: false }) };
|
|
12
|
+
let acquired = false, stopped = false, stream, peer, channel;
|
|
13
|
+
const queue = [];
|
|
14
|
+
let queuedBytes = 0;
|
|
15
|
+
const stop = () => {
|
|
16
|
+
if (stopped)
|
|
17
|
+
return;
|
|
18
|
+
stopped = true;
|
|
19
|
+
stream?.getTracks().forEach(track => track.stop());
|
|
20
|
+
channel?.close();
|
|
21
|
+
peer?.close();
|
|
22
|
+
queue.length = 0;
|
|
23
|
+
void options.audio.unroute().catch(() => { });
|
|
24
|
+
if (acquired) {
|
|
25
|
+
options.audio.microphone.release();
|
|
26
|
+
acquired = false;
|
|
27
|
+
}
|
|
28
|
+
options.signal?.removeEventListener('abort', stop);
|
|
29
|
+
options.onRemoteAudio(false);
|
|
30
|
+
options.onConnectionState('disconnected');
|
|
31
|
+
};
|
|
32
|
+
options.signal?.addEventListener('abort', stop, { once: true });
|
|
33
|
+
const fail = (error) => { if (!stopped) {
|
|
34
|
+
options.onError(error);
|
|
35
|
+
stop();
|
|
36
|
+
} };
|
|
37
|
+
try {
|
|
38
|
+
options.onConnectionState('connecting');
|
|
39
|
+
options.signal?.throwIfAborted();
|
|
40
|
+
await options.audio.microphone.acquire();
|
|
41
|
+
acquired = true;
|
|
42
|
+
if (stopped) {
|
|
43
|
+
options.audio.microphone.release();
|
|
44
|
+
acquired = false;
|
|
45
|
+
throw new Error('Voice is closed.');
|
|
46
|
+
}
|
|
47
|
+
await options.audio.route();
|
|
48
|
+
if (stopped) {
|
|
49
|
+
await options.audio.unroute();
|
|
50
|
+
throw new Error('Voice is closed.');
|
|
51
|
+
}
|
|
52
|
+
stream = await platform.getUserMedia();
|
|
53
|
+
if (stopped) {
|
|
54
|
+
stream.getTracks().forEach(track => track.stop());
|
|
55
|
+
throw new Error('Voice is closed.');
|
|
56
|
+
}
|
|
57
|
+
peer = platform.createPeer();
|
|
58
|
+
channel = peer.createDataChannel(options.label);
|
|
59
|
+
const current = peer, dataChannel = channel;
|
|
60
|
+
const flush = () => { while (!stopped && queue.length && dataChannel.readyState === 'open' && dataChannel.bufferedAmount <= 256 * 1024) {
|
|
61
|
+
const data = queue.shift();
|
|
62
|
+
queuedBytes -= new TextEncoder().encode(data).length;
|
|
63
|
+
dataChannel.send(data);
|
|
64
|
+
} };
|
|
65
|
+
dataChannel.bufferedAmountLowThreshold = 128 * 1024;
|
|
66
|
+
dataChannel.onopen = flush;
|
|
67
|
+
dataChannel.onbufferedamountlow = flush;
|
|
68
|
+
dataChannel.onmessage = event => { if (typeof event.data === 'string' && !event.data.includes('\0') && new TextEncoder().encode(event.data).length <= MAX_REALTIME_WEBRTC_DATA_BYTES && !stopped)
|
|
69
|
+
options.onData(event.data); };
|
|
70
|
+
dataChannel.onerror = () => fail(new Error('Voice channel failed.'));
|
|
71
|
+
dataChannel.onclose = () => fail(new Error('Voice channel closed.'));
|
|
72
|
+
current.onconnectionstatechange = () => { if (stopped)
|
|
73
|
+
return; if (current.connectionState === 'connected')
|
|
74
|
+
options.onConnectionState('connected');
|
|
75
|
+
else if (['failed', 'closed'].includes(current.connectionState))
|
|
76
|
+
fail(new Error('Voice connection ended.'));
|
|
77
|
+
else
|
|
78
|
+
options.onConnectionState('connecting'); };
|
|
79
|
+
current.ontrack = event => { const track = event.track; if (track.kind !== 'audio' || stopped)
|
|
80
|
+
return; options.onRemoteAudio(!track.muted); track.onmute = () => options.onRemoteAudio(false); track.onunmute = () => options.onRemoteAudio(true); track.onended = () => options.onRemoteAudio(false); };
|
|
81
|
+
const input = stream.getAudioTracks()[0];
|
|
82
|
+
if (!input)
|
|
83
|
+
throw new Error('Microphone is unavailable.');
|
|
84
|
+
input.onmute = () => options.onInterruption(true);
|
|
85
|
+
input.onunmute = () => options.onInterruption(false);
|
|
86
|
+
input.onended = () => fail(new Error('Microphone ended.'));
|
|
87
|
+
current.addTrack(input, stream);
|
|
88
|
+
await current.setLocalDescription(await current.createOffer());
|
|
89
|
+
if (current.iceGatheringState !== 'complete')
|
|
90
|
+
await new Promise((resolve, reject) => {
|
|
91
|
+
const timer = setTimeout(() => { current.onicegatheringstatechange = null; reject(new Error('Voice connection timed out.')); }, 5000);
|
|
92
|
+
current.onicegatheringstatechange = () => { if (current.iceGatheringState === 'complete') {
|
|
93
|
+
clearTimeout(timer);
|
|
94
|
+
current.onicegatheringstatechange = null;
|
|
95
|
+
resolve();
|
|
96
|
+
} };
|
|
97
|
+
if (current.iceGatheringState === 'complete') {
|
|
98
|
+
clearTimeout(timer);
|
|
99
|
+
current.onicegatheringstatechange = null;
|
|
100
|
+
resolve();
|
|
101
|
+
}
|
|
102
|
+
});
|
|
103
|
+
if (stopped)
|
|
104
|
+
throw new Error('Voice is closed.');
|
|
105
|
+
options.onOffer(sdp(current.localDescription?.sdp));
|
|
106
|
+
return {
|
|
107
|
+
async acceptAnswer(answer) { if (stopped)
|
|
108
|
+
throw new Error('Voice is closed.'); await current.setRemoteDescription({ type: 'answer', sdp: sdp(answer) }); },
|
|
109
|
+
sendData(data) {
|
|
110
|
+
const bytes = new TextEncoder().encode(data).length;
|
|
111
|
+
if (stopped || !bytes || bytes > MAX_REALTIME_WEBRTC_DATA_BYTES || data.includes('\0'))
|
|
112
|
+
return false;
|
|
113
|
+
if (dataChannel.readyState === 'open' && queue.length === 0) {
|
|
114
|
+
if (dataChannel.bufferedAmount > 256 * 1024)
|
|
115
|
+
return false;
|
|
116
|
+
dataChannel.send(data);
|
|
117
|
+
return true;
|
|
118
|
+
}
|
|
119
|
+
if (!['open', 'connecting'].includes(dataChannel.readyState) || queuedBytes + bytes > 64 * 1024)
|
|
120
|
+
return false;
|
|
121
|
+
queue.push(data);
|
|
122
|
+
queuedBytes += bytes;
|
|
123
|
+
flush();
|
|
124
|
+
return true;
|
|
125
|
+
},
|
|
126
|
+
setMuted(muted) { stream?.getAudioTracks().forEach(track => { track.enabled = !muted; }); }, stop,
|
|
127
|
+
};
|
|
128
|
+
}
|
|
129
|
+
catch (error) {
|
|
130
|
+
stop();
|
|
131
|
+
throw error;
|
|
132
|
+
}
|
|
133
|
+
}
|
package/dist/words.d.ts
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import WORDS from './words.json' with { type: 'json' };
|
|
2
|
+
export { WORDS };
|
|
3
|
+
export type WordKey = keyof typeof WORDS;
|
|
4
|
+
export declare function words(key: WordKey): string;
|
|
5
|
+
export declare function stateWords(state: {
|
|
6
|
+
phase: 'connecting' | 'connected' | 'thinking' | 'speaking' | 'closed';
|
|
7
|
+
}): string;
|
|
8
|
+
export declare function errorWords(_error: unknown): string;
|
package/dist/words.js
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import WORDS from './words.json' with { type: 'json' };
|
|
2
|
+
export { WORDS };
|
|
3
|
+
export function words(key) { return WORDS[key]; }
|
|
4
|
+
export function stateWords(state) { return words(`realtime.${state.phase}`); }
|
|
5
|
+
export function errorWords(_error) { return words('realtime.error'); }
|
package/dist/words.json
ADDED
package/package.json
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@byokit/realtime",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Realtime voice sessions with host-held credentials and injected audio.",
|
|
5
|
+
"license": "Apache-2.0",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/umeranjum17/byokit.git",
|
|
10
|
+
"directory": "packages/realtime"
|
|
11
|
+
},
|
|
12
|
+
"engines": {
|
|
13
|
+
"node": ">=22.18"
|
|
14
|
+
},
|
|
15
|
+
"exports": {
|
|
16
|
+
".": {
|
|
17
|
+
"types": "./dist/index.d.ts",
|
|
18
|
+
"default": "./dist/index.js"
|
|
19
|
+
},
|
|
20
|
+
"./node": {
|
|
21
|
+
"types": "./dist/node.d.ts",
|
|
22
|
+
"default": "./dist/node.js"
|
|
23
|
+
},
|
|
24
|
+
"./webrtc": {
|
|
25
|
+
"react-native": {
|
|
26
|
+
"types": "./dist/rn-webrtc.d.ts",
|
|
27
|
+
"default": "./dist/rn-webrtc.js"
|
|
28
|
+
},
|
|
29
|
+
"types": "./dist/webrtc.d.ts",
|
|
30
|
+
"default": "./dist/webrtc.js"
|
|
31
|
+
}
|
|
32
|
+
},
|
|
33
|
+
"files": [
|
|
34
|
+
"dist",
|
|
35
|
+
"README.md",
|
|
36
|
+
"LICENSE",
|
|
37
|
+
"CHANGELOG.md"
|
|
38
|
+
],
|
|
39
|
+
"scripts": {
|
|
40
|
+
"prepack": "tsc -b && node ../../scripts/fix-words-dts.cjs"
|
|
41
|
+
},
|
|
42
|
+
"publishConfig": {
|
|
43
|
+
"access": "public"
|
|
44
|
+
},
|
|
45
|
+
"dependencies": {
|
|
46
|
+
"ws": "8.21.3"
|
|
47
|
+
},
|
|
48
|
+
"peerDependencies": {
|
|
49
|
+
"react-native-webrtc": "124.0.8"
|
|
50
|
+
},
|
|
51
|
+
"peerDependenciesMeta": {
|
|
52
|
+
"react-native-webrtc": {
|
|
53
|
+
"optional": true
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
}
|