neuroniun 0.2.0 → 0.3.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/README.md +41 -72
- package/bin/neuroniun.js +34 -0
- package/package.json +11 -19
- package/src/api.js +64 -50
- package/src/console.js +158 -0
- package/src/store.js +52 -0
- package/src/worker.js +122 -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/README.md
CHANGED
|
@@ -1,91 +1,60 @@
|
|
|
1
|
-
#
|
|
1
|
+
# neuroniun — o agente de terminal da IA Neuroniun
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
3
|
+
Executa **na sua máquina** o que chega da entidade de tarefas do Neuroniun
|
|
4
|
+
(workflows, comandos de IA). Não é o N-Bash (esse é o `neuroniundb`, console do
|
|
5
|
+
banco): este agente **nunca faz login no NeuroniunDB**. Ele fala só pela porta
|
|
6
|
+
pública (`POST /public`), apresentando o **token** de uma bash — e o servidor
|
|
7
|
+
faz tudo com autoridade de definer, escopada àquela bash. Quem usa o Neuroniun
|
|
8
|
+
não ganha acesso ao banco.
|
|
8
9
|
|
|
9
10
|
## Instalar
|
|
10
11
|
|
|
11
12
|
```bash
|
|
12
|
-
npm
|
|
13
|
-
neuronio configurar
|
|
13
|
+
npm i -g neuroniun
|
|
14
14
|
```
|
|
15
15
|
|
|
16
|
-
|
|
17
|
-
API dentro do Neuroniun. Não há usuário e senha: a credencial já carrega quem
|
|
18
|
-
é a pessoa e a organização dela.
|
|
19
|
-
|
|
20
|
-
Escolha o alcance **"Herda minhas permissões"**. O alcance estreito chama
|
|
21
|
-
fluxo e nada mais — o console conseguiria disparar, mas não conseguiria ler a
|
|
22
|
-
resposta do que disparou.
|
|
23
|
-
|
|
24
|
-
O segredo aparece **uma vez só**. O `client_id` fica visível para sempre e é
|
|
25
|
-
por ele que se revoga — guarde os dois. E vale prender a credencial aos IPs
|
|
26
|
-
da máquina onde o console roda: o nó recusa a chamada de qualquer outro
|
|
27
|
-
endereço.
|
|
28
|
-
|
|
29
|
-
Na configuração o console pergunta três coisas: um identificador, o nome que
|
|
30
|
-
aparece na tela, e se o bash é **da empresa inteira** ou **só seu**. Sem
|
|
31
|
-
organização, o pedido de compartilhar vira pessoal em silêncio — não há com
|
|
32
|
-
quem compartilhar.
|
|
33
|
-
|
|
34
|
-
A configuração fica em `~/.neuronio.json`, modo 600.
|
|
35
|
-
|
|
36
|
-
## Rodar
|
|
16
|
+
## Usar
|
|
37
17
|
|
|
38
18
|
```bash
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
19
|
+
neuroniun # abre o console: menu + tela ao vivo de cada bash
|
|
20
|
+
neuroniun --headless # liga todas as bashes cadastradas, sem menu (serviço)
|
|
21
|
+
neuroniun --add <token> # cadastra uma bash e sai (para scripts/instalação)
|
|
22
|
+
neuroniun --url <u> # aponta para outro nó (padrão: api-neuroniun)
|
|
43
23
|
```
|
|
44
24
|
|
|
45
|
-
No `
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
25
|
+
No console: `a` cola a chave de uma bash (gerada na tela **Configurações →
|
|
26
|
+
Bashes** do app), um **número** abre a tela ao vivo daquela bash (`q`/Esc volta),
|
|
27
|
+
`r` remove uma bash desta máquina, `q` sai. Suporta **várias bashes ao mesmo
|
|
28
|
+
tempo** — cada uma é um worker próprio (estilo pm2), com seu poll (5 s), seu ping
|
|
29
|
+
(5 min) e sua fila.
|
|
50
30
|
|
|
51
|
-
|
|
52
|
-
[Service]
|
|
53
|
-
WorkingDirectory=/opt/neuronio
|
|
54
|
-
ExecStart=/usr/bin/node /opt/neuronio/bin/neuronio.js
|
|
55
|
-
Restart=always
|
|
56
|
-
```
|
|
31
|
+
## O que ele faz, por baixo
|
|
57
32
|
|
|
58
|
-
|
|
33
|
+
1. **Liga** a bash (`nbx_ag_ligar`) — informa host/SO/usuário; se a chave já
|
|
34
|
+
estava ligada em outra máquina, esta toma.
|
|
35
|
+
2. **Poll** a cada 5 s (`nbx_ag_proximo`): pega o próximo comando da fila.
|
|
36
|
+
3. **Executa** com `/bin/sh -c`, com a permissão do usuário que instalou —
|
|
37
|
+
qualquer comando, inclusive `claude`. Tempo máximo 10 min, saída até 1 MB.
|
|
38
|
+
4. **Devolve** a saída (`nbx_ag_concluir`): grava no histórico do dia e o
|
|
39
|
+
comando some da fila.
|
|
40
|
+
5. **Ping** a cada 5 min (`nbx_ag_ping`): mantém o semáforo verde.
|
|
59
41
|
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
42
|
+
Estado local: `~/.neuroniun/bashes.json` (modo 600) — url, instância, bash_id,
|
|
43
|
+
nome e o segredo do token. Nada disso sai da máquina a não ser como o token,
|
|
44
|
+
para o `/public`.
|
|
63
45
|
|
|
64
|
-
|
|
65
|
-
um parâmetro:
|
|
66
|
-
|
|
67
|
-
```
|
|
68
|
-
__$neuroniun_bash.T<tid>.__agentes quem está registrado
|
|
69
|
-
__$neuroniun_bash.T<tid>.__fila.<bash_id> as tarefas daquele bash
|
|
70
|
-
```
|
|
71
|
-
|
|
72
|
-
Uma tarefa passa por `pendente` → `rodando` → `sucesso` ou `erro`. Pegar e
|
|
73
|
-
marcar como rodando acontecem na mesma chamada: é isso que impede dois agentes
|
|
74
|
-
com o mesmo identificador de executarem a mesma coisa. Tarefa presa em
|
|
75
|
-
`rodando` por mais de duas horas volta para a fila — máquina que caiu no meio
|
|
76
|
-
não deixa trabalho preso.
|
|
46
|
+
## Segurança
|
|
77
47
|
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
48
|
+
- O agente não tem credencial do nó — só o token da bash. O token expira e pode
|
|
49
|
+
ser revogado no app; revogado, o agente para de ligar.
|
|
50
|
+
- Roda com a autoridade da máquina onde foi instalado. É o modelo: você acessou
|
|
51
|
+
a máquina e instalou, então pode rodar o que quiser nela.
|
|
81
52
|
|
|
82
|
-
##
|
|
53
|
+
## Testes
|
|
83
54
|
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
55
|
+
```bash
|
|
56
|
+
npm test # unitário (fila falsa, sem rede)
|
|
57
|
+
NBX_INTEGRA=1 node test/integra_producao.mjs # agente real contra produção
|
|
58
|
+
```
|
|
87
59
|
|
|
88
|
-
|
|
89
|
-
qualquer pessoa da organização — é para isso que ele foi publicado. Ninguém
|
|
90
|
-
sequestra um identificador já registrado: reapresentar-se com o nome de outra
|
|
91
|
-
pessoa é recusado.
|
|
60
|
+
Backend e protocolo: `flows/58-flow-nbx.snl` e `docs/SPEC-NEURONIUN-BASH.md`.
|
package/bin/neuroniun.js
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// neuroniun — o console/agente da IA Neuroniun.
|
|
3
|
+
// neuroniun abre o console (menu + tela ao vivo)
|
|
4
|
+
// neuroniun --headless liga todas as bashes cadastradas, sem menu (servico)
|
|
5
|
+
// neuroniun --url <u> aponta para outro no (padrao: o do config, senao pergunta)
|
|
6
|
+
// neuroniun --add <token> cadastra uma bash e sai (para scripts/instalacao)
|
|
7
|
+
import { rodarConsole, rodarHeadless } from '../src/console.js';
|
|
8
|
+
import { carregar, salvar, upsert, bashDeToken } from '../src/store.js';
|
|
9
|
+
import { Worker, realRun } from '../src/worker.js';
|
|
10
|
+
|
|
11
|
+
const argv = process.argv.slice(2);
|
|
12
|
+
function opt(nome) { const i = argv.indexOf(nome); return i >= 0 ? argv[i + 1] : undefined; }
|
|
13
|
+
const has = (n) => argv.includes(n);
|
|
14
|
+
|
|
15
|
+
const url = opt('--url') || process.env.NEURONIUN_URL || 'https://api-neuroniun.neuron-db.com';
|
|
16
|
+
const instance = opt('--instance') || process.env.NEURONIUN_INSTANCE || 'system';
|
|
17
|
+
|
|
18
|
+
async function main() {
|
|
19
|
+
if (has('--add')) {
|
|
20
|
+
const token = opt('--add');
|
|
21
|
+
const bash = bashDeToken(token, url, instance);
|
|
22
|
+
if (!bash) { console.error('chave invalida'); process.exit(2); }
|
|
23
|
+
let estado = carregar();
|
|
24
|
+
estado = upsert(estado, bash); salvar(estado);
|
|
25
|
+
const w = new Worker(bash, { run: realRun });
|
|
26
|
+
try { await w.ligar(); await w.parar('cadastro'); console.log('bash cadastrada e verificada:', bash.bash_id); }
|
|
27
|
+
catch (e) { console.error('cadastrada, mas nao ligou:', e.message || e); process.exit(1); }
|
|
28
|
+
return;
|
|
29
|
+
}
|
|
30
|
+
if (has('--headless')) return rodarHeadless({ url, instance });
|
|
31
|
+
return rodarConsole({ url, instance });
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
main().catch((e) => { console.error(e && e.stack || e); process.exit(1); });
|
package/package.json
CHANGED
|
@@ -1,34 +1,26 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "neuroniun",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "
|
|
3
|
+
"version": "0.3.0",
|
|
4
|
+
"description": "Neuroniun Bash — o agente de terminal da IA Neuroniun. Executa na sua maquina o que chega da entidade de tarefas do Neuroniun. Nao e o N-Bash (esse virou neuroniundb) e nunca faz login no NeuroniunDB.",
|
|
5
|
+
"type": "module",
|
|
5
6
|
"bin": {
|
|
6
|
-
"neuroniun": "./bin/
|
|
7
|
-
"neuronio": "./bin/neuronio.js"
|
|
7
|
+
"neuroniun": "./bin/neuroniun.js"
|
|
8
8
|
},
|
|
9
|
-
"type": "module",
|
|
10
9
|
"engines": {
|
|
11
10
|
"node": ">=18.0.0"
|
|
12
11
|
},
|
|
12
|
+
"scripts": {
|
|
13
|
+
"test": "node --test test/*.test.mjs"
|
|
14
|
+
},
|
|
13
15
|
"files": [
|
|
14
16
|
"bin/",
|
|
15
17
|
"src/",
|
|
16
|
-
"README.md"
|
|
17
|
-
"LICENSE"
|
|
18
|
-
],
|
|
19
|
-
"license": "MIT",
|
|
20
|
-
"author": "Pisani da Arq",
|
|
21
|
-
"homepage": "https://neuron-db.com",
|
|
22
|
-
"keywords": [
|
|
23
|
-
"neuroniun",
|
|
24
|
-
"neuroniundb",
|
|
25
|
-
"console",
|
|
26
|
-
"agent",
|
|
27
|
-
"bash",
|
|
28
|
-
"automation"
|
|
18
|
+
"README.md"
|
|
29
19
|
],
|
|
20
|
+
"license": "UNLICENSED",
|
|
30
21
|
"repository": {
|
|
31
22
|
"type": "git",
|
|
32
|
-
"url": "https://github.com/
|
|
23
|
+
"url": "https://github.com/pisanidaarch/neuroniun.git",
|
|
24
|
+
"directory": "agent"
|
|
33
25
|
}
|
|
34
26
|
}
|
package/src/api.js
CHANGED
|
@@ -1,58 +1,72 @@
|
|
|
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
|
-
saida += B64[((y & 15) << 2) | ((z === undefined ? 0 : z) >> 6)];
|
|
21
|
-
if (z !== undefined) saida += B64[z & 63];
|
|
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];
|
|
23
20
|
}
|
|
24
|
-
return
|
|
21
|
+
return 'b64:' + o;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
// Só letras/dígitos/_/. entram sem aspas escapadas; o token e os ids são assim.
|
|
25
|
+
function arg(v) {
|
|
26
|
+
const s = String(v == null ? '' : v);
|
|
27
|
+
if (s.startsWith('b64:')) return s; // b64 viaja cru
|
|
28
|
+
if (/^[A-Za-z0-9_.]+$/.test(s)) return `"${s}"`; // id/token seguro
|
|
29
|
+
return b64(s); // qualquer outra coisa vira b64
|
|
25
30
|
}
|
|
26
31
|
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
const
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
32
|
+
// Chama uma OPEN flow do Neuroniun por /public. Devolve o `result` já parseado.
|
|
33
|
+
export async function callPublic(baseUrl, instance, flow, args = [], timeoutMs = 30000) {
|
|
34
|
+
const command = `run neuroniun.${flow}(${args.map(arg).join(', ')})`;
|
|
35
|
+
const body = Buffer.from(JSON.stringify({ command, instance: instance || 'system' }), 'utf-8');
|
|
36
|
+
const u = new URL(baseUrl.replace(/\/+$/, '') + '/public');
|
|
37
|
+
const lib = u.protocol === 'http:' ? http : https;
|
|
38
|
+
const opts = {
|
|
39
|
+
method: 'POST',
|
|
40
|
+
hostname: u.hostname,
|
|
41
|
+
port: u.port || (u.protocol === 'http:' ? 80 : 443),
|
|
42
|
+
path: u.pathname,
|
|
43
|
+
headers: {
|
|
44
|
+
'Content-Type': 'application/json',
|
|
45
|
+
'Content-Length': body.length,
|
|
46
|
+
'User-Agent': 'neuroniun-agent/0.1',
|
|
47
|
+
},
|
|
48
|
+
timeout: timeoutMs,
|
|
49
|
+
};
|
|
50
|
+
const raw = await new Promise((resolve, reject) => {
|
|
51
|
+
const req = lib.request(opts, (res) => {
|
|
52
|
+
let data = '';
|
|
53
|
+
res.setEncoding('utf-8');
|
|
54
|
+
res.on('data', (c) => { data += c; });
|
|
55
|
+
res.on('end', () => resolve(data));
|
|
39
56
|
});
|
|
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);
|
|
57
|
+
req.on('error', reject);
|
|
58
|
+
req.on('timeout', () => { req.destroy(new Error('timeout')); });
|
|
59
|
+
req.write(body);
|
|
60
|
+
req.end();
|
|
61
|
+
});
|
|
62
|
+
let d;
|
|
63
|
+
try { d = JSON.parse(raw.replace(/[\u0001\u0002]/g, '')); }
|
|
64
|
+
catch { throw new Error('resposta nao-JSON de /public: ' + raw.slice(0, 200)); }
|
|
65
|
+
if (d && d.success === false) {
|
|
66
|
+
const msg = (d.error) || ((d.console || [])[0] || {}).message || 'erro no flow';
|
|
67
|
+
throw new Error(String(msg));
|
|
57
68
|
}
|
|
69
|
+
let r = d.result;
|
|
70
|
+
if (typeof r === 'string') { try { r = JSON.parse(r); } catch { /* escalar */ } }
|
|
71
|
+
return r;
|
|
58
72
|
}
|
package/src/console.js
ADDED
|
@@ -0,0 +1,158 @@
|
|
|
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 } from './store.js';
|
|
8
|
+
|
|
9
|
+
const C = {
|
|
10
|
+
dim: (s) => `\x1b[2m${s}\x1b[0m`,
|
|
11
|
+
b: (s) => `\x1b[1m${s}\x1b[0m`,
|
|
12
|
+
verde: (s) => `\x1b[32m${s}\x1b[0m`,
|
|
13
|
+
amarelo: (s) => `\x1b[33m${s}\x1b[0m`,
|
|
14
|
+
verm: (s) => `\x1b[31m${s}\x1b[0m`,
|
|
15
|
+
ciano: (s) => `\x1b[36m${s}\x1b[0m`,
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
function pergunta(rl, texto) { return new Promise((res) => rl.question(texto, (a) => res(a.trim()))); }
|
|
19
|
+
|
|
20
|
+
function corEstado(w) {
|
|
21
|
+
if (w.estado === 'ligada') return C.verde('● ligada');
|
|
22
|
+
if (w.estado === 'parado') return C.dim('○ parada');
|
|
23
|
+
return C.amarelo('● ' + w.estado);
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export async function rodarConsole({ url, instance } = {}) {
|
|
27
|
+
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
|
|
28
|
+
let estado = carregar();
|
|
29
|
+
const workers = new Map(); // bash_id -> Worker
|
|
30
|
+
const buffers = new Map(); // bash_id -> últimas linhas de log
|
|
31
|
+
|
|
32
|
+
function conectar(bash) {
|
|
33
|
+
if (workers.has(bash.bash_id)) return workers.get(bash.bash_id);
|
|
34
|
+
const w = new Worker({ ...bash, url: bash.url || url, instance: bash.instance || instance || 'system' }, { run: realRun });
|
|
35
|
+
buffers.set(bash.bash_id, []);
|
|
36
|
+
w.on('log', (ev) => {
|
|
37
|
+
const buf = buffers.get(bash.bash_id);
|
|
38
|
+
buf.push(ev);
|
|
39
|
+
if (buf.length > 500) buf.shift();
|
|
40
|
+
});
|
|
41
|
+
workers.set(bash.bash_id, w);
|
|
42
|
+
return w;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
// liga todas as bashes ja cadastradas
|
|
46
|
+
for (const b of estado.bashes) {
|
|
47
|
+
const w = conectar(b);
|
|
48
|
+
w.iniciar().catch((e) => { /* mostra no menu */ w.erro = String(e.message || e); });
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
async function menu() {
|
|
52
|
+
for (;;) {
|
|
53
|
+
console.log('\n' + C.b('Neuroniun Bash') + C.dim(` — ${workers.size} bash(es) nesta maquina`));
|
|
54
|
+
let i = 0;
|
|
55
|
+
const lista = [...workers.values()];
|
|
56
|
+
for (const w of lista) {
|
|
57
|
+
i++;
|
|
58
|
+
const u = w.ultimo && w.ultimo.comando ? C.dim(` ult: ${w.ultimo.comando.slice(0, 40)} (exit ${w.ultimo.exit})`) : '';
|
|
59
|
+
console.log(` ${C.ciano('[' + i + ']')} ${w.bash.nome} ${corEstado(w)}${w.erro ? ' ' + C.verm(w.erro) : ''}${u}`);
|
|
60
|
+
}
|
|
61
|
+
console.log(C.dim(' ————'));
|
|
62
|
+
console.log(` ${C.ciano('a')} adicionar uma bash (colar a chave)`);
|
|
63
|
+
console.log(` ${C.ciano('g')} gerar uma bash nova a partir desta maquina`);
|
|
64
|
+
console.log(` ${C.ciano('número')} abrir a tela ao vivo de uma bash`);
|
|
65
|
+
console.log(` ${C.ciano('r')} remover uma bash desta maquina`);
|
|
66
|
+
console.log(` ${C.ciano('q')} sair`);
|
|
67
|
+
const a = (await pergunta(rl, '> ')).toLowerCase();
|
|
68
|
+
if (a === 'q') break;
|
|
69
|
+
else if (a === 'a') await adicionar();
|
|
70
|
+
else if (a === 'g') await gerar();
|
|
71
|
+
else if (a === 'r') await removerBash(lista);
|
|
72
|
+
else if (/^\d+$/.test(a)) { const w = lista[Number(a) - 1]; if (w) await telaAoVivo(w); }
|
|
73
|
+
}
|
|
74
|
+
for (const w of workers.values()) await w.parar('saindo do console').catch(() => {});
|
|
75
|
+
rl.close();
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
async function adicionar() {
|
|
79
|
+
const token = await pergunta(rl, 'cole a chave (token) da bash: ');
|
|
80
|
+
const bash = bashDeToken(token, url, instance);
|
|
81
|
+
if (!bash) { console.log(C.verm('chave invalida.')); return; }
|
|
82
|
+
const nome = await pergunta(rl, `nome nesta maquina [${bash.bash_id}]: `);
|
|
83
|
+
if (nome) bash.nome = nome;
|
|
84
|
+
estado = upsert(estado, bash); salvar(estado);
|
|
85
|
+
const w = conectar(bash);
|
|
86
|
+
try { await w.iniciar(); console.log(C.verde('ligada.')); }
|
|
87
|
+
catch (e) { w.erro = String(e.message || e); console.log(C.verm('nao ligou: ' + w.erro)); }
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
async function gerar() {
|
|
91
|
+
const u = url || await pergunta(rl, 'url do Neuroniun (ex: https://api-neuroniun.neuron-db.com): ');
|
|
92
|
+
const inst = instance || (await pergunta(rl, 'instancia [system]: ')) || 'system';
|
|
93
|
+
console.log(C.dim('para gerar, o Neuroniun precisa saber quem e voce.'));
|
|
94
|
+
console.log(C.dim('gere a chave na tela de Configuracoes → Bashes do app e cole aqui com a opcao "a".'));
|
|
95
|
+
// Geração autenticada exige token do usuário; o caminho oficial é o app.
|
|
96
|
+
// Mantido como aviso para não pedir senha no terminal.
|
|
97
|
+
void u; void inst;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
async function removerBash(lista) {
|
|
101
|
+
const a = await pergunta(rl, 'numero da bash a remover desta maquina: ');
|
|
102
|
+
const w = lista[Number(a) - 1];
|
|
103
|
+
if (!w) return;
|
|
104
|
+
await w.parar('removida desta maquina').catch(() => {});
|
|
105
|
+
workers.delete(w.bash.bash_id);
|
|
106
|
+
estado = remover(estado, w.bash.bash_id); salvar(estado);
|
|
107
|
+
console.log(C.dim('removida (a bash continua existindo no Neuroniun; so saiu desta maquina).'));
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function telaAoVivo(w) {
|
|
111
|
+
return new Promise((resolve) => {
|
|
112
|
+
console.clear();
|
|
113
|
+
console.log(C.b(`── ${w.bash.nome} ──`) + C.dim(' (q ou Esc volta ao menu)\n'));
|
|
114
|
+
const buf = buffers.get(w.bash.bash_id) || [];
|
|
115
|
+
for (const ev of buf.slice(-30)) console.log(linha(ev));
|
|
116
|
+
const onLog = (ev) => console.log(linha(ev));
|
|
117
|
+
w.on('log', onLog);
|
|
118
|
+
const rl2 = readline.createInterface({ input: process.stdin });
|
|
119
|
+
readline.emitKeypressEvents(process.stdin);
|
|
120
|
+
if (process.stdin.isTTY) process.stdin.setRawMode(true);
|
|
121
|
+
const onKey = (_s, key) => {
|
|
122
|
+
if (key && (key.name === 'q' || key.name === 'escape' || (key.ctrl && key.name === 'c'))) {
|
|
123
|
+
process.stdin.removeListener('keypress', onKey);
|
|
124
|
+
if (process.stdin.isTTY) process.stdin.setRawMode(false);
|
|
125
|
+
w.removeListener('log', onLog);
|
|
126
|
+
rl2.close();
|
|
127
|
+
console.clear();
|
|
128
|
+
resolve();
|
|
129
|
+
}
|
|
130
|
+
};
|
|
131
|
+
process.stdin.on('keypress', onKey);
|
|
132
|
+
});
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
function linha(ev) {
|
|
136
|
+
const t = new Date().toLocaleTimeString();
|
|
137
|
+
if (ev.tipo === 'comando') return C.ciano(`${t} $ ${ev.comando}`);
|
|
138
|
+
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$/, '')}`;
|
|
139
|
+
if (ev.tipo === 'erro') return C.verm(`${t} erro em ${ev.onde}: ${ev.erro}`);
|
|
140
|
+
if (ev.tipo === 'ligada') return C.verde(`${t} ligada`);
|
|
141
|
+
if (ev.tipo === 'substituida') return C.amarelo(`${t} tomada por outra maquina`);
|
|
142
|
+
if (ev.tipo === 'parado') return C.dim(`${t} parada ${ev.motivo || ''}`);
|
|
143
|
+
return C.dim(`${t} ${ev.tipo}`);
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
await menu();
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
// Modo servico: liga todas as bashes e nunca abre menu. Loga em linha (JSONL-ish).
|
|
150
|
+
export async function rodarHeadless({ url, instance } = {}) {
|
|
151
|
+
const estado = carregar();
|
|
152
|
+
if (!estado.bashes.length) { console.error('nenhuma bash cadastrada (~/.neuroniun/bashes.json vazio).'); process.exit(1); }
|
|
153
|
+
for (const b of estado.bashes) {
|
|
154
|
+
const w = new Worker({ ...b, url: b.url || url, instance: b.instance || instance || 'system' }, { run: realRun });
|
|
155
|
+
w.on('log', (ev) => console.log(`[${ev.nome}] ${ev.tipo}${ev.comando ? ' ' + ev.comando : ''}${ev.erro ? ' ' + ev.erro : ''}`));
|
|
156
|
+
w.iniciar().catch((e) => console.error(`[${b.nome}] nao ligou: ${e.message || e}`));
|
|
157
|
+
}
|
|
158
|
+
}
|
package/src/store.js
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
// Estado local do agente: ~/.neuroniun/bashes.json (modo 600). Guarda so o que a
|
|
2
|
+
// maquina precisa para se apresentar: url, instance, bash_id, nome e o SEGREDO
|
|
3
|
+
// do token. Nada disso sai da maquina a nao ser como o token, para o /public.
|
|
4
|
+
import fs from 'node:fs';
|
|
5
|
+
import os from 'node:os';
|
|
6
|
+
import path from 'node:path';
|
|
7
|
+
|
|
8
|
+
const DIR = path.join(os.homedir(), '.neuroniun');
|
|
9
|
+
const FILE = path.join(DIR, 'bashes.json');
|
|
10
|
+
|
|
11
|
+
export function caminho() { return FILE; }
|
|
12
|
+
|
|
13
|
+
export function carregar() {
|
|
14
|
+
try {
|
|
15
|
+
const raw = fs.readFileSync(FILE, 'utf-8');
|
|
16
|
+
const d = JSON.parse(raw);
|
|
17
|
+
return Array.isArray(d.bashes) ? d : { bashes: [] };
|
|
18
|
+
} catch {
|
|
19
|
+
return { bashes: [] };
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export function salvar(estado) {
|
|
24
|
+
fs.mkdirSync(DIR, { recursive: true });
|
|
25
|
+
fs.writeFileSync(FILE, JSON.stringify(estado, null, 2), { mode: 0o600 });
|
|
26
|
+
try { fs.chmodSync(FILE, 0o600); } catch { /* best effort */ }
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
// Token completo a partir do registro local.
|
|
30
|
+
export function tokenDe(b) { return `${b.bash_id}.${b.segredo}`; }
|
|
31
|
+
|
|
32
|
+
// Adiciona/atualiza uma bash pelo bash_id. Devolve o estado novo.
|
|
33
|
+
export function upsert(estado, bash) {
|
|
34
|
+
const bs = estado.bashes.filter((x) => x.bash_id !== bash.bash_id);
|
|
35
|
+
bs.push(bash);
|
|
36
|
+
return { ...estado, bashes: bs };
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export function remover(estado, bashId) {
|
|
40
|
+
return { ...estado, bashes: estado.bashes.filter((x) => x.bash_id !== bashId) };
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
// Interpreta o token colado ("bash_id.segredo") e uma url/instance.
|
|
44
|
+
export function bashDeToken(token, url, instance, nome) {
|
|
45
|
+
const t = String(token || '').trim();
|
|
46
|
+
const i = t.indexOf('.');
|
|
47
|
+
if (i <= 0) return null;
|
|
48
|
+
const bash_id = t.slice(0, i);
|
|
49
|
+
const segredo = t.slice(i + 1);
|
|
50
|
+
if (!/^nbx_/.test(bash_id) || !segredo) return null;
|
|
51
|
+
return { bash_id, segredo, url, instance: instance || 'system', nome: nome || bash_id };
|
|
52
|
+
}
|
package/src/worker.js
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
// UM worker por bash: liga, faz poll da fila, executa o comando na maquina,
|
|
2
|
+
// devolve a saida e pinga. Vários workers correm juntos (estilo pm2) — cada um
|
|
3
|
+
// com seu poll, seu ping e sua fila. O worker emite eventos para o console
|
|
4
|
+
// mostrar em tela tudo que passa.
|
|
5
|
+
import os from 'node:os';
|
|
6
|
+
import { spawn } from 'node:child_process';
|
|
7
|
+
import { EventEmitter } from 'node:events';
|
|
8
|
+
import { callPublic, b64 } from './api.js';
|
|
9
|
+
import { tokenDe } from './store.js';
|
|
10
|
+
|
|
11
|
+
const POLL_MS = 5000; // o dono: "olha a cada 5, 10 segundos"
|
|
12
|
+
const PING_MS = 5 * 60000; // "um pingzinho a cada cinco minutos"
|
|
13
|
+
const CMD_TIMEOUT_MS = 10 * 60000;
|
|
14
|
+
const OUT_MAX = 1024 * 1024; // 1 MB de saida por comando
|
|
15
|
+
|
|
16
|
+
function infoMaquina() {
|
|
17
|
+
return { host: os.hostname(), so: `${os.platform()} ${os.release()}`, usuario: os.userInfo().username, ip: '' };
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export class Worker extends EventEmitter {
|
|
21
|
+
constructor(bash, { pollMs = POLL_MS, pingMs = PING_MS, run = realRun, call = null } = {}) {
|
|
22
|
+
super();
|
|
23
|
+
this.bash = bash;
|
|
24
|
+
this.token = tokenDe(bash);
|
|
25
|
+
this.pollMs = pollMs;
|
|
26
|
+
this.pingMs = pingMs;
|
|
27
|
+
this.run = run;
|
|
28
|
+
this._callOverride = call; // testes injetam o protocolo sem rede
|
|
29
|
+
this.estado = 'parado';
|
|
30
|
+
this.rodando = false;
|
|
31
|
+
this._timers = [];
|
|
32
|
+
this.ultimo = { comando: '', exit: null, em: 0 };
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
log(tipo, dados) { this.emit('log', { bash_id: this.bash.bash_id, nome: this.bash.nome, tipo, ...dados }); }
|
|
36
|
+
|
|
37
|
+
call(flow, args) {
|
|
38
|
+
if (this._callOverride) return this._callOverride(flow, args);
|
|
39
|
+
return callPublic(this.bash.url, this.bash.instance, flow, args, 30000);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
async ligar() {
|
|
43
|
+
const r = await this.call('nbx_ag_ligar', [this.token, b64(JSON.stringify(infoMaquina()))]);
|
|
44
|
+
if (!r || r.ok !== true) throw new Error((r && r.erro) || 'nao consegui ligar (token invalido?)');
|
|
45
|
+
this.estado = 'ligada';
|
|
46
|
+
this.log('ligada', {});
|
|
47
|
+
return r;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
async ping() {
|
|
51
|
+
try {
|
|
52
|
+
const r = await this.call('nbx_ag_ping', [this.token, b64('{}')]);
|
|
53
|
+
if (r && r.estado === 'substituida') {
|
|
54
|
+
this.log('substituida', {});
|
|
55
|
+
await this.parar('a bash foi ligada em outra maquina');
|
|
56
|
+
}
|
|
57
|
+
} catch (e) { this.log('erro', { onde: 'ping', erro: String(e.message || e) }); }
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// Uma volta: pega o proximo, executa, conclui. Devolve true se executou algo.
|
|
61
|
+
async passo() {
|
|
62
|
+
let prox;
|
|
63
|
+
try { prox = await this.call('nbx_ag_proximo', [this.token]); }
|
|
64
|
+
catch (e) { this.log('erro', { onde: 'proximo', erro: String(e.message || e) }); return false; }
|
|
65
|
+
if (!prox || prox.ok !== true || prox.tem !== true) return false;
|
|
66
|
+
|
|
67
|
+
this.log('comando', { cmd_id: prox.cmd_id, comando: prox.comando });
|
|
68
|
+
const t0 = Date.now();
|
|
69
|
+
let saida = '', exit = -1;
|
|
70
|
+
try {
|
|
71
|
+
const r = await this.run(prox.comando, CMD_TIMEOUT_MS);
|
|
72
|
+
saida = String(r.saida || '').slice(0, OUT_MAX);
|
|
73
|
+
exit = Number.isFinite(r.exit) ? r.exit : -1;
|
|
74
|
+
} catch (e) {
|
|
75
|
+
saida = 'FALHA AO EXECUTAR: ' + String(e.message || e);
|
|
76
|
+
exit = -1;
|
|
77
|
+
}
|
|
78
|
+
const dur = Date.now() - t0;
|
|
79
|
+
this.ultimo = { comando: prox.comando, exit, em: Date.now() };
|
|
80
|
+
this.log('saida', { cmd_id: prox.cmd_id, exit, duracao_ms: dur, saida });
|
|
81
|
+
try {
|
|
82
|
+
await this.call('nbx_ag_concluir', [this.token, prox.cmd_id, prox.seq, b64(saida), String(exit), String(dur)]);
|
|
83
|
+
} catch (e) { this.log('erro', { onde: 'concluir', erro: String(e.message || e) }); }
|
|
84
|
+
return true;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
async _loop() {
|
|
88
|
+
if (this.rodando) return;
|
|
89
|
+
this.rodando = true;
|
|
90
|
+
try { while (await this.passo()) { /* esvazia a fila de uma vez */ } }
|
|
91
|
+
finally { this.rodando = false; }
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
async iniciar() {
|
|
95
|
+
await this.ligar();
|
|
96
|
+
this._loop();
|
|
97
|
+
this._timers.push(setInterval(() => this._loop(), this.pollMs));
|
|
98
|
+
this._timers.push(setInterval(() => this.ping(), this.pingMs));
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
async parar(motivo) {
|
|
102
|
+
for (const t of this._timers) clearInterval(t);
|
|
103
|
+
this._timers = [];
|
|
104
|
+
this.estado = 'parado';
|
|
105
|
+
this.log('parado', { motivo: motivo || '' });
|
|
106
|
+
try { await this.call('nbx_ag_desligar', [this.token]); } catch { /* melhor esforco */ }
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
// Execução real na máquina: /bin/sh -c, com a permissão do usuário que instalou.
|
|
111
|
+
export function realRun(comando, timeoutMs) {
|
|
112
|
+
return new Promise((resolve) => {
|
|
113
|
+
const child = spawn('/bin/sh', ['-c', comando], { cwd: os.homedir(), env: process.env });
|
|
114
|
+
let out = '', done = false;
|
|
115
|
+
const finish = (exit) => { if (!done) { done = true; resolve({ saida: out, exit }); } };
|
|
116
|
+
const to = setTimeout(() => { try { child.kill('SIGKILL'); } catch {} finish(124); }, timeoutMs);
|
|
117
|
+
child.stdout.on('data', (d) => { out += d; });
|
|
118
|
+
child.stderr.on('data', (d) => { out += d; });
|
|
119
|
+
child.on('close', (code) => { clearTimeout(to); finish(code == null ? -1 : code); });
|
|
120
|
+
child.on('error', (e) => { clearTimeout(to); out += String(e.message || e); finish(127); });
|
|
121
|
+
});
|
|
122
|
+
}
|
package/LICENSE
DELETED
|
@@ -1,21 +0,0 @@
|
|
|
1
|
-
MIT License
|
|
2
|
-
|
|
3
|
-
Copyright (c) 2026 Pisani da Arq
|
|
4
|
-
|
|
5
|
-
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
-
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
-
in the Software without restriction, including without limitation the rights
|
|
8
|
-
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
-
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
-
furnished to do so, subject to the following conditions:
|
|
11
|
-
|
|
12
|
-
The above copyright notice and this permission notice shall be included in all
|
|
13
|
-
copies or substantial portions of the Software.
|
|
14
|
-
|
|
15
|
-
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
-
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
-
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
-
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
-
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
-
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
-
SOFTWARE.
|
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
|
-
}
|