@kuralle-syrinx/grok 4.2.0 → 4.3.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.
@@ -1,146 +0,0 @@
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
- });
@@ -1,279 +0,0 @@
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
- });
package/src/stt.test.ts DELETED
@@ -1,244 +0,0 @@
1
- // SPDX-License-Identifier: MIT
2
-
3
- import { afterEach, describe, expect, it } from "vitest";
4
- import { WebSocketServer, type WebSocket } from "ws";
5
- import {
6
- PipelineBusImpl,
7
- Route,
8
- type SttErrorPacket,
9
- type SttInterimPacket,
10
- type SttResultPacket,
11
- } from "@kuralle-syrinx/core";
12
-
13
- import { GrokSTTPlugin } from "./stt.js";
14
-
15
- let servers: WebSocketServer[] = [];
16
-
17
- afterEach(async () => {
18
- await Promise.all(
19
- servers.splice(0).map(
20
- (server) =>
21
- new Promise<void>((resolve) => {
22
- for (const client of server.clients) client.terminate();
23
- server.close(() => resolve());
24
- }),
25
- ),
26
- );
27
- });
28
-
29
- async function createLocalServer(onConnection: (socket: WebSocket) => void): Promise<string> {
30
- const server = await new Promise<WebSocketServer>((resolve) => {
31
- let nextServer: WebSocketServer;
32
- nextServer = new WebSocketServer({ port: 0 }, () => {
33
- resolve(nextServer);
34
- });
35
- });
36
- servers.push(server);
37
- server.on("connection", onConnection);
38
- const address = server.address();
39
- if (!address || typeof address === "string") throw new Error("Expected TCP server address");
40
- return `ws://127.0.0.1:${address.port}/stt`;
41
- }
42
-
43
- async function waitFor<T>(items: T[], count = 1): Promise<void> {
44
- for (let i = 0; i < 50; i += 1) {
45
- if (items.length >= count) return;
46
- await new Promise((resolve) => setTimeout(resolve, 10));
47
- }
48
- }
49
-
50
- describe("GrokSTTPlugin", () => {
51
- it("waits for transcript.created before sending binary audio", async () => {
52
- const binaryFrames: Uint8Array[] = [];
53
- const controlMessages: string[] = [];
54
- const endpointUrl = await createLocalServer((socket) => {
55
- socket.on("message", (data, isBinary) => {
56
- if (isBinary) {
57
- binaryFrames.push(new Uint8Array(data as Buffer));
58
- return;
59
- }
60
- controlMessages.push(data.toString());
61
- });
62
- socket.send(JSON.stringify({ type: "transcript.created" }));
63
- });
64
-
65
- const bus = new PipelineBusImpl();
66
- const started = bus.start();
67
- const plugin = new GrokSTTPlugin();
68
-
69
- await plugin.initialize(bus, {
70
- api_key: "test",
71
- endpoint_url: endpointUrl,
72
- sample_rate: 16000,
73
- });
74
- bus.push(Route.Main, {
75
- kind: "stt.audio",
76
- contextId: "turn-1",
77
- timestampMs: Date.now(),
78
- audio: new Uint8Array(640),
79
- });
80
- await waitFor(binaryFrames);
81
-
82
- expect(binaryFrames).toEqual([new Uint8Array(640)]);
83
- expect(controlMessages).toEqual([]);
84
-
85
- await plugin.close();
86
- await waitFor(controlMessages);
87
- expect(controlMessages).toContain(JSON.stringify({ type: "audio.done" }));
88
- bus.stop();
89
- await started;
90
- });
91
-
92
- it("maps transcript.partial to stt.interim and stt.result", async () => {
93
- const endpointUrl = await createLocalServer((socket) => {
94
- socket.send(JSON.stringify({ type: "transcript.created" }));
95
- socket.on("message", (data, isBinary) => {
96
- if (!isBinary) return;
97
- socket.send(JSON.stringify({
98
- type: "transcript.partial",
99
- text: "hello",
100
- is_final: false,
101
- }));
102
- socket.send(JSON.stringify({
103
- type: "transcript.partial",
104
- text: "hello world",
105
- is_final: true,
106
- speech_final: false,
107
- words: [{ word: "hello" }, { word: "world" }],
108
- start: 0,
109
- duration: 1.2,
110
- end_of_turn_confidence: 0.91,
111
- }));
112
- socket.send(JSON.stringify({
113
- type: "transcript.partial",
114
- text: "hello world",
115
- is_final: true,
116
- speech_final: true,
117
- end_of_turn_confidence: 0.95,
118
- }));
119
- });
120
- });
121
-
122
- const bus = new PipelineBusImpl();
123
- const started = bus.start();
124
- const plugin = new GrokSTTPlugin();
125
- const interims: Array<{ text: string }> = [];
126
- const finals: SttResultPacket[] = [];
127
- const turnCompletes: Array<{ kind: string }> = [];
128
- bus.on("stt.interim", (pkt) => {
129
- interims.push({ text: (pkt as SttInterimPacket).text });
130
- });
131
- bus.on("stt.result", (pkt) => {
132
- finals.push(pkt as SttResultPacket);
133
- });
134
- bus.on("eos.turn_complete", (pkt) => {
135
- turnCompletes.push(pkt as { kind: string });
136
- });
137
-
138
- await plugin.initialize(bus, {
139
- api_key: "test",
140
- endpoint_url: endpointUrl,
141
- sample_rate: 16000,
142
- });
143
- bus.push(Route.Main, {
144
- kind: "user.audio_received",
145
- contextId: "turn-2",
146
- timestampMs: Date.now(),
147
- audio: new Uint8Array(320),
148
- });
149
- await waitFor(finals, 2);
150
- await waitFor(turnCompletes);
151
-
152
- expect(interims).toEqual([{ text: "hello" }]);
153
- expect(finals[0]).toEqual(
154
- expect.objectContaining({
155
- kind: "stt.result",
156
- contextId: "turn-2",
157
- text: "hello world",
158
- confidence: 0.91,
159
- provider: expect.objectContaining({
160
- name: "grok",
161
- speechFinal: false,
162
- words: [{ word: "hello" }, { word: "world" }],
163
- start: 0,
164
- duration: 1.2,
165
- }),
166
- }),
167
- );
168
- expect(finals[1]).toEqual(
169
- expect.objectContaining({
170
- text: "hello world",
171
- confidence: 0.95,
172
- provider: expect.objectContaining({ speechFinal: true }),
173
- }),
174
- );
175
- expect(turnCompletes).toHaveLength(1);
176
-
177
- await plugin.close();
178
- bus.stop();
179
- await started;
180
- });
181
-
182
- it("sends audio.done on stt.finalize", async () => {
183
- const controlMessages: string[] = [];
184
- const endpointUrl = await createLocalServer((socket) => {
185
- socket.send(JSON.stringify({ type: "transcript.created" }));
186
- socket.on("message", (data, isBinary) => {
187
- if (!isBinary) controlMessages.push(data.toString());
188
- });
189
- });
190
-
191
- const bus = new PipelineBusImpl();
192
- const started = bus.start();
193
- const plugin = new GrokSTTPlugin();
194
-
195
- await plugin.initialize(bus, {
196
- api_key: "test",
197
- endpoint_url: endpointUrl,
198
- sample_rate: 16000,
199
- });
200
- bus.push(Route.Main, {
201
- kind: "stt.finalize",
202
- contextId: "turn-3",
203
- timestampMs: Date.now(),
204
- });
205
- await waitFor(controlMessages);
206
-
207
- expect(JSON.parse(controlMessages[0]!)).toEqual({ type: "audio.done" });
208
-
209
- await plugin.close();
210
- bus.stop();
211
- await started;
212
- });
213
-
214
- it("maps provider error frames to stt.error", async () => {
215
- const endpointUrl = await createLocalServer((socket) => {
216
- socket.send(JSON.stringify({ type: "error", message: "bad audio format" }));
217
- });
218
- const bus = new PipelineBusImpl();
219
- const started = bus.start();
220
- const plugin = new GrokSTTPlugin();
221
- const errors: SttErrorPacket[] = [];
222
- bus.on("stt.error", (pkt) => {
223
- errors.push(pkt as SttErrorPacket);
224
- });
225
-
226
- await plugin.initialize(bus, {
227
- api_key: "test",
228
- endpoint_url: endpointUrl,
229
- sample_rate: 16000,
230
- });
231
- await waitFor(errors);
232
-
233
- expect(errors[0]).toEqual(
234
- expect.objectContaining({
235
- kind: "stt.error",
236
- cause: expect.objectContaining({ message: "bad audio format" }),
237
- }),
238
- );
239
-
240
- await plugin.close();
241
- bus.stop();
242
- await started;
243
- });
244
- });