@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/LICENSE +21 -0
- package/README.md +54 -0
- package/package.json +16 -0
- package/src/client.js +142 -0
- package/src/confidential.js +324 -0
- package/src/continuity.js +97 -0
- package/src/gemini.js +374 -0
- package/src/index.d.ts +519 -0
- package/src/index.js +15 -0
- package/src/protocol.js +169 -0
- package/src/quotas.js +162 -0
- package/src/reader.js +205 -0
- package/src/session.js +621 -0
- package/src/shield.js +34 -0
- package/src/textModel.js +287 -0
- package/src/tools.js +284 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Astratra contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
# @astratra/live
|
|
2
|
+
|
|
3
|
+
Composable real-time voice calls for Node 20 or newer. All application state, identity, network transports, models, and user-facing wording are supplied by the host. The client protocol helpers are plain JavaScript for browser and React Native clients.
|
|
4
|
+
|
|
5
|
+
## Installation
|
|
6
|
+
|
|
7
|
+
```sh
|
|
8
|
+
npm install @astratra/live @astratra/voice @astratra/ai
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
## Server
|
|
12
|
+
|
|
13
|
+
`attachLive` accepts an HTTP server, a WebSocket server in `noServer` mode, an authentication function, an optional `authorize(request, context)` guard for origin and entitlement checks, and a `createSession` factory. The package does not create servers, read environment variables, or load keys.
|
|
14
|
+
|
|
15
|
+
```js
|
|
16
|
+
const { attachLive, createLiveSession, createGeminiLiveAdapter } = require('@astratra/live');
|
|
17
|
+
|
|
18
|
+
const provider = createGeminiLiveAdapter({
|
|
19
|
+
websocketFactory: (url) => makeWebSocket(url),
|
|
20
|
+
candidates: [{ model: configuredModel, key: configuredKey }],
|
|
21
|
+
clock
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
const binding = attachLive({
|
|
25
|
+
httpServer,
|
|
26
|
+
websocketServer,
|
|
27
|
+
authenticate: verifyUpgrade,
|
|
28
|
+
createSession: ({ socket, context }) => createLiveSession({
|
|
29
|
+
socket, context, provider, clock, registry, actions,
|
|
30
|
+
transcripts, quota, memory, local, policy, shield,
|
|
31
|
+
persona: configuredPersona, catalog
|
|
32
|
+
})
|
|
33
|
+
});
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
The provider contract is `connect({ instructions, tools, earlier, mode, onEvent, onClose }) -> Promise<line>`. A line implements `sendAudio`, `sendText`, and `close`; image, mute, and interrupt methods are optional. The Gemini adapter accepts an injected WebSocket factory and ordered `{ model, key }` candidates. It sends setup, audio, text, image, and tool response messages using the Gemini Live wire shape, resumes with a handle when possible, and tries later candidates after failure. Supply keys at runtime; do not log adapter URLs.
|
|
37
|
+
|
|
38
|
+
`transcripts` supports `get(id, userId)`, `latest(userId)`, `create({ userId, updatedAt, turns })`, and `append(id, userId, turns, updatedAt)`. Records must include `id`, `userId`, `updatedAt` in milliseconds, and `turns`. A requested conversation is resumed only while fresh within `resumeWindowMs` (30 minutes by default); lookup failures start a fresh conversation. `resumeTurns` bounds the history sent to a new call (12 turns by default). `transcriptCompleteOnly` and `deferLatestExchange` select whether to wait for a reply or another exchange before persisting. `annotateToolResult(name, result)` can attach host-defined source references or cards to the next assistant turn. After the call, `memory.consolidate(where, { transcript, ref })` is invoked in the background when present.
|
|
39
|
+
|
|
40
|
+
`quota` is created with `createMinuteQuota({ store, limits, now })`. The injected store has `usedMs(userId, plan, role)` and `addMs(userId, plan, role, ms)`; group limits additionally use `usedGroupMs(groupId, plan)` and `addGroupMs(groupId, plan, ms)`. Set `limits` by plan and role, and `limits.groups` by plan. Absent limits mean unlimited. The session debits while running, emits `QUOTA_WARNING`, and ends with `QUOTA_EXHAUSTED` or `GROUP_LIMIT`. Storage errors fall back to process memory. Use an atomic shared store for concurrent production calls. `createCallLease` accepts a shared get/set/delete store to replace older calls across processes. `createDailyCounter` provides a generic UTC-day counter for provider usage limits.
|
|
41
|
+
|
|
42
|
+
The `registry` follows `@astratra/ai`'s `ToolRegistry` contract. The `actions` adapter queues and executes write actions. A spoken confirmation needs a proposed action, assistant readback, and recognized affirmative answer with no negative answer. Supply language-specific `catalog.affirmative` and `catalog.negative` phrase arrays. The same pending action can be confirmed by an explicit client `confirm` message. `createLiveShield` composes injected text masking, unmasking, outbound redaction, and structural key filtering. Its `input`/`output` hooks protect model speech, while `args`/`result` protect local tool calls and `external` protects third-party tool arguments. Supply an injected `catalog` and `persona` for instructions and repeat prompts; the package emits codes rather than fixed user-facing sentences.
|
|
43
|
+
|
|
44
|
+
## Confidential path
|
|
45
|
+
|
|
46
|
+
`local` supplies `transcribe`, a `thinker` or injected `textModel`, and a `reader` or voice provider list. `createTextThinker` and `createGeminiTextModel` are available for a streaming text model with tool rounds and candidate fallback. `createGeminiLiveReader` gathers Live audio, checks spoken words against requested text through `@astratra/voice`, and falls back through injected TTS providers. The call uses `@astratra/voice` for VAD segmentation, echo filtering, local transcript analysis, confidential fallback policy, and TTS chunking. Configure `createConfidentialPolicy` from `@astratra/voice` to lock roles or permit explicit cloud fallback. A doubtful transcript emits `repeat` and never reaches the model. The host owns its local decoder, text model, voice provider, and playback format. If a role cannot use cloud audio and local dependencies are absent, the call ends with `LOCAL_UNAVAILABLE`.
|
|
47
|
+
|
|
48
|
+
## Client protocol
|
|
49
|
+
|
|
50
|
+
`encodeMessage` and `decodeMessage` handle JSON messages. `nextCallState` tracks connecting, listening, thinking, speaking, confirming, reconnecting, and ended phases. `floatToPcm16`, `pcm16ToFloat`, base64 helpers, `resample`, `encodeMicroChunk`, `decodeVoiceChunk`, `audioLevel`, `shouldInterrupt`, and `createAudioPacer` cover the 16 kHz microphone / 24 kHz playback pattern. The default pacer sends 25 chunks per second and bounds its queue. All client messages use `type` and optional fields; reason codes are stable and should be rendered through the host's catalog.
|
|
51
|
+
|
|
52
|
+
## Error and persistence boundaries
|
|
53
|
+
|
|
54
|
+
Authentication, action storage, transcript storage, quota storage, logger, WebSocket implementation, and clock are injected. The package does not store secrets, connect to a database, or choose a locale. Transcript and memory failures are reported through the injected logger and do not expose provider errors to callers. A failed provider setup closes with `PROVIDER_UNAVAILABLE`.
|
package/package.json
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@astratra/live",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Injected real-time voice call sessions and client protocol helpers.",
|
|
5
|
+
"engines": { "node": ">=20" },
|
|
6
|
+
"main": "src/index.js",
|
|
7
|
+
"types": "src/index.d.ts",
|
|
8
|
+
"type": "commonjs",
|
|
9
|
+
"files": ["src"],
|
|
10
|
+
"scripts": { "test": "jest --runInBand" },
|
|
11
|
+
"jest": { "testMatch": ["**/__tests__/**/*.test.js"] },
|
|
12
|
+
"license": "MIT",
|
|
13
|
+
"publishConfig": { "access": "public" },
|
|
14
|
+
"dependencies": { "@astratra/voice": "^0.2.0", "@astratra/ai": "^1.4.0" },
|
|
15
|
+
"devDependencies": { "jest": "30.4.2" }
|
|
16
|
+
}
|
package/src/client.js
ADDED
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const SERVER_REASONS = new Set([
|
|
4
|
+
'UNAVAILABLE', 'BUSY', 'DAILY_LIMIT', 'GROUP_LIMIT', 'SUSPENDED',
|
|
5
|
+
'ORIGIN', 'PLAN', 'QUOTA_EXHAUSTED', 'LOCAL_UNAVAILABLE', 'PROVIDER_UNAVAILABLE',
|
|
6
|
+
'CALL_LIMIT', 'IDLE', 'REPLACED', 'SERVER_CLOSED'
|
|
7
|
+
]);
|
|
8
|
+
function serverReason(reason) {
|
|
9
|
+
return typeof reason === 'string' && SERVER_REASONS.has(reason) ? reason : null;
|
|
10
|
+
}
|
|
11
|
+
function closeOutcome(code, {
|
|
12
|
+
reason = null,
|
|
13
|
+
refreshed = false
|
|
14
|
+
} = {}) {
|
|
15
|
+
if (reason === 'IDLE' || reason === 'CALL_LIMIT' || reason === 'SERVER_CLOSED') {
|
|
16
|
+
return { kind: 'ended', code: reason };
|
|
17
|
+
}
|
|
18
|
+
if (serverReason(reason)) return {
|
|
19
|
+
kind: 'failed',
|
|
20
|
+
code: reason
|
|
21
|
+
};
|
|
22
|
+
if (code === 1000) return {
|
|
23
|
+
kind: 'ended'
|
|
24
|
+
};
|
|
25
|
+
if (code === 4401) return refreshed ? {
|
|
26
|
+
kind: 'failed',
|
|
27
|
+
code: 'SESSION'
|
|
28
|
+
} : {
|
|
29
|
+
kind: 'refresh'
|
|
30
|
+
};
|
|
31
|
+
if (code === 4409) return {
|
|
32
|
+
kind: 'failed',
|
|
33
|
+
code: 'REPLACED'
|
|
34
|
+
};
|
|
35
|
+
if (code === 4429) return {
|
|
36
|
+
kind: 'failed',
|
|
37
|
+
code: 'BUSY'
|
|
38
|
+
};
|
|
39
|
+
if (code === 4503 || code === 1011 || code === 4403) return {
|
|
40
|
+
kind: 'failed',
|
|
41
|
+
code: 'UNAVAILABLE'
|
|
42
|
+
};
|
|
43
|
+
return {
|
|
44
|
+
kind: 'failed',
|
|
45
|
+
code: 'NETWORK'
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
function nextSubtitle(state = {
|
|
49
|
+
text: '',
|
|
50
|
+
fresh: true
|
|
51
|
+
}, event) {
|
|
52
|
+
if (event.type === 'said') return {
|
|
53
|
+
text: state.fresh ? event.text : state.text + event.text,
|
|
54
|
+
fresh: false
|
|
55
|
+
};
|
|
56
|
+
return state.fresh ? state : {
|
|
57
|
+
...state,
|
|
58
|
+
fresh: true
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
function subtitleTail(text, max = 110) {
|
|
62
|
+
const clean = String(text || '').replace(/\s+/g, ' ').trim();
|
|
63
|
+
if (clean.length <= max) return clean;
|
|
64
|
+
const tail = clean.slice(-max);
|
|
65
|
+
const space = tail.indexOf(' ');
|
|
66
|
+
return `…${space >= 0 && space < max / 3 ? tail.slice(space + 1) : tail}`;
|
|
67
|
+
}
|
|
68
|
+
function nextConsent(state, event) {
|
|
69
|
+
if (event.type === 'confirm') return {
|
|
70
|
+
actionId: event.actionId,
|
|
71
|
+
readback: ''
|
|
72
|
+
};
|
|
73
|
+
if (!state) return null;
|
|
74
|
+
if (event.type === 'said') return {
|
|
75
|
+
...state,
|
|
76
|
+
readback: state.readback + event.text
|
|
77
|
+
};
|
|
78
|
+
if ((event.type === 'action_done' || event.type === 'action_cancelled') && event.actionId === state.actionId) return null;
|
|
79
|
+
return state;
|
|
80
|
+
}
|
|
81
|
+
function nextTranscript(turns, event) {
|
|
82
|
+
const role = event.type === 'heard' ? 'user' : event.type === 'said' ? 'assistant' : null;
|
|
83
|
+
if (!role || !event.text) return turns;
|
|
84
|
+
const previous = turns.at(-1);
|
|
85
|
+
if (previous?.role === role) return [...turns.slice(0, -1), {
|
|
86
|
+
role,
|
|
87
|
+
text: previous.text + event.text
|
|
88
|
+
}];
|
|
89
|
+
return [...turns, {
|
|
90
|
+
role,
|
|
91
|
+
text: event.text
|
|
92
|
+
}];
|
|
93
|
+
}
|
|
94
|
+
function cleanTranscript(turns) {
|
|
95
|
+
return turns.map(turn => ({
|
|
96
|
+
...turn,
|
|
97
|
+
text: String(turn.text || '').replace(/\s+/g, ' ').trim()
|
|
98
|
+
})).filter(turn => turn.text);
|
|
99
|
+
}
|
|
100
|
+
function nextHeard(state = {
|
|
101
|
+
text: '',
|
|
102
|
+
fresh: true,
|
|
103
|
+
uncertain: false
|
|
104
|
+
}, event) {
|
|
105
|
+
if (event.type !== 'heard') return state.fresh ? state : {
|
|
106
|
+
...state,
|
|
107
|
+
fresh: true
|
|
108
|
+
};
|
|
109
|
+
return {
|
|
110
|
+
text: state.fresh ? event.text : state.text + event.text,
|
|
111
|
+
fresh: false,
|
|
112
|
+
uncertain: Boolean(event.uncertain)
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
function callUrl(baseUrl, {
|
|
116
|
+
path = '/live',
|
|
117
|
+
language,
|
|
118
|
+
conversationId,
|
|
119
|
+
mode
|
|
120
|
+
} = {}) {
|
|
121
|
+
const base = String(baseUrl).trim().replace(/\/+$/, '').replace(/^http(s?):/i, (_all, secure) => `ws${secure}:`);
|
|
122
|
+
const params = [`lang=${encodeURIComponent(language || '')}`];
|
|
123
|
+
if (conversationId) params.push(`conversation=${encodeURIComponent(conversationId)}`);
|
|
124
|
+
if (mode) params.push(`mode=${encodeURIComponent(mode)}`);
|
|
125
|
+
return `${base}${path}?${params.join('&')}`;
|
|
126
|
+
}
|
|
127
|
+
function languageCode(value, supported = [], fallback = 'en') {
|
|
128
|
+
const code = String(value || '').toLowerCase().split(/[-_]/)[0];
|
|
129
|
+
return supported.includes(code) ? code : fallback;
|
|
130
|
+
}
|
|
131
|
+
module.exports = {
|
|
132
|
+
serverReason,
|
|
133
|
+
closeOutcome,
|
|
134
|
+
nextSubtitle,
|
|
135
|
+
subtitleTail,
|
|
136
|
+
nextConsent,
|
|
137
|
+
nextTranscript,
|
|
138
|
+
cleanTranscript,
|
|
139
|
+
nextHeard,
|
|
140
|
+
callUrl,
|
|
141
|
+
languageCode
|
|
142
|
+
};
|
|
@@ -0,0 +1,324 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const voice = require('@astratra/voice');
|
|
4
|
+
const {
|
|
5
|
+
base64ToBytes,
|
|
6
|
+
pcm16ToFloat,
|
|
7
|
+
bytesToBase64
|
|
8
|
+
} = require('./protocol');
|
|
9
|
+
function createConfidentialCall({
|
|
10
|
+
voiceOptions = {},
|
|
11
|
+
transcribe,
|
|
12
|
+
thinker,
|
|
13
|
+
reader,
|
|
14
|
+
policy,
|
|
15
|
+
session,
|
|
16
|
+
shield = {},
|
|
17
|
+
tools,
|
|
18
|
+
send,
|
|
19
|
+
onFallback,
|
|
20
|
+
onTurn,
|
|
21
|
+
clock,
|
|
22
|
+
repeatText = null,
|
|
23
|
+
earlier = []
|
|
24
|
+
}) {
|
|
25
|
+
if (typeof transcribe !== 'function' || typeof thinker !== 'function' || !reader) throw new TypeError('LOCAL_DEPENDENCY_REQUIRED');
|
|
26
|
+
const decision = voice.createConfidentialSession(policy || voice.createConfidentialPolicy(), session || {});
|
|
27
|
+
const segmenter = voice.createVadSegmenter({
|
|
28
|
+
frameSize: voiceOptions.frameSize ?? 512,
|
|
29
|
+
startFrames: 3,
|
|
30
|
+
minSpeechFrames: 3,
|
|
31
|
+
endFrames: 16,
|
|
32
|
+
lookbackFrames: 5,
|
|
33
|
+
...voiceOptions.vad,
|
|
34
|
+
onSpeechStart: () => interrupt()
|
|
35
|
+
});
|
|
36
|
+
const echo = voice.createEchoGuard({
|
|
37
|
+
now: clock.now,
|
|
38
|
+
...voiceOptions.echo
|
|
39
|
+
});
|
|
40
|
+
const local = voice.createLocalTranscriber({
|
|
41
|
+
transcribe: async (...args) => {
|
|
42
|
+
const result = await transcribe(...args);
|
|
43
|
+
if (result == null) throw Object.assign(new Error('TRANSCRIPTION_UNAVAILABLE'), {
|
|
44
|
+
code: 'TRANSCRIPTION_UNAVAILABLE'
|
|
45
|
+
});
|
|
46
|
+
return result;
|
|
47
|
+
},
|
|
48
|
+
sampleRate: voiceOptions.sampleRate ?? 16000,
|
|
49
|
+
...voiceOptions.transcription
|
|
50
|
+
});
|
|
51
|
+
const chunker = () => voice.createSpeechChunker(voiceOptions.reading);
|
|
52
|
+
let ended = false;
|
|
53
|
+
let muted = false;
|
|
54
|
+
let active = null;
|
|
55
|
+
let queue = Promise.resolve();
|
|
56
|
+
const pendingJobs = new Set();
|
|
57
|
+
let sequence = 0;
|
|
58
|
+
let pendingQuestion = null;
|
|
59
|
+
const history = earlier.map(turn => ({
|
|
60
|
+
who: turn.who || (turn.role === 'user' ? 'person' : 'assistant'),
|
|
61
|
+
text: String(turn.text || '')
|
|
62
|
+
}));
|
|
63
|
+
const protect = (kind, value) => typeof shield[kind] === 'function' ? shield[kind](value) : value;
|
|
64
|
+
function interrupt() {
|
|
65
|
+
if (!active) return;
|
|
66
|
+
if (!active.audioSent) {
|
|
67
|
+
pendingQuestion = active.question;
|
|
68
|
+
thinker.undoLast?.();
|
|
69
|
+
} else if (active.spoken.length) {
|
|
70
|
+
onTurn?.({
|
|
71
|
+
who: 'assistant',
|
|
72
|
+
text: active.spoken.join(' ')
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
active.controller.abort();
|
|
76
|
+
active = null;
|
|
77
|
+
reader.interrupt?.();
|
|
78
|
+
echo.playbackInterrupted();
|
|
79
|
+
send({
|
|
80
|
+
type: 'interrupted'
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
async function speak(text, run) {
|
|
84
|
+
if (!text || run.controller.signal.aborted) return;
|
|
85
|
+
const clear = protect('output', text);
|
|
86
|
+
history.push({
|
|
87
|
+
who: 'assistant',
|
|
88
|
+
text: clear
|
|
89
|
+
});
|
|
90
|
+
send({
|
|
91
|
+
type: 'said',
|
|
92
|
+
text: clear
|
|
93
|
+
});
|
|
94
|
+
const sendPiece = piece => {
|
|
95
|
+
if (run.controller.signal.aborted || !piece?.audio) return;
|
|
96
|
+
const audio = Buffer.from(piece.audio);
|
|
97
|
+
echo.playbackSent(audio.length, voiceOptions.outputRate ?? 24000);
|
|
98
|
+
if (!run.audioSent) run.spoken.push(clear);
|
|
99
|
+
run.audioSent = true;
|
|
100
|
+
send({
|
|
101
|
+
type: 'audio',
|
|
102
|
+
data: bytesToBase64(audio),
|
|
103
|
+
mimeType: piece.mimeType || 'audio/pcm;rate=24000'
|
|
104
|
+
});
|
|
105
|
+
};
|
|
106
|
+
let result;
|
|
107
|
+
try {
|
|
108
|
+
result = await reader.synthesize({
|
|
109
|
+
text: clear,
|
|
110
|
+
language: session.language,
|
|
111
|
+
signal: run.controller.signal,
|
|
112
|
+
onPiece: sendPiece,
|
|
113
|
+
onReset: () => {
|
|
114
|
+
echo.playbackInterrupted();
|
|
115
|
+
send({ type: 'interrupted' });
|
|
116
|
+
}
|
|
117
|
+
});
|
|
118
|
+
} catch (_error) {
|
|
119
|
+
send({
|
|
120
|
+
type: 'error',
|
|
121
|
+
reason: 'VOICE_UNAVAILABLE'
|
|
122
|
+
});
|
|
123
|
+
return;
|
|
124
|
+
}
|
|
125
|
+
if (run.controller.signal.aborted) return;
|
|
126
|
+
if (result?.code === 'VOICE_UNAVAILABLE') send({ type: 'error', reason: 'VOICE_UNAVAILABLE' });
|
|
127
|
+
if (!result?.streamed) for (const piece of result?.pieces || [result]) sendPiece(piece);
|
|
128
|
+
}
|
|
129
|
+
async function processText(text, uncertain = false, audio = null) {
|
|
130
|
+
if (ended) return;
|
|
131
|
+
if (uncertain) {
|
|
132
|
+
const verdict = decision.onDoubt();
|
|
133
|
+
send({
|
|
134
|
+
type: 'heard',
|
|
135
|
+
text,
|
|
136
|
+
uncertain: true
|
|
137
|
+
});
|
|
138
|
+
send({
|
|
139
|
+
type: 'repeat',
|
|
140
|
+
code: verdict.reason
|
|
141
|
+
});
|
|
142
|
+
if (repeatText) {
|
|
143
|
+
send({
|
|
144
|
+
type: 'said',
|
|
145
|
+
text: repeatText,
|
|
146
|
+
uncertain: true
|
|
147
|
+
});
|
|
148
|
+
try {
|
|
149
|
+
const audio = await reader.synthesize({
|
|
150
|
+
text: repeatText,
|
|
151
|
+
language: session.language
|
|
152
|
+
});
|
|
153
|
+
for (const piece of audio?.pieces || [audio]) if (piece?.audio) send({
|
|
154
|
+
type: 'audio',
|
|
155
|
+
data: bytesToBase64(Buffer.from(piece.audio)),
|
|
156
|
+
mimeType: piece.mimeType || 'audio/pcm;rate=24000'
|
|
157
|
+
});
|
|
158
|
+
} catch (_error) {/* The repeat code remains available to the client. */}
|
|
159
|
+
}
|
|
160
|
+
send({
|
|
161
|
+
type: 'turn'
|
|
162
|
+
});
|
|
163
|
+
if (verdict.mode === 'normal') await onFallback?.(verdict.reason, audio);
|
|
164
|
+
return;
|
|
165
|
+
}
|
|
166
|
+
decision.onAccepted();
|
|
167
|
+
interrupt();
|
|
168
|
+
history.push({
|
|
169
|
+
who: 'person',
|
|
170
|
+
text
|
|
171
|
+
});
|
|
172
|
+
onTurn?.({
|
|
173
|
+
who: 'person',
|
|
174
|
+
text
|
|
175
|
+
});
|
|
176
|
+
send({
|
|
177
|
+
type: 'heard',
|
|
178
|
+
text
|
|
179
|
+
});
|
|
180
|
+
const question = pendingQuestion ? `${pendingQuestion} ${text}` : text;
|
|
181
|
+
pendingQuestion = null;
|
|
182
|
+
const run = {
|
|
183
|
+
id: ++sequence,
|
|
184
|
+
question,
|
|
185
|
+
audioSent: false,
|
|
186
|
+
spoken: [],
|
|
187
|
+
controller: new globalThis.AbortController()
|
|
188
|
+
};
|
|
189
|
+
active = run;
|
|
190
|
+
const pieces = chunker();
|
|
191
|
+
let reading = Promise.resolve();
|
|
192
|
+
const spoken = [];
|
|
193
|
+
const emit = part => {
|
|
194
|
+
for (const piece of pieces.push(part)) {
|
|
195
|
+
spoken.push(piece);
|
|
196
|
+
reading = reading.then(() => speak(piece, run));
|
|
197
|
+
}
|
|
198
|
+
};
|
|
199
|
+
try {
|
|
200
|
+
const result = await thinker({
|
|
201
|
+
text: protect('input', question),
|
|
202
|
+
history: history.map(turn => ({
|
|
203
|
+
...turn,
|
|
204
|
+
text: protect('input', turn.text)
|
|
205
|
+
})),
|
|
206
|
+
tools,
|
|
207
|
+
signal: run.controller.signal,
|
|
208
|
+
onText: emit
|
|
209
|
+
});
|
|
210
|
+
if (typeof result === 'string' && spoken.length === 0) emit(result);
|
|
211
|
+
for (const piece of pieces.flush()) {
|
|
212
|
+
spoken.push(piece);
|
|
213
|
+
reading = reading.then(() => speak(piece, run));
|
|
214
|
+
}
|
|
215
|
+
await reading;
|
|
216
|
+
if (active === run) {
|
|
217
|
+
send({
|
|
218
|
+
type: 'turn'
|
|
219
|
+
});
|
|
220
|
+
active = null;
|
|
221
|
+
onTurn?.({
|
|
222
|
+
who: 'assistant',
|
|
223
|
+
text: spoken.map(piece => protect('output', piece)).join(' ')
|
|
224
|
+
});
|
|
225
|
+
}
|
|
226
|
+
} catch (_error) {
|
|
227
|
+
if (active === run) {
|
|
228
|
+
active = null;
|
|
229
|
+
send({
|
|
230
|
+
type: 'error',
|
|
231
|
+
reason: 'THINKER_FAILED'
|
|
232
|
+
});
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
async function processSegment(samples) {
|
|
237
|
+
try {
|
|
238
|
+
const result = await local.transcribe(samples, {
|
|
239
|
+
language: session.language
|
|
240
|
+
});
|
|
241
|
+
const doubtful = result.doubtful || (
|
|
242
|
+
Number.isFinite(result.confidence) &&
|
|
243
|
+
result.confidence < (voiceOptions.minConfidence ?? 0.35)
|
|
244
|
+
);
|
|
245
|
+
await processText(result.text, doubtful, samples);
|
|
246
|
+
} catch (_error) {
|
|
247
|
+
const verdict = decision.onLocalFailure();
|
|
248
|
+
if (verdict.mode === 'normal') await onFallback?.(verdict.reason, samples);else if (verdict.state === 'ended') {
|
|
249
|
+
send({
|
|
250
|
+
type: 'error',
|
|
251
|
+
reason: 'LOCAL_UNAVAILABLE'
|
|
252
|
+
});
|
|
253
|
+
end();
|
|
254
|
+
} else send({
|
|
255
|
+
type: 'repeat',
|
|
256
|
+
code: verdict.reason
|
|
257
|
+
});
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
function scheduleSegment(samples) {
|
|
261
|
+
const job = processSegment(samples);
|
|
262
|
+
pendingJobs.add(job);
|
|
263
|
+
void job.finally(() => pendingJobs.delete(job));
|
|
264
|
+
}
|
|
265
|
+
async function receive(message) {
|
|
266
|
+
if (ended) return;
|
|
267
|
+
if (message.type === 'mute') {
|
|
268
|
+
muted = true;
|
|
269
|
+
queue = queue.then(async () => {
|
|
270
|
+
for (const segment of segmenter.flush()) scheduleSegment(segment);
|
|
271
|
+
});
|
|
272
|
+
await queue;
|
|
273
|
+
await Promise.all([...pendingJobs]);
|
|
274
|
+
return;
|
|
275
|
+
}
|
|
276
|
+
if (message.type === 'unmute') {
|
|
277
|
+
muted = false;
|
|
278
|
+
return;
|
|
279
|
+
}
|
|
280
|
+
if (message.type === 'interrupt') {
|
|
281
|
+
interrupt();
|
|
282
|
+
return;
|
|
283
|
+
}
|
|
284
|
+
if (message.type === 'text') {
|
|
285
|
+
return processText(String(message.text || '').trim());
|
|
286
|
+
}
|
|
287
|
+
if (message.type !== 'audio' || muted) return;
|
|
288
|
+
queue = queue.then(async () => {
|
|
289
|
+
const samples = pcm16ToFloat(base64ToBytes(message.data));
|
|
290
|
+
const guarded = await echo.filter(samples);
|
|
291
|
+
if (!guarded) return;
|
|
292
|
+
for (const segment of await segmenter.push(guarded)) scheduleSegment(segment);
|
|
293
|
+
});
|
|
294
|
+
await queue;
|
|
295
|
+
await Promise.all([...pendingJobs]);
|
|
296
|
+
}
|
|
297
|
+
function end() {
|
|
298
|
+
if (ended) return;
|
|
299
|
+
ended = true;
|
|
300
|
+
interrupt();
|
|
301
|
+
segmenter.reset();
|
|
302
|
+
decision.end();
|
|
303
|
+
reader.close?.();
|
|
304
|
+
}
|
|
305
|
+
return {
|
|
306
|
+
receive,
|
|
307
|
+
end,
|
|
308
|
+
flush: async () => {
|
|
309
|
+
await queue;
|
|
310
|
+
for (const segment of segmenter.flush()) scheduleSegment(segment);
|
|
311
|
+
await Promise.all([...pendingJobs]);
|
|
312
|
+
},
|
|
313
|
+
snapshot: decision.snapshot,
|
|
314
|
+
get history() {
|
|
315
|
+
return history.slice();
|
|
316
|
+
},
|
|
317
|
+
get busy() {
|
|
318
|
+
return Boolean(active);
|
|
319
|
+
}
|
|
320
|
+
};
|
|
321
|
+
}
|
|
322
|
+
module.exports = {
|
|
323
|
+
createConfidentialCall
|
|
324
|
+
};
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
async function resumeConversation({
|
|
4
|
+
store,
|
|
5
|
+
userId,
|
|
6
|
+
requestedId = null,
|
|
7
|
+
now,
|
|
8
|
+
windowMs = 30 * 60 * 1000,
|
|
9
|
+
maxTurns = 12
|
|
10
|
+
}) {
|
|
11
|
+
if (!store || typeof (requestedId ? store.get : store.latest) !== 'function') return null;
|
|
12
|
+
let item;
|
|
13
|
+
try {
|
|
14
|
+
item = requestedId ? await store.get(requestedId, userId) : await store.latest(userId);
|
|
15
|
+
} catch (_error) {
|
|
16
|
+
return null;
|
|
17
|
+
}
|
|
18
|
+
if (!item || item.userId !== userId || !Number.isFinite(item.updatedAt) || now() - item.updatedAt > windowMs || item.updatedAt > now()) return null;
|
|
19
|
+
return {
|
|
20
|
+
id: item.id,
|
|
21
|
+
turns: Array.isArray(item.turns) ? item.turns.slice(-maxTurns) : []
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
function createTranscriptRecorder({
|
|
25
|
+
store,
|
|
26
|
+
userId,
|
|
27
|
+
conversationId,
|
|
28
|
+
now,
|
|
29
|
+
onSaved = () => {},
|
|
30
|
+
maxChars = 20000,
|
|
31
|
+
completeOnly = false,
|
|
32
|
+
deferLatestExchange = false
|
|
33
|
+
}) {
|
|
34
|
+
let saved = 0;
|
|
35
|
+
let queue = Promise.resolve();
|
|
36
|
+
let id = conversationId || null;
|
|
37
|
+
return {
|
|
38
|
+
record(turns, { final = false } = {}) {
|
|
39
|
+
const lastAssistant = turns.findLastIndex(turn => turn.who === 'assistant');
|
|
40
|
+
let upto = completeOnly ? lastAssistant + 1 : turns.length;
|
|
41
|
+
if (deferLatestExchange && !final) {
|
|
42
|
+
const lastPerson = turns.findLastIndex(turn => turn.who === 'person');
|
|
43
|
+
upto = Math.min(upto, Math.max(0, lastPerson));
|
|
44
|
+
}
|
|
45
|
+
const operation = queue.then(async () => {
|
|
46
|
+
const fresh = turns.slice(saved, upto).map(turn => ({
|
|
47
|
+
role: turn.who === 'person' ? 'user' : 'assistant',
|
|
48
|
+
text: String(turn.text || '').trim().slice(0, maxChars),
|
|
49
|
+
...(turn.annotations ? {
|
|
50
|
+
annotations: turn.annotations
|
|
51
|
+
} : {})
|
|
52
|
+
})).filter(turn => turn.text);
|
|
53
|
+
if (!fresh.length || !store) return;
|
|
54
|
+
if (!id) {
|
|
55
|
+
if (!fresh.some(turn => turn.role === 'user')) return;
|
|
56
|
+
id = await store.create({
|
|
57
|
+
userId,
|
|
58
|
+
updatedAt: now(),
|
|
59
|
+
turns: []
|
|
60
|
+
});
|
|
61
|
+
onSaved(id);
|
|
62
|
+
}
|
|
63
|
+
await store.append(id, userId, fresh, now());
|
|
64
|
+
saved = upto;
|
|
65
|
+
});
|
|
66
|
+
queue = operation.catch(() => {});
|
|
67
|
+
return operation;
|
|
68
|
+
},
|
|
69
|
+
async kept() {
|
|
70
|
+
await queue;
|
|
71
|
+
return id;
|
|
72
|
+
}
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
async function consolidateAfterCall(memory, where, transcript, id, logger = {}) {
|
|
76
|
+
if (!memory || typeof memory.consolidate !== 'function' || !id || !transcript.length) return {
|
|
77
|
+
status: 'skipped'
|
|
78
|
+
};
|
|
79
|
+
try {
|
|
80
|
+
return await memory.consolidate(where, {
|
|
81
|
+
transcript,
|
|
82
|
+
ref: id
|
|
83
|
+
});
|
|
84
|
+
} catch (error) {
|
|
85
|
+
logger.warn?.('CONSOLIDATION_FAILED', {
|
|
86
|
+
code: error?.code
|
|
87
|
+
});
|
|
88
|
+
return {
|
|
89
|
+
status: 'failed'
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
module.exports = {
|
|
94
|
+
resumeConversation,
|
|
95
|
+
createTranscriptRecorder,
|
|
96
|
+
consolidateAfterCall
|
|
97
|
+
};
|