@livekit/agents-plugin-openai 1.8.0 → 1.9.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/dist/index.cjs +1 -1
- package/dist/index.js +1 -1
- package/dist/realtime/gpt_live_model.cjs +883 -0
- package/dist/realtime/gpt_live_model.cjs.map +1 -0
- package/dist/realtime/gpt_live_model.d.cts +184 -0
- package/dist/realtime/gpt_live_model.d.ts +184 -0
- package/dist/realtime/gpt_live_model.d.ts.map +1 -0
- package/dist/realtime/gpt_live_model.js +859 -0
- package/dist/realtime/gpt_live_model.js.map +1 -0
- package/dist/realtime/gpt_live_model.test.cjs +1436 -0
- package/dist/realtime/gpt_live_model.test.cjs.map +1 -0
- package/dist/realtime/gpt_live_model.test.d.cts +2 -0
- package/dist/realtime/gpt_live_model.test.d.ts +2 -0
- package/dist/realtime/gpt_live_model.test.d.ts.map +1 -0
- package/dist/realtime/gpt_live_model.test.js +1437 -0
- package/dist/realtime/gpt_live_model.test.js.map +1 -0
- package/dist/realtime/gpt_live_types.cjs +17 -0
- package/dist/realtime/gpt_live_types.cjs.map +1 -0
- package/dist/realtime/gpt_live_types.d.cts +170 -0
- package/dist/realtime/gpt_live_types.d.ts +170 -0
- package/dist/realtime/gpt_live_types.d.ts.map +1 -0
- package/dist/realtime/gpt_live_types.js +1 -0
- package/dist/realtime/gpt_live_types.js.map +1 -0
- package/dist/realtime/index.cjs +22 -1
- package/dist/realtime/index.cjs.map +1 -1
- package/dist/realtime/index.d.cts +2 -0
- package/dist/realtime/index.d.ts +2 -0
- package/dist/realtime/index.d.ts.map +1 -1
- package/dist/realtime/index.js +5 -0
- package/dist/realtime/index.js.map +1 -1
- package/dist/tool_utils.cjs +12 -8
- package/dist/tool_utils.cjs.map +1 -1
- package/dist/tool_utils.d.cts +1 -0
- package/dist/tool_utils.d.ts +1 -0
- package/dist/tool_utils.d.ts.map +1 -1
- package/dist/tool_utils.js +11 -8
- package/dist/tool_utils.js.map +1 -1
- package/dist/tool_utils.test.cjs +27 -0
- package/dist/tool_utils.test.cjs.map +1 -1
- package/dist/tool_utils.test.js +27 -0
- package/dist/tool_utils.test.js.map +1 -1
- package/package.json +5 -5
- package/src/realtime/gpt_live_model.test.ts +1509 -0
- package/src/realtime/gpt_live_model.ts +1040 -0
- package/src/realtime/gpt_live_types.ts +140 -0
- package/src/realtime/index.ts +2 -0
- package/src/tool_utils.test.ts +30 -0
- package/src/tool_utils.ts +21 -18
|
@@ -0,0 +1,1436 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var import_agents = require("@livekit/agents");
|
|
3
|
+
var import_rtc_node = require("@livekit/rtc-node");
|
|
4
|
+
var import_node_events = require("node:events");
|
|
5
|
+
var import_promises = require("node:timers/promises");
|
|
6
|
+
var import_vitest = require("vitest");
|
|
7
|
+
var import_ws = require("ws");
|
|
8
|
+
var import_zod = require("zod");
|
|
9
|
+
var import_tools = require("../tools.cjs");
|
|
10
|
+
var import_gpt_live_model = require("./gpt_live_model.cjs");
|
|
11
|
+
(0, import_agents.initializeLogger)({ pretty: false, level: "silent" });
|
|
12
|
+
const weather = import_agents.llm.tool({
|
|
13
|
+
name: "getWeather",
|
|
14
|
+
description: "Get the weather.",
|
|
15
|
+
parameters: import_zod.z.object({ location: import_zod.z.string() }),
|
|
16
|
+
execute: async () => "rainy"
|
|
17
|
+
});
|
|
18
|
+
const tools = new import_agents.llm.ToolContext([weather]);
|
|
19
|
+
const pcm = (duration = 100, level = 0, rate = 24e3, channels = 1) => {
|
|
20
|
+
const samples = new Int16Array(rate * duration / 1e3 * channels);
|
|
21
|
+
for (let i = 0; i < samples.length; i++)
|
|
22
|
+
samples[i] = Math.trunc(level * 32767) * (i % 2 ? -1 : 1);
|
|
23
|
+
return new import_rtc_node.AudioFrame(samples, rate, channels, samples.length / channels);
|
|
24
|
+
};
|
|
25
|
+
const transcript = (role, delta, start) => ({
|
|
26
|
+
type: role === "user" ? "session.input_transcript.delta" : "session.output_transcript.delta",
|
|
27
|
+
delta,
|
|
28
|
+
start_ms: start,
|
|
29
|
+
end_ms: start + 200
|
|
30
|
+
});
|
|
31
|
+
const callDone = (callId) => ({
|
|
32
|
+
type: "response.output_item.done",
|
|
33
|
+
item: {
|
|
34
|
+
id: `fc_${callId}`,
|
|
35
|
+
type: "function_call",
|
|
36
|
+
call_id: callId,
|
|
37
|
+
name: "getWeather",
|
|
38
|
+
arguments: '{"location":"Paris"}'
|
|
39
|
+
}
|
|
40
|
+
});
|
|
41
|
+
const completed = () => ({
|
|
42
|
+
type: "response.completed",
|
|
43
|
+
response: {
|
|
44
|
+
id: "resp_1",
|
|
45
|
+
model: "gpt-5.6-sol",
|
|
46
|
+
usage: {
|
|
47
|
+
input_tokens: 376,
|
|
48
|
+
input_tokens_details: { cached_tokens: 100, cache_write_tokens: 20 },
|
|
49
|
+
output_tokens: 18,
|
|
50
|
+
output_tokens_details: { reasoning_tokens: 5 },
|
|
51
|
+
total_tokens: 394
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
});
|
|
55
|
+
const output = (callId) => new import_agents.llm.FunctionCallOutput({ callId, name: "getWeather", output: "rainy", isError: false });
|
|
56
|
+
class Server {
|
|
57
|
+
server = new import_ws.WebSocketServer({ port: 0, host: "127.0.0.1" });
|
|
58
|
+
sockets = [];
|
|
59
|
+
sent = [];
|
|
60
|
+
autoStart = true;
|
|
61
|
+
autoClose = true;
|
|
62
|
+
closeUsage = 0;
|
|
63
|
+
closeReason = "close_requested";
|
|
64
|
+
requests = [];
|
|
65
|
+
constructor() {
|
|
66
|
+
this.server.on("connection", (ws, req) => {
|
|
67
|
+
const events = [];
|
|
68
|
+
const index = this.sockets.length;
|
|
69
|
+
this.sockets.push(ws);
|
|
70
|
+
this.sent.push(events);
|
|
71
|
+
this.requests.push({ url: req.url, headers: req.headers });
|
|
72
|
+
ws.on("message", (data) => {
|
|
73
|
+
const event = JSON.parse(data.toString());
|
|
74
|
+
events.push(event);
|
|
75
|
+
if (event.type === "session.start" && this.autoStart)
|
|
76
|
+
ws.send(JSON.stringify({ type: "session.started", session: { id: `live_${index}` } }));
|
|
77
|
+
if (event.type === "session.close" && this.autoClose)
|
|
78
|
+
ws.send(
|
|
79
|
+
JSON.stringify({
|
|
80
|
+
type: "session.closed",
|
|
81
|
+
reason: this.closeReason,
|
|
82
|
+
usage: { seconds: this.closeUsage }
|
|
83
|
+
})
|
|
84
|
+
);
|
|
85
|
+
});
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
get url() {
|
|
89
|
+
return `http://127.0.0.1:${this.server.address().port}/v1`;
|
|
90
|
+
}
|
|
91
|
+
events(index = 0) {
|
|
92
|
+
return this.sent[index] ?? [];
|
|
93
|
+
}
|
|
94
|
+
async send(session, event, index = this.sockets.length - 1) {
|
|
95
|
+
const received = (0, import_node_events.once)(session, "openai_server_event_received");
|
|
96
|
+
this.sockets[index].send(JSON.stringify(event));
|
|
97
|
+
await received;
|
|
98
|
+
}
|
|
99
|
+
response(session, event, delegationId = "d1") {
|
|
100
|
+
return this.send(session, { type: "response.event", delegation_id: delegationId, event });
|
|
101
|
+
}
|
|
102
|
+
async stop() {
|
|
103
|
+
for (const socket of this.sockets) socket.terminate();
|
|
104
|
+
await new Promise((resolve) => this.server.close(() => resolve()));
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
let server;
|
|
108
|
+
let sessions;
|
|
109
|
+
const create = (options = {}) => {
|
|
110
|
+
const session = new import_gpt_live_model.GPTLiveModel({
|
|
111
|
+
apiKey: "sk-test",
|
|
112
|
+
baseURL: server.url,
|
|
113
|
+
...options
|
|
114
|
+
}).session();
|
|
115
|
+
session.on("error", () => {
|
|
116
|
+
});
|
|
117
|
+
sessions.push(session);
|
|
118
|
+
return session;
|
|
119
|
+
};
|
|
120
|
+
const ready = async (session) => {
|
|
121
|
+
await session._updateSession();
|
|
122
|
+
await import_vitest.vi.waitFor(() => (0, import_vitest.expect)(session.sessionId).toBeDefined());
|
|
123
|
+
};
|
|
124
|
+
const waitCount = async (count, index = 0) => import_vitest.vi.waitFor(() => (0, import_vitest.expect)(server.events(index)).toHaveLength(count));
|
|
125
|
+
const types = (index = 0) => server.events(index).slice(1).map((event) => event.type);
|
|
126
|
+
const startConfig = (index = 0) => {
|
|
127
|
+
const event = server.events(index)[0];
|
|
128
|
+
if ((event == null ? void 0 : event.type) !== "session.start") throw new Error("Missing session.start");
|
|
129
|
+
return event.session;
|
|
130
|
+
};
|
|
131
|
+
(0, import_vitest.beforeEach)(async () => {
|
|
132
|
+
sessions = [];
|
|
133
|
+
server = new Server();
|
|
134
|
+
await (0, import_node_events.once)(server.server, "listening");
|
|
135
|
+
});
|
|
136
|
+
(0, import_vitest.afterEach)(async () => {
|
|
137
|
+
import_vitest.vi.useRealTimers();
|
|
138
|
+
await Promise.all(sessions.map((session) => session.close()));
|
|
139
|
+
await server.stop();
|
|
140
|
+
import_vitest.vi.restoreAllMocks();
|
|
141
|
+
import_vitest.vi.unstubAllEnvs();
|
|
142
|
+
});
|
|
143
|
+
(0, import_vitest.describe)("GPTLiveModel", () => {
|
|
144
|
+
(0, import_vitest.it)("holds the connection tick and rides out sentence pauses with its audio gate", () => {
|
|
145
|
+
const model = new import_gpt_live_model.GPTLiveModel({ apiKey: "test" });
|
|
146
|
+
const gate = model.audioGate();
|
|
147
|
+
for (const level of [578e-6, 93e-6, 27e-6, 13e-6, 0])
|
|
148
|
+
(0, import_vitest.expect)(gate.update(pcm(100, level))).toBe(false);
|
|
149
|
+
(0, import_vitest.expect)(gate.update(pcm(100, 5e-3))).toBe(true);
|
|
150
|
+
for (let i = 0; i < 5; i++) (0, import_vitest.expect)(gate.update(pcm())).toBe(true);
|
|
151
|
+
(0, import_vitest.expect)(gate.update(pcm(100, 5e-3))).toBe(true);
|
|
152
|
+
for (let i = 0; i < 9; i++) gate.update(pcm());
|
|
153
|
+
(0, import_vitest.expect)(gate.update(pcm())).toBe(false);
|
|
154
|
+
});
|
|
155
|
+
import_vitest.it.each([
|
|
156
|
+
"aster",
|
|
157
|
+
"beacon",
|
|
158
|
+
"cinder",
|
|
159
|
+
"marin",
|
|
160
|
+
"stone",
|
|
161
|
+
"vesper",
|
|
162
|
+
"future-voice",
|
|
163
|
+
{ id: "voice_test" }
|
|
164
|
+
])("sends the complete startup configuration with voice %j unchanged", async (selectedVoice) => {
|
|
165
|
+
var _a;
|
|
166
|
+
const session = create({ voice: selectedVoice });
|
|
167
|
+
await import_vitest.vi.waitFor(() => (0, import_vitest.expect)(server.sockets).toHaveLength(1));
|
|
168
|
+
await server.send(session, { type: "session.updated" });
|
|
169
|
+
(0, import_vitest.expect)(server.events()).toEqual([]);
|
|
170
|
+
const ctx = import_agents.llm.ChatContext.empty();
|
|
171
|
+
ctx.addMessage({ role: "user", content: "a prior turn" });
|
|
172
|
+
await session._updateSession("Be concise.", ctx, tools);
|
|
173
|
+
await waitCount(1);
|
|
174
|
+
(0, import_vitest.expect)(startConfig()).toMatchObject({
|
|
175
|
+
model: "gpt-live-1",
|
|
176
|
+
instructions: "Be concise.",
|
|
177
|
+
audio: { format: { type: "audio/pcm", rate: 24e3 }, output: { voice: selectedVoice } },
|
|
178
|
+
input: [
|
|
179
|
+
{ type: "message", role: "user", content: [{ type: "input_text", text: "a prior turn" }] }
|
|
180
|
+
],
|
|
181
|
+
delegation: {
|
|
182
|
+
type: "responses",
|
|
183
|
+
responses: {
|
|
184
|
+
model: "gpt-5.6-luna",
|
|
185
|
+
tools: [{ name: "getWeather", parameters: { required: ["location"] } }]
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
});
|
|
189
|
+
(0, import_vitest.expect)(server.requests[0]).toMatchObject({
|
|
190
|
+
url: "/v1/live/sessions",
|
|
191
|
+
headers: {
|
|
192
|
+
authorization: "Bearer sk-test",
|
|
193
|
+
"user-agent": "LiveKit Agents"
|
|
194
|
+
}
|
|
195
|
+
});
|
|
196
|
+
(0, import_vitest.expect)((_a = server.requests[0]) == null ? void 0 : _a.headers).not.toHaveProperty("openai-alpha");
|
|
197
|
+
});
|
|
198
|
+
import_vitest.it.each(["config", "ack", "immediate"])(
|
|
199
|
+
"closes promptly while waiting for %s",
|
|
200
|
+
async (stage) => {
|
|
201
|
+
server.autoStart = false;
|
|
202
|
+
const session = create();
|
|
203
|
+
if (stage !== "immediate") await import_vitest.vi.waitFor(() => (0, import_vitest.expect)(server.sockets).toHaveLength(1));
|
|
204
|
+
if (stage === "ack") {
|
|
205
|
+
await session._updateSession();
|
|
206
|
+
await waitCount(1);
|
|
207
|
+
session.appendCommentary("hello");
|
|
208
|
+
}
|
|
209
|
+
const start = performance.now();
|
|
210
|
+
await session.close();
|
|
211
|
+
(0, import_vitest.expect)(performance.now() - start).toBeLessThan(500);
|
|
212
|
+
(0, import_vitest.expect)(await session.audioStream.getReader().read()).toMatchObject({ done: true });
|
|
213
|
+
}
|
|
214
|
+
);
|
|
215
|
+
(0, import_vitest.it)("sends custom voices and all backend options without dropping false values", async () => {
|
|
216
|
+
const session = create({
|
|
217
|
+
voice: { id: "voice_123" },
|
|
218
|
+
responsesOptions: {
|
|
219
|
+
model: "backend",
|
|
220
|
+
instructions: "Use tools.",
|
|
221
|
+
parallelToolCalls: false,
|
|
222
|
+
toolChoice: { type: "function", function: { name: "getWeather" } },
|
|
223
|
+
reasoning: { effort: "medium" },
|
|
224
|
+
text: { verbosity: "low" },
|
|
225
|
+
serviceTier: "priority",
|
|
226
|
+
maxOutputTokens: 32
|
|
227
|
+
}
|
|
228
|
+
});
|
|
229
|
+
await ready(session);
|
|
230
|
+
(0, import_vitest.expect)(startConfig()).toMatchObject({
|
|
231
|
+
audio: { output: { voice: { id: "voice_123" } } },
|
|
232
|
+
delegation: {
|
|
233
|
+
responses: {
|
|
234
|
+
model: "backend",
|
|
235
|
+
instructions: "Use tools.",
|
|
236
|
+
parallel_tool_calls: false,
|
|
237
|
+
tool_choice: { type: "function", name: "getWeather" },
|
|
238
|
+
reasoning: { effort: "medium" },
|
|
239
|
+
text: { verbosity: "low" },
|
|
240
|
+
service_tier: "priority",
|
|
241
|
+
max_output_tokens: 32
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
});
|
|
245
|
+
});
|
|
246
|
+
(0, import_vitest.it)("preserves function schemas and tool context order with hosted tools", async () => {
|
|
247
|
+
const session = create();
|
|
248
|
+
class OtherProviderTool extends import_agents.llm.ProviderTool {
|
|
249
|
+
}
|
|
250
|
+
const raw = import_agents.llm.tool({
|
|
251
|
+
name: "raw",
|
|
252
|
+
description: "Raw schema",
|
|
253
|
+
parameters: {
|
|
254
|
+
type: "object",
|
|
255
|
+
properties: { value: { type: "number" } },
|
|
256
|
+
required: ["value"]
|
|
257
|
+
},
|
|
258
|
+
execute: async () => "ok"
|
|
259
|
+
});
|
|
260
|
+
await session._updateSession(
|
|
261
|
+
"",
|
|
262
|
+
void 0,
|
|
263
|
+
new import_agents.llm.ToolContext([
|
|
264
|
+
raw,
|
|
265
|
+
new import_tools.WebSearch({ searchContextSize: "low" }),
|
|
266
|
+
new OtherProviderTool({ id: "other" }),
|
|
267
|
+
weather,
|
|
268
|
+
new import_tools.FileSearch({ vectorStoreIds: ["vs_1"] }),
|
|
269
|
+
new import_tools.CodeInterpreter({ container: "c1" })
|
|
270
|
+
])
|
|
271
|
+
);
|
|
272
|
+
await waitCount(1);
|
|
273
|
+
(0, import_vitest.expect)(startConfig().delegation).toMatchObject({
|
|
274
|
+
responses: {
|
|
275
|
+
tools: [
|
|
276
|
+
{ name: "raw", parameters: { required: ["value"] } },
|
|
277
|
+
{ name: "getWeather" },
|
|
278
|
+
{ type: "web_search", search_context_size: "low" },
|
|
279
|
+
{ type: "file_search", vector_store_ids: ["vs_1"] },
|
|
280
|
+
{ type: "code_interpreter", container: "c1" }
|
|
281
|
+
]
|
|
282
|
+
}
|
|
283
|
+
});
|
|
284
|
+
});
|
|
285
|
+
(0, import_vitest.it)("refuses changed startup instructions and sends only sparse backend updates", async () => {
|
|
286
|
+
const session = create();
|
|
287
|
+
await session._updateSession("Be concise.");
|
|
288
|
+
await import_vitest.vi.waitFor(() => (0, import_vitest.expect)(session.sessionId).toBeDefined());
|
|
289
|
+
await session._updateInstructions("Be concise.");
|
|
290
|
+
await (0, import_vitest.expect)(session._updateInstructions("Be verbose.")).rejects.toThrow("immutable");
|
|
291
|
+
(0, import_vitest.expect)(startConfig().delegation).toEqual({
|
|
292
|
+
type: "responses",
|
|
293
|
+
responses: { model: "gpt-5.6-luna" }
|
|
294
|
+
});
|
|
295
|
+
await session._updateTools(tools);
|
|
296
|
+
session._updateOptions({ toolChoice: "required" });
|
|
297
|
+
session._updateOptions({ toolChoice: null });
|
|
298
|
+
await session._updateTools(import_agents.llm.ToolContext.empty());
|
|
299
|
+
await waitCount(5);
|
|
300
|
+
(0, import_vitest.expect)(server.events()[1]).toMatchObject({
|
|
301
|
+
type: "session.update",
|
|
302
|
+
session: { delegation: { responses: { tools: [{ name: "getWeather" }] } } }
|
|
303
|
+
});
|
|
304
|
+
(0, import_vitest.expect)(
|
|
305
|
+
server.events().slice(2).map((event) => event.type === "session.update" && event.session)
|
|
306
|
+
).toEqual([
|
|
307
|
+
{ delegation: { type: "responses", responses: { tool_choice: "required" } } },
|
|
308
|
+
{ delegation: { type: "responses", responses: { tool_choice: "auto" } } },
|
|
309
|
+
{ delegation: { type: "responses", responses: { tools: [] } } }
|
|
310
|
+
]);
|
|
311
|
+
});
|
|
312
|
+
(0, import_vitest.it)("waits specifically for session.started before sending commands or audio", async () => {
|
|
313
|
+
var _a;
|
|
314
|
+
server.autoStart = false;
|
|
315
|
+
const session = create();
|
|
316
|
+
await session._updateSession();
|
|
317
|
+
await waitCount(1);
|
|
318
|
+
session._generateReply("Greet the caller.");
|
|
319
|
+
session.pushAudio(pcm());
|
|
320
|
+
await server.send(session, { type: "session.updated" });
|
|
321
|
+
(0, import_vitest.expect)(server.events().map((event) => event.type)).toEqual(["session.start"]);
|
|
322
|
+
(0, import_vitest.expect)(session.sessionId).toBeUndefined();
|
|
323
|
+
await server.send(session, { type: "session.started", session: { id: "live_test" } });
|
|
324
|
+
await waitCount(3);
|
|
325
|
+
(0, import_vitest.expect)(server.events()[1]).toMatchObject({
|
|
326
|
+
type: "session.commentary.append",
|
|
327
|
+
delegation_id: null,
|
|
328
|
+
content: "Immediately follow the instruction below. Do not wait for the caller to speak first. After that, pause and listen.\n\nGreet the caller."
|
|
329
|
+
});
|
|
330
|
+
(0, import_vitest.expect)((_a = server.events()[2]) == null ? void 0 : _a.type).toBe("session.input_audio.append");
|
|
331
|
+
});
|
|
332
|
+
(0, import_vitest.it)("times out missing startup acknowledgments and exhausts the retry budget", async () => {
|
|
333
|
+
server.autoStart = false;
|
|
334
|
+
const session = create({
|
|
335
|
+
connOptions: { timeoutMs: 100, maxRetry: 1, retryIntervalMs: 10 }
|
|
336
|
+
});
|
|
337
|
+
const errors = [];
|
|
338
|
+
session.on("error", (error) => errors.push(error));
|
|
339
|
+
await session._updateSession();
|
|
340
|
+
await import_vitest.vi.waitFor(() => (0, import_vitest.expect)(errors).toHaveLength(2));
|
|
341
|
+
(0, import_vitest.expect)(errors.map((error) => error.recoverable)).toEqual([true, false]);
|
|
342
|
+
(0, import_vitest.expect)(errors.map((error) => error.error.name)).toEqual(["APITimeoutError", "APITimeoutError"]);
|
|
343
|
+
(0, import_vitest.expect)(server.sockets).toHaveLength(2);
|
|
344
|
+
(0, import_vitest.expect)(await session.audioStream.getReader().read()).toMatchObject({ done: true });
|
|
345
|
+
});
|
|
346
|
+
(0, import_vitest.it)("preserves retries across sockets that disconnect before session.started", async () => {
|
|
347
|
+
server.autoStart = false;
|
|
348
|
+
const session = create({
|
|
349
|
+
connOptions: { timeoutMs: 1e3, maxRetry: 2, retryIntervalMs: 10 }
|
|
350
|
+
});
|
|
351
|
+
const errors = [];
|
|
352
|
+
session.on("error", (error) => errors.push(error));
|
|
353
|
+
await session._updateSession();
|
|
354
|
+
for (let index = 0; index < 3; index++) {
|
|
355
|
+
await waitCount(1, index);
|
|
356
|
+
server.sockets[index].terminate();
|
|
357
|
+
}
|
|
358
|
+
await import_vitest.vi.waitFor(() => (0, import_vitest.expect)(errors).toHaveLength(3));
|
|
359
|
+
(0, import_vitest.expect)(errors.map((error) => error.recoverable)).toEqual([true, true, false]);
|
|
360
|
+
(0, import_vitest.expect)(await session.audioStream.getReader().read()).toMatchObject({ done: true });
|
|
361
|
+
(0, import_vitest.expect)(server.sockets).toHaveLength(3);
|
|
362
|
+
});
|
|
363
|
+
(0, import_vitest.it)("starts the acknowledgment deadline after configuration and clears it on startup", async () => {
|
|
364
|
+
const session = create({
|
|
365
|
+
connOptions: { timeoutMs: 100, maxRetry: 0, retryIntervalMs: 10 }
|
|
366
|
+
});
|
|
367
|
+
const errors = [];
|
|
368
|
+
session.on("error", (error) => errors.push(error));
|
|
369
|
+
await import_vitest.vi.waitFor(() => (0, import_vitest.expect)(server.sockets).toHaveLength(1));
|
|
370
|
+
await (0, import_promises.setTimeout)(150);
|
|
371
|
+
(0, import_vitest.expect)(server.events()).toEqual([]);
|
|
372
|
+
await ready(session);
|
|
373
|
+
await (0, import_promises.setTimeout)(150);
|
|
374
|
+
session.appendThinking("Still connected.");
|
|
375
|
+
await waitCount(2);
|
|
376
|
+
(0, import_vitest.expect)(errors).toEqual([]);
|
|
377
|
+
});
|
|
378
|
+
(0, import_vitest.it)("resets the retry budget once a reconnected session starts", async () => {
|
|
379
|
+
server.autoStart = false;
|
|
380
|
+
const session = create({
|
|
381
|
+
connOptions: { timeoutMs: 1e3, maxRetry: 1, retryIntervalMs: 10 }
|
|
382
|
+
});
|
|
383
|
+
const errors = [];
|
|
384
|
+
const reconnected = import_vitest.vi.fn();
|
|
385
|
+
session.on("error", (error) => errors.push(error));
|
|
386
|
+
session.on("session_reconnected", reconnected);
|
|
387
|
+
await session._updateSession();
|
|
388
|
+
await waitCount(1);
|
|
389
|
+
server.sockets[0].terminate();
|
|
390
|
+
await waitCount(1, 1);
|
|
391
|
+
(0, import_vitest.expect)(reconnected).not.toHaveBeenCalled();
|
|
392
|
+
server.autoStart = true;
|
|
393
|
+
await server.send(session, { type: "session.started", session: { id: "live_1" } });
|
|
394
|
+
(0, import_vitest.expect)(reconnected).toHaveBeenCalledOnce();
|
|
395
|
+
server.sockets[1].terminate();
|
|
396
|
+
await import_vitest.vi.waitFor(() => (0, import_vitest.expect)(session.sessionId).toBe("live_2"));
|
|
397
|
+
(0, import_vitest.expect)(errors.map((error) => error.recoverable)).toEqual([true, true]);
|
|
398
|
+
(0, import_vitest.expect)(reconnected).toHaveBeenCalledTimes(2);
|
|
399
|
+
});
|
|
400
|
+
(0, import_vitest.it)("delivers client delegations with the pending transcript and answers by id", async () => {
|
|
401
|
+
const session = create({ delegation: "client" });
|
|
402
|
+
const delegations = [];
|
|
403
|
+
session.on("delegation_created", (event) => delegations.push(event));
|
|
404
|
+
await ready(session);
|
|
405
|
+
(0, import_vitest.expect)(session.capabilities.midSessionToolsUpdate).toBe(false);
|
|
406
|
+
(0, import_vitest.expect)(startConfig().delegation).toEqual({ type: "client" });
|
|
407
|
+
await server.send(session, {
|
|
408
|
+
type: "session.delegation.created",
|
|
409
|
+
delegation: { id: "backend", target: "responses" }
|
|
410
|
+
});
|
|
411
|
+
await server.send(session, transcript("user", "What is the weather", 1e3));
|
|
412
|
+
await server.send(session, {
|
|
413
|
+
type: "session.delegation.created",
|
|
414
|
+
delegation: { id: "d1", target: "client" }
|
|
415
|
+
});
|
|
416
|
+
(0, import_vitest.expect)(delegations).toEqual([{ id: "d1", pendingTranscript: "What is the weather" }]);
|
|
417
|
+
session.appendCommentary("62 and raining.", { delegationId: "d1" });
|
|
418
|
+
session.appendThinking("Still checking.", { delegationId: "d1" });
|
|
419
|
+
await waitCount(3);
|
|
420
|
+
(0, import_vitest.expect)(server.events().slice(1)).toMatchObject([
|
|
421
|
+
{ type: "session.commentary.append", delegation_id: "d1", content: "62 and raining." },
|
|
422
|
+
{ type: "session.thinking.append", delegation_id: "d1", content: "Still checking." }
|
|
423
|
+
]);
|
|
424
|
+
});
|
|
425
|
+
(0, import_vitest.it)("drops old delegation answers during drain, startup, and after reconnect", async () => {
|
|
426
|
+
server.autoClose = false;
|
|
427
|
+
const session = create({ delegation: "client", maxSessionDuration: 300 });
|
|
428
|
+
try {
|
|
429
|
+
await ready(session);
|
|
430
|
+
await server.send(session, {
|
|
431
|
+
type: "session.delegation.created",
|
|
432
|
+
delegation: { id: "old", target: "client" }
|
|
433
|
+
});
|
|
434
|
+
server.autoStart = false;
|
|
435
|
+
await import_vitest.vi.waitFor(() => {
|
|
436
|
+
var _a;
|
|
437
|
+
return (0, import_vitest.expect)((_a = server.events().at(-1)) == null ? void 0 : _a.type).toBe("session.close");
|
|
438
|
+
});
|
|
439
|
+
session.appendCommentary("Old answer during drain", { delegationId: "old" });
|
|
440
|
+
session.appendThinking("Old context during drain", { delegationId: "old" });
|
|
441
|
+
await server.send(session, { type: "session.closed", reason: "close_requested" });
|
|
442
|
+
await waitCount(1, 1);
|
|
443
|
+
session.appendCommentary("Old answer during startup", { delegationId: "old" });
|
|
444
|
+
session.appendThinking("Keep this context");
|
|
445
|
+
await server.send(session, { type: "session.started", session: { id: "live_1" } });
|
|
446
|
+
await waitCount(2, 1);
|
|
447
|
+
session.appendCommentary("Old answer after startup", { delegationId: "old" });
|
|
448
|
+
session.on("openai_server_event_received", (event) => {
|
|
449
|
+
var _a;
|
|
450
|
+
if (event.type === "session.delegation.created" && ((_a = event.delegation) == null ? void 0 : _a.id) === "new")
|
|
451
|
+
session.appendCommentary("New answer", { delegationId: "new" });
|
|
452
|
+
});
|
|
453
|
+
await server.send(session, {
|
|
454
|
+
type: "session.delegation.created",
|
|
455
|
+
delegation: { id: "new", target: "client" }
|
|
456
|
+
});
|
|
457
|
+
await waitCount(3, 1);
|
|
458
|
+
(0, import_vitest.expect)(startConfig(1).input).toBeUndefined();
|
|
459
|
+
(0, import_vitest.expect)(server.events(1).slice(1)).toMatchObject([
|
|
460
|
+
{ type: "session.thinking.append", content: "Keep this context", delegation_id: null },
|
|
461
|
+
{ type: "session.commentary.append", content: "New answer", delegation_id: "new" }
|
|
462
|
+
]);
|
|
463
|
+
} finally {
|
|
464
|
+
server.autoClose = true;
|
|
465
|
+
}
|
|
466
|
+
});
|
|
467
|
+
(0, import_vitest.it)("does not block commands or finish speech on delayed context acknowledgments", async () => {
|
|
468
|
+
var _a, _b;
|
|
469
|
+
const model = new import_gpt_live_model.GPTLiveModel({ apiKey: "sk-test", baseURL: server.url });
|
|
470
|
+
const session = model.session();
|
|
471
|
+
sessions.push(session);
|
|
472
|
+
import_vitest.vi.spyOn(model, "session").mockReturnValue(session);
|
|
473
|
+
const adapted = new import_agents.llm.DuplexRealtimeAdapter(model).session();
|
|
474
|
+
const generations = [];
|
|
475
|
+
const errors = [];
|
|
476
|
+
adapted.on("generation_created", (event) => generations.push(event));
|
|
477
|
+
adapted.on("error", (event) => errors.push(event));
|
|
478
|
+
try {
|
|
479
|
+
await adapted._updateSession();
|
|
480
|
+
await import_vitest.vi.waitFor(() => (0, import_vitest.expect)(session.sessionId).toBeDefined());
|
|
481
|
+
session.appendInstructions("Be concise.");
|
|
482
|
+
session.appendThinking("The caller is returning a chair.");
|
|
483
|
+
session.appendCommentary("Ask for the order number.");
|
|
484
|
+
session.pushAudio(pcm());
|
|
485
|
+
await waitCount(5);
|
|
486
|
+
import_vitest.vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
|
|
487
|
+
await import_vitest.vi.advanceTimersByTimeAsync(model._opts.connOptions.timeoutMs * 2);
|
|
488
|
+
import_vitest.vi.useRealTimers();
|
|
489
|
+
(0, import_vitest.expect)(server.events().map((event) => event.type)).toEqual([
|
|
490
|
+
"session.start",
|
|
491
|
+
"session.instructions.append",
|
|
492
|
+
"session.thinking.append",
|
|
493
|
+
"session.commentary.append",
|
|
494
|
+
"session.input_audio.append"
|
|
495
|
+
]);
|
|
496
|
+
(0, import_vitest.expect)(errors).toEqual([]);
|
|
497
|
+
(0, import_vitest.expect)(generations).toEqual([]);
|
|
498
|
+
const speech = {
|
|
499
|
+
type: "session.output_audio.delta",
|
|
500
|
+
delta: Buffer.from(pcm(100, 0.2).data.buffer).toString("base64")
|
|
501
|
+
};
|
|
502
|
+
await server.send(session, transcript("assistant", "What is", 0));
|
|
503
|
+
await server.send(session, speech);
|
|
504
|
+
await import_vitest.vi.waitFor(() => (0, import_vitest.expect)(generations).toHaveLength(1));
|
|
505
|
+
const messages = generations[0].messageStream.getReader();
|
|
506
|
+
const message = (await messages.read()).value;
|
|
507
|
+
const audio = message.audioStream.getReader();
|
|
508
|
+
(0, import_vitest.expect)((_a = (await audio.read()).value) == null ? void 0 : _a.samplesPerChannel).toBe(2400);
|
|
509
|
+
let nextArrived = false;
|
|
510
|
+
const nextAudio = audio.read().then((value) => {
|
|
511
|
+
nextArrived = true;
|
|
512
|
+
return value;
|
|
513
|
+
});
|
|
514
|
+
const acknowledgmentTypes = [
|
|
515
|
+
"session.instructions.appended",
|
|
516
|
+
"session.thinking.appended",
|
|
517
|
+
"session.commentary.appended"
|
|
518
|
+
];
|
|
519
|
+
for (const [index, type] of acknowledgmentTypes.entries()) {
|
|
520
|
+
await server.send(session, { type, client_event_id: server.events()[index + 1].event_id });
|
|
521
|
+
await (0, import_promises.setImmediate)();
|
|
522
|
+
(0, import_vitest.expect)(nextArrived).toBe(false);
|
|
523
|
+
(0, import_vitest.expect)(generations).toHaveLength(1);
|
|
524
|
+
(0, import_vitest.expect)(adapted.chatCtx.items).toEqual([]);
|
|
525
|
+
}
|
|
526
|
+
await server.send(session, transcript("assistant", " your order number?", 100));
|
|
527
|
+
await server.send(session, speech);
|
|
528
|
+
(0, import_vitest.expect)((_b = (await nextAudio).value) == null ? void 0 : _b.samplesPerChannel).toBe(2400);
|
|
529
|
+
for (let i = 0; i < 8; i++)
|
|
530
|
+
await server.send(session, {
|
|
531
|
+
type: "session.output_audio.delta",
|
|
532
|
+
delta: Buffer.from(pcm().data.buffer).toString("base64")
|
|
533
|
+
});
|
|
534
|
+
while (!(await audio.read()).done) {
|
|
535
|
+
}
|
|
536
|
+
const chunks = [];
|
|
537
|
+
for await (const chunk of message.textStream)
|
|
538
|
+
chunks.push(typeof chunk === "string" ? chunk : chunk.text);
|
|
539
|
+
(0, import_vitest.expect)(chunks.join("")).toBe("What is your order number?");
|
|
540
|
+
(0, import_vitest.expect)((await messages.read()).done).toBe(true);
|
|
541
|
+
(0, import_vitest.expect)(generations).toHaveLength(1);
|
|
542
|
+
(0, import_vitest.expect)(errors).toEqual([]);
|
|
543
|
+
audio.releaseLock();
|
|
544
|
+
messages.releaseLock();
|
|
545
|
+
} finally {
|
|
546
|
+
import_vitest.vi.useRealTimers();
|
|
547
|
+
await adapted.close();
|
|
548
|
+
await model.close();
|
|
549
|
+
}
|
|
550
|
+
});
|
|
551
|
+
(0, import_vitest.it)("rejects tools under client delegation and accepts an empty tool list", async () => {
|
|
552
|
+
const session = create({ delegation: "client" });
|
|
553
|
+
await (0, import_vitest.expect)(session._updateSession("Be concise.", void 0, tools)).rejects.toThrow(
|
|
554
|
+
"no tool channel"
|
|
555
|
+
);
|
|
556
|
+
await (0, import_vitest.expect)(session._updateTools(new import_agents.llm.ToolContext([new import_tools.WebSearch()]))).rejects.toThrow(
|
|
557
|
+
"no tool channel"
|
|
558
|
+
);
|
|
559
|
+
await session._updateSession("Be concise.", void 0, import_agents.llm.ToolContext.empty());
|
|
560
|
+
await waitCount(1);
|
|
561
|
+
(0, import_vitest.expect)(session.tools.flatten()).toEqual([]);
|
|
562
|
+
});
|
|
563
|
+
(0, import_vitest.it)("keeps null delegation ids and supports input mute commands", async () => {
|
|
564
|
+
const session = create();
|
|
565
|
+
await ready(session);
|
|
566
|
+
session.appendThinking("Premium customer.");
|
|
567
|
+
session.appendInstructions("Speak slowly.");
|
|
568
|
+
session.appendCommentary("Hello.");
|
|
569
|
+
session.muteInput();
|
|
570
|
+
session.unmuteInput();
|
|
571
|
+
await waitCount(6);
|
|
572
|
+
for (const event of server.events().slice(1, 4))
|
|
573
|
+
(0, import_vitest.expect)(event).toHaveProperty("delegation_id", null);
|
|
574
|
+
(0, import_vitest.expect)(
|
|
575
|
+
server.events().slice(4).map((event) => event.type)
|
|
576
|
+
).toEqual(["session.input_audio.mute", "session.input_audio.unmute"]);
|
|
577
|
+
});
|
|
578
|
+
(0, import_vitest.it)("forwards every output frame, including silence, and handles stream cancellation", async () => {
|
|
579
|
+
const session = create();
|
|
580
|
+
await ready(session);
|
|
581
|
+
const reader = session.audioStream.getReader();
|
|
582
|
+
for (let i = 0; i < 3; i++) {
|
|
583
|
+
await server.send(session, {
|
|
584
|
+
type: "session.output_audio.delta",
|
|
585
|
+
delta: Buffer.alloc(4800).toString("base64")
|
|
586
|
+
});
|
|
587
|
+
const { value } = await reader.read();
|
|
588
|
+
(0, import_vitest.expect)(value == null ? void 0 : value.frame.sampleRate).toBe(24e3);
|
|
589
|
+
(0, import_vitest.expect)(value == null ? void 0 : value.frame.samplesPerChannel).toBe(2400);
|
|
590
|
+
(0, import_vitest.expect)(value == null ? void 0 : value.startMs).toBeUndefined();
|
|
591
|
+
}
|
|
592
|
+
await reader.cancel();
|
|
593
|
+
await server.send(session, {
|
|
594
|
+
type: "session.output_audio.delta",
|
|
595
|
+
delta: Buffer.alloc(4800).toString("base64")
|
|
596
|
+
});
|
|
597
|
+
await session.close();
|
|
598
|
+
});
|
|
599
|
+
(0, import_vitest.it)("resamples input, handles channel and rate changes, and sends 100 ms chunks", async () => {
|
|
600
|
+
const session = create();
|
|
601
|
+
await ready(session);
|
|
602
|
+
session.pushAudio(pcm(200, 0, 48e3, 2));
|
|
603
|
+
await import_vitest.vi.waitFor(() => (0, import_vitest.expect)(server.events().length).toBeGreaterThan(1));
|
|
604
|
+
session.pushAudio(pcm(200));
|
|
605
|
+
await import_vitest.vi.waitFor(() => (0, import_vitest.expect)(server.events().length).toBeGreaterThan(2));
|
|
606
|
+
for (const event of server.events().slice(1)) {
|
|
607
|
+
(0, import_vitest.expect)(event.type).toBe("session.input_audio.append");
|
|
608
|
+
if (event.type === "session.input_audio.append") {
|
|
609
|
+
const bytes = Buffer.from(event.audio, "base64");
|
|
610
|
+
(0, import_vitest.expect)(bytes).toHaveLength(4800);
|
|
611
|
+
for (let offset = 0; offset < bytes.length; offset += 2)
|
|
612
|
+
(0, import_vitest.expect)(Math.abs(bytes.readInt16LE(offset))).toBeLessThanOrEqual(1);
|
|
613
|
+
}
|
|
614
|
+
}
|
|
615
|
+
});
|
|
616
|
+
(0, import_vitest.it)("queues a tool result before completing the response and then continues once", async () => {
|
|
617
|
+
var _a, _b;
|
|
618
|
+
const session = create();
|
|
619
|
+
const calls = [];
|
|
620
|
+
session.on("function_call", (call) => calls.push(call));
|
|
621
|
+
await ready(session);
|
|
622
|
+
await server.response(session, { type: "response.created" });
|
|
623
|
+
await server.response(session, callDone("c1"));
|
|
624
|
+
(0, import_vitest.expect)(calls.map((call) => [call.callId, call.name, call.args])).toEqual([
|
|
625
|
+
["c1", "getWeather", '{"location":"Paris"}']
|
|
626
|
+
]);
|
|
627
|
+
await session._appendItems([output("c1")]);
|
|
628
|
+
await waitCount(2);
|
|
629
|
+
(0, import_vitest.expect)(server.events()[1]).toMatchObject({
|
|
630
|
+
type: "response.item.create",
|
|
631
|
+
item: { type: "function_call_output", call_id: "c1", output: "rainy" }
|
|
632
|
+
});
|
|
633
|
+
await server.response(session, completed());
|
|
634
|
+
await waitCount(3);
|
|
635
|
+
(0, import_vitest.expect)((_a = server.events()[2]) == null ? void 0 : _a.type).toBe("response.create");
|
|
636
|
+
await session._appendItems([output("c1")]);
|
|
637
|
+
await waitCount(4);
|
|
638
|
+
(0, import_vitest.expect)((_b = server.events()[3]) == null ? void 0 : _b.type).toBe("session.thinking.append");
|
|
639
|
+
});
|
|
640
|
+
(0, import_vitest.it)("waits for every result in a parallel batch, including null delegation ids", async () => {
|
|
641
|
+
var _a;
|
|
642
|
+
const session = create();
|
|
643
|
+
await ready(session);
|
|
644
|
+
await server.response(session, { type: "response.created" }, null);
|
|
645
|
+
await server.response(session, callDone("a"), null);
|
|
646
|
+
await server.response(session, callDone("b"), null);
|
|
647
|
+
await server.response(session, completed(), null);
|
|
648
|
+
await session._appendItems([output("a")]);
|
|
649
|
+
await waitCount(2);
|
|
650
|
+
(0, import_vitest.expect)((_a = server.events()[1]) == null ? void 0 : _a.type).toBe("response.item.create");
|
|
651
|
+
await session._appendItems([output("b")]);
|
|
652
|
+
await waitCount(4);
|
|
653
|
+
(0, import_vitest.expect)(
|
|
654
|
+
server.events().slice(1).map((event) => event.type)
|
|
655
|
+
).toEqual(["response.item.create", "response.item.create", "response.create"]);
|
|
656
|
+
});
|
|
657
|
+
(0, import_vitest.it)("holds the continuation until every open call in the conversation is answered", async () => {
|
|
658
|
+
const session = create();
|
|
659
|
+
await ready(session);
|
|
660
|
+
await server.response(session, { type: "response.created" });
|
|
661
|
+
await server.response(session, callDone("slow"));
|
|
662
|
+
await server.response(session, completed());
|
|
663
|
+
await server.response(session, { type: "response.created" });
|
|
664
|
+
await server.response(session, callDone("fast"));
|
|
665
|
+
await server.response(session, completed());
|
|
666
|
+
await session._appendItems([output("fast")]);
|
|
667
|
+
await waitCount(2);
|
|
668
|
+
await (0, import_promises.setTimeout)(20);
|
|
669
|
+
(0, import_vitest.expect)(types()).toEqual(["response.item.create"]);
|
|
670
|
+
await session._appendItems([output("slow")]);
|
|
671
|
+
await waitCount(4);
|
|
672
|
+
await (0, import_promises.setTimeout)(20);
|
|
673
|
+
(0, import_vitest.expect)(types()).toEqual(["response.item.create", "response.item.create", "response.create"]);
|
|
674
|
+
});
|
|
675
|
+
(0, import_vitest.it)("releases the continuation a failed response held back and discards its calls", async () => {
|
|
676
|
+
var _a;
|
|
677
|
+
const session = create();
|
|
678
|
+
await ready(session);
|
|
679
|
+
await server.response(session, { type: "response.created" }, "d1");
|
|
680
|
+
await server.response(session, callDone("c1"), "d1");
|
|
681
|
+
await server.response(session, completed(), "d1");
|
|
682
|
+
await server.response(session, { type: "response.created" }, "d2");
|
|
683
|
+
await server.response(session, callDone("c2"), "d2");
|
|
684
|
+
await session._appendItems([output("c1")]);
|
|
685
|
+
await waitCount(2);
|
|
686
|
+
await (0, import_promises.setTimeout)(20);
|
|
687
|
+
(0, import_vitest.expect)(types()).toEqual(["response.item.create"]);
|
|
688
|
+
await server.response(session, { type: "response.failed" }, "d2");
|
|
689
|
+
await waitCount(3);
|
|
690
|
+
(0, import_vitest.expect)(types()).toEqual(["response.item.create", "response.create"]);
|
|
691
|
+
await session._appendItems([output("c2")]);
|
|
692
|
+
await waitCount(4);
|
|
693
|
+
(0, import_vitest.expect)((_a = server.events()[3]) == null ? void 0 : _a.type).toBe("session.thinking.append");
|
|
694
|
+
});
|
|
695
|
+
import_vitest.it.each(["response.failed", "response.incomplete"])(
|
|
696
|
+
"clears tool routing after %s",
|
|
697
|
+
async (type) => {
|
|
698
|
+
var _a;
|
|
699
|
+
const session = create();
|
|
700
|
+
await ready(session);
|
|
701
|
+
await server.response(session, { type: "response.created" });
|
|
702
|
+
await server.response(session, callDone("a"));
|
|
703
|
+
await server.response(session, { type });
|
|
704
|
+
await session._appendItems([output("a")]);
|
|
705
|
+
await waitCount(2);
|
|
706
|
+
(0, import_vitest.expect)((_a = server.events()[1]) == null ? void 0 : _a.type).toBe("session.thinking.append");
|
|
707
|
+
}
|
|
708
|
+
);
|
|
709
|
+
(0, import_vitest.it)("ignores incomplete function items and accepts complete calls without response.created", async () => {
|
|
710
|
+
var _a;
|
|
711
|
+
const session = create();
|
|
712
|
+
const calls = import_vitest.vi.fn();
|
|
713
|
+
session.on("function_call", calls);
|
|
714
|
+
await ready(session);
|
|
715
|
+
await server.response(session, {
|
|
716
|
+
type: "response.output_item.done",
|
|
717
|
+
item: { type: "function_call", call_id: "bad" }
|
|
718
|
+
});
|
|
719
|
+
(0, import_vitest.expect)(calls).not.toHaveBeenCalled();
|
|
720
|
+
await server.response(session, callDone("a"));
|
|
721
|
+
await session._appendItems([output("a")]);
|
|
722
|
+
await waitCount(3);
|
|
723
|
+
(0, import_vitest.expect)((_a = server.events().at(-1)) == null ? void 0 : _a.type).toBe("response.create");
|
|
724
|
+
});
|
|
725
|
+
import_vitest.it.each([
|
|
726
|
+
"close_requested",
|
|
727
|
+
"expired",
|
|
728
|
+
"content",
|
|
729
|
+
"remote_hangup",
|
|
730
|
+
"connection_lost",
|
|
731
|
+
null,
|
|
732
|
+
void 0
|
|
733
|
+
])(
|
|
734
|
+
"logs close reason %s and drains final usage separately from backend tokens",
|
|
735
|
+
async (reason) => {
|
|
736
|
+
const debug = import_vitest.vi.spyOn((0, import_agents.log)(), "debug");
|
|
737
|
+
const session = create();
|
|
738
|
+
const collected = [];
|
|
739
|
+
session.on("metrics_collected", (metric) => collected.push(metric));
|
|
740
|
+
await ready(session);
|
|
741
|
+
await server.send(session, {
|
|
742
|
+
type: "session.usage.updated",
|
|
743
|
+
usage: { seconds: 14 },
|
|
744
|
+
context_window: { usage_ratio: 0.2 }
|
|
745
|
+
});
|
|
746
|
+
await server.response(session, completed());
|
|
747
|
+
server.closeUsage = 27;
|
|
748
|
+
server.closeReason = reason;
|
|
749
|
+
await session.close();
|
|
750
|
+
(0, import_vitest.expect)(debug).toHaveBeenCalledWith(
|
|
751
|
+
{ reason: reason ?? null, sessionId: "live_0" },
|
|
752
|
+
"GPT-Live session closed"
|
|
753
|
+
);
|
|
754
|
+
(0, import_vitest.expect)(collected.filter((metric) => metric.type === "llm_metrics")).toMatchObject([
|
|
755
|
+
{
|
|
756
|
+
requestId: "resp_1",
|
|
757
|
+
promptTokens: 376,
|
|
758
|
+
promptCachedTokens: 100,
|
|
759
|
+
cacheCreationTokens: 20,
|
|
760
|
+
completionTokens: 18,
|
|
761
|
+
reasoningTokens: 5,
|
|
762
|
+
metadata: { modelName: "gpt-5.6-sol" }
|
|
763
|
+
}
|
|
764
|
+
]);
|
|
765
|
+
const frontend = collected.filter(
|
|
766
|
+
(metric) => metric.type === "realtime_model_metrics" && metric.sessionDurationMs !== void 0
|
|
767
|
+
);
|
|
768
|
+
(0, import_vitest.expect)(frontend.map((metric) => metric.sessionDurationMs)).toEqual([14e3, 13e3]);
|
|
769
|
+
(0, import_vitest.expect)(
|
|
770
|
+
frontend.every((metric) => metric.inputTokens === 0 && metric.outputTokens === 0)
|
|
771
|
+
).toBe(true);
|
|
772
|
+
}
|
|
773
|
+
);
|
|
774
|
+
(0, import_vitest.it)("bounds the close drain when the service never sends session.closed", async () => {
|
|
775
|
+
const session = create();
|
|
776
|
+
await ready(session);
|
|
777
|
+
server.autoClose = false;
|
|
778
|
+
import_vitest.vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
|
|
779
|
+
const closing = session.close();
|
|
780
|
+
await import_vitest.vi.advanceTimersByTimeAsync(5e3);
|
|
781
|
+
await closing;
|
|
782
|
+
import_vitest.vi.useRealTimers();
|
|
783
|
+
});
|
|
784
|
+
(0, import_vitest.it)("mirrors growing transcripts and reseeds them in order on reconnect", async () => {
|
|
785
|
+
var _a;
|
|
786
|
+
const session = create();
|
|
787
|
+
const deltas = [];
|
|
788
|
+
session.on("transcript_delta", (delta) => deltas.push(delta));
|
|
789
|
+
await ready(session);
|
|
790
|
+
for (const [role, text, start] of [
|
|
791
|
+
["user", " What is", 7e3],
|
|
792
|
+
["assistant", "Let me", 7400],
|
|
793
|
+
["user", " the weather", 7200],
|
|
794
|
+
["assistant", " check.", 7600],
|
|
795
|
+
["assistant", "Sixty-two.", 9e3]
|
|
796
|
+
])
|
|
797
|
+
await server.send(session, transcript(role, text, start));
|
|
798
|
+
(0, import_vitest.expect)(deltas).toEqual([
|
|
799
|
+
{ text: "Let me", startMs: 7400, endMs: 7600 },
|
|
800
|
+
{ text: " check.", startMs: 7600, endMs: 7800 },
|
|
801
|
+
{ text: "Sixty-two.", startMs: 9e3, endMs: 9200 }
|
|
802
|
+
]);
|
|
803
|
+
server.sockets[0].terminate();
|
|
804
|
+
await import_vitest.vi.waitFor(() => (0, import_vitest.expect)(session.sessionId).toBe("live_1"));
|
|
805
|
+
(0, import_vitest.expect)((_a = startConfig(1).input) == null ? void 0 : _a.map((item) => {
|
|
806
|
+
var _a2;
|
|
807
|
+
return [item.role, (_a2 = item.content[0]) == null ? void 0 : _a2.text];
|
|
808
|
+
})).toEqual([
|
|
809
|
+
["user", " What is the weather"],
|
|
810
|
+
["assistant", "Let me check."],
|
|
811
|
+
["assistant", "Sixty-two."]
|
|
812
|
+
]);
|
|
813
|
+
});
|
|
814
|
+
(0, import_vitest.it)("ends a caller turn after 800 ms of input audio without new fragments", async () => {
|
|
815
|
+
var _a, _b, _c;
|
|
816
|
+
const session = create();
|
|
817
|
+
const events = [];
|
|
818
|
+
for (const name of [
|
|
819
|
+
"input_speech_started",
|
|
820
|
+
"input_audio_transcription_completed",
|
|
821
|
+
"input_speech_stopped"
|
|
822
|
+
])
|
|
823
|
+
session.on(name, (data) => events.push({ name, data }));
|
|
824
|
+
await ready(session);
|
|
825
|
+
for (let i = 0; i < 20; i++) session.pushAudio(pcm());
|
|
826
|
+
await server.send(session, transcript("user", " What", 1800));
|
|
827
|
+
await server.send(session, transcript("user", " is the", 2e3));
|
|
828
|
+
(0, import_vitest.expect)(events.map((event) => event.name)).toEqual([
|
|
829
|
+
"input_speech_started",
|
|
830
|
+
"input_audio_transcription_completed",
|
|
831
|
+
"input_audio_transcription_completed"
|
|
832
|
+
]);
|
|
833
|
+
for (let i = 0; i < 7; i++) session.pushAudio(pcm());
|
|
834
|
+
(0, import_vitest.expect)(events).toHaveLength(3);
|
|
835
|
+
session.pushAudio(pcm());
|
|
836
|
+
(0, import_vitest.expect)(events.slice(-2).map((event) => event.name)).toEqual([
|
|
837
|
+
"input_audio_transcription_completed",
|
|
838
|
+
"input_speech_stopped"
|
|
839
|
+
]);
|
|
840
|
+
(0, import_vitest.expect)((_a = events[3]) == null ? void 0 : _a.data).toEqual({ ...(_b = events[2]) == null ? void 0 : _b.data, isFinal: true });
|
|
841
|
+
(0, import_vitest.expect)((_c = events[3]) == null ? void 0 : _c.data).toMatchObject({ transcript: " What is the" });
|
|
842
|
+
});
|
|
843
|
+
(0, import_vitest.it)("splits bursty transcript delivery on gaps in the model timeline", async () => {
|
|
844
|
+
const session = create();
|
|
845
|
+
const finals = [];
|
|
846
|
+
session.on("input_audio_transcription_completed", (event) => {
|
|
847
|
+
if (event.isFinal) finals.push(event.transcript);
|
|
848
|
+
});
|
|
849
|
+
await ready(session);
|
|
850
|
+
await server.send(session, transcript("user", "Hello", 1e3));
|
|
851
|
+
await server.send(session, transcript("user", "Again", 4e3));
|
|
852
|
+
(0, import_vitest.expect)(finals).toEqual(["Hello"]);
|
|
853
|
+
});
|
|
854
|
+
import_vitest.it.each(["responses", "client"])(
|
|
855
|
+
"carries typed input once in the next ask under %s delegation",
|
|
856
|
+
async (delegation) => {
|
|
857
|
+
const session = create({ delegation });
|
|
858
|
+
await ready(session);
|
|
859
|
+
await session._appendItems([
|
|
860
|
+
new import_agents.llm.ChatMessage({ role: "system", content: "Answer in French." }),
|
|
861
|
+
new import_agents.llm.ChatMessage({ role: "user", content: "What is the weather in Paris?" })
|
|
862
|
+
]);
|
|
863
|
+
session._generateReply();
|
|
864
|
+
await waitCount(4);
|
|
865
|
+
(0, import_vitest.expect)(server.events().slice(1)).toMatchObject([
|
|
866
|
+
{ type: "session.instructions.append", content: "Answer in French." },
|
|
867
|
+
{ type: "session.thinking.append", content: "user: What is the weather in Paris?" },
|
|
868
|
+
{
|
|
869
|
+
type: "session.commentary.append",
|
|
870
|
+
content: "Reply to the caller now, don't repeat what they said. Do not wait for the caller to speak first. After that, pause and listen.\n\nWhat is the weather in Paris?"
|
|
871
|
+
}
|
|
872
|
+
]);
|
|
873
|
+
session._generateReply();
|
|
874
|
+
await waitCount(5);
|
|
875
|
+
const bare = server.events()[4];
|
|
876
|
+
(0, import_vitest.expect)(bare).toMatchObject({
|
|
877
|
+
content: "Reply to the caller now. Do not wait for the caller to speak first. After that, pause and listen."
|
|
878
|
+
});
|
|
879
|
+
await session._appendItems([new import_agents.llm.ChatMessage({ role: "user", content: "Never mind." })]);
|
|
880
|
+
await server.send(session, transcript("assistant", "Okay.", 1));
|
|
881
|
+
session._generateReply();
|
|
882
|
+
await waitCount(7);
|
|
883
|
+
(0, import_vitest.expect)(server.events()[6]).toMatchObject({
|
|
884
|
+
content: "Reply to the caller now. Do not wait for the caller to speak first. After that, pause and listen."
|
|
885
|
+
});
|
|
886
|
+
}
|
|
887
|
+
);
|
|
888
|
+
(0, import_vitest.it)("caps startup history at 128 rendered messages and narrates old tool traffic", async () => {
|
|
889
|
+
var _a, _b, _c, _d;
|
|
890
|
+
const session = create();
|
|
891
|
+
const ctx = import_agents.llm.ChatContext.empty();
|
|
892
|
+
for (let i = 0; i < 130; i++) ctx.addMessage({ role: "user", content: `message ${i}` });
|
|
893
|
+
ctx.insert(new import_agents.llm.FunctionCall({ callId: "old", name: "getWeather", args: "{}" }));
|
|
894
|
+
ctx.insert(output("old"));
|
|
895
|
+
await session._updateSession(void 0, ctx);
|
|
896
|
+
await waitCount(1);
|
|
897
|
+
(0, import_vitest.expect)(startConfig().input).toHaveLength(128);
|
|
898
|
+
(0, import_vitest.expect)((_c = (_b = (_a = startConfig().input) == null ? void 0 : _a[0]) == null ? void 0 : _b.content[0]) == null ? void 0 : _c.text).toBe("message 4");
|
|
899
|
+
(0, import_vitest.expect)((_d = startConfig().input) == null ? void 0 : _d.slice(-2)).toMatchObject([
|
|
900
|
+
{ role: "developer", content: [{ text: "Called tool getWeather with {}" }] },
|
|
901
|
+
{ role: "developer", content: [{ text: "Tool getWeather returned rainy" }] }
|
|
902
|
+
]);
|
|
903
|
+
});
|
|
904
|
+
(0, import_vitest.it)("reseeds context received during retry and clears delegated calls and usage", async () => {
|
|
905
|
+
var _a;
|
|
906
|
+
const session = create();
|
|
907
|
+
const errors = [];
|
|
908
|
+
const durations = [];
|
|
909
|
+
session.on("error", (event) => errors.push(event));
|
|
910
|
+
session.on("metrics_collected", (metric) => {
|
|
911
|
+
if (metric.type === "realtime_model_metrics" && metric.sessionDurationMs !== void 0)
|
|
912
|
+
durations.push(metric.sessionDurationMs);
|
|
913
|
+
});
|
|
914
|
+
await ready(session);
|
|
915
|
+
await server.response(session, { type: "response.created" });
|
|
916
|
+
await server.response(session, callDone("old"));
|
|
917
|
+
await server.send(session, { type: "session.usage.updated", usage: { seconds: 10 } });
|
|
918
|
+
server.sockets[0].terminate();
|
|
919
|
+
await import_vitest.vi.waitFor(() => (0, import_vitest.expect)(errors).toHaveLength(1), { interval: 5 });
|
|
920
|
+
await session._appendItems([
|
|
921
|
+
new import_agents.llm.ChatMessage({ role: "user", content: "While reconnecting" })
|
|
922
|
+
]);
|
|
923
|
+
await import_vitest.vi.waitFor(() => (0, import_vitest.expect)(session.sessionId).toBe("live_1"));
|
|
924
|
+
(0, import_vitest.expect)(startConfig(1).input).toMatchObject([
|
|
925
|
+
{ content: [{ text: 'Called tool getWeather with {"location":"Paris"}' }] },
|
|
926
|
+
{ content: [{ text: "While reconnecting" }] }
|
|
927
|
+
]);
|
|
928
|
+
await server.send(session, { type: "session.usage.updated", usage: { seconds: 2 } });
|
|
929
|
+
(0, import_vitest.expect)(durations).toEqual([1e4, 2e3]);
|
|
930
|
+
await session._appendItems([output("old")]);
|
|
931
|
+
await waitCount(2, 1);
|
|
932
|
+
(0, import_vitest.expect)((_a = server.events(1)[1]) == null ? void 0 : _a.type).toBe("session.thinking.append");
|
|
933
|
+
});
|
|
934
|
+
(0, import_vitest.it)("retains sent standing rules and silent context across reconnects", async () => {
|
|
935
|
+
const session = create();
|
|
936
|
+
await ready(session);
|
|
937
|
+
session.appendInstructions("Include tax in prices.");
|
|
938
|
+
session.appendThinking("The caller has a discount.");
|
|
939
|
+
await server.send(session, {
|
|
940
|
+
type: "session.delegation.created",
|
|
941
|
+
delegation: { id: "d1", target: "client" }
|
|
942
|
+
});
|
|
943
|
+
session.appendCommentary("Say hello once.", { delegationId: "d1" });
|
|
944
|
+
await waitCount(4);
|
|
945
|
+
server.sockets[0].terminate();
|
|
946
|
+
await import_vitest.vi.waitFor(() => (0, import_vitest.expect)(session.sessionId).toBe("live_1"));
|
|
947
|
+
(0, import_vitest.expect)(startConfig(1).input).toMatchObject([
|
|
948
|
+
{ role: "developer", content: [{ text: "Include tax in prices." }] },
|
|
949
|
+
{ role: "developer", content: [{ text: "The caller has a discount." }] }
|
|
950
|
+
]);
|
|
951
|
+
(0, import_vitest.expect)(server.events(1)).toHaveLength(1);
|
|
952
|
+
});
|
|
953
|
+
import_vitest.it.each([false, true])(
|
|
954
|
+
"finalizes the caller transcript when shutdown is fatal=%s",
|
|
955
|
+
async (fatal) => {
|
|
956
|
+
const session = create();
|
|
957
|
+
const transcripts = [];
|
|
958
|
+
session.on("input_audio_transcription_completed", (event) => transcripts.push(event));
|
|
959
|
+
await ready(session);
|
|
960
|
+
await server.send(session, transcript("user", "My order is A1042", 0));
|
|
961
|
+
if (fatal) {
|
|
962
|
+
await server.send(session, { type: "error", error: { code: "invalid_api_key" } });
|
|
963
|
+
await import_vitest.vi.waitFor(() => (0, import_vitest.expect)(transcripts.some((event) => event.isFinal)).toBe(true));
|
|
964
|
+
}
|
|
965
|
+
await session.close();
|
|
966
|
+
await session.close();
|
|
967
|
+
(0, import_vitest.expect)(transcripts.map(({ transcript: transcript2, isFinal }) => ({ transcript: transcript2, isFinal }))).toEqual([
|
|
968
|
+
{ transcript: "My order is A1042", isFinal: false },
|
|
969
|
+
{ transcript: "My order is A1042", isFinal: true }
|
|
970
|
+
]);
|
|
971
|
+
}
|
|
972
|
+
);
|
|
973
|
+
import_vitest.it.each(["response.failed", "response.incomplete"])(
|
|
974
|
+
"accounts for backend tokens on %s without continuing the response",
|
|
975
|
+
async (type) => {
|
|
976
|
+
var _a;
|
|
977
|
+
const session = create();
|
|
978
|
+
const collected = [];
|
|
979
|
+
session.on("metrics_collected", (metric) => {
|
|
980
|
+
if (metric.type === "llm_metrics") collected.push(metric);
|
|
981
|
+
});
|
|
982
|
+
await ready(session);
|
|
983
|
+
await server.response(session, { type: "response.created" });
|
|
984
|
+
await server.response(session, callDone("a"));
|
|
985
|
+
await server.response(session, { ...completed(), type });
|
|
986
|
+
(0, import_vitest.expect)(collected).toMatchObject([
|
|
987
|
+
{
|
|
988
|
+
promptTokens: 376,
|
|
989
|
+
completionTokens: 18,
|
|
990
|
+
totalTokens: 394,
|
|
991
|
+
promptCachedTokens: 100,
|
|
992
|
+
cacheCreationTokens: 20,
|
|
993
|
+
requestId: "resp_1",
|
|
994
|
+
cancelled: false
|
|
995
|
+
}
|
|
996
|
+
]);
|
|
997
|
+
await session._appendItems([output("a")]);
|
|
998
|
+
await waitCount(2);
|
|
999
|
+
(0, import_vitest.expect)((_a = server.events()[1]) == null ? void 0 : _a.type).toBe("session.thinking.append");
|
|
1000
|
+
}
|
|
1001
|
+
);
|
|
1002
|
+
(0, import_vitest.it)("does not replay history appends from a failed startup", async () => {
|
|
1003
|
+
server.autoStart = false;
|
|
1004
|
+
const session = create({
|
|
1005
|
+
connOptions: { maxRetry: 1, retryIntervalMs: 10, timeoutMs: 1e3 }
|
|
1006
|
+
});
|
|
1007
|
+
await session._updateSession();
|
|
1008
|
+
await waitCount(1);
|
|
1009
|
+
await session._appendItems([
|
|
1010
|
+
new import_agents.llm.ChatMessage({ role: "user", content: "Pending question" }),
|
|
1011
|
+
new import_agents.llm.ChatMessage({ role: "developer", content: "Pending rule" })
|
|
1012
|
+
]);
|
|
1013
|
+
session.appendThinking("Manual context");
|
|
1014
|
+
server.sockets[0].terminate();
|
|
1015
|
+
await waitCount(1, 1);
|
|
1016
|
+
await session._appendItems([
|
|
1017
|
+
new import_agents.llm.ChatMessage({ role: "user", content: "After retry snapshot" })
|
|
1018
|
+
]);
|
|
1019
|
+
await server.send(session, { type: "session.started", session: { id: "live_1" } });
|
|
1020
|
+
await waitCount(3, 1);
|
|
1021
|
+
(0, import_vitest.expect)(startConfig(1).input).toMatchObject([
|
|
1022
|
+
{ content: [{ text: "Pending question" }] },
|
|
1023
|
+
{ content: [{ text: "Pending rule" }] }
|
|
1024
|
+
]);
|
|
1025
|
+
(0, import_vitest.expect)(server.events(1).slice(1)).toMatchObject([
|
|
1026
|
+
{ type: "session.thinking.append", content: "Manual context" },
|
|
1027
|
+
{ type: "session.thinking.append", content: "user: After retry snapshot" }
|
|
1028
|
+
]);
|
|
1029
|
+
});
|
|
1030
|
+
(0, import_vitest.it)("discards queued tool responses and continuation from a drained connection", async () => {
|
|
1031
|
+
server.autoClose = false;
|
|
1032
|
+
const session = create({ maxSessionDuration: 300 });
|
|
1033
|
+
await ready(session);
|
|
1034
|
+
await server.response(session, { type: "response.created" });
|
|
1035
|
+
await server.response(session, callDone("old"));
|
|
1036
|
+
await server.response(session, completed());
|
|
1037
|
+
await import_vitest.vi.waitFor(() => {
|
|
1038
|
+
var _a;
|
|
1039
|
+
return (0, import_vitest.expect)((_a = server.events().at(-1)) == null ? void 0 : _a.type).toBe("session.close");
|
|
1040
|
+
});
|
|
1041
|
+
await session._appendItems([output("old")]);
|
|
1042
|
+
await server.send(session, { type: "session.closed", reason: "expired" });
|
|
1043
|
+
await import_vitest.vi.waitFor(() => (0, import_vitest.expect)(session.sessionId).toBe("live_1"));
|
|
1044
|
+
(0, import_vitest.expect)(startConfig(1).input).toMatchObject([
|
|
1045
|
+
{ content: [{ text: 'Called tool getWeather with {"location":"Paris"}' }] },
|
|
1046
|
+
{ content: [{ text: "Tool getWeather returned rainy" }] }
|
|
1047
|
+
]);
|
|
1048
|
+
(0, import_vitest.expect)(server.events(1)).toHaveLength(1);
|
|
1049
|
+
server.autoClose = true;
|
|
1050
|
+
});
|
|
1051
|
+
(0, import_vitest.it)("keeps the cumulative usage baseline across missing or decreasing updates", async () => {
|
|
1052
|
+
const session = create();
|
|
1053
|
+
const durations = [];
|
|
1054
|
+
session.on("metrics_collected", (metric) => {
|
|
1055
|
+
if (metric.type === "realtime_model_metrics" && metric.sessionDurationMs !== void 0)
|
|
1056
|
+
durations.push(metric.sessionDurationMs);
|
|
1057
|
+
});
|
|
1058
|
+
await ready(session);
|
|
1059
|
+
for (const usage of [{ seconds: 10 }, void 0, {}, { seconds: 4 }, { seconds: 12 }])
|
|
1060
|
+
await server.send(session, { type: "session.usage.updated", usage });
|
|
1061
|
+
server.closeUsage = 15;
|
|
1062
|
+
await session.close();
|
|
1063
|
+
(0, import_vitest.expect)(durations).toEqual([1e4, 2e3, 3e3]);
|
|
1064
|
+
});
|
|
1065
|
+
import_vitest.it.each([1, 3, 5])("decodes %s audio bytes without reading past the buffer", async (length) => {
|
|
1066
|
+
const session = create();
|
|
1067
|
+
const errors = import_vitest.vi.spyOn((0, import_agents.log)(), "error");
|
|
1068
|
+
await ready(session);
|
|
1069
|
+
const reader = session.audioStream.getReader();
|
|
1070
|
+
await server.send(session, {
|
|
1071
|
+
type: "session.output_audio.delta",
|
|
1072
|
+
delta: Buffer.alloc(length, 1).toString("base64")
|
|
1073
|
+
});
|
|
1074
|
+
const { value } = await reader.read();
|
|
1075
|
+
(0, import_vitest.expect)(value == null ? void 0 : value.frame.samplesPerChannel).toBe(Math.floor(length / 2));
|
|
1076
|
+
(0, import_vitest.expect)(errors).not.toHaveBeenCalled();
|
|
1077
|
+
reader.releaseLock();
|
|
1078
|
+
});
|
|
1079
|
+
(0, import_vitest.it)("recycles a connection at maxSessionDuration in milliseconds", async () => {
|
|
1080
|
+
const session = create({ maxSessionDuration: 200 });
|
|
1081
|
+
await ready(session);
|
|
1082
|
+
await import_vitest.vi.waitFor(() => (0, import_vitest.expect)(session.sessionId).toBe("live_1"));
|
|
1083
|
+
(0, import_vitest.expect)(server.sockets).toHaveLength(2);
|
|
1084
|
+
});
|
|
1085
|
+
import_vitest.it.each([
|
|
1086
|
+
[true, "expired"],
|
|
1087
|
+
[true, "connection_lost"],
|
|
1088
|
+
[false, "expired"],
|
|
1089
|
+
[false, "connection_lost"]
|
|
1090
|
+
])(
|
|
1091
|
+
"drains timed=%s reconnects with reason=%s and waits for each close",
|
|
1092
|
+
async (timed, reason) => {
|
|
1093
|
+
var _a, _b;
|
|
1094
|
+
server.autoClose = false;
|
|
1095
|
+
const session = create({
|
|
1096
|
+
maxSessionDuration: timed ? 300 : null,
|
|
1097
|
+
connOptions: { maxRetry: 0, retryIntervalMs: 10, timeoutMs: 1e3 }
|
|
1098
|
+
});
|
|
1099
|
+
const errors = [];
|
|
1100
|
+
const durations = [];
|
|
1101
|
+
session.on("error", (error) => errors.push(error));
|
|
1102
|
+
session.on("metrics_collected", (metric) => {
|
|
1103
|
+
if (metric.type === "realtime_model_metrics" && metric.sessionDurationMs !== void 0)
|
|
1104
|
+
durations.push(metric.sessionDurationMs);
|
|
1105
|
+
});
|
|
1106
|
+
try {
|
|
1107
|
+
await ready(session);
|
|
1108
|
+
await session._updateTools(tools);
|
|
1109
|
+
session._updateOptions({ toolChoice: "none" });
|
|
1110
|
+
await session._appendItems([output("old")]);
|
|
1111
|
+
if (timed) {
|
|
1112
|
+
await import_vitest.vi.waitFor(() => {
|
|
1113
|
+
var _a2;
|
|
1114
|
+
return (0, import_vitest.expect)((_a2 = server.events().at(-1)) == null ? void 0 : _a2.type).toBe("session.close");
|
|
1115
|
+
});
|
|
1116
|
+
(0, import_vitest.expect)(server.sockets[0].readyState).toBe(import_ws.WebSocket.OPEN);
|
|
1117
|
+
const reader = session.audioStream.getReader();
|
|
1118
|
+
await server.send(session, {
|
|
1119
|
+
type: "session.output_audio.delta",
|
|
1120
|
+
delta: Buffer.from(pcm(100, 0.2).data.buffer).toString("base64")
|
|
1121
|
+
});
|
|
1122
|
+
(0, import_vitest.expect)((_a = (await reader.read()).value) == null ? void 0 : _a.frame.samplesPerChannel).toBe(2400);
|
|
1123
|
+
reader.releaseLock();
|
|
1124
|
+
session.appendThinking("During drain.");
|
|
1125
|
+
await (0, import_promises.setTimeout)(10);
|
|
1126
|
+
(0, import_vitest.expect)((_b = server.events().at(-1)) == null ? void 0 : _b.type).toBe("session.close");
|
|
1127
|
+
}
|
|
1128
|
+
await server.send(session, { type: "session.closed", reason, usage: { seconds: 5 } });
|
|
1129
|
+
if (!timed) server.sockets[0].close();
|
|
1130
|
+
await import_vitest.vi.waitFor(() => (0, import_vitest.expect)(session.sessionId).toBe("live_1"));
|
|
1131
|
+
(0, import_vitest.expect)(errors).toEqual([]);
|
|
1132
|
+
(0, import_vitest.expect)(durations).toEqual([5e3]);
|
|
1133
|
+
(0, import_vitest.expect)(startConfig(1)).toMatchObject({
|
|
1134
|
+
delegation: { responses: { tool_choice: "none", tools: [{ name: "getWeather" }] } },
|
|
1135
|
+
input: [{ content: [{ text: "Tool getWeather returned rainy" }] }]
|
|
1136
|
+
});
|
|
1137
|
+
if (timed) {
|
|
1138
|
+
await import_vitest.vi.waitFor(
|
|
1139
|
+
() => (0, import_vitest.expect)(server.events(1).some((event) => event.type === "session.thinking.append")).toBe(
|
|
1140
|
+
true
|
|
1141
|
+
)
|
|
1142
|
+
);
|
|
1143
|
+
}
|
|
1144
|
+
let closed = false;
|
|
1145
|
+
const closing = session.close().then(() => {
|
|
1146
|
+
closed = true;
|
|
1147
|
+
});
|
|
1148
|
+
await import_vitest.vi.waitFor(() => {
|
|
1149
|
+
var _a2;
|
|
1150
|
+
return (0, import_vitest.expect)((_a2 = server.events(1).at(-1)) == null ? void 0 : _a2.type).toBe("session.close");
|
|
1151
|
+
});
|
|
1152
|
+
await (0, import_promises.setTimeout)(10);
|
|
1153
|
+
(0, import_vitest.expect)(closed).toBe(false);
|
|
1154
|
+
await server.send(session, {
|
|
1155
|
+
type: "session.closed",
|
|
1156
|
+
reason: "close_requested",
|
|
1157
|
+
usage: { seconds: 7 }
|
|
1158
|
+
});
|
|
1159
|
+
await closing;
|
|
1160
|
+
(0, import_vitest.expect)(durations).toEqual([5e3, 7e3]);
|
|
1161
|
+
} finally {
|
|
1162
|
+
server.autoClose = true;
|
|
1163
|
+
const closing = session.close();
|
|
1164
|
+
for (const socket of server.sockets) {
|
|
1165
|
+
if (socket.readyState === import_ws.WebSocket.OPEN)
|
|
1166
|
+
socket.send(JSON.stringify({ type: "session.closed" }));
|
|
1167
|
+
}
|
|
1168
|
+
await closing;
|
|
1169
|
+
}
|
|
1170
|
+
}
|
|
1171
|
+
);
|
|
1172
|
+
import_vitest.it.each([24e3, 48e3])(
|
|
1173
|
+
"discards partial %s Hz input and resampler state on reconnect",
|
|
1174
|
+
async (rate) => {
|
|
1175
|
+
const closeResampler = import_vitest.vi.spyOn(import_rtc_node.AudioResampler.prototype, "close");
|
|
1176
|
+
const session = create();
|
|
1177
|
+
await ready(session);
|
|
1178
|
+
session.pushAudio(pcm(60, 0.5, rate));
|
|
1179
|
+
server.sockets[0].terminate();
|
|
1180
|
+
await import_vitest.vi.waitFor(() => (0, import_vitest.expect)(session.sessionId).toBe("live_1"));
|
|
1181
|
+
if (rate !== 24e3) (0, import_vitest.expect)(closeResampler).toHaveBeenCalledOnce();
|
|
1182
|
+
session.pushAudio(pcm(40, 0, rate));
|
|
1183
|
+
await (0, import_promises.setTimeout)(20);
|
|
1184
|
+
(0, import_vitest.expect)(server.events(1).map((event) => event.type)).toEqual(["session.start"]);
|
|
1185
|
+
session.pushAudio(pcm(200, 0, rate));
|
|
1186
|
+
await import_vitest.vi.waitFor(() => (0, import_vitest.expect)(server.events(1).length).toBeGreaterThan(1));
|
|
1187
|
+
for (const event of server.events(1)) {
|
|
1188
|
+
if (event.type !== "session.input_audio.append") continue;
|
|
1189
|
+
const audio = Buffer.from(event.audio, "base64");
|
|
1190
|
+
(0, import_vitest.expect)(audio.length).toBe(4800);
|
|
1191
|
+
for (let offset = 0; offset < audio.length; offset += 2)
|
|
1192
|
+
(0, import_vitest.expect)(Math.abs(audio.readInt16LE(offset))).toBeLessThanOrEqual(1);
|
|
1193
|
+
}
|
|
1194
|
+
await session.close();
|
|
1195
|
+
if (rate !== 24e3) (0, import_vitest.expect)(closeResampler).toHaveBeenCalledTimes(2);
|
|
1196
|
+
}
|
|
1197
|
+
);
|
|
1198
|
+
import_vitest.it.each(["invalid_request", "invalid_api_key"])(
|
|
1199
|
+
"sanitizes emitted %s provider errors",
|
|
1200
|
+
async (code) => {
|
|
1201
|
+
const session = create();
|
|
1202
|
+
const errors = [];
|
|
1203
|
+
session.on("error", (error) => errors.push(error));
|
|
1204
|
+
await ready(session);
|
|
1205
|
+
await server.send(session, {
|
|
1206
|
+
type: "error",
|
|
1207
|
+
error: { code, message: "private-provider-payload" }
|
|
1208
|
+
});
|
|
1209
|
+
await import_vitest.vi.waitFor(() => (0, import_vitest.expect)(errors).toHaveLength(1));
|
|
1210
|
+
(0, import_vitest.expect)(String(errors[0].error)).not.toContain("private-provider-payload");
|
|
1211
|
+
(0, import_vitest.expect)(JSON.stringify(errors[0].error)).not.toContain("private-provider-payload");
|
|
1212
|
+
(0, import_vitest.expect)(errors[0].error.cause).toBeUndefined();
|
|
1213
|
+
(0, import_vitest.expect)(errors[0].recoverable).toBe(code === "invalid_request");
|
|
1214
|
+
}
|
|
1215
|
+
);
|
|
1216
|
+
import_vitest.it.each(["send", "send callback", "receive"])(
|
|
1217
|
+
"sanitizes %s transport failures",
|
|
1218
|
+
async (operation) => {
|
|
1219
|
+
const session = create({
|
|
1220
|
+
connOptions: { maxRetry: 0, retryIntervalMs: 10, timeoutMs: 1e3 }
|
|
1221
|
+
});
|
|
1222
|
+
const errors = [];
|
|
1223
|
+
session.on("error", (error) => errors.push(error));
|
|
1224
|
+
await ready(session);
|
|
1225
|
+
if (operation === "send") {
|
|
1226
|
+
import_vitest.vi.spyOn(import_ws.WebSocket.prototype, "send").mockImplementationOnce(() => {
|
|
1227
|
+
throw new Error("private-transport-payload");
|
|
1228
|
+
});
|
|
1229
|
+
session.appendThinking("Trigger send.");
|
|
1230
|
+
} else if (operation === "send callback") {
|
|
1231
|
+
import_vitest.vi.spyOn(import_ws.WebSocket.prototype, "send").mockImplementationOnce(function(...args) {
|
|
1232
|
+
const callback = args.at(-1);
|
|
1233
|
+
if (typeof callback === "function") callback(new Error("private-transport-payload"));
|
|
1234
|
+
});
|
|
1235
|
+
session.appendThinking("Trigger send callback.");
|
|
1236
|
+
} else {
|
|
1237
|
+
const send = import_ws.WebSocket.prototype.send;
|
|
1238
|
+
import_vitest.vi.spyOn(import_ws.WebSocket.prototype, "send").mockImplementationOnce(function(...args) {
|
|
1239
|
+
this.emit("error", new Error("private-transport-payload"));
|
|
1240
|
+
return send.apply(this, args);
|
|
1241
|
+
});
|
|
1242
|
+
session.appendThinking("Trigger socket error.");
|
|
1243
|
+
}
|
|
1244
|
+
await import_vitest.vi.waitFor(() => (0, import_vitest.expect)(errors).toHaveLength(1));
|
|
1245
|
+
(0, import_vitest.expect)(String(errors[0].error)).not.toContain("private-transport-payload");
|
|
1246
|
+
(0, import_vitest.expect)(errors[0].error.cause).toBeUndefined();
|
|
1247
|
+
(0, import_vitest.expect)(errors[0].recoverable).toBe(false);
|
|
1248
|
+
}
|
|
1249
|
+
);
|
|
1250
|
+
(0, import_vitest.it)("sanitizes unexpected connection setup errors", async () => {
|
|
1251
|
+
const session = create({ baseURL: "private-invalid-url" });
|
|
1252
|
+
const errors = [];
|
|
1253
|
+
session.on("error", (error) => errors.push(error));
|
|
1254
|
+
await session._updateSession();
|
|
1255
|
+
await import_vitest.vi.waitFor(() => (0, import_vitest.expect)(errors).toHaveLength(1));
|
|
1256
|
+
(0, import_vitest.expect)(errors[0].error.message).toBe("GPT-Live session failed");
|
|
1257
|
+
(0, import_vitest.expect)(JSON.stringify(errors[0].error)).not.toContain("private-invalid-url");
|
|
1258
|
+
(0, import_vitest.expect)(errors[0].error.cause).toBeUndefined();
|
|
1259
|
+
(0, import_vitest.expect)(errors[0].recoverable).toBe(false);
|
|
1260
|
+
});
|
|
1261
|
+
(0, import_vitest.it)("keeps provider content only in PII log fields", async () => {
|
|
1262
|
+
var _a;
|
|
1263
|
+
import_vitest.vi.stubEnv("LK_OPENAI_DEBUG", "1");
|
|
1264
|
+
const logger = (0, import_agents.log)();
|
|
1265
|
+
const logs = [import_vitest.vi.spyOn(logger, "debug"), import_vitest.vi.spyOn(logger, "warn"), import_vitest.vi.spyOn(logger, "error")];
|
|
1266
|
+
const privateText = "private-customer-payload";
|
|
1267
|
+
const session = create();
|
|
1268
|
+
class OtherProviderTool extends import_agents.llm.ProviderTool {
|
|
1269
|
+
}
|
|
1270
|
+
await session._updateTools(new import_agents.llm.ToolContext([new OtherProviderTool({ id: privateText })]));
|
|
1271
|
+
await session._updateInstructions(privateText);
|
|
1272
|
+
await ready(session);
|
|
1273
|
+
await server.response(session, {
|
|
1274
|
+
type: "response.output_item.done",
|
|
1275
|
+
item: { type: "function_call", call_id: privateText, name: privateText }
|
|
1276
|
+
});
|
|
1277
|
+
await server.response(
|
|
1278
|
+
session,
|
|
1279
|
+
{
|
|
1280
|
+
type: "response.output_item.done",
|
|
1281
|
+
item: { type: "function_call", call_id: privateText, name: privateText, arguments: "{}" }
|
|
1282
|
+
},
|
|
1283
|
+
privateText
|
|
1284
|
+
);
|
|
1285
|
+
session.appendThinking(privateText);
|
|
1286
|
+
await server.send(session, transcript("user", privateText, 0));
|
|
1287
|
+
await server.response(session, {
|
|
1288
|
+
type: "response.failed",
|
|
1289
|
+
response: { error: { message: privateText }, incomplete_details: { reason: privateText } }
|
|
1290
|
+
});
|
|
1291
|
+
await server.send(session, { type: "error", error: { message: privateText } });
|
|
1292
|
+
const received = (0, import_node_events.once)(session, "openai_server_event_received");
|
|
1293
|
+
server.sockets[0].send(JSON.stringify({ type: privateText }));
|
|
1294
|
+
await received;
|
|
1295
|
+
await session.close();
|
|
1296
|
+
let piiFields = 0;
|
|
1297
|
+
for (const spy of logs) {
|
|
1298
|
+
for (const args of spy.mock.calls) {
|
|
1299
|
+
for (const arg of args) {
|
|
1300
|
+
if (typeof arg === "string") (0, import_vitest.expect)(arg).not.toContain(privateText);
|
|
1301
|
+
else if (arg && typeof arg === "object") {
|
|
1302
|
+
for (const [key, value] of Object.entries(arg)) {
|
|
1303
|
+
if ((_a = JSON.stringify(value)) == null ? void 0 : _a.includes(privateText)) {
|
|
1304
|
+
(0, import_vitest.expect)(key).toContain(".pii.");
|
|
1305
|
+
piiFields++;
|
|
1306
|
+
}
|
|
1307
|
+
}
|
|
1308
|
+
}
|
|
1309
|
+
}
|
|
1310
|
+
}
|
|
1311
|
+
}
|
|
1312
|
+
(0, import_vitest.expect)(piiFields).toBeGreaterThan(0);
|
|
1313
|
+
});
|
|
1314
|
+
import_vitest.it.each([
|
|
1315
|
+
"invalid_api_key",
|
|
1316
|
+
"insufficient_quota",
|
|
1317
|
+
"account_deactivated",
|
|
1318
|
+
"billing_hard_limit_reached"
|
|
1319
|
+
])("does not reconnect after fatal %s errors", async (code) => {
|
|
1320
|
+
var _a;
|
|
1321
|
+
const session = create();
|
|
1322
|
+
const errors = [];
|
|
1323
|
+
session.on("error", (error) => errors.push(error));
|
|
1324
|
+
await ready(session);
|
|
1325
|
+
await server.send(session, { type: "error", error: { code, message: "Rejected" } });
|
|
1326
|
+
await import_vitest.vi.waitFor(() => (0, import_vitest.expect)(errors).toHaveLength(1));
|
|
1327
|
+
(0, import_vitest.expect)((_a = errors[0]) == null ? void 0 : _a.recoverable).toBe(false);
|
|
1328
|
+
await session.close();
|
|
1329
|
+
(0, import_vitest.expect)(server.sockets).toHaveLength(1);
|
|
1330
|
+
});
|
|
1331
|
+
(0, import_vitest.it)("reports recoverable protocol errors without disconnecting", async () => {
|
|
1332
|
+
var _a;
|
|
1333
|
+
const session = create();
|
|
1334
|
+
const errors = [];
|
|
1335
|
+
session.on("error", (error) => errors.push(error));
|
|
1336
|
+
await ready(session);
|
|
1337
|
+
await server.send(session, {
|
|
1338
|
+
type: "error",
|
|
1339
|
+
error: { code: "invalid_request", message: "Bad command" }
|
|
1340
|
+
});
|
|
1341
|
+
(0, import_vitest.expect)((_a = errors[0]) == null ? void 0 : _a.recoverable).toBe(true);
|
|
1342
|
+
session.appendThinking("Still connected.");
|
|
1343
|
+
await waitCount(2);
|
|
1344
|
+
(0, import_vitest.expect)(server.sockets).toHaveLength(1);
|
|
1345
|
+
});
|
|
1346
|
+
(0, import_vitest.it)("cancels retry sleep during shutdown", async () => {
|
|
1347
|
+
const session = create();
|
|
1348
|
+
const failed = new Promise((resolve) => session.once("error", () => resolve()));
|
|
1349
|
+
await ready(session);
|
|
1350
|
+
server.sockets[0].terminate();
|
|
1351
|
+
await failed;
|
|
1352
|
+
await session.close();
|
|
1353
|
+
await (0, import_promises.setTimeout)(120);
|
|
1354
|
+
(0, import_vitest.expect)(server.sockets).toHaveLength(1);
|
|
1355
|
+
});
|
|
1356
|
+
});
|
|
1357
|
+
(0, import_vitest.describe)("GPT-Live AgentSession integration", () => {
|
|
1358
|
+
(0, import_vitest.it)("runs framework tools and retains final usage through shutdown", async () => {
|
|
1359
|
+
const execute = import_vitest.vi.fn(async () => "rainy");
|
|
1360
|
+
const agent = new import_agents.voice.Agent({
|
|
1361
|
+
instructions: "Be concise.",
|
|
1362
|
+
tools: [
|
|
1363
|
+
import_agents.llm.tool({
|
|
1364
|
+
name: "getWeather",
|
|
1365
|
+
description: "Get weather",
|
|
1366
|
+
parameters: import_zod.z.object({ location: import_zod.z.string() }),
|
|
1367
|
+
execute
|
|
1368
|
+
})
|
|
1369
|
+
]
|
|
1370
|
+
});
|
|
1371
|
+
const session = new import_agents.voice.AgentSession({
|
|
1372
|
+
llm: new import_gpt_live_model.GPTLiveModel({ apiKey: "test", baseURL: server.url }),
|
|
1373
|
+
vad: null,
|
|
1374
|
+
aecWarmupDuration: null
|
|
1375
|
+
});
|
|
1376
|
+
const collected = [];
|
|
1377
|
+
session.on(
|
|
1378
|
+
import_agents.voice.AgentSessionEventTypes.MetricsCollected,
|
|
1379
|
+
(event) => collected.push(event.metrics)
|
|
1380
|
+
);
|
|
1381
|
+
try {
|
|
1382
|
+
await session.start({ agent });
|
|
1383
|
+
const live = agent.duplexSession;
|
|
1384
|
+
await import_vitest.vi.waitFor(() => (0, import_vitest.expect)(live.sessionId).toBeDefined());
|
|
1385
|
+
await server.response(live, { type: "response.created" });
|
|
1386
|
+
await server.response(live, callDone("framework"));
|
|
1387
|
+
await server.response(live, completed());
|
|
1388
|
+
await import_vitest.vi.waitFor(() => (0, import_vitest.expect)(execute).toHaveBeenCalledOnce());
|
|
1389
|
+
await import_vitest.vi.waitFor(
|
|
1390
|
+
() => (0, import_vitest.expect)(server.events().some((event) => event.type === "response.create")).toBe(true)
|
|
1391
|
+
);
|
|
1392
|
+
const result = server.events().find((event) => event.type === "response.item.create");
|
|
1393
|
+
(0, import_vitest.expect)(result).toMatchObject({
|
|
1394
|
+
item: { call_id: "framework", output: JSON.stringify("rainy") }
|
|
1395
|
+
});
|
|
1396
|
+
server.closeUsage = 17;
|
|
1397
|
+
await session.close();
|
|
1398
|
+
(0, import_vitest.expect)(collected).toContainEqual(
|
|
1399
|
+
import_vitest.expect.objectContaining({ type: "realtime_model_metrics", sessionDurationMs: 17e3 })
|
|
1400
|
+
);
|
|
1401
|
+
} finally {
|
|
1402
|
+
await session.close();
|
|
1403
|
+
}
|
|
1404
|
+
});
|
|
1405
|
+
(0, import_vitest.it)("commits user transcripts with the turn start time through the adapter", async () => {
|
|
1406
|
+
const agent = new import_agents.voice.Agent({ instructions: "Be concise." });
|
|
1407
|
+
const session = new import_agents.voice.AgentSession({
|
|
1408
|
+
llm: new import_gpt_live_model.GPTLiveModel({ apiKey: "test", baseURL: server.url }),
|
|
1409
|
+
vad: null,
|
|
1410
|
+
aecWarmupDuration: null
|
|
1411
|
+
});
|
|
1412
|
+
try {
|
|
1413
|
+
await session.start({ agent });
|
|
1414
|
+
const live = agent.duplexSession;
|
|
1415
|
+
await import_vitest.vi.waitFor(() => (0, import_vitest.expect)(live.sessionId).toBeDefined());
|
|
1416
|
+
const start = Date.now();
|
|
1417
|
+
await server.send(live, transcript("user", "Where is my order?", 1e3));
|
|
1418
|
+
live.pushAudio(pcm(800));
|
|
1419
|
+
await import_vitest.vi.waitFor(
|
|
1420
|
+
() => (0, import_vitest.expect)(
|
|
1421
|
+
agent.chatCtx.items.some(
|
|
1422
|
+
(item) => item.type === "message" && item.textContent === "Where is my order?"
|
|
1423
|
+
)
|
|
1424
|
+
).toBe(true)
|
|
1425
|
+
);
|
|
1426
|
+
const message = agent.chatCtx.items.find(
|
|
1427
|
+
(item) => item.type === "message" && item.role === "user"
|
|
1428
|
+
);
|
|
1429
|
+
(0, import_vitest.expect)(message == null ? void 0 : message.createdAt).toBeGreaterThanOrEqual(start);
|
|
1430
|
+
(0, import_vitest.expect)(message == null ? void 0 : message.createdAt).toBeLessThanOrEqual(Date.now());
|
|
1431
|
+
} finally {
|
|
1432
|
+
await session.close();
|
|
1433
|
+
}
|
|
1434
|
+
});
|
|
1435
|
+
});
|
|
1436
|
+
//# sourceMappingURL=gpt_live_model.test.cjs.map
|