neuroniun 0.2.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 +219 -75
- package/bin/neuroniun.js +74 -0
- package/package.json +12 -18
- package/src/api.js +76 -50
- package/src/console.js +181 -0
- 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 +58 -0
- package/src/ticket.js +79 -0
- package/src/uso.js +158 -0
- package/src/worker.js +588 -0
- package/LICENSE +0 -21
- package/bin/neuronio.js +0 -112
- package/src/agente.js +0 -96
- package/src/chat.js +0 -68
- package/src/config.js +0 -33
package/src/api.js
CHANGED
|
@@ -1,58 +1,84 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
1
|
+
// Cliente da PORTA PUBLICA do Neuroniun. O agente NUNCA faz login no NeuroniunDB:
|
|
2
|
+
// fala so por POST /public (sem Authorization), na forma V2 `run db.flow(args)`.
|
|
3
|
+
// O que autoriza e o TOKEN da bash, argumento da flow — nao uma sessao do no.
|
|
4
|
+
import https from 'node:https';
|
|
5
|
+
import http from 'node:http';
|
|
6
|
+
import { URL } from 'node:url';
|
|
7
|
+
|
|
8
8
|
const B64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_';
|
|
9
9
|
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
let
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
if (
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
10
|
+
// b64url SEM padding, com prefixo "b64:" — o mesmo alfabeto que os flows decodificam.
|
|
11
|
+
export function b64(str) {
|
|
12
|
+
const s = Buffer.from(String(str == null ? '' : str), 'utf-8');
|
|
13
|
+
let o = '';
|
|
14
|
+
for (let i = 0; i < s.length; i += 3) {
|
|
15
|
+
const x = s[i], y = s[i + 1], z = s[i + 2];
|
|
16
|
+
o += B64[x >> 2];
|
|
17
|
+
o += B64[((x & 3) << 4) | ((y === undefined ? 0 : y) >> 4)];
|
|
18
|
+
if (y !== undefined) o += B64[((y & 15) << 2) | ((z === undefined ? 0 : z) >> 6)];
|
|
19
|
+
if (z !== undefined) o += B64[z & 63];
|
|
20
|
+
}
|
|
21
|
+
return 'b64:' + o;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
// Valor que JA e base64 padrao (A-Z a-z 0-9 + / =) e o flow usa como esta (ex.: o audio do N-Call, que
|
|
25
|
+
// o comando nativo `audio =>` le em base64 puro). Vai cru entre aspas: re-embrulhar em "b64:" faria o
|
|
26
|
+
// flow receber o base64 do base64. Nao contem aspas, $ nem {{, entao nao vira referencia no SNL.
|
|
27
|
+
export class Cru {
|
|
28
|
+
constructor(s) {
|
|
29
|
+
const t = String(s == null ? '' : s);
|
|
30
|
+
if (!/^[A-Za-z0-9+/=]*$/.test(t)) throw new Error('Cru: so base64 padrao');
|
|
31
|
+
this.s = t;
|
|
23
32
|
}
|
|
24
|
-
return `b64:${saida}`;
|
|
25
33
|
}
|
|
26
34
|
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
35
|
+
// Só letras/dígitos/_/. entram sem aspas escapadas; o token e os ids são assim.
|
|
36
|
+
function arg(v) {
|
|
37
|
+
if (v instanceof Cru) return `"${v.s}"`; // base64 padrao validado, cru
|
|
38
|
+
const s = String(v == null ? '' : v);
|
|
39
|
+
if (s.startsWith('b64:')) return s; // b64 viaja cru
|
|
40
|
+
if (/^[A-Za-z0-9_.]+$/.test(s)) return `"${s}"`; // id/token seguro
|
|
41
|
+
return b64(s); // qualquer outra coisa vira b64
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
// Chama uma OPEN flow do Neuroniun por /public. Devolve o `result` já parseado.
|
|
45
|
+
export async function callPublic(baseUrl, instance, flow, args = [], timeoutMs = 30000) {
|
|
46
|
+
const command = `run neuroniun.${flow}(${args.map(arg).join(', ')})`;
|
|
47
|
+
const body = Buffer.from(JSON.stringify({ command, instance: instance || 'prd' }), 'utf-8');
|
|
48
|
+
const u = new URL(baseUrl.replace(/\/+$/, '') + '/public');
|
|
49
|
+
const lib = u.protocol === 'http:' ? http : https;
|
|
50
|
+
const opts = {
|
|
51
|
+
method: 'POST',
|
|
52
|
+
hostname: u.hostname,
|
|
53
|
+
port: u.port || (u.protocol === 'http:' ? 80 : 443),
|
|
54
|
+
path: u.pathname,
|
|
55
|
+
headers: {
|
|
56
|
+
'Content-Type': 'application/json',
|
|
57
|
+
'Content-Length': body.length,
|
|
58
|
+
'User-Agent': 'neuroniun-agent/0.5',
|
|
59
|
+
},
|
|
60
|
+
timeout: timeoutMs,
|
|
61
|
+
};
|
|
62
|
+
const raw = await new Promise((resolve, reject) => {
|
|
63
|
+
const req = lib.request(opts, (res) => {
|
|
64
|
+
let data = '';
|
|
65
|
+
res.setEncoding('utf-8');
|
|
66
|
+
res.on('data', (c) => { data += c; });
|
|
67
|
+
res.on('end', () => resolve(data));
|
|
39
68
|
});
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
// Nem toda resposta e JSON; o texto cru serve.
|
|
52
|
-
}
|
|
53
|
-
}
|
|
54
|
-
return dado;
|
|
55
|
-
} finally {
|
|
56
|
-
clearTimeout(relogio);
|
|
69
|
+
req.on('error', reject);
|
|
70
|
+
req.on('timeout', () => { req.destroy(new Error('timeout')); });
|
|
71
|
+
req.write(body);
|
|
72
|
+
req.end();
|
|
73
|
+
});
|
|
74
|
+
let d;
|
|
75
|
+
try { d = JSON.parse(raw.replace(/[\u0001\u0002]/g, '')); }
|
|
76
|
+
catch { throw new Error('resposta nao-JSON de /public: ' + raw.slice(0, 200)); }
|
|
77
|
+
if (d && d.success === false) {
|
|
78
|
+
const msg = (d.error) || ((d.console || [])[0] || {}).message || 'erro no flow';
|
|
79
|
+
throw new Error(String(msg));
|
|
57
80
|
}
|
|
81
|
+
let r = d.result;
|
|
82
|
+
if (typeof r === 'string') { try { r = JSON.parse(r); } catch { /* escalar */ } }
|
|
83
|
+
return r;
|
|
58
84
|
}
|
package/src/console.js
ADDED
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
// O CONSOLE do Neuroniun: um menuzinho e a tela ao vivo do que cada bash executa.
|
|
2
|
+
// Suporta varias bashes ao mesmo tempo (estilo pm2). Sem dependencias externas —
|
|
3
|
+
// readline + ANSI. `q`/Esc volta da tela ao vivo para o menu.
|
|
4
|
+
import readline from 'node:readline';
|
|
5
|
+
import { callPublic } from './api.js';
|
|
6
|
+
import { Worker, realRun } from './worker.js';
|
|
7
|
+
import { carregar, salvar, upsert, remover, bashDeToken, tokenDe, INSTANCIA_PADRAO } from './store.js';
|
|
8
|
+
import { servicoLigado, linhaServico, planoServico, aplicarPlano } from './servico.js';
|
|
9
|
+
|
|
10
|
+
const C = {
|
|
11
|
+
dim: (s) => `\x1b[2m${s}\x1b[0m`,
|
|
12
|
+
b: (s) => `\x1b[1m${s}\x1b[0m`,
|
|
13
|
+
verde: (s) => `\x1b[32m${s}\x1b[0m`,
|
|
14
|
+
amarelo: (s) => `\x1b[33m${s}\x1b[0m`,
|
|
15
|
+
verm: (s) => `\x1b[31m${s}\x1b[0m`,
|
|
16
|
+
ciano: (s) => `\x1b[36m${s}\x1b[0m`,
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
function pergunta(rl, texto) { return new Promise((res) => rl.question(texto, (a) => res(a.trim()))); }
|
|
20
|
+
|
|
21
|
+
function corEstado(w) {
|
|
22
|
+
if (w.estado === 'ligada') return C.verde('● ligada');
|
|
23
|
+
if (w.estado === 'parado') return C.dim('○ parada');
|
|
24
|
+
return C.amarelo('● ' + w.estado);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export async function rodarConsole({ url, instance } = {}) {
|
|
28
|
+
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
|
|
29
|
+
let estado = carregar();
|
|
30
|
+
const workers = new Map(); // bash_id -> Worker
|
|
31
|
+
const buffers = new Map(); // bash_id -> últimas linhas de log
|
|
32
|
+
|
|
33
|
+
function conectar(bash) {
|
|
34
|
+
if (workers.has(bash.bash_id)) return workers.get(bash.bash_id);
|
|
35
|
+
const w = new Worker({ ...bash, url: bash.url || url, instance: bash.instance || instance || INSTANCIA_PADRAO }, { run: realRun });
|
|
36
|
+
buffers.set(bash.bash_id, []);
|
|
37
|
+
w.on('log', (ev) => {
|
|
38
|
+
const buf = buffers.get(bash.bash_id);
|
|
39
|
+
buf.push(ev);
|
|
40
|
+
if (buf.length > 500) buf.shift();
|
|
41
|
+
});
|
|
42
|
+
workers.set(bash.bash_id, w);
|
|
43
|
+
return w;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
// liga todas as bashes ja cadastradas
|
|
47
|
+
for (const b of estado.bashes) {
|
|
48
|
+
const w = conectar(b);
|
|
49
|
+
w.iniciar().catch((e) => { /* mostra no menu */ w.erro = String(e.message || e); });
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
async function menu() {
|
|
53
|
+
for (;;) {
|
|
54
|
+
console.log('\n' + C.b('Neuroniun Bash') + C.dim(` — ${workers.size} bash(es) nesta maquina`));
|
|
55
|
+
let i = 0;
|
|
56
|
+
const lista = [...workers.values()];
|
|
57
|
+
for (const w of lista) {
|
|
58
|
+
i++;
|
|
59
|
+
const u = w.ultimo && w.ultimo.comando ? C.dim(` ult: ${w.ultimo.comando.slice(0, 40)} (exit ${w.ultimo.exit})`) : '';
|
|
60
|
+
console.log(` ${C.ciano('[' + i + ']')} ${w.bash.nome} ${corEstado(w)}${w.erro ? ' ' + C.verm(w.erro) : ''}${u}`);
|
|
61
|
+
}
|
|
62
|
+
// D19: iniciar com o sistema (recomendado; desligavel)
|
|
63
|
+
let ligado = false;
|
|
64
|
+
try { ligado = servicoLigado(); } catch { /* sistema sem servico conhecido */ }
|
|
65
|
+
const ls = linhaServico(ligado, workers.size > 0);
|
|
66
|
+
console.log(' ' + (ligado ? C.verde(ls) : C.amarelo(ls)));
|
|
67
|
+
console.log(C.dim(' ————'));
|
|
68
|
+
console.log(` ${C.ciano('a')} adicionar uma bash (colar a chave)`);
|
|
69
|
+
console.log(` ${C.ciano('s')} ${ligado ? 'desligar' : 'ligar'} o iniciar com o sistema`);
|
|
70
|
+
console.log(` ${C.ciano('g')} gerar uma bash nova a partir desta maquina`);
|
|
71
|
+
console.log(` ${C.ciano('número')} abrir a tela ao vivo de uma bash`);
|
|
72
|
+
console.log(` ${C.ciano('r')} remover uma bash desta maquina`);
|
|
73
|
+
console.log(` ${C.ciano('q')} sair`);
|
|
74
|
+
const a = (await pergunta(rl, '> ')).toLowerCase();
|
|
75
|
+
if (a === 'q') break;
|
|
76
|
+
else if (a === 'a') await adicionar();
|
|
77
|
+
else if (a === 'g') await gerar();
|
|
78
|
+
else if (a === 'r') await removerBash(lista);
|
|
79
|
+
else if (a === 's') await alternarServico();
|
|
80
|
+
else if (/^\d+$/.test(a)) { const w = lista[Number(a) - 1]; if (w) await telaAoVivo(w); }
|
|
81
|
+
}
|
|
82
|
+
for (const w of workers.values()) await w.parar('saindo do console').catch(() => {});
|
|
83
|
+
rl.close();
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
async function adicionar() {
|
|
87
|
+
const token = await pergunta(rl, 'cole a chave (token) da bash: ');
|
|
88
|
+
const bash = bashDeToken(token, url, instance);
|
|
89
|
+
if (!bash) { console.log(C.verm('chave invalida.')); return; }
|
|
90
|
+
const nome = await pergunta(rl, `nome nesta maquina [${bash.bash_id}]: `);
|
|
91
|
+
if (nome) bash.nome = nome;
|
|
92
|
+
estado = upsert(estado, bash); salvar(estado);
|
|
93
|
+
const w = conectar(bash);
|
|
94
|
+
try { await w.iniciar(); console.log(C.verde('ligada.')); }
|
|
95
|
+
catch (e) { w.erro = String(e.message || e); console.log(C.verm('nao ligou: ' + w.erro)); }
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
async function gerar() {
|
|
99
|
+
const u = url || await pergunta(rl, 'url do Neuroniun (ex: https://api-neuroniun.neuron-db.com): ');
|
|
100
|
+
const inst = instance || (await pergunta(rl, `instancia [${INSTANCIA_PADRAO}]: `)) || INSTANCIA_PADRAO;
|
|
101
|
+
console.log(C.dim('para gerar, o Neuroniun precisa saber quem e voce.'));
|
|
102
|
+
console.log(C.dim('gere a chave na tela de Configuracoes → Bashes do app e cole aqui com a opcao "a".'));
|
|
103
|
+
// Geração autenticada exige token do usuário; o caminho oficial é o app.
|
|
104
|
+
// Mantido como aviso para não pedir senha no terminal.
|
|
105
|
+
void u; void inst;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
async function alternarServico() {
|
|
109
|
+
let ligado = false;
|
|
110
|
+
try { ligado = servicoLigado(); } catch { /* sem servico */ }
|
|
111
|
+
const ok = (await pergunta(rl, ligado ? 'desligar o iniciar com o sistema? (s/n) ' : 'ligar o iniciar com o sistema? (s/n) ')).toLowerCase();
|
|
112
|
+
if (ok !== 's' && ok !== 'sim' && ok !== 'y') return;
|
|
113
|
+
let r;
|
|
114
|
+
try { r = aplicarPlano(planoServico({ acao: ligado ? 'remover' : 'instalar' })); }
|
|
115
|
+
catch (e) { console.log(C.verm('nao deu: ' + String(e.message || e))); return; }
|
|
116
|
+
if (!r.ok) { console.log(C.verm('nao deu:') + '\n ' + r.feito.join('\n ')); return; }
|
|
117
|
+
if (ligado) console.log(C.dim('desligado: as bashes so rodam com este console (ou neuroniun --headless) aberto.'));
|
|
118
|
+
else console.log(C.verde('ligado.') + C.dim(' o servico ja assume as bashes em segundo plano (elas saem deste console); pode fechar o console.'));
|
|
119
|
+
if (r.nota) console.log(C.dim('nota: ' + r.nota));
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
async function removerBash(lista) {
|
|
123
|
+
const a = await pergunta(rl, 'numero da bash a remover desta maquina: ');
|
|
124
|
+
const w = lista[Number(a) - 1];
|
|
125
|
+
if (!w) return;
|
|
126
|
+
await w.parar('removida desta maquina').catch(() => {});
|
|
127
|
+
workers.delete(w.bash.bash_id);
|
|
128
|
+
estado = remover(estado, w.bash.bash_id); salvar(estado);
|
|
129
|
+
console.log(C.dim('removida (a bash continua existindo no Neuroniun; so saiu desta maquina).'));
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
function telaAoVivo(w) {
|
|
133
|
+
return new Promise((resolve) => {
|
|
134
|
+
console.clear();
|
|
135
|
+
console.log(C.b(`── ${w.bash.nome} ──`) + C.dim(' (q ou Esc volta ao menu)\n'));
|
|
136
|
+
const buf = buffers.get(w.bash.bash_id) || [];
|
|
137
|
+
for (const ev of buf.slice(-30)) console.log(linha(ev));
|
|
138
|
+
const onLog = (ev) => console.log(linha(ev));
|
|
139
|
+
w.on('log', onLog);
|
|
140
|
+
const rl2 = readline.createInterface({ input: process.stdin });
|
|
141
|
+
readline.emitKeypressEvents(process.stdin);
|
|
142
|
+
if (process.stdin.isTTY) process.stdin.setRawMode(true);
|
|
143
|
+
const onKey = (_s, key) => {
|
|
144
|
+
if (key && (key.name === 'q' || key.name === 'escape' || (key.ctrl && key.name === 'c'))) {
|
|
145
|
+
process.stdin.removeListener('keypress', onKey);
|
|
146
|
+
if (process.stdin.isTTY) process.stdin.setRawMode(false);
|
|
147
|
+
w.removeListener('log', onLog);
|
|
148
|
+
rl2.close();
|
|
149
|
+
console.clear();
|
|
150
|
+
resolve();
|
|
151
|
+
}
|
|
152
|
+
};
|
|
153
|
+
process.stdin.on('keypress', onKey);
|
|
154
|
+
});
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
function linha(ev) {
|
|
158
|
+
const t = new Date().toLocaleTimeString();
|
|
159
|
+
if (ev.tipo === 'comando') return C.ciano(`${t} $ ${ev.comando}`);
|
|
160
|
+
if (ev.tipo === 'saida') return `${C.dim(t)} ${ev.exit === 0 ? C.verde('exit 0') : C.verm('exit ' + ev.exit)} ${C.dim('(' + ev.duracao_ms + 'ms)')}\n${ev.saida.replace(/\n$/, '')}`;
|
|
161
|
+
if (ev.tipo === 'erro') return C.verm(`${t} erro em ${ev.onde}: ${ev.erro}`);
|
|
162
|
+
if (ev.tipo === 'aviso') return C.amarelo(`${t} AVISO ${ev.texto}`);
|
|
163
|
+
if (ev.tipo === 'ligada') return C.verde(`${t} ligada`);
|
|
164
|
+
if (ev.tipo === 'substituida') return C.amarelo(`${t} tomada por outra maquina`);
|
|
165
|
+
if (ev.tipo === 'parado') return C.dim(`${t} parada ${ev.motivo || ''}`);
|
|
166
|
+
return C.dim(`${t} ${ev.tipo}`);
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
await menu();
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
// Modo servico: liga todas as bashes e nunca abre menu. Loga em linha (JSONL-ish).
|
|
173
|
+
export async function rodarHeadless({ url, instance } = {}) {
|
|
174
|
+
const estado = carregar();
|
|
175
|
+
if (!estado.bashes.length) { console.error('nenhuma bash cadastrada (~/.neuroniun/bashes.json vazio).'); process.exit(1); }
|
|
176
|
+
for (const b of estado.bashes) {
|
|
177
|
+
const w = new Worker({ ...b, url: b.url || url, instance: b.instance || instance || INSTANCIA_PADRAO }, { run: realRun });
|
|
178
|
+
w.on('log', (ev) => console.log(`[${ev.nome}] ${ev.tipo}${ev.comando ? ' ' + ev.comando : ''}${ev.erro ? ' ' + ev.erro : ''}${ev.texto ? ' ' + ev.texto : ''}`));
|
|
179
|
+
w.iniciar().catch((e) => console.error(`[${b.nome}] nao ligou: ${e.message || e}`));
|
|
180
|
+
}
|
|
181
|
+
}
|
package/src/estado.js
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
// ESTADO EM DISCO de cada comando (runner 0.5.0; spec 03 par. 5.8):
|
|
2
|
+
// ~/.neuroniun/exec/<cmd_id>.json (modo 600). Serve para:
|
|
3
|
+
// - reenviar o resultado se o concluir falhou (rede caiu, no reiniciou);
|
|
4
|
+
// - declarar "interrompido" ao religar, quando o runner morreu no meio.
|
|
5
|
+
// Nunca guarda valor de segredo: so a saida JA redigida.
|
|
6
|
+
import fs from 'node:fs';
|
|
7
|
+
import path from 'node:path';
|
|
8
|
+
|
|
9
|
+
function idOk(cid) { return String(cid || '').replace(/[^A-Za-z0-9_]/g, '').slice(0, 60); }
|
|
10
|
+
|
|
11
|
+
export class EstadoEmDisco {
|
|
12
|
+
constructor(dir) { this.dir = dir; }
|
|
13
|
+
|
|
14
|
+
caminho(cid) { return path.join(this.dir, idOk(cid) + '.json'); }
|
|
15
|
+
|
|
16
|
+
salvar(reg) {
|
|
17
|
+
const cid = idOk(reg && reg.cmd_id);
|
|
18
|
+
if (!cid) return false;
|
|
19
|
+
try {
|
|
20
|
+
fs.mkdirSync(this.dir, { recursive: true, mode: 0o700 });
|
|
21
|
+
const f = this.caminho(cid);
|
|
22
|
+
fs.writeFileSync(f + '.tmp', JSON.stringify({ ...reg, cmd_id: cid, salvo_em: Date.now() }), { mode: 0o600 });
|
|
23
|
+
fs.renameSync(f + '.tmp', f);
|
|
24
|
+
return true;
|
|
25
|
+
} catch { return false; }
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
ler(cid) {
|
|
29
|
+
try { return JSON.parse(fs.readFileSync(this.caminho(cid), 'utf8')); } catch { return null; }
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
apagar(cid) {
|
|
33
|
+
try { fs.rmSync(this.caminho(cid), { force: true }); } catch { /* ja foi */ }
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** Os registros desta bash que ficaram para tras (rodando ou pronto sem envio). */
|
|
37
|
+
pendentes(bashId) {
|
|
38
|
+
let nomes = [];
|
|
39
|
+
try { nomes = fs.readdirSync(this.dir).filter((n) => /^[A-Za-z0-9_]+\.json$/.test(n)); } catch { return []; }
|
|
40
|
+
const out = [];
|
|
41
|
+
for (const n of nomes) {
|
|
42
|
+
try {
|
|
43
|
+
const r = JSON.parse(fs.readFileSync(path.join(this.dir, n), 'utf8'));
|
|
44
|
+
if (r && r.cmd_id && (!bashId || r.bash_id === bashId) && (r.estado === 'rodando' || r.estado === 'pronto')) out.push(r);
|
|
45
|
+
} catch { /* arquivo quebrado: ignora */ }
|
|
46
|
+
}
|
|
47
|
+
return out;
|
|
48
|
+
}
|
|
49
|
+
}
|