@voicethere/agent 0.4.0 → 0.5.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 +3 -1
- package/dist/agent.js +84 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js.map +1 -1
- package/dist/protocol.d.ts +33 -4
- package/dist/protocol.d.ts.map +1 -1
- package/dist/protocol.js +3 -2
- package/dist/protocol.js.map +1 -1
- package/dist/runtime.d.ts +18 -0
- package/dist/runtime.d.ts.map +1 -1
- package/dist/runtime.js +94 -2
- package/dist/runtime.js.map +1 -1
- package/dist/templates/echo/agent.js +90 -2
- package/dist/templates/echo-dc/agent.js +90 -2
- package/dist/templates/game-sync/agent.js +90 -2
- package/dist/templates/registry.d.ts.map +1 -1
- package/dist/templates/registry.js +16 -0
- package/dist/templates/registry.js.map +1 -1
- package/dist/templates/voice-starter/agent.js +90 -2
- package/dist/templates/webhooks/agent.js +674 -0
- package/dist/templates/webhooks-redis/agent.js +11449 -0
- package/package.json +1 -1
- package/templates/README.md +9 -1
- package/templates/webhooks-redis.ts +135 -0
- package/templates/webhooks.ts +111 -0
|
@@ -0,0 +1,674 @@
|
|
|
1
|
+
import { createRequire } from "node:module";
|
|
2
|
+
const require = createRequire(import.meta.url);
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
// templates/webhooks.ts
|
|
6
|
+
import { createHmac, timingSafeEqual } from "node:crypto";
|
|
7
|
+
|
|
8
|
+
// dist/runtime.js
|
|
9
|
+
import { randomUUID } from "node:crypto";
|
|
10
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
11
|
+
|
|
12
|
+
// dist/session-serial-queue.js
|
|
13
|
+
var SessionSerialQueueCancellationError = class extends Error {
|
|
14
|
+
sessionId;
|
|
15
|
+
generation;
|
|
16
|
+
code = "SESSION_SERIAL_QUEUE_CANCELLED";
|
|
17
|
+
constructor(sessionId, generation) {
|
|
18
|
+
super(`session serial queue cancelled (sessionId=${sessionId}, generation=${generation})`);
|
|
19
|
+
this.sessionId = sessionId;
|
|
20
|
+
this.generation = generation;
|
|
21
|
+
this.name = "SessionSerialQueueCancellationError";
|
|
22
|
+
}
|
|
23
|
+
};
|
|
24
|
+
var SessionSerialQueue = class {
|
|
25
|
+
sessions = /* @__PURE__ */ new Map();
|
|
26
|
+
/** Monotonic token source — never reused across clear/enqueue cycles. */
|
|
27
|
+
nextGeneration = 1;
|
|
28
|
+
/**
|
|
29
|
+
* Enqueue work for `sessionId`. Returns a promise that settles when this
|
|
30
|
+
* task finishes, is skipped as stale, or is cancelled by {@link clear}.
|
|
31
|
+
* Fire-and-forget callers may ignore the return value (compat).
|
|
32
|
+
*/
|
|
33
|
+
enqueue(sessionId, task) {
|
|
34
|
+
const state = this.ensureState(sessionId);
|
|
35
|
+
const captured = state;
|
|
36
|
+
const generation = captured.generation;
|
|
37
|
+
captured.pending += 1;
|
|
38
|
+
const previous = captured.tail;
|
|
39
|
+
let taskAbort = null;
|
|
40
|
+
const settled = previous.catch(() => void 0).then(async () => {
|
|
41
|
+
if (this.sessions.get(sessionId) !== captured) {
|
|
42
|
+
return "cancelled";
|
|
43
|
+
}
|
|
44
|
+
const abort = new AbortController();
|
|
45
|
+
taskAbort = abort;
|
|
46
|
+
captured.abort = abort;
|
|
47
|
+
const context = {
|
|
48
|
+
sessionId,
|
|
49
|
+
generation,
|
|
50
|
+
signal: abort.signal
|
|
51
|
+
};
|
|
52
|
+
try {
|
|
53
|
+
await Promise.resolve(task(abort.signal, context));
|
|
54
|
+
if (this.sessions.get(sessionId) !== captured) {
|
|
55
|
+
return "cancelled";
|
|
56
|
+
}
|
|
57
|
+
return "completed";
|
|
58
|
+
} catch (error) {
|
|
59
|
+
if (abort.signal.aborted || this.sessions.get(sessionId) !== captured || error instanceof SessionSerialQueueCancellationError) {
|
|
60
|
+
return "cancelled";
|
|
61
|
+
}
|
|
62
|
+
return "failed";
|
|
63
|
+
} finally {
|
|
64
|
+
if (captured.abort === abort) {
|
|
65
|
+
captured.abort = null;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
}).finally(() => {
|
|
69
|
+
captured.pending = Math.max(0, captured.pending - 1);
|
|
70
|
+
if (taskAbort && captured.abort === taskAbort) {
|
|
71
|
+
captured.abort = null;
|
|
72
|
+
}
|
|
73
|
+
});
|
|
74
|
+
captured.tail = settled;
|
|
75
|
+
return settled;
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Invalidate queued + running work for `sessionId`. Aborts the live AbortSignal,
|
|
79
|
+
* drops the map entry, and leaves a fresh identity for the next enqueue.
|
|
80
|
+
* Old in-flight `finally` blocks only touch their captured state object.
|
|
81
|
+
*/
|
|
82
|
+
clear(sessionId) {
|
|
83
|
+
const old = this.sessions.get(sessionId);
|
|
84
|
+
if (!old)
|
|
85
|
+
return;
|
|
86
|
+
old.abort?.abort();
|
|
87
|
+
old.abort = null;
|
|
88
|
+
this.sessions.delete(sessionId);
|
|
89
|
+
}
|
|
90
|
+
clearAll() {
|
|
91
|
+
for (const sessionId of [...this.sessions.keys()]) {
|
|
92
|
+
this.clear(sessionId);
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
hasPending(sessionId) {
|
|
96
|
+
return (this.sessions.get(sessionId)?.pending ?? 0) > 0;
|
|
97
|
+
}
|
|
98
|
+
/** Live generation token for a session, or `undefined` when cleared. */
|
|
99
|
+
generationOf(sessionId) {
|
|
100
|
+
return this.sessions.get(sessionId)?.generation;
|
|
101
|
+
}
|
|
102
|
+
/** True when `generation` is the live map entry for `sessionId`. */
|
|
103
|
+
isCurrentGeneration(sessionId, generation) {
|
|
104
|
+
return this.sessions.get(sessionId)?.generation === generation;
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* True when a queue row exists for the session (registered since first
|
|
108
|
+
* enqueue, until {@link clear}). Not the same as {@link hasPending}.
|
|
109
|
+
*/
|
|
110
|
+
isLive(sessionId) {
|
|
111
|
+
return this.sessions.has(sessionId);
|
|
112
|
+
}
|
|
113
|
+
/** Registered session rows (must not grow without matching `clear` calls). */
|
|
114
|
+
get activeSessionCount() {
|
|
115
|
+
return this.sessions.size;
|
|
116
|
+
}
|
|
117
|
+
ensureState(sessionId) {
|
|
118
|
+
const existing = this.sessions.get(sessionId);
|
|
119
|
+
if (existing)
|
|
120
|
+
return existing;
|
|
121
|
+
const created = {
|
|
122
|
+
generation: this.nextGeneration++,
|
|
123
|
+
tail: Promise.resolve(),
|
|
124
|
+
abort: null,
|
|
125
|
+
pending: 0
|
|
126
|
+
};
|
|
127
|
+
this.sessions.set(sessionId, created);
|
|
128
|
+
return created;
|
|
129
|
+
}
|
|
130
|
+
};
|
|
131
|
+
|
|
132
|
+
// dist/runtime.js
|
|
133
|
+
var SESSION_START_INIT_DELAY_ENABLED_ENV = "AGENT_SESSION_START_INIT_DELAY_ENABLED";
|
|
134
|
+
var SESSION_START_INIT_DELAY_MS_ENV = "AGENT_SESSION_START_INIT_DELAY_MS";
|
|
135
|
+
var DEFAULT_SESSION_START_INIT_DELAY_MS = 500;
|
|
136
|
+
function isRecordingControlAckMessage(value) {
|
|
137
|
+
if (!value || typeof value !== "object")
|
|
138
|
+
return false;
|
|
139
|
+
const msg = value;
|
|
140
|
+
return msg.type === "recording_control_ack" && typeof msg.requestId === "string";
|
|
141
|
+
}
|
|
142
|
+
function isWebhookMessage(value) {
|
|
143
|
+
if (!value || typeof value !== "object")
|
|
144
|
+
return false;
|
|
145
|
+
const msg = value;
|
|
146
|
+
return msg.type === "webhook" && typeof msg.eventId === "string" && typeof msg.projectId === "string";
|
|
147
|
+
}
|
|
148
|
+
function coerceInboundBinary(value) {
|
|
149
|
+
if (!value)
|
|
150
|
+
return null;
|
|
151
|
+
if (Buffer.isBuffer(value))
|
|
152
|
+
return value;
|
|
153
|
+
if (value instanceof Uint8Array) {
|
|
154
|
+
return Buffer.from(value.buffer, value.byteOffset, value.byteLength);
|
|
155
|
+
}
|
|
156
|
+
if (value instanceof ArrayBuffer)
|
|
157
|
+
return Buffer.from(value);
|
|
158
|
+
if (ArrayBuffer.isView(value)) {
|
|
159
|
+
return Buffer.from(value.buffer, value.byteOffset, value.byteLength);
|
|
160
|
+
}
|
|
161
|
+
if (typeof value === "object") {
|
|
162
|
+
const maybeBufferLike = value;
|
|
163
|
+
if (maybeBufferLike.type === "Buffer" && Array.isArray(maybeBufferLike.data)) {
|
|
164
|
+
return Buffer.from(maybeBufferLike.data);
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
return null;
|
|
168
|
+
}
|
|
169
|
+
function normalizeWebhookHeaders(value) {
|
|
170
|
+
if (!value || typeof value !== "object")
|
|
171
|
+
return {};
|
|
172
|
+
const out = {};
|
|
173
|
+
for (const [key, raw] of Object.entries(value)) {
|
|
174
|
+
if (typeof raw === "string") {
|
|
175
|
+
out[key] = raw;
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
return out;
|
|
179
|
+
}
|
|
180
|
+
function isParentMessage(value) {
|
|
181
|
+
if (!value || typeof value !== "object")
|
|
182
|
+
return false;
|
|
183
|
+
const msg = value;
|
|
184
|
+
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 === "recording_control_ack" || msg.type === "webhook";
|
|
185
|
+
}
|
|
186
|
+
function isSessionScopedParentMessage(value) {
|
|
187
|
+
return isParentMessage(value) && !isWebhookMessage(value);
|
|
188
|
+
}
|
|
189
|
+
function parseDataChannelPayload(raw) {
|
|
190
|
+
try {
|
|
191
|
+
return JSON.parse(raw);
|
|
192
|
+
} catch {
|
|
193
|
+
return raw;
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
var peerEnvBySessionId = /* @__PURE__ */ new Map();
|
|
197
|
+
var endedSessionIds = /* @__PURE__ */ new Set();
|
|
198
|
+
var pendingRecordingAcks = /* @__PURE__ */ new Map();
|
|
199
|
+
function handleRecordingControlAck(message) {
|
|
200
|
+
const pending = pendingRecordingAcks.get(message.requestId);
|
|
201
|
+
if (!pending)
|
|
202
|
+
return;
|
|
203
|
+
clearTimeout(pending.timer);
|
|
204
|
+
pendingRecordingAcks.delete(message.requestId);
|
|
205
|
+
pending.resolve({
|
|
206
|
+
ok: message.ok,
|
|
207
|
+
reason: message.reason,
|
|
208
|
+
requestId: message.requestId
|
|
209
|
+
});
|
|
210
|
+
}
|
|
211
|
+
function clearPendingRecordingAcksForSession(sessionId, reason) {
|
|
212
|
+
for (const [requestId, pending] of pendingRecordingAcks) {
|
|
213
|
+
if (pending.sessionId !== sessionId)
|
|
214
|
+
continue;
|
|
215
|
+
clearTimeout(pending.timer);
|
|
216
|
+
pendingRecordingAcks.delete(requestId);
|
|
217
|
+
pending.resolve({ ok: false, reason, requestId });
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
var sessionExecutionContext = new AsyncLocalStorage();
|
|
221
|
+
var agentLogSessionContext = new AsyncLocalStorage();
|
|
222
|
+
var inboundQueueAuthority = null;
|
|
223
|
+
var childUnhandledRejectionGuardInstalled = false;
|
|
224
|
+
function normalizeRejectionReason(reason) {
|
|
225
|
+
return reason instanceof Error ? reason : new Error(String(reason));
|
|
226
|
+
}
|
|
227
|
+
function installChildUnhandledRejectionGuard() {
|
|
228
|
+
if (childUnhandledRejectionGuardInstalled) {
|
|
229
|
+
return;
|
|
230
|
+
}
|
|
231
|
+
childUnhandledRejectionGuardInstalled = true;
|
|
232
|
+
process.on("unhandledRejection", (reason) => {
|
|
233
|
+
const err = normalizeRejectionReason(reason);
|
|
234
|
+
const store = sessionExecutionContext.getStore();
|
|
235
|
+
const sessionId = store?.sessionId ?? agentLogSessionContext.getStore() ?? "";
|
|
236
|
+
if (!allowOutboundForSession(sessionId || void 0)) {
|
|
237
|
+
return;
|
|
238
|
+
}
|
|
239
|
+
agentLog("error", `unhandledRejection: ${err.message}`, sessionId || void 0);
|
|
240
|
+
sendParentMessage({
|
|
241
|
+
type: "agent_error",
|
|
242
|
+
sessionId,
|
|
243
|
+
message: err.message,
|
|
244
|
+
stack: err.stack
|
|
245
|
+
});
|
|
246
|
+
});
|
|
247
|
+
}
|
|
248
|
+
function allowOutboundForSession(sessionId) {
|
|
249
|
+
if (!sessionId) {
|
|
250
|
+
return true;
|
|
251
|
+
}
|
|
252
|
+
const store = sessionExecutionContext.getStore();
|
|
253
|
+
const queue = inboundQueueAuthority;
|
|
254
|
+
if (store && store.sessionId === sessionId) {
|
|
255
|
+
if (!queue)
|
|
256
|
+
return !endedSessionIds.has(sessionId);
|
|
257
|
+
return queue.isCurrentGeneration(sessionId, store.generation);
|
|
258
|
+
}
|
|
259
|
+
if (endedSessionIds.has(sessionId))
|
|
260
|
+
return false;
|
|
261
|
+
if (!queue)
|
|
262
|
+
return true;
|
|
263
|
+
return queue.isLive(sessionId);
|
|
264
|
+
}
|
|
265
|
+
function sendParentMessage(message) {
|
|
266
|
+
const sessionId = message && typeof message === "object" && "sessionId" in message && typeof message.sessionId === "string" ? message.sessionId : void 0;
|
|
267
|
+
if (!allowOutboundForSession(sessionId))
|
|
268
|
+
return;
|
|
269
|
+
process.send?.(message);
|
|
270
|
+
}
|
|
271
|
+
function parseBooleanEnv(value, defaultValue) {
|
|
272
|
+
if (value === void 0)
|
|
273
|
+
return defaultValue;
|
|
274
|
+
const normalized = value.trim().toLowerCase();
|
|
275
|
+
if (normalized === "")
|
|
276
|
+
return defaultValue;
|
|
277
|
+
if (["0", "false", "off", "no"].includes(normalized))
|
|
278
|
+
return false;
|
|
279
|
+
if (["1", "true", "on", "yes"].includes(normalized))
|
|
280
|
+
return true;
|
|
281
|
+
return defaultValue;
|
|
282
|
+
}
|
|
283
|
+
function parseNonNegativeIntegerEnv(value, defaultValue) {
|
|
284
|
+
if (value === void 0)
|
|
285
|
+
return defaultValue;
|
|
286
|
+
const parsed = Number(value);
|
|
287
|
+
if (!Number.isFinite(parsed) || parsed < 0)
|
|
288
|
+
return defaultValue;
|
|
289
|
+
return Math.floor(parsed);
|
|
290
|
+
}
|
|
291
|
+
function resolveSessionStartInitDelayMs() {
|
|
292
|
+
const enabled = parseBooleanEnv(process.env[SESSION_START_INIT_DELAY_ENABLED_ENV], true);
|
|
293
|
+
if (!enabled)
|
|
294
|
+
return 0;
|
|
295
|
+
return parseNonNegativeIntegerEnv(process.env[SESSION_START_INIT_DELAY_MS_ENV], DEFAULT_SESSION_START_INIT_DELAY_MS);
|
|
296
|
+
}
|
|
297
|
+
async function handleWebhookMessage(message, handlers) {
|
|
298
|
+
if (!handlers.onWebhook)
|
|
299
|
+
return;
|
|
300
|
+
const body = coerceInboundBinary(message.body);
|
|
301
|
+
if (!body) {
|
|
302
|
+
agentLog("warn", "webhook ipc dropped: body is not binary");
|
|
303
|
+
return;
|
|
304
|
+
}
|
|
305
|
+
const ctx = {
|
|
306
|
+
eventId: message.eventId,
|
|
307
|
+
projectId: message.projectId,
|
|
308
|
+
method: typeof message.method === "string" ? message.method : "POST",
|
|
309
|
+
path: typeof message.path === "string" ? message.path : "",
|
|
310
|
+
headers: normalizeWebhookHeaders(message.headers),
|
|
311
|
+
body,
|
|
312
|
+
contentType: typeof message.contentType === "string" ? message.contentType : null,
|
|
313
|
+
receivedAt: typeof message.receivedAt === "string" ? message.receivedAt : ""
|
|
314
|
+
};
|
|
315
|
+
try {
|
|
316
|
+
const started = Date.now();
|
|
317
|
+
await handlers.onWebhook(ctx);
|
|
318
|
+
sendParentMessage({
|
|
319
|
+
type: "webhook_handled",
|
|
320
|
+
projectId: message.projectId,
|
|
321
|
+
eventId: message.eventId,
|
|
322
|
+
durationMs: Date.now() - started
|
|
323
|
+
});
|
|
324
|
+
} catch (error) {
|
|
325
|
+
const err = error instanceof Error ? error : new Error(String(error));
|
|
326
|
+
await runErrorHook(handlers, {
|
|
327
|
+
sessionId: "",
|
|
328
|
+
projectId: message.projectId,
|
|
329
|
+
env: process.env,
|
|
330
|
+
error: err
|
|
331
|
+
});
|
|
332
|
+
sendParentMessage({
|
|
333
|
+
type: "agent_error",
|
|
334
|
+
sessionId: "",
|
|
335
|
+
message: err.message,
|
|
336
|
+
stack: err.stack
|
|
337
|
+
});
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
async function handleParentMessage(message, handlers) {
|
|
341
|
+
switch (message.type) {
|
|
342
|
+
case "session_start":
|
|
343
|
+
endedSessionIds.delete(message.sessionId);
|
|
344
|
+
peerEnvBySessionId.set(message.sessionId, message.env);
|
|
345
|
+
const sessionStartInitDelayMs = resolveSessionStartInitDelayMs();
|
|
346
|
+
if (sessionStartInitDelayMs > 0) {
|
|
347
|
+
await new Promise((resolve) => setTimeout(resolve, sessionStartInitDelayMs));
|
|
348
|
+
}
|
|
349
|
+
await (handlers.onClientJoin ?? handlers.onSessionStart)?.({
|
|
350
|
+
sessionId: message.sessionId,
|
|
351
|
+
env: message.env,
|
|
352
|
+
recordingAvailable: message.recordingAvailable ?? false
|
|
353
|
+
});
|
|
354
|
+
sendParentMessage({
|
|
355
|
+
type: "session_start_ack",
|
|
356
|
+
sessionId: message.sessionId
|
|
357
|
+
});
|
|
358
|
+
break;
|
|
359
|
+
case "speech_event":
|
|
360
|
+
await handlers.onSpeechEvent?.({ sessionId: message.sessionId }, message.event);
|
|
361
|
+
if (message.event.type === "user_speech_final" && typeof message.event.text === "string" && message.event.text.trim()) {
|
|
362
|
+
await handlers.onUserSpeechFinal?.({
|
|
363
|
+
sessionId: message.sessionId,
|
|
364
|
+
text: message.event.text.trim()
|
|
365
|
+
});
|
|
366
|
+
}
|
|
367
|
+
break;
|
|
368
|
+
case "data_channel_message":
|
|
369
|
+
await handlers.onDataChannelMessage?.({
|
|
370
|
+
sessionId: message.sessionId,
|
|
371
|
+
message: parseDataChannelPayload(message.payload),
|
|
372
|
+
raw: message.payload,
|
|
373
|
+
rawBinary: null,
|
|
374
|
+
channel: "control"
|
|
375
|
+
});
|
|
376
|
+
break;
|
|
377
|
+
case "data_channel_binary":
|
|
378
|
+
await handlers.onDataChannelBinary?.({
|
|
379
|
+
sessionId: message.sessionId,
|
|
380
|
+
message: null,
|
|
381
|
+
raw: null,
|
|
382
|
+
rawBinary: message.data,
|
|
383
|
+
channel: message.channel ?? "sync"
|
|
384
|
+
});
|
|
385
|
+
break;
|
|
386
|
+
case "session_end":
|
|
387
|
+
clearPendingRecordingAcksForSession(message.sessionId, "session_ended");
|
|
388
|
+
peerEnvBySessionId.delete(message.sessionId);
|
|
389
|
+
await (handlers.onClientLeave ?? handlers.onSessionEnd)?.({
|
|
390
|
+
sessionId: message.sessionId
|
|
391
|
+
});
|
|
392
|
+
break;
|
|
393
|
+
case "idle_timeout":
|
|
394
|
+
await runIdleTimeoutHook(handlers, message);
|
|
395
|
+
break;
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
function defineAgent(handlers) {
|
|
399
|
+
installChildUnhandledRejectionGuard();
|
|
400
|
+
const inboundBySession = new SessionSerialQueue();
|
|
401
|
+
inboundQueueAuthority = inboundBySession;
|
|
402
|
+
const agentStartReady = runAgentStartHook(handlers);
|
|
403
|
+
process.on("message", (message) => {
|
|
404
|
+
if (isRecordingControlAckMessage(message)) {
|
|
405
|
+
handleRecordingControlAck(message);
|
|
406
|
+
return;
|
|
407
|
+
}
|
|
408
|
+
if (isWebhookMessage(message)) {
|
|
409
|
+
void agentStartReady.then(() => handleWebhookMessage(message, handlers));
|
|
410
|
+
return;
|
|
411
|
+
}
|
|
412
|
+
if (!isSessionScopedParentMessage(message))
|
|
413
|
+
return;
|
|
414
|
+
if (message.type === "session_end") {
|
|
415
|
+
endedSessionIds.add(message.sessionId);
|
|
416
|
+
clearPendingRecordingAcksForSession(message.sessionId, "session_ended");
|
|
417
|
+
inboundBySession.clear(message.sessionId);
|
|
418
|
+
}
|
|
419
|
+
if (message.type === "session_start") {
|
|
420
|
+
endedSessionIds.delete(message.sessionId);
|
|
421
|
+
inboundBySession.clear(message.sessionId);
|
|
422
|
+
}
|
|
423
|
+
inboundBySession.enqueue(message.sessionId, async (_signal, context) => {
|
|
424
|
+
await agentStartReady;
|
|
425
|
+
try {
|
|
426
|
+
await sessionExecutionContext.run({
|
|
427
|
+
sessionId: message.sessionId,
|
|
428
|
+
generation: context.generation
|
|
429
|
+
}, async () => agentLogSessionContext.run(message.sessionId, async () => {
|
|
430
|
+
try {
|
|
431
|
+
await handleParentMessage(message, handlers);
|
|
432
|
+
} catch (error) {
|
|
433
|
+
const err = error instanceof Error ? error : new Error(String(error));
|
|
434
|
+
const env = peerEnvBySessionId.get(message.sessionId) ?? buildIdleEnv(message.sessionId);
|
|
435
|
+
await runErrorHook(handlers, {
|
|
436
|
+
sessionId: message.sessionId,
|
|
437
|
+
projectId: env.PROJECT_ID,
|
|
438
|
+
buildId: env.BUILD_ID,
|
|
439
|
+
env,
|
|
440
|
+
error: err,
|
|
441
|
+
customerContext: parseCustomerContext(env.AGENT_CUSTOMER_CONTEXT)
|
|
442
|
+
});
|
|
443
|
+
sendParentMessage({
|
|
444
|
+
type: "agent_error",
|
|
445
|
+
sessionId: message.sessionId,
|
|
446
|
+
message: err.message,
|
|
447
|
+
stack: err.stack
|
|
448
|
+
});
|
|
449
|
+
}
|
|
450
|
+
}));
|
|
451
|
+
} finally {
|
|
452
|
+
if (message.type === "session_end" && inboundBySession.isCurrentGeneration(message.sessionId, context.generation)) {
|
|
453
|
+
inboundBySession.clear(message.sessionId);
|
|
454
|
+
}
|
|
455
|
+
}
|
|
456
|
+
});
|
|
457
|
+
});
|
|
458
|
+
}
|
|
459
|
+
async function runAgentStartHook(handlers) {
|
|
460
|
+
if (!handlers.onAgentStart)
|
|
461
|
+
return;
|
|
462
|
+
try {
|
|
463
|
+
await handlers.onAgentStart({
|
|
464
|
+
env: process.env
|
|
465
|
+
});
|
|
466
|
+
} catch (error) {
|
|
467
|
+
const err = error instanceof Error ? error : new Error(String(error));
|
|
468
|
+
agentLog("error", `onAgentStart failed: ${err.message}`);
|
|
469
|
+
sendParentMessage({
|
|
470
|
+
type: "agent_error",
|
|
471
|
+
sessionId: "",
|
|
472
|
+
message: err.message,
|
|
473
|
+
stack: err.stack
|
|
474
|
+
});
|
|
475
|
+
}
|
|
476
|
+
}
|
|
477
|
+
function parseCustomerContext(raw) {
|
|
478
|
+
if (!raw?.trim())
|
|
479
|
+
return void 0;
|
|
480
|
+
try {
|
|
481
|
+
const parsed = JSON.parse(raw);
|
|
482
|
+
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
|
|
483
|
+
return parsed;
|
|
484
|
+
}
|
|
485
|
+
} catch {
|
|
486
|
+
}
|
|
487
|
+
return void 0;
|
|
488
|
+
}
|
|
489
|
+
async function runErrorHook(handlers, ctx) {
|
|
490
|
+
if (!handlers.errorHook)
|
|
491
|
+
return;
|
|
492
|
+
try {
|
|
493
|
+
await handlers.errorHook(ctx);
|
|
494
|
+
} catch (hookError) {
|
|
495
|
+
const message = hookError instanceof Error ? hookError.message : String(hookError);
|
|
496
|
+
agentLog("error", `errorHook failed: ${message}`, ctx.sessionId);
|
|
497
|
+
}
|
|
498
|
+
}
|
|
499
|
+
async function runIdleTimeoutHook(handlers, message) {
|
|
500
|
+
const onIdleTimeout = handlers.onIdleTimeout;
|
|
501
|
+
agentLog("info", `idle_timeout ipc received (maxGraceMs=${message.maxGraceMs}, onIdleTimeout=${typeof onIdleTimeout === "function"})`, message.sessionId);
|
|
502
|
+
if (!onIdleTimeout) {
|
|
503
|
+
sendParentMessage({
|
|
504
|
+
type: "idle_timeout_done",
|
|
505
|
+
sessionId: message.sessionId
|
|
506
|
+
});
|
|
507
|
+
agentLog("info", "idle_timeout_done ipc sent (no onIdleTimeout handler)", message.sessionId);
|
|
508
|
+
return;
|
|
509
|
+
}
|
|
510
|
+
const env = peerEnvBySessionId.get(message.sessionId) ?? buildIdleEnv(message.sessionId);
|
|
511
|
+
const idleTimeoutSeconds = Number(env.IDLE_TIMEOUT_SEC) || 0;
|
|
512
|
+
const ctx = {
|
|
513
|
+
sessionId: message.sessionId,
|
|
514
|
+
projectId: env.PROJECT_ID,
|
|
515
|
+
buildId: env.BUILD_ID,
|
|
516
|
+
env,
|
|
517
|
+
idleTimeoutSeconds
|
|
518
|
+
};
|
|
519
|
+
let error;
|
|
520
|
+
try {
|
|
521
|
+
await onIdleTimeout(ctx);
|
|
522
|
+
} catch (hookError) {
|
|
523
|
+
error = hookError instanceof Error ? hookError.message : String(hookError);
|
|
524
|
+
agentLog("error", `onIdleTimeout failed: ${error}`, message.sessionId);
|
|
525
|
+
}
|
|
526
|
+
sendParentMessage({
|
|
527
|
+
type: "idle_timeout_done",
|
|
528
|
+
sessionId: message.sessionId,
|
|
529
|
+
error
|
|
530
|
+
});
|
|
531
|
+
agentLog("info", error ? `idle_timeout_done ipc sent (onIdleTimeout error: ${error})` : "idle_timeout_done ipc sent (onIdleTimeout completed)", message.sessionId);
|
|
532
|
+
}
|
|
533
|
+
function buildIdleEnv(sessionId) {
|
|
534
|
+
return {
|
|
535
|
+
SESSION_ID: sessionId,
|
|
536
|
+
...process.env.PROJECT_ID ? { PROJECT_ID: process.env.PROJECT_ID } : {},
|
|
537
|
+
...process.env.BUILD_ID ? { BUILD_ID: process.env.BUILD_ID } : {},
|
|
538
|
+
...process.env.IDLE_TIMEOUT_SEC ? { IDLE_TIMEOUT_SEC: process.env.IDLE_TIMEOUT_SEC } : {}
|
|
539
|
+
};
|
|
540
|
+
}
|
|
541
|
+
function speak(sessionId, text) {
|
|
542
|
+
sendParentMessage({ type: "speak", sessionId, text });
|
|
543
|
+
}
|
|
544
|
+
function sendToClient(sessionId, payload) {
|
|
545
|
+
sendParentMessage({ type: "send_to_client", sessionId, payload });
|
|
546
|
+
}
|
|
547
|
+
function broadcastToClients(payload, sessionIds) {
|
|
548
|
+
for (const sessionId of sessionIds) {
|
|
549
|
+
sendToClient(sessionId, payload);
|
|
550
|
+
}
|
|
551
|
+
}
|
|
552
|
+
var AGENT_LOG_MESSAGE_MAX_CHARS = 2048;
|
|
553
|
+
var AGENT_LOG_FIELDS_MAX_CHARS = 8192;
|
|
554
|
+
function truncateAgentLogMessage(message) {
|
|
555
|
+
if (message.length <= AGENT_LOG_MESSAGE_MAX_CHARS) {
|
|
556
|
+
return message;
|
|
557
|
+
}
|
|
558
|
+
const suffix = "\u2026[truncated]";
|
|
559
|
+
return message.slice(0, AGENT_LOG_MESSAGE_MAX_CHARS - suffix.length) + suffix;
|
|
560
|
+
}
|
|
561
|
+
function isPlainObject(value) {
|
|
562
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
563
|
+
}
|
|
564
|
+
function sanitizeAgentLogFields(fields) {
|
|
565
|
+
if (Object.keys(fields).length === 0) {
|
|
566
|
+
return void 0;
|
|
567
|
+
}
|
|
568
|
+
try {
|
|
569
|
+
const serialized = JSON.stringify(fields);
|
|
570
|
+
if (serialized.length <= AGENT_LOG_FIELDS_MAX_CHARS) {
|
|
571
|
+
return fields;
|
|
572
|
+
}
|
|
573
|
+
return {
|
|
574
|
+
_agentLogFieldsTruncated: true,
|
|
575
|
+
_originalBytes: serialized.length,
|
|
576
|
+
_preview: serialized.slice(0, AGENT_LOG_FIELDS_MAX_CHARS - 80) + "\u2026[truncated]"
|
|
577
|
+
};
|
|
578
|
+
} catch {
|
|
579
|
+
return { _agentLogFieldsError: "not_serializable" };
|
|
580
|
+
}
|
|
581
|
+
}
|
|
582
|
+
function buildAgentLogPayload(level, message, fields, sessionId) {
|
|
583
|
+
const resolvedSessionId = sessionId ?? sessionExecutionContext.getStore()?.sessionId ?? agentLogSessionContext.getStore();
|
|
584
|
+
const sanitizedFields = fields ? sanitizeAgentLogFields(fields) : void 0;
|
|
585
|
+
return {
|
|
586
|
+
type: "log",
|
|
587
|
+
level,
|
|
588
|
+
message: truncateAgentLogMessage(message),
|
|
589
|
+
ts: Date.now(),
|
|
590
|
+
...resolvedSessionId ? { sessionId: resolvedSessionId } : {},
|
|
591
|
+
...sanitizedFields ? { fields: sanitizedFields } : {}
|
|
592
|
+
};
|
|
593
|
+
}
|
|
594
|
+
function agentLog(level, message, fieldsOrSessionId, sessionId) {
|
|
595
|
+
let fields;
|
|
596
|
+
let resolvedSessionId;
|
|
597
|
+
if (typeof fieldsOrSessionId === "string") {
|
|
598
|
+
resolvedSessionId = fieldsOrSessionId;
|
|
599
|
+
} else if (isPlainObject(fieldsOrSessionId)) {
|
|
600
|
+
fields = fieldsOrSessionId;
|
|
601
|
+
resolvedSessionId = sessionId;
|
|
602
|
+
} else {
|
|
603
|
+
resolvedSessionId = sessionId;
|
|
604
|
+
}
|
|
605
|
+
sendParentMessage(buildAgentLogPayload(level, message, fields, resolvedSessionId));
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
// templates/webhooks.ts
|
|
609
|
+
var WEBHOOK_SIGNATURE_HEADER = "x-agent-webhook-signature";
|
|
610
|
+
var connectedSessions = /* @__PURE__ */ new Set();
|
|
611
|
+
function verifyWebhookSignature(body, headers, secret) {
|
|
612
|
+
const received = headers[WEBHOOK_SIGNATURE_HEADER] ?? headers[WEBHOOK_SIGNATURE_HEADER.toUpperCase()];
|
|
613
|
+
if (!received?.trim()) {
|
|
614
|
+
return false;
|
|
615
|
+
}
|
|
616
|
+
const expected = createHmac("sha256", secret).update(body).digest("hex");
|
|
617
|
+
try {
|
|
618
|
+
const actual = Buffer.from(received.trim(), "hex");
|
|
619
|
+
const want = Buffer.from(expected, "hex");
|
|
620
|
+
return actual.length === want.length && timingSafeEqual(actual, want);
|
|
621
|
+
} catch {
|
|
622
|
+
return false;
|
|
623
|
+
}
|
|
624
|
+
}
|
|
625
|
+
defineAgent({
|
|
626
|
+
onSessionStart({ sessionId }) {
|
|
627
|
+
connectedSessions.add(sessionId);
|
|
628
|
+
},
|
|
629
|
+
onSessionEnd({ sessionId }) {
|
|
630
|
+
connectedSessions.delete(sessionId);
|
|
631
|
+
},
|
|
632
|
+
async onWebhook(ctx) {
|
|
633
|
+
const secret = process.env.AGENT_WEBHOOK_SIGNING_SECRET?.trim();
|
|
634
|
+
if (!secret) {
|
|
635
|
+
agentLog("warn", "webhook ignored: AGENT_WEBHOOK_SIGNING_SECRET unset");
|
|
636
|
+
return;
|
|
637
|
+
}
|
|
638
|
+
if (!verifyWebhookSignature(ctx.body, ctx.headers, secret)) {
|
|
639
|
+
agentLog("warn", `webhook signature invalid eventId=${ctx.eventId}`);
|
|
640
|
+
return;
|
|
641
|
+
}
|
|
642
|
+
let payload;
|
|
643
|
+
try {
|
|
644
|
+
payload = JSON.parse(ctx.body.toString("utf8"));
|
|
645
|
+
} catch {
|
|
646
|
+
agentLog("warn", `webhook body is not JSON eventId=${ctx.eventId}`);
|
|
647
|
+
return;
|
|
648
|
+
}
|
|
649
|
+
const record = payload && typeof payload === "object" ? payload : null;
|
|
650
|
+
const messageType = record?.type ?? "webhook";
|
|
651
|
+
const text = typeof record?.text === "string" && record.text.trim() ? record.text.trim() : `webhook:${messageType}`;
|
|
652
|
+
const sessionIds = [...connectedSessions];
|
|
653
|
+
if (sessionIds.length === 0) {
|
|
654
|
+
agentLog("info", `webhook verified with no live sessions eventId=${ctx.eventId}`);
|
|
655
|
+
return;
|
|
656
|
+
}
|
|
657
|
+
broadcastToClients(
|
|
658
|
+
{
|
|
659
|
+
type: "webhook_event",
|
|
660
|
+
eventId: ctx.eventId,
|
|
661
|
+
path: ctx.path,
|
|
662
|
+
payload
|
|
663
|
+
},
|
|
664
|
+
sessionIds
|
|
665
|
+
);
|
|
666
|
+
for (const sessionId of sessionIds) {
|
|
667
|
+
speak(sessionId, text);
|
|
668
|
+
}
|
|
669
|
+
agentLog(
|
|
670
|
+
"info",
|
|
671
|
+
`webhook delivered to ${sessionIds.length} session(s) eventId=${ctx.eventId}`
|
|
672
|
+
);
|
|
673
|
+
}
|
|
674
|
+
});
|