@astratra/live 0.1.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/src/session.js ADDED
@@ -0,0 +1,621 @@
1
+ 'use strict';
2
+
3
+ const {
4
+ createConfidentialPolicy
5
+ } = require('@astratra/voice');
6
+ const {
7
+ decodeMessage,
8
+ encodeMessage
9
+ } = require('./protocol');
10
+ const {
11
+ resumeConversation,
12
+ createTranscriptRecorder,
13
+ consolidateAfterCall
14
+ } = require('./continuity');
15
+ const {
16
+ createSpokenConfirmation,
17
+ createCallTools,
18
+ buildInstructions
19
+ } = require('./tools');
20
+ const {
21
+ createConfidentialCall
22
+ } = require('./confidential');
23
+ const {
24
+ createTextThinker
25
+ } = require('./textModel');
26
+ const voice = require('@astratra/voice');
27
+ const {
28
+ base64ToBytes,
29
+ pcm16ToFloat,
30
+ floatToPcm16,
31
+ bytesToBase64
32
+ } = require('./protocol');
33
+ const CLOSE = Object.freeze({
34
+ AUTH: 4401,
35
+ DENIED: 4403,
36
+ REPLACED: 4409,
37
+ BUSY: 4429,
38
+ UNAVAILABLE: 4503,
39
+ NORMAL: 1000
40
+ });
41
+ function createLiveSession({
42
+ socket,
43
+ context,
44
+ provider,
45
+ local,
46
+ policy,
47
+ registry,
48
+ actions,
49
+ quota,
50
+ lease,
51
+ transcripts,
52
+ memory,
53
+ clock,
54
+ logger = {},
55
+ catalog = {},
56
+ persona = '',
57
+ resumeWindowMs = 1800000,
58
+ resumeTurns = 12,
59
+ transcriptCompleteOnly = false,
60
+ deferLatestExchange = false,
61
+ idleMs = 60000,
62
+ checkMs = 5000,
63
+ maxCallMs = 1800000,
64
+ shield = {},
65
+ annotateToolResult,
66
+ directAudio = null
67
+ }) {
68
+ if (!socket || !context?.userId || !clock) throw new TypeError('SESSION_DEPENDENCY_REQUIRED');
69
+ const startedAt = clock.now();
70
+ const callId = context.callId || `${context.userId}:${startedAt}`;
71
+ let lastDebitAt = startedAt;
72
+ let chargedMs = 0;
73
+ let lastActivity = startedAt;
74
+ let busy = 0;
75
+ let ended = false;
76
+ let closing = false;
77
+ let muted = false;
78
+ let mode = null;
79
+ let line = null;
80
+ let recorder = null;
81
+ let timer = null;
82
+ let warned = false;
83
+ let conversationId = null;
84
+ let history = [];
85
+ let instructions = '';
86
+ let gate = null;
87
+ let echo = null;
88
+ let audioQueue = Promise.resolve();
89
+ let turnOver = false;
90
+ const pendingMessages = [];
91
+ const turns = [];
92
+ let pendingAnnotations = [];
93
+ const confirmation = createSpokenConfirmation({
94
+ now: clock.now,
95
+ affirmative: catalog.affirmative,
96
+ negative: catalog.negative
97
+ });
98
+ const safeSend = message => {
99
+ if (!ended && socket.readyState === 1) socket.send(encodeMessage(message));
100
+ };
101
+ const recordTurn = (who, text) => {
102
+ if (!text) return;
103
+ const entry = {
104
+ who,
105
+ text: String(text)
106
+ };
107
+ if (who === 'assistant' && pendingAnnotations.length) {
108
+ entry.annotations = pendingAnnotations;
109
+ pendingAnnotations = [];
110
+ }
111
+ const prior = turns.at(-1);
112
+ if (prior?.who === who && !turnOver) {
113
+ prior.text += entry.text;
114
+ if (entry.annotations) prior.annotations = [...(prior.annotations || []), ...entry.annotations];
115
+ } else turns.push(entry);
116
+ turnOver = false;
117
+ confirmation.heard(entry);
118
+ lastActivity = clock.now();
119
+ };
120
+ const persist = () => {
121
+ void recorder?.record(turns).catch(error => logger.warn?.('TRANSCRIPT_FAILED', {
122
+ code: error?.code
123
+ }));
124
+ };
125
+ const tools = createCallTools({
126
+ registry,
127
+ context,
128
+ confirmation,
129
+ actions,
130
+ shield,
131
+ clock,
132
+ send: safeSend,
133
+ onResult: (name, result) => {
134
+ const annotation = annotateToolResult?.(name, result);
135
+ if (annotation != null) pendingAnnotations.push(annotation);
136
+ },
137
+ catalog
138
+ });
139
+ async function close(reason = 'NORMAL', code = CLOSE.NORMAL) {
140
+ if (ended || closing) return;
141
+ closing = true;
142
+ if (reason === 'NORMAL' && line?.flush) {
143
+ try {
144
+ await line.flush();
145
+ } catch (_error) {
146
+ logger.warn?.('FINAL_AUDIO_FLUSH_FAILED');
147
+ }
148
+ }
149
+ ended = true;
150
+ if (timer) clock.clearInterval(timer);
151
+ line?.end?.();
152
+ line?.close?.();
153
+ try {
154
+ await recorder?.record(turns, { final: true });
155
+ } catch (error) {
156
+ logger.warn?.('TRANSCRIPT_FAILED', {
157
+ code: error?.code
158
+ });
159
+ }
160
+ try {
161
+ conversationId = (await recorder?.kept()) || conversationId;
162
+ } catch (_error) {/* Persistence is optional. */}
163
+ try {
164
+ await quota?.charge(context, startedAt, chargedMs);
165
+ } catch (_error) {
166
+ logger.warn?.('QUOTA_CHARGE_FAILED');
167
+ }
168
+ try {
169
+ await lease?.release(context.userId, callId);
170
+ } catch (_error) {
171
+ logger.warn?.('LEASE_RELEASE_FAILED');
172
+ }
173
+ void consolidateAfterCall(memory, context.memoryWhere || {
174
+ userId: context.userId
175
+ }, turns, conversationId, logger);
176
+ if (socket.readyState === 1) {
177
+ socket.send(encodeMessage({
178
+ type: 'end',
179
+ reason
180
+ }));
181
+ socket.close(code);
182
+ }
183
+ }
184
+ async function tick() {
185
+ if (ended || closing) return;
186
+ try {
187
+ if (lease && !(await lease.isOwner(context.userId, callId))) {
188
+ await close('REPLACED', CLOSE.REPLACED);
189
+ return;
190
+ }
191
+ } catch (_error) {
192
+ logger.warn?.('LEASE_CHECK_FAILED');
193
+ }
194
+ if (clock.now() - startedAt >= maxCallMs) {
195
+ await close('CALL_LIMIT');
196
+ return;
197
+ }
198
+ if (!busy && !line?.busy && clock.now() - lastActivity >= idleMs) {
199
+ safeSend({
200
+ type: 'idle'
201
+ });
202
+ await close('IDLE');
203
+ return;
204
+ }
205
+ try {
206
+ if (quota?.debit) {
207
+ const now = clock.now();
208
+ chargedMs += await quota.debit(context, now - lastDebitAt);
209
+ lastDebitAt = now;
210
+ }
211
+ const result = await quota?.check(context, startedAt, chargedMs);
212
+ if (result?.code === 'QUOTA_EXHAUSTED' || result?.code === 'GROUP_LIMIT') await close(result.code);else if (!warned && result?.code === 'QUOTA_WARNING') {
213
+ warned = true;
214
+ safeSend({
215
+ type: 'quota',
216
+ code: result.code,
217
+ remainingMs: result.remainingMs
218
+ });
219
+ }
220
+ } catch (_error) {
221
+ logger.warn?.('QUOTA_CHECK_FAILED');
222
+ }
223
+ }
224
+ function onProviderEvent(event) {
225
+ if (ended) return;
226
+ if (event.type === 'heard') recordTurn('person', event.text);
227
+ if (event.type === 'said' || event.type === 'text') recordTurn('assistant', event.text);
228
+ if (event.type === 'tool') busy += 1;
229
+ if (event.type === 'tool_done') busy = Math.max(0, busy - 1);
230
+ if (event.type === 'audio' || event.type === 'ready' || event.type === 'turn') lastActivity = clock.now();
231
+ if (event.type === 'turn') {
232
+ turnOver = true;
233
+ persist();
234
+ }
235
+ if (event.type === 'audio' && echo && event.data) echo.playbackSent(base64ToBytes(event.data).length, directAudio?.outputRate || 24000);
236
+ if (event.type === 'interrupted') echo?.playbackInterrupted();
237
+ if (event.type === 'error') {
238
+ safeSend({
239
+ type: 'error',
240
+ reason: event.code || 'PROVIDER_ERROR'
241
+ });
242
+ return;
243
+ }
244
+ if (event.type !== 'handle' && event.type !== 'goAway' && event.type !== 'tools' && event.type !== 'toolCancel') safeSend(event);
245
+ }
246
+ async function openLine(nextMode, earlier) {
247
+ line?.end?.();
248
+ line?.close?.();
249
+ line = null;
250
+ mode = nextMode;
251
+ if (mode === 'confidential' && local?.transcribe && (local?.thinker || local?.textModel) && (local?.reader || local?.readers)) {
252
+ const service = local.readers ? voice.createPieceVoiceService({
253
+ providers: local.readers
254
+ }) : null;
255
+ const reader = local.reader || {
256
+ synthesize: ({
257
+ text,
258
+ language
259
+ }) => service.synthesize(text, {
260
+ language
261
+ })
262
+ };
263
+ const textThinker = local.textModel ? createTextThinker({
264
+ model: local.textModel,
265
+ instructions,
266
+ declarations: tools.declarations,
267
+ tools,
268
+ earlier,
269
+ onTool: (name, state) => safeSend({ type: state === 'start' ? 'tool' : 'tool_done', name })
270
+ }) : null;
271
+ const thinker = local.thinker || (({
272
+ text,
273
+ onText,
274
+ signal
275
+ }) => textThinker.respond(text, {
276
+ onText,
277
+ signal
278
+ }));
279
+ if (textThinker && !local.thinker) thinker.undoLast = () => textThinker.undoLast();
280
+ line = createConfidentialCall({
281
+ ...local,
282
+ thinker,
283
+ reader,
284
+ policy,
285
+ earlier,
286
+ session: {
287
+ role: context.role,
288
+ language: context.language,
289
+ requestedMode: 'confidential',
290
+ allowCloudFallback: context.allowCloudFallback
291
+ },
292
+ shield,
293
+ tools,
294
+ send: safeSend,
295
+ onTurn: turn => {
296
+ recordTurn(turn.who, turn.text);
297
+ if (turn.who === 'assistant') {
298
+ turnOver = true;
299
+ persist();
300
+ }
301
+ },
302
+ clock,
303
+ repeatText: catalog.repeat?.[context.language],
304
+ onFallback: async (reason, audio) => {
305
+ if (closing) return;
306
+ safeSend({
307
+ type: 'fallback',
308
+ reason
309
+ });
310
+ await openLine('normal', [...history, ...turns]);
311
+ if (audio && line?.sendAudio) {
312
+ const bytes = floatToPcm16(audio);
313
+ for (let at = 0; at < bytes.length; at += 32000) {
314
+ line.sendAudio(bytesToBase64(bytes.subarray(at, at + 32000)));
315
+ }
316
+ line.sendAudio(bytesToBase64(new Uint8Array(32000)));
317
+ }
318
+ }
319
+ });
320
+ safeSend({
321
+ type: 'ready',
322
+ mode
323
+ });
324
+ return;
325
+ }
326
+ if (mode === 'confidential') {
327
+ const fallback = (policy || createConfidentialPolicy()).onLocalFailure({
328
+ role: context.role,
329
+ language: context.language,
330
+ requestedMode: 'confidential',
331
+ allowCloudFallback: context.allowCloudFallback
332
+ });
333
+ if (!fallback.cloudAudioAllowed) {
334
+ await close('LOCAL_UNAVAILABLE', CLOSE.UNAVAILABLE);
335
+ return;
336
+ }
337
+ mode = 'normal';
338
+ safeSend({
339
+ type: 'fallback',
340
+ reason: fallback.reason
341
+ });
342
+ }
343
+ if (!provider?.connect) {
344
+ await close('PROVIDER_UNAVAILABLE', CLOSE.UNAVAILABLE);
345
+ return;
346
+ }
347
+ const protectedEarlier = earlier.map(turn => ({
348
+ ...turn,
349
+ text: typeof shield.history === 'function' ? shield.history(turn.text) : turn.text
350
+ }));
351
+ try {
352
+ line = await provider.connect({
353
+ instructions,
354
+ tools,
355
+ earlier: protectedEarlier,
356
+ getHistory: () => [...history, ...turns].map(turn => ({
357
+ ...turn,
358
+ text: typeof shield.history === 'function' ? shield.history(turn.text) : turn.text
359
+ })),
360
+ onEvent: onProviderEvent,
361
+ onClose: code => void close(code, CLOSE.UNAVAILABLE)
362
+ });
363
+ } catch (_error) {
364
+ await close('PROVIDER_UNAVAILABLE', CLOSE.UNAVAILABLE);
365
+ }
366
+ }
367
+ async function start() {
368
+ if (quota) {
369
+ try {
370
+ const initial = await quota.check(context, startedAt);
371
+ if (initial.code === 'QUOTA_EXHAUSTED' || initial.code === 'GROUP_LIMIT') {
372
+ await close(initial.code);
373
+ return;
374
+ }
375
+ } catch (_error) {
376
+ logger.warn?.('QUOTA_CHECK_FAILED');
377
+ }
378
+ }
379
+ try {
380
+ await lease?.acquire(context.userId, callId);
381
+ } catch (_error) {
382
+ logger.warn?.('LEASE_ACQUIRE_FAILED');
383
+ }
384
+ const resumed = await resumeConversation({
385
+ store: transcripts,
386
+ userId: context.userId,
387
+ requestedId: context.conversationId,
388
+ now: clock.now,
389
+ windowMs: resumeWindowMs,
390
+ maxTurns: resumeTurns
391
+ });
392
+ conversationId = resumed?.id || null;
393
+ history = resumed?.turns || [];
394
+ recorder = createTranscriptRecorder({
395
+ store: transcripts,
396
+ userId: context.userId,
397
+ conversationId,
398
+ now: clock.now,
399
+ completeOnly: transcriptCompleteOnly,
400
+ deferLatestExchange,
401
+ onSaved: id => safeSend({
402
+ type: 'saved',
403
+ conversationId: id
404
+ })
405
+ });
406
+ if (conversationId) safeSend({
407
+ type: 'saved',
408
+ conversationId
409
+ });
410
+ const decision = (policy || createConfidentialPolicy()).decide({
411
+ role: context.role,
412
+ language: context.language,
413
+ requestedMode: context.mode
414
+ });
415
+ mode = decision.mode;
416
+ instructions = buildInstructions({
417
+ persona,
418
+ language: context.language,
419
+ role: context.role,
420
+ now: () => new Date(clock.now()).toISOString(),
421
+ catalog,
422
+ shield
423
+ });
424
+ if (directAudio) {
425
+ gate = voice.createVadSpeechGate(directAudio.vad || {});
426
+ echo = voice.createEchoGuard({
427
+ now: clock.now,
428
+ ...(directAudio.echo || {})
429
+ });
430
+ }
431
+ await openLine(mode, history);
432
+ if (ended) return;
433
+ timer = clock.setInterval(() => {
434
+ void tick();
435
+ }, checkMs);
436
+ timer?.unref?.();
437
+ for (const raw of pendingMessages.splice(0)) await receive(raw);
438
+ }
439
+ async function receive(raw) {
440
+ if (ended || closing) return;
441
+ const message = decodeMessage(raw);
442
+ if (!message) return;
443
+ if (!line && message.type !== 'end') {
444
+ if (pendingMessages.length < 200) pendingMessages.push(raw);
445
+ return;
446
+ }
447
+ lastActivity = clock.now();
448
+ if (message.type === 'end') return close('NORMAL');
449
+ if (message.type === 'confirm' || message.type === 'cancel') {
450
+ const result = await (message.type === 'confirm' ? tools.confirmByClient(message.actionId) : tools.cancelByClient(message.actionId));
451
+ if (result.code && result.code !== 'ACTION_DONE' && result.code !== 'ACTION_CANCELLED') safeSend({
452
+ type: 'error',
453
+ reason: result.code
454
+ });
455
+ return;
456
+ }
457
+ if (message.type === 'mode') {
458
+ const decision = (policy || createConfidentialPolicy()).decide({
459
+ role: context.role,
460
+ language: context.language,
461
+ requestedMode: message.mode
462
+ });
463
+ if (decision.mode !== mode) {
464
+ persist();
465
+ await openLine(decision.mode, [...history, ...turns]);
466
+ }
467
+ safeSend({
468
+ type: 'mode',
469
+ mode,
470
+ reason: decision.reason
471
+ });
472
+ return;
473
+ }
474
+ if (message.type === 'mute') {
475
+ muted = true;
476
+ line?.mute?.();
477
+ }
478
+ if (message.type === 'unmute') muted = false;
479
+ if (mode === 'confidential') return line?.receive(message);
480
+ if (message.type === 'audio' && !muted && typeof message.data === 'string') {
481
+ if (!gate && !echo) line?.sendAudio(message.data);else {
482
+ audioQueue = audioQueue.then(async () => {
483
+ const raw = pcm16ToFloat(base64ToBytes(message.data));
484
+ const filtered = await gate.push(raw);
485
+ const accepted = await echo.filter(filtered);
486
+ if (accepted?.length) line?.sendAudio(bytesToBase64(floatToPcm16(accepted)));
487
+ }).catch(() => line?.sendAudio(message.data));
488
+ await audioQueue;
489
+ }
490
+ }
491
+ if (message.type === 'text' && typeof message.text === 'string' && message.text.length <= 2000) {
492
+ recordTurn('person', message.text);
493
+ turnOver = true;
494
+ line?.sendText(message.text);
495
+ }
496
+ if (message.type === 'image' && typeof message.data === 'string' && message.data.length <= 256 * 1024) line?.sendImage?.(message.data);
497
+ if (message.type === 'interrupt') line?.interrupt?.();
498
+ }
499
+ return {
500
+ start,
501
+ receive,
502
+ close,
503
+ tick,
504
+ get mode() {
505
+ return mode;
506
+ },
507
+ get ended() {
508
+ return ended;
509
+ },
510
+ get turns() {
511
+ return turns.slice();
512
+ }
513
+ };
514
+ }
515
+ function attachLive({
516
+ httpServer,
517
+ websocketServer,
518
+ authenticate,
519
+ authorize,
520
+ createSession,
521
+ path = '/live',
522
+ maxCalls = 8,
523
+ logger = {},
524
+ languages = [],
525
+ modes = ['normal', 'confidential'],
526
+ conversationIdPattern = /^[\w:.-]{1,120}$/
527
+ }) {
528
+ if (!httpServer?.on || !websocketServer?.handleUpgrade ||
529
+ typeof authenticate !== 'function' || typeof createSession !== 'function') {
530
+ throw new TypeError('SERVER_DEPENDENCY_REQUIRED');
531
+ }
532
+ const calls = new Map();
533
+ async function upgrade(request, socket, head) {
534
+ let url;
535
+ try {
536
+ url = new URL(request.url, 'http://localhost');
537
+ } catch (_error) {
538
+ return;
539
+ }
540
+ if (url.pathname !== path) return;
541
+ let context;
542
+ try {
543
+ context = await authenticate(request);
544
+ } catch (_error) {
545
+ context = null;
546
+ }
547
+ websocketServer.handleUpgrade(request, socket, head, async client => {
548
+ if (!context?.userId) {
549
+ client.close(CLOSE.AUTH);
550
+ return;
551
+ }
552
+ if (authorize) {
553
+ let verdict;
554
+ try { verdict = await authorize(request, context); }
555
+ catch (_error) { verdict = { allowed: false, reason: 'DENIED' }; }
556
+ if (verdict === false || verdict?.allowed === false) {
557
+ if (verdict?.reason && client.readyState === 1) client.send(encodeMessage({ type: 'error', reason: verdict.reason }));
558
+ client.close(verdict?.code || CLOSE.DENIED);
559
+ return;
560
+ }
561
+ }
562
+ const userId = String(context.userId);
563
+ if (calls.has(userId)) {
564
+ await calls.get(userId).close('REPLACED', CLOSE.REPLACED);
565
+ calls.delete(userId);
566
+ }
567
+ if (calls.size >= maxCalls) {
568
+ client.close(CLOSE.BUSY);
569
+ return;
570
+ }
571
+ let session;
572
+ try {
573
+ const language = url.searchParams.get('lang');
574
+ const conversationId = url.searchParams.get('conversation');
575
+ const requestedMode = url.searchParams.get('mode');
576
+ session = createSession({
577
+ socket: client,
578
+ context: {
579
+ ...context,
580
+ userId,
581
+ language: languages.includes(language) ? language : context.language,
582
+ conversationId: conversationId && conversationIdPattern.test(conversationId) ? conversationId : context.conversationId,
583
+ mode: modes.includes(requestedMode) ? requestedMode : context.mode
584
+ }
585
+ });
586
+ calls.set(userId, session);
587
+ client.on('message', raw => {
588
+ void session.receive(raw).catch(error => logger.warn?.('SESSION_RECEIVE_FAILED', { code: error?.code }));
589
+ });
590
+ client.on('close', () => {
591
+ void session.close('NORMAL').catch(error => logger.warn?.('SESSION_CLOSE_FAILED', { code: error?.code }));
592
+ if (calls.get(userId) === session) calls.delete(userId);
593
+ });
594
+ await session.start();
595
+ } catch (error) {
596
+ logger.warn?.('SESSION_START_FAILED', {
597
+ code: error?.code
598
+ });
599
+ client.close(CLOSE.UNAVAILABLE);
600
+ if (calls.get(userId) === session) calls.delete(userId);
601
+ }
602
+ });
603
+ }
604
+ httpServer.on('upgrade', upgrade);
605
+ return {
606
+ get size() {
607
+ return calls.size;
608
+ },
609
+ close() {
610
+ httpServer.off?.('upgrade', upgrade);
611
+ for (const session of calls.values()) void session.close('SERVER_CLOSED');
612
+ calls.clear();
613
+ websocketServer.close?.();
614
+ }
615
+ };
616
+ }
617
+ module.exports = {
618
+ CLOSE,
619
+ createLiveSession,
620
+ attachLive
621
+ };
package/src/shield.js ADDED
@@ -0,0 +1,34 @@
1
+ 'use strict';
2
+
3
+ function createLiveShield({
4
+ omitKey = () => false,
5
+ redactText = text => text,
6
+ maskText = text => text,
7
+ unmaskText = text => text,
8
+ maxDepth = 12
9
+ } = {}) {
10
+ function visit(value, transform, path = [], depth = 0, seen = new WeakSet()) {
11
+ if (typeof value === 'string') return transform(value);
12
+ if (value === null || typeof value !== 'object') return value;
13
+ if (depth >= maxDepth || seen.has(value)) return null;
14
+ seen.add(value);
15
+ const output = Array.isArray(value) ? [] : {};
16
+ for (const [key, child] of Object.entries(value)) {
17
+ if (omitKey(key, path, child)) continue;
18
+ output[key] = visit(child, transform, [...path, key], depth + 1, seen);
19
+ }
20
+ seen.delete(value);
21
+ return output;
22
+ }
23
+ return {
24
+ input: maskText,
25
+ output: unmaskText,
26
+ args: value => visit(value, unmaskText),
27
+ result: value => visit(value, maskText),
28
+ external: value => visit(value, redactText),
29
+ history: value => visit(value, redactText)
30
+ };
31
+ }
32
+ module.exports = {
33
+ createLiveShield
34
+ };