@vrealtime/server 0.0.0-stage → 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/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,5 @@
1
- # Temporary Holding Version
1
+ # @vrealtime/server
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ vRealTime server: attach any WebSocket, Node serve(), Cloudflare Workers and Durable Objects
4
+
5
+ Part of [vRealTime](https://github.com/austinchennn/vRT). Licensed under Apache-2.0.
@@ -0,0 +1,13 @@
1
+ import type { Capabilities } from '@vrealtime/core';
2
+ /**
3
+ * A protocol capability (spec/capabilities.json) this server implements. It is
4
+ * offered only when the agent's model can support it, e.g. argument streaming.
5
+ */
6
+ export interface CapabilityRule {
7
+ token: string;
8
+ available(model: Capabilities): boolean;
9
+ }
10
+ /** Every capability this server implements. None yet. */
11
+ export declare const CAPABILITY_RULES: readonly CapabilityRule[];
12
+ /** The tokens sessions of an agent with this model may negotiate. */
13
+ export declare function supportedCapabilities(model: Capabilities, rules?: readonly CapabilityRule[]): ReadonlySet<string>;
@@ -0,0 +1,6 @@
1
+ /** Every capability this server implements. None yet. */
2
+ export const CAPABILITY_RULES = [];
3
+ /** The tokens sessions of an agent with this model may negotiate. */
4
+ export function supportedCapabilities(model, rules = CAPABILITY_RULES) {
5
+ return new Set(rules.filter((rule) => rule.available(model)).map((rule) => rule.token));
6
+ }
@@ -0,0 +1,137 @@
1
+ import { type AgentDefinition, type AgentSession, type AudioFormat, type Clock, type SessionConfig } from '@vrealtime/core';
2
+ import { Inbox, Outbox, type ServerMessage, type Unsequenced, type WireAudioFormat } from '@vrealtime/protocol';
3
+ /**
4
+ * The only socket surface the server needs. Runtimes with event-style sockets
5
+ * (browsers, Deno, Workers, `ws`) can pass the socket as-is; callback-style
6
+ * runtimes (Bun) call `connection.receive()` and `connection.closed()` instead.
7
+ */
8
+ export interface WebSocketLike {
9
+ send(data: string | Uint8Array): void;
10
+ close(code?: number, reason?: string): void;
11
+ /** Bytes queued but not yet sent; enables backpressure when present. */
12
+ readonly bufferedAmount?: number;
13
+ addEventListener?(type: 'message' | 'close', listener: (event: {
14
+ data?: unknown;
15
+ }) => void): void;
16
+ }
17
+ /** Who is connected. `id` identifies the subject: a resume must come from the same `id`. */
18
+ export interface Principal {
19
+ id: string;
20
+ [key: string]: unknown;
21
+ }
22
+ export interface AuthRequest {
23
+ /** `hello.auth`: a short-lived token sent in the first message, never in the URL. */
24
+ token: string | undefined;
25
+ /** `hello.context`, e.g. the document the app wants to work on. */
26
+ context: unknown;
27
+ /** Set when the client is resuming a session. */
28
+ sessionId: string | undefined;
29
+ /** Headers of the upgrade request, when the edge has them (cookies, origin). */
30
+ headers: Headers | undefined;
31
+ }
32
+ export interface AttachOptions {
33
+ /**
34
+ * Called for every `hello`, new or resumed. Return a principal to accept, or
35
+ * `null` / `undefined` / `false` (or throw) to refuse with `UNAUTHORIZED`.
36
+ * Without it every connection is accepted.
37
+ */
38
+ authenticate?: (request: AuthRequest) => Principal | null | undefined | false | Promise<Principal | null | undefined | false>;
39
+ /** Per-session config for new sessions (instructions, voice, transcription vocabulary...), from the principal and `hello.context`. */
40
+ configure?: (principal: Principal | undefined, hello: {
41
+ context: unknown;
42
+ }) => Partial<SessionConfig> | Promise<Partial<SessionConfig>>;
43
+ /** How long a session survives without a socket, waiting for a resume. Default 30 s. */
44
+ resumeWindowMs?: number;
45
+ /** Close a socket that sent nothing (not even `ping`) for this long. Default 45 s. */
46
+ heartbeatTimeoutMs?: number;
47
+ /** Queue outgoing frames while `bufferedAmount` exceeds this. Default 256 KiB. */
48
+ highWaterMark?: number;
49
+ /** Receives `context` messages and `hello.context` from the app. */
50
+ onContext?: (context: unknown, session: AgentSession) => void;
51
+ clock?: Clock;
52
+ }
53
+ export interface Connection {
54
+ /** Feed one incoming WebSocket message (text or binary). */
55
+ receive(data: unknown): void;
56
+ /** Tell the server the socket closed. */
57
+ closed(): void;
58
+ readonly sessionId: string | undefined;
59
+ }
60
+ export declare function toCoreFormat(format: WireAudioFormat | undefined): AudioFormat | undefined;
61
+ export declare function toWireFormat(format: AudioFormat): WireAudioFormat;
62
+ /** One agent session and everything that must survive a reconnect. */
63
+ declare class LiveSession {
64
+ #private;
65
+ private readonly hub;
66
+ readonly principal: Principal | undefined;
67
+ readonly id: `${string}-${string}-${string}-${string}-${string}`;
68
+ readonly outbox: Outbox<ServerMessage>;
69
+ readonly inbox: Inbox;
70
+ session: AgentSession;
71
+ input: AudioFormat;
72
+ output: AudioFormat;
73
+ /** Negotiated when the session starts; fixed for its lifetime, resumes included. */
74
+ capabilities: readonly string[];
75
+ socket: SocketConnection | undefined;
76
+ expiry: unknown;
77
+ constructor(hub: Hub, principal: Principal | undefined);
78
+ bind(agentSession: AgentSession): void;
79
+ send(message: Unsequenced<ServerMessage>, epoch?: number): void;
80
+ /** Opens the session on the bound socket; `resumedFrom` is set on a resume. */
81
+ sendReady(resumedFrom?: number): void;
82
+ /** Re-sends everything after the client's last seen seq. False when that is no longer possible. */
83
+ resend(lastSeen: number): boolean;
84
+ detach(): void;
85
+ flush(): void;
86
+ }
87
+ declare class SocketConnection implements Connection {
88
+ #private;
89
+ private readonly hub;
90
+ private readonly socket;
91
+ private readonly headers?;
92
+ constructor(hub: Hub, socket: WebSocketLike, headers?: Headers | undefined);
93
+ get sessionId(): string | undefined;
94
+ congested(): boolean;
95
+ send(data: string | Uint8Array): void;
96
+ close(code: number, reason: string): void;
97
+ receive(data: unknown): void;
98
+ closed(): void;
99
+ }
100
+ /** Shares sessions between sockets, so a reconnecting app can resume. */
101
+ export declare class Hub {
102
+ #private;
103
+ readonly agent: AgentDefinition;
104
+ readonly options: AttachOptions;
105
+ readonly clock: Clock;
106
+ readonly highWaterMark: number;
107
+ readonly heartbeatTimeoutMs: number;
108
+ /** Protocol capabilities sessions may negotiate: what this server implements and the agent's model supports. */
109
+ readonly capabilities: ReadonlySet<string>;
110
+ constructor(agent: AgentDefinition, options?: AttachOptions);
111
+ /** `headers` (of the upgrade request) are passed to `authenticate`. */
112
+ attach(socket: WebSocketLike, info?: {
113
+ headers?: Headers;
114
+ }): Connection;
115
+ /** Live sessions, connected or waiting for a resume. */
116
+ get size(): number;
117
+ close(): Promise<void>;
118
+ /** @internal */
119
+ adopt(live: LiveSession): void;
120
+ /** @internal */
121
+ find(id: string): LiveSession | undefined;
122
+ /** @internal */
123
+ forget(live: LiveSession): void;
124
+ /** @internal Keeps a socketless session for `resumeWindowMs`, then closes it. */
125
+ park(live: LiveSession): void;
126
+ /** @internal */
127
+ unpark(live: LiveSession): void;
128
+ }
129
+ /**
130
+ * Serves `agent` over one WebSocket using protocol v1. Sockets attached for the
131
+ * same agent share a hub, so a reconnecting app can resume its session.
132
+ * Options apply when the agent's hub is first created.
133
+ */
134
+ export declare function attach(agent: AgentDefinition, socket: WebSocketLike, options?: AttachOptions, info?: {
135
+ headers?: Headers;
136
+ }): Connection;
137
+ export {};
package/dist/index.js ADDED
@@ -0,0 +1,474 @@
1
+ import { startSession, } from '@vrealtime/core';
2
+ import { Inbox, Outbox, decodeAudioFrame, decodeClientMessage, encodeAudioFrame, encodeMessage, negotiateCapabilities, PROTOCOL_VERSION, } from '@vrealtime/protocol';
3
+ import { supportedCapabilities } from './capabilities.js';
4
+ const PCM24 = { encoding: 'pcm16', sampleRate: 24000, channels: 1 };
5
+ const REFUSED = Symbol('refused');
6
+ const FLUSH_INTERVAL_MS = 10;
7
+ const OUTPUT = 2;
8
+ const INPUT = 1;
9
+ const systemClock = {
10
+ now: () => performance.now(),
11
+ setTimeout: (run, ms) => setTimeout(run, ms),
12
+ clearTimeout: (id) => clearTimeout(id),
13
+ };
14
+ export function toCoreFormat(format) {
15
+ if (format === undefined)
16
+ return undefined;
17
+ if (format.encoding === 'pcmu')
18
+ return { encoding: 'pcmu' };
19
+ if (format.encoding === 'opus')
20
+ return { encoding: 'opus', frameMs: 20 };
21
+ const rate = format.sampleRate;
22
+ return rate === 8000 || rate === 16000 || rate === 24000 || rate === 48000 ? { encoding: 'pcm16', sampleRate: rate, channels: 1 } : undefined;
23
+ }
24
+ export function toWireFormat(format) {
25
+ return format.encoding === 'pcm16' ? { encoding: 'pcm16', sampleRate: format.sampleRate } : { encoding: format.encoding };
26
+ }
27
+ function sameFormat(a, b) {
28
+ return a.encoding === b.encoding && (a.encoding !== 'pcm16' || (b.encoding === 'pcm16' && a.sampleRate === b.sampleRate));
29
+ }
30
+ /** Use the app's format when the model takes it as-is (pass-through), otherwise 24 kHz PCM16. */
31
+ function negotiate(requested, supported) {
32
+ const format = toCoreFormat(requested);
33
+ if (format && supported.some((s) => sameFormat(s, format)))
34
+ return format;
35
+ return supported.find((s) => sameFormat(s, PCM24)) ?? supported[0] ?? PCM24;
36
+ }
37
+ /** One agent session and everything that must survive a reconnect. */
38
+ class LiveSession {
39
+ hub;
40
+ principal;
41
+ id = crypto.randomUUID();
42
+ outbox = new Outbox();
43
+ inbox = new Inbox();
44
+ session;
45
+ input = PCM24;
46
+ output = PCM24;
47
+ /** Negotiated when the session starts; fixed for its lifetime, resumes included. */
48
+ capabilities = [];
49
+ socket;
50
+ expiry;
51
+ #audioSeq = 0;
52
+ #audioItem;
53
+ #queue = [];
54
+ #flushTimer;
55
+ constructor(hub, principal) {
56
+ this.hub = hub;
57
+ this.principal = principal;
58
+ }
59
+ bind(agentSession) {
60
+ this.session = agentSession;
61
+ agentSession.on('turn.state', (e) => this.send({ type: 'turn.state', turnId: e.turnId, epoch: e.epoch, state: e.state }));
62
+ agentSession.on('transcript', (e) => this.send({ type: 'transcript', role: e.role, itemId: e.itemId, text: e.text, final: e.final }));
63
+ agentSession.on('text', (e) => this.send({ type: 'text', responseId: e.responseId, delta: e.delta }));
64
+ agentSession.on('audio', (e) => this.#audio(e));
65
+ // `arguments` and `preview` are required members on the wire: a missing value is sent as null.
66
+ agentSession.on('tool.call', (e) => this.send({ type: 'tool.call', callId: e.callId, epoch: e.epoch, turnId: e.turnId, name: e.name, arguments: e.arguments ?? null }));
67
+ agentSession.on('tool.call.delta', (e) => this.send({ type: 'tool.call.delta', callId: e.callId, epoch: e.epoch, name: e.name, preview: { argumentsDelta: e.argumentsDelta } }));
68
+ agentSession.on('tool.preview', (e) => this.send({ type: 'tool.call.delta', callId: e.callId, epoch: e.epoch, name: e.name, preview: e.preview ?? null }));
69
+ agentSession.on('interrupted', (e) => {
70
+ this.#dropAudio(e.epoch);
71
+ this.send({ type: 'interrupted', epoch: e.epoch });
72
+ });
73
+ agentSession.on('error', (e) => this.send({ type: 'error', code: 'AGENT_ERROR', message: e.error.message, recoverable: e.recoverable }));
74
+ agentSession.on('closed', () => {
75
+ this.hub.forget(this);
76
+ this.socket?.close(1000, 'session closed');
77
+ });
78
+ }
79
+ send(message, epoch) {
80
+ const stamped = this.outbox.stamp(message);
81
+ this.#write(encodeMessage(stamped), epoch);
82
+ }
83
+ /** Opens the session on the bound socket; `resumedFrom` is set on a resume. */
84
+ sendReady(resumedFrom) {
85
+ this.send({
86
+ type: 'ready',
87
+ sessionId: this.id,
88
+ input: toWireFormat(this.input),
89
+ output: toWireFormat(this.output),
90
+ ...(resumedFrom !== undefined ? { resumedFrom } : {}),
91
+ ...(this.capabilities.length > 0 ? { capabilities: [...this.capabilities] } : {}),
92
+ });
93
+ }
94
+ /** Re-sends everything after the client's last seen seq. False when that is no longer possible. */
95
+ resend(lastSeen) {
96
+ const missed = this.outbox.resendFrom(lastSeen);
97
+ if (missed === undefined)
98
+ return false;
99
+ for (const message of missed)
100
+ this.#write(encodeMessage(message));
101
+ return true;
102
+ }
103
+ detach() {
104
+ this.socket = undefined;
105
+ this.#queue = [];
106
+ this.#audioItem = undefined;
107
+ }
108
+ flush() {
109
+ this.#flushTimer = undefined;
110
+ const socket = this.socket;
111
+ if (!socket) {
112
+ this.#queue = [];
113
+ return;
114
+ }
115
+ while (this.#queue.length > 0 && !socket.congested())
116
+ socket.send(this.#queue.shift().data);
117
+ if (this.#queue.length > 0)
118
+ this.#scheduleFlush();
119
+ }
120
+ #audio(event) {
121
+ if (!this.socket)
122
+ return;
123
+ if (event.itemId !== this.#audioItem) {
124
+ this.#audioItem = event.itemId;
125
+ this.send({ type: 'audio.start', itemId: event.itemId, responseId: event.responseId, epoch: event.epoch }, event.epoch);
126
+ }
127
+ this.#write(encodeAudioFrame(OUTPUT, this.#audioSeq++, event.chunk.data), event.epoch);
128
+ }
129
+ /** Frames keep their order: once anything is queued, everything queues behind it. */
130
+ #write(data, epoch) {
131
+ const socket = this.socket;
132
+ if (!socket)
133
+ return;
134
+ if (this.#queue.length === 0 && !socket.congested()) {
135
+ socket.send(data);
136
+ return;
137
+ }
138
+ this.#queue.push(epoch === undefined ? { data } : { data, epoch });
139
+ this.#scheduleFlush();
140
+ }
141
+ #dropAudio(closedEpoch) {
142
+ this.#queue = this.#queue.filter((item) => item.epoch === undefined || item.epoch > closedEpoch);
143
+ this.#audioItem = undefined;
144
+ }
145
+ #scheduleFlush() {
146
+ if (this.#flushTimer === undefined)
147
+ this.#flushTimer = this.hub.clock.setTimeout(() => this.flush(), FLUSH_INTERVAL_MS);
148
+ }
149
+ }
150
+ class SocketConnection {
151
+ hub;
152
+ socket;
153
+ headers;
154
+ #live;
155
+ #starting;
156
+ #pending = [];
157
+ #closed = false;
158
+ #lastSeen;
159
+ #heartbeat;
160
+ #ackScheduled = false;
161
+ constructor(hub, socket, headers) {
162
+ this.hub = hub;
163
+ this.socket = socket;
164
+ this.headers = headers;
165
+ this.#lastSeen = hub.clock.now();
166
+ this.#checkHeartbeat();
167
+ socket.addEventListener?.('message', (event) => this.receive(event.data));
168
+ socket.addEventListener?.('close', () => this.closed());
169
+ }
170
+ get sessionId() {
171
+ return this.#live?.id;
172
+ }
173
+ congested() {
174
+ return (this.socket.bufferedAmount ?? 0) > this.hub.highWaterMark;
175
+ }
176
+ send(data) {
177
+ if (!this.#closed)
178
+ this.socket.send(data);
179
+ }
180
+ close(code, reason) {
181
+ if (this.#closed)
182
+ return;
183
+ this.socket.close(code, reason);
184
+ this.closed();
185
+ }
186
+ receive(data) {
187
+ if (this.#closed)
188
+ return;
189
+ this.#lastSeen = this.hub.clock.now();
190
+ if (typeof data !== 'string') {
191
+ this.#receiveAudio(data);
192
+ return;
193
+ }
194
+ const decoded = decodeClientMessage(data);
195
+ if (!decoded.ok) {
196
+ this.#error(decoded.error.code, decoded.error.message, true);
197
+ return;
198
+ }
199
+ const message = decoded.message;
200
+ if (message.type === 'ping') {
201
+ this.#sendDirect({ type: 'pong' });
202
+ return;
203
+ }
204
+ if (message.type === 'hello') {
205
+ void this.#hello(message);
206
+ return;
207
+ }
208
+ if (this.#starting || !this.#live) {
209
+ if (this.#starting)
210
+ this.#pending.push(message);
211
+ else
212
+ this.#error('NO_SESSION', 'Send hello first', false);
213
+ return;
214
+ }
215
+ this.#handle(this.#live, message);
216
+ }
217
+ closed() {
218
+ if (this.#closed)
219
+ return;
220
+ this.#closed = true;
221
+ this.hub.clock.clearTimeout(this.#heartbeat);
222
+ const live = this.#live;
223
+ if (live?.socket === this) {
224
+ live.detach();
225
+ this.hub.park(live);
226
+ }
227
+ }
228
+ #receiveAudio(data) {
229
+ const bytes = data instanceof Uint8Array ? data : data instanceof ArrayBuffer ? new Uint8Array(data) : undefined;
230
+ const frame = bytes && decodeAudioFrame(bytes);
231
+ if (!frame || frame.kind !== INPUT) {
232
+ this.#error('MALFORMED', 'Invalid audio frame', true);
233
+ return;
234
+ }
235
+ const live = this.#live;
236
+ if (live && !this.#starting)
237
+ live.session.sendAudio({ data: frame.payload, format: live.input });
238
+ }
239
+ async #hello(hello) {
240
+ if (this.#live || this.#starting) {
241
+ this.#error('DUPLICATE_HELLO', 'hello was already received', true);
242
+ return;
243
+ }
244
+ // Messages that arrive while authenticating or starting are queued in order.
245
+ let done;
246
+ this.#starting = new Promise((resolve) => { done = resolve; });
247
+ try {
248
+ const principal = await this.#authenticate(hello);
249
+ if (this.#closed)
250
+ return;
251
+ if (principal === REFUSED) {
252
+ this.#error('UNAUTHORIZED', 'Authentication failed', false);
253
+ this.close(4401, 'unauthorized');
254
+ return;
255
+ }
256
+ const live = hello.sessionId !== undefined ? this.#resume(hello, principal) : await this.#start(hello, principal);
257
+ if (!live)
258
+ return;
259
+ if (hello.context !== undefined)
260
+ this.hub.options.onContext?.(hello.context, live.session);
261
+ for (const message of this.#pending.splice(0))
262
+ this.#handle(live, message);
263
+ }
264
+ finally {
265
+ this.#starting = undefined;
266
+ done();
267
+ }
268
+ }
269
+ async #authenticate(hello) {
270
+ const authenticate = this.hub.options.authenticate;
271
+ if (!authenticate)
272
+ return undefined;
273
+ try {
274
+ const principal = await authenticate({ token: hello.auth, context: hello.context, sessionId: hello.sessionId, headers: this.headers });
275
+ return principal ? principal : REFUSED;
276
+ }
277
+ catch {
278
+ return REFUSED;
279
+ }
280
+ }
281
+ async #start(hello, principal) {
282
+ const live = new LiveSession(this.hub, principal);
283
+ const supported = this.hub.agent.model.capabilities;
284
+ live.input = negotiate(hello.input, supported.input.formats);
285
+ live.output = negotiate(hello.output, supported.output.formats);
286
+ live.capabilities = negotiateCapabilities(hello.capabilities, this.hub.capabilities);
287
+ try {
288
+ const configured = (await this.hub.options.configure?.(principal, { context: hello.context })) ?? {};
289
+ const session = await startSession(this.hub.agent, {
290
+ clientTools: hello.tools,
291
+ config: { ...configured, inputFormat: live.input, outputFormat: live.output },
292
+ clock: this.hub.clock,
293
+ data: principal,
294
+ });
295
+ live.bind(session);
296
+ }
297
+ catch (error) {
298
+ this.#error('START_FAILED', error instanceof Error ? error.message : String(error), false);
299
+ this.close(1011, 'session start failed');
300
+ return undefined;
301
+ }
302
+ this.hub.adopt(live);
303
+ if (this.#closed) {
304
+ // The socket went away while the model was connecting; park so a resume can still find it.
305
+ this.hub.park(live);
306
+ return undefined;
307
+ }
308
+ this.#bind(live);
309
+ live.sendReady();
310
+ live.resend(0); // anything the session emitted before the socket was bound
311
+ return live;
312
+ }
313
+ #resume(hello, principal) {
314
+ const live = this.hub.find(hello.sessionId);
315
+ // An unknown session and someone else's session get the same answer.
316
+ if (!live || live.principal?.id !== principal?.id) {
317
+ this.#error('RESUME_FAILED', 'Unknown or expired session', false);
318
+ this.close(4404, 'unknown session');
319
+ return undefined;
320
+ }
321
+ live.socket?.close(4000, 'replaced by a newer connection');
322
+ this.#bind(live);
323
+ if (live.session.closed)
324
+ return undefined;
325
+ live.sendReady(live.inbox.lastSeq);
326
+ if (!live.resend(hello.resumeFrom ?? 0)) {
327
+ this.#error('RESUME_FAILED', 'Cannot resend from resumeFrom: those messages were dropped or never sent', false);
328
+ void live.session.close();
329
+ return undefined;
330
+ }
331
+ return live;
332
+ }
333
+ #bind(live) {
334
+ this.hub.unpark(live);
335
+ this.#live = live;
336
+ live.socket = this;
337
+ }
338
+ #handle(live, message) {
339
+ if (message.type === 'ack') {
340
+ live.outbox.ack(message.upTo);
341
+ return;
342
+ }
343
+ if (!live.inbox.accept(message)) {
344
+ this.#scheduleAck(live);
345
+ return;
346
+ }
347
+ const session = live.session;
348
+ switch (message.type) {
349
+ case 'text':
350
+ session.sendText(message.text);
351
+ break;
352
+ case 'interrupt':
353
+ session.interrupt(message.reason);
354
+ break;
355
+ case 'playback':
356
+ session.playback(message.itemId, message.playedMs);
357
+ break;
358
+ case 'tool.result': {
359
+ const result = message.ok
360
+ ? { ok: true, output: message.output }
361
+ : { ok: false, code: message.code, message: message.message };
362
+ session.submitClientToolResult(message.callId, result);
363
+ break;
364
+ }
365
+ case 'context':
366
+ this.hub.options.onContext?.(message.context, session);
367
+ break;
368
+ }
369
+ this.#scheduleAck(live);
370
+ }
371
+ #scheduleAck(live) {
372
+ if (this.#ackScheduled)
373
+ return;
374
+ this.#ackScheduled = true;
375
+ queueMicrotask(() => {
376
+ this.#ackScheduled = false;
377
+ if (live.socket === this)
378
+ live.send({ type: 'ack', upTo: live.inbox.lastSeq });
379
+ });
380
+ }
381
+ #sendDirect(message) {
382
+ if (this.#live?.socket === this)
383
+ this.#live.send(message);
384
+ else
385
+ this.send(encodeMessage({ v: PROTOCOL_VERSION, seq: 0, ...message }));
386
+ }
387
+ #error(code, message, recoverable) {
388
+ this.#sendDirect({ type: 'error', code, message, recoverable });
389
+ }
390
+ #checkHeartbeat() {
391
+ const timeout = this.hub.heartbeatTimeoutMs;
392
+ this.#heartbeat = this.hub.clock.setTimeout(() => {
393
+ if (this.#closed)
394
+ return;
395
+ if (this.hub.clock.now() - this.#lastSeen >= timeout)
396
+ this.close(4408, 'heartbeat timeout');
397
+ else
398
+ this.#checkHeartbeat();
399
+ }, Math.max(1, timeout / 3));
400
+ }
401
+ }
402
+ /** Shares sessions between sockets, so a reconnecting app can resume. */
403
+ export class Hub {
404
+ agent;
405
+ options;
406
+ clock;
407
+ highWaterMark;
408
+ heartbeatTimeoutMs;
409
+ /** Protocol capabilities sessions may negotiate: what this server implements and the agent's model supports. */
410
+ capabilities;
411
+ #sessions = new Map();
412
+ constructor(agent, options = {}) {
413
+ this.agent = agent;
414
+ this.options = options;
415
+ this.capabilities = supportedCapabilities(agent.model.capabilities);
416
+ this.clock = options.clock ?? systemClock;
417
+ this.highWaterMark = options.highWaterMark ?? 256 * 1024;
418
+ this.heartbeatTimeoutMs = options.heartbeatTimeoutMs ?? 45_000;
419
+ }
420
+ /** `headers` (of the upgrade request) are passed to `authenticate`. */
421
+ attach(socket, info = {}) {
422
+ return new SocketConnection(this, socket, info.headers);
423
+ }
424
+ /** Live sessions, connected or waiting for a resume. */
425
+ get size() {
426
+ return this.#sessions.size;
427
+ }
428
+ async close() {
429
+ await Promise.all([...this.#sessions.values()].map((live) => live.session.close()));
430
+ this.#sessions.clear();
431
+ }
432
+ /** @internal */
433
+ adopt(live) {
434
+ this.#sessions.set(live.id, live);
435
+ }
436
+ /** @internal */
437
+ find(id) {
438
+ return this.#sessions.get(id);
439
+ }
440
+ /** @internal */
441
+ forget(live) {
442
+ this.unpark(live);
443
+ this.#sessions.delete(live.id);
444
+ }
445
+ /** @internal Keeps a socketless session for `resumeWindowMs`, then closes it. */
446
+ park(live) {
447
+ this.unpark(live);
448
+ live.expiry = this.clock.setTimeout(() => {
449
+ live.expiry = undefined;
450
+ if (!live.socket)
451
+ void live.session.close();
452
+ }, this.options.resumeWindowMs ?? 30_000);
453
+ }
454
+ /** @internal */
455
+ unpark(live) {
456
+ if (live.expiry !== undefined)
457
+ this.clock.clearTimeout(live.expiry);
458
+ live.expiry = undefined;
459
+ }
460
+ }
461
+ const hubs = new WeakMap();
462
+ /**
463
+ * Serves `agent` over one WebSocket using protocol v1. Sockets attached for the
464
+ * same agent share a hub, so a reconnecting app can resume its session.
465
+ * Options apply when the agent's hub is first created.
466
+ */
467
+ export function attach(agent, socket, options, info) {
468
+ let hub = hubs.get(agent);
469
+ if (!hub) {
470
+ hub = new Hub(agent, options);
471
+ hubs.set(agent, hub);
472
+ }
473
+ return hub.attach(socket, info);
474
+ }
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Microphone debug page served by `serve()` at `/`. A dependency-free protocol v1
3
+ * client: text and voice in, transcripts and audio out, a barge-in interrupt and
4
+ * one app-side tool (`set_accent_color`) behind an epoch gate.
5
+ */
6
+ export declare const DEBUG_PAGE = "<!doctype html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n<meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">\n<title>vRealTime debug</title>\n<style>\n :root { --accent: #2563eb; --bg: #fff; --fg: #111827; --muted: #6b7280; --line: #e5e7eb; color-scheme: light dark; }\n @media (prefers-color-scheme: dark) { :root { --bg: #0b0f17; --fg: #e5e7eb; --muted: #9ca3af; --line: #1f2937; } }\n body { margin: 0; background: var(--bg); color: var(--fg); font: 15px/1.5 system-ui, sans-serif; }\n main { max-width: 720px; margin: 0 auto; padding: 16px; }\n h1 { font-size: 20px; margin: 0 0 4px; color: var(--accent); }\n .muted { color: var(--muted); font-size: 13px; }\n .row { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; margin: 12px 0; }\n button { background: var(--accent); color: #fff; border: 0; border-radius: 6px; padding: 8px 14px; font: inherit; cursor: pointer; }\n button.secondary { background: transparent; color: var(--fg); border: 1px solid var(--line); }\n form { display: flex; gap: 8px; }\n input { flex: 1; min-width: 0; padding: 8px; border: 1px solid var(--line); border-radius: 6px; background: transparent; color: inherit; font: inherit; }\n #state { padding: 2px 8px; border-radius: 99px; border: 1px solid var(--accent); color: var(--accent); font-size: 13px; }\n #log { border-top: 1px solid var(--line); margin-top: 12px; padding-top: 8px; }\n #log p { margin: 6px 0; } .user { font-weight: 600; } .note { color: var(--muted); font-size: 13px; }\n</style>\n</head>\n<body>\n<main>\n <h1>vRealTime</h1>\n <div class=\"muted\" id=\"status\">connecting\u2026</div>\n <div class=\"row\">\n <button id=\"mic\">Start mic</button>\n <button id=\"stop\" class=\"secondary\">Interrupt</button>\n <span id=\"state\">idle</span>\n </div>\n <form id=\"form\"><input id=\"text\" placeholder=\"Type a message\" autocomplete=\"off\"><button>Send</button></form>\n <div id=\"log\"></div>\n</main>\n<script type=\"module\">\nconst RATE = 24000, FRAME = 480, TRANSIENT = ['hello', 'ack', 'ping'];\nconst $ = (id) => document.getElementById(id);\nlet seq = 0, lastSeq = 0, epoch = 0, closedEpoch = -1, audioSeq = 0;\n\nconst tools = {\n set_accent_color: {\n description: 'Set the page accent color to any CSS color.',\n parameters: { type: 'object', properties: { color: { type: 'string' } }, required: ['color'] },\n run: ({ color }) => { document.documentElement.style.setProperty('--accent', color); return { color }; },\n },\n};\n\nconst ws = new WebSocket(location.origin.replace(/^http/, 'ws') + location.pathname);\nws.binaryType = 'arraybuffer';\nconst send = (m) => { if (ws.readyState === 1) ws.send(JSON.stringify({ v: 1, seq: TRANSIENT.includes(m.type) ? 0 : ++seq, ...m })); };\nws.onopen = () => send({\n type: 'hello',\n tools: Object.entries(tools).map(([name, t]) => ({ name, description: t.description, parameters: t.parameters })),\n input: { encoding: 'pcm16', sampleRate: RATE }, output: { encoding: 'pcm16', sampleRate: RATE },\n});\nws.onclose = (e) => { $('status').textContent = 'disconnected (' + e.code + ')'; };\nsetInterval(() => { send({ type: 'ping' }); if (lastSeq) send({ type: 'ack', upTo: lastSeq }); }, 10000);\n\nconst lines = new Map();\nfunction line(id, role, text) {\n let el = lines.get(id);\n if (!el) { el = document.createElement('p'); el.className = role; $('log').append(el); lines.set(id, el); }\n el.textContent = (role === 'user' ? 'You: ' : 'Agent: ') + text;\n el.scrollIntoView({ block: 'end' });\n}\nfunction note(text) { const el = document.createElement('p'); el.className = 'note'; el.textContent = text; $('log').append(el); }\n\n// Playback: schedule PCM16 chunks back to back; track what was actually heard per item.\nlet ctx, playhead = 0, sources = [], item;\nconst audio = () => (ctx ??= new AudioContext({ sampleRate: RATE }));\nfunction play(bytes) {\n const c = audio(), n = bytes.byteLength >> 1, view = new DataView(bytes.buffer, bytes.byteOffset, n * 2);\n const buffer = c.createBuffer(1, n, RATE), data = buffer.getChannelData(0);\n for (let i = 0; i < n; i++) data[i] = view.getInt16(i * 2, true) / 32768;\n const src = c.createBufferSource();\n src.buffer = buffer; src.connect(c.destination);\n const at = Math.max(playhead, c.currentTime + 0.02);\n if (item.start === undefined) item.start = at;\n src.start(at); playhead = at + buffer.duration; item.end = playhead;\n sources.push(src); src.onended = () => { sources = sources.filter((s) => s !== src); };\n}\nfunction stopPlayback() {\n for (const s of sources) s.stop();\n sources = []; playhead = 0;\n if (item && item.start !== undefined) {\n const heard = Math.max(0, Math.min(audio().currentTime, item.end) - item.start) * 1000;\n send({ type: 'playback', itemId: item.id, playedMs: Math.round(heard) });\n }\n item = undefined;\n}\nfunction interrupt() {\n closedEpoch = Math.max(closedEpoch, epoch);\n stopPlayback();\n send({ type: 'interrupt', epoch, reason: 'user' });\n}\n\nasync function runTool(m) {\n const tool = tools[m.name];\n if (m.epoch <= closedEpoch) return send({ type: 'tool.result', callId: m.callId, epoch: m.epoch, ok: false, code: 'INTERRUPTED', message: 'interrupted' });\n if (!tool) return send({ type: 'tool.result', callId: m.callId, epoch: m.epoch, ok: false, code: 'FAILED', message: 'unknown tool' });\n try {\n const output = await tool.run(m.arguments);\n send({ type: 'tool.result', callId: m.callId, epoch: m.epoch, ok: true, output });\n note('tool ' + m.name + ' ' + JSON.stringify(m.arguments));\n } catch (e) {\n send({ type: 'tool.result', callId: m.callId, epoch: m.epoch, ok: false, code: 'FAILED', message: String(e) });\n }\n}\n\nws.onmessage = (e) => {\n if (typeof e.data !== 'string') {\n const bytes = new Uint8Array(e.data);\n if (bytes[0] === 2 && item) play(bytes.subarray(5));\n return;\n }\n const m = JSON.parse(e.data);\n if (m.seq > 0) { if (m.seq <= lastSeq) return; lastSeq = m.seq; }\n switch (m.type) {\n case 'ready': $('status').textContent = 'session ' + m.sessionId; break;\n case 'turn.state':\n epoch = Math.max(epoch, m.epoch); $('state').textContent = m.state;\n if (m.state === 'listening' && sources.length) stopPlayback();\n break;\n case 'transcript': line(m.itemId, m.role, m.text); break;\n case 'text': line(m.responseId, 'agent', ((lines.get(m.responseId)?.textContent ?? 'Agent: ').slice(7)) + m.delta); break;\n case 'audio.start': item = m.epoch > closedEpoch ? { id: m.itemId } : undefined; break;\n case 'tool.call': runTool(m); break;\n case 'interrupted': closedEpoch = Math.max(closedEpoch, m.epoch); stopPlayback(); note('interrupted'); break;\n case 'error': note('error ' + m.code + ': ' + m.message); break;\n }\n};\n\n$('form').onsubmit = (e) => {\n e.preventDefault();\n const text = $('text').value.trim();\n if (!text) return;\n stopPlayback(); line('local-' + seq, 'user', text); send({ type: 'text', text }); $('text').value = '';\n};\n$('stop').onclick = interrupt;\n\n// Microphone: AudioWorklet \u2192 20 ms PCM16 frames \u2192 [kind=1][seq u32 BE][payload].\nconst WORKLET = `class Capture extends AudioWorkletProcessor {\n constructor() { super(); this.buf = new Int16Array(${FRAME}); this.n = 0; }\n process(inputs) {\n const ch = inputs[0][0];\n if (ch) for (let i = 0; i < ch.length; i++) {\n const s = Math.max(-1, Math.min(1, ch[i]));\n this.buf[this.n++] = s < 0 ? s * 32768 : s * 32767;\n if (this.n === ${FRAME}) { this.port.postMessage(this.buf.buffer.slice(0)); this.n = 0; }\n }\n return true;\n }\n}\nregisterProcessor('vrt-capture', Capture);`;\nlet mic;\n$('mic').onclick = async () => {\n if (mic) { mic.getTracks().forEach((t) => t.stop()); mic = undefined; $('mic').textContent = 'Start mic'; return; }\n const c = audio();\n await c.resume();\n mic = await navigator.mediaDevices.getUserMedia({ audio: { echoCancellation: true, noiseSuppression: true, channelCount: 1 } });\n await c.audioWorklet.addModule(URL.createObjectURL(new Blob([WORKLET], { type: 'text/javascript' })));\n const node = new AudioWorkletNode(c, 'vrt-capture');\n node.port.onmessage = ({ data }) => {\n if (!mic || ws.readyState !== 1) return;\n const frame = new Uint8Array(5 + data.byteLength);\n frame[0] = 1; new DataView(frame.buffer).setUint32(1, audioSeq++ >>> 0); frame.set(new Uint8Array(data), 5);\n ws.send(frame);\n };\n c.createMediaStreamSource(mic).connect(node);\n $('mic').textContent = 'Stop mic';\n};\n</script>\n</body>\n</html>\n";
@@ -0,0 +1,181 @@
1
+ /**
2
+ * Microphone debug page served by `serve()` at `/`. A dependency-free protocol v1
3
+ * client: text and voice in, transcripts and audio out, a barge-in interrupt and
4
+ * one app-side tool (`set_accent_color`) behind an epoch gate.
5
+ */
6
+ export const DEBUG_PAGE = /* html */ `<!doctype html>
7
+ <html lang="en">
8
+ <head>
9
+ <meta charset="utf-8">
10
+ <meta name="viewport" content="width=device-width,initial-scale=1">
11
+ <title>vRealTime debug</title>
12
+ <style>
13
+ :root { --accent: #2563eb; --bg: #fff; --fg: #111827; --muted: #6b7280; --line: #e5e7eb; color-scheme: light dark; }
14
+ @media (prefers-color-scheme: dark) { :root { --bg: #0b0f17; --fg: #e5e7eb; --muted: #9ca3af; --line: #1f2937; } }
15
+ body { margin: 0; background: var(--bg); color: var(--fg); font: 15px/1.5 system-ui, sans-serif; }
16
+ main { max-width: 720px; margin: 0 auto; padding: 16px; }
17
+ h1 { font-size: 20px; margin: 0 0 4px; color: var(--accent); }
18
+ .muted { color: var(--muted); font-size: 13px; }
19
+ .row { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; margin: 12px 0; }
20
+ button { background: var(--accent); color: #fff; border: 0; border-radius: 6px; padding: 8px 14px; font: inherit; cursor: pointer; }
21
+ button.secondary { background: transparent; color: var(--fg); border: 1px solid var(--line); }
22
+ form { display: flex; gap: 8px; }
23
+ input { flex: 1; min-width: 0; padding: 8px; border: 1px solid var(--line); border-radius: 6px; background: transparent; color: inherit; font: inherit; }
24
+ #state { padding: 2px 8px; border-radius: 99px; border: 1px solid var(--accent); color: var(--accent); font-size: 13px; }
25
+ #log { border-top: 1px solid var(--line); margin-top: 12px; padding-top: 8px; }
26
+ #log p { margin: 6px 0; } .user { font-weight: 600; } .note { color: var(--muted); font-size: 13px; }
27
+ </style>
28
+ </head>
29
+ <body>
30
+ <main>
31
+ <h1>vRealTime</h1>
32
+ <div class="muted" id="status">connecting…</div>
33
+ <div class="row">
34
+ <button id="mic">Start mic</button>
35
+ <button id="stop" class="secondary">Interrupt</button>
36
+ <span id="state">idle</span>
37
+ </div>
38
+ <form id="form"><input id="text" placeholder="Type a message" autocomplete="off"><button>Send</button></form>
39
+ <div id="log"></div>
40
+ </main>
41
+ <script type="module">
42
+ const RATE = 24000, FRAME = 480, TRANSIENT = ['hello', 'ack', 'ping'];
43
+ const $ = (id) => document.getElementById(id);
44
+ let seq = 0, lastSeq = 0, epoch = 0, closedEpoch = -1, audioSeq = 0;
45
+
46
+ const tools = {
47
+ set_accent_color: {
48
+ description: 'Set the page accent color to any CSS color.',
49
+ parameters: { type: 'object', properties: { color: { type: 'string' } }, required: ['color'] },
50
+ run: ({ color }) => { document.documentElement.style.setProperty('--accent', color); return { color }; },
51
+ },
52
+ };
53
+
54
+ const ws = new WebSocket(location.origin.replace(/^http/, 'ws') + location.pathname);
55
+ ws.binaryType = 'arraybuffer';
56
+ const send = (m) => { if (ws.readyState === 1) ws.send(JSON.stringify({ v: 1, seq: TRANSIENT.includes(m.type) ? 0 : ++seq, ...m })); };
57
+ ws.onopen = () => send({
58
+ type: 'hello',
59
+ tools: Object.entries(tools).map(([name, t]) => ({ name, description: t.description, parameters: t.parameters })),
60
+ input: { encoding: 'pcm16', sampleRate: RATE }, output: { encoding: 'pcm16', sampleRate: RATE },
61
+ });
62
+ ws.onclose = (e) => { $('status').textContent = 'disconnected (' + e.code + ')'; };
63
+ setInterval(() => { send({ type: 'ping' }); if (lastSeq) send({ type: 'ack', upTo: lastSeq }); }, 10000);
64
+
65
+ const lines = new Map();
66
+ function line(id, role, text) {
67
+ let el = lines.get(id);
68
+ if (!el) { el = document.createElement('p'); el.className = role; $('log').append(el); lines.set(id, el); }
69
+ el.textContent = (role === 'user' ? 'You: ' : 'Agent: ') + text;
70
+ el.scrollIntoView({ block: 'end' });
71
+ }
72
+ function note(text) { const el = document.createElement('p'); el.className = 'note'; el.textContent = text; $('log').append(el); }
73
+
74
+ // Playback: schedule PCM16 chunks back to back; track what was actually heard per item.
75
+ let ctx, playhead = 0, sources = [], item;
76
+ const audio = () => (ctx ??= new AudioContext({ sampleRate: RATE }));
77
+ function play(bytes) {
78
+ const c = audio(), n = bytes.byteLength >> 1, view = new DataView(bytes.buffer, bytes.byteOffset, n * 2);
79
+ const buffer = c.createBuffer(1, n, RATE), data = buffer.getChannelData(0);
80
+ for (let i = 0; i < n; i++) data[i] = view.getInt16(i * 2, true) / 32768;
81
+ const src = c.createBufferSource();
82
+ src.buffer = buffer; src.connect(c.destination);
83
+ const at = Math.max(playhead, c.currentTime + 0.02);
84
+ if (item.start === undefined) item.start = at;
85
+ src.start(at); playhead = at + buffer.duration; item.end = playhead;
86
+ sources.push(src); src.onended = () => { sources = sources.filter((s) => s !== src); };
87
+ }
88
+ function stopPlayback() {
89
+ for (const s of sources) s.stop();
90
+ sources = []; playhead = 0;
91
+ if (item && item.start !== undefined) {
92
+ const heard = Math.max(0, Math.min(audio().currentTime, item.end) - item.start) * 1000;
93
+ send({ type: 'playback', itemId: item.id, playedMs: Math.round(heard) });
94
+ }
95
+ item = undefined;
96
+ }
97
+ function interrupt() {
98
+ closedEpoch = Math.max(closedEpoch, epoch);
99
+ stopPlayback();
100
+ send({ type: 'interrupt', epoch, reason: 'user' });
101
+ }
102
+
103
+ async function runTool(m) {
104
+ const tool = tools[m.name];
105
+ if (m.epoch <= closedEpoch) return send({ type: 'tool.result', callId: m.callId, epoch: m.epoch, ok: false, code: 'INTERRUPTED', message: 'interrupted' });
106
+ if (!tool) return send({ type: 'tool.result', callId: m.callId, epoch: m.epoch, ok: false, code: 'FAILED', message: 'unknown tool' });
107
+ try {
108
+ const output = await tool.run(m.arguments);
109
+ send({ type: 'tool.result', callId: m.callId, epoch: m.epoch, ok: true, output });
110
+ note('tool ' + m.name + ' ' + JSON.stringify(m.arguments));
111
+ } catch (e) {
112
+ send({ type: 'tool.result', callId: m.callId, epoch: m.epoch, ok: false, code: 'FAILED', message: String(e) });
113
+ }
114
+ }
115
+
116
+ ws.onmessage = (e) => {
117
+ if (typeof e.data !== 'string') {
118
+ const bytes = new Uint8Array(e.data);
119
+ if (bytes[0] === 2 && item) play(bytes.subarray(5));
120
+ return;
121
+ }
122
+ const m = JSON.parse(e.data);
123
+ if (m.seq > 0) { if (m.seq <= lastSeq) return; lastSeq = m.seq; }
124
+ switch (m.type) {
125
+ case 'ready': $('status').textContent = 'session ' + m.sessionId; break;
126
+ case 'turn.state':
127
+ epoch = Math.max(epoch, m.epoch); $('state').textContent = m.state;
128
+ if (m.state === 'listening' && sources.length) stopPlayback();
129
+ break;
130
+ case 'transcript': line(m.itemId, m.role, m.text); break;
131
+ case 'text': line(m.responseId, 'agent', ((lines.get(m.responseId)?.textContent ?? 'Agent: ').slice(7)) + m.delta); break;
132
+ case 'audio.start': item = m.epoch > closedEpoch ? { id: m.itemId } : undefined; break;
133
+ case 'tool.call': runTool(m); break;
134
+ case 'interrupted': closedEpoch = Math.max(closedEpoch, m.epoch); stopPlayback(); note('interrupted'); break;
135
+ case 'error': note('error ' + m.code + ': ' + m.message); break;
136
+ }
137
+ };
138
+
139
+ $('form').onsubmit = (e) => {
140
+ e.preventDefault();
141
+ const text = $('text').value.trim();
142
+ if (!text) return;
143
+ stopPlayback(); line('local-' + seq, 'user', text); send({ type: 'text', text }); $('text').value = '';
144
+ };
145
+ $('stop').onclick = interrupt;
146
+
147
+ // Microphone: AudioWorklet → 20 ms PCM16 frames → [kind=1][seq u32 BE][payload].
148
+ const WORKLET = \`class Capture extends AudioWorkletProcessor {
149
+ constructor() { super(); this.buf = new Int16Array(\${FRAME}); this.n = 0; }
150
+ process(inputs) {
151
+ const ch = inputs[0][0];
152
+ if (ch) for (let i = 0; i < ch.length; i++) {
153
+ const s = Math.max(-1, Math.min(1, ch[i]));
154
+ this.buf[this.n++] = s < 0 ? s * 32768 : s * 32767;
155
+ if (this.n === \${FRAME}) { this.port.postMessage(this.buf.buffer.slice(0)); this.n = 0; }
156
+ }
157
+ return true;
158
+ }
159
+ }
160
+ registerProcessor('vrt-capture', Capture);\`;
161
+ let mic;
162
+ $('mic').onclick = async () => {
163
+ if (mic) { mic.getTracks().forEach((t) => t.stop()); mic = undefined; $('mic').textContent = 'Start mic'; return; }
164
+ const c = audio();
165
+ await c.resume();
166
+ mic = await navigator.mediaDevices.getUserMedia({ audio: { echoCancellation: true, noiseSuppression: true, channelCount: 1 } });
167
+ await c.audioWorklet.addModule(URL.createObjectURL(new Blob([WORKLET], { type: 'text/javascript' })));
168
+ const node = new AudioWorkletNode(c, 'vrt-capture');
169
+ node.port.onmessage = ({ data }) => {
170
+ if (!mic || ws.readyState !== 1) return;
171
+ const frame = new Uint8Array(5 + data.byteLength);
172
+ frame[0] = 1; new DataView(frame.buffer).setUint32(1, audioSeq++ >>> 0); frame.set(new Uint8Array(data), 5);
173
+ ws.send(frame);
174
+ };
175
+ c.createMediaStreamSource(mic).connect(node);
176
+ $('mic').textContent = 'Stop mic';
177
+ };
178
+ </script>
179
+ </body>
180
+ </html>
181
+ `;
@@ -0,0 +1,23 @@
1
+ import type { AgentDefinition } from '@vrealtime/core';
2
+ import { Hub, type AttachOptions } from '../index.js';
3
+ export interface ServeOptions extends AttachOptions {
4
+ /** Default 8790; 0 picks a free port. */
5
+ port?: number;
6
+ /** Default `localhost`. */
7
+ host?: string;
8
+ /** Serve static files from this directory; its `index.html` replaces the debug page. */
9
+ publicDir?: string | URL;
10
+ /** Called once listening; logs the URL by default. */
11
+ onListening?: (url: string) => void;
12
+ }
13
+ export interface RunningServer {
14
+ url: string;
15
+ port: number;
16
+ hub: Hub;
17
+ close(): Promise<void>;
18
+ }
19
+ /**
20
+ * Serves `agent` on Node: WebSocket protocol v1 on every path, the microphone
21
+ * debug page (or `publicDir`) over HTTP. Needs the optional peer dependency `ws`.
22
+ */
23
+ export declare function serve(agent: AgentDefinition, options?: ServeOptions): Promise<RunningServer>;
@@ -0,0 +1,120 @@
1
+ /// <reference types="node" />
2
+ import { readFile } from 'node:fs/promises';
3
+ import { createServer } from 'node:http';
4
+ import { extname, resolve, sep } from 'node:path';
5
+ import { fileURLToPath } from 'node:url';
6
+ import { Hub } from '../index.js';
7
+ import { DEBUG_PAGE } from './debug-page.js';
8
+ const CONTENT_TYPES = {
9
+ '.html': 'text/html; charset=utf-8',
10
+ '.js': 'text/javascript; charset=utf-8',
11
+ '.mjs': 'text/javascript; charset=utf-8',
12
+ '.css': 'text/css; charset=utf-8',
13
+ '.json': 'application/json',
14
+ '.map': 'application/json',
15
+ '.svg': 'image/svg+xml',
16
+ '.png': 'image/png',
17
+ '.ico': 'image/x-icon',
18
+ '.wasm': 'application/wasm',
19
+ };
20
+ function toHeaders(req) {
21
+ const headers = new Headers();
22
+ for (const [name, value] of Object.entries(req.headers)) {
23
+ if (Array.isArray(value))
24
+ for (const v of value)
25
+ headers.append(name, v);
26
+ else if (value !== undefined)
27
+ headers.set(name, value);
28
+ }
29
+ return headers;
30
+ }
31
+ const utf8 = new TextDecoder();
32
+ function toBytes(data) {
33
+ if (Array.isArray(data))
34
+ return Buffer.concat(data);
35
+ return data instanceof ArrayBuffer ? new Uint8Array(data) : data;
36
+ }
37
+ /**
38
+ * Serves `agent` on Node: WebSocket protocol v1 on every path, the microphone
39
+ * debug page (or `publicDir`) over HTTP. Needs the optional peer dependency `ws`.
40
+ */
41
+ export async function serve(agent, options = {}) {
42
+ let ws;
43
+ try {
44
+ ws = await import('ws');
45
+ }
46
+ catch {
47
+ throw new Error('@vrealtime/server/node: serve() needs the optional peer dependency "ws" (npm i ws)');
48
+ }
49
+ const hub = new Hub(agent, options);
50
+ const publicDir = options.publicDir === undefined ? undefined : resolve(options.publicDir instanceof URL ? fileURLToPath(options.publicDir) : options.publicDir);
51
+ const wss = new ws.WebSocketServer({ noServer: true });
52
+ async function handle(req, res) {
53
+ if (req.method !== 'GET' && req.method !== 'HEAD') {
54
+ res.writeHead(405).end();
55
+ return;
56
+ }
57
+ const path = decodeURIComponent(new URL(req.url ?? '/', 'http://localhost').pathname);
58
+ if (publicDir !== undefined) {
59
+ const file = resolve(publicDir, `.${path.endsWith('/') ? `${path}index.html` : path}`);
60
+ if (file !== publicDir && !file.startsWith(publicDir + sep)) {
61
+ res.writeHead(403).end();
62
+ return;
63
+ }
64
+ try {
65
+ const body = await readFile(file);
66
+ res.writeHead(200, { 'content-type': CONTENT_TYPES[extname(file)] ?? 'application/octet-stream' }).end(req.method === 'HEAD' ? undefined : body);
67
+ }
68
+ catch {
69
+ res.writeHead(404).end('Not found');
70
+ }
71
+ return;
72
+ }
73
+ if (path !== '/') {
74
+ res.writeHead(404).end('Not found');
75
+ return;
76
+ }
77
+ res.writeHead(200, { 'content-type': CONTENT_TYPES['.html'] }).end(req.method === 'HEAD' ? undefined : DEBUG_PAGE);
78
+ }
79
+ const server = createServer((req, res) => {
80
+ handle(req, res).catch(() => res.writeHead(500).end());
81
+ });
82
+ server.on('upgrade', (req, socket, head) => {
83
+ wss.handleUpgrade(req, socket, head, (client) => {
84
+ const connection = hub.attach({
85
+ send: (data) => client.send(data),
86
+ close: (code, reason) => client.close(code, reason),
87
+ get bufferedAmount() {
88
+ return client.bufferedAmount;
89
+ },
90
+ }, { headers: toHeaders(req) });
91
+ client.on('message', (data, isBinary) => connection.receive(isBinary ? toBytes(data) : utf8.decode(toBytes(data))));
92
+ client.on('close', () => connection.closed());
93
+ client.on('error', () => connection.closed());
94
+ });
95
+ });
96
+ const host = options.host ?? 'localhost';
97
+ await new Promise((resolveListen, reject) => {
98
+ server.once('error', reject);
99
+ server.listen(options.port ?? 8790, host, () => {
100
+ server.off('error', reject);
101
+ resolveListen();
102
+ });
103
+ });
104
+ const address = server.address();
105
+ const port = typeof address === 'object' && address ? address.port : (options.port ?? 8790);
106
+ const url = `http://${host}:${port}`;
107
+ (options.onListening ?? ((u) => console.log(`vRealTime listening on ${u}`)))(url);
108
+ return {
109
+ url,
110
+ port,
111
+ hub,
112
+ async close() {
113
+ for (const client of wss.clients)
114
+ client.terminate();
115
+ await hub.close();
116
+ wss.close();
117
+ await new Promise((done) => server.close(() => done()));
118
+ },
119
+ };
120
+ }
@@ -0,0 +1,15 @@
1
+ import type { AgentDefinition } from '@vrealtime/core';
2
+ import { Hub, type AttachOptions } from '../index.js';
3
+ /**
4
+ * Upgrades a request to a vRealTime session on Cloudflare Workers or inside a
5
+ * Durable Object's `fetch()`. Sessions live in memory (per isolate, or per object),
6
+ * so route reconnects to the same Durable Object to resume. Use the standard,
7
+ * non-hibernating WebSocket API.
8
+ *
9
+ * ```ts
10
+ * export default { fetch: (request) => upgrade(agent, request) };
11
+ * ```
12
+ */
13
+ export declare function upgrade(agent: AgentDefinition | Hub, request: Request, options?: AttachOptions): Response;
14
+ export type { AttachOptions, AuthRequest, Connection, Principal } from '../index.js';
15
+ export { Hub };
@@ -0,0 +1,37 @@
1
+ import { Hub } from '../index.js';
2
+ const hubs = new WeakMap();
3
+ function hubFor(agent, options) {
4
+ if (agent instanceof Hub)
5
+ return agent;
6
+ let hub = hubs.get(agent);
7
+ if (!hub) {
8
+ hub = new Hub(agent, options);
9
+ hubs.set(agent, hub);
10
+ }
11
+ return hub;
12
+ }
13
+ /**
14
+ * Upgrades a request to a vRealTime session on Cloudflare Workers or inside a
15
+ * Durable Object's `fetch()`. Sessions live in memory (per isolate, or per object),
16
+ * so route reconnects to the same Durable Object to resume. Use the standard,
17
+ * non-hibernating WebSocket API.
18
+ *
19
+ * ```ts
20
+ * export default { fetch: (request) => upgrade(agent, request) };
21
+ * ```
22
+ */
23
+ export function upgrade(agent, request, options) {
24
+ if (request.headers.get('Upgrade')?.toLowerCase() !== 'websocket') {
25
+ return new Response('Expected a WebSocket upgrade', { status: 426, headers: { Upgrade: 'websocket' } });
26
+ }
27
+ const Pair = globalThis.WebSocketPair;
28
+ if (!Pair)
29
+ throw new Error('@vrealtime/server/workers: upgrade() needs the Workers runtime (WebSocketPair)');
30
+ const pair = new Pair();
31
+ const client = pair[0];
32
+ const server = pair[1];
33
+ server.accept();
34
+ hubFor(agent, options).attach(server, { headers: request.headers });
35
+ return new Response(null, { status: 101, webSocket: client });
36
+ }
37
+ export { Hub };
package/package.json CHANGED
@@ -1,6 +1,64 @@
1
1
  {
2
2
  "name": "@vrealtime/server",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "vRealTime server: attach any WebSocket, Node serve(), Cloudflare Workers and Durable Objects",
5
+ "license": "Apache-2.0",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/austinchennn/vRT.git",
9
+ "directory": "packages/server"
10
+ },
11
+ "homepage": "https://github.com/austinchennn/vRT#readme",
12
+ "bugs": "https://github.com/austinchennn/vRT/issues",
13
+ "keywords": [
14
+ "realtime",
15
+ "voice",
16
+ "agent",
17
+ "websocket",
18
+ "vrealtime"
19
+ ],
20
+ "type": "module",
21
+ "sideEffects": false,
22
+ "types": "./dist/index.d.ts",
23
+ "exports": {
24
+ ".": {
25
+ "@vrealtime/source": "./src/index.ts",
26
+ "types": "./dist/index.d.ts",
27
+ "default": "./dist/index.js"
28
+ },
29
+ "./node": {
30
+ "@vrealtime/source": "./src/node/index.ts",
31
+ "types": "./dist/node/index.d.ts",
32
+ "default": "./dist/node/index.js"
33
+ },
34
+ "./workers": {
35
+ "@vrealtime/source": "./src/workers/index.ts",
36
+ "types": "./dist/workers/index.d.ts",
37
+ "default": "./dist/workers/index.js"
38
+ }
39
+ },
40
+ "files": [
41
+ "dist"
42
+ ],
43
+ "engines": {
44
+ "node": ">=22"
45
+ },
46
+ "publishConfig": {
47
+ "access": "public"
48
+ },
49
+ "scripts": {
50
+ "build": "tsc -p tsconfig.build.json"
51
+ },
52
+ "dependencies": {
53
+ "@vrealtime/core": "0.1.0",
54
+ "@vrealtime/protocol": "0.1.0"
55
+ },
56
+ "peerDependencies": {
57
+ "ws": "^8.0.0"
58
+ },
59
+ "peerDependenciesMeta": {
60
+ "ws": {
61
+ "optional": true
62
+ }
63
+ }
64
+ }