@voicethere/agent 0.28.0 → 0.29.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/README.md +40 -17
- package/dist/agent.js +85 -3
- package/dist/flow/core/abort.d.ts +10 -0
- package/dist/flow/core/abort.d.ts.map +1 -0
- package/dist/flow/core/abort.js +16 -0
- package/dist/flow/core/abort.js.map +1 -0
- package/dist/flow/core/interpreter.d.ts.map +1 -1
- package/dist/flow/core/interpreter.js +4 -3
- package/dist/flow/core/interpreter.js.map +1 -1
- package/dist/flow/record.d.ts +2 -0
- package/dist/flow/record.d.ts.map +1 -1
- package/dist/flow/record.js +23 -9
- package/dist/flow/record.js.map +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/protocol.d.ts +95 -2
- package/dist/protocol.d.ts.map +1 -1
- package/dist/protocol.js.map +1 -1
- package/dist/runtime.d.ts +51 -1
- package/dist/runtime.d.ts.map +1 -1
- package/dist/runtime.js +184 -1
- package/dist/runtime.js.map +1 -1
- package/dist/templates/echo/agent.js +84 -3
- package/dist/templates/echo-dc/agent.js +84 -3
- package/dist/templates/flow-agent/agent.js +93 -6
- package/dist/templates/game-sync/agent.js +84 -3
- package/dist/templates/language-switch/agent.js +84 -3
- package/dist/templates/llm-agent/agent.js +84 -3
- package/dist/templates/llm-docs-rag/agent.js +84 -3
- package/dist/templates/llm-mcp-service/agent.js +84 -3
- package/dist/templates/llm-support-sticky-user/agent.js +84 -3
- package/dist/templates/positional-tts/agent.js +84 -3
- package/dist/templates/recording-consent/agent.js +84 -3
- package/dist/templates/registry.d.ts.map +1 -1
- package/dist/templates/registry.js +11 -0
- package/dist/templates/registry.js.map +1 -1
- package/dist/templates/spatial-showcase/agent.js +84 -3
- package/dist/templates/speaker-gate/agent.js +1575 -0
- package/dist/templates/voice-showcase/agent.js +84 -3
- package/dist/templates/voice-starter/agent.js +84 -3
- package/dist/templates/webhooks/agent.js +84 -3
- package/dist/templates/webhooks-redis/agent.js +84 -3
- package/dist/templates/world-sync/agent.js +84 -3
- package/dist/templates/world-sync-binary/agent.js +84 -3
- package/eject/llm/loop.ts +1 -1
- package/package.json +1 -1
- package/templates/README.md +24 -23
- package/templates/speaker-gate/README.md +48 -0
- package/templates/speaker-gate/agent.ts +168 -0
|
@@ -0,0 +1,1575 @@
|
|
|
1
|
+
import { createRequire as __voicethereCreateRequire } from "node:module";
|
|
2
|
+
const require = __voicethereCreateRequire(import.meta.url);
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
// dist/runtime.js
|
|
6
|
+
import { randomUUID } from "node:crypto";
|
|
7
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
8
|
+
|
|
9
|
+
// dist/voice-provider-id.js
|
|
10
|
+
function toPublicProviderId(id) {
|
|
11
|
+
const lower = id.trim().toLowerCase();
|
|
12
|
+
return lower === "local-sherpa" || lower === "cluster-sherpa" ? "voicethere" : id;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
// dist/voice-request-validation.js
|
|
16
|
+
var VOICE_SWITCH_MESSAGES = {
|
|
17
|
+
invalid_scope: 'scope must be "stt", "tts" or "both".',
|
|
18
|
+
nothing_to_apply: "Pass sttVendor, ttsVendor or language.",
|
|
19
|
+
unknown_stt: 'No VoiceThere STT model matches sttVendor.model or the language; use a catalog id such as "en" or "en-small".',
|
|
20
|
+
unknown_voice: 'No VoiceThere voice matches ttsVendor.voice or the language; use a catalog id such as "en-lessac".',
|
|
21
|
+
invalid_language: 'language must be an ISO 639-1 code such as "en" or "de".',
|
|
22
|
+
language_unavailable: "The models for this language did not start; try again later or pick another language.",
|
|
23
|
+
unavailable: "Voice switching is not available for this session.",
|
|
24
|
+
timeout: "The voice switch did not finish in time; try again."
|
|
25
|
+
};
|
|
26
|
+
function localVoiceSwitchMessage(reason) {
|
|
27
|
+
return reason !== void 0 && Object.prototype.hasOwnProperty.call(VOICE_SWITCH_MESSAGES, reason) ? VOICE_SWITCH_MESSAGES[reason] : void 0;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
// dist/session-serial-queue.js
|
|
31
|
+
var SessionSerialQueueCancellationError = class extends Error {
|
|
32
|
+
sessionId;
|
|
33
|
+
generation;
|
|
34
|
+
code = "SESSION_SERIAL_QUEUE_CANCELLED";
|
|
35
|
+
constructor(sessionId, generation) {
|
|
36
|
+
super(`session serial queue cancelled (sessionId=${sessionId}, generation=${generation})`);
|
|
37
|
+
this.sessionId = sessionId;
|
|
38
|
+
this.generation = generation;
|
|
39
|
+
this.name = "SessionSerialQueueCancellationError";
|
|
40
|
+
}
|
|
41
|
+
};
|
|
42
|
+
var SessionSerialQueue = class {
|
|
43
|
+
sessions = /* @__PURE__ */ new Map();
|
|
44
|
+
/** Monotonic token source — never reused across clear/enqueue cycles. */
|
|
45
|
+
nextGeneration = 1;
|
|
46
|
+
/**
|
|
47
|
+
* Enqueue work for `sessionId`. Returns a promise that settles when this
|
|
48
|
+
* task finishes, is skipped as stale, or is cancelled by {@link clear}.
|
|
49
|
+
* Fire-and-forget callers may ignore the return value (compat).
|
|
50
|
+
*/
|
|
51
|
+
enqueue(sessionId, task) {
|
|
52
|
+
const state = this.ensureState(sessionId);
|
|
53
|
+
const captured = state;
|
|
54
|
+
const generation = captured.generation;
|
|
55
|
+
captured.pending += 1;
|
|
56
|
+
const previous = captured.tail;
|
|
57
|
+
let taskAbort = null;
|
|
58
|
+
const settled = previous.catch(() => void 0).then(async () => {
|
|
59
|
+
if (this.sessions.get(sessionId) !== captured) {
|
|
60
|
+
return "cancelled";
|
|
61
|
+
}
|
|
62
|
+
const abort = new AbortController();
|
|
63
|
+
taskAbort = abort;
|
|
64
|
+
captured.abort = abort;
|
|
65
|
+
const context = {
|
|
66
|
+
sessionId,
|
|
67
|
+
generation,
|
|
68
|
+
signal: abort.signal
|
|
69
|
+
};
|
|
70
|
+
try {
|
|
71
|
+
await Promise.resolve(task(abort.signal, context));
|
|
72
|
+
if (this.sessions.get(sessionId) !== captured) {
|
|
73
|
+
return "cancelled";
|
|
74
|
+
}
|
|
75
|
+
return "completed";
|
|
76
|
+
} catch (error) {
|
|
77
|
+
if (abort.signal.aborted || this.sessions.get(sessionId) !== captured || error instanceof SessionSerialQueueCancellationError) {
|
|
78
|
+
return "cancelled";
|
|
79
|
+
}
|
|
80
|
+
return "failed";
|
|
81
|
+
} finally {
|
|
82
|
+
if (captured.abort === abort) {
|
|
83
|
+
captured.abort = null;
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
}).finally(() => {
|
|
87
|
+
captured.pending = Math.max(0, captured.pending - 1);
|
|
88
|
+
if (taskAbort && captured.abort === taskAbort) {
|
|
89
|
+
captured.abort = null;
|
|
90
|
+
}
|
|
91
|
+
});
|
|
92
|
+
captured.tail = settled;
|
|
93
|
+
return settled;
|
|
94
|
+
}
|
|
95
|
+
/**
|
|
96
|
+
* Invalidate queued + running work for `sessionId`. Aborts the live AbortSignal,
|
|
97
|
+
* drops the map entry, and leaves a fresh identity for the next enqueue.
|
|
98
|
+
* Old in-flight `finally` blocks only touch their captured state object.
|
|
99
|
+
*/
|
|
100
|
+
clear(sessionId) {
|
|
101
|
+
const old = this.sessions.get(sessionId);
|
|
102
|
+
if (!old)
|
|
103
|
+
return;
|
|
104
|
+
old.abort?.abort();
|
|
105
|
+
old.abort = null;
|
|
106
|
+
this.sessions.delete(sessionId);
|
|
107
|
+
}
|
|
108
|
+
clearAll() {
|
|
109
|
+
for (const sessionId of [...this.sessions.keys()]) {
|
|
110
|
+
this.clear(sessionId);
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
hasPending(sessionId) {
|
|
114
|
+
return (this.sessions.get(sessionId)?.pending ?? 0) > 0;
|
|
115
|
+
}
|
|
116
|
+
/** Live generation token for a session, or `undefined` when cleared. */
|
|
117
|
+
generationOf(sessionId) {
|
|
118
|
+
return this.sessions.get(sessionId)?.generation;
|
|
119
|
+
}
|
|
120
|
+
/** True when `generation` is the live map entry for `sessionId`. */
|
|
121
|
+
isCurrentGeneration(sessionId, generation) {
|
|
122
|
+
return this.sessions.get(sessionId)?.generation === generation;
|
|
123
|
+
}
|
|
124
|
+
/**
|
|
125
|
+
* True when a queue row exists for the session (registered since first
|
|
126
|
+
* enqueue, until {@link clear}). Not the same as {@link hasPending}.
|
|
127
|
+
*/
|
|
128
|
+
isLive(sessionId) {
|
|
129
|
+
return this.sessions.has(sessionId);
|
|
130
|
+
}
|
|
131
|
+
/** Registered session rows (must not grow without matching `clear` calls). */
|
|
132
|
+
get activeSessionCount() {
|
|
133
|
+
return this.sessions.size;
|
|
134
|
+
}
|
|
135
|
+
ensureState(sessionId) {
|
|
136
|
+
const existing = this.sessions.get(sessionId);
|
|
137
|
+
if (existing)
|
|
138
|
+
return existing;
|
|
139
|
+
const created = {
|
|
140
|
+
generation: this.nextGeneration++,
|
|
141
|
+
tail: Promise.resolve(),
|
|
142
|
+
abort: null,
|
|
143
|
+
pending: 0
|
|
144
|
+
};
|
|
145
|
+
this.sessions.set(sessionId, created);
|
|
146
|
+
return created;
|
|
147
|
+
}
|
|
148
|
+
};
|
|
149
|
+
|
|
150
|
+
// dist/runtime.js
|
|
151
|
+
var SESSION_START_INIT_DELAY_ENABLED_ENV = "AGENT_SESSION_START_INIT_DELAY_ENABLED";
|
|
152
|
+
var SESSION_START_INIT_DELAY_MS_ENV = "AGENT_SESSION_START_INIT_DELAY_MS";
|
|
153
|
+
var DEFAULT_SESSION_START_INIT_DELAY_MS = 500;
|
|
154
|
+
function isSpeakResultMessage(value) {
|
|
155
|
+
if (!value || typeof value !== "object")
|
|
156
|
+
return false;
|
|
157
|
+
const msg = value;
|
|
158
|
+
return msg.type === "speak_result" && typeof msg.requestId === "string";
|
|
159
|
+
}
|
|
160
|
+
function isBargeInControlAckMessage(value) {
|
|
161
|
+
if (!value || typeof value !== "object")
|
|
162
|
+
return false;
|
|
163
|
+
const msg = value;
|
|
164
|
+
return msg.type === "barge_in_control_ack" && typeof msg.requestId === "string";
|
|
165
|
+
}
|
|
166
|
+
function isSessionTimeLimitControlAckMessage(value) {
|
|
167
|
+
if (!value || typeof value !== "object")
|
|
168
|
+
return false;
|
|
169
|
+
const msg = value;
|
|
170
|
+
return msg.type === "session_time_limit_control_ack" && typeof msg.requestId === "string";
|
|
171
|
+
}
|
|
172
|
+
function isPlayAckMessage(value) {
|
|
173
|
+
if (!value || typeof value !== "object")
|
|
174
|
+
return false;
|
|
175
|
+
const msg = value;
|
|
176
|
+
return msg.type === "play_ack" && typeof msg.requestId === "string";
|
|
177
|
+
}
|
|
178
|
+
function isPlayStatusAckMessage(value) {
|
|
179
|
+
if (!value || typeof value !== "object")
|
|
180
|
+
return false;
|
|
181
|
+
const msg = value;
|
|
182
|
+
return msg.type === "play_status_ack" && typeof msg.requestId === "string";
|
|
183
|
+
}
|
|
184
|
+
function isPlayStopAckMessage(value) {
|
|
185
|
+
if (!value || typeof value !== "object")
|
|
186
|
+
return false;
|
|
187
|
+
const msg = value;
|
|
188
|
+
return msg.type === "play_stop_ack" && typeof msg.requestId === "string";
|
|
189
|
+
}
|
|
190
|
+
function isPlayPoseAckMessage(value) {
|
|
191
|
+
if (!value || typeof value !== "object")
|
|
192
|
+
return false;
|
|
193
|
+
const msg = value;
|
|
194
|
+
return msg.type === "play_pose_ack" && typeof msg.requestId === "string";
|
|
195
|
+
}
|
|
196
|
+
function isRecordingControlAckMessage(value) {
|
|
197
|
+
if (!value || typeof value !== "object")
|
|
198
|
+
return false;
|
|
199
|
+
const msg = value;
|
|
200
|
+
return msg.type === "recording_control_ack" && typeof msg.requestId === "string";
|
|
201
|
+
}
|
|
202
|
+
function isConversationHistoryControlAckMessage(value) {
|
|
203
|
+
if (!value || typeof value !== "object")
|
|
204
|
+
return false;
|
|
205
|
+
const msg = value;
|
|
206
|
+
return msg.type === "conversation_history_control_ack" && typeof msg.requestId === "string";
|
|
207
|
+
}
|
|
208
|
+
function isUserHistoryResponseMessage(value) {
|
|
209
|
+
if (!value || typeof value !== "object")
|
|
210
|
+
return false;
|
|
211
|
+
const msg = value;
|
|
212
|
+
return msg.type === "user_history_response" && typeof msg.requestId === "string";
|
|
213
|
+
}
|
|
214
|
+
function isMixControlAckMessage(value) {
|
|
215
|
+
if (!value || typeof value !== "object")
|
|
216
|
+
return false;
|
|
217
|
+
const msg = value;
|
|
218
|
+
return msg.type === "mix_control_ack" && typeof msg.requestId === "string";
|
|
219
|
+
}
|
|
220
|
+
function isSttControlAckMessage(value) {
|
|
221
|
+
if (!value || typeof value !== "object")
|
|
222
|
+
return false;
|
|
223
|
+
const msg = value;
|
|
224
|
+
return msg.type === "stt_control_ack" && typeof msg.requestId === "string";
|
|
225
|
+
}
|
|
226
|
+
function isVoiceLanguageControlAckMessage(value) {
|
|
227
|
+
if (!value || typeof value !== "object")
|
|
228
|
+
return false;
|
|
229
|
+
const msg = value;
|
|
230
|
+
return msg.type === "voice_language_control_ack" && typeof msg.requestId === "string";
|
|
231
|
+
}
|
|
232
|
+
function isVoiceLanguagePrepareResultMessage(value) {
|
|
233
|
+
if (!value || typeof value !== "object")
|
|
234
|
+
return false;
|
|
235
|
+
const msg = value;
|
|
236
|
+
return msg.type === "voice_language_prepare_result" && typeof msg.requestId === "string";
|
|
237
|
+
}
|
|
238
|
+
function isSetSpeakerGateResultMessage(value) {
|
|
239
|
+
if (!value || typeof value !== "object")
|
|
240
|
+
return false;
|
|
241
|
+
const msg = value;
|
|
242
|
+
return msg.type === "setSpeakerGateResult" && typeof msg.requestId === "string";
|
|
243
|
+
}
|
|
244
|
+
function isResetSpeakerEnrollmentResultMessage(value) {
|
|
245
|
+
if (!value || typeof value !== "object")
|
|
246
|
+
return false;
|
|
247
|
+
const msg = value;
|
|
248
|
+
return msg.type === "resetSpeakerEnrollmentResult" && typeof msg.requestId === "string";
|
|
249
|
+
}
|
|
250
|
+
function isVoiceReplayLastResultMessage(value) {
|
|
251
|
+
if (!value || typeof value !== "object")
|
|
252
|
+
return false;
|
|
253
|
+
const msg = value;
|
|
254
|
+
return msg.type === "voice_replay_last_result" && typeof msg.requestId === "string";
|
|
255
|
+
}
|
|
256
|
+
function isWebhookMessage(value) {
|
|
257
|
+
if (!value || typeof value !== "object")
|
|
258
|
+
return false;
|
|
259
|
+
const msg = value;
|
|
260
|
+
return msg.type === "webhook" && typeof msg.eventId === "string" && typeof msg.projectId === "string";
|
|
261
|
+
}
|
|
262
|
+
function coerceInboundBinary(value) {
|
|
263
|
+
if (!value)
|
|
264
|
+
return null;
|
|
265
|
+
if (Buffer.isBuffer(value))
|
|
266
|
+
return value;
|
|
267
|
+
if (value instanceof Uint8Array) {
|
|
268
|
+
return Buffer.from(value.buffer, value.byteOffset, value.byteLength);
|
|
269
|
+
}
|
|
270
|
+
if (value instanceof ArrayBuffer)
|
|
271
|
+
return Buffer.from(value);
|
|
272
|
+
if (ArrayBuffer.isView(value)) {
|
|
273
|
+
return Buffer.from(value.buffer, value.byteOffset, value.byteLength);
|
|
274
|
+
}
|
|
275
|
+
if (typeof value === "object") {
|
|
276
|
+
const maybeBufferLike = value;
|
|
277
|
+
if (maybeBufferLike.type === "Buffer" && Array.isArray(maybeBufferLike.data)) {
|
|
278
|
+
return Buffer.from(maybeBufferLike.data);
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
return null;
|
|
282
|
+
}
|
|
283
|
+
function normalizeWebhookHeaders(value) {
|
|
284
|
+
if (!value || typeof value !== "object")
|
|
285
|
+
return {};
|
|
286
|
+
const out = {};
|
|
287
|
+
for (const [key, raw] of Object.entries(value)) {
|
|
288
|
+
if (typeof raw === "string") {
|
|
289
|
+
out[key] = raw;
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
return out;
|
|
293
|
+
}
|
|
294
|
+
function isParentMessage(value) {
|
|
295
|
+
if (!value || typeof value !== "object")
|
|
296
|
+
return false;
|
|
297
|
+
const msg = value;
|
|
298
|
+
return msg.type === "session_start" || msg.type === "speech_event" || msg.type === "session_end" || msg.type === "data_channel_message" || msg.type === "data_channel_binary" || msg.type === "idle_timeout" || msg.type === "session_time_limit" || msg.type === "session_time_limit_control_ack" || msg.type === "recording_control_ack" || msg.type === "conversation_history_control_ack" || msg.type === "user_identified" || msg.type === "user_history_response" || msg.type === "play_ack" || msg.type === "play_status_ack" || msg.type === "play_stop_ack" || msg.type === "play_pose_ack" || msg.type === "mix_control_ack" || msg.type === "stt_control_ack" || msg.type === "voice_language_control_ack" || msg.type === "voice_language_prepare_result" || msg.type === "voice_replay_last_result" || msg.type === "setSpeakerGateResult" || msg.type === "resetSpeakerEnrollmentResult" || msg.type === "speak_result" || msg.type === "barge_in_control_ack" || msg.type === "agent_interrupted" || msg.type === "webhook";
|
|
299
|
+
}
|
|
300
|
+
function isSessionScopedParentMessage(value) {
|
|
301
|
+
return isParentMessage(value) && !isWebhookMessage(value);
|
|
302
|
+
}
|
|
303
|
+
function parseDataChannelPayload(raw) {
|
|
304
|
+
try {
|
|
305
|
+
return JSON.parse(raw);
|
|
306
|
+
} catch {
|
|
307
|
+
return raw;
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
var peerEnvBySessionId = /* @__PURE__ */ new Map();
|
|
311
|
+
var recordingAvailableBySessionId = /* @__PURE__ */ new Map();
|
|
312
|
+
var conversationHistoryAvailableBySessionId = /* @__PURE__ */ new Map();
|
|
313
|
+
var endUserBySessionId = /* @__PURE__ */ new Map();
|
|
314
|
+
var mixAvailableBySessionId = /* @__PURE__ */ new Map();
|
|
315
|
+
var voiceLanguageSwitchAvailableBySessionId = /* @__PURE__ */ new Map();
|
|
316
|
+
var lastVoiceLanguageBySessionId = /* @__PURE__ */ new Map();
|
|
317
|
+
var speakerGateBySessionId = /* @__PURE__ */ new Map();
|
|
318
|
+
var SPEAKER_GATE_ACK_TIMEOUT_MS = 1e4;
|
|
319
|
+
var pendingSpeakerGateAcks = /* @__PURE__ */ new Map();
|
|
320
|
+
var pendingSpeakerResets = /* @__PURE__ */ new Map();
|
|
321
|
+
var ttsPoseAvailableBySessionId = /* @__PURE__ */ new Map();
|
|
322
|
+
var speakControlAvailableBySessionId = /* @__PURE__ */ new Map();
|
|
323
|
+
var chatReplyRecordAvailableBySessionId = /* @__PURE__ */ new Map();
|
|
324
|
+
var sessionTimeLimitAvailableBySessionId = /* @__PURE__ */ new Map();
|
|
325
|
+
var sessionTimeLimitWarnedSessionIds = /* @__PURE__ */ new Set();
|
|
326
|
+
var speakControlWarnedSessionIds = /* @__PURE__ */ new Set();
|
|
327
|
+
var endedSessionIds = /* @__PURE__ */ new Set();
|
|
328
|
+
var SPEAK_RESULT_SAFETY_TIMEOUT_MS = 6e5;
|
|
329
|
+
var pendingSpeakResults = /* @__PURE__ */ new Map();
|
|
330
|
+
var pendingBargeInAcks = /* @__PURE__ */ new Map();
|
|
331
|
+
var pendingSessionTimeLimitAcks = /* @__PURE__ */ new Map();
|
|
332
|
+
function handleSessionTimeLimitControlAck(message) {
|
|
333
|
+
const pending = pendingSessionTimeLimitAcks.get(message.requestId);
|
|
334
|
+
if (!pending)
|
|
335
|
+
return;
|
|
336
|
+
clearTimeout(pending.timer);
|
|
337
|
+
pendingSessionTimeLimitAcks.delete(message.requestId);
|
|
338
|
+
if (message.ok && message.state) {
|
|
339
|
+
pending.resolve({ ok: true, state: message.state });
|
|
340
|
+
return;
|
|
341
|
+
}
|
|
342
|
+
pending.resolve({
|
|
343
|
+
ok: false,
|
|
344
|
+
error: message.error ?? "unknown_session"
|
|
345
|
+
});
|
|
346
|
+
}
|
|
347
|
+
function handleSpeakResult(message) {
|
|
348
|
+
const pending = pendingSpeakResults.get(message.requestId);
|
|
349
|
+
if (!pending)
|
|
350
|
+
return;
|
|
351
|
+
clearTimeout(pending.timer);
|
|
352
|
+
pendingSpeakResults.delete(message.requestId);
|
|
353
|
+
pending.resolve({
|
|
354
|
+
requestId: message.requestId,
|
|
355
|
+
...message.turnId !== void 0 ? { turnId: message.turnId } : {},
|
|
356
|
+
status: message.status,
|
|
357
|
+
playedMs: message.playedMs,
|
|
358
|
+
...message.synthesizedMs !== void 0 ? { synthesizedMs: message.synthesizedMs } : {},
|
|
359
|
+
...message.errorCode !== void 0 ? { errorCode: message.errorCode } : {}
|
|
360
|
+
});
|
|
361
|
+
}
|
|
362
|
+
function handleBargeInControlAck(message) {
|
|
363
|
+
const pending = pendingBargeInAcks.get(message.requestId);
|
|
364
|
+
if (!pending)
|
|
365
|
+
return;
|
|
366
|
+
clearTimeout(pending.timer);
|
|
367
|
+
pendingBargeInAcks.delete(message.requestId);
|
|
368
|
+
pending.resolve({
|
|
369
|
+
ok: message.ok,
|
|
370
|
+
...message.reason ? { reason: message.reason } : {}
|
|
371
|
+
});
|
|
372
|
+
}
|
|
373
|
+
function clearPendingSpeakForSession(sessionId, errorCode) {
|
|
374
|
+
for (const [requestId, pending] of pendingSpeakResults) {
|
|
375
|
+
if (pending.sessionId !== sessionId)
|
|
376
|
+
continue;
|
|
377
|
+
clearTimeout(pending.timer);
|
|
378
|
+
pendingSpeakResults.delete(requestId);
|
|
379
|
+
pending.resolve({
|
|
380
|
+
requestId,
|
|
381
|
+
...pending.turnId !== void 0 ? { turnId: pending.turnId } : {},
|
|
382
|
+
status: "cancelled",
|
|
383
|
+
playedMs: 0,
|
|
384
|
+
errorCode
|
|
385
|
+
});
|
|
386
|
+
}
|
|
387
|
+
for (const [requestId, pending] of pendingBargeInAcks) {
|
|
388
|
+
if (pending.sessionId !== sessionId)
|
|
389
|
+
continue;
|
|
390
|
+
clearTimeout(pending.timer);
|
|
391
|
+
pendingBargeInAcks.delete(requestId);
|
|
392
|
+
pending.resolve({ ok: false, reason: "session_ended" });
|
|
393
|
+
}
|
|
394
|
+
for (const [requestId, pending] of pendingSessionTimeLimitAcks) {
|
|
395
|
+
if (pending.sessionId !== sessionId)
|
|
396
|
+
continue;
|
|
397
|
+
clearTimeout(pending.timer);
|
|
398
|
+
pendingSessionTimeLimitAcks.delete(requestId);
|
|
399
|
+
pending.resolve({ ok: false, error: "session_closing" });
|
|
400
|
+
}
|
|
401
|
+
speakControlWarnedSessionIds.delete(sessionId);
|
|
402
|
+
sessionTimeLimitWarnedSessionIds.delete(sessionId);
|
|
403
|
+
}
|
|
404
|
+
var PLAY_BYTES_MAX_DECODED_LENGTH = 64 * 1024;
|
|
405
|
+
var pendingRecordingAcks = /* @__PURE__ */ new Map();
|
|
406
|
+
var pendingConversationHistoryAcks = /* @__PURE__ */ new Map();
|
|
407
|
+
var pendingUserHistory = /* @__PURE__ */ new Map();
|
|
408
|
+
var pendingPlayAcks = /* @__PURE__ */ new Map();
|
|
409
|
+
var pendingPlayStatusAcks = /* @__PURE__ */ new Map();
|
|
410
|
+
var pendingPlayStopAcks = /* @__PURE__ */ new Map();
|
|
411
|
+
var pendingPlayPoseAcks = /* @__PURE__ */ new Map();
|
|
412
|
+
var pendingMixAcks = /* @__PURE__ */ new Map();
|
|
413
|
+
var pendingSttAcks = /* @__PURE__ */ new Map();
|
|
414
|
+
var pendingVoiceLanguageAcks = /* @__PURE__ */ new Map();
|
|
415
|
+
var pendingVoiceLanguagePrepares = /* @__PURE__ */ new Map();
|
|
416
|
+
var pendingVoiceReplays = /* @__PURE__ */ new Map();
|
|
417
|
+
var voiceLanguageSwitchSettingsBySessionId = /* @__PURE__ */ new Map();
|
|
418
|
+
function handleRecordingControlAck(message) {
|
|
419
|
+
const pending = pendingRecordingAcks.get(message.requestId);
|
|
420
|
+
if (!pending)
|
|
421
|
+
return;
|
|
422
|
+
clearTimeout(pending.timer);
|
|
423
|
+
pendingRecordingAcks.delete(message.requestId);
|
|
424
|
+
pending.resolve({
|
|
425
|
+
ok: message.ok,
|
|
426
|
+
reason: message.reason,
|
|
427
|
+
requestId: message.requestId
|
|
428
|
+
});
|
|
429
|
+
}
|
|
430
|
+
function handleConversationHistoryControlAck(message) {
|
|
431
|
+
const pending = pendingConversationHistoryAcks.get(message.requestId);
|
|
432
|
+
if (!pending)
|
|
433
|
+
return;
|
|
434
|
+
clearTimeout(pending.timer);
|
|
435
|
+
pendingConversationHistoryAcks.delete(message.requestId);
|
|
436
|
+
pending.resolve({
|
|
437
|
+
ok: message.ok,
|
|
438
|
+
reason: message.reason,
|
|
439
|
+
requestId: message.requestId
|
|
440
|
+
});
|
|
441
|
+
}
|
|
442
|
+
function handleUserHistoryResponse(message) {
|
|
443
|
+
const pending = pendingUserHistory.get(message.requestId);
|
|
444
|
+
if (!pending)
|
|
445
|
+
return;
|
|
446
|
+
clearTimeout(pending.timer);
|
|
447
|
+
pendingUserHistory.delete(message.requestId);
|
|
448
|
+
pending.resolve({
|
|
449
|
+
ok: message.ok,
|
|
450
|
+
...message.reason ? { reason: message.reason } : {},
|
|
451
|
+
conversations: Array.isArray(message.conversations) ? message.conversations : []
|
|
452
|
+
});
|
|
453
|
+
}
|
|
454
|
+
function clearPendingUserHistoryForSession(sessionId, reason) {
|
|
455
|
+
for (const [requestId, pending] of pendingUserHistory) {
|
|
456
|
+
if (pending.sessionId !== sessionId)
|
|
457
|
+
continue;
|
|
458
|
+
clearTimeout(pending.timer);
|
|
459
|
+
pendingUserHistory.delete(requestId);
|
|
460
|
+
pending.resolve({ ok: false, reason, conversations: [] });
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
function handlePlayAck(message) {
|
|
464
|
+
const pending = pendingPlayAcks.get(message.requestId);
|
|
465
|
+
if (!pending)
|
|
466
|
+
return;
|
|
467
|
+
clearTimeout(pending.timer);
|
|
468
|
+
pendingPlayAcks.delete(message.requestId);
|
|
469
|
+
pending.resolve({
|
|
470
|
+
ok: message.ok,
|
|
471
|
+
...message.playId ? { playId: message.playId } : {},
|
|
472
|
+
reason: message.reason,
|
|
473
|
+
requestId: message.requestId
|
|
474
|
+
});
|
|
475
|
+
}
|
|
476
|
+
function handlePlayStatusAck(message) {
|
|
477
|
+
const pending = pendingPlayStatusAcks.get(message.requestId);
|
|
478
|
+
if (!pending)
|
|
479
|
+
return;
|
|
480
|
+
clearTimeout(pending.timer);
|
|
481
|
+
pendingPlayStatusAcks.delete(message.requestId);
|
|
482
|
+
pending.resolve({
|
|
483
|
+
ok: message.ok,
|
|
484
|
+
playId: message.playId,
|
|
485
|
+
...message.status ? { status: message.status } : {},
|
|
486
|
+
reason: message.reason,
|
|
487
|
+
requestId: message.requestId
|
|
488
|
+
});
|
|
489
|
+
}
|
|
490
|
+
function handlePlayStopAck(message) {
|
|
491
|
+
const pending = pendingPlayStopAcks.get(message.requestId);
|
|
492
|
+
if (!pending)
|
|
493
|
+
return;
|
|
494
|
+
clearTimeout(pending.timer);
|
|
495
|
+
pendingPlayStopAcks.delete(message.requestId);
|
|
496
|
+
pending.resolve({
|
|
497
|
+
ok: message.ok,
|
|
498
|
+
playId: message.playId,
|
|
499
|
+
reason: message.reason,
|
|
500
|
+
requestId: message.requestId
|
|
501
|
+
});
|
|
502
|
+
}
|
|
503
|
+
function handlePlayPoseAck(message) {
|
|
504
|
+
const pending = pendingPlayPoseAcks.get(message.requestId);
|
|
505
|
+
if (!pending)
|
|
506
|
+
return;
|
|
507
|
+
clearTimeout(pending.timer);
|
|
508
|
+
pendingPlayPoseAcks.delete(message.requestId);
|
|
509
|
+
pending.resolve({
|
|
510
|
+
ok: message.ok,
|
|
511
|
+
playId: message.playId,
|
|
512
|
+
reason: message.reason,
|
|
513
|
+
requestId: message.requestId
|
|
514
|
+
});
|
|
515
|
+
}
|
|
516
|
+
function handleMixControlAck(message) {
|
|
517
|
+
const pending = pendingMixAcks.get(message.requestId);
|
|
518
|
+
if (!pending)
|
|
519
|
+
return;
|
|
520
|
+
clearTimeout(pending.timer);
|
|
521
|
+
pendingMixAcks.delete(message.requestId);
|
|
522
|
+
pending.resolve({
|
|
523
|
+
ok: message.ok,
|
|
524
|
+
reason: message.reason,
|
|
525
|
+
requestId: message.requestId,
|
|
526
|
+
...message.statuses ? { statuses: message.statuses } : {}
|
|
527
|
+
});
|
|
528
|
+
}
|
|
529
|
+
function handleSttControlAck(message) {
|
|
530
|
+
const pending = pendingSttAcks.get(message.requestId);
|
|
531
|
+
if (!pending)
|
|
532
|
+
return;
|
|
533
|
+
clearTimeout(pending.timer);
|
|
534
|
+
pendingSttAcks.delete(message.requestId);
|
|
535
|
+
pending.resolve({
|
|
536
|
+
ok: message.ok,
|
|
537
|
+
reason: message.reason,
|
|
538
|
+
requestId: message.requestId
|
|
539
|
+
});
|
|
540
|
+
}
|
|
541
|
+
function handleVoiceLanguageControlAck(message) {
|
|
542
|
+
const pending = pendingVoiceLanguageAcks.get(message.requestId);
|
|
543
|
+
if (!pending)
|
|
544
|
+
return;
|
|
545
|
+
clearTimeout(pending.timer);
|
|
546
|
+
pendingVoiceLanguageAcks.delete(message.requestId);
|
|
547
|
+
if (message.ok && message.language?.trim()) {
|
|
548
|
+
lastVoiceLanguageBySessionId.set(message.sessionId, message.language.trim());
|
|
549
|
+
}
|
|
550
|
+
const text = message.message ?? (message.ok ? void 0 : localVoiceSwitchMessage(message.reason));
|
|
551
|
+
pending.resolve({
|
|
552
|
+
ok: message.ok,
|
|
553
|
+
reason: message.reason,
|
|
554
|
+
...text ? { message: text } : {},
|
|
555
|
+
requestId: message.requestId,
|
|
556
|
+
...message.language ? { language: message.language } : {},
|
|
557
|
+
...message.voice ? { voice: message.voice } : {},
|
|
558
|
+
...message.stt ? { stt: message.stt } : {},
|
|
559
|
+
...message.scope ? { scope: message.scope } : {},
|
|
560
|
+
...message.sttProvider ? { sttProvider: toPublicProviderId(message.sttProvider) } : {},
|
|
561
|
+
...message.ttsProvider ? { ttsProvider: toPublicProviderId(message.ttsProvider) } : {}
|
|
562
|
+
});
|
|
563
|
+
}
|
|
564
|
+
function handleVoiceLanguagePrepareResult(message) {
|
|
565
|
+
const pending = pendingVoiceLanguagePrepares.get(message.requestId);
|
|
566
|
+
if (!pending)
|
|
567
|
+
return;
|
|
568
|
+
clearTimeout(pending.timer);
|
|
569
|
+
pendingVoiceLanguagePrepares.delete(message.requestId);
|
|
570
|
+
const text = message.message ?? (message.ok && message.ready ? void 0 : localVoiceSwitchMessage(message.reason));
|
|
571
|
+
pending.resolve({
|
|
572
|
+
ok: message.ok,
|
|
573
|
+
ready: message.ready,
|
|
574
|
+
reason: message.reason,
|
|
575
|
+
...text ? { message: text } : {},
|
|
576
|
+
...message.language ? { language: message.language } : {}
|
|
577
|
+
});
|
|
578
|
+
}
|
|
579
|
+
function handleSetSpeakerGateResult(message) {
|
|
580
|
+
const pending = pendingSpeakerGateAcks.get(message.requestId);
|
|
581
|
+
if (!pending)
|
|
582
|
+
return;
|
|
583
|
+
clearTimeout(pending.timer);
|
|
584
|
+
pendingSpeakerGateAcks.delete(message.requestId);
|
|
585
|
+
if (message.ok) {
|
|
586
|
+
speakerGateBySessionId.set(pending.sessionId, {
|
|
587
|
+
available: true,
|
|
588
|
+
mode: message.mode,
|
|
589
|
+
bargeIn: message.bargeIn
|
|
590
|
+
});
|
|
591
|
+
pending.resolve({
|
|
592
|
+
ok: true,
|
|
593
|
+
mode: message.mode,
|
|
594
|
+
bargeIn: message.bargeIn
|
|
595
|
+
});
|
|
596
|
+
return;
|
|
597
|
+
}
|
|
598
|
+
pending.resolve({ ok: false, reason: message.reason });
|
|
599
|
+
}
|
|
600
|
+
function handleResetSpeakerEnrollmentResult(message) {
|
|
601
|
+
const pending = pendingSpeakerResets.get(message.requestId);
|
|
602
|
+
if (!pending)
|
|
603
|
+
return;
|
|
604
|
+
clearTimeout(pending.timer);
|
|
605
|
+
pendingSpeakerResets.delete(message.requestId);
|
|
606
|
+
pending.resolve(message.ok ? { ok: true } : { ok: false, reason: message.reason });
|
|
607
|
+
}
|
|
608
|
+
function handleVoiceReplayLastResult(message) {
|
|
609
|
+
const pending = pendingVoiceReplays.get(message.requestId);
|
|
610
|
+
if (!pending)
|
|
611
|
+
return;
|
|
612
|
+
clearTimeout(pending.timer);
|
|
613
|
+
pendingVoiceReplays.delete(message.requestId);
|
|
614
|
+
pending.resolve({ ok: message.ok, reason: message.reason });
|
|
615
|
+
}
|
|
616
|
+
function clearPendingRecordingAcksForSession(sessionId, reason) {
|
|
617
|
+
for (const [requestId, pending] of pendingRecordingAcks) {
|
|
618
|
+
if (pending.sessionId !== sessionId)
|
|
619
|
+
continue;
|
|
620
|
+
clearTimeout(pending.timer);
|
|
621
|
+
pendingRecordingAcks.delete(requestId);
|
|
622
|
+
pending.resolve({ ok: false, reason, requestId });
|
|
623
|
+
}
|
|
624
|
+
}
|
|
625
|
+
function clearPendingConversationHistoryAcksForSession(sessionId, reason) {
|
|
626
|
+
for (const [requestId, pending] of pendingConversationHistoryAcks) {
|
|
627
|
+
if (pending.sessionId !== sessionId)
|
|
628
|
+
continue;
|
|
629
|
+
clearTimeout(pending.timer);
|
|
630
|
+
pendingConversationHistoryAcks.delete(requestId);
|
|
631
|
+
pending.resolve({ ok: false, reason, requestId });
|
|
632
|
+
}
|
|
633
|
+
}
|
|
634
|
+
function isVoicethereAgentChild() {
|
|
635
|
+
return typeof process.send === "function" && process.connected !== false && typeof process.env.__CHILD_BUNDLE_PATH__ === "string" && process.env.__CHILD_BUNDLE_PATH__.trim().length > 0;
|
|
636
|
+
}
|
|
637
|
+
var sessionExecutionContext = new AsyncLocalStorage();
|
|
638
|
+
var agentLogSessionContext = new AsyncLocalStorage();
|
|
639
|
+
var CURRENT_SESSION_ID_GETTER_KEY = Symbol.for("voicethere.agent.currentSessionId");
|
|
640
|
+
function currentHandlerSessionId() {
|
|
641
|
+
const id = sessionExecutionContext.getStore()?.sessionId ?? agentLogSessionContext.getStore();
|
|
642
|
+
return id ? id : void 0;
|
|
643
|
+
}
|
|
644
|
+
var previousSessionIdGetter;
|
|
645
|
+
function stringOrUndefined(value) {
|
|
646
|
+
return typeof value === "string" && value ? value : void 0;
|
|
647
|
+
}
|
|
648
|
+
function currentSessionIdGetter() {
|
|
649
|
+
const own = currentHandlerSessionId();
|
|
650
|
+
if (own)
|
|
651
|
+
return own;
|
|
652
|
+
try {
|
|
653
|
+
return stringOrUndefined(previousSessionIdGetter?.());
|
|
654
|
+
} catch {
|
|
655
|
+
return void 0;
|
|
656
|
+
}
|
|
657
|
+
}
|
|
658
|
+
function installCurrentSessionIdGetter() {
|
|
659
|
+
const g = globalThis;
|
|
660
|
+
const previous = g[CURRENT_SESSION_ID_GETTER_KEY];
|
|
661
|
+
if (previous === currentSessionIdGetter)
|
|
662
|
+
return;
|
|
663
|
+
g[CURRENT_SESSION_ID_GETTER_KEY] = currentSessionIdGetter;
|
|
664
|
+
previousSessionIdGetter = typeof previous === "function" ? previous : void 0;
|
|
665
|
+
}
|
|
666
|
+
installCurrentSessionIdGetter();
|
|
667
|
+
var inboundQueueAuthority = null;
|
|
668
|
+
var childUnhandledRejectionGuardInstalled = false;
|
|
669
|
+
function normalizeRejectionReason(reason) {
|
|
670
|
+
return reason instanceof Error ? reason : new Error(String(reason));
|
|
671
|
+
}
|
|
672
|
+
function installChildUnhandledRejectionGuard() {
|
|
673
|
+
if (childUnhandledRejectionGuardInstalled) {
|
|
674
|
+
return;
|
|
675
|
+
}
|
|
676
|
+
childUnhandledRejectionGuardInstalled = true;
|
|
677
|
+
process.on("unhandledRejection", (reason) => {
|
|
678
|
+
const err = normalizeRejectionReason(reason);
|
|
679
|
+
const store = sessionExecutionContext.getStore();
|
|
680
|
+
const sessionId = store?.sessionId ?? agentLogSessionContext.getStore() ?? "";
|
|
681
|
+
if (!allowOutboundForSession(sessionId || void 0)) {
|
|
682
|
+
return;
|
|
683
|
+
}
|
|
684
|
+
agentLog("error", `unhandledRejection: ${err.message}`, sessionId || void 0);
|
|
685
|
+
sendParentMessage({
|
|
686
|
+
type: "agent_error",
|
|
687
|
+
sessionId,
|
|
688
|
+
message: err.message,
|
|
689
|
+
stack: err.stack
|
|
690
|
+
});
|
|
691
|
+
});
|
|
692
|
+
}
|
|
693
|
+
function allowOutboundForSession(sessionId) {
|
|
694
|
+
if (!sessionId) {
|
|
695
|
+
return true;
|
|
696
|
+
}
|
|
697
|
+
const store = sessionExecutionContext.getStore();
|
|
698
|
+
const queue = inboundQueueAuthority;
|
|
699
|
+
if (store && store.sessionId === sessionId) {
|
|
700
|
+
if (!queue)
|
|
701
|
+
return !endedSessionIds.has(sessionId);
|
|
702
|
+
return queue.isCurrentGeneration(sessionId, store.generation);
|
|
703
|
+
}
|
|
704
|
+
if (endedSessionIds.has(sessionId))
|
|
705
|
+
return false;
|
|
706
|
+
if (!queue)
|
|
707
|
+
return true;
|
|
708
|
+
return queue.isLive(sessionId);
|
|
709
|
+
}
|
|
710
|
+
function sendParentMessage(message) {
|
|
711
|
+
const msgType = message && typeof message === "object" && "type" in message ? message.type : void 0;
|
|
712
|
+
if (msgType === "mix_control" || msgType === "stt_control" || msgType === "voice_language_control" || msgType === "voice_language_prepare" || msgType === "voice_replay_last" || msgType === "setSpeakerGate" || msgType === "resetSpeakerEnrollment") {
|
|
713
|
+
process.send?.(message);
|
|
714
|
+
return;
|
|
715
|
+
}
|
|
716
|
+
if (msgType === "play" || msgType === "play_status" || msgType === "play_stop" || msgType === "play_pose") {
|
|
717
|
+
process.send?.(message);
|
|
718
|
+
return;
|
|
719
|
+
}
|
|
720
|
+
const sessionId = message && typeof message === "object" && "sessionId" in message && typeof message.sessionId === "string" ? message.sessionId : void 0;
|
|
721
|
+
if (!allowOutboundForSession(sessionId))
|
|
722
|
+
return;
|
|
723
|
+
process.send?.(message);
|
|
724
|
+
}
|
|
725
|
+
function parseBooleanEnv(value, defaultValue) {
|
|
726
|
+
if (value === void 0)
|
|
727
|
+
return defaultValue;
|
|
728
|
+
const normalized = value.trim().toLowerCase();
|
|
729
|
+
if (normalized === "")
|
|
730
|
+
return defaultValue;
|
|
731
|
+
if (["0", "false", "off", "no"].includes(normalized))
|
|
732
|
+
return false;
|
|
733
|
+
if (["1", "true", "on", "yes"].includes(normalized))
|
|
734
|
+
return true;
|
|
735
|
+
return defaultValue;
|
|
736
|
+
}
|
|
737
|
+
function parseNonNegativeIntegerEnv(value, defaultValue) {
|
|
738
|
+
if (value === void 0)
|
|
739
|
+
return defaultValue;
|
|
740
|
+
const parsed = Number(value);
|
|
741
|
+
if (!Number.isFinite(parsed) || parsed < 0)
|
|
742
|
+
return defaultValue;
|
|
743
|
+
return Math.floor(parsed);
|
|
744
|
+
}
|
|
745
|
+
function resolveSessionStartInitDelayMs() {
|
|
746
|
+
const enabled = parseBooleanEnv(process.env[SESSION_START_INIT_DELAY_ENABLED_ENV], true);
|
|
747
|
+
if (!enabled)
|
|
748
|
+
return 0;
|
|
749
|
+
return parseNonNegativeIntegerEnv(process.env[SESSION_START_INIT_DELAY_MS_ENV], DEFAULT_SESSION_START_INIT_DELAY_MS);
|
|
750
|
+
}
|
|
751
|
+
async function handleWebhookMessage(message, handlers) {
|
|
752
|
+
if (!handlers.onWebhook)
|
|
753
|
+
return;
|
|
754
|
+
const body = coerceInboundBinary(message.body);
|
|
755
|
+
if (!body) {
|
|
756
|
+
agentLog("warn", "webhook ipc dropped: body is not binary");
|
|
757
|
+
return;
|
|
758
|
+
}
|
|
759
|
+
const ctx = {
|
|
760
|
+
eventId: message.eventId,
|
|
761
|
+
projectId: message.projectId,
|
|
762
|
+
method: typeof message.method === "string" ? message.method : "POST",
|
|
763
|
+
path: typeof message.path === "string" ? message.path : "",
|
|
764
|
+
headers: normalizeWebhookHeaders(message.headers),
|
|
765
|
+
body,
|
|
766
|
+
contentType: typeof message.contentType === "string" ? message.contentType : null,
|
|
767
|
+
receivedAt: typeof message.receivedAt === "string" ? message.receivedAt : "",
|
|
768
|
+
sessionIds: Array.isArray(message.sessionIds) ? message.sessionIds.filter((id) => typeof id === "string" && id.length > 0) : []
|
|
769
|
+
};
|
|
770
|
+
try {
|
|
771
|
+
const started = Date.now();
|
|
772
|
+
await handlers.onWebhook(ctx);
|
|
773
|
+
sendParentMessage({
|
|
774
|
+
type: "webhook_handled",
|
|
775
|
+
projectId: message.projectId,
|
|
776
|
+
eventId: message.eventId,
|
|
777
|
+
durationMs: Date.now() - started
|
|
778
|
+
});
|
|
779
|
+
} catch (error) {
|
|
780
|
+
const err = error instanceof Error ? error : new Error(String(error));
|
|
781
|
+
await runErrorHook(handlers, {
|
|
782
|
+
sessionId: "",
|
|
783
|
+
projectId: message.projectId,
|
|
784
|
+
env: process.env,
|
|
785
|
+
error: err
|
|
786
|
+
});
|
|
787
|
+
sendParentMessage({
|
|
788
|
+
type: "agent_error",
|
|
789
|
+
sessionId: "",
|
|
790
|
+
message: err.message,
|
|
791
|
+
stack: err.stack
|
|
792
|
+
});
|
|
793
|
+
}
|
|
794
|
+
}
|
|
795
|
+
function speakerGateOf(sessionId) {
|
|
796
|
+
const gate = speakerGateBySessionId.get(sessionId);
|
|
797
|
+
return gate?.available ? { speakerGate: gate } : {};
|
|
798
|
+
}
|
|
799
|
+
var SPEAKER_VERDICTS = ["caller", "other", "unknown"];
|
|
800
|
+
function speakerFieldsOf(event) {
|
|
801
|
+
const e = event;
|
|
802
|
+
return {
|
|
803
|
+
...typeof e.speaker === "string" && SPEAKER_VERDICTS.includes(e.speaker) ? { speaker: e.speaker } : {},
|
|
804
|
+
...typeof e.speakerUnknownReason === "string" ? { speakerUnknownReason: e.speakerUnknownReason } : {},
|
|
805
|
+
...typeof e.speakerCheckWindows === "number" ? { speakerCheckWindows: e.speakerCheckWindows } : {},
|
|
806
|
+
...typeof e.speakerRechecked === "boolean" ? { speakerRechecked: e.speakerRechecked } : {}
|
|
807
|
+
};
|
|
808
|
+
}
|
|
809
|
+
function resolveUserLanguageCode(event) {
|
|
810
|
+
const withLanguage = event;
|
|
811
|
+
const candidates = [withLanguage.language, event.text];
|
|
812
|
+
for (const value of candidates) {
|
|
813
|
+
if (typeof value === "string" && value.trim()) {
|
|
814
|
+
return value.trim();
|
|
815
|
+
}
|
|
816
|
+
}
|
|
817
|
+
return void 0;
|
|
818
|
+
}
|
|
819
|
+
async function handleParentMessage(message, handlers) {
|
|
820
|
+
switch (message.type) {
|
|
821
|
+
case "session_start":
|
|
822
|
+
endedSessionIds.delete(message.sessionId);
|
|
823
|
+
peerEnvBySessionId.set(message.sessionId, message.env);
|
|
824
|
+
recordingAvailableBySessionId.set(message.sessionId, message.recordingAvailable ?? false);
|
|
825
|
+
conversationHistoryAvailableBySessionId.set(message.sessionId, message.conversationHistoryAvailable ?? false);
|
|
826
|
+
const startUser = parseEndUserInfo(message.endUser) ?? parseEndUserEnv(message.env?.AGENT_END_USER);
|
|
827
|
+
if (startUser)
|
|
828
|
+
endUserBySessionId.set(message.sessionId, startUser);
|
|
829
|
+
else
|
|
830
|
+
endUserBySessionId.delete(message.sessionId);
|
|
831
|
+
mixAvailableBySessionId.set(message.sessionId, message.mixAvailable ?? false);
|
|
832
|
+
voiceLanguageSwitchAvailableBySessionId.set(message.sessionId, message.voiceLanguageSwitchAvailable ?? false);
|
|
833
|
+
ttsPoseAvailableBySessionId.set(message.sessionId, message.ttsPoseAvailable ?? false);
|
|
834
|
+
speakControlAvailableBySessionId.set(message.sessionId, message.speakControlAvailable ?? false);
|
|
835
|
+
chatReplyRecordAvailableBySessionId.set(message.sessionId, message.chatReplyRecordAvailable ?? false);
|
|
836
|
+
sessionTimeLimitAvailableBySessionId.set(message.sessionId, message.sessionTimeLimitAvailable ?? false);
|
|
837
|
+
speakerGateBySessionId.set(message.sessionId, message.speakerGate?.available === true ? message.speakerGate : { available: false });
|
|
838
|
+
if (message.voiceLanguageSwitch) {
|
|
839
|
+
voiceLanguageSwitchSettingsBySessionId.set(message.sessionId, message.voiceLanguageSwitch);
|
|
840
|
+
} else {
|
|
841
|
+
voiceLanguageSwitchSettingsBySessionId.delete(message.sessionId);
|
|
842
|
+
}
|
|
843
|
+
const sessionStartInitDelayMs = resolveSessionStartInitDelayMs();
|
|
844
|
+
if (sessionStartInitDelayMs > 0) {
|
|
845
|
+
await new Promise((resolve) => setTimeout(resolve, sessionStartInitDelayMs));
|
|
846
|
+
}
|
|
847
|
+
await (handlers.onClientJoin ?? handlers.onSessionStart)?.({
|
|
848
|
+
sessionId: message.sessionId,
|
|
849
|
+
env: message.env,
|
|
850
|
+
...startUser ? { user: startUser } : {},
|
|
851
|
+
recordingAvailable: message.recordingAvailable ?? false,
|
|
852
|
+
conversationHistoryAvailable: message.conversationHistoryAvailable ?? false,
|
|
853
|
+
mixAvailable: message.mixAvailable ?? false,
|
|
854
|
+
voiceLanguageSwitchAvailable: message.voiceLanguageSwitchAvailable ?? false,
|
|
855
|
+
...speakerGateOf(message.sessionId),
|
|
856
|
+
ttsPoseAvailable: message.ttsPoseAvailable ?? false,
|
|
857
|
+
speakControlAvailable: message.speakControlAvailable ?? false,
|
|
858
|
+
sessionTimeLimitAvailable: message.sessionTimeLimitAvailable ?? false
|
|
859
|
+
});
|
|
860
|
+
sendParentMessage({
|
|
861
|
+
type: "session_start_ack",
|
|
862
|
+
sessionId: message.sessionId
|
|
863
|
+
});
|
|
864
|
+
break;
|
|
865
|
+
case "user_identified": {
|
|
866
|
+
if (endedSessionIds.has(message.sessionId))
|
|
867
|
+
break;
|
|
868
|
+
const user = parseEndUserInfo(message.endUser);
|
|
869
|
+
if (!user)
|
|
870
|
+
break;
|
|
871
|
+
endUserBySessionId.set(message.sessionId, user);
|
|
872
|
+
await handlers.onUserIdentified?.({
|
|
873
|
+
sessionId: message.sessionId,
|
|
874
|
+
env: peerEnvBySessionId.get(message.sessionId) ?? {},
|
|
875
|
+
recordingAvailable: recordingAvailableBySessionId.get(message.sessionId) ?? false,
|
|
876
|
+
conversationHistoryAvailable: conversationHistoryAvailableBySessionId.get(message.sessionId) ?? false,
|
|
877
|
+
mixAvailable: mixAvailableBySessionId.get(message.sessionId) ?? false,
|
|
878
|
+
voiceLanguageSwitchAvailable: voiceLanguageSwitchAvailableBySessionId.get(message.sessionId) ?? false,
|
|
879
|
+
...speakerGateOf(message.sessionId),
|
|
880
|
+
ttsPoseAvailable: ttsPoseAvailableBySessionId.get(message.sessionId) ?? false,
|
|
881
|
+
speakControlAvailable: speakControlAvailableBySessionId.get(message.sessionId) ?? false,
|
|
882
|
+
sessionTimeLimitAvailable: sessionTimeLimitAvailableBySessionId.get(message.sessionId) ?? false,
|
|
883
|
+
user
|
|
884
|
+
});
|
|
885
|
+
break;
|
|
886
|
+
}
|
|
887
|
+
case "speech_event":
|
|
888
|
+
await handlers.onSpeechEvent?.({ sessionId: message.sessionId }, message.event);
|
|
889
|
+
if (message.event.type === "user_speech_final" && typeof message.event.text === "string" && message.event.text.trim()) {
|
|
890
|
+
const rawUtteranceId = message.event.utteranceId;
|
|
891
|
+
const utteranceId = typeof rawUtteranceId === "string" ? rawUtteranceId.trim() : "";
|
|
892
|
+
await handlers.onUserSpeechFinal?.({
|
|
893
|
+
sessionId: message.sessionId,
|
|
894
|
+
text: message.event.text.trim(),
|
|
895
|
+
...message.event.replay === true ? { replay: true } : {},
|
|
896
|
+
...utteranceId ? { utteranceId } : {},
|
|
897
|
+
...speakerFieldsOf(message.event)
|
|
898
|
+
});
|
|
899
|
+
}
|
|
900
|
+
if (message.event.type === "user_speech_ignored") {
|
|
901
|
+
const ignored = message.event;
|
|
902
|
+
if (typeof ignored.utteranceId === "string" && ignored.reason === "speaker_mismatch") {
|
|
903
|
+
await handlers.onUserSpeechIgnored?.({
|
|
904
|
+
sessionId: message.sessionId,
|
|
905
|
+
utteranceId: ignored.utteranceId,
|
|
906
|
+
reason: ignored.reason
|
|
907
|
+
});
|
|
908
|
+
}
|
|
909
|
+
}
|
|
910
|
+
if (message.event.type === "user_language") {
|
|
911
|
+
const language = resolveUserLanguageCode(message.event);
|
|
912
|
+
if (language) {
|
|
913
|
+
lastVoiceLanguageBySessionId.set(message.sessionId, language);
|
|
914
|
+
await handlers.onUserLanguage?.({
|
|
915
|
+
sessionId: message.sessionId,
|
|
916
|
+
language
|
|
917
|
+
});
|
|
918
|
+
}
|
|
919
|
+
}
|
|
920
|
+
if (message.event.type === "voice_language_changed") {
|
|
921
|
+
const language = resolveUserLanguageCode(message.event);
|
|
922
|
+
if (language) {
|
|
923
|
+
lastVoiceLanguageBySessionId.set(message.sessionId, language);
|
|
924
|
+
await handlers.onVoiceLanguageChanged?.({
|
|
925
|
+
sessionId: message.sessionId,
|
|
926
|
+
language
|
|
927
|
+
});
|
|
928
|
+
}
|
|
929
|
+
}
|
|
930
|
+
break;
|
|
931
|
+
case "agent_interrupted": {
|
|
932
|
+
const { type: _type, ...interrupted } = message;
|
|
933
|
+
await handlers.onAgentInterrupted?.(interrupted);
|
|
934
|
+
break;
|
|
935
|
+
}
|
|
936
|
+
case "data_channel_message":
|
|
937
|
+
await handlers.onDataChannelMessage?.({
|
|
938
|
+
sessionId: message.sessionId,
|
|
939
|
+
message: parseDataChannelPayload(message.payload),
|
|
940
|
+
raw: message.payload,
|
|
941
|
+
rawBinary: null,
|
|
942
|
+
channel: "control"
|
|
943
|
+
});
|
|
944
|
+
break;
|
|
945
|
+
case "data_channel_binary":
|
|
946
|
+
await handlers.onDataChannelBinary?.({
|
|
947
|
+
sessionId: message.sessionId,
|
|
948
|
+
message: null,
|
|
949
|
+
raw: null,
|
|
950
|
+
rawBinary: message.data,
|
|
951
|
+
channel: message.channel ?? "sync"
|
|
952
|
+
});
|
|
953
|
+
break;
|
|
954
|
+
case "session_end":
|
|
955
|
+
clearPendingRecordingAcksForSession(message.sessionId, "session_ended");
|
|
956
|
+
clearPendingConversationHistoryAcksForSession(message.sessionId, "session_ended");
|
|
957
|
+
peerEnvBySessionId.delete(message.sessionId);
|
|
958
|
+
recordingAvailableBySessionId.delete(message.sessionId);
|
|
959
|
+
conversationHistoryAvailableBySessionId.delete(message.sessionId);
|
|
960
|
+
endUserBySessionId.delete(message.sessionId);
|
|
961
|
+
mixAvailableBySessionId.delete(message.sessionId);
|
|
962
|
+
voiceLanguageSwitchAvailableBySessionId.delete(message.sessionId);
|
|
963
|
+
speakerGateBySessionId.delete(message.sessionId);
|
|
964
|
+
voiceLanguageSwitchSettingsBySessionId.delete(message.sessionId);
|
|
965
|
+
lastVoiceLanguageBySessionId.delete(message.sessionId);
|
|
966
|
+
ttsPoseAvailableBySessionId.delete(message.sessionId);
|
|
967
|
+
speakControlAvailableBySessionId.delete(message.sessionId);
|
|
968
|
+
chatReplyRecordAvailableBySessionId.delete(message.sessionId);
|
|
969
|
+
sessionTimeLimitAvailableBySessionId.delete(message.sessionId);
|
|
970
|
+
clearPendingSpeakForSession(message.sessionId, "session_ended");
|
|
971
|
+
await (handlers.onClientLeave ?? handlers.onSessionEnd)?.({
|
|
972
|
+
sessionId: message.sessionId
|
|
973
|
+
});
|
|
974
|
+
break;
|
|
975
|
+
case "idle_timeout":
|
|
976
|
+
await runIdleTimeoutHook(handlers, message);
|
|
977
|
+
break;
|
|
978
|
+
case "session_time_limit":
|
|
979
|
+
await runSessionTimeLimitHook(handlers, message);
|
|
980
|
+
break;
|
|
981
|
+
}
|
|
982
|
+
}
|
|
983
|
+
function defineAgent(handlers) {
|
|
984
|
+
installChildUnhandledRejectionGuard();
|
|
985
|
+
const inboundBySession = new SessionSerialQueue();
|
|
986
|
+
inboundQueueAuthority = inboundBySession;
|
|
987
|
+
const agentStartReady = runAgentStartHook(handlers);
|
|
988
|
+
process.on("message", (message) => {
|
|
989
|
+
if (isRecordingControlAckMessage(message)) {
|
|
990
|
+
handleRecordingControlAck(message);
|
|
991
|
+
return;
|
|
992
|
+
}
|
|
993
|
+
if (isConversationHistoryControlAckMessage(message)) {
|
|
994
|
+
handleConversationHistoryControlAck(message);
|
|
995
|
+
return;
|
|
996
|
+
}
|
|
997
|
+
if (isUserHistoryResponseMessage(message)) {
|
|
998
|
+
handleUserHistoryResponse(message);
|
|
999
|
+
return;
|
|
1000
|
+
}
|
|
1001
|
+
if (isSpeakResultMessage(message)) {
|
|
1002
|
+
handleSpeakResult(message);
|
|
1003
|
+
return;
|
|
1004
|
+
}
|
|
1005
|
+
if (isBargeInControlAckMessage(message)) {
|
|
1006
|
+
handleBargeInControlAck(message);
|
|
1007
|
+
return;
|
|
1008
|
+
}
|
|
1009
|
+
if (isSessionTimeLimitControlAckMessage(message)) {
|
|
1010
|
+
handleSessionTimeLimitControlAck(message);
|
|
1011
|
+
return;
|
|
1012
|
+
}
|
|
1013
|
+
if (isPlayAckMessage(message)) {
|
|
1014
|
+
handlePlayAck(message);
|
|
1015
|
+
return;
|
|
1016
|
+
}
|
|
1017
|
+
if (isPlayStatusAckMessage(message)) {
|
|
1018
|
+
handlePlayStatusAck(message);
|
|
1019
|
+
return;
|
|
1020
|
+
}
|
|
1021
|
+
if (isPlayStopAckMessage(message)) {
|
|
1022
|
+
handlePlayStopAck(message);
|
|
1023
|
+
return;
|
|
1024
|
+
}
|
|
1025
|
+
if (isPlayPoseAckMessage(message)) {
|
|
1026
|
+
handlePlayPoseAck(message);
|
|
1027
|
+
return;
|
|
1028
|
+
}
|
|
1029
|
+
if (isMixControlAckMessage(message)) {
|
|
1030
|
+
handleMixControlAck(message);
|
|
1031
|
+
return;
|
|
1032
|
+
}
|
|
1033
|
+
if (isSttControlAckMessage(message)) {
|
|
1034
|
+
handleSttControlAck(message);
|
|
1035
|
+
return;
|
|
1036
|
+
}
|
|
1037
|
+
if (isVoiceLanguageControlAckMessage(message)) {
|
|
1038
|
+
handleVoiceLanguageControlAck(message);
|
|
1039
|
+
return;
|
|
1040
|
+
}
|
|
1041
|
+
if (isVoiceLanguagePrepareResultMessage(message)) {
|
|
1042
|
+
handleVoiceLanguagePrepareResult(message);
|
|
1043
|
+
return;
|
|
1044
|
+
}
|
|
1045
|
+
if (isVoiceReplayLastResultMessage(message)) {
|
|
1046
|
+
handleVoiceReplayLastResult(message);
|
|
1047
|
+
return;
|
|
1048
|
+
}
|
|
1049
|
+
if (isSetSpeakerGateResultMessage(message)) {
|
|
1050
|
+
handleSetSpeakerGateResult(message);
|
|
1051
|
+
return;
|
|
1052
|
+
}
|
|
1053
|
+
if (isResetSpeakerEnrollmentResultMessage(message)) {
|
|
1054
|
+
handleResetSpeakerEnrollmentResult(message);
|
|
1055
|
+
return;
|
|
1056
|
+
}
|
|
1057
|
+
if (isWebhookMessage(message)) {
|
|
1058
|
+
void agentStartReady.then(() => handleWebhookMessage(message, handlers));
|
|
1059
|
+
return;
|
|
1060
|
+
}
|
|
1061
|
+
if (!isSessionScopedParentMessage(message))
|
|
1062
|
+
return;
|
|
1063
|
+
if (message.type === "session_end") {
|
|
1064
|
+
endedSessionIds.add(message.sessionId);
|
|
1065
|
+
clearPendingSpeakForSession(message.sessionId, "session_ended");
|
|
1066
|
+
clearPendingRecordingAcksForSession(message.sessionId, "session_ended");
|
|
1067
|
+
clearPendingConversationHistoryAcksForSession(message.sessionId, "session_ended");
|
|
1068
|
+
clearPendingUserHistoryForSession(message.sessionId, "session_ended");
|
|
1069
|
+
inboundBySession.clear(message.sessionId);
|
|
1070
|
+
}
|
|
1071
|
+
if (message.type === "session_start") {
|
|
1072
|
+
endedSessionIds.delete(message.sessionId);
|
|
1073
|
+
inboundBySession.clear(message.sessionId);
|
|
1074
|
+
}
|
|
1075
|
+
inboundBySession.enqueue(message.sessionId, async (_signal, context) => {
|
|
1076
|
+
await agentStartReady;
|
|
1077
|
+
try {
|
|
1078
|
+
await sessionExecutionContext.run({
|
|
1079
|
+
sessionId: message.sessionId,
|
|
1080
|
+
generation: context.generation
|
|
1081
|
+
}, async () => agentLogSessionContext.run(message.sessionId, async () => {
|
|
1082
|
+
try {
|
|
1083
|
+
await handleParentMessage(message, handlers);
|
|
1084
|
+
} catch (error) {
|
|
1085
|
+
const err = error instanceof Error ? error : new Error(String(error));
|
|
1086
|
+
const env = peerEnvBySessionId.get(message.sessionId) ?? buildIdleEnv(message.sessionId);
|
|
1087
|
+
await runErrorHook(handlers, {
|
|
1088
|
+
sessionId: message.sessionId,
|
|
1089
|
+
projectId: env.PROJECT_ID,
|
|
1090
|
+
buildId: env.BUILD_ID,
|
|
1091
|
+
env,
|
|
1092
|
+
error: err,
|
|
1093
|
+
customerContext: parseCustomerContext(env.AGENT_CUSTOMER_CONTEXT)
|
|
1094
|
+
});
|
|
1095
|
+
sendParentMessage({
|
|
1096
|
+
type: "agent_error",
|
|
1097
|
+
sessionId: message.sessionId,
|
|
1098
|
+
message: err.message,
|
|
1099
|
+
stack: err.stack
|
|
1100
|
+
});
|
|
1101
|
+
}
|
|
1102
|
+
}));
|
|
1103
|
+
} finally {
|
|
1104
|
+
if (message.type === "session_end" && inboundBySession.isCurrentGeneration(message.sessionId, context.generation)) {
|
|
1105
|
+
inboundBySession.clear(message.sessionId);
|
|
1106
|
+
}
|
|
1107
|
+
}
|
|
1108
|
+
});
|
|
1109
|
+
});
|
|
1110
|
+
}
|
|
1111
|
+
async function runAgentStartHook(handlers) {
|
|
1112
|
+
if (!handlers.onAgentStart)
|
|
1113
|
+
return;
|
|
1114
|
+
try {
|
|
1115
|
+
await handlers.onAgentStart({
|
|
1116
|
+
env: process.env
|
|
1117
|
+
});
|
|
1118
|
+
} catch (error) {
|
|
1119
|
+
const err = error instanceof Error ? error : new Error(String(error));
|
|
1120
|
+
agentLog("error", `onAgentStart failed: ${err.message}`);
|
|
1121
|
+
sendParentMessage({
|
|
1122
|
+
type: "agent_error",
|
|
1123
|
+
sessionId: "",
|
|
1124
|
+
message: err.message,
|
|
1125
|
+
stack: err.stack
|
|
1126
|
+
});
|
|
1127
|
+
}
|
|
1128
|
+
}
|
|
1129
|
+
function parseCustomerContext(raw) {
|
|
1130
|
+
if (!raw?.trim())
|
|
1131
|
+
return void 0;
|
|
1132
|
+
try {
|
|
1133
|
+
const parsed = JSON.parse(raw);
|
|
1134
|
+
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
|
|
1135
|
+
return parsed;
|
|
1136
|
+
}
|
|
1137
|
+
} catch {
|
|
1138
|
+
}
|
|
1139
|
+
return void 0;
|
|
1140
|
+
}
|
|
1141
|
+
function parseEndUserInfo(value) {
|
|
1142
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
1143
|
+
return void 0;
|
|
1144
|
+
}
|
|
1145
|
+
const v = value;
|
|
1146
|
+
if (typeof v.id !== "string" || v.id.length === 0)
|
|
1147
|
+
return void 0;
|
|
1148
|
+
const isObj = (x) => !!x && typeof x === "object" && !Array.isArray(x);
|
|
1149
|
+
return {
|
|
1150
|
+
id: v.id,
|
|
1151
|
+
verified: v.verified === true,
|
|
1152
|
+
...isObj(v.attributes) ? { attributes: v.attributes } : {},
|
|
1153
|
+
...isObj(v.sessionContext) ? { sessionContext: v.sessionContext } : {}
|
|
1154
|
+
};
|
|
1155
|
+
}
|
|
1156
|
+
function parseEndUserEnv(raw) {
|
|
1157
|
+
if (!raw?.trim())
|
|
1158
|
+
return void 0;
|
|
1159
|
+
try {
|
|
1160
|
+
return parseEndUserInfo(JSON.parse(raw));
|
|
1161
|
+
} catch {
|
|
1162
|
+
return void 0;
|
|
1163
|
+
}
|
|
1164
|
+
}
|
|
1165
|
+
async function runErrorHook(handlers, ctx) {
|
|
1166
|
+
if (!handlers.errorHook)
|
|
1167
|
+
return;
|
|
1168
|
+
try {
|
|
1169
|
+
await handlers.errorHook(ctx);
|
|
1170
|
+
} catch (hookError) {
|
|
1171
|
+
const message = hookError instanceof Error ? hookError.message : String(hookError);
|
|
1172
|
+
agentLog("error", `errorHook failed: ${message}`, ctx.sessionId);
|
|
1173
|
+
}
|
|
1174
|
+
}
|
|
1175
|
+
async function runIdleTimeoutHook(handlers, message) {
|
|
1176
|
+
const onIdleTimeout = handlers.onIdleTimeout;
|
|
1177
|
+
agentLog("info", `idle_timeout ipc received (maxGraceMs=${message.maxGraceMs}, onIdleTimeout=${typeof onIdleTimeout === "function"})`, message.sessionId);
|
|
1178
|
+
if (!onIdleTimeout) {
|
|
1179
|
+
sendParentMessage({
|
|
1180
|
+
type: "idle_timeout_done",
|
|
1181
|
+
sessionId: message.sessionId
|
|
1182
|
+
});
|
|
1183
|
+
agentLog("info", "idle_timeout_done ipc sent (no onIdleTimeout handler)", message.sessionId);
|
|
1184
|
+
return;
|
|
1185
|
+
}
|
|
1186
|
+
const env = peerEnvBySessionId.get(message.sessionId) ?? buildIdleEnv(message.sessionId);
|
|
1187
|
+
const idleTimeoutSeconds = Number(env.IDLE_TIMEOUT_SEC) || 0;
|
|
1188
|
+
const ctx = {
|
|
1189
|
+
sessionId: message.sessionId,
|
|
1190
|
+
projectId: env.PROJECT_ID,
|
|
1191
|
+
buildId: env.BUILD_ID,
|
|
1192
|
+
env,
|
|
1193
|
+
idleTimeoutSeconds
|
|
1194
|
+
};
|
|
1195
|
+
let error;
|
|
1196
|
+
try {
|
|
1197
|
+
await onIdleTimeout(ctx);
|
|
1198
|
+
} catch (hookError) {
|
|
1199
|
+
error = hookError instanceof Error ? hookError.message : String(hookError);
|
|
1200
|
+
agentLog("error", `onIdleTimeout failed: ${error}`, message.sessionId);
|
|
1201
|
+
}
|
|
1202
|
+
sendParentMessage({
|
|
1203
|
+
type: "idle_timeout_done",
|
|
1204
|
+
sessionId: message.sessionId,
|
|
1205
|
+
error
|
|
1206
|
+
});
|
|
1207
|
+
agentLog("info", error ? `idle_timeout_done ipc sent (onIdleTimeout error: ${error})` : "idle_timeout_done ipc sent (onIdleTimeout completed)", message.sessionId);
|
|
1208
|
+
}
|
|
1209
|
+
async function runSessionTimeLimitHook(handlers, message) {
|
|
1210
|
+
const onSessionTimeLimit = handlers.onSessionTimeLimit;
|
|
1211
|
+
agentLog("info", `session_time_limit ipc received (maxGraceMs=${message.maxGraceMs}, onSessionTimeLimit=${typeof onSessionTimeLimit === "function"})`, message.sessionId);
|
|
1212
|
+
if (!onSessionTimeLimit) {
|
|
1213
|
+
sendParentMessage({
|
|
1214
|
+
type: "session_time_limit_done",
|
|
1215
|
+
sessionId: message.sessionId
|
|
1216
|
+
});
|
|
1217
|
+
return;
|
|
1218
|
+
}
|
|
1219
|
+
const env = peerEnvBySessionId.get(message.sessionId) ?? {
|
|
1220
|
+
SESSION_ID: message.sessionId,
|
|
1221
|
+
...process.env.PROJECT_ID ? { PROJECT_ID: process.env.PROJECT_ID } : {},
|
|
1222
|
+
...process.env.BUILD_ID ? { BUILD_ID: process.env.BUILD_ID } : {}
|
|
1223
|
+
};
|
|
1224
|
+
const ctx = {
|
|
1225
|
+
sessionId: message.sessionId,
|
|
1226
|
+
projectId: env.PROJECT_ID,
|
|
1227
|
+
buildId: env.BUILD_ID,
|
|
1228
|
+
env,
|
|
1229
|
+
limitMinutes: message.limitMinutes,
|
|
1230
|
+
elapsedMs: message.elapsedMs,
|
|
1231
|
+
graceMs: message.maxGraceMs
|
|
1232
|
+
};
|
|
1233
|
+
let error;
|
|
1234
|
+
try {
|
|
1235
|
+
await onSessionTimeLimit(ctx);
|
|
1236
|
+
} catch (hookError) {
|
|
1237
|
+
error = hookError instanceof Error ? hookError.message : String(hookError);
|
|
1238
|
+
agentLog("error", `onSessionTimeLimit failed: ${error}`, message.sessionId);
|
|
1239
|
+
}
|
|
1240
|
+
sendParentMessage({
|
|
1241
|
+
type: "session_time_limit_done",
|
|
1242
|
+
sessionId: message.sessionId,
|
|
1243
|
+
...error !== void 0 ? { error } : {}
|
|
1244
|
+
});
|
|
1245
|
+
}
|
|
1246
|
+
function buildIdleEnv(sessionId) {
|
|
1247
|
+
return {
|
|
1248
|
+
SESSION_ID: sessionId,
|
|
1249
|
+
...process.env.PROJECT_ID ? { PROJECT_ID: process.env.PROJECT_ID } : {},
|
|
1250
|
+
...process.env.BUILD_ID ? { BUILD_ID: process.env.BUILD_ID } : {},
|
|
1251
|
+
...process.env.IDLE_TIMEOUT_SEC ? { IDLE_TIMEOUT_SEC: process.env.IDLE_TIMEOUT_SEC } : {}
|
|
1252
|
+
};
|
|
1253
|
+
}
|
|
1254
|
+
function speakKindFields(options) {
|
|
1255
|
+
if (options?.kind !== "filler")
|
|
1256
|
+
return {};
|
|
1257
|
+
return {
|
|
1258
|
+
kind: "filler",
|
|
1259
|
+
...options.fillerKind ? { fillerKind: options.fillerKind } : {}
|
|
1260
|
+
};
|
|
1261
|
+
}
|
|
1262
|
+
function speakControlAvailableFor(sessionId) {
|
|
1263
|
+
return speakControlAvailableBySessionId.get(sessionId) ?? false;
|
|
1264
|
+
}
|
|
1265
|
+
function warnSpeakControlUnavailable(sessionId) {
|
|
1266
|
+
if (speakControlWarnedSessionIds.has(sessionId))
|
|
1267
|
+
return;
|
|
1268
|
+
speakControlWarnedSessionIds.add(sessionId);
|
|
1269
|
+
agentLog("warn", "speak control not available on this runner; speak results, cancel and barge-in control are disabled", sessionId);
|
|
1270
|
+
}
|
|
1271
|
+
function speak(sessionId, text, options) {
|
|
1272
|
+
const requestId = randomUUID();
|
|
1273
|
+
const handle = (done2) => ({
|
|
1274
|
+
requestId,
|
|
1275
|
+
done: Promise.resolve(done2),
|
|
1276
|
+
cancel: () => cancelSpeech(sessionId, { requestId })
|
|
1277
|
+
});
|
|
1278
|
+
if (!isVoicethereAgentChild()) {
|
|
1279
|
+
return handle({
|
|
1280
|
+
requestId,
|
|
1281
|
+
status: "unsupported",
|
|
1282
|
+
playedMs: 0,
|
|
1283
|
+
errorCode: "no_parent"
|
|
1284
|
+
});
|
|
1285
|
+
}
|
|
1286
|
+
if (!allowOutboundForSession(sessionId)) {
|
|
1287
|
+
return handle({
|
|
1288
|
+
requestId,
|
|
1289
|
+
status: "cancelled",
|
|
1290
|
+
playedMs: 0,
|
|
1291
|
+
errorCode: "session_ended"
|
|
1292
|
+
});
|
|
1293
|
+
}
|
|
1294
|
+
if (!speakControlAvailableFor(sessionId)) {
|
|
1295
|
+
sendParentMessage({
|
|
1296
|
+
type: "speak",
|
|
1297
|
+
sessionId,
|
|
1298
|
+
text,
|
|
1299
|
+
...options?.interruptible === false ? { interruptible: false } : {},
|
|
1300
|
+
...speakKindFields(options)
|
|
1301
|
+
});
|
|
1302
|
+
warnSpeakControlUnavailable(sessionId);
|
|
1303
|
+
return handle({ requestId, status: "unsupported", playedMs: 0 });
|
|
1304
|
+
}
|
|
1305
|
+
const turnId = options?.turnId;
|
|
1306
|
+
const inReplyTo = options?.inReplyTo;
|
|
1307
|
+
const done = new Promise((resolve) => {
|
|
1308
|
+
const timer = setTimeout(() => {
|
|
1309
|
+
pendingSpeakResults.delete(requestId);
|
|
1310
|
+
resolve({
|
|
1311
|
+
requestId,
|
|
1312
|
+
...turnId ? { turnId } : {},
|
|
1313
|
+
status: "failed",
|
|
1314
|
+
playedMs: 0,
|
|
1315
|
+
errorCode: "timeout"
|
|
1316
|
+
});
|
|
1317
|
+
}, SPEAK_RESULT_SAFETY_TIMEOUT_MS);
|
|
1318
|
+
pendingSpeakResults.set(requestId, {
|
|
1319
|
+
sessionId,
|
|
1320
|
+
...turnId ? { turnId } : {},
|
|
1321
|
+
resolve,
|
|
1322
|
+
timer
|
|
1323
|
+
});
|
|
1324
|
+
});
|
|
1325
|
+
sendParentMessage({
|
|
1326
|
+
type: "speak",
|
|
1327
|
+
sessionId,
|
|
1328
|
+
text,
|
|
1329
|
+
requestId,
|
|
1330
|
+
...options?.interruptible === false ? { interruptible: false } : {},
|
|
1331
|
+
...turnId ? { turnId } : {},
|
|
1332
|
+
...inReplyTo ? { inReplyTo } : {},
|
|
1333
|
+
...speakKindFields(options)
|
|
1334
|
+
});
|
|
1335
|
+
return {
|
|
1336
|
+
requestId,
|
|
1337
|
+
done,
|
|
1338
|
+
cancel: () => cancelSpeech(sessionId, { requestId })
|
|
1339
|
+
};
|
|
1340
|
+
}
|
|
1341
|
+
function cancelSpeech(sessionId, target) {
|
|
1342
|
+
if (!isVoicethereAgentChild() || !allowOutboundForSession(sessionId))
|
|
1343
|
+
return;
|
|
1344
|
+
if (!speakControlAvailableFor(sessionId)) {
|
|
1345
|
+
warnSpeakControlUnavailable(sessionId);
|
|
1346
|
+
return;
|
|
1347
|
+
}
|
|
1348
|
+
sendParentMessage({
|
|
1349
|
+
type: "speak_cancel",
|
|
1350
|
+
sessionId,
|
|
1351
|
+
...target?.requestId ? { requestId: target.requestId } : {},
|
|
1352
|
+
...target?.turnId ? { turnId: target.turnId } : {}
|
|
1353
|
+
});
|
|
1354
|
+
}
|
|
1355
|
+
var SPEAKER_GATE_MODES = ["disabled", "auto", "manual"];
|
|
1356
|
+
var SPEAKER_GATE_BARGE_IN = ["caller_only", "anyone"];
|
|
1357
|
+
function getSpeakerGate(sessionId) {
|
|
1358
|
+
return speakerGateBySessionId.get(sessionId) ?? { available: false };
|
|
1359
|
+
}
|
|
1360
|
+
function setSpeakerGate(sessionId, update) {
|
|
1361
|
+
const { mode, bargeIn } = update ?? {};
|
|
1362
|
+
if (mode !== void 0 && !SPEAKER_GATE_MODES.includes(mode) || bargeIn !== void 0 && !SPEAKER_GATE_BARGE_IN.includes(bargeIn)) {
|
|
1363
|
+
return Promise.resolve({ ok: false, reason: "invalid" });
|
|
1364
|
+
}
|
|
1365
|
+
if (!isVoicethereAgentChild() || !getSpeakerGate(sessionId).available) {
|
|
1366
|
+
return Promise.resolve({ ok: false, reason: "not_available" });
|
|
1367
|
+
}
|
|
1368
|
+
const requestId = randomUUID();
|
|
1369
|
+
return new Promise((resolve) => {
|
|
1370
|
+
const timer = setTimeout(() => {
|
|
1371
|
+
pendingSpeakerGateAcks.delete(requestId);
|
|
1372
|
+
resolve({ ok: false, reason: "timeout" });
|
|
1373
|
+
}, SPEAKER_GATE_ACK_TIMEOUT_MS);
|
|
1374
|
+
pendingSpeakerGateAcks.set(requestId, { sessionId, resolve, timer });
|
|
1375
|
+
sendParentMessage({
|
|
1376
|
+
type: "setSpeakerGate",
|
|
1377
|
+
requestId,
|
|
1378
|
+
sessionId,
|
|
1379
|
+
...mode !== void 0 ? { mode } : {},
|
|
1380
|
+
...bargeIn !== void 0 ? { bargeIn } : {}
|
|
1381
|
+
});
|
|
1382
|
+
});
|
|
1383
|
+
}
|
|
1384
|
+
function resetSpeakerEnrollment(sessionId) {
|
|
1385
|
+
if (!isVoicethereAgentChild() || !getSpeakerGate(sessionId).available) {
|
|
1386
|
+
return Promise.resolve({ ok: false, reason: "not_available" });
|
|
1387
|
+
}
|
|
1388
|
+
const requestId = randomUUID();
|
|
1389
|
+
return new Promise((resolve) => {
|
|
1390
|
+
const timer = setTimeout(() => {
|
|
1391
|
+
pendingSpeakerResets.delete(requestId);
|
|
1392
|
+
resolve({ ok: false, reason: "timeout" });
|
|
1393
|
+
}, SPEAKER_GATE_ACK_TIMEOUT_MS);
|
|
1394
|
+
pendingSpeakerResets.set(requestId, { resolve, timer });
|
|
1395
|
+
sendParentMessage({
|
|
1396
|
+
type: "resetSpeakerEnrollment",
|
|
1397
|
+
requestId,
|
|
1398
|
+
sessionId
|
|
1399
|
+
});
|
|
1400
|
+
});
|
|
1401
|
+
}
|
|
1402
|
+
var AGENT_LOG_MESSAGE_MAX_CHARS = 2048;
|
|
1403
|
+
var AGENT_LOG_FIELDS_MAX_CHARS = 8192;
|
|
1404
|
+
function truncateAgentLogMessage(message) {
|
|
1405
|
+
if (message.length <= AGENT_LOG_MESSAGE_MAX_CHARS) {
|
|
1406
|
+
return message;
|
|
1407
|
+
}
|
|
1408
|
+
const suffix = "\u2026[truncated]";
|
|
1409
|
+
return message.slice(0, AGENT_LOG_MESSAGE_MAX_CHARS - suffix.length) + suffix;
|
|
1410
|
+
}
|
|
1411
|
+
function isPlainObject(value) {
|
|
1412
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1413
|
+
}
|
|
1414
|
+
function sanitizeAgentLogFields(fields) {
|
|
1415
|
+
if (Object.keys(fields).length === 0) {
|
|
1416
|
+
return void 0;
|
|
1417
|
+
}
|
|
1418
|
+
try {
|
|
1419
|
+
const serialized = JSON.stringify(fields);
|
|
1420
|
+
if (serialized.length <= AGENT_LOG_FIELDS_MAX_CHARS) {
|
|
1421
|
+
return fields;
|
|
1422
|
+
}
|
|
1423
|
+
return {
|
|
1424
|
+
_agentLogFieldsTruncated: true,
|
|
1425
|
+
_originalBytes: serialized.length,
|
|
1426
|
+
_preview: serialized.slice(0, AGENT_LOG_FIELDS_MAX_CHARS - 80) + "\u2026[truncated]"
|
|
1427
|
+
};
|
|
1428
|
+
} catch {
|
|
1429
|
+
return { _agentLogFieldsError: "not_serializable" };
|
|
1430
|
+
}
|
|
1431
|
+
}
|
|
1432
|
+
function buildAgentLogPayload(level, message, fields, sessionId) {
|
|
1433
|
+
const resolvedSessionId = sessionId ?? currentHandlerSessionId();
|
|
1434
|
+
const sanitizedFields = fields ? sanitizeAgentLogFields(fields) : void 0;
|
|
1435
|
+
return {
|
|
1436
|
+
type: "log",
|
|
1437
|
+
level,
|
|
1438
|
+
message: truncateAgentLogMessage(message),
|
|
1439
|
+
ts: Date.now(),
|
|
1440
|
+
...resolvedSessionId ? { sessionId: resolvedSessionId } : {},
|
|
1441
|
+
...sanitizedFields ? { fields: sanitizedFields } : {}
|
|
1442
|
+
};
|
|
1443
|
+
}
|
|
1444
|
+
function agentLog(level, message, fieldsOrSessionId, sessionId) {
|
|
1445
|
+
let fields;
|
|
1446
|
+
let resolvedSessionId;
|
|
1447
|
+
if (typeof fieldsOrSessionId === "string") {
|
|
1448
|
+
resolvedSessionId = fieldsOrSessionId;
|
|
1449
|
+
} else if (isPlainObject(fieldsOrSessionId)) {
|
|
1450
|
+
fields = fieldsOrSessionId;
|
|
1451
|
+
resolvedSessionId = sessionId;
|
|
1452
|
+
} else {
|
|
1453
|
+
resolvedSessionId = sessionId;
|
|
1454
|
+
}
|
|
1455
|
+
sendParentMessage(buildAgentLogPayload(level, message, fields, resolvedSessionId));
|
|
1456
|
+
}
|
|
1457
|
+
function parseChatText(message) {
|
|
1458
|
+
if (!message || typeof message !== "object")
|
|
1459
|
+
return null;
|
|
1460
|
+
const record = message;
|
|
1461
|
+
if (record.type !== "chat" || typeof record.text !== "string")
|
|
1462
|
+
return null;
|
|
1463
|
+
const trimmed = record.text.trim();
|
|
1464
|
+
return trimmed.length > 0 ? trimmed : null;
|
|
1465
|
+
}
|
|
1466
|
+
|
|
1467
|
+
// templates/speaker-gate/agent.ts
|
|
1468
|
+
function parseSpeakerGateCommand(text) {
|
|
1469
|
+
const match = /^speaker-gate:(auto|manual|disabled|reset)$/i.exec(
|
|
1470
|
+
text.trim()
|
|
1471
|
+
);
|
|
1472
|
+
if (!match) return null;
|
|
1473
|
+
const word = match[1].toLowerCase();
|
|
1474
|
+
if (word === "reset") return { kind: "reset" };
|
|
1475
|
+
return { kind: "mode", mode: word };
|
|
1476
|
+
}
|
|
1477
|
+
function normalizeSpoken(text) {
|
|
1478
|
+
return text.toLowerCase().replace(/[^\p{L}\p{N}\s]/gu, " ").replace(/\s+/g, " ").trim();
|
|
1479
|
+
}
|
|
1480
|
+
function parseSpokenCommand(text) {
|
|
1481
|
+
const phrase = normalizeSpoken(text);
|
|
1482
|
+
if (phrase === "only listen to me") return { kind: "mode", mode: "auto" };
|
|
1483
|
+
if (phrase === "listen to everyone") {
|
|
1484
|
+
return { kind: "mode", mode: "manual" };
|
|
1485
|
+
}
|
|
1486
|
+
return null;
|
|
1487
|
+
}
|
|
1488
|
+
function shouldAnswer(speaker) {
|
|
1489
|
+
return speaker !== "other";
|
|
1490
|
+
}
|
|
1491
|
+
var OTHER_NOTICE_INTERVAL_MS = 3e4;
|
|
1492
|
+
var lastOtherNoticeAt = /* @__PURE__ */ new Map();
|
|
1493
|
+
var counters = /* @__PURE__ */ new Map();
|
|
1494
|
+
function logLine(sessionId, kind, fields) {
|
|
1495
|
+
const n = (counters.get(sessionId) ?? 0) + 1;
|
|
1496
|
+
counters.set(sessionId, n);
|
|
1497
|
+
const line = `speaker_gate.${kind} n=${n}${fields ? ` ${fields}` : ""}`;
|
|
1498
|
+
agentLog("info", line, sessionId);
|
|
1499
|
+
return line;
|
|
1500
|
+
}
|
|
1501
|
+
async function runCommand(sessionId, command) {
|
|
1502
|
+
if (command.kind === "reset") {
|
|
1503
|
+
const result2 = await resetSpeakerEnrollment(sessionId);
|
|
1504
|
+
if (!result2.ok) return;
|
|
1505
|
+
logLine(sessionId, "reset", "");
|
|
1506
|
+
speak(sessionId, "Okay, I will learn your voice again.");
|
|
1507
|
+
return;
|
|
1508
|
+
}
|
|
1509
|
+
const result = await setSpeakerGate(sessionId, { mode: command.mode });
|
|
1510
|
+
if (!result.ok) return;
|
|
1511
|
+
logLine(sessionId, "mode", `mode=${result.mode}`);
|
|
1512
|
+
speak(
|
|
1513
|
+
sessionId,
|
|
1514
|
+
result.mode === "auto" ? "Okay, I only listen to you now." : result.mode === "manual" ? "Okay, I listen to everyone and tell voices apart." : "Okay, I listen to every voice."
|
|
1515
|
+
);
|
|
1516
|
+
}
|
|
1517
|
+
defineAgent({
|
|
1518
|
+
onSessionStart(ctx) {
|
|
1519
|
+
logLine(
|
|
1520
|
+
ctx.sessionId,
|
|
1521
|
+
"mode",
|
|
1522
|
+
`mode=${ctx.speakerGate?.mode ?? "disabled"}`
|
|
1523
|
+
);
|
|
1524
|
+
},
|
|
1525
|
+
async onUserSpeechFinal(ctx) {
|
|
1526
|
+
logLine(
|
|
1527
|
+
ctx.sessionId,
|
|
1528
|
+
"final",
|
|
1529
|
+
`speaker=${ctx.speaker ?? "none"} text=${JSON.stringify(ctx.text)}`
|
|
1530
|
+
);
|
|
1531
|
+
const spoken = parseSpokenCommand(ctx.text);
|
|
1532
|
+
if (spoken && ctx.speaker !== "other") {
|
|
1533
|
+
await runCommand(ctx.sessionId, spoken);
|
|
1534
|
+
return;
|
|
1535
|
+
}
|
|
1536
|
+
if (!shouldAnswer(ctx.speaker)) {
|
|
1537
|
+
const now = Date.now();
|
|
1538
|
+
const last = lastOtherNoticeAt.get(ctx.sessionId) ?? 0;
|
|
1539
|
+
if (now - last >= OTHER_NOTICE_INTERVAL_MS) {
|
|
1540
|
+
lastOtherNoticeAt.set(ctx.sessionId, now);
|
|
1541
|
+
speak(
|
|
1542
|
+
ctx.sessionId,
|
|
1543
|
+
"I heard someone else. I am listening to the caller."
|
|
1544
|
+
);
|
|
1545
|
+
}
|
|
1546
|
+
return;
|
|
1547
|
+
}
|
|
1548
|
+
speak(ctx.sessionId, `You said: ${ctx.text}`);
|
|
1549
|
+
},
|
|
1550
|
+
onUserSpeechIgnored(ctx) {
|
|
1551
|
+
logLine(
|
|
1552
|
+
ctx.sessionId,
|
|
1553
|
+
"ignored",
|
|
1554
|
+
`utteranceId=${ctx.utteranceId} reason=${ctx.reason}`
|
|
1555
|
+
);
|
|
1556
|
+
},
|
|
1557
|
+
async onDataChannelMessage(ctx) {
|
|
1558
|
+
const text = parseChatText(ctx.message);
|
|
1559
|
+
if (!text) return;
|
|
1560
|
+
const command = parseSpeakerGateCommand(text);
|
|
1561
|
+
if (!command) return;
|
|
1562
|
+
await runCommand(ctx.sessionId, command);
|
|
1563
|
+
},
|
|
1564
|
+
onSessionEnd(ctx) {
|
|
1565
|
+
lastOtherNoticeAt.delete(ctx.sessionId);
|
|
1566
|
+
counters.delete(ctx.sessionId);
|
|
1567
|
+
}
|
|
1568
|
+
});
|
|
1569
|
+
export {
|
|
1570
|
+
OTHER_NOTICE_INTERVAL_MS,
|
|
1571
|
+
logLine,
|
|
1572
|
+
parseSpeakerGateCommand,
|
|
1573
|
+
parseSpokenCommand,
|
|
1574
|
+
shouldAnswer
|
|
1575
|
+
};
|