tuxevil-rotator 3.6.1 → 3.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1538 @@
1
+ import type { IncomingMessage, ServerResponse, ClientRequest } from "node:http";
2
+ import type { Duplex } from "node:stream";
3
+ import https from "node:https";
4
+ import cp from "node:child_process";
5
+ import crypto from "node:crypto";
6
+ import fs from "node:fs";
7
+ import { readLimitedBody } from "./body-limit.js";
8
+ import { authenticateVirtualKey, sendAuthErrorResponse, type KeyAuthResult } from "./key-auth.js";
9
+ import { logger } from "./logger.js";
10
+ import { logSpend } from "./spend-logger.js";
11
+ import { applyModelAlias } from "./types.js";
12
+ import { hashKey } from "./virtual-keys.js";
13
+
14
+ const audioLogger = logger.child("audio-transcription");
15
+ const AUDIO_SESSION_START_TIMEOUT_MS = 10_000;
16
+ const AUDIO_TRANSCRIPTION_TIMEOUT_MS = 30_000;
17
+ const AUDIO_UNARY_REQUEST_TIMEOUT_MS = 10_000;
18
+ export const MAX_AUDIO_FRAME_BYTES = 256 * 1024;
19
+ export const MAX_QUEUED_AUDIO_BYTES = 1024 * 1024;
20
+ const MAX_QUEUED_AUDIO_CHUNKS = 1024;
21
+ const MAX_WS_INCOMING_BUFFER_BYTES = 2 * MAX_QUEUED_AUDIO_BYTES;
22
+
23
+ // Antigravity's local Language Server presents a self-signed certificate. Keep
24
+ // the exception narrowly scoped to the loopback service and require its CSRF
25
+ // token at the application layer instead of changing Node's global TLS policy.
26
+ const LOCAL_LANGUAGE_SERVER_TLS_OPTIONS = Object.freeze({
27
+ rejectUnauthorized: false, // codeql[js/disabling-certificate-validation]
28
+ });
29
+
30
+ export interface AntigravityCredentials {
31
+ port: number;
32
+ csrf: string;
33
+ }
34
+
35
+ let cachedCreds: AntigravityCredentials | null = null;
36
+ let lastCredsCheck = 0;
37
+
38
+ /**
39
+ * Auto-detect the running Antigravity Language Server credentials.
40
+ * Checks for running language_server instances with their HTTPS listening ports.
41
+ */
42
+ export function getAntigravityCredentials(): AntigravityCredentials {
43
+ const now = Date.now();
44
+ if (cachedCreds && now - lastCredsCheck < 30_000) {
45
+ return cachedCreds;
46
+ }
47
+
48
+ try {
49
+ const ps = cp.execSync("ps aux | grep language_server | grep -v grep").toString();
50
+ const lines = ps.split("\n");
51
+ // Sort so Hub instance comes first
52
+ lines.sort((a, b) => (b.includes("hub") ? 1 : 0) - (a.includes("hub") ? 1 : 0));
53
+ for (const line of lines) {
54
+ const matchCsrf = line.match(/--csrf_token\s+([a-f0-9-]+)/);
55
+ const matchPid = line.trim().match(/^\S+\s+(\d+)/);
56
+ if (matchCsrf && matchPid) {
57
+ const pid = matchPid[1];
58
+ const csrf = matchCsrf[1];
59
+ const lsof = cp.execSync(`lsof -nP -iTCP -sTCP:LISTEN -a -p ${pid}`).toString();
60
+ const ports = [...lsof.matchAll(/:(\d+)\s+\(LISTEN\)/g)].map((m) => parseInt(m[1], 10));
61
+ if (ports.length > 0) {
62
+ cachedCreds = { port: ports[0], csrf };
63
+ lastCredsCheck = now;
64
+ return cachedCreds;
65
+ }
66
+ }
67
+ }
68
+ } catch (e: unknown) {
69
+ const err = e as Error;
70
+ audioLogger.warn(`Failed to auto-detect language_server: ${err.message}`);
71
+ }
72
+
73
+ return cachedCreds ?? { port: 52176, csrf: "ab6faa2f-e834-47f1-994b-cb39112ae062" };
74
+ }
75
+
76
+ export function resolveMimeType(fileName: string, mimeType?: string): string {
77
+ if (mimeType && mimeType.startsWith("audio/")) return mimeType;
78
+ const lower = fileName.toLowerCase();
79
+ if (lower.endsWith(".wav")) return "audio/wav";
80
+ if (lower.endsWith(".mp3")) return "audio/mp3";
81
+ if (lower.endsWith(".m4a")) return "audio/m4a";
82
+ if (lower.endsWith(".webm")) return "audio/webm;codecs=opus";
83
+ if (lower.endsWith(".ogg")) return "audio/ogg";
84
+ if (lower.endsWith(".flac")) return "audio/flac";
85
+ if (lower.endsWith(".pcm")) return "audio/pcm;rate=16000";
86
+ return "audio/wav";
87
+ }
88
+
89
+ export interface TranscribeOptions {
90
+ mimeType?: string;
91
+ model?: string;
92
+ prompt?: string;
93
+ language?: string;
94
+ }
95
+
96
+ function parseConnectEndStreamError(payload: Buffer): Error | null {
97
+ const endStream = JSON.parse(payload.toString("utf8"));
98
+ if (!endStream || typeof endStream !== "object" || Array.isArray(endStream)) {
99
+ throw new Error("expected a JSON object");
100
+ }
101
+ if (!Object.hasOwn(endStream, "error")) return null;
102
+
103
+ const upstreamError = endStream.error;
104
+ const message =
105
+ upstreamError && typeof upstreamError === "object"
106
+ ? String(upstreamError.message || upstreamError.code || "invalid error envelope")
107
+ : typeof upstreamError === "string" && upstreamError
108
+ ? upstreamError
109
+ : "invalid error envelope";
110
+ return new Error(`Antigravity StreamAudioTranscription error: ${message}`);
111
+ }
112
+
113
+ /**
114
+ * Transcribes an audio buffer using Antigravity models/proactive-observer-v10.
115
+ */
116
+ export async function transcribeAudioWithAntigravity(
117
+ audioBuffer: Buffer,
118
+ options: TranscribeOptions = {},
119
+ ): Promise<string> {
120
+ const creds = getAntigravityCredentials();
121
+ const rawModel = options.model || "models/proactive-observer-v10";
122
+ const model = applyModelAlias(rawModel);
123
+ const mimeType = options.mimeType || "audio/wav";
124
+ const prompt = options.prompt || "";
125
+
126
+ return new Promise((resolve, reject) => {
127
+ let sessionId: string | null = null;
128
+ let finalText = "";
129
+ let lastInterim = "";
130
+ let isResolved = false;
131
+ let endStarted = false;
132
+ let endComplete = false;
133
+ let protocolComplete = false;
134
+ const pendingUnaryRequests = new Map<ClientRequest, () => void>();
135
+
136
+ const payload = JSON.stringify({
137
+ mimeType,
138
+ model,
139
+ cascadeId: `transcribe-${Date.now()}`,
140
+ preCursorText: prompt,
141
+ continuous: false,
142
+ language: options.language,
143
+ });
144
+ const payloadBuf = Buffer.from(payload, "utf8");
145
+ const frame = Buffer.alloc(5 + payloadBuf.length);
146
+ frame.writeUInt8(0, 0);
147
+ frame.writeUInt32BE(payloadBuf.length, 1);
148
+ payloadBuf.copy(frame, 5);
149
+
150
+ const streamReq = https.request(
151
+ {
152
+ hostname: "127.0.0.1",
153
+ port: creds.port,
154
+ path: "/exa.language_server_pb.LanguageServerService/StreamAudioTranscription",
155
+ method: "POST",
156
+ ...LOCAL_LANGUAGE_SERVER_TLS_OPTIONS,
157
+ headers: {
158
+ "Content-Type": "application/connect+json",
159
+ "Connect-Protocol-Version": "1",
160
+ "X-Codeium-Csrf-Token": creds.csrf,
161
+ },
162
+ },
163
+ (res) => {
164
+ res.on("error", fail);
165
+ if (res.statusCode !== 200) {
166
+ fail(new Error(`Antigravity StreamAudioTranscription error: HTTP ${res.statusCode}`));
167
+ return;
168
+ }
169
+
170
+ let buf = Buffer.alloc(0);
171
+ res.on("data", (chunk: Buffer) => {
172
+ if (isResolved) return;
173
+ buf = Buffer.concat([buf, chunk]);
174
+ while (buf.length >= 5) {
175
+ if (isResolved) return;
176
+ const flag = buf.readUInt8(0);
177
+ const len = buf.readUInt32BE(1);
178
+ if (buf.length < 5 + len) break;
179
+ const msgBuf = buf.subarray(5, 5 + len);
180
+ buf = buf.subarray(5 + len);
181
+
182
+ if (flag === 0) {
183
+ try {
184
+ const msg = JSON.parse(msgBuf.toString("utf8"));
185
+ if (msg.ready) {
186
+ const readySessionId = msg.ready.sessionId;
187
+ if (typeof readySessionId !== "string" || readySessionId.trim().length === 0) {
188
+ fail(new Error("Antigravity stream returned an invalid ready sessionId"));
189
+ } else if (!endStarted) {
190
+ sessionId = readySessionId;
191
+ endStarted = true;
192
+ void sendChunksAndEnd().then(() => {
193
+ endComplete = true;
194
+ maybeFinish();
195
+ }, fail);
196
+ }
197
+ } else if (msg.transcription) {
198
+ const text = msg.transcription.text || "";
199
+ if (msg.transcription.isFinal) {
200
+ finalText += (finalText ? " " : "") + text;
201
+ } else {
202
+ lastInterim = text;
203
+ }
204
+ } else if (msg.complete) {
205
+ completeProtocol();
206
+ }
207
+ } catch (err: unknown) {
208
+ fail(new Error(`Invalid Antigravity transcription message: ${String(err)}`));
209
+ }
210
+ } else if (flag === 2) {
211
+ try {
212
+ const error = parseConnectEndStreamError(msgBuf);
213
+ if (error) fail(error);
214
+ else completeProtocol();
215
+ } catch (err: unknown) {
216
+ fail(new Error(`Invalid Antigravity end-stream message: ${String(err)}`));
217
+ }
218
+ }
219
+ }
220
+ });
221
+
222
+ res.on("end", () => {
223
+ if (isResolved) return;
224
+ if (buf.length > 0) {
225
+ fail(new Error("Antigravity stream ended with a truncated frame"));
226
+ } else if (!sessionId) {
227
+ fail(new Error("Antigravity stream ended before a ready session"));
228
+ } else if (!protocolComplete) {
229
+ fail(new Error("Antigravity stream ended before protocol completion"));
230
+ }
231
+ });
232
+ },
233
+ );
234
+
235
+ streamReq.on("error", (err) => {
236
+ fail(err);
237
+ });
238
+
239
+ streamReq.write(frame);
240
+ streamReq.end();
241
+
242
+ const timeout = setTimeout(() => {
243
+ fail(new Error("Antigravity audio transcription timed out"));
244
+ }, AUDIO_TRANSCRIPTION_TIMEOUT_MS);
245
+
246
+ function cleanup() {
247
+ clearTimeout(timeout);
248
+ for (const [request, finish] of pendingUnaryRequests) {
249
+ try {
250
+ request.destroy();
251
+ } catch {
252
+ // ignore cleanup error
253
+ }
254
+ finish();
255
+ }
256
+ try {
257
+ streamReq.destroy();
258
+ } catch {
259
+ // ignore cleanup error
260
+ }
261
+ }
262
+
263
+ function succeed(text = (finalText || lastInterim).trim()) {
264
+ if (isResolved) return;
265
+ isResolved = true;
266
+ cleanup();
267
+ resolve(text);
268
+ }
269
+
270
+ function completeProtocol() {
271
+ if (!sessionId || !endStarted) {
272
+ fail(new Error("Antigravity stream completed before a ready session"));
273
+ return;
274
+ }
275
+ protocolComplete = true;
276
+ maybeFinish();
277
+ }
278
+
279
+ function maybeFinish() {
280
+ if (sessionId && protocolComplete && endStarted && endComplete) succeed();
281
+ }
282
+
283
+ function fail(error: Error) {
284
+ if (isResolved) return;
285
+ isResolved = true;
286
+ cleanup();
287
+ reject(error);
288
+ }
289
+
290
+ async function sendChunksAndEnd() {
291
+ if (!sessionId || isResolved) return;
292
+ const chunkSize = 3200; // 100ms at 16kHz
293
+ let seq = 0;
294
+
295
+ for (let i = 0; i < audioBuffer.length; i += chunkSize) {
296
+ if (isResolved) return;
297
+ const chunk = audioBuffer.subarray(i, Math.min(i + chunkSize, audioBuffer.length));
298
+ const data = JSON.stringify({
299
+ sessionId,
300
+ data: chunk.toString("base64"),
301
+ sequenceNumber: String(seq++),
302
+ });
303
+
304
+ await new Promise<void>((resolveChunk, rejectChunk) => {
305
+ let settled = false;
306
+ function finish(error?: Error): void {
307
+ if (settled) return;
308
+ settled = true;
309
+ pendingUnaryRequests.delete(req);
310
+ if (error) rejectChunk(error);
311
+ else resolveChunk();
312
+ }
313
+ const req = https.request(
314
+ {
315
+ hostname: "127.0.0.1",
316
+ port: creds.port,
317
+ path: "/exa.language_server_pb.LanguageServerService/SendAudioChunk",
318
+ method: "POST",
319
+ ...LOCAL_LANGUAGE_SERVER_TLS_OPTIONS,
320
+ headers: {
321
+ "Content-Type": "application/json",
322
+ "X-Codeium-Csrf-Token": creds.csrf,
323
+ "Content-Length": Buffer.byteLength(data),
324
+ },
325
+ },
326
+ (resp) => {
327
+ resp.resume();
328
+ resp.on("end", finish);
329
+ resp.on("error", () => finish());
330
+ },
331
+ );
332
+ pendingUnaryRequests.set(req, finish);
333
+ req.setTimeout(AUDIO_UNARY_REQUEST_TIMEOUT_MS, () => {
334
+ const error = new Error("SendAudioChunk timed out");
335
+ audioLogger.warn(error.message);
336
+ try {
337
+ req.destroy();
338
+ } catch {
339
+ // ignore cleanup error
340
+ }
341
+ finish(error);
342
+ });
343
+ req.on("error", () => finish());
344
+ req.write(data);
345
+ req.end();
346
+ });
347
+ if (isResolved) return;
348
+ }
349
+
350
+ // End session
351
+ if (isResolved) return;
352
+ const endData = JSON.stringify({ sessionId });
353
+ await new Promise<void>((resolveEnd, rejectEnd) => {
354
+ let settled = false;
355
+ function finish(error?: Error): void {
356
+ if (settled) return;
357
+ settled = true;
358
+ pendingUnaryRequests.delete(req);
359
+ if (error) rejectEnd(error);
360
+ else resolveEnd();
361
+ }
362
+ const req = https.request(
363
+ {
364
+ hostname: "127.0.0.1",
365
+ port: creds.port,
366
+ path: "/exa.language_server_pb.LanguageServerService/EndAudioSession",
367
+ method: "POST",
368
+ ...LOCAL_LANGUAGE_SERVER_TLS_OPTIONS,
369
+ headers: {
370
+ "Content-Type": "application/json",
371
+ "X-Codeium-Csrf-Token": creds.csrf,
372
+ "Content-Length": Buffer.byteLength(endData),
373
+ },
374
+ },
375
+ (resp) => {
376
+ resp.on("error", finish);
377
+ resp.resume();
378
+ if (resp.statusCode === undefined || resp.statusCode < 200 || resp.statusCode >= 300) {
379
+ finish(new Error(`Antigravity EndAudioSession error: HTTP ${resp.statusCode}`));
380
+ return;
381
+ }
382
+ resp.on("end", finish);
383
+ },
384
+ );
385
+ pendingUnaryRequests.set(req, () => finish());
386
+ req.setTimeout(AUDIO_UNARY_REQUEST_TIMEOUT_MS, () => {
387
+ const error = new Error("EndAudioSession timed out");
388
+ try {
389
+ req.destroy();
390
+ } catch {
391
+ // ignore cleanup error
392
+ }
393
+ finish(error);
394
+ });
395
+ req.on("error", finish);
396
+ req.end(endData);
397
+ });
398
+ }
399
+ });
400
+ }
401
+
402
+ export function getAudioDurationSeconds(audioBuffer: Buffer, mimeType: string): number | undefined {
403
+ if (!mimeType.toLowerCase().startsWith("audio/wav")) return undefined;
404
+ if (
405
+ audioBuffer.length < 12 ||
406
+ audioBuffer.toString("ascii", 0, 4) !== "RIFF" ||
407
+ audioBuffer.toString("ascii", 8, 12) !== "WAVE"
408
+ ) {
409
+ return undefined;
410
+ }
411
+
412
+ let byteRate: number | undefined;
413
+ let dataLength: number | undefined;
414
+ for (let offset = 12; offset + 8 <= audioBuffer.length; ) {
415
+ const chunkId = audioBuffer.toString("ascii", offset, offset + 4);
416
+ const chunkLength = audioBuffer.readUInt32LE(offset + 4);
417
+ const dataOffset = offset + 8;
418
+ const chunkEnd = dataOffset + chunkLength;
419
+ if (!Number.isSafeInteger(chunkEnd) || chunkEnd > audioBuffer.length) return undefined;
420
+ if (chunkId === "fmt " && chunkLength >= 12) {
421
+ byteRate = audioBuffer.readUInt32LE(dataOffset + 8);
422
+ } else if (chunkId === "data") {
423
+ dataLength = chunkLength;
424
+ }
425
+ if (byteRate && dataLength !== undefined) return dataLength / byteRate;
426
+ offset = chunkEnd + (chunkLength % 2);
427
+ }
428
+ return undefined;
429
+ }
430
+
431
+ /**
432
+ * Handles standard OpenAI-compatible POST /v1/audio/transcriptions
433
+ */
434
+ export async function handleOpenAIAudioTranscriptions(
435
+ req: IncomingMessage,
436
+ res: ServerResponse,
437
+ ): Promise<void> {
438
+ const requestStartedAt = Date.now();
439
+ const initialAuth = await authenticateVirtualKey(req);
440
+ if (!initialAuth.authenticated) {
441
+ sendAuthErrorResponse(res, initialAuth);
442
+ return;
443
+ }
444
+ let apiKeyHash = initialAuth.key?.tokenHash || (initialAuth.rawKey ? hashKey(initialAuth.rawKey) : null);
445
+ let spendModel = "models/proactive-observer-v10";
446
+ let spendLogged = false;
447
+ const logRequest = (status: "success" | "failure"): void => {
448
+ if (spendLogged) return;
449
+ spendLogged = true;
450
+ const endTime = Date.now();
451
+ logSpend({
452
+ apiKeyHash,
453
+ model: applyModelAlias(spendModel),
454
+ callType: "audio_transcription",
455
+ status,
456
+ promptTokens: 0,
457
+ completionTokens: 0,
458
+ startTime: new Date(requestStartedAt).toISOString(),
459
+ endTime: new Date(endTime).toISOString(),
460
+ durationMs: endTime - requestStartedAt,
461
+ requesterIp: req.socket?.remoteAddress || null,
462
+ });
463
+ };
464
+
465
+ const contentType = req.headers["content-type"] || "";
466
+ if (!contentType.includes("multipart/form-data")) {
467
+ logRequest("failure");
468
+ res.writeHead(400, { "Content-Type": "application/json" });
469
+ res.end(
470
+ JSON.stringify({
471
+ error: {
472
+ message: "Content-Type must be multipart/form-data for audio transcriptions",
473
+ type: "invalid_request_error",
474
+ param: null,
475
+ code: null,
476
+ },
477
+ }),
478
+ );
479
+ return;
480
+ }
481
+
482
+ let rawBody: Buffer;
483
+ try {
484
+ rawBody = await readLimitedBody(req);
485
+ } catch (err: unknown) {
486
+ const error = err as Error;
487
+ logRequest("failure");
488
+ res.writeHead(413, { "Content-Type": "application/json" });
489
+ res.end(
490
+ JSON.stringify({
491
+ error: {
492
+ message: error.message || "Payload too large",
493
+ type: "invalid_request_error",
494
+ },
495
+ }),
496
+ );
497
+ return;
498
+ }
499
+
500
+ let formData: FormData;
501
+ try {
502
+ const responseWrapper = new Response(new Uint8Array(rawBody), {
503
+ headers: { "content-type": contentType },
504
+ });
505
+ formData = await responseWrapper.formData();
506
+ } catch (err: unknown) {
507
+ const error = err as Error;
508
+ logRequest("failure");
509
+ res.writeHead(400, { "Content-Type": "application/json" });
510
+ res.end(
511
+ JSON.stringify({
512
+ error: {
513
+ message: `Failed to parse multipart/form-data: ${error.message}`,
514
+ type: "invalid_request_error",
515
+ },
516
+ }),
517
+ );
518
+ return;
519
+ }
520
+
521
+ const fileEntry = formData.get("file");
522
+ if (!fileEntry || typeof fileEntry === "string") {
523
+ logRequest("failure");
524
+ res.writeHead(400, { "Content-Type": "application/json" });
525
+ res.end(
526
+ JSON.stringify({
527
+ error: {
528
+ message: "Missing required 'file' parameter",
529
+ type: "invalid_request_error",
530
+ param: "file",
531
+ },
532
+ }),
533
+ );
534
+ return;
535
+ }
536
+
537
+ const model = String(formData.get("model") || "models/proactive-observer-v10");
538
+ spendModel = model;
539
+ const modelAuth = await authenticateVirtualKey(req, model);
540
+ if (!modelAuth.authenticated) {
541
+ logRequest("failure");
542
+ sendAuthErrorResponse(res, modelAuth);
543
+ return;
544
+ }
545
+ apiKeyHash = modelAuth.key?.tokenHash || (modelAuth.rawKey ? hashKey(modelAuth.rawKey) : apiKeyHash);
546
+ const prompt = formData.get("prompt") ? String(formData.get("prompt")) : undefined;
547
+ const language = formData.get("language") ? String(formData.get("language")) : undefined;
548
+ const responseFormat = String(formData.get("response_format") || "json").toLowerCase();
549
+
550
+ const fileName = (fileEntry as File).name || "audio.wav";
551
+ const mimeType = resolveMimeType(fileName, fileEntry.type);
552
+ const arrayBuf = await fileEntry.arrayBuffer();
553
+ const audioBuffer = Buffer.from(arrayBuf);
554
+
555
+ try {
556
+ const transcribedText = await transcribeAudioWithAntigravity(audioBuffer, {
557
+ mimeType,
558
+ model,
559
+ prompt,
560
+ language,
561
+ });
562
+
563
+ if (responseFormat === "text") {
564
+ res.writeHead(200, { "Content-Type": "text/plain; charset=utf-8" });
565
+ res.end(transcribedText);
566
+ logRequest("success");
567
+ return;
568
+ }
569
+
570
+ if (responseFormat === "verbose_json") {
571
+ const verbose: Record<string, unknown> = {
572
+ task: "transcribe",
573
+ text: transcribedText,
574
+ segments: [],
575
+ };
576
+ if (language) verbose.language = language;
577
+ const duration = getAudioDurationSeconds(audioBuffer, mimeType);
578
+ if (duration !== undefined) verbose.duration = duration;
579
+ res.writeHead(200, { "Content-Type": "application/json; charset=utf-8" });
580
+ res.end(JSON.stringify(verbose));
581
+ logRequest("success");
582
+ return;
583
+ }
584
+
585
+ // Default: json
586
+ res.writeHead(200, { "Content-Type": "application/json; charset=utf-8" });
587
+ res.end(JSON.stringify({ text: transcribedText }));
588
+ logRequest("success");
589
+ } catch (err: unknown) {
590
+ const error = err as Error;
591
+ logRequest("failure");
592
+ audioLogger.error(`Transcription failed: ${error.message}`);
593
+ res.writeHead(500, { "Content-Type": "application/json" });
594
+ res.end(
595
+ JSON.stringify({
596
+ error: {
597
+ message: `Transcription error: ${error.message}`,
598
+ type: "api_error",
599
+ },
600
+ }),
601
+ );
602
+ }
603
+ }
604
+
605
+ /**
606
+ * Antigravity real-time streaming audio transcription session.
607
+ */
608
+ export class AntigravityAudioSession {
609
+ private port: number;
610
+ private csrf: string;
611
+ public model: string;
612
+ public cascadeId: string;
613
+ public preCursorText: string;
614
+ public postCursorText: string;
615
+ public continuous: boolean;
616
+ public language?: string;
617
+ public sessionId: string | null = null;
618
+ private seq = 0;
619
+ private streamReq: ClientRequest | null = null;
620
+ private streamBuffer = Buffer.alloc(0);
621
+ private queue: Buffer[] = [];
622
+ private queuedAudioBytes = 0;
623
+ private isProcessingQueue = false;
624
+ private pendingEnd: { promise: Promise<void>; resolve: () => void } | null = null;
625
+ private endAcknowledged = false;
626
+ private protocolComplete = false;
627
+ private completionTimer: ReturnType<typeof setTimeout> | null = null;
628
+ private state: "idle" | "starting" | "ready" | "ending" | "ended" | "failed" | "destroyed" =
629
+ "idle";
630
+ private startTimer: ReturnType<typeof setTimeout> | null = null;
631
+ private startReject: ((error: Error) => void) | null = null;
632
+ private readonly startTimeoutMs: number;
633
+ private readonly pendingRequests = new Map<ClientRequest, () => void>();
634
+ private onEvent: (event: any) => void;
635
+ private onError: (err: Error) => void;
636
+
637
+ constructor(
638
+ creds: AntigravityCredentials,
639
+ options: {
640
+ model?: string;
641
+ cascadeId?: string;
642
+ preCursorText?: string;
643
+ postCursorText?: string;
644
+ continuous?: boolean;
645
+ language?: string;
646
+ startTimeoutMs?: number;
647
+ onEvent?: (event: any) => void;
648
+ onError?: (err: Error) => void;
649
+ } = {},
650
+ ) {
651
+ this.port = creds.port;
652
+ this.csrf = creds.csrf;
653
+ this.model = applyModelAlias(options.model || "models/proactive-observer-v10");
654
+ this.cascadeId = options.cascadeId || `stream-${Date.now()}`;
655
+ this.preCursorText = options.preCursorText || "";
656
+ this.postCursorText = options.postCursorText || "";
657
+ this.continuous = options.continuous ?? false;
658
+ this.language = options.language;
659
+ this.startTimeoutMs = Math.max(1, options.startTimeoutMs ?? AUDIO_SESSION_START_TIMEOUT_MS);
660
+ this.onEvent = options.onEvent || (() => {});
661
+ this.onError = options.onError || (() => {});
662
+ }
663
+
664
+ public start(): Promise<string> {
665
+ if (this.state !== "idle") {
666
+ return Promise.reject(new Error("Antigravity audio session has already been started"));
667
+ }
668
+ this.state = "starting";
669
+ return new Promise((resolve, reject) => {
670
+ this.startReject = reject;
671
+ this.startTimer = setTimeout(() => {
672
+ this.failStart(new Error(`Antigravity audio session start timed out after ${this.startTimeoutMs}ms`));
673
+ }, this.startTimeoutMs);
674
+ const payload = JSON.stringify({
675
+ mimeType: "audio/pcm;rate=16000",
676
+ model: this.model,
677
+ cascadeId: this.cascadeId,
678
+ preCursorText: this.preCursorText,
679
+ postCursorText: this.postCursorText,
680
+ continuous: this.continuous,
681
+ language: this.language,
682
+ });
683
+ const payloadBuf = Buffer.from(payload, "utf8");
684
+ const frame = Buffer.alloc(5 + payloadBuf.length);
685
+ frame.writeUInt8(0, 0);
686
+ frame.writeUInt32BE(payloadBuf.length, 1);
687
+ payloadBuf.copy(frame, 5);
688
+
689
+ this.streamReq = https.request(
690
+ {
691
+ hostname: "127.0.0.1",
692
+ port: this.port,
693
+ path: "/exa.language_server_pb.LanguageServerService/StreamAudioTranscription",
694
+ method: "POST",
695
+ ...LOCAL_LANGUAGE_SERVER_TLS_OPTIONS,
696
+ headers: {
697
+ "Content-Type": "application/connect+json",
698
+ "Connect-Protocol-Version": "1",
699
+ "X-Codeium-Csrf-Token": this.csrf,
700
+ },
701
+ },
702
+ (res) => {
703
+ res.on("error", (err) => this.handleStreamError(err));
704
+ if (res.statusCode !== 200) {
705
+ const err = new Error(`Antigravity stream error status: ${res.statusCode}`);
706
+ res.resume();
707
+ this.failStart(err);
708
+ return;
709
+ }
710
+ res.on("data", (chunk: Buffer) => {
711
+ if (this.state === "destroyed" || this.state === "failed") return;
712
+ this.streamBuffer = Buffer.concat([this.streamBuffer, chunk]);
713
+ while (this.streamBuffer.length >= 5) {
714
+ const flag = this.streamBuffer.readUInt8(0);
715
+ const len = this.streamBuffer.readUInt32BE(1);
716
+ if (this.streamBuffer.length < 5 + len) break;
717
+ const msgBuf = this.streamBuffer.subarray(5, 5 + len);
718
+ this.streamBuffer = this.streamBuffer.subarray(5 + len);
719
+
720
+ if (flag === 0) {
721
+ try {
722
+ const msg = JSON.parse(msgBuf.toString("utf8"));
723
+ if (msg.ready?.sessionId && this.state === "starting") {
724
+ const sessionId = String(msg.ready.sessionId);
725
+ this.sessionId = sessionId;
726
+ this.state = "ready";
727
+ this.clearStartWait();
728
+ resolve(sessionId);
729
+ void this.processQueue();
730
+ }
731
+ if (msg.complete) this.completeStream();
732
+ else this.onEvent(msg);
733
+ } catch (error: unknown) {
734
+ this.handleStreamError(
735
+ new Error(`Invalid Antigravity JSON stream message: ${String(error)}`),
736
+ );
737
+ return;
738
+ }
739
+ } else if (flag === 2) {
740
+ try {
741
+ const error = parseConnectEndStreamError(msgBuf);
742
+ if (error) this.handleStreamError(error);
743
+ else this.completeStream();
744
+ } catch (error: unknown) {
745
+ this.handleStreamError(
746
+ new Error(`Invalid Antigravity end-stream message: ${String(error)}`),
747
+ );
748
+ }
749
+ }
750
+ }
751
+ });
752
+
753
+ res.on("end", () => {
754
+ if (this.state === "starting") {
755
+ this.failStart(new Error("Antigravity audio stream ended before becoming ready"));
756
+ return;
757
+ }
758
+ if (
759
+ !this.protocolComplete &&
760
+ (this.state === "ready" || this.state === "ending")
761
+ ) {
762
+ this.handleStreamError(new Error("Antigravity audio stream ended unexpectedly"));
763
+ }
764
+ });
765
+ },
766
+ );
767
+
768
+ this.streamReq.on("error", (err) => {
769
+ this.handleStreamError(err);
770
+ });
771
+
772
+ this.streamReq.write(frame);
773
+ this.streamReq.end();
774
+ });
775
+ }
776
+
777
+ public sendChunk(pcmBuffer: Buffer): boolean {
778
+ if (
779
+ (this.state !== "starting" && this.state !== "ready") ||
780
+ this.pendingEnd !== null ||
781
+ pcmBuffer.length === 0 ||
782
+ pcmBuffer.length > MAX_AUDIO_FRAME_BYTES ||
783
+ this.queue.length >= MAX_QUEUED_AUDIO_CHUNKS ||
784
+ this.queuedAudioBytes + pcmBuffer.length > MAX_QUEUED_AUDIO_BYTES
785
+ ) {
786
+ return false;
787
+ }
788
+ this.queue.push(pcmBuffer);
789
+ this.queuedAudioBytes += pcmBuffer.length;
790
+ if (this.state === "ready") void this.processQueue();
791
+ return true;
792
+ }
793
+
794
+ private async processQueue(): Promise<void> {
795
+ if (
796
+ this.isProcessingQueue ||
797
+ (this.state !== "ready" && this.state !== "ending") ||
798
+ !this.sessionId
799
+ )
800
+ return;
801
+ this.isProcessingQueue = true;
802
+
803
+ while (
804
+ this.queue.length > 0 &&
805
+ (this.state === "ready" || this.state === "ending") &&
806
+ this.sessionId
807
+ ) {
808
+ const chunk = this.queue.shift();
809
+ if (chunk) {
810
+ this.queuedAudioBytes -= chunk.length;
811
+ await this.sendChunkUnary(chunk);
812
+ }
813
+ }
814
+
815
+ this.isProcessingQueue = false;
816
+
817
+ if (this.pendingEnd && (this.state === "ready" || this.state === "ending")) {
818
+ this.state = "ending";
819
+ await this.executeEndSession();
820
+ }
821
+ }
822
+
823
+ private sendChunkUnary(pcmBuffer: Buffer): Promise<void> {
824
+ if (!this.sessionId) return Promise.resolve();
825
+ const data = JSON.stringify({
826
+ sessionId: this.sessionId,
827
+ data: pcmBuffer.toString("base64"),
828
+ sequenceNumber: String(this.seq++),
829
+ });
830
+
831
+ return new Promise((resolve) => {
832
+ let settled = false;
833
+ const finish = (): void => {
834
+ if (settled) return;
835
+ settled = true;
836
+ this.pendingRequests.delete(req);
837
+ resolve();
838
+ };
839
+ const req = https.request(
840
+ {
841
+ hostname: "127.0.0.1",
842
+ port: this.port,
843
+ path: "/exa.language_server_pb.LanguageServerService/SendAudioChunk",
844
+ method: "POST",
845
+ ...LOCAL_LANGUAGE_SERVER_TLS_OPTIONS,
846
+ headers: {
847
+ "Content-Type": "application/json",
848
+ "X-Codeium-Csrf-Token": this.csrf,
849
+ "Content-Length": Buffer.byteLength(data),
850
+ },
851
+ },
852
+ (res) => {
853
+ res.resume();
854
+ res.on("end", finish);
855
+ res.on("error", finish);
856
+ },
857
+ );
858
+ this.pendingRequests.set(req, finish);
859
+ req.setTimeout(AUDIO_UNARY_REQUEST_TIMEOUT_MS, () => {
860
+ const error = new Error("SendAudioChunk timed out");
861
+ audioLogger.warn(error.message);
862
+ this.failSession(error);
863
+ });
864
+ req.on("error", (e) => {
865
+ audioLogger.warn(`SendAudioChunk error: ${e.message}`);
866
+ finish();
867
+ });
868
+ req.write(data);
869
+ req.end();
870
+ });
871
+ }
872
+
873
+ public endSession(): Promise<void> {
874
+ if (this.state === "ended" || this.state === "failed" || this.state === "destroyed") {
875
+ return Promise.resolve();
876
+ }
877
+ if (this.pendingEnd) return this.pendingEnd.promise;
878
+
879
+ let resolveEnd!: () => void;
880
+ const promise = new Promise<void>((resolve) => {
881
+ resolveEnd = resolve;
882
+ });
883
+ this.pendingEnd = { promise, resolve: resolveEnd };
884
+ if (this.state === "ready") this.state = "ending";
885
+ if (!this.isProcessingQueue && this.queue.length === 0 && this.sessionId) {
886
+ void this.executeEndSession();
887
+ }
888
+ return promise;
889
+ }
890
+
891
+ private executeEndSession(): Promise<void> {
892
+ if (!this.sessionId) return Promise.resolve();
893
+ const sessionId = this.sessionId;
894
+ const data = JSON.stringify({ sessionId });
895
+ return new Promise((resolve) => {
896
+ let settled = false;
897
+ const settle = (): boolean => {
898
+ if (settled) return false;
899
+ settled = true;
900
+ this.pendingRequests.delete(req);
901
+ resolve();
902
+ return true;
903
+ };
904
+ const acknowledge = (): void => {
905
+ if (!settle() || this.state !== "ending" || this.sessionId !== sessionId) return;
906
+ this.endAcknowledged = true;
907
+ if (this.protocolComplete) this.finishCompletedStream();
908
+ else this.waitForProtocolCompletion();
909
+ };
910
+ const req = https.request(
911
+ {
912
+ hostname: "127.0.0.1",
913
+ port: this.port,
914
+ path: "/exa.language_server_pb.LanguageServerService/EndAudioSession",
915
+ method: "POST",
916
+ ...LOCAL_LANGUAGE_SERVER_TLS_OPTIONS,
917
+ headers: {
918
+ "Content-Type": "application/json",
919
+ "X-Codeium-Csrf-Token": this.csrf,
920
+ "Content-Length": Buffer.byteLength(data),
921
+ },
922
+ },
923
+ (res) => {
924
+ res.resume();
925
+ res.on("error", (error) => {
926
+ if (!settled) this.failSession(error);
927
+ });
928
+ if (res.statusCode === undefined || res.statusCode < 200 || res.statusCode >= 300) {
929
+ this.failSession(
930
+ new Error(`Antigravity EndAudioSession error: HTTP ${res.statusCode}`),
931
+ );
932
+ return;
933
+ }
934
+ res.on("end", acknowledge);
935
+ },
936
+ );
937
+ this.pendingRequests.set(req, () => {
938
+ settle();
939
+ });
940
+ req.setTimeout(AUDIO_UNARY_REQUEST_TIMEOUT_MS, () => {
941
+ if (settled) return;
942
+ const error = new Error("EndAudioSession timed out");
943
+ audioLogger.warn(error.message);
944
+ this.failSession(error);
945
+ });
946
+ req.on("error", (error) => {
947
+ if (settled) return;
948
+ audioLogger.warn(`EndAudioSession error: ${error.message}`);
949
+ this.failSession(error);
950
+ });
951
+ req.write(data);
952
+ req.end();
953
+ });
954
+ }
955
+
956
+ public destroy(): void {
957
+ if (this.state === "destroyed") return;
958
+ const rejectStart = this.startReject;
959
+ this.clearCompletionWait();
960
+ this.state = "destroyed";
961
+ this.clearStartWait();
962
+ this.queue = [];
963
+ this.queuedAudioBytes = 0;
964
+ const pendingEnd = this.pendingEnd;
965
+ this.pendingEnd = null;
966
+ pendingEnd?.resolve();
967
+ this.sessionId = null;
968
+ this.streamBuffer = Buffer.alloc(0);
969
+ for (const [request, finish] of [...this.pendingRequests]) {
970
+ try {
971
+ request.destroy();
972
+ } catch {
973
+ // ignore destroy error
974
+ }
975
+ finish();
976
+ }
977
+ if (this.streamReq) {
978
+ try {
979
+ this.streamReq.destroy();
980
+ } catch {
981
+ // ignore destroy error
982
+ }
983
+ this.streamReq = null;
984
+ }
985
+ rejectStart?.(new Error("Antigravity audio session was destroyed before becoming ready"));
986
+ }
987
+
988
+ private clearStartWait(): void {
989
+ if (this.startTimer) clearTimeout(this.startTimer);
990
+ this.startTimer = null;
991
+ this.startReject = null;
992
+ }
993
+
994
+ private clearCompletionWait(): void {
995
+ if (this.completionTimer) clearTimeout(this.completionTimer);
996
+ this.completionTimer = null;
997
+ }
998
+
999
+ private failStart(error: Error): void {
1000
+ if (this.state !== "starting") return;
1001
+ const reject = this.startReject;
1002
+ this.state = "failed";
1003
+ this.clearStartWait();
1004
+ this.queue = [];
1005
+ this.queuedAudioBytes = 0;
1006
+ const pendingEnd = this.pendingEnd;
1007
+ this.pendingEnd = null;
1008
+ pendingEnd?.resolve();
1009
+ this.streamBuffer = Buffer.alloc(0);
1010
+ if (this.streamReq) {
1011
+ try {
1012
+ this.streamReq.destroy();
1013
+ } catch {
1014
+ // ignore destroy error
1015
+ }
1016
+ this.streamReq = null;
1017
+ }
1018
+ reject?.(error);
1019
+ }
1020
+
1021
+ private failSession(error: Error): void {
1022
+ if (this.state !== "ready" && this.state !== "ending") return;
1023
+ this.onError(error);
1024
+ this.destroy();
1025
+ }
1026
+
1027
+ private completeStream(): void {
1028
+ if (this.state === "starting") {
1029
+ this.failStart(new Error("Antigravity audio stream completed before becoming ready"));
1030
+ return;
1031
+ }
1032
+ if (this.state !== "ready" && this.state !== "ending") return;
1033
+ this.protocolComplete = true;
1034
+ if (this.state === "ending" && !this.endAcknowledged) return;
1035
+ this.finishCompletedStream();
1036
+ }
1037
+
1038
+ private finishCompletedStream(): void {
1039
+ if (this.state !== "ready" && this.state !== "ending") return;
1040
+ this.destroy();
1041
+ this.onEvent({ complete: true });
1042
+ }
1043
+
1044
+ private waitForProtocolCompletion(): void {
1045
+ if (this.completionTimer || this.protocolComplete || this.state !== "ending") return;
1046
+ this.completionTimer = setTimeout(() => {
1047
+ this.completionTimer = null;
1048
+ this.failSession(
1049
+ new Error("Antigravity audio stream completion timed out after EndAudioSession"),
1050
+ );
1051
+ }, AUDIO_UNARY_REQUEST_TIMEOUT_MS);
1052
+ this.completionTimer.unref?.();
1053
+ }
1054
+
1055
+ private handleStreamError(error: Error): void {
1056
+ if (this.state === "starting") {
1057
+ this.failStart(error);
1058
+ return;
1059
+ }
1060
+ if (this.state === "ready" || this.state === "ending") {
1061
+ this.failSession(error);
1062
+ }
1063
+ }
1064
+ }
1065
+
1066
+ interface AudioWsClient {
1067
+ socket: Duplex;
1068
+ antigravity: AntigravityAudioSession | null;
1069
+ authorizeModel: (model: string) => Promise<KeyAuthResult>;
1070
+ apiKeyHash: string | null;
1071
+ requesterIp: string | null;
1072
+ spendStartedAt: number | null;
1073
+ spendModel: string;
1074
+ closed: boolean;
1075
+ tStartTime: number | null;
1076
+ tFirstAntigravity: number | null;
1077
+ tStopTime: number | null;
1078
+ send: (obj: unknown) => void;
1079
+ }
1080
+
1081
+ function destroyClientSession(client: AudioWsClient): void {
1082
+ if (client.antigravity) {
1083
+ client.antigravity.destroy();
1084
+ client.antigravity = null;
1085
+ }
1086
+ }
1087
+
1088
+ function beginClientSpend(client: AudioWsClient, model: string): void {
1089
+ client.spendStartedAt = Date.now();
1090
+ client.spendModel = applyModelAlias(model);
1091
+ }
1092
+
1093
+ function finishClientSpend(client: AudioWsClient, status: "success" | "failure"): void {
1094
+ if (client.spendStartedAt === null) return;
1095
+ const startedAt = client.spendStartedAt;
1096
+ client.spendStartedAt = null;
1097
+ const endTime = Date.now();
1098
+ logSpend({
1099
+ apiKeyHash: client.apiKeyHash,
1100
+ model: client.spendModel,
1101
+ callType: "audio_stream",
1102
+ status,
1103
+ promptTokens: 0,
1104
+ completionTokens: 0,
1105
+ startTime: new Date(startedAt).toISOString(),
1106
+ endTime: new Date(endTime).toISOString(),
1107
+ durationMs: endTime - startedAt,
1108
+ requesterIp: client.requesterIp,
1109
+ });
1110
+ }
1111
+
1112
+ function cleanupClient(client: AudioWsClient, status: "success" | "failure" = "failure"): void {
1113
+ finishClientSpend(client, status);
1114
+ destroyClientSession(client);
1115
+ }
1116
+
1117
+ function closeClient(client: AudioWsClient, code: number, reason: string): void {
1118
+ if (client.closed) return;
1119
+ client.closed = true;
1120
+ cleanupClient(client);
1121
+ const reasonBuffer = Buffer.from(reason, "utf8").subarray(0, 123);
1122
+ const frame = Buffer.alloc(4 + reasonBuffer.length);
1123
+ frame[0] = 0x88;
1124
+ frame[1] = 2 + reasonBuffer.length;
1125
+ frame.writeUInt16BE(code, 2);
1126
+ reasonBuffer.copy(frame, 4);
1127
+ try {
1128
+ client.socket.end(frame);
1129
+ } catch {
1130
+ client.socket.destroy();
1131
+ }
1132
+ }
1133
+
1134
+ async function authorizeClientModel(client: AudioWsClient, model: string): Promise<boolean> {
1135
+ if (client.closed) return false;
1136
+ const auth = await client.authorizeModel(model);
1137
+ if (client.closed) return false;
1138
+ if (auth.authenticated) return true;
1139
+ client.send({
1140
+ type: "antigravity_error",
1141
+ event: "error",
1142
+ message: auth.error || "Authentication failed",
1143
+ });
1144
+ closeClient(client, 1008, "Model is not allowed");
1145
+ return false;
1146
+ }
1147
+
1148
+ function createClientSession(
1149
+ client: AudioWsClient,
1150
+ model: string,
1151
+ options: { preCursorText?: string; postCursorText?: string; continuous?: boolean; language?: string },
1152
+ ): AntigravityAudioSession {
1153
+ const creds = getAntigravityCredentials();
1154
+ client.tStartTime = Date.now();
1155
+ client.tFirstAntigravity = null;
1156
+ client.tStopTime = null;
1157
+ beginClientSpend(client, model);
1158
+ const session = new AntigravityAudioSession(creds, {
1159
+ model,
1160
+ ...options,
1161
+ onEvent: (event) => {
1162
+ if (client.antigravity !== session || client.closed) return;
1163
+ const now = Date.now();
1164
+ if (event.ready) {
1165
+ client.send({
1166
+ type: "antigravity_ready",
1167
+ event: "ready",
1168
+ sessionId: event.ready.sessionId,
1169
+ });
1170
+ } else if (event.transcription) {
1171
+ if (!client.tFirstAntigravity) client.tFirstAntigravity = now;
1172
+ client.send({
1173
+ type: "antigravity_transcript",
1174
+ event: "transcript",
1175
+ text: event.transcription.text || "",
1176
+ isFinal: !!event.transcription.isFinal,
1177
+ is_final: !!event.transcription.isFinal,
1178
+ ttftMs: client.tStartTime ? now - client.tStartTime : 0,
1179
+ latencyFromStopMs: client.tStopTime ? now - client.tStopTime : null,
1180
+ timestamp: now,
1181
+ });
1182
+ } else if (event.complete) {
1183
+ client.send({
1184
+ type: "antigravity_complete",
1185
+ event: "complete",
1186
+ totalDurationMs: client.tStartTime ? now - client.tStartTime : 0,
1187
+ timestamp: now,
1188
+ });
1189
+ finishClientSpend(client, "success");
1190
+ if (client.antigravity === session && session.sessionId === null) {
1191
+ client.antigravity = null;
1192
+ }
1193
+ }
1194
+ },
1195
+ onError: (err) => {
1196
+ if (client.antigravity !== session || client.closed) return;
1197
+ client.send({ type: "antigravity_error", event: "error", message: err.message });
1198
+ closeClient(client, 1011, "Antigravity audio stream failed");
1199
+ },
1200
+ });
1201
+ return session;
1202
+ }
1203
+
1204
+ async function handleClientCommand(client: AudioWsClient, cmd: any): Promise<void> {
1205
+ if (client.closed) return;
1206
+ if (cmd.type === "start") {
1207
+ const model = String(cmd.antigravityModel || cmd.model || "models/proactive-observer-v10");
1208
+ if (!(await authorizeClientModel(client, model))) return;
1209
+ if (client.antigravity) {
1210
+ finishClientSpend(client, "success");
1211
+ destroyClientSession(client);
1212
+ }
1213
+
1214
+ client.send({
1215
+ type: "session_starting",
1216
+ event: "session_starting",
1217
+ timestamp: Date.now(),
1218
+ });
1219
+
1220
+ const session = createClientSession(client, model, {
1221
+ preCursorText: cmd.preCursorText || "",
1222
+ postCursorText: cmd.postCursorText || "",
1223
+ continuous: cmd.continuous ?? false,
1224
+ language: typeof cmd.language === "string" ? cmd.language : undefined,
1225
+ });
1226
+ client.antigravity = session;
1227
+
1228
+ try {
1229
+ await session.start();
1230
+ } catch (e: any) {
1231
+ if (client.antigravity === session) {
1232
+ client.send({ type: "antigravity_error", event: "error", message: e.message || String(e) });
1233
+ finishClientSpend(client, "failure");
1234
+ destroyClientSession(client);
1235
+ }
1236
+ return;
1237
+ }
1238
+
1239
+ if (client.closed || client.antigravity !== session) return;
1240
+ client.send({
1241
+ type: "ready_to_receive_audio",
1242
+ event: "ready_to_receive_audio",
1243
+ });
1244
+ } else if (cmd.type === "stop") {
1245
+ client.tStopTime = Date.now();
1246
+ client.send({
1247
+ type: "audio_stopped",
1248
+ event: "audio_stopped",
1249
+ timestamp: client.tStopTime,
1250
+ });
1251
+
1252
+ if (client.antigravity) {
1253
+ const session = client.antigravity;
1254
+ await session.endSession();
1255
+ if (client.antigravity === session) {
1256
+ finishClientSpend(client, "success");
1257
+ destroyClientSession(client);
1258
+ }
1259
+ }
1260
+ } else if (cmd.type === "test_sample") {
1261
+ await runTestSample(client, cmd.sample || "es");
1262
+ }
1263
+ }
1264
+
1265
+ async function handleAudioChunk(client: AudioWsClient, pcmBuffer: Buffer): Promise<void> {
1266
+ if (client.closed) return;
1267
+ if (pcmBuffer.length > MAX_AUDIO_FRAME_BYTES) {
1268
+ closeClient(client, 1009, "Audio frame is too large");
1269
+ return;
1270
+ }
1271
+ // If Antigravity session was not explicitly started via JSON command, start it automatically
1272
+ if (!client.antigravity) {
1273
+ const model = "models/proactive-observer-v10";
1274
+ if (!(await authorizeClientModel(client, model))) return;
1275
+ const session = createClientSession(client, model, {
1276
+ continuous: true,
1277
+ });
1278
+ client.antigravity = session;
1279
+ void session.start().catch((err) => {
1280
+ if (client.antigravity !== session) return;
1281
+ audioLogger.error(`Auto-start Antigravity session failed: ${err}`);
1282
+ client.send({ type: "antigravity_error", event: "error", message: err.message || String(err) });
1283
+ finishClientSpend(client, "failure");
1284
+ destroyClientSession(client);
1285
+ });
1286
+ }
1287
+
1288
+ if (!client.antigravity.sendChunk(pcmBuffer)) {
1289
+ closeClient(client, 1009, "Queued audio limit exceeded");
1290
+ }
1291
+ }
1292
+
1293
+ async function runTestSample(client: AudioWsClient, _lang: string): Promise<void> {
1294
+ const samplePath = "/tmp/test_hello.wav";
1295
+ if (!fs.existsSync(samplePath)) {
1296
+ try {
1297
+ cp.execSync(
1298
+ 'say -o /tmp/test_hello.aiff "Hello Antigravity, testing audio transcription" && afconvert -f WAVE -d LEI16@16000 /tmp/test_hello.aiff /tmp/test_hello.wav',
1299
+ );
1300
+ } catch {
1301
+ client.send({
1302
+ type: "antigravity_error",
1303
+ message: "No test sample found and afconvert not available.",
1304
+ });
1305
+ return;
1306
+ }
1307
+ }
1308
+
1309
+ const wav = fs.readFileSync(samplePath);
1310
+ const rawPcm = wav.subarray(44);
1311
+
1312
+ await handleClientCommand(client, {
1313
+ type: "start",
1314
+ language: "en",
1315
+ deepgramApiKey: process.env.DEEPGRAM_API_KEY,
1316
+ });
1317
+
1318
+ let attempts = 0;
1319
+ while ((!client.antigravity || !client.antigravity.sessionId) && attempts++ < 60) {
1320
+ await new Promise((r) => setTimeout(r, 50));
1321
+ }
1322
+
1323
+ const chunkSize = 3200; // 100ms
1324
+ for (let i = 0; i < rawPcm.length; i += chunkSize) {
1325
+ const chunk = rawPcm.subarray(i, Math.min(i + chunkSize, rawPcm.length));
1326
+ await handleAudioChunk(client, chunk);
1327
+ await new Promise((r) => setTimeout(r, 40));
1328
+ }
1329
+
1330
+ await handleClientCommand(client, { type: "stop" });
1331
+ }
1332
+
1333
+ /**
1334
+ * Handles WebSocket streaming on /ws, /ws/audio, /v1/audio/transcriptions/stream, or /v1/listen
1335
+ */
1336
+ export async function handleAudioWebSocket(req: IncomingMessage, socket: Duplex): Promise<void> {
1337
+ const auth = await authenticateVirtualKey(req);
1338
+ if (!auth.authenticated) {
1339
+ const statusCode = auth.statusCode || 401;
1340
+ const body = JSON.stringify({
1341
+ error: {
1342
+ message: auth.error || "Authentication failed",
1343
+ type: statusCode === 403 ? "permission_error" : "authentication_error",
1344
+ },
1345
+ });
1346
+ socket.end(
1347
+ `HTTP/1.1 ${statusCode} ${statusCode === 403 ? "Forbidden" : "Unauthorized"}\r\n` +
1348
+ "Content-Type: application/json\r\n" +
1349
+ `Content-Length: ${Buffer.byteLength(body)}\r\n` +
1350
+ "Connection: close\r\n\r\n" +
1351
+ body,
1352
+ );
1353
+ return;
1354
+ }
1355
+
1356
+ const key = req.headers["sec-websocket-key"];
1357
+ if (typeof key !== "string") {
1358
+ socket.destroy();
1359
+ return;
1360
+ }
1361
+
1362
+ const accept = crypto
1363
+ .createHash("sha1")
1364
+ .update(key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11")
1365
+ .digest("base64");
1366
+
1367
+ socket.write(
1368
+ "HTTP/1.1 101 Switching Protocols\r\n" +
1369
+ "Upgrade: websocket\r\n" +
1370
+ "Connection: Upgrade\r\n" +
1371
+ "Sec-WebSocket-Accept: " +
1372
+ accept +
1373
+ "\r\n\r\n",
1374
+ );
1375
+
1376
+ const client: AudioWsClient = {
1377
+ socket,
1378
+ antigravity: null,
1379
+ authorizeModel: (model) => authenticateVirtualKey(req, model),
1380
+ apiKeyHash: auth.key?.tokenHash || (auth.rawKey ? hashKey(auth.rawKey) : null),
1381
+ requesterIp: req.socket?.remoteAddress || null,
1382
+ spendStartedAt: null,
1383
+ spendModel: "models/proactive-observer-v10",
1384
+ closed: false,
1385
+ tStartTime: null,
1386
+ tFirstAntigravity: null,
1387
+ tStopTime: null,
1388
+ send(obj: unknown) {
1389
+ try {
1390
+ const str = JSON.stringify(obj);
1391
+ const buf = Buffer.from(str, "utf8");
1392
+ let header: Buffer;
1393
+ if (buf.length < 126) {
1394
+ header = Buffer.alloc(2);
1395
+ header[0] = 0x81;
1396
+ header[1] = buf.length;
1397
+ } else if (buf.length < 65536) {
1398
+ header = Buffer.alloc(4);
1399
+ header[0] = 0x81;
1400
+ header[1] = 126;
1401
+ header.writeUInt16BE(buf.length, 2);
1402
+ } else {
1403
+ header = Buffer.alloc(10);
1404
+ header[0] = 0x81;
1405
+ header[1] = 127;
1406
+ header.writeBigUInt64BE(BigInt(buf.length), 2);
1407
+ }
1408
+ socket.write(Buffer.concat([header, buf]));
1409
+ } catch {
1410
+ // socket write error or closed
1411
+ }
1412
+ },
1413
+ };
1414
+
1415
+ // Send initial system info
1416
+ const creds = getAntigravityCredentials();
1417
+ client.send({
1418
+ type: "system_status",
1419
+ event: "system_status",
1420
+ antigravity: { detected: true, port: creds.port },
1421
+ });
1422
+
1423
+ let incomingBuffer = Buffer.alloc(0);
1424
+ let processing = false;
1425
+
1426
+ const processFrames = async (): Promise<void> => {
1427
+ if (processing || client.closed) return;
1428
+ processing = true;
1429
+ try {
1430
+ while (incomingBuffer.length >= 2 && !client.closed) {
1431
+ const firstByte = incomingBuffer[0];
1432
+ const secondByte = incomingBuffer[1];
1433
+ const opcode = firstByte & 0x0f;
1434
+ const isMasked = (secondByte & 0x80) !== 0;
1435
+ let payloadLength = secondByte & 0x7f;
1436
+
1437
+ let offset = 2;
1438
+ if (payloadLength === 126) {
1439
+ if (incomingBuffer.length < 4) break;
1440
+ payloadLength = incomingBuffer.readUInt16BE(2);
1441
+ offset = 4;
1442
+ } else if (payloadLength === 127) {
1443
+ if (incomingBuffer.length < 10) break;
1444
+ const largePayloadLength = incomingBuffer.readBigUInt64BE(2);
1445
+ if (largePayloadLength > BigInt(MAX_AUDIO_FRAME_BYTES)) {
1446
+ closeClient(client, 1009, "WebSocket frame is too large");
1447
+ incomingBuffer = Buffer.alloc(0);
1448
+ return;
1449
+ }
1450
+ payloadLength = Number(largePayloadLength);
1451
+ offset = 10;
1452
+ }
1453
+
1454
+ if (payloadLength > MAX_AUDIO_FRAME_BYTES) {
1455
+ closeClient(client, 1009, "WebSocket frame is too large");
1456
+ incomingBuffer = Buffer.alloc(0);
1457
+ return;
1458
+ }
1459
+
1460
+ const maskLength = isMasked ? 4 : 0;
1461
+ if (incomingBuffer.length < offset + maskLength + payloadLength) break;
1462
+
1463
+ let mask: Buffer | null = null;
1464
+ if (isMasked) {
1465
+ mask = incomingBuffer.subarray(offset, offset + 4);
1466
+ offset += 4;
1467
+ }
1468
+
1469
+ const rawPayload = incomingBuffer.subarray(offset, offset + payloadLength);
1470
+ incomingBuffer = incomingBuffer.subarray(offset + payloadLength);
1471
+
1472
+ const payload = Buffer.alloc(payloadLength);
1473
+ if (isMasked && mask) {
1474
+ for (let i = 0; i < payloadLength; i++) {
1475
+ payload[i] = rawPayload[i] ^ mask[i % 4];
1476
+ }
1477
+ } else {
1478
+ rawPayload.copy(payload);
1479
+ }
1480
+
1481
+ // Handle frame
1482
+ if (opcode === 8) {
1483
+ // Close
1484
+ client.closed = true;
1485
+ cleanupClient(client);
1486
+ socket.end();
1487
+ break;
1488
+ } else if (opcode === 9) {
1489
+ // Ping -> Pong
1490
+ const pong = Buffer.alloc(2);
1491
+ pong[0] = 0x8a;
1492
+ pong[1] = 0;
1493
+ socket.write(pong);
1494
+ } else if (opcode === 1) {
1495
+ // Text frame (JSON command)
1496
+ try {
1497
+ const cmd = JSON.parse(payload.toString("utf8"));
1498
+ await handleClientCommand(client, cmd);
1499
+ } catch (e) {
1500
+ audioLogger.error(`Error processing text frame: ${e}`);
1501
+ }
1502
+ } else if (opcode === 2) {
1503
+ // Binary frame (Audio PCM 16kHz Chunk)
1504
+ await handleAudioChunk(client, payload);
1505
+ }
1506
+ if (client.closed) {
1507
+ incomingBuffer = Buffer.alloc(0);
1508
+ return;
1509
+ }
1510
+ }
1511
+ } finally {
1512
+ processing = false;
1513
+ }
1514
+ };
1515
+
1516
+ socket.on("data", (chunk: Buffer) => {
1517
+ if (client.closed) return;
1518
+ if (incomingBuffer.length + chunk.length > MAX_WS_INCOMING_BUFFER_BYTES) {
1519
+ closeClient(client, 1009, "WebSocket input buffer is too large");
1520
+ incomingBuffer = Buffer.alloc(0);
1521
+ return;
1522
+ }
1523
+ incomingBuffer = Buffer.concat([incomingBuffer, chunk]);
1524
+ void processFrames();
1525
+ });
1526
+
1527
+ socket.on("close", () => {
1528
+ client.closed = true;
1529
+ cleanupClient(client);
1530
+ incomingBuffer = Buffer.alloc(0);
1531
+ });
1532
+
1533
+ socket.on("error", () => {
1534
+ client.closed = true;
1535
+ cleanupClient(client);
1536
+ incomingBuffer = Buffer.alloc(0);
1537
+ });
1538
+ }