@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.
@@ -0,0 +1,287 @@
1
+ 'use strict';
2
+
3
+ async function* parseSse(stream) {
4
+ const decoder = new globalThis.TextDecoder();
5
+ let buffer = '';
6
+ for await (const chunk of stream) {
7
+ buffer += decoder.decode(chunk, {
8
+ stream: true
9
+ });
10
+ let boundary = buffer.search(/\r?\n\r?\n/);
11
+ while (boundary >= 0) {
12
+ const block = buffer.slice(0, boundary);
13
+ buffer = buffer.slice(boundary).replace(/^\r?\n\r?\n/, '');
14
+ const data = block.split(/\r?\n/).filter(line => line.startsWith('data:')).map(line => line.slice(5).trim()).join('');
15
+ if (data) {
16
+ try {
17
+ yield JSON.parse(data);
18
+ } catch (_error) {/* Skip a malformed event. */}
19
+ }
20
+ boundary = buffer.search(/\r?\n\r?\n/);
21
+ }
22
+ }
23
+ buffer += decoder.decode();
24
+ const data = buffer.split(/\r?\n/).filter(line => line.startsWith('data:')).map(line => line.slice(5).trim()).join('');
25
+ if (data) {
26
+ try {
27
+ yield JSON.parse(data);
28
+ } catch (_error) {/* Skip a malformed final event. */}
29
+ }
30
+ }
31
+ function createGeminiTextModel({
32
+ fetch,
33
+ candidates = [],
34
+ endpoint = 'https://generativelanguage.googleapis.com/v1beta',
35
+ clock,
36
+ timeoutMs = 20000,
37
+ cooldownMs = 600000,
38
+ generationConfig = {},
39
+ logger = {}
40
+ }) {
41
+ if (typeof fetch !== 'function' || !clock) throw new TypeError('TEXT_MODEL_DEPENDENCY_REQUIRED');
42
+ const resting = new Map();
43
+ return {
44
+ async generate({
45
+ instructions,
46
+ contents,
47
+ declarations = [],
48
+ signal,
49
+ onText = () => {}
50
+ }) {
51
+ const ordered = [
52
+ ...candidates.filter(item => (resting.get(item.key) || 0) <= clock.now()),
53
+ ...candidates.filter(item => (resting.get(item.key) || 0) > clock.now())
54
+ ];
55
+ for (const candidate of ordered) {
56
+ if (signal?.aborted) return {
57
+ parts: [],
58
+ interrupted: true
59
+ };
60
+ const controller = new globalThis.AbortController();
61
+ const abort = () => controller.abort();
62
+ signal?.addEventListener?.('abort', abort, {
63
+ once: true
64
+ });
65
+ const timer = clock.setTimeout(abort, timeoutMs);
66
+ const parts = [];
67
+ let started = false;
68
+ try {
69
+ const response = await fetch(`${endpoint}/models/${encodeURIComponent(candidate.model)}:streamGenerateContent?alt=sse`, {
70
+ method: 'POST',
71
+ headers: {
72
+ 'Content-Type': 'application/json',
73
+ 'x-goog-api-key': candidate.key
74
+ },
75
+ body: JSON.stringify({
76
+ systemInstruction: {
77
+ parts: [{
78
+ text: instructions
79
+ }]
80
+ },
81
+ contents,
82
+ ...(declarations.length ? {
83
+ tools: [{
84
+ functionDeclarations: declarations
85
+ }]
86
+ } : {}),
87
+ generationConfig: {
88
+ temperature: 0.7,
89
+ maxOutputTokens: 1024,
90
+ ...generationConfig
91
+ }
92
+ }),
93
+ signal: controller.signal
94
+ });
95
+ if (!response.ok) {
96
+ if ([400, 401, 403, 429].includes(response.status)) resting.set(candidate.key, clock.now() + cooldownMs);
97
+ continue;
98
+ }
99
+ for await (const event of parseSse(response.body)) {
100
+ for (const part of event.candidates?.[0]?.content?.parts || []) {
101
+ parts.push(part);
102
+ if (typeof part.text === 'string' && !part.thought) {
103
+ started = true;
104
+ onText(part.text);
105
+ }
106
+ }
107
+ }
108
+ return {
109
+ parts,
110
+ interrupted: Boolean(signal?.aborted)
111
+ };
112
+ } catch (error) {
113
+ if (signal?.aborted) return {
114
+ parts,
115
+ interrupted: true
116
+ };
117
+ if (started) return {
118
+ parts,
119
+ interrupted: false
120
+ };
121
+ logger.warn?.('TEXT_PROVIDER_FAILED', {
122
+ code: error?.code
123
+ });
124
+ } finally {
125
+ clock.clearTimeout(timer);
126
+ signal?.removeEventListener?.('abort', abort);
127
+ }
128
+ }
129
+ throw Object.assign(new Error('TEXT_MODEL_UNAVAILABLE'), {
130
+ code: 'TEXT_MODEL_UNAVAILABLE'
131
+ });
132
+ }
133
+ };
134
+ }
135
+ function createTextThinker({
136
+ model,
137
+ instructions,
138
+ declarations = [],
139
+ tools,
140
+ earlier = [],
141
+ maxTurns = 6,
142
+ maxHistory = 40,
143
+ onTool = () => {}
144
+ }) {
145
+ if (!model?.generate) throw new TypeError('TEXT_MODEL_REQUIRED');
146
+ let history = [];
147
+ for (const turn of earlier) {
148
+ const role = turn.who === 'person' || turn.role === 'user' ? 'user' : 'model';
149
+ const text = String(turn.text || '').trim();
150
+ if (!text) continue;
151
+ const last = history.at(-1);
152
+ if (last?.role === role) last.parts[0].text += `\n${text}`;else history.push({
153
+ role,
154
+ parts: [{
155
+ text
156
+ }]
157
+ });
158
+ }
159
+ if (history[0]?.role === 'model') history.shift();
160
+ let lastStart = null;
161
+ function trim() {
162
+ if (history.length <= maxHistory) return;
163
+ let at = history.length - maxHistory;
164
+ while (at < history.length && !(history[at].role === 'user' && history[at].parts[0]?.text !== undefined)) at += 1;
165
+ history = history.slice(at);
166
+ }
167
+ return {
168
+ async respond(question, {
169
+ onText = () => {},
170
+ signal
171
+ } = {}) {
172
+ lastStart = history.length;
173
+ history.push({
174
+ role: 'user',
175
+ parts: [{
176
+ text: question
177
+ }]
178
+ });
179
+ let spoken = '';
180
+ for (let turn = 0; turn < maxTurns; turn += 1) {
181
+ let result;
182
+ let streamed = false;
183
+ try {
184
+ result = await model.generate({
185
+ instructions,
186
+ contents: history,
187
+ declarations,
188
+ signal,
189
+ onText: part => {
190
+ streamed = true;
191
+ spoken += part;
192
+ onText(part);
193
+ }
194
+ });
195
+ } catch (error) {
196
+ history.splice(lastStart);
197
+ throw error;
198
+ }
199
+ const parts = result.parts || [];
200
+ if (!streamed) for (const part of parts) if (typeof part.text === 'string' && !part.thought) {
201
+ spoken += part.text;
202
+ onText(part.text);
203
+ }
204
+ const interrupted = Boolean(result.interrupted);
205
+ const calls = interrupted ? [] : parts.filter(part => part.functionCall).map(part => part.functionCall);
206
+ if (parts.length) {
207
+ const text = parts.filter(part => typeof part.text === 'string' && !part.thought).map(part => part.text).join('');
208
+ const retained = calls.length && !interrupted ? parts : [...(text ? [{
209
+ text: interrupted ? `${text}…` : text
210
+ }] : []), ...parts.filter(part => typeof part.text !== 'string')];
211
+ history.push({
212
+ role: 'model',
213
+ parts: retained
214
+ });
215
+ }
216
+ if (!calls.length) {
217
+ trim();
218
+ return {
219
+ text: spoken,
220
+ interrupted
221
+ };
222
+ }
223
+ const responses = await Promise.all(calls.map(async call => {
224
+ onTool(call.name, 'start');
225
+ let result;
226
+ try {
227
+ result = await tools.call({
228
+ id: call.id,
229
+ name: call.name,
230
+ args: call.args || {}
231
+ });
232
+ } catch (_error) {
233
+ result = {
234
+ code: 'TOOL_FAILED'
235
+ };
236
+ }
237
+ onTool(call.name, 'end');
238
+ return {
239
+ functionResponse: {
240
+ ...(call.id ? {
241
+ id: call.id
242
+ } : {}),
243
+ name: call.name,
244
+ response: {
245
+ result
246
+ }
247
+ }
248
+ };
249
+ }));
250
+ history.push({
251
+ role: 'user',
252
+ parts: responses
253
+ });
254
+ if (signal?.aborted) {
255
+ trim();
256
+ return {
257
+ text: spoken,
258
+ interrupted: true
259
+ };
260
+ }
261
+ }
262
+ trim();
263
+ return {
264
+ text: spoken,
265
+ interrupted: false,
266
+ limitReached: true
267
+ };
268
+ },
269
+ undoLast() {
270
+ if (lastStart !== null) history.splice(lastStart);
271
+ lastStart = null;
272
+ },
273
+ get history() {
274
+ return history.map(turn => ({
275
+ role: turn.role,
276
+ parts: turn.parts.map(part => ({
277
+ ...part
278
+ }))
279
+ }));
280
+ }
281
+ };
282
+ }
283
+ module.exports = {
284
+ parseSse,
285
+ createGeminiTextModel,
286
+ createTextThinker
287
+ };
package/src/tools.js ADDED
@@ -0,0 +1,284 @@
1
+ 'use strict';
2
+
3
+ function normalizeSpeech(value) {
4
+ return String(value || '').normalize('NFD').replace(/[\u0300-\u036f]/g, '').toLowerCase().replace(/[^a-z]+/g, ' ').trim();
5
+ }
6
+ function hasPhrase(text, phrases) {
7
+ const normalized = ` ${normalizeSpeech(text)} `;
8
+ return phrases.some(phrase => normalized.includes(` ${normalizeSpeech(phrase)} `));
9
+ }
10
+ function createSpokenConfirmation({
11
+ now,
12
+ timeoutMs = 120000,
13
+ affirmative = {},
14
+ negative = {}
15
+ }) {
16
+ let pending = null;
17
+ let previous = null;
18
+ return {
19
+ propose(id) {
20
+ pending = {
21
+ id,
22
+ at: now(),
23
+ readBack: false,
24
+ answer: ''
25
+ };
26
+ },
27
+ heard({
28
+ who,
29
+ text
30
+ }) {
31
+ if (!pending) return;
32
+ if (who === 'assistant') {
33
+ pending.readBack = true;
34
+ } else if (who === 'person' && pending.readBack) {
35
+ pending.answer = previous === 'person' ? `${pending.answer} ${text}` : String(text);
36
+ }
37
+ previous = who;
38
+ },
39
+ verify(id, language) {
40
+ if (!pending || pending.id !== id) return 'ACTION_MISSING';
41
+ if (now() - pending.at > timeoutMs) {
42
+ pending = null;
43
+ return 'ACTION_EXPIRED';
44
+ }
45
+ if (!pending.readBack) return 'READBACK_MISSING';
46
+ if (!pending.answer) return 'ANSWER_MISSING';
47
+ return hasPhrase(pending.answer, affirmative[language] || []) && !hasPhrase(pending.answer, negative[language] || []) ? 'CONFIRMED' : 'CONSENT_MISSING';
48
+ },
49
+ clear(id) {
50
+ if (pending?.id === id) pending = null;
51
+ },
52
+ get pendingId() {
53
+ return pending && now() - pending.at <= timeoutMs ? pending.id : null;
54
+ }
55
+ };
56
+ }
57
+ function toolDeclarations(registry, role, catalog = {}) {
58
+ if (!registry) return [];
59
+ const describeParameter = description => {
60
+ if (description && typeof description === 'object') return description;
61
+ const label = String(description || '');
62
+ const match = /^(number|boolean|object|string)\b/i.exec(label);
63
+ return {
64
+ type: match ? match[1].toLowerCase() : 'string',
65
+ description: label
66
+ };
67
+ };
68
+ const tools = registry.getToolsForRole(role).filter(tool => tool.type === 'write' || typeof tool.handler === 'function').map(tool => ({
69
+ name: tool.name,
70
+ description: tool.description,
71
+ parameters: {
72
+ type: 'object',
73
+ properties: Object.fromEntries(Object.entries(tool.params || {}).map(([name, description]) => [name, describeParameter(description)])),
74
+ required: Object.entries(tool.params || {})
75
+ .filter(([, description]) => {
76
+ if (description && typeof description === 'object') {
77
+ return description.required !== false && description.optional !== true;
78
+ }
79
+ return !/optional|optionnel|défaut|defaut/i.test(String(description));
80
+ })
81
+ .map(([name]) => name)
82
+ }
83
+ }));
84
+ if (!tools.some(tool => registry.getToolByName(tool.name)?.type === 'write')) return tools;
85
+ const parameters = {
86
+ type: 'object',
87
+ properties: {
88
+ actionId: {
89
+ type: 'string'
90
+ }
91
+ },
92
+ required: ['actionId']
93
+ };
94
+ return [...tools, {
95
+ name: 'confirm_action',
96
+ description: catalog.confirmAction || 'CONFIRM_ACTION',
97
+ parameters
98
+ }, {
99
+ name: 'cancel_action',
100
+ description: catalog.cancelAction || 'CANCEL_ACTION',
101
+ parameters
102
+ }];
103
+ }
104
+ function createCallTools({
105
+ registry,
106
+ context,
107
+ confirmation,
108
+ actions,
109
+ shield = {},
110
+ clock,
111
+ timeoutMs = 20000,
112
+ maxResultChars = 6000,
113
+ send = () => {},
114
+ onResult = () => {},
115
+ catalog = {}
116
+ }) {
117
+ const safe = (kind, value) => typeof shield[kind] === 'function' ? shield[kind](value) : value;
118
+ async function withTimeout(promise) {
119
+ let timer;
120
+ try {
121
+ return await Promise.race([promise, new Promise((_, reject) => {
122
+ timer = clock.setTimeout(() => reject({
123
+ code: 'TOOL_TIMEOUT'
124
+ }), timeoutMs);
125
+ })]);
126
+ } finally {
127
+ clock.clearTimeout(timer);
128
+ }
129
+ }
130
+ return {
131
+ declarations: toolDeclarations(registry, context.role, catalog),
132
+ async confirmByClient(actionId) {
133
+ if (!actionId || confirmation.pendingId !== actionId) return {
134
+ code: 'ACTION_MISSING'
135
+ };
136
+ confirmation.clear(actionId);
137
+ try {
138
+ const result = await actions.execute(actionId, context);
139
+ send({
140
+ type: 'action_done',
141
+ actionId,
142
+ ok: Boolean(result?.success)
143
+ });
144
+ return {
145
+ code: result?.success ? 'ACTION_DONE' : 'ACTION_FAILED'
146
+ };
147
+ } catch (_error) {
148
+ send({
149
+ type: 'action_done',
150
+ actionId,
151
+ ok: false
152
+ });
153
+ return {
154
+ code: 'ACTION_FAILED'
155
+ };
156
+ }
157
+ },
158
+ async cancelByClient(actionId) {
159
+ if (!actionId || confirmation.pendingId !== actionId) return {
160
+ code: 'ACTION_MISSING'
161
+ };
162
+ confirmation.clear(actionId);
163
+ try {
164
+ await actions.cancel?.(actionId, context);
165
+ } catch (_error) {/* The pending action was cleared locally. */}
166
+ send({
167
+ type: 'action_cancelled',
168
+ actionId
169
+ });
170
+ return {
171
+ code: 'ACTION_CANCELLED'
172
+ };
173
+ },
174
+ async call({
175
+ name,
176
+ args = {}
177
+ }) {
178
+ const tool = registry?.getToolByName(name);
179
+ const input = await (tool?.external && typeof shield.external === 'function'
180
+ ? shield.external(args)
181
+ : safe(typeof shield.args === 'function' ? 'args' : 'input', args));
182
+ if (name === 'confirm_action') {
183
+ const verdict = confirmation.verify(input.actionId, context.language);
184
+ if (verdict !== 'CONFIRMED') return {
185
+ code: verdict
186
+ };
187
+ confirmation.clear(input.actionId);
188
+ try {
189
+ const result = await actions.execute(input.actionId, context);
190
+ send({
191
+ type: 'action_done',
192
+ actionId: input.actionId,
193
+ ok: Boolean(result?.success)
194
+ });
195
+ return {
196
+ code: result?.success ? 'ACTION_DONE' : 'ACTION_FAILED'
197
+ };
198
+ } catch (_error) {
199
+ return {
200
+ code: 'ACTION_FAILED'
201
+ };
202
+ }
203
+ }
204
+ if (name === 'cancel_action') {
205
+ if (confirmation.pendingId !== input.actionId) return {
206
+ code: 'ACTION_MISSING'
207
+ };
208
+ confirmation.clear(input.actionId);
209
+ try {
210
+ await actions.cancel?.(input.actionId, context);
211
+ } catch (_error) {/* The pending action was cleared locally. */}
212
+ send({
213
+ type: 'action_cancelled',
214
+ actionId: input.actionId
215
+ });
216
+ return {
217
+ code: 'ACTION_CANCELLED'
218
+ };
219
+ }
220
+ if (!tool || !tool.roles.includes(context.role)) return {
221
+ code: 'TOOL_DENIED'
222
+ };
223
+ if (tool.type === 'write') {
224
+ if (!actions?.queue) return {
225
+ code: 'ACTION_UNAVAILABLE'
226
+ };
227
+ try {
228
+ const actionId = await actions.queue({
229
+ name,
230
+ args: input,
231
+ context
232
+ });
233
+ confirmation.propose(actionId);
234
+ send({
235
+ type: 'confirm',
236
+ actionId
237
+ });
238
+ return {
239
+ code: 'CONFIRMATION_REQUIRED',
240
+ actionId
241
+ };
242
+ } catch (_error) {
243
+ return {
244
+ code: 'ACTION_UNAVAILABLE'
245
+ };
246
+ }
247
+ }
248
+ try {
249
+ const rawResult = await withTimeout(Promise.resolve().then(() => tool.handler(input, context)));
250
+ const result = await safe(typeof shield.result === 'function' ? 'result' : 'output', rawResult);
251
+ try {
252
+ onResult(name, result);
253
+ } catch (_error) {/* Annotations are optional. */}
254
+ const serialized = JSON.stringify(result ?? null);
255
+ return serialized.length <= maxResultChars ? result : {
256
+ code: 'RESULT_TRUNCATED',
257
+ value: serialized.slice(0, maxResultChars)
258
+ };
259
+ } catch (error) {
260
+ return {
261
+ code: error?.code === 'TOOL_TIMEOUT' ? 'TOOL_TIMEOUT' : 'TOOL_FAILED'
262
+ };
263
+ }
264
+ }
265
+ };
266
+ }
267
+ function buildInstructions({
268
+ persona,
269
+ language,
270
+ role,
271
+ now,
272
+ catalog = {},
273
+ shield
274
+ }) {
275
+ const pieces = [persona, catalog.language?.[language], catalog.role?.[role], catalog.voice, catalog.confirmation, now?.()];
276
+ return pieces.filter(piece => piece != null && piece !== '').map(piece => shield?.input ? shield.input(String(piece)) : String(piece)).join('\n');
277
+ }
278
+ module.exports = {
279
+ normalizeSpeech,
280
+ createSpokenConfirmation,
281
+ toolDeclarations,
282
+ createCallTools,
283
+ buildInstructions
284
+ };