@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/src/quotas.js
ADDED
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
function createMemoryMinuteStore({
|
|
4
|
+
now
|
|
5
|
+
}) {
|
|
6
|
+
const users = new Map();
|
|
7
|
+
const groups = new Map();
|
|
8
|
+
const day = () => new Date(now()).toISOString().slice(0, 10);
|
|
9
|
+
const key = (...parts) => JSON.stringify([day(), ...parts]);
|
|
10
|
+
return {
|
|
11
|
+
async usedMs(userId, plan, role) {
|
|
12
|
+
return users.get(key(userId, plan, role)) || 0;
|
|
13
|
+
},
|
|
14
|
+
async addMs(userId, plan, role, ms) {
|
|
15
|
+
const id = key(userId, plan, role);
|
|
16
|
+
users.set(id, (users.get(id) || 0) + ms);
|
|
17
|
+
},
|
|
18
|
+
async usedGroupMs(groupId, plan) {
|
|
19
|
+
return groups.get(key(groupId, plan)) || 0;
|
|
20
|
+
},
|
|
21
|
+
async addGroupMs(groupId, plan, ms) {
|
|
22
|
+
const id = key(groupId, plan);
|
|
23
|
+
groups.set(id, (groups.get(id) || 0) + ms);
|
|
24
|
+
}
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
function createMinuteQuota({
|
|
28
|
+
store,
|
|
29
|
+
limits = {},
|
|
30
|
+
now,
|
|
31
|
+
warningBeforeMs = 60000,
|
|
32
|
+
maxCallMs = 1800000,
|
|
33
|
+
countGroup = ctx => Boolean(ctx.groupId)
|
|
34
|
+
}) {
|
|
35
|
+
if (typeof now !== 'function') throw new TypeError('CLOCK_REQUIRED');
|
|
36
|
+
const fallback = createMemoryMinuteStore({
|
|
37
|
+
now
|
|
38
|
+
});
|
|
39
|
+
let storeAvailable = true;
|
|
40
|
+
function limitFor(ctx) {
|
|
41
|
+
const value = limits[ctx.plan]?.[ctx.role] ?? limits[ctx.plan]?.default ?? limits[ctx.role] ?? limits.default;
|
|
42
|
+
return value == null ? Infinity : Number(value);
|
|
43
|
+
}
|
|
44
|
+
function groupLimitFor(ctx) {
|
|
45
|
+
if (!countGroup(ctx)) return Infinity;
|
|
46
|
+
const value = limits.groups?.[ctx.plan] ?? limits.groups?.default;
|
|
47
|
+
return value == null ? Infinity : Number(value);
|
|
48
|
+
}
|
|
49
|
+
async function use(method, args) {
|
|
50
|
+
try {
|
|
51
|
+
if (storeAvailable && typeof store?.[method] === 'function') {
|
|
52
|
+
const result = await store[method](...args);
|
|
53
|
+
if (method.startsWith('add')) await fallback[method](...args);
|
|
54
|
+
return result;
|
|
55
|
+
}
|
|
56
|
+
} catch (_error) {
|
|
57
|
+
storeAvailable = false;
|
|
58
|
+
}
|
|
59
|
+
return fallback[method](...args);
|
|
60
|
+
}
|
|
61
|
+
async function check(ctx, startedAt, chargedMs = 0) {
|
|
62
|
+
const elapsedMs = Math.max(0, now() - startedAt);
|
|
63
|
+
const unchargedMs = Math.max(0, elapsedMs - chargedMs);
|
|
64
|
+
const userUsed = Number(await use('usedMs', [ctx.userId, ctx.plan, ctx.role])) || 0;
|
|
65
|
+
const userRemaining = limitFor(ctx) * 60000 - userUsed - unchargedMs;
|
|
66
|
+
const groupUsed = countGroup(ctx) ? Number(await use('usedGroupMs', [ctx.groupId, ctx.plan])) || 0 : 0;
|
|
67
|
+
const groupRemaining = groupLimitFor(ctx) * 60000 - groupUsed - unchargedMs;
|
|
68
|
+
const callRemaining = maxCallMs - elapsedMs;
|
|
69
|
+
const remainingMs = Math.max(0, Math.min(userRemaining, groupRemaining, callRemaining));
|
|
70
|
+
const reason = groupRemaining < userRemaining && groupRemaining <= callRemaining ? 'GROUP_LIMIT' : 'QUOTA_EXHAUSTED';
|
|
71
|
+
const code = remainingMs <= 0 ? reason : remainingMs <= warningBeforeMs ? 'QUOTA_WARNING' : 'QUOTA_OK';
|
|
72
|
+
return {
|
|
73
|
+
remainingMs,
|
|
74
|
+
code,
|
|
75
|
+
reason
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
async function debit(ctx, ms) {
|
|
79
|
+
const amount = Math.max(0, Math.round(ms));
|
|
80
|
+
if (!amount) return 0;
|
|
81
|
+
await use('addMs', [ctx.userId, ctx.plan, ctx.role, amount]);
|
|
82
|
+
if (countGroup(ctx)) await use('addGroupMs', [ctx.groupId, ctx.plan, amount]);
|
|
83
|
+
return amount;
|
|
84
|
+
}
|
|
85
|
+
async function charge(ctx, startedAt, chargedMs = 0) {
|
|
86
|
+
const elapsedMs = Math.max(0, Math.min(maxCallMs, now() - startedAt));
|
|
87
|
+
await debit(ctx, elapsedMs - chargedMs);
|
|
88
|
+
return elapsedMs;
|
|
89
|
+
}
|
|
90
|
+
return {
|
|
91
|
+
check,
|
|
92
|
+
debit,
|
|
93
|
+
charge,
|
|
94
|
+
limitFor,
|
|
95
|
+
groupLimitFor
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
function createDailyCounter({
|
|
99
|
+
store,
|
|
100
|
+
now
|
|
101
|
+
}) {
|
|
102
|
+
if (typeof now !== 'function') throw new TypeError('CLOCK_REQUIRED');
|
|
103
|
+
const local = new Map();
|
|
104
|
+
let storeAvailable = true;
|
|
105
|
+
function key(id) {
|
|
106
|
+
return JSON.stringify([new Date(now()).toISOString().slice(0, 10), id]);
|
|
107
|
+
}
|
|
108
|
+
function untilMidnightMs() {
|
|
109
|
+
const current = now();
|
|
110
|
+
return (Math.floor(current / 86400000) + 1) * 86400000 - current;
|
|
111
|
+
}
|
|
112
|
+
return {
|
|
113
|
+
async used(id) {
|
|
114
|
+
const name = key(id);
|
|
115
|
+
if (storeAvailable && store?.get) {
|
|
116
|
+
try {
|
|
117
|
+
return Number(await store.get(name)) || 0;
|
|
118
|
+
} catch (_error) {
|
|
119
|
+
storeAvailable = false;
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
return local.get(name) || 0;
|
|
123
|
+
},
|
|
124
|
+
async add(id, amount = 1) {
|
|
125
|
+
const name = key(id);
|
|
126
|
+
local.set(name, (local.get(name) || 0) + Math.max(0, amount));
|
|
127
|
+
if (storeAvailable && store?.add) {
|
|
128
|
+
try {
|
|
129
|
+
await store.add(name, Math.max(0, amount), untilMidnightMs());
|
|
130
|
+
} catch (_error) {
|
|
131
|
+
storeAvailable = false;
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
return local.get(name);
|
|
135
|
+
}
|
|
136
|
+
};
|
|
137
|
+
}
|
|
138
|
+
function createCallLease({
|
|
139
|
+
store,
|
|
140
|
+
ttlMs = 90000
|
|
141
|
+
}) {
|
|
142
|
+
if (!store?.get || !store?.set || !store?.delete) throw new TypeError('LEASE_DEPENDENCY_REQUIRED');
|
|
143
|
+
return {
|
|
144
|
+
async acquire(userId, callId) {
|
|
145
|
+
await store.set(userId, callId, ttlMs);
|
|
146
|
+
},
|
|
147
|
+
async isOwner(userId, callId) {
|
|
148
|
+
if ((await store.get(userId)) !== callId) return false;
|
|
149
|
+
await store.set(userId, callId, ttlMs);
|
|
150
|
+
return true;
|
|
151
|
+
},
|
|
152
|
+
async release(userId, callId) {
|
|
153
|
+
if ((await store.get(userId)) === callId) await store.delete(userId);
|
|
154
|
+
}
|
|
155
|
+
};
|
|
156
|
+
}
|
|
157
|
+
module.exports = {
|
|
158
|
+
createMemoryMinuteStore,
|
|
159
|
+
createMinuteQuota,
|
|
160
|
+
createDailyCounter,
|
|
161
|
+
createCallLease
|
|
162
|
+
};
|
package/src/reader.js
ADDED
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const voice = require('@astratra/voice');
|
|
4
|
+
const {
|
|
5
|
+
createGeminiLiveAdapter
|
|
6
|
+
} = require('./gemini');
|
|
7
|
+
function createLiveReader({
|
|
8
|
+
primary = null,
|
|
9
|
+
providers = [],
|
|
10
|
+
maxConcurrent = 1,
|
|
11
|
+
drift = {},
|
|
12
|
+
logger = {}
|
|
13
|
+
} = {}) {
|
|
14
|
+
const fallback = voice.createPieceVoiceService({
|
|
15
|
+
providers,
|
|
16
|
+
maxConcurrent
|
|
17
|
+
});
|
|
18
|
+
let generation = 0;
|
|
19
|
+
let closed = false;
|
|
20
|
+
return {
|
|
21
|
+
async synthesize({
|
|
22
|
+
text,
|
|
23
|
+
language,
|
|
24
|
+
signal,
|
|
25
|
+
onPiece,
|
|
26
|
+
onReset
|
|
27
|
+
} = {}) {
|
|
28
|
+
if (closed || signal?.aborted) return {
|
|
29
|
+
pieces: [],
|
|
30
|
+
code: 'INTERRUPTED'
|
|
31
|
+
};
|
|
32
|
+
const expected = String(text || '').trim();
|
|
33
|
+
if (!expected) return {
|
|
34
|
+
pieces: [],
|
|
35
|
+
code: 'TEXT_REQUIRED'
|
|
36
|
+
};
|
|
37
|
+
const current = generation;
|
|
38
|
+
if (primary?.synthesize) {
|
|
39
|
+
let streamedPieces = false;
|
|
40
|
+
try {
|
|
41
|
+
const result = await primary.synthesize({
|
|
42
|
+
text: expected,
|
|
43
|
+
language,
|
|
44
|
+
signal,
|
|
45
|
+
onPiece: onPiece ? (piece) => {
|
|
46
|
+
streamedPieces = true;
|
|
47
|
+
onPiece(piece);
|
|
48
|
+
} : undefined
|
|
49
|
+
});
|
|
50
|
+
if (closed || signal?.aborted || current !== generation) return {
|
|
51
|
+
pieces: [],
|
|
52
|
+
code: 'INTERRUPTED'
|
|
53
|
+
};
|
|
54
|
+
if (!result || !result.audio && !result.pieces?.length) throw new Error('EMPTY_AUDIO');
|
|
55
|
+
if (!result?.spokenText || !voice.hasSpeechDrift(expected, result.spokenText, {
|
|
56
|
+
...drift,
|
|
57
|
+
final: true
|
|
58
|
+
})) {
|
|
59
|
+
return {
|
|
60
|
+
pieces: result?.pieces || [result],
|
|
61
|
+
provider: primary.id || 'primary',
|
|
62
|
+
fallback: false,
|
|
63
|
+
streamed: Boolean(result.streamed)
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
logger.warn?.('SPEECH_DRIFT');
|
|
67
|
+
if (result.streamed) onReset?.();
|
|
68
|
+
} catch (_error) {
|
|
69
|
+
if (closed || signal?.aborted || current !== generation) return { pieces: [], code: 'INTERRUPTED' };
|
|
70
|
+
if (streamedPieces) onReset?.();
|
|
71
|
+
logger.warn?.('READER_PRIMARY_FAILED');
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
try {
|
|
75
|
+
const result = await fallback.synthesize(expected, {
|
|
76
|
+
language
|
|
77
|
+
});
|
|
78
|
+
if (closed || signal?.aborted || current !== generation) return {
|
|
79
|
+
pieces: [],
|
|
80
|
+
code: 'INTERRUPTED'
|
|
81
|
+
};
|
|
82
|
+
if (onPiece) for (const piece of result.pieces || [result]) onPiece(piece);
|
|
83
|
+
return {
|
|
84
|
+
...result,
|
|
85
|
+
fallback: true,
|
|
86
|
+
streamed: Boolean(onPiece)
|
|
87
|
+
};
|
|
88
|
+
} catch (_error) {
|
|
89
|
+
if (closed || signal?.aborted || current !== generation) return { pieces: [], code: 'INTERRUPTED' };
|
|
90
|
+
return {
|
|
91
|
+
pieces: [],
|
|
92
|
+
code: 'VOICE_UNAVAILABLE'
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
},
|
|
96
|
+
interrupt() {
|
|
97
|
+
generation += 1;
|
|
98
|
+
primary?.interrupt?.();
|
|
99
|
+
},
|
|
100
|
+
close() {
|
|
101
|
+
closed = true;
|
|
102
|
+
generation += 1;
|
|
103
|
+
primary?.close?.();
|
|
104
|
+
}
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
function createGeminiLiveReader({
|
|
108
|
+
adapter,
|
|
109
|
+
websocketFactory,
|
|
110
|
+
candidates,
|
|
111
|
+
clock,
|
|
112
|
+
voice: voiceName,
|
|
113
|
+
providers = [],
|
|
114
|
+
timeoutMs = 12000,
|
|
115
|
+
instructions = '',
|
|
116
|
+
logger = {}
|
|
117
|
+
}) {
|
|
118
|
+
if (!clock) throw new TypeError('CLOCK_REQUIRED');
|
|
119
|
+
const live = adapter || createGeminiLiveAdapter({
|
|
120
|
+
websocketFactory,
|
|
121
|
+
candidates,
|
|
122
|
+
voice: voiceName,
|
|
123
|
+
clock,
|
|
124
|
+
logger
|
|
125
|
+
});
|
|
126
|
+
let currentLine = null;
|
|
127
|
+
let rejectActive = null;
|
|
128
|
+
let queue = Promise.resolve();
|
|
129
|
+
const primary = {
|
|
130
|
+
id: 'gemini-live',
|
|
131
|
+
synthesize({
|
|
132
|
+
text,
|
|
133
|
+
signal,
|
|
134
|
+
onPiece
|
|
135
|
+
}) {
|
|
136
|
+
const operation = queue.then(() => readTurn(text, signal, onPiece));
|
|
137
|
+
queue = operation.catch(() => {});
|
|
138
|
+
return operation;
|
|
139
|
+
},
|
|
140
|
+
interrupt() {
|
|
141
|
+
rejectActive?.(new Error('INTERRUPTED'));
|
|
142
|
+
currentLine?.close?.();
|
|
143
|
+
},
|
|
144
|
+
close() {
|
|
145
|
+
rejectActive?.(new Error('INTERRUPTED'));
|
|
146
|
+
currentLine?.close?.();
|
|
147
|
+
}
|
|
148
|
+
};
|
|
149
|
+
async function readTurn(text, signal, onPiece) {
|
|
150
|
+
const pieces = [];
|
|
151
|
+
let transcription = '';
|
|
152
|
+
let modelText = '';
|
|
153
|
+
let settle;
|
|
154
|
+
let reject;
|
|
155
|
+
const completion = new Promise((resolve, fail) => {
|
|
156
|
+
settle = resolve;
|
|
157
|
+
reject = fail;
|
|
158
|
+
});
|
|
159
|
+
let timer;
|
|
160
|
+
const abort = () => reject(new Error('INTERRUPTED'));
|
|
161
|
+
try {
|
|
162
|
+
currentLine = await live.connect({
|
|
163
|
+
instructions,
|
|
164
|
+
onEvent(event) {
|
|
165
|
+
if (event.type === 'audio') {
|
|
166
|
+
const piece = { audio: Buffer.from(event.data, 'base64'), mimeType: event.mimeType };
|
|
167
|
+
pieces.push(piece);
|
|
168
|
+
onPiece?.(piece);
|
|
169
|
+
}
|
|
170
|
+
if (event.type === 'said') transcription += event.text;
|
|
171
|
+
if (event.type === 'text') modelText += event.text;
|
|
172
|
+
if (event.type === 'turn') settle();
|
|
173
|
+
if (event.type === 'error') reject(new Error(event.code));
|
|
174
|
+
},
|
|
175
|
+
onClose: reject
|
|
176
|
+
});
|
|
177
|
+
if (signal?.aborted) throw new Error('INTERRUPTED');
|
|
178
|
+
rejectActive = reject;
|
|
179
|
+
timer = clock.setTimeout(() => reject(new Error('READER_TIMEOUT')), timeoutMs);
|
|
180
|
+
signal?.addEventListener?.('abort', abort, { once: true });
|
|
181
|
+
currentLine.sendText(text);
|
|
182
|
+
await completion;
|
|
183
|
+
return {
|
|
184
|
+
pieces,
|
|
185
|
+
spokenText: transcription || modelText,
|
|
186
|
+
streamed: Boolean(onPiece)
|
|
187
|
+
};
|
|
188
|
+
} finally {
|
|
189
|
+
if (timer !== undefined) clock.clearTimeout(timer);
|
|
190
|
+
signal?.removeEventListener?.('abort', abort);
|
|
191
|
+
rejectActive = null;
|
|
192
|
+
currentLine?.close?.();
|
|
193
|
+
currentLine = null;
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
return createLiveReader({
|
|
197
|
+
primary,
|
|
198
|
+
providers,
|
|
199
|
+
logger
|
|
200
|
+
});
|
|
201
|
+
}
|
|
202
|
+
module.exports = {
|
|
203
|
+
createLiveReader,
|
|
204
|
+
createGeminiLiveReader
|
|
205
|
+
};
|