@voicethere/agent 0.7.13 → 0.8.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 +14 -3
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/runtime.d.ts.map +1 -1
- package/dist/runtime.js +11 -2
- package/dist/runtime.js.map +1 -1
- package/dist/templates/echo/agent.js +1 -1
- package/dist/templates/echo-dc/agent.js +1 -1
- package/dist/templates/game-sync/agent.js +162 -125
- package/dist/templates/registry.d.ts +1 -1
- package/dist/templates/registry.d.ts.map +1 -1
- package/dist/templates/registry.js +42 -26
- package/dist/templates/registry.js.map +1 -1
- package/dist/templates/voice-starter/agent.js +1 -1
- package/dist/templates/webhooks/agent.js +2 -2
- package/dist/templates/webhooks-redis/agent.js +11 -4
- package/dist/templates/world-sync/agent.js +829 -0
- package/dist/templates/world-sync-binary/agent.js +1031 -0
- package/package.json +3 -2
- package/templates/README.md +41 -69
- package/templates/crash/README.md +13 -0
- package/templates/echo/README.md +13 -0
- package/templates/{echo.ts → echo/agent.ts} +1 -1
- package/templates/echo-dc/README.md +13 -0
- package/templates/{echo-dc.ts → echo-dc/agent.ts} +1 -1
- package/templates/echo-smoke/README.md +13 -0
- package/templates/game-sync/README.md +21 -0
- package/templates/{game-sync.ts → game-sync/agent.ts} +126 -94
- package/templates/{game-sync-redis.ts → game-sync/redis.ts} +4 -13
- package/templates/{game-sync-sim.ts → game-sync/sim.ts} +14 -7
- package/templates/{game-sync-world-layout.ts → game-sync/world-layout.ts} +72 -30
- package/templates/game-sync-smoke/README.md +13 -0
- package/templates/mix-smoke/README.md +13 -0
- package/templates/positional-tts/README.md +13 -0
- package/templates/recording-consent/README.md +13 -0
- package/templates/redis-sync/README.md +23 -0
- package/templates/redis-sync/agent.ts +72 -95
- package/templates/redis-sync/world-layout.ts +103 -26
- package/templates/spatial-showcase/README.md +13 -0
- package/templates/voice-showcase/README.md +13 -0
- package/templates/voice-starter/README.md +13 -0
- package/templates/webhooks/README.md +13 -0
- package/templates/{webhooks.ts → webhooks/agent.ts} +1 -1
- package/templates/webhooks-redis/README.md +13 -0
- package/templates/{webhooks-redis.ts → webhooks-redis/agent.ts} +9 -9
- package/templates/world-sync/README.md +20 -0
- package/templates/world-sync/agent.ts +62 -0
- package/templates/world-sync-binary/README.md +21 -0
- package/templates/world-sync-binary/agent.ts +107 -0
- package/templates/world-sync-binary/protocol.ts +281 -0
- /package/templates/{crash.ts → crash/agent.ts} +0 -0
- /package/templates/{echo-smoke.ts → echo-smoke/agent.ts} +0 -0
- /package/templates/{game-sync-protocol.ts → game-sync/protocol.ts} +0 -0
- /package/templates/{game-sync-smoke.ts → game-sync-smoke/agent.ts} +0 -0
- /package/templates/{mix-smoke.ts → mix-smoke/agent.ts} +0 -0
- /package/templates/{agent.ts → voice-starter/agent.ts} +0 -0
|
@@ -0,0 +1,1031 @@
|
|
|
1
|
+
import { createRequire } from "node:module";
|
|
2
|
+
const require = createRequire(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/session-serial-queue.js
|
|
10
|
+
var SessionSerialQueueCancellationError = class extends Error {
|
|
11
|
+
sessionId;
|
|
12
|
+
generation;
|
|
13
|
+
code = "SESSION_SERIAL_QUEUE_CANCELLED";
|
|
14
|
+
constructor(sessionId, generation) {
|
|
15
|
+
super(`session serial queue cancelled (sessionId=${sessionId}, generation=${generation})`);
|
|
16
|
+
this.sessionId = sessionId;
|
|
17
|
+
this.generation = generation;
|
|
18
|
+
this.name = "SessionSerialQueueCancellationError";
|
|
19
|
+
}
|
|
20
|
+
};
|
|
21
|
+
var SessionSerialQueue = class {
|
|
22
|
+
sessions = /* @__PURE__ */ new Map();
|
|
23
|
+
/** Monotonic token source — never reused across clear/enqueue cycles. */
|
|
24
|
+
nextGeneration = 1;
|
|
25
|
+
/**
|
|
26
|
+
* Enqueue work for `sessionId`. Returns a promise that settles when this
|
|
27
|
+
* task finishes, is skipped as stale, or is cancelled by {@link clear}.
|
|
28
|
+
* Fire-and-forget callers may ignore the return value (compat).
|
|
29
|
+
*/
|
|
30
|
+
enqueue(sessionId, task) {
|
|
31
|
+
const state = this.ensureState(sessionId);
|
|
32
|
+
const captured = state;
|
|
33
|
+
const generation = captured.generation;
|
|
34
|
+
captured.pending += 1;
|
|
35
|
+
const previous = captured.tail;
|
|
36
|
+
let taskAbort = null;
|
|
37
|
+
const settled = previous.catch(() => void 0).then(async () => {
|
|
38
|
+
if (this.sessions.get(sessionId) !== captured) {
|
|
39
|
+
return "cancelled";
|
|
40
|
+
}
|
|
41
|
+
const abort = new AbortController();
|
|
42
|
+
taskAbort = abort;
|
|
43
|
+
captured.abort = abort;
|
|
44
|
+
const context = {
|
|
45
|
+
sessionId,
|
|
46
|
+
generation,
|
|
47
|
+
signal: abort.signal
|
|
48
|
+
};
|
|
49
|
+
try {
|
|
50
|
+
await Promise.resolve(task(abort.signal, context));
|
|
51
|
+
if (this.sessions.get(sessionId) !== captured) {
|
|
52
|
+
return "cancelled";
|
|
53
|
+
}
|
|
54
|
+
return "completed";
|
|
55
|
+
} catch (error) {
|
|
56
|
+
if (abort.signal.aborted || this.sessions.get(sessionId) !== captured || error instanceof SessionSerialQueueCancellationError) {
|
|
57
|
+
return "cancelled";
|
|
58
|
+
}
|
|
59
|
+
return "failed";
|
|
60
|
+
} finally {
|
|
61
|
+
if (captured.abort === abort) {
|
|
62
|
+
captured.abort = null;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
}).finally(() => {
|
|
66
|
+
captured.pending = Math.max(0, captured.pending - 1);
|
|
67
|
+
if (taskAbort && captured.abort === taskAbort) {
|
|
68
|
+
captured.abort = null;
|
|
69
|
+
}
|
|
70
|
+
});
|
|
71
|
+
captured.tail = settled;
|
|
72
|
+
return settled;
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Invalidate queued + running work for `sessionId`. Aborts the live AbortSignal,
|
|
76
|
+
* drops the map entry, and leaves a fresh identity for the next enqueue.
|
|
77
|
+
* Old in-flight `finally` blocks only touch their captured state object.
|
|
78
|
+
*/
|
|
79
|
+
clear(sessionId) {
|
|
80
|
+
const old = this.sessions.get(sessionId);
|
|
81
|
+
if (!old)
|
|
82
|
+
return;
|
|
83
|
+
old.abort?.abort();
|
|
84
|
+
old.abort = null;
|
|
85
|
+
this.sessions.delete(sessionId);
|
|
86
|
+
}
|
|
87
|
+
clearAll() {
|
|
88
|
+
for (const sessionId of [...this.sessions.keys()]) {
|
|
89
|
+
this.clear(sessionId);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
hasPending(sessionId) {
|
|
93
|
+
return (this.sessions.get(sessionId)?.pending ?? 0) > 0;
|
|
94
|
+
}
|
|
95
|
+
/** Live generation token for a session, or `undefined` when cleared. */
|
|
96
|
+
generationOf(sessionId) {
|
|
97
|
+
return this.sessions.get(sessionId)?.generation;
|
|
98
|
+
}
|
|
99
|
+
/** True when `generation` is the live map entry for `sessionId`. */
|
|
100
|
+
isCurrentGeneration(sessionId, generation) {
|
|
101
|
+
return this.sessions.get(sessionId)?.generation === generation;
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* True when a queue row exists for the session (registered since first
|
|
105
|
+
* enqueue, until {@link clear}). Not the same as {@link hasPending}.
|
|
106
|
+
*/
|
|
107
|
+
isLive(sessionId) {
|
|
108
|
+
return this.sessions.has(sessionId);
|
|
109
|
+
}
|
|
110
|
+
/** Registered session rows (must not grow without matching `clear` calls). */
|
|
111
|
+
get activeSessionCount() {
|
|
112
|
+
return this.sessions.size;
|
|
113
|
+
}
|
|
114
|
+
ensureState(sessionId) {
|
|
115
|
+
const existing = this.sessions.get(sessionId);
|
|
116
|
+
if (existing)
|
|
117
|
+
return existing;
|
|
118
|
+
const created = {
|
|
119
|
+
generation: this.nextGeneration++,
|
|
120
|
+
tail: Promise.resolve(),
|
|
121
|
+
abort: null,
|
|
122
|
+
pending: 0
|
|
123
|
+
};
|
|
124
|
+
this.sessions.set(sessionId, created);
|
|
125
|
+
return created;
|
|
126
|
+
}
|
|
127
|
+
};
|
|
128
|
+
|
|
129
|
+
// dist/runtime.js
|
|
130
|
+
var SESSION_START_INIT_DELAY_ENABLED_ENV = "AGENT_SESSION_START_INIT_DELAY_ENABLED";
|
|
131
|
+
var SESSION_START_INIT_DELAY_MS_ENV = "AGENT_SESSION_START_INIT_DELAY_MS";
|
|
132
|
+
var DEFAULT_SESSION_START_INIT_DELAY_MS = 500;
|
|
133
|
+
function isPlayAckMessage(value) {
|
|
134
|
+
if (!value || typeof value !== "object")
|
|
135
|
+
return false;
|
|
136
|
+
const msg = value;
|
|
137
|
+
return msg.type === "play_ack" && typeof msg.requestId === "string";
|
|
138
|
+
}
|
|
139
|
+
function isPlayStatusAckMessage(value) {
|
|
140
|
+
if (!value || typeof value !== "object")
|
|
141
|
+
return false;
|
|
142
|
+
const msg = value;
|
|
143
|
+
return msg.type === "play_status_ack" && typeof msg.requestId === "string";
|
|
144
|
+
}
|
|
145
|
+
function isPlayStopAckMessage(value) {
|
|
146
|
+
if (!value || typeof value !== "object")
|
|
147
|
+
return false;
|
|
148
|
+
const msg = value;
|
|
149
|
+
return msg.type === "play_stop_ack" && typeof msg.requestId === "string";
|
|
150
|
+
}
|
|
151
|
+
function isPlayPoseAckMessage(value) {
|
|
152
|
+
if (!value || typeof value !== "object")
|
|
153
|
+
return false;
|
|
154
|
+
const msg = value;
|
|
155
|
+
return msg.type === "play_pose_ack" && typeof msg.requestId === "string";
|
|
156
|
+
}
|
|
157
|
+
function isRecordingControlAckMessage(value) {
|
|
158
|
+
if (!value || typeof value !== "object")
|
|
159
|
+
return false;
|
|
160
|
+
const msg = value;
|
|
161
|
+
return msg.type === "recording_control_ack" && typeof msg.requestId === "string";
|
|
162
|
+
}
|
|
163
|
+
function isMixControlAckMessage(value) {
|
|
164
|
+
if (!value || typeof value !== "object")
|
|
165
|
+
return false;
|
|
166
|
+
const msg = value;
|
|
167
|
+
return msg.type === "mix_control_ack" && typeof msg.requestId === "string";
|
|
168
|
+
}
|
|
169
|
+
function isSttControlAckMessage(value) {
|
|
170
|
+
if (!value || typeof value !== "object")
|
|
171
|
+
return false;
|
|
172
|
+
const msg = value;
|
|
173
|
+
return msg.type === "stt_control_ack" && typeof msg.requestId === "string";
|
|
174
|
+
}
|
|
175
|
+
function isWebhookMessage(value) {
|
|
176
|
+
if (!value || typeof value !== "object")
|
|
177
|
+
return false;
|
|
178
|
+
const msg = value;
|
|
179
|
+
return msg.type === "webhook" && typeof msg.eventId === "string" && typeof msg.projectId === "string";
|
|
180
|
+
}
|
|
181
|
+
function coerceInboundBinary(value) {
|
|
182
|
+
if (!value)
|
|
183
|
+
return null;
|
|
184
|
+
if (Buffer.isBuffer(value))
|
|
185
|
+
return value;
|
|
186
|
+
if (value instanceof Uint8Array) {
|
|
187
|
+
return Buffer.from(value.buffer, value.byteOffset, value.byteLength);
|
|
188
|
+
}
|
|
189
|
+
if (value instanceof ArrayBuffer)
|
|
190
|
+
return Buffer.from(value);
|
|
191
|
+
if (ArrayBuffer.isView(value)) {
|
|
192
|
+
return Buffer.from(value.buffer, value.byteOffset, value.byteLength);
|
|
193
|
+
}
|
|
194
|
+
if (typeof value === "object") {
|
|
195
|
+
const maybeBufferLike = value;
|
|
196
|
+
if (maybeBufferLike.type === "Buffer" && Array.isArray(maybeBufferLike.data)) {
|
|
197
|
+
return Buffer.from(maybeBufferLike.data);
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
return null;
|
|
201
|
+
}
|
|
202
|
+
function normalizeWebhookHeaders(value) {
|
|
203
|
+
if (!value || typeof value !== "object")
|
|
204
|
+
return {};
|
|
205
|
+
const out = {};
|
|
206
|
+
for (const [key, raw] of Object.entries(value)) {
|
|
207
|
+
if (typeof raw === "string") {
|
|
208
|
+
out[key] = raw;
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
return out;
|
|
212
|
+
}
|
|
213
|
+
function isParentMessage(value) {
|
|
214
|
+
if (!value || typeof value !== "object")
|
|
215
|
+
return false;
|
|
216
|
+
const msg = value;
|
|
217
|
+
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 === "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 === "webhook";
|
|
218
|
+
}
|
|
219
|
+
function isSessionScopedParentMessage(value) {
|
|
220
|
+
return isParentMessage(value) && !isWebhookMessage(value);
|
|
221
|
+
}
|
|
222
|
+
function parseDataChannelPayload(raw) {
|
|
223
|
+
try {
|
|
224
|
+
return JSON.parse(raw);
|
|
225
|
+
} catch {
|
|
226
|
+
return raw;
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
var peerEnvBySessionId = /* @__PURE__ */ new Map();
|
|
230
|
+
var recordingAvailableBySessionId = /* @__PURE__ */ new Map();
|
|
231
|
+
var mixAvailableBySessionId = /* @__PURE__ */ new Map();
|
|
232
|
+
var ttsPoseAvailableBySessionId = /* @__PURE__ */ new Map();
|
|
233
|
+
var endedSessionIds = /* @__PURE__ */ new Set();
|
|
234
|
+
var PLAY_BYTES_MAX_DECODED_LENGTH = 64 * 1024;
|
|
235
|
+
var pendingRecordingAcks = /* @__PURE__ */ new Map();
|
|
236
|
+
var pendingPlayAcks = /* @__PURE__ */ new Map();
|
|
237
|
+
var pendingPlayStatusAcks = /* @__PURE__ */ new Map();
|
|
238
|
+
var pendingPlayStopAcks = /* @__PURE__ */ new Map();
|
|
239
|
+
var pendingPlayPoseAcks = /* @__PURE__ */ new Map();
|
|
240
|
+
var pendingMixAcks = /* @__PURE__ */ new Map();
|
|
241
|
+
var pendingSttAcks = /* @__PURE__ */ new Map();
|
|
242
|
+
function handleRecordingControlAck(message) {
|
|
243
|
+
const pending = pendingRecordingAcks.get(message.requestId);
|
|
244
|
+
if (!pending)
|
|
245
|
+
return;
|
|
246
|
+
clearTimeout(pending.timer);
|
|
247
|
+
pendingRecordingAcks.delete(message.requestId);
|
|
248
|
+
pending.resolve({
|
|
249
|
+
ok: message.ok,
|
|
250
|
+
reason: message.reason,
|
|
251
|
+
requestId: message.requestId
|
|
252
|
+
});
|
|
253
|
+
}
|
|
254
|
+
function handlePlayAck(message) {
|
|
255
|
+
const pending = pendingPlayAcks.get(message.requestId);
|
|
256
|
+
if (!pending)
|
|
257
|
+
return;
|
|
258
|
+
clearTimeout(pending.timer);
|
|
259
|
+
pendingPlayAcks.delete(message.requestId);
|
|
260
|
+
pending.resolve({
|
|
261
|
+
ok: message.ok,
|
|
262
|
+
...message.playId ? { playId: message.playId } : {},
|
|
263
|
+
reason: message.reason,
|
|
264
|
+
requestId: message.requestId
|
|
265
|
+
});
|
|
266
|
+
}
|
|
267
|
+
function handlePlayStatusAck(message) {
|
|
268
|
+
const pending = pendingPlayStatusAcks.get(message.requestId);
|
|
269
|
+
if (!pending)
|
|
270
|
+
return;
|
|
271
|
+
clearTimeout(pending.timer);
|
|
272
|
+
pendingPlayStatusAcks.delete(message.requestId);
|
|
273
|
+
pending.resolve({
|
|
274
|
+
ok: message.ok,
|
|
275
|
+
playId: message.playId,
|
|
276
|
+
...message.status ? { status: message.status } : {},
|
|
277
|
+
reason: message.reason,
|
|
278
|
+
requestId: message.requestId
|
|
279
|
+
});
|
|
280
|
+
}
|
|
281
|
+
function handlePlayStopAck(message) {
|
|
282
|
+
const pending = pendingPlayStopAcks.get(message.requestId);
|
|
283
|
+
if (!pending)
|
|
284
|
+
return;
|
|
285
|
+
clearTimeout(pending.timer);
|
|
286
|
+
pendingPlayStopAcks.delete(message.requestId);
|
|
287
|
+
pending.resolve({
|
|
288
|
+
ok: message.ok,
|
|
289
|
+
playId: message.playId,
|
|
290
|
+
reason: message.reason,
|
|
291
|
+
requestId: message.requestId
|
|
292
|
+
});
|
|
293
|
+
}
|
|
294
|
+
function handlePlayPoseAck(message) {
|
|
295
|
+
const pending = pendingPlayPoseAcks.get(message.requestId);
|
|
296
|
+
if (!pending)
|
|
297
|
+
return;
|
|
298
|
+
clearTimeout(pending.timer);
|
|
299
|
+
pendingPlayPoseAcks.delete(message.requestId);
|
|
300
|
+
pending.resolve({
|
|
301
|
+
ok: message.ok,
|
|
302
|
+
playId: message.playId,
|
|
303
|
+
reason: message.reason,
|
|
304
|
+
requestId: message.requestId
|
|
305
|
+
});
|
|
306
|
+
}
|
|
307
|
+
function handleMixControlAck(message) {
|
|
308
|
+
const pending = pendingMixAcks.get(message.requestId);
|
|
309
|
+
if (!pending)
|
|
310
|
+
return;
|
|
311
|
+
clearTimeout(pending.timer);
|
|
312
|
+
pendingMixAcks.delete(message.requestId);
|
|
313
|
+
pending.resolve({
|
|
314
|
+
ok: message.ok,
|
|
315
|
+
reason: message.reason,
|
|
316
|
+
requestId: message.requestId,
|
|
317
|
+
...message.statuses ? { statuses: message.statuses } : {}
|
|
318
|
+
});
|
|
319
|
+
}
|
|
320
|
+
function handleSttControlAck(message) {
|
|
321
|
+
const pending = pendingSttAcks.get(message.requestId);
|
|
322
|
+
if (!pending)
|
|
323
|
+
return;
|
|
324
|
+
clearTimeout(pending.timer);
|
|
325
|
+
pendingSttAcks.delete(message.requestId);
|
|
326
|
+
pending.resolve({
|
|
327
|
+
ok: message.ok,
|
|
328
|
+
reason: message.reason,
|
|
329
|
+
requestId: message.requestId
|
|
330
|
+
});
|
|
331
|
+
}
|
|
332
|
+
function clearPendingRecordingAcksForSession(sessionId, reason) {
|
|
333
|
+
for (const [requestId, pending] of pendingRecordingAcks) {
|
|
334
|
+
if (pending.sessionId !== sessionId)
|
|
335
|
+
continue;
|
|
336
|
+
clearTimeout(pending.timer);
|
|
337
|
+
pendingRecordingAcks.delete(requestId);
|
|
338
|
+
pending.resolve({ ok: false, reason, requestId });
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
var sessionExecutionContext = new AsyncLocalStorage();
|
|
342
|
+
var agentLogSessionContext = new AsyncLocalStorage();
|
|
343
|
+
var inboundQueueAuthority = null;
|
|
344
|
+
var childUnhandledRejectionGuardInstalled = false;
|
|
345
|
+
function normalizeRejectionReason(reason) {
|
|
346
|
+
return reason instanceof Error ? reason : new Error(String(reason));
|
|
347
|
+
}
|
|
348
|
+
function installChildUnhandledRejectionGuard() {
|
|
349
|
+
if (childUnhandledRejectionGuardInstalled) {
|
|
350
|
+
return;
|
|
351
|
+
}
|
|
352
|
+
childUnhandledRejectionGuardInstalled = true;
|
|
353
|
+
process.on("unhandledRejection", (reason) => {
|
|
354
|
+
const err = normalizeRejectionReason(reason);
|
|
355
|
+
const store = sessionExecutionContext.getStore();
|
|
356
|
+
const sessionId = store?.sessionId ?? agentLogSessionContext.getStore() ?? "";
|
|
357
|
+
if (!allowOutboundForSession(sessionId || void 0)) {
|
|
358
|
+
return;
|
|
359
|
+
}
|
|
360
|
+
agentLog("error", `unhandledRejection: ${err.message}`, sessionId || void 0);
|
|
361
|
+
sendParentMessage({
|
|
362
|
+
type: "agent_error",
|
|
363
|
+
sessionId,
|
|
364
|
+
message: err.message,
|
|
365
|
+
stack: err.stack
|
|
366
|
+
});
|
|
367
|
+
});
|
|
368
|
+
}
|
|
369
|
+
function allowOutboundForSession(sessionId) {
|
|
370
|
+
if (!sessionId) {
|
|
371
|
+
return true;
|
|
372
|
+
}
|
|
373
|
+
const store = sessionExecutionContext.getStore();
|
|
374
|
+
const queue = inboundQueueAuthority;
|
|
375
|
+
if (store && store.sessionId === sessionId) {
|
|
376
|
+
if (!queue)
|
|
377
|
+
return !endedSessionIds.has(sessionId);
|
|
378
|
+
return queue.isCurrentGeneration(sessionId, store.generation);
|
|
379
|
+
}
|
|
380
|
+
if (endedSessionIds.has(sessionId))
|
|
381
|
+
return false;
|
|
382
|
+
if (!queue)
|
|
383
|
+
return true;
|
|
384
|
+
return queue.isLive(sessionId);
|
|
385
|
+
}
|
|
386
|
+
function sendParentMessage(message) {
|
|
387
|
+
const msgType = message && typeof message === "object" && "type" in message ? message.type : void 0;
|
|
388
|
+
if (msgType === "mix_control" || msgType === "stt_control") {
|
|
389
|
+
process.send?.(message);
|
|
390
|
+
return;
|
|
391
|
+
}
|
|
392
|
+
if (msgType === "play" || msgType === "play_status" || msgType === "play_stop" || msgType === "play_pose") {
|
|
393
|
+
process.send?.(message);
|
|
394
|
+
return;
|
|
395
|
+
}
|
|
396
|
+
const sessionId = message && typeof message === "object" && "sessionId" in message && typeof message.sessionId === "string" ? message.sessionId : void 0;
|
|
397
|
+
if (!allowOutboundForSession(sessionId))
|
|
398
|
+
return;
|
|
399
|
+
process.send?.(message);
|
|
400
|
+
}
|
|
401
|
+
function parseBooleanEnv(value, defaultValue) {
|
|
402
|
+
if (value === void 0)
|
|
403
|
+
return defaultValue;
|
|
404
|
+
const normalized = value.trim().toLowerCase();
|
|
405
|
+
if (normalized === "")
|
|
406
|
+
return defaultValue;
|
|
407
|
+
if (["0", "false", "off", "no"].includes(normalized))
|
|
408
|
+
return false;
|
|
409
|
+
if (["1", "true", "on", "yes"].includes(normalized))
|
|
410
|
+
return true;
|
|
411
|
+
return defaultValue;
|
|
412
|
+
}
|
|
413
|
+
function parseNonNegativeIntegerEnv(value, defaultValue) {
|
|
414
|
+
if (value === void 0)
|
|
415
|
+
return defaultValue;
|
|
416
|
+
const parsed = Number(value);
|
|
417
|
+
if (!Number.isFinite(parsed) || parsed < 0)
|
|
418
|
+
return defaultValue;
|
|
419
|
+
return Math.floor(parsed);
|
|
420
|
+
}
|
|
421
|
+
function resolveSessionStartInitDelayMs() {
|
|
422
|
+
const enabled = parseBooleanEnv(process.env[SESSION_START_INIT_DELAY_ENABLED_ENV], true);
|
|
423
|
+
if (!enabled)
|
|
424
|
+
return 0;
|
|
425
|
+
return parseNonNegativeIntegerEnv(process.env[SESSION_START_INIT_DELAY_MS_ENV], DEFAULT_SESSION_START_INIT_DELAY_MS);
|
|
426
|
+
}
|
|
427
|
+
async function handleWebhookMessage(message, handlers) {
|
|
428
|
+
if (!handlers.onWebhook)
|
|
429
|
+
return;
|
|
430
|
+
const body = coerceInboundBinary(message.body);
|
|
431
|
+
if (!body) {
|
|
432
|
+
agentLog("warn", "webhook ipc dropped: body is not binary");
|
|
433
|
+
return;
|
|
434
|
+
}
|
|
435
|
+
const ctx = {
|
|
436
|
+
eventId: message.eventId,
|
|
437
|
+
projectId: message.projectId,
|
|
438
|
+
method: typeof message.method === "string" ? message.method : "POST",
|
|
439
|
+
path: typeof message.path === "string" ? message.path : "",
|
|
440
|
+
headers: normalizeWebhookHeaders(message.headers),
|
|
441
|
+
body,
|
|
442
|
+
contentType: typeof message.contentType === "string" ? message.contentType : null,
|
|
443
|
+
receivedAt: typeof message.receivedAt === "string" ? message.receivedAt : "",
|
|
444
|
+
sessionIds: Array.isArray(message.sessionIds) ? message.sessionIds.filter((id) => typeof id === "string" && id.length > 0) : []
|
|
445
|
+
};
|
|
446
|
+
try {
|
|
447
|
+
const started = Date.now();
|
|
448
|
+
await handlers.onWebhook(ctx);
|
|
449
|
+
sendParentMessage({
|
|
450
|
+
type: "webhook_handled",
|
|
451
|
+
projectId: message.projectId,
|
|
452
|
+
eventId: message.eventId,
|
|
453
|
+
durationMs: Date.now() - started
|
|
454
|
+
});
|
|
455
|
+
} catch (error) {
|
|
456
|
+
const err = error instanceof Error ? error : new Error(String(error));
|
|
457
|
+
await runErrorHook(handlers, {
|
|
458
|
+
sessionId: "",
|
|
459
|
+
projectId: message.projectId,
|
|
460
|
+
env: process.env,
|
|
461
|
+
error: err
|
|
462
|
+
});
|
|
463
|
+
sendParentMessage({
|
|
464
|
+
type: "agent_error",
|
|
465
|
+
sessionId: "",
|
|
466
|
+
message: err.message,
|
|
467
|
+
stack: err.stack
|
|
468
|
+
});
|
|
469
|
+
}
|
|
470
|
+
}
|
|
471
|
+
function resolveUserLanguageCode(event) {
|
|
472
|
+
const withLanguage = event;
|
|
473
|
+
const candidates = [withLanguage.language, event.text];
|
|
474
|
+
for (const value of candidates) {
|
|
475
|
+
if (typeof value === "string" && value.trim()) {
|
|
476
|
+
return value.trim();
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
return void 0;
|
|
480
|
+
}
|
|
481
|
+
async function handleParentMessage(message, handlers) {
|
|
482
|
+
switch (message.type) {
|
|
483
|
+
case "session_start":
|
|
484
|
+
endedSessionIds.delete(message.sessionId);
|
|
485
|
+
peerEnvBySessionId.set(message.sessionId, message.env);
|
|
486
|
+
recordingAvailableBySessionId.set(message.sessionId, message.recordingAvailable ?? false);
|
|
487
|
+
mixAvailableBySessionId.set(message.sessionId, message.mixAvailable ?? false);
|
|
488
|
+
ttsPoseAvailableBySessionId.set(message.sessionId, message.ttsPoseAvailable ?? false);
|
|
489
|
+
const sessionStartInitDelayMs = resolveSessionStartInitDelayMs();
|
|
490
|
+
if (sessionStartInitDelayMs > 0) {
|
|
491
|
+
await new Promise((resolve) => setTimeout(resolve, sessionStartInitDelayMs));
|
|
492
|
+
}
|
|
493
|
+
await (handlers.onClientJoin ?? handlers.onSessionStart)?.({
|
|
494
|
+
sessionId: message.sessionId,
|
|
495
|
+
env: message.env,
|
|
496
|
+
recordingAvailable: message.recordingAvailable ?? false,
|
|
497
|
+
mixAvailable: message.mixAvailable ?? false,
|
|
498
|
+
ttsPoseAvailable: message.ttsPoseAvailable ?? false
|
|
499
|
+
});
|
|
500
|
+
sendParentMessage({
|
|
501
|
+
type: "session_start_ack",
|
|
502
|
+
sessionId: message.sessionId
|
|
503
|
+
});
|
|
504
|
+
break;
|
|
505
|
+
case "speech_event":
|
|
506
|
+
await handlers.onSpeechEvent?.({ sessionId: message.sessionId }, message.event);
|
|
507
|
+
if (message.event.type === "user_speech_final" && typeof message.event.text === "string" && message.event.text.trim()) {
|
|
508
|
+
await handlers.onUserSpeechFinal?.({
|
|
509
|
+
sessionId: message.sessionId,
|
|
510
|
+
text: message.event.text.trim()
|
|
511
|
+
});
|
|
512
|
+
}
|
|
513
|
+
if (message.event.type === "user_language") {
|
|
514
|
+
const language = resolveUserLanguageCode(message.event);
|
|
515
|
+
if (language) {
|
|
516
|
+
await handlers.onUserLanguage?.({
|
|
517
|
+
sessionId: message.sessionId,
|
|
518
|
+
language
|
|
519
|
+
});
|
|
520
|
+
}
|
|
521
|
+
}
|
|
522
|
+
break;
|
|
523
|
+
case "data_channel_message":
|
|
524
|
+
await handlers.onDataChannelMessage?.({
|
|
525
|
+
sessionId: message.sessionId,
|
|
526
|
+
message: parseDataChannelPayload(message.payload),
|
|
527
|
+
raw: message.payload,
|
|
528
|
+
rawBinary: null,
|
|
529
|
+
channel: "control"
|
|
530
|
+
});
|
|
531
|
+
break;
|
|
532
|
+
case "data_channel_binary":
|
|
533
|
+
await handlers.onDataChannelBinary?.({
|
|
534
|
+
sessionId: message.sessionId,
|
|
535
|
+
message: null,
|
|
536
|
+
raw: null,
|
|
537
|
+
rawBinary: message.data,
|
|
538
|
+
channel: message.channel ?? "sync"
|
|
539
|
+
});
|
|
540
|
+
break;
|
|
541
|
+
case "session_end":
|
|
542
|
+
clearPendingRecordingAcksForSession(message.sessionId, "session_ended");
|
|
543
|
+
peerEnvBySessionId.delete(message.sessionId);
|
|
544
|
+
recordingAvailableBySessionId.delete(message.sessionId);
|
|
545
|
+
mixAvailableBySessionId.delete(message.sessionId);
|
|
546
|
+
ttsPoseAvailableBySessionId.delete(message.sessionId);
|
|
547
|
+
await (handlers.onClientLeave ?? handlers.onSessionEnd)?.({
|
|
548
|
+
sessionId: message.sessionId
|
|
549
|
+
});
|
|
550
|
+
break;
|
|
551
|
+
case "idle_timeout":
|
|
552
|
+
await runIdleTimeoutHook(handlers, message);
|
|
553
|
+
break;
|
|
554
|
+
}
|
|
555
|
+
}
|
|
556
|
+
function defineAgent(handlers) {
|
|
557
|
+
installChildUnhandledRejectionGuard();
|
|
558
|
+
const inboundBySession = new SessionSerialQueue();
|
|
559
|
+
inboundQueueAuthority = inboundBySession;
|
|
560
|
+
const agentStartReady = runAgentStartHook(handlers);
|
|
561
|
+
process.on("message", (message) => {
|
|
562
|
+
if (isRecordingControlAckMessage(message)) {
|
|
563
|
+
handleRecordingControlAck(message);
|
|
564
|
+
return;
|
|
565
|
+
}
|
|
566
|
+
if (isPlayAckMessage(message)) {
|
|
567
|
+
handlePlayAck(message);
|
|
568
|
+
return;
|
|
569
|
+
}
|
|
570
|
+
if (isPlayStatusAckMessage(message)) {
|
|
571
|
+
handlePlayStatusAck(message);
|
|
572
|
+
return;
|
|
573
|
+
}
|
|
574
|
+
if (isPlayStopAckMessage(message)) {
|
|
575
|
+
handlePlayStopAck(message);
|
|
576
|
+
return;
|
|
577
|
+
}
|
|
578
|
+
if (isPlayPoseAckMessage(message)) {
|
|
579
|
+
handlePlayPoseAck(message);
|
|
580
|
+
return;
|
|
581
|
+
}
|
|
582
|
+
if (isMixControlAckMessage(message)) {
|
|
583
|
+
handleMixControlAck(message);
|
|
584
|
+
return;
|
|
585
|
+
}
|
|
586
|
+
if (isSttControlAckMessage(message)) {
|
|
587
|
+
handleSttControlAck(message);
|
|
588
|
+
return;
|
|
589
|
+
}
|
|
590
|
+
if (isWebhookMessage(message)) {
|
|
591
|
+
void agentStartReady.then(() => handleWebhookMessage(message, handlers));
|
|
592
|
+
return;
|
|
593
|
+
}
|
|
594
|
+
if (!isSessionScopedParentMessage(message))
|
|
595
|
+
return;
|
|
596
|
+
if (message.type === "session_end") {
|
|
597
|
+
endedSessionIds.add(message.sessionId);
|
|
598
|
+
clearPendingRecordingAcksForSession(message.sessionId, "session_ended");
|
|
599
|
+
inboundBySession.clear(message.sessionId);
|
|
600
|
+
}
|
|
601
|
+
if (message.type === "session_start") {
|
|
602
|
+
endedSessionIds.delete(message.sessionId);
|
|
603
|
+
inboundBySession.clear(message.sessionId);
|
|
604
|
+
}
|
|
605
|
+
inboundBySession.enqueue(message.sessionId, async (_signal, context) => {
|
|
606
|
+
await agentStartReady;
|
|
607
|
+
try {
|
|
608
|
+
await sessionExecutionContext.run({
|
|
609
|
+
sessionId: message.sessionId,
|
|
610
|
+
generation: context.generation
|
|
611
|
+
}, async () => agentLogSessionContext.run(message.sessionId, async () => {
|
|
612
|
+
try {
|
|
613
|
+
await handleParentMessage(message, handlers);
|
|
614
|
+
} catch (error) {
|
|
615
|
+
const err = error instanceof Error ? error : new Error(String(error));
|
|
616
|
+
const env = peerEnvBySessionId.get(message.sessionId) ?? buildIdleEnv(message.sessionId);
|
|
617
|
+
await runErrorHook(handlers, {
|
|
618
|
+
sessionId: message.sessionId,
|
|
619
|
+
projectId: env.PROJECT_ID,
|
|
620
|
+
buildId: env.BUILD_ID,
|
|
621
|
+
env,
|
|
622
|
+
error: err,
|
|
623
|
+
customerContext: parseCustomerContext(env.AGENT_CUSTOMER_CONTEXT)
|
|
624
|
+
});
|
|
625
|
+
sendParentMessage({
|
|
626
|
+
type: "agent_error",
|
|
627
|
+
sessionId: message.sessionId,
|
|
628
|
+
message: err.message,
|
|
629
|
+
stack: err.stack
|
|
630
|
+
});
|
|
631
|
+
}
|
|
632
|
+
}));
|
|
633
|
+
} finally {
|
|
634
|
+
if (message.type === "session_end" && inboundBySession.isCurrentGeneration(message.sessionId, context.generation)) {
|
|
635
|
+
inboundBySession.clear(message.sessionId);
|
|
636
|
+
}
|
|
637
|
+
}
|
|
638
|
+
});
|
|
639
|
+
});
|
|
640
|
+
}
|
|
641
|
+
async function runAgentStartHook(handlers) {
|
|
642
|
+
if (!handlers.onAgentStart)
|
|
643
|
+
return;
|
|
644
|
+
try {
|
|
645
|
+
await handlers.onAgentStart({
|
|
646
|
+
env: process.env
|
|
647
|
+
});
|
|
648
|
+
} catch (error) {
|
|
649
|
+
const err = error instanceof Error ? error : new Error(String(error));
|
|
650
|
+
agentLog("error", `onAgentStart failed: ${err.message}`);
|
|
651
|
+
sendParentMessage({
|
|
652
|
+
type: "agent_error",
|
|
653
|
+
sessionId: "",
|
|
654
|
+
message: err.message,
|
|
655
|
+
stack: err.stack
|
|
656
|
+
});
|
|
657
|
+
}
|
|
658
|
+
}
|
|
659
|
+
function parseCustomerContext(raw) {
|
|
660
|
+
if (!raw?.trim())
|
|
661
|
+
return void 0;
|
|
662
|
+
try {
|
|
663
|
+
const parsed = JSON.parse(raw);
|
|
664
|
+
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
|
|
665
|
+
return parsed;
|
|
666
|
+
}
|
|
667
|
+
} catch {
|
|
668
|
+
}
|
|
669
|
+
return void 0;
|
|
670
|
+
}
|
|
671
|
+
async function runErrorHook(handlers, ctx) {
|
|
672
|
+
if (!handlers.errorHook)
|
|
673
|
+
return;
|
|
674
|
+
try {
|
|
675
|
+
await handlers.errorHook(ctx);
|
|
676
|
+
} catch (hookError) {
|
|
677
|
+
const message = hookError instanceof Error ? hookError.message : String(hookError);
|
|
678
|
+
agentLog("error", `errorHook failed: ${message}`, ctx.sessionId);
|
|
679
|
+
}
|
|
680
|
+
}
|
|
681
|
+
async function runIdleTimeoutHook(handlers, message) {
|
|
682
|
+
const onIdleTimeout = handlers.onIdleTimeout;
|
|
683
|
+
agentLog("info", `idle_timeout ipc received (maxGraceMs=${message.maxGraceMs}, onIdleTimeout=${typeof onIdleTimeout === "function"})`, message.sessionId);
|
|
684
|
+
if (!onIdleTimeout) {
|
|
685
|
+
sendParentMessage({
|
|
686
|
+
type: "idle_timeout_done",
|
|
687
|
+
sessionId: message.sessionId
|
|
688
|
+
});
|
|
689
|
+
agentLog("info", "idle_timeout_done ipc sent (no onIdleTimeout handler)", message.sessionId);
|
|
690
|
+
return;
|
|
691
|
+
}
|
|
692
|
+
const env = peerEnvBySessionId.get(message.sessionId) ?? buildIdleEnv(message.sessionId);
|
|
693
|
+
const idleTimeoutSeconds = Number(env.IDLE_TIMEOUT_SEC) || 0;
|
|
694
|
+
const ctx = {
|
|
695
|
+
sessionId: message.sessionId,
|
|
696
|
+
projectId: env.PROJECT_ID,
|
|
697
|
+
buildId: env.BUILD_ID,
|
|
698
|
+
env,
|
|
699
|
+
idleTimeoutSeconds
|
|
700
|
+
};
|
|
701
|
+
let error;
|
|
702
|
+
try {
|
|
703
|
+
await onIdleTimeout(ctx);
|
|
704
|
+
} catch (hookError) {
|
|
705
|
+
error = hookError instanceof Error ? hookError.message : String(hookError);
|
|
706
|
+
agentLog("error", `onIdleTimeout failed: ${error}`, message.sessionId);
|
|
707
|
+
}
|
|
708
|
+
sendParentMessage({
|
|
709
|
+
type: "idle_timeout_done",
|
|
710
|
+
sessionId: message.sessionId,
|
|
711
|
+
error
|
|
712
|
+
});
|
|
713
|
+
agentLog("info", error ? `idle_timeout_done ipc sent (onIdleTimeout error: ${error})` : "idle_timeout_done ipc sent (onIdleTimeout completed)", message.sessionId);
|
|
714
|
+
}
|
|
715
|
+
function buildIdleEnv(sessionId) {
|
|
716
|
+
return {
|
|
717
|
+
SESSION_ID: sessionId,
|
|
718
|
+
...process.env.PROJECT_ID ? { PROJECT_ID: process.env.PROJECT_ID } : {},
|
|
719
|
+
...process.env.BUILD_ID ? { BUILD_ID: process.env.BUILD_ID } : {},
|
|
720
|
+
...process.env.IDLE_TIMEOUT_SEC ? { IDLE_TIMEOUT_SEC: process.env.IDLE_TIMEOUT_SEC } : {}
|
|
721
|
+
};
|
|
722
|
+
}
|
|
723
|
+
function asOutboundBuffer(data) {
|
|
724
|
+
return Buffer.isBuffer(data) ? data : Buffer.from(data.buffer, data.byteOffset, data.byteLength);
|
|
725
|
+
}
|
|
726
|
+
function broadCastBinaryToClients(data, sessionIds2, channel = "sync") {
|
|
727
|
+
const buffer = asOutboundBuffer(data);
|
|
728
|
+
for (const sessionId of sessionIds2) {
|
|
729
|
+
sendParentMessage({
|
|
730
|
+
type: "send_binary_to_client",
|
|
731
|
+
sessionId,
|
|
732
|
+
data: buffer,
|
|
733
|
+
channel
|
|
734
|
+
});
|
|
735
|
+
}
|
|
736
|
+
}
|
|
737
|
+
var AGENT_LOG_MESSAGE_MAX_CHARS = 2048;
|
|
738
|
+
var AGENT_LOG_FIELDS_MAX_CHARS = 8192;
|
|
739
|
+
function truncateAgentLogMessage(message) {
|
|
740
|
+
if (message.length <= AGENT_LOG_MESSAGE_MAX_CHARS) {
|
|
741
|
+
return message;
|
|
742
|
+
}
|
|
743
|
+
const suffix = "\u2026[truncated]";
|
|
744
|
+
return message.slice(0, AGENT_LOG_MESSAGE_MAX_CHARS - suffix.length) + suffix;
|
|
745
|
+
}
|
|
746
|
+
function isPlainObject(value) {
|
|
747
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
748
|
+
}
|
|
749
|
+
function sanitizeAgentLogFields(fields) {
|
|
750
|
+
if (Object.keys(fields).length === 0) {
|
|
751
|
+
return void 0;
|
|
752
|
+
}
|
|
753
|
+
try {
|
|
754
|
+
const serialized = JSON.stringify(fields);
|
|
755
|
+
if (serialized.length <= AGENT_LOG_FIELDS_MAX_CHARS) {
|
|
756
|
+
return fields;
|
|
757
|
+
}
|
|
758
|
+
return {
|
|
759
|
+
_agentLogFieldsTruncated: true,
|
|
760
|
+
_originalBytes: serialized.length,
|
|
761
|
+
_preview: serialized.slice(0, AGENT_LOG_FIELDS_MAX_CHARS - 80) + "\u2026[truncated]"
|
|
762
|
+
};
|
|
763
|
+
} catch {
|
|
764
|
+
return { _agentLogFieldsError: "not_serializable" };
|
|
765
|
+
}
|
|
766
|
+
}
|
|
767
|
+
function buildAgentLogPayload(level, message, fields, sessionId) {
|
|
768
|
+
const resolvedSessionId = sessionId ?? sessionExecutionContext.getStore()?.sessionId ?? agentLogSessionContext.getStore();
|
|
769
|
+
const sanitizedFields = fields ? sanitizeAgentLogFields(fields) : void 0;
|
|
770
|
+
return {
|
|
771
|
+
type: "log",
|
|
772
|
+
level,
|
|
773
|
+
message: truncateAgentLogMessage(message),
|
|
774
|
+
ts: Date.now(),
|
|
775
|
+
...resolvedSessionId ? { sessionId: resolvedSessionId } : {},
|
|
776
|
+
...sanitizedFields ? { fields: sanitizedFields } : {}
|
|
777
|
+
};
|
|
778
|
+
}
|
|
779
|
+
function agentLog(level, message, fieldsOrSessionId, sessionId) {
|
|
780
|
+
let fields;
|
|
781
|
+
let resolvedSessionId;
|
|
782
|
+
if (typeof fieldsOrSessionId === "string") {
|
|
783
|
+
resolvedSessionId = fieldsOrSessionId;
|
|
784
|
+
} else if (isPlainObject(fieldsOrSessionId)) {
|
|
785
|
+
fields = fieldsOrSessionId;
|
|
786
|
+
resolvedSessionId = sessionId;
|
|
787
|
+
} else {
|
|
788
|
+
resolvedSessionId = sessionId;
|
|
789
|
+
}
|
|
790
|
+
sendParentMessage(buildAgentLogPayload(level, message, fields, resolvedSessionId));
|
|
791
|
+
}
|
|
792
|
+
|
|
793
|
+
// templates/world-sync-binary/protocol.ts
|
|
794
|
+
var POSE_FLOAT_COUNT = 3;
|
|
795
|
+
var POSE_BYTE_LENGTH = POSE_FLOAT_COUNT * 4;
|
|
796
|
+
var encoder = new TextEncoder();
|
|
797
|
+
var decoder = new TextDecoder();
|
|
798
|
+
var POSE_BYTES = new Uint8Array(POSE_BYTE_LENGTH);
|
|
799
|
+
var POSE_VIEW = new DataView(
|
|
800
|
+
POSE_BYTES.buffer,
|
|
801
|
+
POSE_BYTES.byteOffset,
|
|
802
|
+
POSE_BYTE_LENGTH
|
|
803
|
+
);
|
|
804
|
+
function asDataView(data) {
|
|
805
|
+
if (ArrayBuffer.isView(data)) {
|
|
806
|
+
return new DataView(data.buffer, data.byteOffset, data.byteLength);
|
|
807
|
+
}
|
|
808
|
+
return new DataView(data);
|
|
809
|
+
}
|
|
810
|
+
function utf8ByteLength(value) {
|
|
811
|
+
let bytes = 0;
|
|
812
|
+
for (let i = 0; i < value.length; i += 1) {
|
|
813
|
+
const code = value.charCodeAt(i);
|
|
814
|
+
if (code < 128) {
|
|
815
|
+
bytes += 1;
|
|
816
|
+
} else if (code < 2048) {
|
|
817
|
+
bytes += 2;
|
|
818
|
+
} else if (code >= 55296 && code <= 56319) {
|
|
819
|
+
bytes += 4;
|
|
820
|
+
i += 1;
|
|
821
|
+
} else {
|
|
822
|
+
bytes += 3;
|
|
823
|
+
}
|
|
824
|
+
}
|
|
825
|
+
return bytes;
|
|
826
|
+
}
|
|
827
|
+
function isFinitePose(x, y, z) {
|
|
828
|
+
return Number.isFinite(x) && Number.isFinite(y) && Number.isFinite(z);
|
|
829
|
+
}
|
|
830
|
+
function decodePoseInto(data, dest, floatOffset = 0) {
|
|
831
|
+
if (data == null || dest.length < floatOffset + POSE_FLOAT_COUNT) {
|
|
832
|
+
return false;
|
|
833
|
+
}
|
|
834
|
+
const view = asDataView(data);
|
|
835
|
+
if (view.byteLength < POSE_BYTE_LENGTH) {
|
|
836
|
+
return false;
|
|
837
|
+
}
|
|
838
|
+
const x = view.getFloat32(0, true);
|
|
839
|
+
const y = view.getFloat32(4, true);
|
|
840
|
+
const z = view.getFloat32(8, true);
|
|
841
|
+
if (!isFinitePose(x, y, z)) {
|
|
842
|
+
return false;
|
|
843
|
+
}
|
|
844
|
+
dest[floatOffset] = x;
|
|
845
|
+
dest[floatOffset + 1] = y;
|
|
846
|
+
dest[floatOffset + 2] = z;
|
|
847
|
+
return true;
|
|
848
|
+
}
|
|
849
|
+
var WorldSnapshotBuffer = class {
|
|
850
|
+
bytes;
|
|
851
|
+
view;
|
|
852
|
+
used = 0;
|
|
853
|
+
out;
|
|
854
|
+
constructor(capacity = 256) {
|
|
855
|
+
this.bytes = new Uint8Array(capacity);
|
|
856
|
+
this.view = new DataView(
|
|
857
|
+
this.bytes.buffer,
|
|
858
|
+
this.bytes.byteOffset,
|
|
859
|
+
this.bytes.byteLength
|
|
860
|
+
);
|
|
861
|
+
this.out = this.bytes.subarray(0, 0);
|
|
862
|
+
}
|
|
863
|
+
get byteLength() {
|
|
864
|
+
return this.used;
|
|
865
|
+
}
|
|
866
|
+
/**
|
|
867
|
+
* View of the last encoded snapshot (same backing buffer, length = used).
|
|
868
|
+
* The view object is reused while the encoded length is unchanged.
|
|
869
|
+
*/
|
|
870
|
+
bytesView() {
|
|
871
|
+
if (this.out.byteLength !== this.used || this.out.buffer !== this.bytes.buffer) {
|
|
872
|
+
this.out = this.bytes.subarray(0, this.used);
|
|
873
|
+
}
|
|
874
|
+
return this.out;
|
|
875
|
+
}
|
|
876
|
+
encode(entries) {
|
|
877
|
+
const list = Array.isArray(entries) ? entries : [...entries];
|
|
878
|
+
let size = 4;
|
|
879
|
+
for (const entry of list) {
|
|
880
|
+
size += 2 + utf8ByteLength(entry.sessionId) + POSE_BYTE_LENGTH;
|
|
881
|
+
}
|
|
882
|
+
this.ensure(size);
|
|
883
|
+
this.view.setUint32(0, list.length, true);
|
|
884
|
+
let offset = 4;
|
|
885
|
+
for (const entry of list) {
|
|
886
|
+
offset = this.writePeer(
|
|
887
|
+
offset,
|
|
888
|
+
entry.sessionId,
|
|
889
|
+
entry.pose.x,
|
|
890
|
+
entry.pose.y,
|
|
891
|
+
entry.pose.z
|
|
892
|
+
);
|
|
893
|
+
}
|
|
894
|
+
this.used = offset;
|
|
895
|
+
return this.bytesView();
|
|
896
|
+
}
|
|
897
|
+
encodePacked(sessionIds2, xyz2, count) {
|
|
898
|
+
let size = 4;
|
|
899
|
+
for (let i = 0; i < count; i += 1) {
|
|
900
|
+
size += 2 + utf8ByteLength(sessionIds2[i] ?? "") + POSE_BYTE_LENGTH;
|
|
901
|
+
}
|
|
902
|
+
this.ensure(size);
|
|
903
|
+
this.view.setUint32(0, count, true);
|
|
904
|
+
let offset = 4;
|
|
905
|
+
for (let i = 0; i < count; i += 1) {
|
|
906
|
+
const floatOffset = i * POSE_FLOAT_COUNT;
|
|
907
|
+
offset = this.writePeer(
|
|
908
|
+
offset,
|
|
909
|
+
sessionIds2[i] ?? "",
|
|
910
|
+
xyz2[floatOffset] ?? 0,
|
|
911
|
+
xyz2[floatOffset + 1] ?? 0,
|
|
912
|
+
xyz2[floatOffset + 2] ?? 0
|
|
913
|
+
);
|
|
914
|
+
}
|
|
915
|
+
this.used = offset;
|
|
916
|
+
return this.bytesView();
|
|
917
|
+
}
|
|
918
|
+
writePeer(offset, sessionId, x, y, z) {
|
|
919
|
+
const { written } = encoder.encodeInto(
|
|
920
|
+
sessionId,
|
|
921
|
+
this.bytes.subarray(offset + 2)
|
|
922
|
+
);
|
|
923
|
+
this.view.setUint16(offset, written, true);
|
|
924
|
+
offset += 2 + written;
|
|
925
|
+
this.view.setFloat32(offset, x, true);
|
|
926
|
+
this.view.setFloat32(offset + 4, y, true);
|
|
927
|
+
this.view.setFloat32(offset + 8, z, true);
|
|
928
|
+
return offset + POSE_BYTE_LENGTH;
|
|
929
|
+
}
|
|
930
|
+
ensure(size) {
|
|
931
|
+
if (this.bytes.byteLength >= size) {
|
|
932
|
+
return;
|
|
933
|
+
}
|
|
934
|
+
let capacity = Math.max(this.bytes.byteLength, 1);
|
|
935
|
+
while (capacity < size) {
|
|
936
|
+
capacity *= 2;
|
|
937
|
+
}
|
|
938
|
+
this.bytes = new Uint8Array(capacity);
|
|
939
|
+
this.view = new DataView(
|
|
940
|
+
this.bytes.buffer,
|
|
941
|
+
this.bytes.byteOffset,
|
|
942
|
+
this.bytes.byteLength
|
|
943
|
+
);
|
|
944
|
+
}
|
|
945
|
+
};
|
|
946
|
+
var defaultSnapshot = new WorldSnapshotBuffer();
|
|
947
|
+
|
|
948
|
+
// templates/world-sync-binary/agent.ts
|
|
949
|
+
var snapshot = new WorldSnapshotBuffer();
|
|
950
|
+
var indexBySession = /* @__PURE__ */ new Map();
|
|
951
|
+
var sessionIds = [];
|
|
952
|
+
var xyz = new Float32Array(8 * POSE_FLOAT_COUNT);
|
|
953
|
+
var peerCount = 0;
|
|
954
|
+
function ensurePeerCapacity(count) {
|
|
955
|
+
const needed = count * POSE_FLOAT_COUNT;
|
|
956
|
+
if (xyz.length >= needed) {
|
|
957
|
+
return;
|
|
958
|
+
}
|
|
959
|
+
let nextLength = xyz.length;
|
|
960
|
+
while (nextLength < needed) {
|
|
961
|
+
nextLength *= 2;
|
|
962
|
+
}
|
|
963
|
+
const grown = new Float32Array(nextLength);
|
|
964
|
+
grown.set(xyz);
|
|
965
|
+
xyz = grown;
|
|
966
|
+
}
|
|
967
|
+
function setPose(sessionId, x, y, z) {
|
|
968
|
+
let index = indexBySession.get(sessionId);
|
|
969
|
+
if (index === void 0) {
|
|
970
|
+
index = peerCount;
|
|
971
|
+
peerCount += 1;
|
|
972
|
+
sessionIds[index] = sessionId;
|
|
973
|
+
indexBySession.set(sessionId, index);
|
|
974
|
+
ensurePeerCapacity(peerCount);
|
|
975
|
+
}
|
|
976
|
+
const offset = index * POSE_FLOAT_COUNT;
|
|
977
|
+
xyz[offset] = x;
|
|
978
|
+
xyz[offset + 1] = y;
|
|
979
|
+
xyz[offset + 2] = z;
|
|
980
|
+
}
|
|
981
|
+
function removePeer(sessionId) {
|
|
982
|
+
const index = indexBySession.get(sessionId);
|
|
983
|
+
if (index === void 0) {
|
|
984
|
+
return;
|
|
985
|
+
}
|
|
986
|
+
const last = peerCount - 1;
|
|
987
|
+
if (index !== last) {
|
|
988
|
+
const lastId = sessionIds[last];
|
|
989
|
+
sessionIds[index] = lastId;
|
|
990
|
+
indexBySession.set(lastId, index);
|
|
991
|
+
const dest = index * POSE_FLOAT_COUNT;
|
|
992
|
+
const src = last * POSE_FLOAT_COUNT;
|
|
993
|
+
xyz[dest] = xyz[src];
|
|
994
|
+
xyz[dest + 1] = xyz[src + 1];
|
|
995
|
+
xyz[dest + 2] = xyz[src + 2];
|
|
996
|
+
}
|
|
997
|
+
indexBySession.delete(sessionId);
|
|
998
|
+
peerCount -= 1;
|
|
999
|
+
sessionIds.length = peerCount;
|
|
1000
|
+
}
|
|
1001
|
+
function broadcastWorld() {
|
|
1002
|
+
const payload = snapshot.encodePacked(sessionIds, xyz, peerCount);
|
|
1003
|
+
broadCastBinaryToClients(payload, sessionIds, "sync");
|
|
1004
|
+
}
|
|
1005
|
+
var agent_default = defineAgent({
|
|
1006
|
+
onClientJoin({ sessionId }) {
|
|
1007
|
+
setPose(sessionId, 0, 0, 0);
|
|
1008
|
+
broadcastWorld();
|
|
1009
|
+
},
|
|
1010
|
+
onClientLeave({ sessionId }) {
|
|
1011
|
+
removePeer(sessionId);
|
|
1012
|
+
broadcastWorld();
|
|
1013
|
+
},
|
|
1014
|
+
onDataChannelBinary({ sessionId, rawBinary }) {
|
|
1015
|
+
let index = indexBySession.get(sessionId);
|
|
1016
|
+
if (index === void 0) {
|
|
1017
|
+
setPose(sessionId, 0, 0, 0);
|
|
1018
|
+
index = indexBySession.get(sessionId);
|
|
1019
|
+
if (index === void 0) {
|
|
1020
|
+
return;
|
|
1021
|
+
}
|
|
1022
|
+
}
|
|
1023
|
+
if (!decodePoseInto(rawBinary, xyz, index * POSE_FLOAT_COUNT)) {
|
|
1024
|
+
return;
|
|
1025
|
+
}
|
|
1026
|
+
broadcastWorld();
|
|
1027
|
+
}
|
|
1028
|
+
});
|
|
1029
|
+
export {
|
|
1030
|
+
agent_default as default
|
|
1031
|
+
};
|