@kuralle-syrinx/grok 2.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,22 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Kuralle
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
22
+
package/README.md ADDED
@@ -0,0 +1,116 @@
1
+ # @kuralle-syrinx/grok
2
+
3
+ xAI Grok voice provider for Syrinx — streaming STT, streaming TTS, and speech-to-speech realtime.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ pnpm add @kuralle-syrinx/grok
9
+ ```
10
+
11
+ ## Auth
12
+
13
+ Pass `apiKey` in plugin config or adapter options. For local smokes, set `XAI_API_KEY` in the repo-root `.env`.
14
+
15
+ ## Streaming STT — `GrokSTTPlugin`
16
+
17
+ ```typescript
18
+ import { GrokSTTPlugin } from "@kuralle-syrinx/grok/stt";
19
+ import { createNodeWsSocket } from "@kuralle-syrinx/ws/node";
20
+
21
+ const stt = new GrokSTTPlugin(createNodeWsSocket);
22
+ await stt.initialize(bus, {
23
+ api_key: process.env.XAI_API_KEY!,
24
+ language: "en",
25
+ sample_rate: 16000,
26
+ });
27
+ ```
28
+
29
+ Connects to `wss://api.x.ai/v1/stt` with query-param config. Sends raw PCM16 frames after `transcript.created`, then `{"type":"audio.done"}` on finalize/shutdown. Emits `stt.interim`, `stt.result`, and `eos.turn_complete` (when `speech_final`).
30
+
31
+ ## Streaming TTS — `GrokTTSPlugin`
32
+
33
+ ```typescript
34
+ import { GrokTTSPlugin } from "@kuralle-syrinx/grok/tts";
35
+
36
+ const tts = new GrokTTSPlugin(createNodeWsSocket);
37
+ await tts.initialize(bus, {
38
+ api_key: process.env.XAI_API_KEY!,
39
+ voice_id: "eve",
40
+ sample_rate: 16000,
41
+ });
42
+ ```
43
+
44
+ Connects to `wss://api.x.ai/v1/tts?codec=pcm&sample_rate=16000`. Consumes `tts.text` / `tts.done`, emits `tts.audio` + `tts.end`. Uses `text.delta` / `text.done` / `text.clear` on the wire.
45
+
46
+ ## Realtime S2S — `fromGrokRealtime`
47
+
48
+ ```typescript
49
+ import { fromGrokRealtime } from "@kuralle-syrinx/grok/realtime";
50
+ import { RealtimeBridge } from "@kuralle-syrinx/realtime";
51
+
52
+ const adapter = fromGrokRealtime({
53
+ apiKey: process.env.XAI_API_KEY!,
54
+ socketFactory: createNodeWsSocket,
55
+ voice: "eve",
56
+ turnDetection: { type: "server_vad" },
57
+ tools: [/* caller-supplied RealtimeToolDef[] */],
58
+ });
59
+ const bridge = new RealtimeBridge(adapter);
60
+ ```
61
+
62
+ OpenAI Realtime-compatible subset on `wss://api.x.ai/v1/realtime?model=grok-voice-latest`. Caps: `supportsTruncate: false`, `supportsConcurrentToolAudio: false`. Barge-in relies on client/kernel VAD plus `response.cancel` (no `speech_started` / truncate).
63
+
64
+ ## Deploy on Cloudflare Workers
65
+
66
+ `@kuralle-syrinx/grok` is **edge-clean**: no `Buffer`, `process`, or `node:*` in `src/`. All three surfaces (STT, TTS, realtime S2S) accept an injectable `SocketFactory` — on Workers, outbound provider WebSockets that require auth headers use the fetch-upgrade path via `createWorkersSocket` (not the global `WebSocket` constructor, which cannot set headers).
67
+
68
+ Wire secrets through the Worker **`env` binding** (Wrangler secrets / vars), not `process.env`. Pass `apiKey` as constructor/initialize config:
69
+
70
+ ```ts
71
+ import { VoiceAgentSession } from "@kuralle-syrinx/core";
72
+ import { GrokSTTPlugin } from "@kuralle-syrinx/grok/stt";
73
+ import { GrokTTSPlugin } from "@kuralle-syrinx/grok/tts";
74
+ import { fromGrokRealtime } from "@kuralle-syrinx/grok/realtime";
75
+ import { RealtimeBridge } from "@kuralle-syrinx/realtime";
76
+ import { createWorkersSocket } from "@kuralle-syrinx/ws/workers";
77
+
78
+ /** Bound in wrangler.jsonc / dashboard — e.g. XAI_API_KEY secret. */
79
+ export interface Env {
80
+ readonly XAI_API_KEY: string;
81
+ }
82
+
83
+ export function createGrokVoiceSession(env: Env): VoiceAgentSession {
84
+ const stt = new GrokSTTPlugin(createWorkersSocket);
85
+ const tts = new GrokTTSPlugin(createWorkersSocket);
86
+ const adapter = fromGrokRealtime({
87
+ apiKey: env.XAI_API_KEY,
88
+ socketFactory: createWorkersSocket,
89
+ voice: "eve",
90
+ turnDetection: { type: "server_vad" },
91
+ });
92
+
93
+ const session = new VoiceAgentSession({
94
+ endpointingOwner: "timer",
95
+ plugins: { stt: {}, tts: {}, realtime: {} },
96
+ });
97
+ session.registerPlugin("stt", stt);
98
+ session.registerPlugin("tts", tts);
99
+ session.registerPlugin("realtime", new RealtimeBridge(adapter));
100
+ return session;
101
+ }
102
+ ```
103
+
104
+ **Durable Object session shape** (see `packages/server-workers`): the Worker `fetch` handler routes `/ws?sessionId=…` to a `VoiceConversation` Durable Object. The DO accepts the client upgrade via `WebSocketPair`, constructs the `VoiceAgentSession` (cascade or bi-model realtime — same env-injection pattern), and pumps audio over the accepted socket. Provider outbound legs (Grok STT/TTS/realtime, Deepgram, Cartesia, …) all dial through `createWorkersSocket` so auth headers ride on the fetch upgrade.
105
+
106
+ Regression lock: `edge-safety.test.ts` scans `src/` for Node-only primitives and runs the realtime audio path with a mock socket.
107
+
108
+ ## Live smokes
109
+
110
+ From `examples/02-hello-voice-headless` (requires `XAI_API_KEY`):
111
+
112
+ ```bash
113
+ pnpm smoke:grok-stt
114
+ pnpm smoke:grok-tts
115
+ pnpm smoke:grok-realtime
116
+ ```
package/package.json ADDED
@@ -0,0 +1,30 @@
1
+ {
2
+ "name": "@kuralle-syrinx/grok",
3
+ "version": "2.1.0",
4
+ "private": false,
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "main": "./src/index.ts",
8
+ "types": "./src/index.ts",
9
+ "exports": {
10
+ ".": "./src/index.ts",
11
+ "./stt": "./src/stt.ts",
12
+ "./tts": "./src/tts.ts",
13
+ "./realtime": "./src/from-grok-realtime.ts"
14
+ },
15
+ "dependencies": {
16
+ "@kuralle-syrinx/core": "2.1.0",
17
+ "@kuralle-syrinx/ws": "2.1.0",
18
+ "@kuralle-syrinx/realtime": "2.1.0"
19
+ },
20
+ "devDependencies": {
21
+ "@types/ws": "^8.5.0",
22
+ "typescript": "^5.7.0",
23
+ "vitest": "^2.1.0",
24
+ "ws": "^8.18.0"
25
+ },
26
+ "scripts": {
27
+ "typecheck": "tsc --noEmit",
28
+ "test": "vitest run"
29
+ }
30
+ }
@@ -0,0 +1,146 @@
1
+ // SPDX-License-Identifier: MIT
2
+ //
3
+ // Regression gate — the grok package must run on workerd without Buffer, process,
4
+ // or node:* imports. Reintroducing any Node-only primitive in src/ should fail.
5
+
6
+ import { readFileSync, readdirSync } from "node:fs";
7
+ import path from "node:path";
8
+ import { fileURLToPath } from "node:url";
9
+
10
+ import { describe, expect, it } from "vitest";
11
+
12
+ import type { ManagedSocket, SocketData, SocketFactory } from "@kuralle-syrinx/ws";
13
+
14
+ import { bytesToBase64, fromGrokRealtime } from "./from-grok-realtime.js";
15
+ import type { RealtimeEvent } from "@kuralle-syrinx/realtime";
16
+
17
+ const srcDir = path.dirname(fileURLToPath(import.meta.url));
18
+
19
+ interface EdgeMockHarness {
20
+ readonly factory: SocketFactory;
21
+ readonly sent: string[];
22
+ inject(msg: Record<string, unknown>): void;
23
+ }
24
+
25
+ function createEdgeMockHarness(): EdgeMockHarness {
26
+ const sent: string[] = [];
27
+ let messageHandler: ((data: SocketData, isBinary: boolean) => void) | null = null;
28
+
29
+ const socket: ManagedSocket = {
30
+ get isOpen() {
31
+ return true;
32
+ },
33
+ send: (data: SocketData) => {
34
+ sent.push(typeof data === "string" ? data : "");
35
+ },
36
+ keepAlivePing: () => {},
37
+ verify: async () => true,
38
+ dispose: () => {},
39
+ onOpen: (handler) => {
40
+ queueMicrotask(() => handler());
41
+ },
42
+ onMessage: (handler) => {
43
+ messageHandler = handler;
44
+ },
45
+ onClose: () => {},
46
+ onError: () => {},
47
+ };
48
+
49
+ return {
50
+ factory: () => socket,
51
+ sent,
52
+ inject: (msg) => messageHandler?.(JSON.stringify(msg), false),
53
+ };
54
+ }
55
+
56
+ function collectSourceFiles(dir: string): string[] {
57
+ const out: string[] = [];
58
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
59
+ const full = path.join(dir, entry.name);
60
+ if (entry.isDirectory()) {
61
+ out.push(...collectSourceFiles(full));
62
+ continue;
63
+ }
64
+ if (entry.name.endsWith(".ts") && !entry.name.endsWith(".test.ts")) {
65
+ out.push(full);
66
+ }
67
+ }
68
+ return out;
69
+ }
70
+
71
+ async function collectEvents(
72
+ events: AsyncIterable<RealtimeEvent>,
73
+ max = 2,
74
+ ): Promise<RealtimeEvent[]> {
75
+ const out: RealtimeEvent[] = [];
76
+ for await (const event of events) {
77
+ out.push(event);
78
+ if (out.length >= max) break;
79
+ }
80
+ return out;
81
+ }
82
+
83
+ async function waitFor(predicate: () => boolean, timeoutMs = 2000): Promise<void> {
84
+ const startedAt = Date.now();
85
+ while (Date.now() - startedAt < timeoutMs) {
86
+ if (predicate()) return;
87
+ await new Promise((resolve) => setTimeout(resolve, 5));
88
+ }
89
+ throw new Error("Timed out waiting for condition");
90
+ }
91
+
92
+ describe("edge safety (grok)", () => {
93
+ it("src/ contains no Buffer, process, or node:* imports", () => {
94
+ const forbidden = [
95
+ /\bfrom\s+["']node:/,
96
+ /\brequire\s*\(\s*["']node:/,
97
+ /\bglobalThis\.Buffer\b/,
98
+ /\bglobalThis\.process\b/,
99
+ /\bprocess\.env\b/,
100
+ /\bBuffer\.from\b/,
101
+ /\bBuffer\.alloc\b/,
102
+ ];
103
+ const hits: string[] = [];
104
+ for (const file of collectSourceFiles(srcDir)) {
105
+ const text = readFileSync(file, "utf8");
106
+ for (const pattern of forbidden) {
107
+ if (pattern.test(text)) {
108
+ hits.push(`${path.relative(srcDir, file)}: ${pattern.source}`);
109
+ }
110
+ }
111
+ }
112
+ expect(hits).toEqual([]);
113
+ });
114
+
115
+ it("fromGrokRealtime round-trips audio via runtime-agnostic helpers", async () => {
116
+ const mock = createEdgeMockHarness();
117
+ const adapter = fromGrokRealtime({
118
+ apiKey: "edge-test-key",
119
+ socketFactory: mock.factory,
120
+ url: () => "wss://example.test/realtime?model=grok-voice-latest",
121
+ });
122
+
123
+ const eventsTask = collectEvents(adapter.events, 2);
124
+ const openTask = adapter.open(new AbortController().signal);
125
+ await waitFor(() => mock.sent.length > 0);
126
+ mock.inject({ type: "session.updated" });
127
+ await openTask;
128
+
129
+ const providerPcm = new Uint8Array([100, 200, 300, 400]);
130
+ mock.inject({ type: "response.created" });
131
+ mock.inject({
132
+ type: "response.output_audio.delta",
133
+ delta: bytesToBase64(providerPcm),
134
+ });
135
+
136
+ const events = await eventsTask;
137
+ expect(events[0]).toEqual({ type: "response_started" });
138
+ expect(events[1]).toEqual({
139
+ type: "audio",
140
+ pcm16: providerPcm,
141
+ sampleRateHz: 24_000,
142
+ });
143
+
144
+ await adapter.close();
145
+ });
146
+ });
@@ -0,0 +1,279 @@
1
+ // SPDX-License-Identifier: MIT
2
+
3
+ import { describe, expect, it } from "vitest";
4
+
5
+ import type { ManagedSocket, SocketData, SocketFactory } from "@kuralle-syrinx/ws";
6
+
7
+ import type { RealtimeEvent } from "@kuralle-syrinx/realtime";
8
+
9
+ import { bytesToBase64, fromGrokRealtime } from "./from-grok-realtime.js";
10
+
11
+ interface MockSocketHarness {
12
+ readonly factory: SocketFactory;
13
+ readonly sent: string[];
14
+ inject(msg: Record<string, unknown>): void;
15
+ }
16
+
17
+ function createMockSocketHarness(): MockSocketHarness {
18
+ const sent: string[] = [];
19
+ let messageHandler: ((data: SocketData, isBinary: boolean) => void) | null = null;
20
+
21
+ const socket: ManagedSocket = {
22
+ get isOpen() {
23
+ return true;
24
+ },
25
+ send: (data: SocketData) => {
26
+ sent.push(typeof data === "string" ? data : "");
27
+ },
28
+ keepAlivePing: () => {},
29
+ verify: async () => true,
30
+ dispose: () => {},
31
+ onOpen: (handler) => {
32
+ queueMicrotask(() => handler());
33
+ },
34
+ onMessage: (handler) => {
35
+ messageHandler = handler;
36
+ },
37
+ onClose: () => {},
38
+ onError: () => {},
39
+ };
40
+
41
+ return {
42
+ factory: () => socket,
43
+ sent,
44
+ inject: (msg) => messageHandler?.(JSON.stringify(msg), false),
45
+ };
46
+ }
47
+
48
+ async function collectEvents(
49
+ events: AsyncIterable<RealtimeEvent>,
50
+ max = 8,
51
+ ): Promise<RealtimeEvent[]> {
52
+ const out: RealtimeEvent[] = [];
53
+ for await (const event of events) {
54
+ out.push(event);
55
+ if (out.length >= max) break;
56
+ }
57
+ return out;
58
+ }
59
+
60
+ async function waitFor(predicate: () => boolean, timeoutMs = 2000): Promise<void> {
61
+ const startedAt = Date.now();
62
+ while (Date.now() - startedAt < timeoutMs) {
63
+ if (predicate()) return;
64
+ await new Promise((resolve) => setTimeout(resolve, 5));
65
+ }
66
+ throw new Error("Timed out waiting for condition");
67
+ }
68
+
69
+ describe("fromGrokRealtime", () => {
70
+ it("sends Grok session.update and client control messages", async () => {
71
+ const mock = createMockSocketHarness();
72
+ const adapter = fromGrokRealtime({
73
+ apiKey: "test-key",
74
+ socketFactory: mock.factory,
75
+ url: () => "wss://example.test/realtime?model=grok-voice-latest",
76
+ voice: "eve",
77
+ instructions: "Be concise.",
78
+ turnDetection: { type: "server_vad" },
79
+ tools: [
80
+ {
81
+ name: "lookup",
82
+ description: "Look up facts.",
83
+ parameters: { type: "object", properties: { q: { type: "string" } }, required: ["q"] },
84
+ },
85
+ ],
86
+ });
87
+
88
+ const openTask = adapter.open(new AbortController().signal);
89
+ await waitFor(() => mock.sent.length > 0);
90
+ mock.inject({ type: "session.updated" });
91
+ await openTask;
92
+
93
+ expect(JSON.parse(mock.sent[0]!)).toEqual({
94
+ type: "session.update",
95
+ session: {
96
+ voice: "eve",
97
+ instructions: "Be concise.",
98
+ turn_detection: { type: "server_vad" },
99
+ tools: [
100
+ {
101
+ type: "function",
102
+ name: "lookup",
103
+ description: "Look up facts.",
104
+ parameters: { type: "object", properties: { q: { type: "string" } }, required: ["q"] },
105
+ },
106
+ ],
107
+ audio: {
108
+ input: { format: { type: "audio/pcm", rate: 24000 } },
109
+ output: { format: { type: "audio/pcm", rate: 24000 }, voice: "eve" },
110
+ },
111
+ },
112
+ });
113
+
114
+ const pcm = new Uint8Array([0, 1, 2, 3]);
115
+ adapter.sendAudio(pcm);
116
+ expect(JSON.parse(mock.sent[1]!)).toEqual({
117
+ type: "input_audio_buffer.append",
118
+ audio: bytesToBase64(pcm),
119
+ });
120
+
121
+ mock.inject({ type: "response.created" });
122
+ adapter.cancelResponse(420);
123
+ expect(JSON.parse(mock.sent[2]!)).toEqual({ type: "response.cancel" });
124
+ expect(
125
+ mock.sent
126
+ .map((raw) => JSON.parse(raw) as Record<string, unknown>)
127
+ .some((msg) => msg["type"] === "conversation.item.truncate"),
128
+ ).toBe(false);
129
+
130
+ adapter.injectToolResult("call_abc", "result text");
131
+ expect(JSON.parse(mock.sent[3]!)).toEqual({
132
+ type: "conversation.item.create",
133
+ item: {
134
+ type: "function_call_output",
135
+ call_id: "call_abc",
136
+ output: "result text",
137
+ },
138
+ });
139
+ expect(mock.sent).toHaveLength(4);
140
+
141
+ mock.inject({ type: "response.done", response: {} });
142
+ expect(JSON.parse(mock.sent[4]!)).toEqual({ type: "response.create" });
143
+ });
144
+
145
+ it("normalizes provider server events into RealtimeEvent", async () => {
146
+ const mock = createMockSocketHarness();
147
+ const adapter = fromGrokRealtime({
148
+ apiKey: "test-key",
149
+ socketFactory: mock.factory,
150
+ url: () => "wss://example.test/realtime?model=grok-voice-latest",
151
+ });
152
+
153
+ const eventsTask = collectEvents(adapter.events, 7);
154
+ const openTask = adapter.open(new AbortController().signal);
155
+ await waitFor(() => mock.sent.length > 0);
156
+ mock.inject({ type: "session.updated" });
157
+ await openTask;
158
+
159
+ const audioBytes = new Uint8Array([9, 10, 11, 12]);
160
+ mock.inject({ type: "response.created" });
161
+ mock.inject({ type: "response.output_audio.delta", delta: bytesToBase64(audioBytes) });
162
+ mock.inject({
163
+ type: "conversation.item.input_audio_transcription.updated",
164
+ transcript: "hello there",
165
+ });
166
+ mock.inject({ type: "response.output_audio_transcript.delta", delta: "Sure, " });
167
+ mock.inject({
168
+ type: "response.output_audio_transcript.done",
169
+ transcript: "Sure, I can help.",
170
+ });
171
+ mock.inject({
172
+ type: "response.done",
173
+ response: {
174
+ output: [
175
+ {
176
+ type: "function_call",
177
+ call_id: "call_123",
178
+ name: "lookup",
179
+ arguments: JSON.stringify({ q: "hours" }),
180
+ },
181
+ ],
182
+ },
183
+ });
184
+
185
+ const events = await eventsTask;
186
+ expect(events.slice(0, 6)).toEqual([
187
+ { type: "response_started" },
188
+ { type: "audio", pcm16: audioBytes, sampleRateHz: 24000 },
189
+ { type: "transcript", role: "user", text: "hello there", final: true },
190
+ { type: "transcript", role: "assistant", text: "Sure, ", final: false },
191
+ { type: "transcript", role: "assistant", text: "Sure, I can help.", final: true },
192
+ {
193
+ type: "tool_call",
194
+ toolId: "call_123",
195
+ toolName: "lookup",
196
+ args: { q: "hours" },
197
+ },
198
+ ]);
199
+ expect(events[6]).toEqual({ type: "response_done" });
200
+ });
201
+
202
+ it("B1: does not send response.create while response is active (cancel-in-flight, no truncate)", async () => {
203
+ const mock = createMockSocketHarness();
204
+ const adapter = fromGrokRealtime({
205
+ apiKey: "test-key",
206
+ socketFactory: mock.factory,
207
+ url: () => "wss://example.test/realtime?model=grok-voice-latest",
208
+ });
209
+
210
+ const openTask = adapter.open(new AbortController().signal);
211
+ await waitFor(() => mock.sent.length > 0);
212
+ mock.inject({ type: "session.updated" });
213
+ await openTask;
214
+
215
+ mock.inject({ type: "response.created" });
216
+ adapter.cancelResponse(420);
217
+ expect(JSON.parse(mock.sent[1]!)).toEqual({ type: "response.cancel" });
218
+ expect(
219
+ mock.sent
220
+ .map((raw) => JSON.parse(raw) as Record<string, unknown>)
221
+ .some((msg) => msg["type"] === "conversation.item.truncate"),
222
+ ).toBe(false);
223
+
224
+ adapter.injectToolResult("call_abc", "result text");
225
+ const typesAfterInject = mock.sent.map(
226
+ (raw) => (JSON.parse(raw) as Record<string, unknown>)["type"],
227
+ );
228
+ expect(typesAfterInject).toContain("conversation.item.create");
229
+ expect(typesAfterInject).not.toContain("response.create");
230
+
231
+ mock.inject({ type: "response.done", response: {} });
232
+ expect(JSON.parse(mock.sent[mock.sent.length - 1]!)).toEqual({ type: "response.create" });
233
+ });
234
+
235
+ it("B1: does not send response.create while response is active (direct inject without cancel)", async () => {
236
+ const mock = createMockSocketHarness();
237
+ const adapter = fromGrokRealtime({
238
+ apiKey: "test-key",
239
+ socketFactory: mock.factory,
240
+ url: () => "wss://example.test/realtime?model=grok-voice-latest",
241
+ });
242
+
243
+ const openTask = adapter.open(new AbortController().signal);
244
+ await waitFor(() => mock.sent.length > 0);
245
+ mock.inject({ type: "session.updated" });
246
+ await openTask;
247
+
248
+ mock.inject({ type: "response.created" });
249
+
250
+ adapter.injectToolResult("call_xyz", "inline result");
251
+ const typesAfterInject = mock.sent.map(
252
+ (raw) => (JSON.parse(raw) as Record<string, unknown>)["type"],
253
+ );
254
+ expect(typesAfterInject).toContain("conversation.item.create");
255
+ expect(typesAfterInject).not.toContain("response.create");
256
+
257
+ mock.inject({ type: "response.done", response: {} });
258
+ expect(
259
+ mock.sent.map((raw) => (JSON.parse(raw) as Record<string, unknown>)["type"]),
260
+ ).toContain("response.create");
261
+ });
262
+
263
+ it("exposes Grok capability flags", () => {
264
+ const mock = createMockSocketHarness();
265
+ const adapter = fromGrokRealtime({
266
+ apiKey: "test-key",
267
+ socketFactory: mock.factory,
268
+ inputRateHz: 16000,
269
+ outputRateHz: 16000,
270
+ });
271
+ expect(adapter.caps).toEqual({
272
+ inputSampleRateHz: 16000,
273
+ outputSampleRateHz: 16000,
274
+ supportsConcurrentToolAudio: false,
275
+ supportsTruncate: false,
276
+ emitsServerSpeechStarted: false,
277
+ });
278
+ });
279
+ });
@@ -0,0 +1,94 @@
1
+ // SPDX-License-Identifier: MIT
2
+
3
+ import type { SocketFactory } from "@kuralle-syrinx/ws";
4
+ import {
5
+ base64ToBytes,
6
+ bytesToBase64,
7
+ createOpenAiCompatibleRealtimeAdapter,
8
+ type RealtimeAdapter,
9
+ type RealtimeToolDef,
10
+ } from "@kuralle-syrinx/realtime";
11
+
12
+ const DEFAULT_MODEL = "grok-voice-latest";
13
+ const DEFAULT_VOICE = "eve";
14
+ const DEFAULT_SAMPLE_RATE_HZ = 24_000;
15
+
16
+ export interface GrokRealtimeOptions {
17
+ readonly apiKey: string;
18
+ readonly model?: string;
19
+ readonly voice?: string;
20
+ readonly socketFactory: SocketFactory;
21
+ readonly url?: () => string;
22
+ readonly turnDetection?: Record<string, unknown> | null;
23
+ readonly tools?: readonly RealtimeToolDef[];
24
+ readonly debug?: boolean;
25
+ readonly instructions?: string;
26
+ readonly inputRateHz?: number;
27
+ readonly outputRateHz?: number;
28
+ }
29
+
30
+ export function fromGrokRealtime(opts: GrokRealtimeOptions): RealtimeAdapter {
31
+ const inputRateHz = opts.inputRateHz ?? DEFAULT_SAMPLE_RATE_HZ;
32
+ const outputRateHz = opts.outputRateHz ?? DEFAULT_SAMPLE_RATE_HZ;
33
+ const voice = opts.voice ?? DEFAULT_VOICE;
34
+
35
+ return createOpenAiCompatibleRealtimeAdapter({
36
+ apiKey: opts.apiKey,
37
+ socketFactory: opts.socketFactory,
38
+ debug: opts.debug,
39
+ debugLogPrefix: "[grok-raw]",
40
+ defaultModel: DEFAULT_MODEL,
41
+ model: opts.model,
42
+ url: opts.url,
43
+ buildUrl: (model) => `wss://api.x.ai/v1/realtime?model=${encodeURIComponent(model)}`,
44
+ caps: {
45
+ inputSampleRateHz: inputRateHz,
46
+ outputSampleRateHz: outputRateHz,
47
+ supportsConcurrentToolAudio: false,
48
+ supportsTruncate: false,
49
+ emitsServerSpeechStarted: false,
50
+ },
51
+ buildSessionUpdate: () => {
52
+ const turnDetection =
53
+ "turnDetection" in opts ? opts.turnDetection : { type: "server_vad" };
54
+
55
+ const session: Record<string, unknown> = {
56
+ voice,
57
+ turn_detection: turnDetection,
58
+ tools: (opts.tools ?? []).map((t) => ({
59
+ type: "function" as const,
60
+ name: t.name,
61
+ description: t.description,
62
+ parameters: t.parameters,
63
+ })),
64
+ audio: {
65
+ input: { format: { type: "audio/pcm", rate: inputRateHz } },
66
+ output: { format: { type: "audio/pcm", rate: outputRateHz }, voice },
67
+ },
68
+ };
69
+
70
+ if (opts.instructions !== undefined) {
71
+ session["instructions"] = opts.instructions;
72
+ }
73
+
74
+ return session;
75
+ },
76
+ supportsTruncate: false,
77
+ defaultErrorMessage: "Grok Realtime error",
78
+ extendServerMessage: (type, msg, ctx) => {
79
+ if (type !== "conversation.item.input_audio_transcription.updated") return false;
80
+ const transcript = typeof msg["transcript"] === "string" ? msg["transcript"] : "";
81
+ if (transcript.length > 0) {
82
+ ctx.push({
83
+ type: "transcript",
84
+ role: "user",
85
+ text: transcript,
86
+ final: true,
87
+ });
88
+ }
89
+ return true;
90
+ },
91
+ });
92
+ }
93
+
94
+ export { base64ToBytes, bytesToBase64 };
package/src/index.ts ADDED
@@ -0,0 +1,5 @@
1
+ // SPDX-License-Identifier: MIT
2
+
3
+ export { GrokSTTPlugin } from "./stt.js";
4
+ export { GrokTTSPlugin } from "./tts.js";
5
+ export { fromGrokRealtime, type GrokRealtimeOptions } from "./from-grok-realtime.js";