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/bin/neuronio.js
DELETED
|
@@ -1,112 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
/**
|
|
3
|
-
* Neuronio — o console local do Neuroniun.
|
|
4
|
-
*
|
|
5
|
-
* `neuronio` sobe o agente; `neuronio configurar` refaz o cadastro. Nada de
|
|
6
|
-
* usuario e senha: a credencial e a chave de API, que ja carrega quem e a
|
|
7
|
-
* pessoa e a organizacao dela.
|
|
8
|
-
*/
|
|
9
|
-
import readline from 'node:readline/promises';
|
|
10
|
-
import { stdin, stdout } from 'node:process';
|
|
11
|
-
import { gravaConfig, leConfig, ARQUIVO } from '../src/config.js';
|
|
12
|
-
import { executa } from '../src/api.js';
|
|
13
|
-
import { laco, registra } from '../src/agente.js';
|
|
14
|
-
import { laco as lacoChat } from '../src/chat.js';
|
|
15
|
-
|
|
16
|
-
const log = (t) => console.log(t);
|
|
17
|
-
|
|
18
|
-
async function pergunta(rl, texto, padrao = '') {
|
|
19
|
-
const r = (await rl.question(padrao ? `${texto} [${padrao}] ` : `${texto} `)).trim();
|
|
20
|
-
return r || padrao;
|
|
21
|
-
}
|
|
22
|
-
|
|
23
|
-
async function configurar() {
|
|
24
|
-
const rl = readline.createInterface({ input: stdin, output: stdout });
|
|
25
|
-
try {
|
|
26
|
-
const antigo = leConfig() || {};
|
|
27
|
-
console.log('');
|
|
28
|
-
console.log(' Neuronio — console local');
|
|
29
|
-
console.log('');
|
|
30
|
-
const url = await pergunta(
|
|
31
|
-
rl,
|
|
32
|
-
' Nó:',
|
|
33
|
-
antigo.url || 'https://api-neuroniun.neuron-db.com',
|
|
34
|
-
);
|
|
35
|
-
console.log(' As credenciais saem de Ajustes > Chaves de API, no Neuroniun.');
|
|
36
|
-
console.log(' Escolha o alcance "Herda minhas permissões" — o console');
|
|
37
|
-
console.log(' precisa LER a resposta do que chamou.');
|
|
38
|
-
// O client_id não autentica nada: guardar serve para a pessoa saber qual
|
|
39
|
-
// credencial revogar quando esta máquina for embora.
|
|
40
|
-
const clientId = await pergunta(rl, ' client_id (opcional):', antigo.client_id || '');
|
|
41
|
-
const chave = await pergunta(rl, ' Segredo:', antigo.chave || '');
|
|
42
|
-
if (!chave) {
|
|
43
|
-
console.log(' Sem chave não dá para seguir.');
|
|
44
|
-
return null;
|
|
45
|
-
}
|
|
46
|
-
const bashId = await pergunta(
|
|
47
|
-
rl,
|
|
48
|
-
' Identificador deste bash (só letras, números, - e _):',
|
|
49
|
-
antigo.bash_id || 'meu-console',
|
|
50
|
-
);
|
|
51
|
-
const nome = await pergunta(rl, ' Nome que aparece na tela:', antigo.nome || bashId);
|
|
52
|
-
const compartilhar = await pergunta(
|
|
53
|
-
rl,
|
|
54
|
-
' Compartilhar com a empresa inteira? (s/N):',
|
|
55
|
-
antigo.escopo === 'org' ? 's' : 'n',
|
|
56
|
-
);
|
|
57
|
-
const config = {
|
|
58
|
-
url,
|
|
59
|
-
client_id: clientId,
|
|
60
|
-
chave,
|
|
61
|
-
bash_id: bashId.toLowerCase().replace(/[^a-z0-9_-]/g, ''),
|
|
62
|
-
nome,
|
|
63
|
-
escopo: compartilhar.toLowerCase().startsWith('s') ? 'org' : 'user',
|
|
64
|
-
};
|
|
65
|
-
const r = await registra(config);
|
|
66
|
-
if (!r || r.ok !== true) {
|
|
67
|
-
console.log(` Não deu: ${(r && r.erro) || 'o nó recusou o registro'}`);
|
|
68
|
-
return null;
|
|
69
|
-
}
|
|
70
|
-
gravaConfig(config);
|
|
71
|
-
const escopoReal = (r.agente && r.agente.escopo) || config.escopo;
|
|
72
|
-
if (escopoReal !== config.escopo) {
|
|
73
|
-
console.log(' Sem organização, este bash fica só seu.');
|
|
74
|
-
}
|
|
75
|
-
console.log(` Registrado. Configuração em ${ARQUIVO} (modo 600).`);
|
|
76
|
-
return { ...config, escopo: escopoReal };
|
|
77
|
-
} finally {
|
|
78
|
-
rl.close();
|
|
79
|
-
}
|
|
80
|
-
}
|
|
81
|
-
|
|
82
|
-
async function main() {
|
|
83
|
-
const acao = process.argv[2] || 'rodar';
|
|
84
|
-
if (acao === 'configurar') {
|
|
85
|
-
await configurar();
|
|
86
|
-
return;
|
|
87
|
-
}
|
|
88
|
-
let config = leConfig();
|
|
89
|
-
if (!config || !config.chave) config = await configurar();
|
|
90
|
-
if (!config) process.exit(1);
|
|
91
|
-
|
|
92
|
-
if (acao === 'chat') {
|
|
93
|
-
await lacoChat(config);
|
|
94
|
-
return;
|
|
95
|
-
}
|
|
96
|
-
|
|
97
|
-
if (acao === 'testar') {
|
|
98
|
-
const r = await executa(config, 'run => neuroniun.bash().agentes()');
|
|
99
|
-
console.log(JSON.stringify(r, null, 2));
|
|
100
|
-
return;
|
|
101
|
-
}
|
|
102
|
-
|
|
103
|
-
console.log(` Neuronio ligado como "${config.nome}" (${config.escopo}).`);
|
|
104
|
-
console.log(' Aguardando tarefas. Ctrl+C para sair.');
|
|
105
|
-
console.log(' Para conversar em vez de esperar: neuronio chat');
|
|
106
|
-
await laco(config, log);
|
|
107
|
-
}
|
|
108
|
-
|
|
109
|
-
main().catch((erro) => {
|
|
110
|
-
console.error(` ${erro.message}`);
|
|
111
|
-
process.exit(1);
|
|
112
|
-
});
|
package/src/agente.js
DELETED
|
@@ -1,96 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* O laco do console: pergunta se ha tarefa, executa aqui, devolve o resultado.
|
|
3
|
-
*
|
|
4
|
-
* Polling e nao conexao longa. Com dezenas de maquinas ligadas, uma conexao
|
|
5
|
-
* aberta por maquina e onde a lentidao apareceria; um GET a cada cinco
|
|
6
|
-
* segundos custa quase nada e sobrevive a queda de rede sem reconectar nada.
|
|
7
|
-
*/
|
|
8
|
-
import { exec } from 'node:child_process';
|
|
9
|
-
import os from 'node:os';
|
|
10
|
-
import { b64, executa } from './api.js';
|
|
11
|
-
import {
|
|
12
|
-
HEARTBEAT_MS,
|
|
13
|
-
INTERVALO_MS,
|
|
14
|
-
SAIDA_MAX,
|
|
15
|
-
TIMEOUT_COMANDO_MS,
|
|
16
|
-
} from './config.js';
|
|
17
|
-
|
|
18
|
-
const VERSAO = '0.1.0';
|
|
19
|
-
|
|
20
|
-
export async function registra(config) {
|
|
21
|
-
return executa(
|
|
22
|
-
config,
|
|
23
|
-
`run => neuroniun.bash().registrar("${config.bash_id}", ` +
|
|
24
|
-
`"${b64(config.nome)}", "${config.escopo}", "${b64(os.hostname())}", ` +
|
|
25
|
-
`"${VERSAO}")`,
|
|
26
|
-
);
|
|
27
|
-
}
|
|
28
|
-
|
|
29
|
-
/** Roda UM comando nesta maquina e devolve o que saiu.
|
|
30
|
-
*
|
|
31
|
-
* Sem sandbox de proposito: o console existe para a IA poder criar arquivo,
|
|
32
|
-
* rodar build, abrir outra ferramenta. Quem instala e a dona da maquina, e a
|
|
33
|
-
* fronteira e a chave — nao um filtro de comandos que daria falsa seguranca. */
|
|
34
|
-
function rodaLocal(comando) {
|
|
35
|
-
return new Promise((resolve) => {
|
|
36
|
-
exec(
|
|
37
|
-
comando,
|
|
38
|
-
{
|
|
39
|
-
timeout: TIMEOUT_COMANDO_MS,
|
|
40
|
-
maxBuffer: 8 * 1024 * 1024,
|
|
41
|
-
shell: '/bin/bash',
|
|
42
|
-
},
|
|
43
|
-
(erro, stdout, stderr) => {
|
|
44
|
-
const saida = `${stdout || ''}${stderr || ''}`.slice(0, SAIDA_MAX);
|
|
45
|
-
resolve({
|
|
46
|
-
status: erro ? 'erro' : 'sucesso',
|
|
47
|
-
// `erro.code` é undefined quando o processo morreu por timeout; 0 é
|
|
48
|
-
// um código válido e falsy, então o teste tem de ser por null.
|
|
49
|
-
exit_code: erro ? (erro.code ?? -1) : 0,
|
|
50
|
-
saida: saida || (erro ? String(erro.message).slice(0, 400) : ''),
|
|
51
|
-
});
|
|
52
|
-
},
|
|
53
|
-
);
|
|
54
|
-
});
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
export async function umaVolta(config, log) {
|
|
58
|
-
const pendentes = await executa(
|
|
59
|
-
config,
|
|
60
|
-
`run => neuroniun.bash().pegar("${config.bash_id}", "1")`,
|
|
61
|
-
);
|
|
62
|
-
const itens = (pendentes && pendentes.itens) || [];
|
|
63
|
-
if (!itens.length) return 0;
|
|
64
|
-
for (const tarefa of itens) {
|
|
65
|
-
log(`> ${tarefa.titulo || tarefa.comando}`);
|
|
66
|
-
const r = await rodaLocal(String(tarefa.comando || ''));
|
|
67
|
-
await executa(
|
|
68
|
-
config,
|
|
69
|
-
`run => neuroniun.bash().resultado("${config.bash_id}", ` +
|
|
70
|
-
`"${tarefa.id}", "${r.status}", "${b64(r.saida)}", "${r.exit_code}")`,
|
|
71
|
-
);
|
|
72
|
-
log(` ${r.status} (exit ${r.exit_code})`);
|
|
73
|
-
}
|
|
74
|
-
return itens.length;
|
|
75
|
-
}
|
|
76
|
-
|
|
77
|
-
export async function laco(config, log, { pare } = {}) {
|
|
78
|
-
let ultimoPing = 0;
|
|
79
|
-
for (;;) {
|
|
80
|
-
if (pare && pare()) return;
|
|
81
|
-
try {
|
|
82
|
-
const agora = Date.now();
|
|
83
|
-
// Registrar de novo É o heartbeat: o servidor guarda `visto_em` e a tela
|
|
84
|
-
// decide "vivo" por tempo. Um estado guardado mentiria sobre a máquina
|
|
85
|
-
// que caiu sem avisar.
|
|
86
|
-
if (agora - ultimoPing > HEARTBEAT_MS) {
|
|
87
|
-
await registra(config);
|
|
88
|
-
ultimoPing = agora;
|
|
89
|
-
}
|
|
90
|
-
await umaVolta(config, log);
|
|
91
|
-
} catch (erro) {
|
|
92
|
-
log(`falha: ${erro.message}`);
|
|
93
|
-
}
|
|
94
|
-
await new Promise((r) => setTimeout(r, INTERVALO_MS));
|
|
95
|
-
}
|
|
96
|
-
}
|
package/src/chat.js
DELETED
|
@@ -1,68 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Conversar com o Neuroniun sem sair do terminal.
|
|
3
|
-
*
|
|
4
|
-
* O que muda em relação ao chat da tela: aqui a resposta é texto puro. Cartão,
|
|
5
|
-
* imagem e formulário não têm como aparecer — quando a resposta vier assim, o
|
|
6
|
-
* console diz o que ela é e onde vê-la, em vez de imprimir um JSON cru que
|
|
7
|
-
* ninguém lê.
|
|
8
|
-
*/
|
|
9
|
-
import readline from 'node:readline/promises';
|
|
10
|
-
import { stdin, stdout } from 'node:process';
|
|
11
|
-
import { b64, executa } from './api.js';
|
|
12
|
-
|
|
13
|
-
/** Uma pergunta, uma resposta. Separado do laço para poder ser testado. */
|
|
14
|
-
export async function pergunta(config, texto) {
|
|
15
|
-
const r = await executa(
|
|
16
|
-
config,
|
|
17
|
-
`run => neuroniun.chat_core("${b64(texto)}", "text", "", "nao", "", "")`,
|
|
18
|
-
{ timeoutMs: 240000 },
|
|
19
|
-
);
|
|
20
|
-
return leResposta(r);
|
|
21
|
-
}
|
|
22
|
-
|
|
23
|
-
/** O que mostrar de uma resposta do Neuroniun. */
|
|
24
|
-
export function leResposta(r) {
|
|
25
|
-
if (r == null) return 'O nó não devolveu resposta.';
|
|
26
|
-
if (typeof r === 'string') {
|
|
27
|
-
// O motor às vezes devolve o nome do bag em vez do valor. Dizer isso é
|
|
28
|
-
// melhor do que imprimir "__bag.out" e deixar a pessoa achando que é a
|
|
29
|
-
// resposta.
|
|
30
|
-
if (r.startsWith('__bag')) return 'O nó devolveu uma resposta vazia.';
|
|
31
|
-
return r;
|
|
32
|
-
}
|
|
33
|
-
const texto = String(r.answer ?? r.resposta ?? '').trim();
|
|
34
|
-
if (texto) return texto;
|
|
35
|
-
const meta = r.meta ?? {};
|
|
36
|
-
if (meta.interaction) return 'O Neuroniun pediu uma confirmação — responda na tela.';
|
|
37
|
-
if (meta.form) return 'A resposta é um formulário — abra na tela.';
|
|
38
|
-
if (r.image === true || r.kind === 'image') return 'A resposta é uma imagem — abra na tela.';
|
|
39
|
-
const evid = String(r.evidencia ?? '').trim();
|
|
40
|
-
if (evid) return evid;
|
|
41
|
-
return 'Sem texto na resposta.';
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
export async function laco(config) {
|
|
45
|
-
const rl = readline.createInterface({ input: stdin, output: stdout });
|
|
46
|
-
console.log('');
|
|
47
|
-
console.log(' Neuronio — conversa. Ctrl+C ou "sair" para voltar.');
|
|
48
|
-
console.log('');
|
|
49
|
-
try {
|
|
50
|
-
for (;;) {
|
|
51
|
-
const texto = (await rl.question(' você> ')).trim();
|
|
52
|
-
if (!texto) continue;
|
|
53
|
-
if (['sair', 'exit', 'quit'].includes(texto.toLowerCase())) return;
|
|
54
|
-
process.stdout.write(' ...\r');
|
|
55
|
-
try {
|
|
56
|
-
const resposta = await pergunta(config, texto);
|
|
57
|
-
process.stdout.write(' \r');
|
|
58
|
-
console.log(` neuroniun> ${resposta}`);
|
|
59
|
-
} catch (erro) {
|
|
60
|
-
process.stdout.write(' \r');
|
|
61
|
-
console.log(` falhou: ${erro.message}`);
|
|
62
|
-
}
|
|
63
|
-
console.log('');
|
|
64
|
-
}
|
|
65
|
-
} finally {
|
|
66
|
-
rl.close();
|
|
67
|
-
}
|
|
68
|
-
}
|
package/src/config.js
DELETED
|
@@ -1,33 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Onde o console guarda o que precisa para voltar sozinho.
|
|
3
|
-
*
|
|
4
|
-
* A chave de API mora aqui e em mais lugar nenhum: e ela que identifica a
|
|
5
|
-
* pessoa e, por tabela, a organizacao dela. Por isso o arquivo nasce 600 — um
|
|
6
|
-
* console instalado num servidor compartilhado nao pode ser lido pelo vizinho.
|
|
7
|
-
*/
|
|
8
|
-
import fs from 'node:fs';
|
|
9
|
-
import os from 'node:os';
|
|
10
|
-
import path from 'node:path';
|
|
11
|
-
|
|
12
|
-
export const ARQUIVO = path.join(os.homedir(), '.neuronio.json');
|
|
13
|
-
export const INTERVALO_MS = 5000;
|
|
14
|
-
export const HEARTBEAT_MS = 30000;
|
|
15
|
-
export const TIMEOUT_COMANDO_MS = 30 * 60 * 1000;
|
|
16
|
-
export const SAIDA_MAX = 20000;
|
|
17
|
-
|
|
18
|
-
export function leConfig() {
|
|
19
|
-
try {
|
|
20
|
-
return JSON.parse(fs.readFileSync(ARQUIVO, 'utf8'));
|
|
21
|
-
} catch {
|
|
22
|
-
return null;
|
|
23
|
-
}
|
|
24
|
-
}
|
|
25
|
-
|
|
26
|
-
export function gravaConfig(config) {
|
|
27
|
-
fs.writeFileSync(ARQUIVO, JSON.stringify(config, null, 2), { mode: 0o600 });
|
|
28
|
-
try {
|
|
29
|
-
fs.chmodSync(ARQUIVO, 0o600);
|
|
30
|
-
} catch {
|
|
31
|
-
// Sistema de arquivos sem permissao POSIX: o aviso ja foi dado na criacao.
|
|
32
|
-
}
|
|
33
|
-
}
|