@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/CHANGELOG.md
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## Unreleased
|
|
4
|
+
|
|
5
|
+
- Add interruption fencing and tool cancellation, bounded provider and transport reconnects, and fresh-call ChatGPT subscription voice interruption.
|
|
6
|
+
|
|
7
|
+
## 0.1.0 (2026-09-30)
|
|
8
|
+
|
|
9
|
+
- Add realtime speech-to-speech sessions with injected audio and child-process provider adapters.
|
|
10
|
+
- Add ChatGPT subscription voice through accounts and OpenAI, Gemini and xAI with an API key (billed per use).
|
|
11
|
+
- live ChatGPT-plan voice proof: pending, needs the owner at the desk with a microphone.
|
|
12
|
+
|
|
13
|
+
- Initial realtime voice kit with bounded frames, WebRTC signaling, tool calls, turn events, interruption hooks and usage.
|
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
# @byokit/realtime
|
|
2
|
+
|
|
3
|
+
Realtime voice sessions with injected audio and provider adapters in a child process. First consumer: muxr.
|
|
4
|
+
|
|
5
|
+
```ts
|
|
6
|
+
import { realtimeClient, type AudioPorts, type RealtimeHostFrame, type RealtimeStream } from '@byokit/realtime';
|
|
7
|
+
import { realtimeEngine, toolBridge } from '@byokit/realtime/node';
|
|
8
|
+
|
|
9
|
+
// The app supplies its sign-in, carrier, audio implementation and authorized planner.
|
|
10
|
+
declare const accounts: { access(member: number, signal?: AbortSignal): Promise<{ access: string; accountId: string }> };
|
|
11
|
+
declare const emit: (frame: RealtimeHostFrame) => void;
|
|
12
|
+
declare const runPlanner: (request: string, signal: AbortSignal) => Promise<string>;
|
|
13
|
+
declare const openVoiceStream: () => Promise<RealtimeStream>;
|
|
14
|
+
declare const audio: AudioPorts;
|
|
15
|
+
const member = 1;
|
|
16
|
+
const tools = [{ name: 'delegate', description: 'Handle a spoken request', parameters: { type: 'object', properties: { request: { type: 'string' } } } }];
|
|
17
|
+
const bridge = toolBridge({
|
|
18
|
+
tools, handlers: { delegate: async (args, { signal }) => runPlanner(String(args.request), signal) },
|
|
19
|
+
emit, failure: () => 'That request could not be completed.',
|
|
20
|
+
});
|
|
21
|
+
const engine = realtimeEngine({
|
|
22
|
+
engine: 'chatgpt', auth: { kind: 'plan', access: signal => accounts.access(member, signal) },
|
|
23
|
+
tools, bridge, instructions: 'Answer briefly.', emit,
|
|
24
|
+
});
|
|
25
|
+
// Forward device frames to engine.receive(frame); engine.close() ends the child.
|
|
26
|
+
const client = realtimeClient({
|
|
27
|
+
open: openVoiceStream, audio,
|
|
28
|
+
onStatus: status => console.log(status),
|
|
29
|
+
onTurn: (role, text) => console.log(role, text),
|
|
30
|
+
});
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
For ChatGPT voice register a `delegate` tool handler receiving `{ request }` and supply the app's planner. API routes use `auth: { kind: 'key', key }`, with billing per use. The subscription route uses the person's ChatGPT sign-in from `@byokit/accounts`; it never reads Codex credentials or starts the Codex CLI. Backend refusal is reported as `not-included`.
|
|
34
|
+
|
|
35
|
+
The main entry is portable for web and React Native and loads no native code. `./webrtc` supplies `webRtcPeer` for browsers and selects its native implementation under the `react-native` condition; install the optional `react-native-webrtc` 124.0.8 peer in the RN app. All media APIs can be injected for tests. `./node` requires Node 22.18+ and is for the credential host. It starts its own adapter child with an empty environment; credentials travel over private stdin. No provider key or plan token is sent to the device.
|
|
36
|
+
|
|
37
|
+
`AudioPorts` requires microphone acquisition/release, PCM capture, playback admission/drain and audio routing. The app owns permissions and its microphone service. Acquire must resolve only after that service is ready. The client awaits it before capture. Each client owns its ports; the app must arbitrate shared microphones.
|
|
38
|
+
|
|
39
|
+
Close the client and engine when the call ends. `client.interrupt()` clears playback and aborts unfinished tools; old response output is fenced. Transient provider and transport failures retry twice, after 500 and 1,000 ms, with a fresh budget after 30 healthy seconds. Sent audio, speech and tool calls are never replayed. The app can mark transport closure terminal with `retryableClose`. Explicit ChatGPT interruption opens a fresh call; explicit Gemini interruption rotates its provider session. Native speech interruption remains provider-driven. No STT/LLM/TTS chain is exported. See [the lift contract](../../docs/realtime-kit.md) for bounds, events and usage.
|
|
40
|
+
|
|
41
|
+
For an explicitly live microphone and subscription-provider proof, run [the bounded voice demo](../../examples/realtime-voice/README.md). It signs in through accounts, keeps credentials only in memory, and records connection facts and turn counts. Offline tests do not establish a live pass.
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { toolBridge } from './tools.ts';
|
|
2
|
+
import type { RealtimeTool } from './types.ts';
|
|
3
|
+
export type AdapterOptions = {
|
|
4
|
+
key: string;
|
|
5
|
+
instructions: string;
|
|
6
|
+
tools: RealtimeTool[];
|
|
7
|
+
bridge: ReturnType<typeof toolBridge>;
|
|
8
|
+
model?: string;
|
|
9
|
+
voice?: string;
|
|
10
|
+
endpoint?: string;
|
|
11
|
+
redact?: RegExp[];
|
|
12
|
+
hangup?: (text: string) => boolean;
|
|
13
|
+
};
|
package/dist/adapter.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { RealtimeProviderId, RealtimeUsage } from './types.ts';
|
|
2
|
+
export type RealtimeProviderInfo = {
|
|
3
|
+
id: RealtimeProviderId;
|
|
4
|
+
name: string;
|
|
5
|
+
billing: 'subscription' | 'api';
|
|
6
|
+
planSignIn: boolean;
|
|
7
|
+
terms: 'grey' | 'allowed';
|
|
8
|
+
why?: string;
|
|
9
|
+
source: string;
|
|
10
|
+
inputRate: number;
|
|
11
|
+
outputRate: number;
|
|
12
|
+
usage: RealtimeUsage['basis'];
|
|
13
|
+
};
|
|
14
|
+
export declare const providers: readonly RealtimeProviderInfo[];
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
[
|
|
2
|
+
{ "id": "chatgpt", "name": "ChatGPT voice", "billing": "subscription", "planSignIn": true, "terms": "grey", "why": "Uses the person's ChatGPT sign-in through accounts on the host.", "source": "https://github.com/openai/codex", "inputRate": 24000, "outputRate": 24000, "usage": "subscription" },
|
|
3
|
+
{ "id": "openai", "name": "OpenAI", "billing": "api", "planSignIn": false, "terms": "allowed", "source": "https://platform.openai.com/docs/guides/realtime", "inputRate": 24000, "outputRate": 24000, "usage": "tokens" },
|
|
4
|
+
{ "id": "gemini", "name": "Gemini", "billing": "api", "planSignIn": false, "terms": "allowed", "source": "https://ai.google.dev/gemini-api/docs/live", "inputRate": 16000, "outputRate": 24000, "usage": "tokens" },
|
|
5
|
+
{ "id": "xai", "name": "Grok", "billing": "api", "planSignIn": false, "terms": "allowed", "source": "https://docs.x.ai/docs/guides/voice", "inputRate": 24000, "outputRate": 24000, "usage": "minutes" }
|
|
6
|
+
]
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { RealtimeClientFrame } from './frames.ts';
|
|
2
|
+
import type { AdapterOptions } from './adapter.ts';
|
|
3
|
+
export declare const CHATGPT_SIGNALING_URL = "https://chatgpt.com/backend-api/codex/realtime/calls?intent=quicksilver&architecture=avas";
|
|
4
|
+
export declare function boundedBody(response: Response, max?: number): Promise<string>;
|
|
5
|
+
export declare function createChatgptAdapter(options: AdapterOptions & {
|
|
6
|
+
accountId: string;
|
|
7
|
+
}): {
|
|
8
|
+
receive(frame: RealtimeClientFrame): void;
|
|
9
|
+
close: (reason?: string, retryable?: boolean) => void;
|
|
10
|
+
};
|
package/dist/chatgpt.js
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
import { responseFence } from "./policy.js";
|
|
2
|
+
import { cleanProse } from "./prose.js";
|
|
3
|
+
import { MAX_REALTIME_SDP_BYTES } from "./frames.js";
|
|
4
|
+
export const CHATGPT_SIGNALING_URL = 'https://chatgpt.com/backend-api/codex/realtime/calls?intent=quicksilver&architecture=avas';
|
|
5
|
+
function emit(frame) { process.stdout.write(`${JSON.stringify(frame)}\n`); }
|
|
6
|
+
export async function boundedBody(response, max = MAX_REALTIME_SDP_BYTES) {
|
|
7
|
+
const reader = response.body?.getReader();
|
|
8
|
+
if (!reader)
|
|
9
|
+
return '';
|
|
10
|
+
const chunks = [];
|
|
11
|
+
let size = 0;
|
|
12
|
+
try {
|
|
13
|
+
while (true) {
|
|
14
|
+
const item = await reader.read();
|
|
15
|
+
if (item.done)
|
|
16
|
+
break;
|
|
17
|
+
size += item.value.length;
|
|
18
|
+
if (size > max)
|
|
19
|
+
throw new Error('Voice answer exceeded its limit.');
|
|
20
|
+
chunks.push(item.value);
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
catch (error) {
|
|
24
|
+
await reader.cancel().catch(() => { });
|
|
25
|
+
throw error;
|
|
26
|
+
}
|
|
27
|
+
finally {
|
|
28
|
+
reader.releaseLock();
|
|
29
|
+
}
|
|
30
|
+
const bytes = new Uint8Array(size);
|
|
31
|
+
let offset = 0;
|
|
32
|
+
for (const chunk of chunks) {
|
|
33
|
+
bytes.set(chunk, offset);
|
|
34
|
+
offset += chunk.length;
|
|
35
|
+
}
|
|
36
|
+
return new TextDecoder().decode(bytes);
|
|
37
|
+
}
|
|
38
|
+
export function createChatgptAdapter(options) {
|
|
39
|
+
const fence = responseFence();
|
|
40
|
+
const lifetime = new AbortController();
|
|
41
|
+
let offered = false, closed = false;
|
|
42
|
+
const safe = (text) => cleanProse(text, 'Voice could not complete that request.', 4000, options.redact);
|
|
43
|
+
const delegations = new Map(), turns = new Map();
|
|
44
|
+
const send = (value) => emit({ type: 'realtime.webrtc.data', data: JSON.stringify(value) });
|
|
45
|
+
const append = (text, id) => {
|
|
46
|
+
const chunks = [];
|
|
47
|
+
let chunk = '';
|
|
48
|
+
for (const char of safe(text).slice(0, 8000)) {
|
|
49
|
+
if (Buffer.byteLength(chunk + char) > 500) {
|
|
50
|
+
chunks.push(chunk);
|
|
51
|
+
chunk = '';
|
|
52
|
+
}
|
|
53
|
+
chunk += char;
|
|
54
|
+
}
|
|
55
|
+
chunks.push(chunk);
|
|
56
|
+
for (const text of chunks)
|
|
57
|
+
send({ type: id ? 'delegation.context.append' : 'session.context.append', ...(id ? { delegation_item_id: id } : {}), channel: 'speakable', content: [{ type: 'input_text', text }] });
|
|
58
|
+
};
|
|
59
|
+
const close = (reason = 'Voice ended.', retryable = false) => { if (closed)
|
|
60
|
+
return; closed = true; fence.interrupt(); lifetime.abort(); options.bridge.close(); emit({ type: 'realtime.closed', reason: safe(reason), ...(retryable ? { retryable: true } : {}) }); };
|
|
61
|
+
const signalOffer = async (sdp) => {
|
|
62
|
+
if (offered)
|
|
63
|
+
throw new Error('Duplicate voice offer.');
|
|
64
|
+
offered = true;
|
|
65
|
+
const endpoint = options.endpoint ?? CHATGPT_SIGNALING_URL;
|
|
66
|
+
const url = new URL(endpoint);
|
|
67
|
+
if (endpoint !== CHATGPT_SIGNALING_URL && !['127.0.0.1', '[::1]', 'localhost'].includes(url.hostname))
|
|
68
|
+
throw new Error('Unsupported voice signaling origin.');
|
|
69
|
+
const response = await fetch(url, {
|
|
70
|
+
method: 'POST', redirect: 'error', signal: AbortSignal.any([lifetime.signal, AbortSignal.timeout(20000)]),
|
|
71
|
+
headers: { Authorization: `Bearer ${options.key}`, 'chatgpt-account-id': options.accountId, originator: 'byokit', 'User-Agent': 'byokit', 'OpenAI-Alpha': 'quicksilver=v2', 'content-type': 'application/json' },
|
|
72
|
+
body: JSON.stringify({ sdp, session: { model: options.model ?? 'gpt-live-1-codex', instructions: options.instructions, audio: { output: { voice: options.voice ?? 'sol' } }, delegation: { type: 'client', ack_filler: false } } }),
|
|
73
|
+
});
|
|
74
|
+
const answer = await boundedBody(response);
|
|
75
|
+
if (!response.ok) {
|
|
76
|
+
close(response.status === 401 ? 'signed-out' : response.status === 403 ? 'not-included' : response.status === 429 ? 'rate-limited' : 'network');
|
|
77
|
+
return;
|
|
78
|
+
}
|
|
79
|
+
if (!answer.startsWith('v=0') || answer.includes('\0'))
|
|
80
|
+
throw new Error('Invalid voice answer.');
|
|
81
|
+
if (!closed)
|
|
82
|
+
emit({ type: 'realtime.webrtc.answer', sdp: answer });
|
|
83
|
+
};
|
|
84
|
+
const data = async (raw) => {
|
|
85
|
+
// Provider event vocabulary stays inside the credential child.
|
|
86
|
+
const event = JSON.parse(raw);
|
|
87
|
+
if (event.type === 'turn.done' && typeof event.turn?.transcript === 'string') {
|
|
88
|
+
const role = event.turn.role === 'assistant' ? 'agent' : 'user';
|
|
89
|
+
if (role === 'user') {
|
|
90
|
+
fence.begin();
|
|
91
|
+
turns.clear();
|
|
92
|
+
emit({ type: 'realtime.audio.clear' });
|
|
93
|
+
}
|
|
94
|
+
emit({ type: 'realtime.transcript', role, text: safe(event.turn.transcript) });
|
|
95
|
+
if (role === 'agent')
|
|
96
|
+
options.bridge.answered();
|
|
97
|
+
options.bridge.state(role === 'agent' ? 'connected' : 'thinking');
|
|
98
|
+
}
|
|
99
|
+
else if (event.type === 'session.started' || event.type === 'session.updated')
|
|
100
|
+
options.bridge.state('connected');
|
|
101
|
+
else if (event.type === 'output_audio.delta')
|
|
102
|
+
options.bridge.state('speaking');
|
|
103
|
+
else if (event.type === 'error')
|
|
104
|
+
close(safe(event.message ?? event.error?.message));
|
|
105
|
+
else if (event.type === 'delegation.created' && event.item?.type === 'delegation' && event.item.target === 'client') {
|
|
106
|
+
const id = event.item.id;
|
|
107
|
+
const request = Array.isArray(event.item.content) ? event.item.content.filter((item) => item.type === 'input_text' && typeof item.text === 'string').map((item) => item.text).join('\n') : '';
|
|
108
|
+
if (typeof id !== 'string' || !id || id.length > 128 || Buffer.byteLength(request) > 16000 || delegations.size >= 128 || delegations.has(id))
|
|
109
|
+
return;
|
|
110
|
+
const turn = event.item.user_bidi_turn_id;
|
|
111
|
+
const share = typeof turn === 'string' && turn.trim() && turn.length <= 128 ? JSON.stringify([turn.trim(), request.trim()]) : undefined;
|
|
112
|
+
const signal = fence.signal;
|
|
113
|
+
let promise = share ? turns.get(share) : undefined;
|
|
114
|
+
if (!promise) {
|
|
115
|
+
promise = options.bridge.run('delegate', { request }, `codex:${id}`, AbortSignal.any([lifetime.signal, signal]));
|
|
116
|
+
if (share)
|
|
117
|
+
turns.set(share, promise);
|
|
118
|
+
}
|
|
119
|
+
delegations.set(id, promise);
|
|
120
|
+
const result = await promise;
|
|
121
|
+
if (!closed && !signal.aborted)
|
|
122
|
+
append(result, id);
|
|
123
|
+
}
|
|
124
|
+
};
|
|
125
|
+
emit({ type: 'realtime.webrtc.start', dataChannelLabel: 'oai-events' });
|
|
126
|
+
return {
|
|
127
|
+
receive(frame) {
|
|
128
|
+
if (closed)
|
|
129
|
+
return;
|
|
130
|
+
if (frame.type === 'realtime.webrtc.offer')
|
|
131
|
+
void signalOffer(frame.sdp).catch(() => close('Voice signaling failed.'));
|
|
132
|
+
else if (frame.type === 'realtime.webrtc.data')
|
|
133
|
+
void data(frame.data).catch(() => close('Invalid voice message.'));
|
|
134
|
+
else if (frame.type === 'realtime.say')
|
|
135
|
+
append(frame.text);
|
|
136
|
+
else if (frame.type === 'realtime.control' && frame.action === 'interrupt') {
|
|
137
|
+
send({ type: 'session.close' });
|
|
138
|
+
close('Voice interrupted.', true);
|
|
139
|
+
}
|
|
140
|
+
else if (frame.type === 'realtime.control' && frame.action === 'stop') {
|
|
141
|
+
send({ type: 'session.close' });
|
|
142
|
+
close();
|
|
143
|
+
}
|
|
144
|
+
}, close,
|
|
145
|
+
};
|
|
146
|
+
}
|
package/dist/child.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
package/dist/child.js
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
|
|
2
|
+
if (typeof path === "string" && /^\.\.?\//.test(path)) {
|
|
3
|
+
return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
|
|
4
|
+
return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
|
|
5
|
+
});
|
|
6
|
+
}
|
|
7
|
+
return path;
|
|
8
|
+
};
|
|
9
|
+
import { createInterface } from 'node:readline';
|
|
10
|
+
import { toolBridge } from "./tools.js";
|
|
11
|
+
import { parseRealtimeClientFrame } from "./frames.js";
|
|
12
|
+
import { createChatgptAdapter } from "./chatgpt.js";
|
|
13
|
+
const input = createInterface({ input: process.stdin, crlfDelay: Infinity });
|
|
14
|
+
let adapter;
|
|
15
|
+
const pending = new Map();
|
|
16
|
+
const emit = (frame) => { process.stdout.write(`${JSON.stringify(frame)}\n`); };
|
|
17
|
+
let starting;
|
|
18
|
+
input.on('line', line => {
|
|
19
|
+
void (async () => {
|
|
20
|
+
if (!starting) {
|
|
21
|
+
const config = JSON.parse(line);
|
|
22
|
+
starting = (async () => {
|
|
23
|
+
const handlers = Object.fromEntries(config.tools.map(tool => [tool.name, (_args, context) => new Promise(resolve => {
|
|
24
|
+
const finish = (value) => { context.signal.removeEventListener('abort', abort); pending.delete(context.id); resolve(value); };
|
|
25
|
+
const abort = () => { process.stdout.write(`${JSON.stringify({ type: 'kit.tool.cancel', id: context.id })}\n`); finish('The request was cancelled.'); };
|
|
26
|
+
pending.set(context.id, finish);
|
|
27
|
+
context.signal.addEventListener('abort', abort, { once: true });
|
|
28
|
+
process.stdout.write(`${JSON.stringify({ type: 'kit.tool', name: tool.name, args: _args, id: context.id })}\n`);
|
|
29
|
+
})]));
|
|
30
|
+
const bridge = toolBridge({ tools: config.tools, handlers, emit, timeoutFor: () => 300000, failure: () => 'The request could not be completed.' });
|
|
31
|
+
const options = { ...config, bridge, redact: config.redact?.map(pattern => new RegExp(pattern.source, pattern.flags)) };
|
|
32
|
+
if (config.engine === 'chatgpt')
|
|
33
|
+
adapter = createChatgptAdapter({ ...options, accountId: config.accountId ?? '' });
|
|
34
|
+
else {
|
|
35
|
+
const module = await import(__rewriteRelativeImportExtension(`./providers/${config.engine}.${import.meta.url.endsWith('.ts') ? 'ts' : 'js'}`));
|
|
36
|
+
adapter = module.createAdapter(options);
|
|
37
|
+
}
|
|
38
|
+
})();
|
|
39
|
+
await starting;
|
|
40
|
+
return;
|
|
41
|
+
}
|
|
42
|
+
await starting;
|
|
43
|
+
const frame = JSON.parse(line);
|
|
44
|
+
if (frame.type === 'kit.tool.result')
|
|
45
|
+
pending.get(frame.id)?.(String(frame.output));
|
|
46
|
+
else
|
|
47
|
+
adapter?.receive(parseRealtimeClientFrame(frame));
|
|
48
|
+
})().catch(() => { emit({ type: 'realtime.closed', reason: 'Voice session could not start.' }); process.exit(1); });
|
|
49
|
+
});
|
|
50
|
+
input.on('close', () => { adapter?.close(); process.exit(0); });
|
package/dist/client.d.ts
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { RealtimeClientOptions } from './types.ts';
|
|
2
|
+
/** Provider-blind client with bounded reconnects and exclusive media ownership. */
|
|
3
|
+
export declare function realtimeClient(options: RealtimeClientOptions): {
|
|
4
|
+
stop: (reason?: string) => void;
|
|
5
|
+
interrupt(): void;
|
|
6
|
+
setMuted(value: boolean): void;
|
|
7
|
+
speak(text: string): void;
|
|
8
|
+
};
|