neuroniun 0.3.0 → 0.7.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/CHANGELOG.md +89 -0
- package/README.md +176 -1
- package/bin/neuroniun.js +57 -17
- package/package.json +5 -3
- package/src/api.js +14 -2
- package/src/console.js +28 -5
- package/src/estado.js +49 -0
- package/src/executores.js +474 -0
- package/src/ia.js +221 -0
- package/src/login.js +207 -0
- package/src/ncall.js +351 -0
- package/src/ncall_cli.js +308 -0
- package/src/ncall_fala.js +366 -0
- package/src/ncall_regra.js +71 -0
- package/src/ncall_vad.js +258 -0
- package/src/recibo.js +88 -0
- package/src/redigir.js +44 -0
- package/src/redigir_cofre.cjs +213 -0
- package/src/servico.js +124 -0
- package/src/shell.js +36 -0
- package/src/store.js +7 -1
- package/src/ticket.js +79 -0
- package/src/uso.js +158 -0
- package/src/worker.js +489 -23
package/src/ncall.js
ADDED
|
@@ -0,0 +1,351 @@
|
|
|
1
|
+
// Cliente do agente na sala do N-Call (spec docs/specs/1-abertas/20261121-ncall-agentes.md §1, F1).
|
|
2
|
+
// Entra na sala LiveKit, separa a fala de cada participante (VAD por trilha), manda cada trecho ao
|
|
3
|
+
// rea_ouvir (fila no servidor; a task transcreve cobrando a empresa) e le o texto pelo rea_estado.
|
|
4
|
+
// A biblioteca @livekit/rtc-node e opcional: so e carregada aqui, por import dinamico.
|
|
5
|
+
import { SegmentadorDeFala, wavBase64, energiaDb } from './ncall_vad.js';
|
|
6
|
+
import { foiChamado } from './ncall_regra.js';
|
|
7
|
+
import { FalaDoAgente, codifica, decodifica, lerWav, TOPICO_DA_SALA } from './ncall_fala.js';
|
|
8
|
+
import { callPublic, Cru } from './api.js';
|
|
9
|
+
|
|
10
|
+
// Interrupcao: limiar de voz um pouco acima do do segmentador (-45 dB) e 6 quadros de 10 ms seguidos.
|
|
11
|
+
const limiarInterrupcaoDb = -40;
|
|
12
|
+
const quadrosParaInterromper = 6;
|
|
13
|
+
|
|
14
|
+
/** Identidade de agente na sala: `A_<agente>` (o nucleo pode devolver em minusculas, `a_…`). */
|
|
15
|
+
export function ehAgente(identidade) {
|
|
16
|
+
return /^a_/i.test(String(identidade || ''));
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function falanteSeguro(identidade) {
|
|
20
|
+
if (!identidade) return 'anon';
|
|
21
|
+
const limpo = identidade.replace(/[^A-Za-z0-9_]/g, '_');
|
|
22
|
+
if (limpo.length === 0) return 'anon';
|
|
23
|
+
return limpo.slice(0, 64);
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export async function esperaTexto(chamar, token, id, { tentativas = 12, intervaloMs = 2500, dorme, flow = 'rea_estado' } = {}) {
|
|
27
|
+
const dormir = dorme || ((ms) => new Promise((r) => setTimeout(r, ms)));
|
|
28
|
+
for (let i = 0; i < tentativas; i++) {
|
|
29
|
+
const r = await chamar(flow, [token, id]);
|
|
30
|
+
if (r?.ok === true && r.estado !== 'na_fila') {
|
|
31
|
+
return r;
|
|
32
|
+
}
|
|
33
|
+
// Falha definitiva (stt_falhou, token_invalido, id_invalido): nao adianta esperar mais.
|
|
34
|
+
if (r?.ok === false) {
|
|
35
|
+
return r;
|
|
36
|
+
}
|
|
37
|
+
if (i < tentativas - 1) {
|
|
38
|
+
await dormir(intervaloMs);
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
return { ok: false, codigo: 'tempo_esgotado' };
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export async function entrarNaSala(opcoes) {
|
|
45
|
+
const {
|
|
46
|
+
urlLiveKit,
|
|
47
|
+
tokenLiveKit,
|
|
48
|
+
sala,
|
|
49
|
+
agente,
|
|
50
|
+
apelido,
|
|
51
|
+
tokenBash,
|
|
52
|
+
baseUrl,
|
|
53
|
+
instancia,
|
|
54
|
+
lk,
|
|
55
|
+
chamar,
|
|
56
|
+
aoFalar,
|
|
57
|
+
aoSerChamado,
|
|
58
|
+
aoEsvaziar,
|
|
59
|
+
esperaVaziaMs = 60000,
|
|
60
|
+
agendar = { setTimeout: globalThis.setTimeout, clearTimeout: globalThis.clearTimeout },
|
|
61
|
+
log = () => {},
|
|
62
|
+
esperaOpts = {},
|
|
63
|
+
// F2 (o agente FALA): liga com o apelido; `comVoz` publica a voz como trilha; `idioma` dos avisos.
|
|
64
|
+
fala = true,
|
|
65
|
+
comVoz = true,
|
|
66
|
+
idioma = 'pt',
|
|
67
|
+
nome = '',
|
|
68
|
+
aoPedirSaida,
|
|
69
|
+
falaOpts = {},
|
|
70
|
+
} = opcoes;
|
|
71
|
+
|
|
72
|
+
let lkMod = lk;
|
|
73
|
+
if (!lkMod) {
|
|
74
|
+
try {
|
|
75
|
+
lkMod = await import('@livekit/rtc-node');
|
|
76
|
+
} catch {
|
|
77
|
+
throw new Error('instale @livekit/rtc-node: npm i -g @livekit/rtc-node');
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
const chamarFlow = chamar || ((flow, args) => callPublic(baseUrl, instancia, flow, args));
|
|
82
|
+
|
|
83
|
+
const room = new lkMod.Room();
|
|
84
|
+
const seg = new SegmentadorDeFala({ taxa: 16000 });
|
|
85
|
+
const falas = [];
|
|
86
|
+
const fila = [];
|
|
87
|
+
let processando = false;
|
|
88
|
+
// Criado depois do connect (precisa da identidade local); antes disso nada fala.
|
|
89
|
+
let falaAg = null;
|
|
90
|
+
|
|
91
|
+
// --- contagem de participantes remotos e timer de sala vazia ---
|
|
92
|
+
let timerVazia = null;
|
|
93
|
+
let esvaziou = false;
|
|
94
|
+
|
|
95
|
+
function cancelaTimerVazia() {
|
|
96
|
+
if (timerVazia !== null) {
|
|
97
|
+
agendar.clearTimeout(timerVazia);
|
|
98
|
+
timerVazia = null;
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function armaTimerVazia() {
|
|
103
|
+
if (esvaziou) return;
|
|
104
|
+
cancelaTimerVazia();
|
|
105
|
+
timerVazia = agendar.setTimeout(() => {
|
|
106
|
+
if (esvaziou) return;
|
|
107
|
+
esvaziou = true;
|
|
108
|
+
log('sala_vazia', { ms: esperaVaziaMs });
|
|
109
|
+
aoEsvaziar?.();
|
|
110
|
+
}, esperaVaziaMs);
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
// So pessoas contam: outro agente (identidade A_*) nao segura a sala aberta (dois agentes sozinhos nao ficam para
|
|
114
|
+
// sempre). Quem acabou de sair e descontado, seja qual for a ordem do evento e do mapa no LiveKit.
|
|
115
|
+
function remotosCount(saindo) {
|
|
116
|
+
const rp = room.remoteParticipants;
|
|
117
|
+
if (!rp || typeof rp.values !== 'function') return 0;
|
|
118
|
+
let n = 0;
|
|
119
|
+
for (const p of rp.values()) {
|
|
120
|
+
const id = String(p?.identity || '');
|
|
121
|
+
if (!id || ehAgente(id)) continue;
|
|
122
|
+
if (saindo && id === saindo) continue;
|
|
123
|
+
n += 1;
|
|
124
|
+
}
|
|
125
|
+
return n;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function verificaVazia(saindo) {
|
|
129
|
+
if (remotosCount(saindo) === 0) {
|
|
130
|
+
armaTimerVazia();
|
|
131
|
+
} else {
|
|
132
|
+
cancelaTimerVazia();
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
async function processa(segmento) {
|
|
137
|
+
try {
|
|
138
|
+
log('trecho', { falante: segmento.falante, ms: Math.round(segmento.fimMs - segmento.inicioMs) });
|
|
139
|
+
const r = await chamarFlow('rea_ouvir', [
|
|
140
|
+
tokenBash,
|
|
141
|
+
sala,
|
|
142
|
+
agente,
|
|
143
|
+
segmento.falante,
|
|
144
|
+
new Cru(wavBase64(segmento.pcm, 16000)),
|
|
145
|
+
]);
|
|
146
|
+
if (r?.ok !== true) {
|
|
147
|
+
log('rea_ouvir', r);
|
|
148
|
+
return;
|
|
149
|
+
}
|
|
150
|
+
log('na_fila', { id: r.id });
|
|
151
|
+
const t = await esperaTexto(chamarFlow, tokenBash, r.id, esperaOpts);
|
|
152
|
+
if (!(t.ok === true && t.texto)) log('rea_estado', { codigo: t.codigo, ok: t.ok });
|
|
153
|
+
if (t.ok === true && t.texto) {
|
|
154
|
+
const fala = {
|
|
155
|
+
falante: segmento.falante,
|
|
156
|
+
texto: t.texto,
|
|
157
|
+
inicioMs: segmento.inicioMs,
|
|
158
|
+
fimMs: segmento.fimMs,
|
|
159
|
+
};
|
|
160
|
+
falas.push(fala);
|
|
161
|
+
aoFalar?.(fala);
|
|
162
|
+
if (foiChamado(t.texto, [apelido])) {
|
|
163
|
+
aoSerChamado?.(fala);
|
|
164
|
+
}
|
|
165
|
+
// Sem await: pensar/falar nao segura a fila de transcricao das outras falas.
|
|
166
|
+
if (falaAg) falaAg.ouviu(fala).catch((e) => log('fala', e));
|
|
167
|
+
}
|
|
168
|
+
} catch (e) {
|
|
169
|
+
log('processa', e);
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
async function enfileira(segmento) {
|
|
174
|
+
fila.push(segmento);
|
|
175
|
+
if (processando) return;
|
|
176
|
+
processando = true;
|
|
177
|
+
while (fila.length > 0) {
|
|
178
|
+
const seg = fila.shift();
|
|
179
|
+
await processa(seg);
|
|
180
|
+
}
|
|
181
|
+
processando = false;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
room.on(lkMod.RoomEvent.TrackSubscribed, (track, publication, participant) => {
|
|
185
|
+
log('trilha', { identidade: participant?.identity, tipo: track?.kind });
|
|
186
|
+
if (track.kind !== lkMod.TrackKind.KIND_AUDIO) return;
|
|
187
|
+
if (participant.identity === room.localParticipant?.identity) return;
|
|
188
|
+
|
|
189
|
+
const stream = new lkMod.AudioStream(track, 16000, 1);
|
|
190
|
+
(async () => {
|
|
191
|
+
try {
|
|
192
|
+
let n = 0;
|
|
193
|
+
let vozSeguida = 0;
|
|
194
|
+
const pessoa = !ehAgente(participant.identity);
|
|
195
|
+
for await (const quadro of stream) {
|
|
196
|
+
n += 1;
|
|
197
|
+
// INTERRUPCAO: uma PESSOA falando (~60 ms seguidos acima do limiar) enquanto a voz do agente toca.
|
|
198
|
+
// A SOS (spec 20261203 §5): o mesmo sinal marca a ultima voz humana; o agente so responde depois de
|
|
199
|
+
// ~1,5 s sem ela.
|
|
200
|
+
if (falaAg && pessoa) {
|
|
201
|
+
const comVoz = energiaDb(quadro.data) >= limiarInterrupcaoDb;
|
|
202
|
+
vozSeguida = comVoz ? vozSeguida + 1 : 0;
|
|
203
|
+
if (vozSeguida >= quadrosParaInterromper) {
|
|
204
|
+
falaAg.vozHumana();
|
|
205
|
+
if (falaAg.tocando) {
|
|
206
|
+
falaAg.alguemFalando();
|
|
207
|
+
vozSeguida = 0;
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
if (n === 1 || n % 6000 === 0) log('quadros', { identidade: participant.identity, n, amostras: quadro.data?.length, taxa: quadro.sampleRate, db: Math.round(energiaDb(quadro.data)) });
|
|
212
|
+
// Agente nao e transcrito (spec §5: entre agentes so o topico, sem STT de voz sintetica).
|
|
213
|
+
if (!pessoa) continue;
|
|
214
|
+
const segmentos = seg.empurra(falanteSeguro(participant.identity), quadro.data);
|
|
215
|
+
// Sem await: a fila ja e serial; esperar aqui pararia o audio desta trilha durante o STT (5-10 s).
|
|
216
|
+
for (const s of segmentos) {
|
|
217
|
+
enfileira(s);
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
} catch (e) {
|
|
221
|
+
log('stream', e);
|
|
222
|
+
}
|
|
223
|
+
})();
|
|
224
|
+
});
|
|
225
|
+
|
|
226
|
+
if (lkMod.RoomEvent?.DataReceived) {
|
|
227
|
+
room.on(lkMod.RoomEvent.DataReceived, (payload, participant, _kind, topic) => {
|
|
228
|
+
if (!falaAg || topic !== TOPICO_DA_SALA) return;
|
|
229
|
+
falaAg.recebeuDado(decodifica(payload), participant?.identity).catch((e) => log('dado', e));
|
|
230
|
+
});
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
room.on(lkMod.RoomEvent.Disconnected, () => {
|
|
234
|
+
log('disconnected', null);
|
|
235
|
+
});
|
|
236
|
+
|
|
237
|
+
// Registra ParticipantConnected / ParticipantDisconnected se o RoomEvent do fake tiver essas chaves.
|
|
238
|
+
if (lkMod.RoomEvent?.ParticipantConnected && lkMod.RoomEvent?.ParticipantDisconnected) {
|
|
239
|
+
room.on(lkMod.RoomEvent.ParticipantConnected, () => {
|
|
240
|
+
verificaVazia();
|
|
241
|
+
});
|
|
242
|
+
room.on(lkMod.RoomEvent.ParticipantDisconnected, (p) => {
|
|
243
|
+
verificaVazia(String(p?.identity || ''));
|
|
244
|
+
});
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
await room.connect(urlLiveKit, tokenLiveKit, { autoSubscribe: true });
|
|
248
|
+
|
|
249
|
+
// Ao conectar, verifica se ja esta vazia (0 remotos).
|
|
250
|
+
verificaVazia();
|
|
251
|
+
|
|
252
|
+
// --- F2: a fala do agente (texto no topico + voz como trilha) ---
|
|
253
|
+
let fonteVoz = null;
|
|
254
|
+
async function fonteDaVoz(taxa, canais) {
|
|
255
|
+
if (fonteVoz && fonteVoz.taxa === taxa && fonteVoz.canais === canais) return fonteVoz.source;
|
|
256
|
+
const source = new lkMod.AudioSource(taxa, canais);
|
|
257
|
+
const track = lkMod.LocalAudioTrack.createAudioTrack('voz_do_agente', source);
|
|
258
|
+
const opts = new lkMod.TrackPublishOptions();
|
|
259
|
+
opts.source = lkMod.TrackSource.SOURCE_MICROPHONE;
|
|
260
|
+
await room.localParticipant.publishTrack(track, opts);
|
|
261
|
+
fonteVoz = { source, taxa, canais };
|
|
262
|
+
return source;
|
|
263
|
+
}
|
|
264
|
+
function toca(b64) {
|
|
265
|
+
const w = lerWav(b64);
|
|
266
|
+
if (!w) {
|
|
267
|
+
log('voz', { codigo: 'wav_invalido' });
|
|
268
|
+
return { parar() {}, fim: Promise.resolve(false) };
|
|
269
|
+
}
|
|
270
|
+
let parado = false;
|
|
271
|
+
const parar = () => {
|
|
272
|
+
parado = true;
|
|
273
|
+
try {
|
|
274
|
+
fonteVoz?.source?.clearQueue?.();
|
|
275
|
+
} catch {
|
|
276
|
+
/* a fila ja estava vazia */
|
|
277
|
+
}
|
|
278
|
+
};
|
|
279
|
+
const fim = (async () => {
|
|
280
|
+
const source = await fonteDaVoz(w.taxa, w.canais);
|
|
281
|
+
const porQuadro = Math.floor(w.taxa / 100) * w.canais; // 10 ms
|
|
282
|
+
for (let i = 0; i < w.amostras.length && !parado; i += porQuadro) {
|
|
283
|
+
const pedaco = w.amostras.slice(i, Math.min(i + porQuadro, w.amostras.length));
|
|
284
|
+
await source.captureFrame(new lkMod.AudioFrame(pedaco, w.taxa, w.canais, pedaco.length / w.canais));
|
|
285
|
+
}
|
|
286
|
+
return !parado;
|
|
287
|
+
})();
|
|
288
|
+
return { parar, fim };
|
|
289
|
+
}
|
|
290
|
+
const publica = (msg) => {
|
|
291
|
+
const b = codifica(msg);
|
|
292
|
+
if (!b) return log('dado', { codigo: 'grande_demais', t: msg.t });
|
|
293
|
+
Promise.resolve(room.localParticipant?.publishData?.(b, { reliable: true, topic: TOPICO_DA_SALA })).catch((e) => log('publica', e));
|
|
294
|
+
};
|
|
295
|
+
falaAg = fala && apelido
|
|
296
|
+
? new FalaDoAgente({
|
|
297
|
+
chamar: chamarFlow,
|
|
298
|
+
publica,
|
|
299
|
+
toca: comVoz ? toca : null,
|
|
300
|
+
tokenBash,
|
|
301
|
+
sala,
|
|
302
|
+
agente,
|
|
303
|
+
apelido,
|
|
304
|
+
nome,
|
|
305
|
+
identidade: room.localParticipant?.identity || '',
|
|
306
|
+
idioma,
|
|
307
|
+
comVoz,
|
|
308
|
+
log,
|
|
309
|
+
esperaOpts,
|
|
310
|
+
aoSair: (motivo) => aoPedirSaida?.(motivo),
|
|
311
|
+
// So PESSOAS contam (outro agente A_* nao); 1 = a sos com o agente.
|
|
312
|
+
pessoasNaSala: () => remotosCount(),
|
|
313
|
+
...falaOpts,
|
|
314
|
+
})
|
|
315
|
+
: null;
|
|
316
|
+
|
|
317
|
+
const sair = async () => {
|
|
318
|
+
cancelaTimerVazia();
|
|
319
|
+
// Despede-se (texto no topico) antes de sair; no teto o aviso ja saiu.
|
|
320
|
+
if (falaAg && !falaAg.encerrado) await falaAg.sai('tchau');
|
|
321
|
+
const finais = seg.fecha();
|
|
322
|
+
for (const s of finais) {
|
|
323
|
+
await enfileira(s);
|
|
324
|
+
}
|
|
325
|
+
while (processando || fila.length > 0) {
|
|
326
|
+
await new Promise((r) => setTimeout(r, 10));
|
|
327
|
+
}
|
|
328
|
+
await room.disconnect();
|
|
329
|
+
// A ATA (modo b da spec §3): o servidor gera com a IA do agente, paga pela empresa, e guarda; o cliente
|
|
330
|
+
// so pede e espera. Sem fala nenhuma nao ha ata.
|
|
331
|
+
let ata = null;
|
|
332
|
+
if (falas.length > 0) {
|
|
333
|
+
try {
|
|
334
|
+
const r = await chamarFlow('rea_ata', [tokenBash, sala, agente]);
|
|
335
|
+
if (r?.ok === true) {
|
|
336
|
+
log('ata_pedida', { id: r.id });
|
|
337
|
+
ata = await esperaTexto(chamarFlow, tokenBash, r.id, { tentativas: 24, ...esperaOpts, flow: 'rea_ata_estado' });
|
|
338
|
+
} else {
|
|
339
|
+
log('rea_ata', r);
|
|
340
|
+
}
|
|
341
|
+
} catch (e) {
|
|
342
|
+
log('ata', e);
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
sessao.ata = ata;
|
|
346
|
+
return falas;
|
|
347
|
+
};
|
|
348
|
+
|
|
349
|
+
const sessao = { sair, falas, ata: null, room, fala: falaAg };
|
|
350
|
+
return sessao;
|
|
351
|
+
}
|
package/src/ncall_cli.js
ADDED
|
@@ -0,0 +1,308 @@
|
|
|
1
|
+
import { entrarNaSala } from './ncall.js';
|
|
2
|
+
import { carregar, tokenDe } from './store.js';
|
|
3
|
+
import { callPublic } from './api.js';
|
|
4
|
+
|
|
5
|
+
const RE_AGENTE = /^ag_[a-f0-9]{12}$/;
|
|
6
|
+
const RE_SALA = /^[A-Za-z0-9_~-]{1,80}$/;
|
|
7
|
+
const RE_DAILY = /^[A-Za-z0-9_]{3,80}$/;
|
|
8
|
+
const RE_CONVITE = /^nc_[a-z0-9_]{3,160}$/;
|
|
9
|
+
|
|
10
|
+
export function opcoesDe(argv) {
|
|
11
|
+
const o = {
|
|
12
|
+
ok: true,
|
|
13
|
+
agente: null,
|
|
14
|
+
apelido: 'agente',
|
|
15
|
+
sala: null,
|
|
16
|
+
bash: null,
|
|
17
|
+
minutos: 60,
|
|
18
|
+
lkUrl: null,
|
|
19
|
+
lkToken: null,
|
|
20
|
+
link: null,
|
|
21
|
+
pin: null,
|
|
22
|
+
daily: null,
|
|
23
|
+
// N-Call fora da daily: o id do convite que o rea_ncall_convidar pos na fila (flows/302_4)
|
|
24
|
+
convite: null,
|
|
25
|
+
// F2: o agente fala (texto no topico + voz); --sem-voz so texto; --so-ouvir como a F1.
|
|
26
|
+
fala: true,
|
|
27
|
+
comVoz: true,
|
|
28
|
+
idioma: 'pt',
|
|
29
|
+
_ms: null,
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
let i = 0;
|
|
33
|
+
while (i < argv.length) {
|
|
34
|
+
const a = argv[i];
|
|
35
|
+
if (a === '--agente') {
|
|
36
|
+
o.agente = argv[++i] ?? null;
|
|
37
|
+
} else if (a === '--apelido') {
|
|
38
|
+
o.apelido = argv[++i] ?? 'agente';
|
|
39
|
+
} else if (a === '--sala') {
|
|
40
|
+
o.sala = argv[++i] ?? null;
|
|
41
|
+
} else if (a === '--bash') {
|
|
42
|
+
o.bash = argv[++i] ?? null;
|
|
43
|
+
} else if (a === '--minutos') {
|
|
44
|
+
const n = Number(argv[++i]);
|
|
45
|
+
if (Number.isFinite(n)) {
|
|
46
|
+
o.minutos = Math.max(1, Math.min(240, Math.floor(n)));
|
|
47
|
+
}
|
|
48
|
+
} else if (a === '--lk-url') {
|
|
49
|
+
o.lkUrl = argv[++i] ?? null;
|
|
50
|
+
} else if (a === '--lk-token') {
|
|
51
|
+
o.lkToken = argv[++i] ?? null;
|
|
52
|
+
} else if (a === '--pin') {
|
|
53
|
+
o.pin = argv[++i] ?? null;
|
|
54
|
+
} else if (a === '--sem-voz') {
|
|
55
|
+
o.comVoz = false;
|
|
56
|
+
} else if (a === '--so-ouvir') {
|
|
57
|
+
o.fala = false;
|
|
58
|
+
} else if (a === '--idioma') {
|
|
59
|
+
const l = String(argv[++i] ?? '').toLowerCase();
|
|
60
|
+
o.idioma = ['pt', 'en', 'es'].includes(l) ? l : 'pt';
|
|
61
|
+
} else if (a === '--daily') {
|
|
62
|
+
o.daily = argv[++i] ?? null;
|
|
63
|
+
} else if (a === '--convite') {
|
|
64
|
+
o.convite = argv[++i] ?? null;
|
|
65
|
+
} else if (a === '--_ms') {
|
|
66
|
+
o._ms = Number(argv[++i]);
|
|
67
|
+
} else if (a.startsWith('--')) {
|
|
68
|
+
// opção desconhecida: ignora
|
|
69
|
+
} else {
|
|
70
|
+
// primeiro posicional que não é opção = link
|
|
71
|
+
if (o.link === null) {
|
|
72
|
+
o.link = a;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
i++;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// validações
|
|
79
|
+
if (!o.agente || !RE_AGENTE.test(o.agente)) {
|
|
80
|
+
return { ok: false, erro: 'agente invalido (ag_ + 12 hex)' };
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
// --daily: sala e lk-url/lk-token/link deixam de ser obrigatórios
|
|
84
|
+
if (o.convite !== null) {
|
|
85
|
+
if (!RE_CONVITE.test(o.convite)) {
|
|
86
|
+
return { ok: false, erro: 'convite invalido' };
|
|
87
|
+
}
|
|
88
|
+
return o;
|
|
89
|
+
}
|
|
90
|
+
if (o.daily !== null) {
|
|
91
|
+
if (!RE_DAILY.test(o.daily)) {
|
|
92
|
+
return { ok: false, erro: 'daily invalida' };
|
|
93
|
+
}
|
|
94
|
+
return o;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
// sem --daily: validações originais
|
|
98
|
+
if (!o.sala || !RE_SALA.test(o.sala)) {
|
|
99
|
+
return { ok: false, erro: 'sala invalida' };
|
|
100
|
+
}
|
|
101
|
+
if (!o.lkUrl && !o.lkToken && !o.link) {
|
|
102
|
+
return { ok: false, erro: 'informe --lk-url e --lk-token (ou o link da reuniao)' };
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
return o;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
export async function principal(argv, {
|
|
109
|
+
url,
|
|
110
|
+
instance,
|
|
111
|
+
entrar = entrarNaSala,
|
|
112
|
+
store = { carregar, tokenDe },
|
|
113
|
+
env = process.env,
|
|
114
|
+
saida = console,
|
|
115
|
+
sinais = process,
|
|
116
|
+
chamar = (flow, args) => callPublic(url, instance, flow, args),
|
|
117
|
+
} = {}) {
|
|
118
|
+
const o = opcoesDe(argv);
|
|
119
|
+
if (!o.ok) {
|
|
120
|
+
saida.error(o.erro);
|
|
121
|
+
return 2;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
// entrada por link sem lk-url/lk-token
|
|
125
|
+
if (o.link && !o.lkUrl && !o.lkToken) {
|
|
126
|
+
saida.error('entrada por link + PIN chega com a s384 (convidado externo); use --lk-url/--lk-token na dev');
|
|
127
|
+
return 3;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
// resolver bash
|
|
131
|
+
const est = store.carregar();
|
|
132
|
+
const bashes = (est.bashes || []).filter(b => b.url === url && b.instance === instance);
|
|
133
|
+
|
|
134
|
+
let bash;
|
|
135
|
+
if (o.bash) {
|
|
136
|
+
bash = bashes.find(b => b.bash_id === o.bash);
|
|
137
|
+
if (!bash) {
|
|
138
|
+
saida.error('escolha a bash com --bash <bash_id>');
|
|
139
|
+
return 2;
|
|
140
|
+
}
|
|
141
|
+
} else {
|
|
142
|
+
if (bashes.length === 1) {
|
|
143
|
+
bash = bashes[0];
|
|
144
|
+
} else {
|
|
145
|
+
saida.error('escolha a bash com --bash <bash_id>');
|
|
146
|
+
return 2;
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
const tokenBash = store.tokenDe(bash);
|
|
151
|
+
|
|
152
|
+
// --- fluxo com --daily ou --convite (o servidor devolve o token so depois de conferir a convocacao) ---
|
|
153
|
+
if (o.daily !== null || o.convite !== null) {
|
|
154
|
+
const r = o.convite !== null
|
|
155
|
+
? await chamar('rea_ncall_entrada', [tokenBash, o.convite, o.agente])
|
|
156
|
+
: await chamar('rea_daily_entrada', [tokenBash, o.daily, o.agente]);
|
|
157
|
+
|
|
158
|
+
if (!r || r.ok !== true) {
|
|
159
|
+
const codigo = r?.codigo || 'desconhecido';
|
|
160
|
+
saida.error(`nao entrou na ${o.convite !== null ? 'chamada' : 'daily'}: ${codigo}`);
|
|
161
|
+
return 4;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
// extrai lk: aceita {url, token} ou {data:{url, token}}
|
|
165
|
+
let lk = r.lk;
|
|
166
|
+
if (lk && lk.data && typeof lk.data === 'object') {
|
|
167
|
+
lk = lk.data;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
const urlLiveKit = lk?.url || null;
|
|
171
|
+
const tokenLiveKit = lk?.token || null;
|
|
172
|
+
const sala = r.sala || null;
|
|
173
|
+
|
|
174
|
+
if (!urlLiveKit || !tokenLiveKit) {
|
|
175
|
+
saida.error('nao entrou na daily: token_invalido');
|
|
176
|
+
return 4;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
// callback para sala vazia
|
|
180
|
+
let esvaziou = false;
|
|
181
|
+
let resolveEspera = null;
|
|
182
|
+
|
|
183
|
+
const aoEsvaziar = () => {
|
|
184
|
+
esvaziou = true;
|
|
185
|
+
if (resolveEspera) resolveEspera();
|
|
186
|
+
};
|
|
187
|
+
|
|
188
|
+
let sessao;
|
|
189
|
+
try {
|
|
190
|
+
sessao = await entrar({
|
|
191
|
+
urlLiveKit,
|
|
192
|
+
tokenLiveKit,
|
|
193
|
+
sala,
|
|
194
|
+
agente: o.agente,
|
|
195
|
+
apelido: o.apelido,
|
|
196
|
+
tokenBash,
|
|
197
|
+
baseUrl: url,
|
|
198
|
+
instancia: instance,
|
|
199
|
+
aoFalar: (f) => saida.log(`[${f.falante}] ${f.texto}`),
|
|
200
|
+
aoSerChamado: (f) => saida.log(`(chamado por ${f.falante})`),
|
|
201
|
+
log: (o_, e) => saida.log(`.. ${o_} ${e?.codigo || e?.message || JSON.stringify(e)?.slice(0, 160) || ''}`),
|
|
202
|
+
aoEsvaziar,
|
|
203
|
+
fala: o.fala,
|
|
204
|
+
comVoz: o.comVoz,
|
|
205
|
+
idioma: o.idioma,
|
|
206
|
+
// Teto da reuniao: o agente avisou no topico; sai como se a sala esvaziasse (gera a ata).
|
|
207
|
+
aoPedirSaida: aoEsvaziar,
|
|
208
|
+
});
|
|
209
|
+
} catch (e) {
|
|
210
|
+
saida.error('nao entrou na sala: ' + (e.message || e));
|
|
211
|
+
return 1;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
// tempo na sala
|
|
215
|
+
const ms = o._ms != null ? o._ms : o.minutos * 60 * 1000;
|
|
216
|
+
|
|
217
|
+
// Fica ate o tempo acabar, SIGINT/SIGTERM, ou a sala esvaziar (o que vier primeiro); limpa timer e ouvintes.
|
|
218
|
+
let timer = null;
|
|
219
|
+
let onSig = null;
|
|
220
|
+
await new Promise((resolve) => {
|
|
221
|
+
resolveEspera = resolve;
|
|
222
|
+
timer = setTimeout(resolve, ms);
|
|
223
|
+
onSig = () => resolve();
|
|
224
|
+
sinais.once('SIGINT', onSig);
|
|
225
|
+
sinais.once('SIGTERM', onSig);
|
|
226
|
+
if (esvaziou) resolve(); // a sala ja esvaziou durante a entrada
|
|
227
|
+
});
|
|
228
|
+
clearTimeout(timer);
|
|
229
|
+
sinais.removeListener('SIGINT', onSig);
|
|
230
|
+
sinais.removeListener('SIGTERM', onSig);
|
|
231
|
+
|
|
232
|
+
const falas = await sessao.sair();
|
|
233
|
+
if (sessao.ata?.ok === true) saida.log('ATA ' + JSON.stringify(sessao.ata.json ?? sessao.ata));
|
|
234
|
+
else if (sessao.ata) saida.log('.. ata ' + (sessao.ata.codigo || 'sem ata'));
|
|
235
|
+
saida.log(JSON.stringify({ ok: true, sala, agente: o.agente, falas: falas.length }));
|
|
236
|
+
return 0;
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
// --- fluxo sem --daily (comportamento original) ---
|
|
240
|
+
// resolver lkToken
|
|
241
|
+
let tokenLiveKit = o.lkToken;
|
|
242
|
+
if (tokenLiveKit === '-') {
|
|
243
|
+
tokenLiveKit = env.NEURONIUN_LK_TOKEN || '';
|
|
244
|
+
if (!tokenLiveKit) {
|
|
245
|
+
saida.error('NEURONIUN_LK_TOKEN vazio');
|
|
246
|
+
return 2;
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
// callback para sala vazia
|
|
251
|
+
let esvaziou = false;
|
|
252
|
+
let resolveEspera = null;
|
|
253
|
+
|
|
254
|
+
const aoEsvaziar = () => {
|
|
255
|
+
esvaziou = true;
|
|
256
|
+
if (resolveEspera) resolveEspera();
|
|
257
|
+
};
|
|
258
|
+
|
|
259
|
+
// entrar na sala
|
|
260
|
+
let sessao;
|
|
261
|
+
try {
|
|
262
|
+
sessao = await entrar({
|
|
263
|
+
urlLiveKit: o.lkUrl,
|
|
264
|
+
tokenLiveKit,
|
|
265
|
+
sala: o.sala,
|
|
266
|
+
agente: o.agente,
|
|
267
|
+
apelido: o.apelido,
|
|
268
|
+
tokenBash,
|
|
269
|
+
baseUrl: url,
|
|
270
|
+
instancia: instance,
|
|
271
|
+
aoFalar: (f) => saida.log(`[${f.falante}] ${f.texto}`),
|
|
272
|
+
aoSerChamado: (f) => saida.log(`(chamado por ${f.falante})`),
|
|
273
|
+
log: (o_, e) => saida.log(`.. ${o_} ${e?.codigo || e?.message || JSON.stringify(e)?.slice(0, 160) || ''}`),
|
|
274
|
+
aoEsvaziar,
|
|
275
|
+
fala: o.fala,
|
|
276
|
+
comVoz: o.comVoz,
|
|
277
|
+
idioma: o.idioma,
|
|
278
|
+
aoPedirSaida: aoEsvaziar,
|
|
279
|
+
});
|
|
280
|
+
} catch (e) {
|
|
281
|
+
saida.error('nao entrou na sala: ' + (e.message || e));
|
|
282
|
+
return 1;
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
// tempo na sala
|
|
286
|
+
const ms = o._ms != null ? o._ms : o.minutos * 60 * 1000;
|
|
287
|
+
|
|
288
|
+
// Fica ate o tempo acabar ou chegar SIGINT/SIGTERM (o que vier primeiro); limpa timer e ouvintes.
|
|
289
|
+
let timer = null;
|
|
290
|
+
let onSig = null;
|
|
291
|
+
await new Promise((resolve) => {
|
|
292
|
+
resolveEspera = resolve;
|
|
293
|
+
timer = setTimeout(resolve, ms);
|
|
294
|
+
onSig = () => resolve();
|
|
295
|
+
sinais.once('SIGINT', onSig);
|
|
296
|
+
sinais.once('SIGTERM', onSig);
|
|
297
|
+
if (esvaziou) resolve(); // a sala ja esvaziou durante a entrada
|
|
298
|
+
});
|
|
299
|
+
clearTimeout(timer);
|
|
300
|
+
sinais.removeListener('SIGINT', onSig);
|
|
301
|
+
sinais.removeListener('SIGTERM', onSig);
|
|
302
|
+
|
|
303
|
+
const falas = await sessao.sair();
|
|
304
|
+
if (sessao.ata?.ok === true) saida.log('ATA ' + JSON.stringify(sessao.ata.json ?? sessao.ata));
|
|
305
|
+
else if (sessao.ata) saida.log('.. ata ' + (sessao.ata.codigo || 'sem ata'));
|
|
306
|
+
saida.log(JSON.stringify({ ok: true, sala: o.sala, agente: o.agente, falas: falas.length }));
|
|
307
|
+
return 0;
|
|
308
|
+
}
|