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/src/worker.js CHANGED
@@ -2,24 +2,217 @@
2
2
  // devolve a saida e pinga. Vários workers correm juntos (estilo pm2) — cada um
3
3
  // com seu poll, seu ping e sua fila. O worker emite eventos para o console
4
4
  // mostrar em tela tudo que passa.
5
+ //
6
+ // 0.4.0 (AGENTES E-nbash, 17/11/2026): informa capacidades e host ao ligar; se o
7
+ // servidor anuncia protocolo 2, devolve o resultado no envelope "nbx2:" com
8
+ // host, inicio, fim, sha256 do comando e o USO do CLI de codigo (Claude Code /
9
+ // Codex com saida JSON); roda cada comando na pasta do agente/projeto
10
+ // (~/neuroniun-projetos/<agente_id>/<projeto>, cwd_rel do item) com timeout_s e
11
+ // NBX_CMD_ID / NBX_USO_ARQ / NBX_IA_* no ambiente. Servidor antigo: protocolo 1,
12
+ // igual ao 0.3.0.
13
+ //
14
+ // 0.5.0 (onda 2 dos Agentes, NBX-2/4): com o servidor novo (flows/58_2) pega um
15
+ // LOTE por nbx_ag_proximo2 (vagas = paralelo da bash - rodando), roda varios ao
16
+ // mesmo tempo (trilhas diferentes), cancela o que o servidor mandar, roda a
17
+ // `verifica` (pos-condicao), redige a saida (valor do segredo em todas as formas
18
+ // + padroes, agent/src/redigir.js) e devolve por nbx_ag_concluir2. Estado em
19
+ // disco (~/.neuroniun/exec/<cmd_id>.json) para reenviar o resultado e declarar
20
+ // "interrompido" ao religar. Segredo so pelo ticket (NBX_TICKET_URL; sem ele,
21
+ // recusa sem rodar). Windows: sh do Git for Windows ou PowerShell (src/shell.js).
22
+ // Servidor sem os flows novos: cai no caminho do 0.4.0 sozinho.
23
+ import fs from 'node:fs';
5
24
  import os from 'node:os';
6
- import { spawn } from 'node:child_process';
25
+ import path from 'node:path';
26
+ import { spawn, spawnSync } from 'node:child_process';
7
27
  import { EventEmitter } from 'node:events';
8
28
  import { callPublic, b64 } from './api.js';
9
29
  import { tokenDe } from './store.js';
30
+ import { VERSAO, envelope, montaResultado, pastaDeTrabalho, raizProjetos, sha256 } from './recibo.js';
31
+ import { usoDe } from './uso.js';
32
+ import { redigir } from './redigir.js';
33
+ import { shellDe } from './shell.js';
34
+ import { EstadoEmDisco } from './estado.js';
35
+ import { resgatar, SemTicket } from './ticket.js';
36
+ import { disponiveis } from './executores.js';
37
+ import { garantirAjudante } from './ia.js';
10
38
 
11
39
  const POLL_MS = 5000; // o dono: "olha a cada 5, 10 segundos"
12
40
  const PING_MS = 5 * 60000; // "um pingzinho a cada cinco minutos"
41
+ // 0.6.0 (SPEC-AGENTE-LOCAL-EXECUTORES par. 5.2): enquanto um comando roda, batimento a
42
+ // cada 60 s pelo nbx_ag_ping2 (o servidor declara abandonado com 30 min sem sinal);
43
+ // codigo/agente ate 24 h. Nenhuma chamada passa de ~60 s (Cloudflare corta em ~100 s).
44
+ const BATIDA_MS = 60000;
45
+ const TETO_S = 86400;
13
46
  const CMD_TIMEOUT_MS = 10 * 60000;
14
47
  const OUT_MAX = 1024 * 1024; // 1 MB de saida por comando
15
48
 
16
- function infoMaquina() {
17
- return { host: os.hostname(), so: `${os.platform()} ${os.release()}`, usuario: os.userInfo().username, ip: '' };
49
+ function temBinario(nome) {
50
+ try {
51
+ const r = spawnSync(process.platform === 'win32' ? 'where' : 'which', [nome], { timeout: 3000, stdio: 'ignore' });
52
+ return r.status === 0;
53
+ } catch { return false; }
54
+ }
55
+
56
+ // O que a maquina tem (gravado pelo servidor em capacidades; nunca digitado).
57
+ // CLI presente sem conferir login fica "" (a acao diag confere).
58
+ // 0.6.0: grok (tambem em ~/.grok/bin), antigravity e gemini (este so com a chave
59
+ // propria declarada em NBX_ENV_PASSAR: sem ela, "sem_chave"); `ia: true` diz ao
60
+ // servidor que o comando pode chamar "$NBX_IA" (executores plugaveis).
61
+ export function capacidadesDaMaquina(tem = temBinario, { env = null, casa = os.homedir(), existe } = {}) {
62
+ const cli = { claude: tem('claude') ? '' : 'ausente', codex: tem('codex') ? '' : 'ausente' };
63
+ const d = disponiveis(env || envMinimo(), { casa, existe });
64
+ for (const e of ['grok', 'antigravity', 'gemini', 'qwen']) cli[e] = d[e].estado === 'ok' ? '' : d[e].estado;
65
+ return {
66
+ so: os.platform(), arch: os.arch(), shell: shellDe().nome, runner: VERSAO,
67
+ git: tem('git'), node: true, ia: true, cli,
68
+ };
69
+ }
70
+
71
+ function infoMaquina(capacidades) {
72
+ const i = { host: os.hostname(), so: `${os.platform()} ${os.release()}`, usuario: os.userInfo().username, ip: '' };
73
+ if (capacidades) i.capacidades = capacidades;
74
+ return i;
75
+ }
76
+
77
+ // env do item: so NBX_* com nome em maiusculas e valor texto curto
78
+ function envDoItem(item) {
79
+ const out = {};
80
+ const e = item && item.env && typeof item.env === 'object' ? item.env : {};
81
+ for (const [k, v] of Object.entries(e)) {
82
+ if (/^NBX_[A-Z0-9_]{1,36}$/.test(k) && (typeof v === 'string' || typeof v === 'number') && String(v).length <= 200 && String(v) !== '') out[k] = String(v);
83
+ }
84
+ return out;
85
+ }
86
+
87
+ // SEGURANCA 3 (revisao da onda 1): o comando pode ter sido escrito por IA, entao
88
+ // ele NAO herda o ambiente inteiro do runner (chaves de API, tokens, URL do no).
89
+ // Passa so o minimo para o shell e os CLIs de codigo acharem binario, casa,
90
+ // idioma e configuracao; o resto e declarado pelo dono da maquina em
91
+ // NBX_ENV_PASSAR (nomes separados por virgula, ex.: JAVA_HOME,ANDROID_HOME).
92
+ // Credencial no ambiente (ANTHROPIC_API_KEY etc.) so passa se ele declarar.
93
+ export const ENV_MINIMO = [
94
+ 'PATH', 'HOME', 'USER', 'LOGNAME', 'SHELL', 'LANG', 'LC_ALL', 'LC_CTYPE', 'TERM', 'TZ', 'TMPDIR',
95
+ // configuracao dos CLIs de codigo e das ferramentas de build (nunca segredo)
96
+ 'XDG_CONFIG_HOME', 'XDG_CACHE_HOME', 'XDG_DATA_HOME', 'CLAUDE_CONFIG_DIR', 'CODEX_HOME',
97
+ // Windows
98
+ 'SYSTEMROOT', 'SystemRoot', 'COMSPEC', 'ComSpec', 'PATHEXT', 'USERPROFILE', 'APPDATA', 'LOCALAPPDATA', 'TEMP', 'TMP', 'HOMEDRIVE', 'HOMEPATH',
99
+ ];
100
+
101
+ export function envMinimo(base = process.env) {
102
+ const out = {};
103
+ const extra = String(base.NBX_ENV_PASSAR || '').split(',').map((x) => x.trim()).filter((x) => /^[A-Za-z_][A-Za-z0-9_]{0,63}$/.test(x));
104
+ for (const k of ENV_MINIMO.concat(extra)) {
105
+ if (typeof base[k] === 'string' && base[k] !== '') out[k] = base[k];
106
+ }
107
+ return out;
108
+ }
109
+
110
+ // SEGURANCA (revisao da volta 3): MODO AGENTE = item com cwd_rel (o laco de
111
+ // codigo do agente com bash, so liberado em bash marcada confiavel). Esse modo
112
+ // RODA CODIGO ESCRITO POR IA nesta maquina. O comando nunca recebe o HOME real:
113
+ // HOME (e USERPROFILE) viram a casa vazia do agente, <raiz>/.casa/<agente_id>
114
+ // (modo 700). A casa real so vai em NBX_CLI_HOME, que o script fixo do servidor
115
+ // usa apenas para chamar o CLI de codigo (o login dele) e apaga antes de
116
+ // compilar/testar (HOME = <pasta>/.neuroniun/home). Todo item recebe
117
+ // NBX_PROJETOS (a raiz das pastas), para todos os passos de um run acharem a
118
+ // mesma pasta com qualquer HOME. Isso NAO isola a maquina: o mesmo usuario do
119
+ // sistema le qualquer arquivo por caminho absoluto. Recomendado: rodar o
120
+ // runner com um usuario do sistema dedicado ou num conteiner.
121
+ export const AVISO_MODO_AGENTE = 'modo agente: este comando roda codigo escrito por IA nesta maquina; use um usuario do sistema dedicado ou um conteiner';
122
+
123
+ export function casaDoAgente(raiz, cwdRel) {
124
+ const ag = String(cwdRel || '').split('/')[0].replace(/[^A-Za-z0-9._-]/g, '') || 'agente';
125
+ return path.join(raiz, '.casa', ag === '.' || ag === '..' ? 'agente' : ag);
126
+ }
127
+
128
+ export function envDoComando(base, item, { raiz, home, usoArq, cid, ia = '', execArq = '' } = {}) {
129
+ const env = { ...envMinimo(base), ...envDoItem(item), NBX_CMD_ID: cid, NBX_USO_ARQ: usoArq, NBX_PROJETOS: raiz };
130
+ delete env.NBX_EXEC_ARQ;
131
+ if (execArq) env.NBX_EXEC_ARQ = execArq;
132
+ // 0.6.0: o ajudante dos executores (src/ia.js); so o runner define (o item nao troca)
133
+ delete env.NBX_IA;
134
+ if (ia) env.NBX_IA = ia;
135
+ const agente = !!(item && item.cwd_rel);
136
+ delete env.NBX_CLI_HOME; // so o runner define, e so no modo agente
137
+ if (agente) {
138
+ const casa = casaDoAgente(raiz, item.cwd_rel);
139
+ env.NBX_CLI_HOME = home;
140
+ env.HOME = casa;
141
+ if (env.USERPROFILE) env.USERPROFILE = casa;
142
+ }
143
+ return { env, agente };
144
+ }
145
+
146
+ export function timeoutDoItem(item) {
147
+ const t = Number(item && item.timeout_s);
148
+ return Number.isFinite(t) && t >= 10 ? Math.min(t, TETO_S) * 1000 : CMD_TIMEOUT_MS;
149
+ }
150
+
151
+ /** Mata o comando E os filhos dele (o CLI de codigo roda em sub-processos): no
152
+ * POSIX o comando nasce lider de um grupo (spawn detached) e o sinal vai ao grupo. */
153
+ export function matar(child, sinal = 'SIGTERM') {
154
+ if (!child) return;
155
+ if (process.platform !== 'win32' && child.pid) {
156
+ try { process.kill(-child.pid, sinal); return; } catch { /* grupo ja saiu: tenta o processo */ }
157
+ }
158
+ try { child.kill(sinal); } catch { /* ja saiu */ }
159
+ }
160
+
161
+ // Os comandos vivos (grupos proprios): se o runner sai (Ctrl-C, servico parado,
162
+ // erro), leva os grupos junto, como o terminal fazia quando eram do mesmo grupo.
163
+ const VIVOS = new Set();
164
+ let guardaLigada = false;
165
+ function guardarSaida() {
166
+ if (guardaLigada) return;
167
+ guardaLigada = true;
168
+ const mataTodos = () => { for (const c of VIVOS) matar(c, 'SIGTERM'); };
169
+ process.on('exit', mataTodos);
170
+ for (const [sig, n] of [['SIGINT', 2], ['SIGTERM', 15], ['SIGHUP', 1]]) {
171
+ process.once(sig, () => { mataTodos(); process.exit(128 + n); });
172
+ }
173
+ }
174
+
175
+ /** O estado do executor do comando ($NBX_EXEC_ARQ, gravado pelo ajudante): "rodando" no
176
+ * fim = o runner matou no timeout (travou); cancelado = sem estado (nao e erro do executor). */
177
+ export function estadoDoExecutor(arq, exit, cancelado, valores = []) {
178
+ let e = null;
179
+ try { e = JSON.parse(fs.readFileSync(arq, 'utf8')); fs.rmSync(arq, { force: true }); } catch { return null; }
180
+ if (!e || typeof e !== 'object') return null;
181
+ if (e.estado === 'rodando') {
182
+ if (cancelado) return null;
183
+ e = { ...e, estado: 'erro', classe: exit === 124 ? 'travou' : 'erro', offline: exit === 124, detalhe: exit === 124 ? 'o comando passou do tempo e foi parado' : 'o comando parou no meio da chamada' };
184
+ }
185
+ return { nome: String(e.nome || ''), estado: e.estado === 'ok' ? 'ok' : 'erro', classe: String(e.classe || ''), offline: e.offline === true, pedido_ausente: String(e.pedido_ausente || ''), detalhe: redigir(String(e.detalhe || ''), valores).slice(0, 300) };
186
+ }
187
+
188
+ /** A ultima linha com texto da saida parcial (o andamento do batimento), redigida. */
189
+ export function ultimaLinha(texto, valores = []) {
190
+ const ls = String(texto || '').slice(-4000).split(/\r?\n/).map((l) => l.trim()).filter(Boolean);
191
+ return ls.length ? redigir(ls[ls.length - 1], valores).slice(0, 300) : '';
18
192
  }
19
193
 
20
194
  export class Worker extends EventEmitter {
21
- constructor(bash, { pollMs = POLL_MS, pingMs = PING_MS, run = realRun, call = null } = {}) {
195
+ constructor(bash, { pollMs = POLL_MS, pingMs = PING_MS, run = realRun, call = null,
196
+ capacidades = null, raiz = null, home = null, execDir = null, agora = Date.now, envBase = null,
197
+ resgate = resgatar, v2 = null, ajudante = undefined, batidaMs = BATIDA_MS } = {}) {
22
198
  super();
199
+ this.batidaMs = batidaMs;
200
+ this._ajudante = ajudante; // undefined = criar em ~/.neuroniun/bin; '' = sem (testes)
201
+ this.v2 = v2; // null = descobrir; false = servidor sem flows/58_2; true = protocolo 2 completo
202
+ this.v2Desde = 0;
203
+ this.rodando2 = new Map(); // cmd_id -> {child, cancelado, promessa}
204
+ this.paralelo = 1;
205
+ this.envFixos = {};
206
+ this.executorBash = ''; // o executor escolhido para esta bash (A.1 Modelos); '' = automatico
207
+ this.resgate = resgate;
208
+ this.envBase = envBase || process.env; // testes injetam o ambiente do runner
209
+ this.protocolo = 1;
210
+ this._capacidades = capacidades; // testes injetam; senao detecta ao ligar
211
+ this.raiz = raiz || raizProjetos();
212
+ this.home = home || os.homedir();
213
+ this.execDir = execDir || path.join(os.homedir(), '.neuroniun', 'exec');
214
+ this.estadoDisco = new EstadoEmDisco(this.execDir);
215
+ this.agora = agora;
23
216
  this.bash = bash;
24
217
  this.token = tokenDe(bash);
25
218
  this.pollMs = pollMs;
@@ -32,6 +225,14 @@ export class Worker extends EventEmitter {
32
225
  this.ultimo = { comando: '', exit: null, em: 0 };
33
226
  }
34
227
 
228
+ /** O caminho do ajudante $NBX_IA (criado uma vez; falhou = comando segue sem ele). */
229
+ ajudante() {
230
+ if (this._ajudante !== undefined) return this._ajudante;
231
+ try { this._ajudante = process.platform === 'win32' ? '' : garantirAjudante(path.join(this.home, '.neuroniun', 'bin')); }
232
+ catch { this._ajudante = ''; }
233
+ return this._ajudante;
234
+ }
235
+
35
236
  log(tipo, dados) { this.emit('log', { bash_id: this.bash.bash_id, nome: this.bash.nome, tipo, ...dados }); }
36
237
 
37
238
  call(flow, args) {
@@ -40,16 +241,22 @@ export class Worker extends EventEmitter {
40
241
  }
41
242
 
42
243
  async ligar() {
43
- const r = await this.call('nbx_ag_ligar', [this.token, b64(JSON.stringify(infoMaquina()))]);
244
+ const cap = this._capacidades || capacidadesDaMaquina();
245
+ const r = await this.call('nbx_ag_ligar', [this.token, b64(JSON.stringify(infoMaquina(cap)))]);
44
246
  if (!r || r.ok !== true) throw new Error((r && r.erro) || 'nao consegui ligar (token invalido?)');
45
247
  this.estado = 'ligada';
46
- this.log('ligada', {});
248
+ this.protocolo = Number(r.protocolo) >= 2 ? 2 : 1;
249
+ this.log('ligada', { protocolo: this.protocolo });
47
250
  return r;
48
251
  }
49
252
 
50
253
  async ping() {
51
254
  try {
52
- const r = await this.call('nbx_ag_ping', [this.token, b64('{}')]);
255
+ let r = null;
256
+ if (this.v2 !== false) {
257
+ try { r = await this.call('nbx_ag_ping2', [this.token, b64('{}')]); } catch (e) { if (semFlow(e)) r = null; else throw e; }
258
+ }
259
+ if (!r || typeof r !== 'object') r = await this.call('nbx_ag_ping', [this.token, b64('{}')]);
53
260
  if (r && r.estado === 'substituida') {
54
261
  this.log('substituida', {});
55
262
  await this.parar('a bash foi ligada em outra maquina');
@@ -64,22 +271,43 @@ export class Worker extends EventEmitter {
64
271
  catch (e) { this.log('erro', { onde: 'proximo', erro: String(e.message || e) }); return false; }
65
272
  if (!prox || prox.ok !== true || prox.tem !== true) return false;
66
273
 
67
- this.log('comando', { cmd_id: prox.cmd_id, comando: prox.comando });
68
- const t0 = Date.now();
274
+ this.log('comando', { cmd_id: prox.cmd_id, comando: prox.comando, cwd_rel: prox.cwd_rel || '' });
275
+ const comando = String(prox.comando == null ? '' : prox.comando);
276
+ const cid = String(prox.cmd_id || 'x').replace(/[^A-Za-z0-9_]/g, '').slice(0, 60) || 'x';
277
+ const usoArq = path.join(this.execDir, cid + '.uso.json');
278
+ const inicio = this.agora();
69
279
  let saida = '', exit = -1;
70
280
  try {
71
- const r = await this.run(prox.comando, CMD_TIMEOUT_MS);
281
+ const pasta = pastaDeTrabalho(prox.cwd_rel || '', { raiz: this.raiz, home: this.home });
282
+ if (!pasta.ok) throw new Error(pasta.erro);
283
+ try { fs.mkdirSync(this.execDir, { recursive: true }); fs.rmSync(usoArq, { force: true }); } catch { /* sem disco: segue sem arquivo de uso */ }
284
+ const { env, agente } = envDoComando(this.envBase, prox, { raiz: this.raiz, home: this.home, usoArq, cid, ia: this.ajudante() });
285
+ if (agente) {
286
+ try { fs.mkdirSync(env.HOME, { recursive: true, mode: 0o700 }); } catch { /* sem disco (teste) */ }
287
+ this.log('aviso', { cmd_id: prox.cmd_id, texto: AVISO_MODO_AGENTE });
288
+ }
289
+ const r = await this.run(comando, timeoutDoItem(prox), { cwd: pasta.cwd, env });
72
290
  saida = String(r.saida || '').slice(0, OUT_MAX);
73
291
  exit = Number.isFinite(r.exit) ? r.exit : -1;
74
292
  } catch (e) {
75
293
  saida = 'FALHA AO EXECUTAR: ' + String(e.message || e);
76
294
  exit = -1;
77
295
  }
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 });
296
+ const fim = this.agora();
297
+ const dur = Math.max(0, fim - inicio);
298
+ let arq = '';
299
+ try { arq = fs.readFileSync(usoArq, 'utf8'); fs.rmSync(usoArq, { force: true }); } catch { /* sem gancho */ }
300
+ const uso = usoDe(comando, saida, arq);
301
+ saida = redigir(saida); // 0.5.0: padroes de credencial (o item v1 nao traz segredo)
302
+ this.ultimo = { comando, exit, em: fim };
303
+ this.log('saida', { cmd_id: prox.cmd_id, exit, duracao_ms: dur, saida, uso });
304
+ let saida64 = b64(saida);
305
+ if (this.protocolo >= 2) {
306
+ const res = montaResultado({ comando, saida, exit, inicio, fim, host: os.hostname(), so: `${os.platform()} ${os.release()}`, uso });
307
+ saida64 = b64(envelope(res));
308
+ }
81
309
  try {
82
- await this.call('nbx_ag_concluir', [this.token, prox.cmd_id, prox.seq, b64(saida), String(exit), String(dur)]);
310
+ await this.call('nbx_ag_concluir', [this.token, prox.cmd_id, prox.seq, saida64, String(exit), String(dur)]);
83
311
  } catch (e) { this.log('erro', { onde: 'concluir', erro: String(e.message || e) }); }
84
312
  return true;
85
313
  }
@@ -87,8 +315,180 @@ export class Worker extends EventEmitter {
87
315
  async _loop() {
88
316
  if (this.rodando) return;
89
317
  this.rodando = true;
90
- try { while (await this.passo()) { /* esvazia a fila de uma vez */ } }
91
- finally { this.rodando = false; }
318
+ try {
319
+ // servidor sem o protocolo 2: tenta de novo a cada 10 min (pode ter sido publicado)
320
+ if (this.v2 === false && this.agora() - this.v2Desde > 600000) this.v2 = null;
321
+ if (this.v2 !== false) {
322
+ const n = await this.passo2();
323
+ if (n >= 0) return;
324
+ }
325
+ while (await this.passo()) { /* esvazia a fila de uma vez */ }
326
+ } finally { this.rodando = false; }
327
+ }
328
+
329
+ // ======================= PROTOCOLO 2 (0.5.0) =======================
330
+
331
+ /** Uma volta do protocolo 2: pede ate `vagas` itens e dispara cada um. -1 = servidor sem 58_2. */
332
+ async passo2() {
333
+ const vagas = Math.max(0, this.paralelo - this.rodando2.size);
334
+ let r;
335
+ try { r = await this.call('nbx_ag_proximo2', [this.token, String(vagas)]); }
336
+ catch (e) {
337
+ if (semFlow(e)) { this.v2 = false; this.v2Desde = this.agora(); return -1; }
338
+ this.log('erro', { onde: 'proximo2', erro: String(e.message || e) });
339
+ return 0;
340
+ }
341
+ if (!r || typeof r !== 'object' || (r.ok === true && r.protocolo !== 2)) { this.v2 = false; this.v2Desde = this.agora(); return -1; }
342
+ if (r.ok !== true) { this.log('erro', { onde: 'proximo2', erro: String(r.erro || 'recusado') }); return 0; }
343
+ if (this.v2 !== true) { this.v2 = true; await this.reenviarPendentes(); }
344
+ const b = r.bash && typeof r.bash === 'object' ? r.bash : {};
345
+ const par = Number(b.paralelo);
346
+ this.paralelo = Number.isInteger(par) && par >= 1 && par <= 4 ? par : 1;
347
+ this.envFixos = envFixosValidos(b.env_fixos);
348
+ this.executorBash = executorDaBash(b.executor);
349
+ for (const cid of Array.isArray(r.cancelar) ? r.cancelar : []) this.cancelar(String(cid));
350
+ const itens = Array.isArray(r.itens) ? r.itens : [];
351
+ for (const it of itens) {
352
+ const cid = idDoComando(it.cmd_id);
353
+ if (!cid || this.rodando2.has(cid)) continue;
354
+ const reg = { child: null, cancelado: false, promessa: null };
355
+ this.rodando2.set(cid, reg);
356
+ reg.promessa = this.executar2(it, reg).finally(() => this.rodando2.delete(cid));
357
+ }
358
+ return itens.length;
359
+ }
360
+
361
+ /** O servidor mandou cancelar: mata o processo e os filhos (TERM, depois KILL). */
362
+ cancelar(cid) {
363
+ const reg = this.rodando2.get(idDoComando(cid));
364
+ if (!reg || reg.cancelado) return false;
365
+ reg.cancelado = true;
366
+ this.log('cancelado', { cmd_id: cid });
367
+ if (reg.child) {
368
+ matar(reg.child, 'SIGTERM');
369
+ const c = reg.child;
370
+ setTimeout(() => matar(c, 'SIGKILL'), 5000).unref?.();
371
+ }
372
+ return true;
373
+ }
374
+
375
+ /** Batimento (0.6.0): a cada 60 s, so com comando rodando no protocolo 2. A
376
+ * resposta traz os cancelamentos (chegam em ate 60 s, sem esperar o lote). */
377
+ async batida() {
378
+ if (this.v2 !== true || this.rodando2.size === 0) return null;
379
+ const batimentos = [...this.rodando2.entries()].slice(0, 4).map(([cid, reg]) => ({
380
+ cmd_id: cid, fase: reg.cancelado ? 'cancelando' : 'rodando', inicio: reg.inicio || null,
381
+ evento: reg.parcial && typeof reg.parcial.ler === 'function' ? ultimaLinha(reg.parcial.ler(), reg.valores || []) : '',
382
+ }));
383
+ try {
384
+ const r = await this.call('nbx_ag_ping2', [this.token, b64(JSON.stringify({ batimentos }))]);
385
+ for (const cid of Array.isArray(r && r.cancelar) ? r.cancelar : []) this.cancelar(String(cid));
386
+ this.log('batimento', { comandos: batimentos.length });
387
+ return r;
388
+ } catch (e) { this.log('erro', { onde: 'batimento', erro: String(e.message || e) }); return null; }
389
+ }
390
+
391
+ /** Espera os comandos em andamento (testes e parada limpa). */
392
+ async aguardar() { await Promise.all([...this.rodando2.values()].map((r) => r.promessa).filter(Boolean)); }
393
+
394
+ /** Executa um item v2 e devolve por nbx_ag_concluir2. Nunca lanca. */
395
+ async executar2(it, reg = { cancelado: false }) {
396
+ const comando = String(it.comando == null ? '' : it.comando);
397
+ const cid = idDoComando(it.cmd_id) || 'x';
398
+ const usoArq = path.join(this.execDir, cid + '.uso.json');
399
+ const execArq = path.join(this.execDir, cid + '.exec.json');
400
+ const segDir = path.join(this.execDir, cid + '.seg');
401
+ const inicio = this.agora();
402
+ this.estadoDisco.salvar({ cmd_id: cid, seq: String(it.seq || ''), bash_id: this.bash.bash_id, inicio, estado: 'rodando', sha_runner: sha256(comando) });
403
+ this.log('comando', { cmd_id: cid, comando: redigir(comando), cwd_rel: it.cwd_rel || '' });
404
+ let saida = '', exit = -1, valores = [], verificacao = { feita: false, exit_code: null, trecho: '' };
405
+ try {
406
+ const pasta = pastaDeTrabalho(it.cwd_rel || '', { raiz: this.raiz, home: this.home });
407
+ if (!pasta.ok) throw new Error(pasta.erro);
408
+ try { fs.mkdirSync(this.execDir, { recursive: true, mode: 0o700 }); fs.rmSync(usoArq, { force: true }); } catch { /* sem disco */ }
409
+ try { fs.rmSync(execArq, { force: true }); } catch { /* sem disco */ }
410
+ const { env, agente } = envDoComando(this.envBase, it, { raiz: this.raiz, home: this.home, usoArq, cid, ia: this.ajudante(), execArq });
411
+ for (const [k, v] of Object.entries(this.envFixos)) if (!(k in env)) env[k] = v;
412
+ delete env.NBX_EXECUTOR_BASH; // so o runner define, pelo que o servidor mandou da bash
413
+ if (this.executorBash) env.NBX_EXECUTOR_BASH = this.executorBash;
414
+ // SEGREDO: so pelo ticket; sem endpoint, recusa sem rodar
415
+ let seg = [];
416
+ try { seg = await this.resgate(it, { token: this.token, env: this.envBase }); }
417
+ catch (e) {
418
+ const mot = e instanceof SemTicket ? e.motivo : 'ticket_falhou';
419
+ throw Object.assign(new Error('RECUSADO: ' + mot + ' (o comando precisa de segredo e nao rodou)'), { recusa: true, exit: -5 });
420
+ }
421
+ for (const s of seg) {
422
+ valores.push(...s.valores.map((v) => ({ nome: s.nome, valor: v })));
423
+ for (const [nome, valor] of Object.entries(s.env)) if (nomeDeSegredoOk(nome)) env[nome] = valor;
424
+ for (const [nome, valor] of Object.entries(s.arquivos)) {
425
+ if (!nomeDeSegredoOk(nome)) continue;
426
+ fs.mkdirSync(segDir, { recursive: true, mode: 0o700 });
427
+ const f = path.join(segDir, nome.replace(/[^A-Za-z0-9_]/g, '_'));
428
+ fs.writeFileSync(f, valor.endsWith('\n') ? valor : valor + '\n', { mode: 0o600 });
429
+ env[nome] = f;
430
+ }
431
+ }
432
+ if (it.git === true) prepararGit(env, segDir);
433
+ if (agente) {
434
+ try { fs.mkdirSync(env.HOME, { recursive: true, mode: 0o700 }); } catch { /* sem disco (teste) */ }
435
+ this.log('aviso', { cmd_id: cid, texto: AVISO_MODO_AGENTE });
436
+ }
437
+ const shell = shellDe({ env: this.envBase });
438
+ reg.inicio = inicio; reg.valores = valores; reg.parcial = {};
439
+ const r = await this.run(comando, timeoutDoItem(it), { cwd: pasta.cwd, env, shell, parcial: reg.parcial, aoFilho: (c) => { reg.child = c; if (reg.cancelado) matar(c, 'SIGTERM'); } });
440
+ saida = String(r.saida || '').slice(0, OUT_MAX);
441
+ exit = Number.isFinite(r.exit) ? r.exit : -1;
442
+ const vf = it.verifica && typeof it.verifica === 'object' && typeof it.verifica.comando === 'string' ? it.verifica : null;
443
+ if (vf && !reg.cancelado) {
444
+ const v = await this.run(vf.comando.slice(0, 2000), 60000, { cwd: pasta.cwd, env, shell });
445
+ verificacao = { feita: true, exit_code: Number.isFinite(v.exit) ? v.exit : -1, trecho: String(v.saida || '').slice(-2000) };
446
+ }
447
+ } catch (e) {
448
+ saida = e && e.recusa ? String(e.message) : 'FALHA AO EXECUTAR: ' + String((e && e.message) || e);
449
+ exit = e && e.recusa ? e.exit : -1;
450
+ } finally {
451
+ try { fs.rmSync(segDir, { recursive: true, force: true }); } catch { /* ja foi */ }
452
+ }
453
+ const fim = this.agora();
454
+ let arq = '';
455
+ try { arq = fs.readFileSync(usoArq, 'utf8'); fs.rmSync(usoArq, { force: true }); } catch { /* sem gancho */ }
456
+ const uso = usoDe(comando, saida, arq);
457
+ const executor = estadoDoExecutor(execArq, exit, reg.cancelado === true, valores);
458
+ const red = redigir(saida, valores);
459
+ verificacao.trecho = redigir(verificacao.trecho, valores);
460
+ const res = { ...montaResultado({ comando, saida: red, exit, inicio, fim, host: os.hostname(), so: `${os.platform()} ${os.release()}`, uso }), cancelado: reg.cancelado === true, verificacao, ...(executor ? { executor } : {}) };
461
+ valores = [];
462
+ this.ultimo = { comando, exit, em: fim };
463
+ this.log('saida', { cmd_id: cid, exit, duracao_ms: res.duracao_ms, saida: red, uso, verificacao });
464
+ this.estadoDisco.salvar({ cmd_id: cid, seq: String(it.seq || ''), bash_id: this.bash.bash_id, inicio, estado: 'pronto', resultado: res });
465
+ await this.enviar2(cid, String(it.seq || ''), res);
466
+ }
467
+
468
+ /** Manda o resultado; so apaga o estado em disco quando o servidor gravou. */
469
+ async enviar2(cid, seq, res) {
470
+ try {
471
+ const r = await this.call('nbx_ag_concluir2', [this.token, cid, seq, b64(JSON.stringify(res))]);
472
+ if (r && r.ok === true) { this.estadoDisco.apagar(cid); return true; }
473
+ this.log('erro', { onde: 'concluir2', erro: String((r && r.erro) || 'recusado') });
474
+ if (r && (r.erro === 'resultado_invalido')) this.estadoDisco.apagar(cid);
475
+ } catch (e) { this.log('erro', { onde: 'concluir2', erro: String(e.message || e) }); }
476
+ return false;
477
+ }
478
+
479
+ /** Ao (re)ligar: reenvia resultados que nao chegaram e declara interrompido o que morreu no meio. */
480
+ async reenviarPendentes() {
481
+ for (const p of this.estadoDisco.pendentes(this.bash.bash_id)) {
482
+ if (this.rodando2.has(p.cmd_id)) continue;
483
+ let res = p.resultado;
484
+ if (p.estado === 'rodando' || !res) {
485
+ const fim = this.agora();
486
+ res = { saida: '(interrompido: o runner parou no meio do comando)', exit_code: -2, duracao_ms: Math.max(0, fim - Number(p.inicio || fim)), inicio: Number(p.inicio || fim), fim, host: os.hostname(), so: `${os.platform()} ${os.release()}`, runner: VERSAO, sha_runner: p.sha_runner || '', interrompido: true, cancelado: false, verificacao: { feita: false, exit_code: null, trecho: '' }, uso: null };
487
+ this.estadoDisco.salvar({ ...p, estado: 'pronto', resultado: res });
488
+ }
489
+ this.log('reenvio', { cmd_id: p.cmd_id });
490
+ await this.enviar2(p.cmd_id, String(p.seq || ''), res);
491
+ }
92
492
  }
93
493
 
94
494
  async iniciar() {
@@ -96,9 +496,11 @@ export class Worker extends EventEmitter {
96
496
  this._loop();
97
497
  this._timers.push(setInterval(() => this._loop(), this.pollMs));
98
498
  this._timers.push(setInterval(() => this.ping(), this.pingMs));
499
+ this._timers.push(setInterval(() => this.batida(), this.batidaMs));
99
500
  }
100
501
 
101
502
  async parar(motivo) {
503
+ for (const r of this.rodando2.values()) matar(r.child, 'SIGTERM');
102
504
  for (const t of this._timers) clearInterval(t);
103
505
  this._timers = [];
104
506
  this.estado = 'parado';
@@ -107,16 +509,80 @@ export class Worker extends EventEmitter {
107
509
  }
108
510
  }
109
511
 
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) {
512
+ // Execução real na máquina, com a permissão do usuário que instalou.
513
+ // 0.4.0: cwd e env vêm do item (pasta do agente/projeto; NBX_*).
514
+ // 0.5.0: o shell vem de src/shell.js (sh, sh do Git for Windows ou PowerShell);
515
+ // aoFilho recebe o processo (cancelamento).
516
+ // 0.6.0: o comando nasce lider de um grupo (POSIX) para o timeout e o cancelamento
517
+ // levarem junto o CLI de codigo e os filhos; `parcial.ler()` da a saida ate agora.
518
+ export function realRun(comando, timeoutMs, { cwd, env, shell, aoFilho, parcial } = {}) {
519
+ const sh = shell || shellDe();
112
520
  return new Promise((resolve) => {
113
- const child = spawn('/bin/sh', ['-c', comando], { cwd: os.homedir(), env: process.env });
521
+ const child = spawn(sh.cmd, sh.args(comando), { cwd: cwd || os.homedir(), env: env || envMinimo(), windowsHide: true, detached: process.platform !== 'win32' });
522
+ if (typeof aoFilho === 'function') aoFilho(child);
523
+ if (process.platform !== 'win32') { guardarSaida(); VIVOS.add(child); child.on('exit', () => VIVOS.delete(child)); child.on('error', () => VIVOS.delete(child)); }
114
524
  let out = '', done = false;
525
+ if (parcial && typeof parcial === 'object') parcial.ler = () => out;
115
526
  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); });
527
+ const to = setTimeout(() => { matar(child, 'SIGKILL'); finish(124); }, timeoutMs);
528
+ const junta = (d) => { if (out.length < OUT_MAX * 2) out += d; };
529
+ child.stdout.on('data', junta);
530
+ child.stderr.on('data', junta);
531
+ child.on('close', (code, sinal) => { clearTimeout(to); finish(code == null ? (sinal ? 143 : -1) : code); });
120
532
  child.on('error', (e) => { clearTimeout(to); out += String(e.message || e); finish(127); });
121
533
  });
122
534
  }
535
+
536
+ // ---- auxiliares do protocolo 2 ----
537
+
538
+ /** O flow nao existe no no (servidor anterior ao flows/58_2). */
539
+ export function semFlow(e) {
540
+ return /not found|nao encontrad|não encontrad|inexistente|unknown flow|does not exist|no such flow|isolated in context/i.test(String((e && e.message) || e));
541
+ }
542
+
543
+ function idDoComando(x) { return String(x == null ? '' : x).replace(/[^A-Za-z0-9_]/g, '').slice(0, 60); }
544
+
545
+ const ENV_FIXO_PROIBIDO = new Set(['PATH', 'HOME', 'SHELL', 'USER', 'LOGNAME', 'PWD', 'IFS', 'ENV', 'BASH_ENV', 'TMPDIR', 'NODE_OPTIONS', 'GIT_ASKPASS', 'GIT_SSH', 'GIT_SSH_COMMAND', 'GIT_TERMINAL_PROMPT', 'USERPROFILE']);
546
+
547
+ /** Nome de variavel que um segredo pode ocupar (o Cofre ja confere; aqui de novo). */
548
+ export function nomeDeSegredoOk(n) {
549
+ return /^[A-Z_][A-Z0-9_]{0,63}$/.test(n) && !ENV_FIXO_PROIBIDO.has(n) && !/^(NBX_|NEURONIUN_|LD_|DYLD_)/.test(n);
550
+ }
551
+
552
+ /** O executor escolhido para a bash (A.1 Modelos): so nome conhecido; o resto = automatico. */
553
+ export function executorDaBash(x) {
554
+ const k = String(x == null ? '' : x).trim().toLowerCase();
555
+ return ['claude', 'codex', 'google', 'grok', 'antigravity', 'gemini', 'qwen'].includes(k) ? k : '';
556
+ }
557
+
558
+ /** env_fixos da bash (nunca segredo: o servidor ja recusa nome com cara de segredo). */
559
+ export function envFixosValidos(e) {
560
+ const out = {};
561
+ if (!e || typeof e !== 'object') return out;
562
+ for (const [k, v] of Object.entries(e).slice(0, 20)) {
563
+ if (!/^[A-Z0-9_]{1,40}$/.test(k) || ENV_FIXO_PROIBIDO.has(k) || /^(NBX_|NEURONIUN_|LD_|DYLD_)/.test(k)) continue;
564
+ if (/TOKEN|KEY|SECRET|SENHA|PASSWORD/.test(k)) continue;
565
+ if (typeof v !== 'string' || v.length > 500) continue;
566
+ out[k] = v;
567
+ }
568
+ return out;
569
+ }
570
+
571
+ /**
572
+ * Git sem prompt e sem o segredo na URL nem no .git/config (spec 03 par. 5.6):
573
+ * token -> GIT_ASKPASS (script que so le a variavel do proprio processo);
574
+ * chave ssh (arquivo 0600) -> GIT_SSH_COMMAND. Tudo some no fim do comando.
575
+ */
576
+ export function prepararGit(env, segDir) {
577
+ env.GIT_TERMINAL_PROMPT = '0';
578
+ if (env.SEGREDO_GIT_TOKEN) {
579
+ fs.mkdirSync(segDir, { recursive: true, mode: 0o700 });
580
+ const f = path.join(segDir, 'askpass.sh');
581
+ fs.writeFileSync(f, '#!/bin/sh\ncase "$1" in\n *sername*) printf \'%s\\n\' "${SEGREDO_GIT_USUARIO:-x-access-token}" ;;\n *) printf \'%s\\n\' "$SEGREDO_GIT_TOKEN" ;;\nesac\n', { mode: 0o700 });
582
+ env.GIT_ASKPASS = f;
583
+ }
584
+ if (env.SEGREDO_GIT_CHAVE) {
585
+ env.GIT_SSH_COMMAND = `ssh -i "${env.SEGREDO_GIT_CHAVE}" -o IdentitiesOnly=yes -o StrictHostKeyChecking=accept-new`;
586
+ }
587
+ return env;
588
+ }