primocode 4.3.0 → 7.0.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 +91 -107
- package/bin/primocode.js +272 -459
- package/lib/act.js +43 -471
- package/lib/api.js +2 -2
- package/lib/config.js +4 -32
- package/lib/desktop.js +142 -0
- package/lib/tools.js +68 -467
- package/lib/ui.js +135 -78
- package/package.json +7 -18
- package/lib/mascot.js +0 -121
- package/lib/memory.js +0 -179
- package/lib/mouse.js +0 -144
- package/lib/platform.js +0 -245
package/bin/primocode.js
CHANGED
|
@@ -1,14 +1,10 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
/**
|
|
3
|
-
* PrimoCode
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
* - IA NUNCA entrega código no CMD
|
|
9
|
-
* - Sempre salva em arquivo e abre no navegador
|
|
10
|
-
* - Memória de projetos em C:\\primocode\\ (ou ~/primocode/)
|
|
11
|
-
* - Mouse virtual para controle completo da interface
|
|
3
|
+
* PrimoCode CLI v6.1 · ConectaPrimoAI
|
|
4
|
+
* Interface estilo Claude Code — minimalista, poderosa, elegante.
|
|
5
|
+
* Auto-instalação de Node.js com confirmação Y/n e barra de progresso.
|
|
6
|
+
* Suporte Termux (pkg install nodejs).
|
|
7
|
+
* Modos: primocode (agente completo, PADRÃO) · chat (conversa pura)
|
|
12
8
|
*/
|
|
13
9
|
|
|
14
10
|
'use strict';
|
|
@@ -17,176 +13,89 @@ const readline = require('readline');
|
|
|
17
13
|
const path = require('path');
|
|
18
14
|
const fs = require('fs');
|
|
19
15
|
const os = require('os');
|
|
20
|
-
const {
|
|
16
|
+
const { execSync, spawn } = require('child_process');
|
|
17
|
+
const pkg = require('../package.json');
|
|
21
18
|
|
|
22
|
-
const { c, welcomeBox, Spinner } = require('../lib/ui');
|
|
19
|
+
const { c, welcomeBox, Spinner, ProgressBar, askYesNo } = require('../lib/ui');
|
|
23
20
|
const api = require('../lib/api');
|
|
24
21
|
const tools = require('../lib/tools');
|
|
25
22
|
const cfg = require('../lib/config');
|
|
26
|
-
const
|
|
27
|
-
|
|
28
|
-
const
|
|
23
|
+
const { runAct } = require('../lib/act');
|
|
24
|
+
|
|
25
|
+
const VERSION = pkg.version;
|
|
29
26
|
|
|
30
27
|
const state = {
|
|
31
28
|
config: cfg.loadConfig(),
|
|
32
29
|
history: [],
|
|
33
|
-
mode: '
|
|
30
|
+
mode: 'primocode',
|
|
34
31
|
attachedFiles: [],
|
|
35
32
|
lastResponse: '',
|
|
36
|
-
currentProject: null,
|
|
37
33
|
};
|
|
38
34
|
|
|
39
35
|
const HELP = `
|
|
40
36
|
${c.bold('Comandos')}
|
|
41
|
-
/mode
|
|
42
|
-
/attach
|
|
43
|
-
/clear
|
|
44
|
-
/cls
|
|
45
|
-
/uninstall
|
|
46
|
-
/
|
|
47
|
-
/terminal abrir terminal
|
|
48
|
-
/run <arquivo> executar arquivo (py, js, html)
|
|
49
|
-
/screenshot capturar tela
|
|
50
|
-
/mouse <x> <y> mover mouse para coordenadas
|
|
51
|
-
/click <x> <y> clicar em coordenadas
|
|
52
|
-
/search <termo> pesquisar na web
|
|
53
|
-
/project mostrar projeto atual
|
|
54
|
-
/projects listar projetos
|
|
55
|
-
/help ajuda
|
|
56
|
-
/exit sair
|
|
37
|
+
${c.brand('/mode')} Primo Code / Chat
|
|
38
|
+
${c.brand('/attach')} (Caminho do arquivo ou pasta) anexa arquivo
|
|
39
|
+
${c.brand('/clear')} limpa conversa
|
|
40
|
+
${c.brand('/cls')} limpa tela
|
|
41
|
+
${c.brand('/uninstall')} remove PrimoCode
|
|
42
|
+
${c.brand('/exit')} sair
|
|
57
43
|
|
|
58
44
|
${c.bold('Modos')}
|
|
59
|
-
${c.
|
|
60
|
-
${c.brand('Chat')}
|
|
45
|
+
${c.magenta('Primo Code')} ${c.muted('Agente completo — cursor próprio, escreve código, controla desktop e navegador')}
|
|
46
|
+
${c.brand('Chat')} ${c.muted('Conversa pura — sem tools, só diálogo')}
|
|
61
47
|
`;
|
|
62
48
|
|
|
63
49
|
let rl = null;
|
|
64
50
|
|
|
65
51
|
function makePrompt() {
|
|
66
|
-
const
|
|
52
|
+
const modeTag = state.mode === 'primocode'
|
|
53
|
+
? c.magenta('Primo Code')
|
|
54
|
+
: c.brand('Chat');
|
|
67
55
|
const att = state.attachedFiles.length ? c.muted(` +${state.attachedFiles.length}`) : '';
|
|
68
|
-
|
|
69
|
-
return `\n${c.muted(tag + att + proj)} ${c.brand('❯')} `;
|
|
56
|
+
return `\n${c.muted(modeTag + att)} ${c.brand('❯')} `;
|
|
70
57
|
}
|
|
71
58
|
function refreshPrompt() { if (rl) rl.setPrompt(makePrompt()); }
|
|
72
59
|
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
const
|
|
77
|
-
|
|
78
|
-
return result;
|
|
79
|
-
} catch (e) {
|
|
80
|
-
return { ok: false, error: e.message };
|
|
60
|
+
async function sendPrompt(userText) {
|
|
61
|
+
let promptWithAttach = userText;
|
|
62
|
+
if (state.attachedFiles.length) {
|
|
63
|
+
const parts = state.attachedFiles.map(f => `Arquivo: ${f.path}\n\`\`\`\n${f.content}\n\`\`\``);
|
|
64
|
+
promptWithAttach = parts.join('\n\n') + '\n\n' + userText;
|
|
81
65
|
}
|
|
82
|
-
}
|
|
83
|
-
|
|
84
|
-
// ---- Pipeline Multi-Agente Oculto ----
|
|
85
|
-
async function runMultiAgent(userText) {
|
|
86
|
-
console.log(c.muted(' 🚀 Gerando código... (5-15 segundos)'));
|
|
87
|
-
const sp = new Spinner('').start();
|
|
88
66
|
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
history:
|
|
96
|
-
model: 'main',
|
|
97
|
-
maxIterations: 3,
|
|
98
|
-
projectPath: process.cwd(),
|
|
67
|
+
if (state.mode === 'agent') {
|
|
68
|
+
await runAgent(promptWithAttach, userText);
|
|
69
|
+
} else if (state.mode === 'act') {
|
|
70
|
+
const r = await runAct(promptWithAttach, {
|
|
71
|
+
server: state.config.server,
|
|
72
|
+
model: state.config.model,
|
|
73
|
+
history: state.history,
|
|
99
74
|
});
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
return;
|
|
107
|
-
}
|
|
108
|
-
|
|
109
|
-
const code = result.finalCode || result.response || '';
|
|
110
|
-
state.lastResponse = code;
|
|
111
|
-
|
|
112
|
-
// NUNCA mostrar código no CMD — sempre salvar em arquivo
|
|
113
|
-
if (code && code.length > 0) {
|
|
114
|
-
// Determinar nome do projeto
|
|
115
|
-
let projectName = state.currentProject;
|
|
116
|
-
if (!projectName) {
|
|
117
|
-
const match = userText.match(/(?:crie|faça|desenvolva|build|make|create)\s+(?:um|uma|o|a)?\s*([\w\-]+)/i);
|
|
118
|
-
projectName = match ? match[1] : `projeto-${Date.now()}`;
|
|
119
|
-
state.currentProject = projectName;
|
|
120
|
-
}
|
|
121
|
-
|
|
122
|
-
// Criar projeto se não existir
|
|
123
|
-
const project = memory.createProject(projectName);
|
|
124
|
-
|
|
125
|
-
// Salvar código em arquivo
|
|
126
|
-
const ext = code.includes('<!DOCTYPE html>') || code.includes('<html') ? '.html' :
|
|
127
|
-
code.includes('import ') || code.includes('export ') ? '.js' :
|
|
128
|
-
code.includes('def ') || code.includes('import ') ? '.py' : '.txt';
|
|
129
|
-
const filename = `index${ext}`;
|
|
130
|
-
const filePath = memory.saveProjectFile(projectName, filename, code);
|
|
131
|
-
|
|
132
|
-
// Salvar também como output.html para fácil acesso
|
|
133
|
-
const outputHtml = path.join(memory.PRIMOCODE_DIR, 'output.html');
|
|
134
|
-
fs.writeFileSync(outputHtml, code, 'utf8');
|
|
135
|
-
|
|
136
|
-
// Atualizar memória do projeto
|
|
137
|
-
const projMem = memory.loadProjectMemory(projectName);
|
|
138
|
-
const updatedMem = projMem + `\n## Código Gerado (${new Date().toLocaleString('pt-BR')})\n\`\`\`\n${code.substring(0, 500)}...\n\`\`\`\n`;
|
|
139
|
-
memory.saveProjectMemory(projectName, updatedMem);
|
|
140
|
-
|
|
141
|
-
console.log(c.ok(`\n ✓ Código salvo em: ${filePath}`));
|
|
142
|
-
|
|
143
|
-
// Abrir no navegador se for HTML
|
|
144
|
-
if (ext === '.html') {
|
|
145
|
-
try {
|
|
146
|
-
platform.openBrowser(filePath);
|
|
147
|
-
console.log(c.muted(' 🌐 Abrindo no navegador...'));
|
|
148
|
-
} catch (e) {
|
|
149
|
-
// Silencia erro
|
|
150
|
-
}
|
|
151
|
-
} else {
|
|
152
|
-
// Para outros arquivos, tenta executar
|
|
153
|
-
try {
|
|
154
|
-
if (ext === '.py') {
|
|
155
|
-
execSync(`start cmd /k python "${filePath}"`, { stdio: 'ignore' });
|
|
156
|
-
console.log(c.muted(' ▶ Executando Python...'));
|
|
157
|
-
} else if (ext === '.js') {
|
|
158
|
-
execSync(`start cmd /k node "${filePath}"`, { stdio: 'ignore' });
|
|
159
|
-
console.log(c.muted(' ▶ Executando Node.js...'));
|
|
160
|
-
}
|
|
161
|
-
} catch (e) {
|
|
162
|
-
console.log(c.muted(' 📄 Arquivo salvo (não executável automaticamente)'));
|
|
163
|
-
}
|
|
164
|
-
}
|
|
165
|
-
}
|
|
166
|
-
|
|
167
|
-
cfg.appendHistory({ mode: 'Primo Code', prompt: userText, response: code });
|
|
168
|
-
|
|
169
|
-
} catch (err) {
|
|
170
|
-
sp.stop();
|
|
171
|
-
// Silencia erro de pipeline, tenta modo chat
|
|
172
|
-
await runChat(userText, userText);
|
|
75
|
+
state.history.push({ role: 'user', content: userText });
|
|
76
|
+
state.history.push({ role: 'assistant', content: r.assistantMessage.content });
|
|
77
|
+
state.lastResponse = r.assistantMessage.content;
|
|
78
|
+
cfg.appendHistory({ mode: 'primocode', prompt: userText, response: r.assistantMessage.content });
|
|
79
|
+
} else {
|
|
80
|
+
await runChat(promptWithAttach, userText);
|
|
173
81
|
}
|
|
82
|
+
state.attachedFiles = [];
|
|
83
|
+
refreshPrompt();
|
|
174
84
|
}
|
|
175
85
|
|
|
176
86
|
async function runChat(promptForModel, userTextForMemory) {
|
|
177
|
-
const sp = new Spinner('').start();
|
|
178
|
-
|
|
87
|
+
const sp = new Spinner('pensando').start();
|
|
179
88
|
let started = false;
|
|
180
89
|
let text = '';
|
|
181
90
|
try {
|
|
182
91
|
await api.requestStream(state.config.server, '/api/normal/stream', {
|
|
183
92
|
prompt: promptForModel,
|
|
184
93
|
history: state.history.slice(-20),
|
|
185
|
-
model:
|
|
94
|
+
model: state.config.model,
|
|
186
95
|
}, (evt) => {
|
|
187
96
|
if (evt.erro) {
|
|
188
97
|
if (!started) sp.stop();
|
|
189
|
-
|
|
98
|
+
console.log(c.err(`\nerro: ${evt.erro}`));
|
|
190
99
|
return;
|
|
191
100
|
}
|
|
192
101
|
if (evt.delta) {
|
|
@@ -194,363 +103,267 @@ async function runChat(promptForModel, userTextForMemory) {
|
|
|
194
103
|
text += evt.delta;
|
|
195
104
|
process.stdout.write(c.white(evt.delta));
|
|
196
105
|
}
|
|
197
|
-
if (evt.done
|
|
106
|
+
if (evt.done) { if (!started) sp.stop(); process.stdout.write('\n'); }
|
|
198
107
|
});
|
|
199
|
-
} catch (
|
|
108
|
+
} catch (e) {
|
|
200
109
|
sp.stop();
|
|
201
|
-
|
|
202
|
-
return;
|
|
203
|
-
}
|
|
204
|
-
if (!started) { sp.stop(); console.log(c.muted('\n ⏳ Servidor processando, tente novamente em instantes')); return; }
|
|
205
|
-
|
|
206
|
-
state.history.push({ role: 'user', content: userTextForMemory });
|
|
207
|
-
state.history.push({ role: 'assistant', content: text });
|
|
208
|
-
state.lastResponse = text;
|
|
209
|
-
cfg.appendHistory({ mode: state.mode, prompt: userTextForMemory, response: text });
|
|
210
|
-
}
|
|
211
|
-
|
|
212
|
-
// ---- Envio Principal ----
|
|
213
|
-
async function sendPrompt(userText) {
|
|
214
|
-
let promptWithAttach = userText;
|
|
215
|
-
if (state.attachedFiles.length) {
|
|
216
|
-
const parts = state.attachedFiles.map(f => `Arquivo: ${f.path}\n\`\`\`\n${f.content}\n\`\`\``);
|
|
217
|
-
promptWithAttach = parts.join('\n\n') + '\n\n' + userText;
|
|
110
|
+
console.log(c.err(`\n${e.message || e}`));
|
|
218
111
|
}
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
promptWithAttach = `[Memória do sistema: ${memContext.substring(0, 300)}]\n\n${promptWithAttach}`;
|
|
112
|
+
if (text) {
|
|
113
|
+
state.history.push({ role: 'user', content: userTextForMemory });
|
|
114
|
+
state.history.push({ role: 'assistant', content: text });
|
|
115
|
+
state.lastResponse = text;
|
|
116
|
+
cfg.appendHistory({ mode: 'chat', prompt: userTextForMemory, response: text });
|
|
225
117
|
}
|
|
118
|
+
}
|
|
226
119
|
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
120
|
+
async function runAgent(promptForModel, userTextForMemory) {
|
|
121
|
+
const sp = new Spinner('agente pensando').start();
|
|
122
|
+
let step = '';
|
|
123
|
+
let text = '';
|
|
124
|
+
try {
|
|
125
|
+
await api.requestStream(state.config.server, '/api/agent/stream', {
|
|
126
|
+
prompt: promptForModel,
|
|
127
|
+
history: state.history.slice(-20),
|
|
128
|
+
}, (evt) => {
|
|
129
|
+
if (evt.erro) { sp.stop(); console.log(c.err(`\nerro: ${evt.erro}`)); return; }
|
|
130
|
+
if (evt.step && evt.event === 'start') {
|
|
131
|
+
if (!step) sp.stop();
|
|
132
|
+
step = evt.step;
|
|
133
|
+
const label = step === 'arquiteto' ? 'Arquiteto' : step === 'engenheiro' ? 'Engenheiro' : 'Revisor';
|
|
134
|
+
console.log(c.muted(`\n ${label}…`));
|
|
135
|
+
return;
|
|
136
|
+
}
|
|
137
|
+
if (evt.step === 'revisor' && evt.delta) {
|
|
138
|
+
if (!text) process.stdout.write('\n');
|
|
139
|
+
text += evt.delta;
|
|
140
|
+
process.stdout.write(c.white(evt.delta));
|
|
141
|
+
}
|
|
142
|
+
if (evt.done) process.stdout.write('\n');
|
|
143
|
+
});
|
|
144
|
+
} catch (e) { sp.stop(); console.log(c.err(`\n${e.message || e}`)); }
|
|
145
|
+
if (text) {
|
|
146
|
+
state.history.push({ role: 'user', content: userTextForMemory });
|
|
147
|
+
state.history.push({ role: 'assistant', content: text });
|
|
148
|
+
state.lastResponse = text;
|
|
149
|
+
cfg.appendHistory({ mode: 'agent', prompt: userTextForMemory, response: text });
|
|
231
150
|
}
|
|
232
|
-
|
|
233
|
-
state.attachedFiles = [];
|
|
234
|
-
refreshPrompt();
|
|
235
151
|
}
|
|
236
152
|
|
|
237
|
-
|
|
238
|
-
async function handleSlash(line) {
|
|
239
|
-
const [cmd, ...rest] = line.trim().split(/\s+/);
|
|
240
|
-
const arg = rest.join(' ').trim();
|
|
153
|
+
function isSlash(text) { return text.trim().startsWith('/'); }
|
|
241
154
|
|
|
155
|
+
async function handleSlash(text) {
|
|
156
|
+
const [cmd, ...args] = text.trim().slice(1).split(/\s+/);
|
|
157
|
+
const rest = text.trim().slice(1 + cmd.length).trim();
|
|
242
158
|
switch (cmd.toLowerCase()) {
|
|
243
|
-
case '
|
|
244
|
-
case '
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
console.log(c.muted(' Conversa limpa'));
|
|
250
|
-
return;
|
|
251
|
-
case '/version':
|
|
252
|
-
console.log(c.muted(` PrimoCode v4.2 — Cross-Platform`));
|
|
253
|
-
console.log(c.muted(` Servidor: ${state.config.server}`));
|
|
254
|
-
return;
|
|
255
|
-
case '/status': {
|
|
256
|
-
const sp = new Spinner('Verificando').start();
|
|
257
|
-
try {
|
|
258
|
-
const res = await api.request(state.config.server, '/health', {});
|
|
259
|
-
sp.stop();
|
|
260
|
-
if (res.status === 'ok') {
|
|
261
|
-
console.log(c.ok(' Online') + c.muted(` ${state.config.server}`));
|
|
262
|
-
} else {
|
|
263
|
-
console.log(c.muted(' Servidor offline'));
|
|
264
|
-
}
|
|
265
|
-
} catch (e) {
|
|
266
|
-
sp.stop();
|
|
267
|
-
// Silencia erro de status
|
|
268
|
-
console.log(c.muted(' Servidor offline'));
|
|
269
|
-
}
|
|
270
|
-
return;
|
|
271
|
-
}
|
|
272
|
-
case '/mode': {
|
|
273
|
-
const valid = ['Primo Code', 'Chat'];
|
|
274
|
-
let target = arg;
|
|
275
|
-
if (!valid.includes(target)) {
|
|
276
|
-
console.log(c.warn(' /mode Primo Code | Chat'));
|
|
277
|
-
return;
|
|
278
|
-
}
|
|
279
|
-
state.mode = target;
|
|
280
|
-
state.config.model = cfg.resolveModel(target);
|
|
281
|
-
console.log(c.muted(` Modo: ${target}`));
|
|
282
|
-
refreshPrompt();
|
|
283
|
-
return;
|
|
159
|
+
case 'help': console.log(HELP); break;
|
|
160
|
+
case 'mode': {
|
|
161
|
+
const m = rest.toLowerCase();
|
|
162
|
+
if (['act','agent','chat'].includes(m)) { state.mode = m; console.log(c.ok(`Modo: ${m}`)); }
|
|
163
|
+
else console.log(c.err('Uso: /mode chat|agent|act'));
|
|
164
|
+
break;
|
|
284
165
|
}
|
|
285
|
-
case '
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
console.log(c.muted(` Anexado: ${arg}`));
|
|
291
|
-
refreshPrompt();
|
|
292
|
-
} catch (e) { console.log(c.muted(` Erro ao anexar`)); }
|
|
293
|
-
return;
|
|
166
|
+
case 'model': {
|
|
167
|
+
const m = rest.toLowerCase();
|
|
168
|
+
if (['main','fast'].includes(m)) { state.config.model = m; cfg.saveConfig(state.config); console.log(c.ok(`Modelo: ${m}`)); }
|
|
169
|
+
else console.log(c.err('Uso: /model main|fast'));
|
|
170
|
+
break;
|
|
294
171
|
}
|
|
295
|
-
case '
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
const projMem = memory.loadProjectMemory(state.currentProject);
|
|
301
|
-
if (projMem) {
|
|
302
|
-
console.log(c.muted(' Memória do projeto carregada'));
|
|
303
|
-
}
|
|
304
|
-
} else {
|
|
305
|
-
console.log(c.muted(' Nenhum projeto ativo'));
|
|
306
|
-
}
|
|
307
|
-
return;
|
|
172
|
+
case 'attach': {
|
|
173
|
+
if (!rest) { console.log(c.err('Uso: /attach <arquivo>')); break; }
|
|
174
|
+
try { const content = fs.readFileSync(path.resolve(rest), 'utf-8'); state.attachedFiles.push({ path: rest, content }); console.log(c.ok(`Anexado: ${rest} (${tools.fmtBytes(content.length)})`)); }
|
|
175
|
+
catch { console.log(c.err(`Não consegui ler: ${rest}`)); }
|
|
176
|
+
break;
|
|
308
177
|
}
|
|
309
|
-
case '
|
|
310
|
-
|
|
311
|
-
if (
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
}
|
|
319
|
-
|
|
178
|
+
case 'detach': state.attachedFiles = []; console.log(c.ok('Anexos removidos.')); break;
|
|
179
|
+
case 'files':
|
|
180
|
+
if (!state.attachedFiles.length) console.log(c.muted('Nenhum arquivo anexado.'));
|
|
181
|
+
else state.attachedFiles.forEach(f => console.log(` ${c.brand(f.path)} ${c.muted(tools.fmtBytes(f.content.length))}`));
|
|
182
|
+
break;
|
|
183
|
+
case 'tree': { const depth = parseInt(rest,10)||2; console.log(tools.treeDir('.', depth)); break; }
|
|
184
|
+
case 'read': {
|
|
185
|
+
if (!rest) { console.log(c.err('Uso: /read <arquivo>')); break; }
|
|
186
|
+
try { const content = fs.readFileSync(path.resolve(rest), 'utf-8'); console.log(c.muted(`\n--- ${rest} ---\n`)); console.log(content.length>2000?content.slice(0,2000)+'\n...':content); }
|
|
187
|
+
catch { console.log(c.err(`Não consegui ler: ${rest}`)); }
|
|
188
|
+
break;
|
|
320
189
|
}
|
|
321
|
-
case '
|
|
322
|
-
if (!
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
// Silencia erro
|
|
328
|
-
}
|
|
329
|
-
return;
|
|
190
|
+
case 'write': {
|
|
191
|
+
if (!rest) { console.log(c.err('Uso: /write <arquivo>')); break; }
|
|
192
|
+
if (!state.lastResponse) { console.log(c.err('Nenhuma resposta para salvar.')); break; }
|
|
193
|
+
try { fs.writeFileSync(path.resolve(rest), state.lastResponse, 'utf-8'); console.log(c.ok(`Salvo em: ${rest}`)); }
|
|
194
|
+
catch (e) { console.log(c.err(`Erro: ${e.message}`)); }
|
|
195
|
+
break;
|
|
330
196
|
}
|
|
331
|
-
case '
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
// Silencia erro
|
|
337
|
-
}
|
|
338
|
-
return;
|
|
197
|
+
case 'apply': {
|
|
198
|
+
const applied = tools.applyCodeBlocks(state.lastResponse);
|
|
199
|
+
if (applied.length) applied.forEach(a => console.log(c.ok(`${a.created?'Criado':'Atualizado'}: ${a.path}`)));
|
|
200
|
+
else console.log(c.muted('Nenhum bloco com hint // filename: encontrado.'));
|
|
201
|
+
break;
|
|
339
202
|
}
|
|
340
|
-
case '
|
|
341
|
-
if (!
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
const result = platform.openApp(arg);
|
|
349
|
-
console.log(result.ok ? c.ok(` ✓ Executando: ${arg}`) : c.muted(` Indisponível`));
|
|
350
|
-
}
|
|
351
|
-
} catch (e) {
|
|
352
|
-
// Silencia erro
|
|
353
|
-
}
|
|
354
|
-
return;
|
|
355
|
-
}
|
|
356
|
-
case '/screenshot': {
|
|
357
|
-
try {
|
|
358
|
-
const result = await mouse.screenshot();
|
|
359
|
-
console.log(result.ok ? c.ok(` ✓ Screenshot salvo: ${result.path}`) : c.muted(` Indisponível`));
|
|
360
|
-
} catch (e) {
|
|
361
|
-
// Silencia erro
|
|
362
|
-
}
|
|
363
|
-
return;
|
|
203
|
+
case 'run': {
|
|
204
|
+
if (!rest) { console.log(c.err('Uso: /run <comando>')); break; }
|
|
205
|
+
console.log(c.muted(`$ ${rest}`));
|
|
206
|
+
const result = await tools.runShell(rest);
|
|
207
|
+
if (result.stdout) console.log(result.stdout);
|
|
208
|
+
if (result.stderr) console.log(c.err(result.stderr));
|
|
209
|
+
if (result.code !== 0) console.log(c.err(`exit ${result.code}`));
|
|
210
|
+
break;
|
|
364
211
|
}
|
|
365
|
-
case '
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
console.log(result.ok !== false ? c.ok(` ✓ Mouse movido para (${x}, ${y})`) : c.muted(` Indisponível`));
|
|
371
|
-
} catch (e) {
|
|
372
|
-
// Silencia erro
|
|
373
|
-
}
|
|
374
|
-
return;
|
|
212
|
+
case 'open': {
|
|
213
|
+
if (!rest) { console.log(c.err('Uso: /open <arquivo|url>')); break; }
|
|
214
|
+
await tools.openInBrowser(rest);
|
|
215
|
+
console.log(c.ok(`Aberto: ${rest}`));
|
|
216
|
+
break;
|
|
375
217
|
}
|
|
376
|
-
case '
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
const result = await mouse.clickAt(cx, cy);
|
|
381
|
-
console.log(result.ok ? c.ok(` ✓ Clicado em (${cx}, ${cy})`) : c.muted(` Indisponível`));
|
|
382
|
-
} catch (e) {
|
|
383
|
-
// Silencia erro
|
|
384
|
-
}
|
|
385
|
-
return;
|
|
218
|
+
case 'act': {
|
|
219
|
+
if (!rest) { console.log(c.err('Uso: /act <tarefa>')); break; }
|
|
220
|
+
const old = state.mode; state.mode = 'act'; await sendPrompt(rest); state.mode = old;
|
|
221
|
+
break;
|
|
386
222
|
}
|
|
387
|
-
case '
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
}
|
|
395
|
-
return;
|
|
223
|
+
case 'clear': state.history = []; console.log(c.ok('Memória limpa.')); break;
|
|
224
|
+
case 'cls': process.stdout.write('\x1Bc'); break;
|
|
225
|
+
case 'status': {
|
|
226
|
+
const sp2 = new Spinner('verificando').start();
|
|
227
|
+
try { const h = await api.getHealth(state.config.server); sp2.stop(); console.log(c.ok(`Servidor: ${h.status||'ok'}`)); console.log(c.muted(` Modelos: ${Object.values(h.models||{}).join(', ')}`)); console.log(c.muted(` Fallback: ${h.using_fallback?'ativo':'inativo'}`)); }
|
|
228
|
+
catch (e) { sp2.stop(); console.log(c.err(`Indisponível: ${e.message}`)); }
|
|
229
|
+
break;
|
|
396
230
|
}
|
|
397
|
-
case '
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
const installDir = path.join(os.homedir(), '.primocode');
|
|
401
|
-
const globalLink = path.join(os.homedir(), '.local/bin/primocode');
|
|
402
|
-
if (fs.existsSync(globalLink)) fs.unlinkSync(globalLink);
|
|
403
|
-
if (fs.existsSync(installDir)) fs.rmSync(installDir, { recursive: true, force: true });
|
|
404
|
-
console.log(c.ok(' PrimoCode removido'));
|
|
405
|
-
} catch (e) {
|
|
406
|
-
// Silencia erro
|
|
407
|
-
}
|
|
408
|
-
return;
|
|
409
|
-
}
|
|
410
|
-
default:
|
|
411
|
-
console.log(c.warn(` Comando desconhecido: ${cmd}`));
|
|
412
|
-
console.log(c.muted(' /help'));
|
|
231
|
+
case 'version': console.log(c.brand(`PrimoCode v${VERSION}`)); break;
|
|
232
|
+
case 'exit': case 'quit': console.log(c.muted('Até logo!')); process.exit(0);
|
|
233
|
+
default: console.log(c.err(`Comando desconhecido: /${cmd}. Digite /help.`));
|
|
413
234
|
}
|
|
414
235
|
}
|
|
415
236
|
|
|
416
|
-
//
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
237
|
+
// Detecta Termux
|
|
238
|
+
function isTermux() {
|
|
239
|
+
return !!process.env.TERMUX_VERSION || (process.env.PREFIX && process.env.PREFIX.includes('termux'));
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
// ---- Auto-instalação Node.js com barra de progresso ----
|
|
243
|
+
async function checkAndInstallNode() {
|
|
244
|
+
const nodeExists = () => { try { execSync('node --version', {stdio:'ignore'}); return true; } catch { return false; } };
|
|
245
|
+
|
|
246
|
+
if (nodeExists()) {
|
|
247
|
+
const v = execSync('node --version', {encoding:'utf-8'}).trim();
|
|
248
|
+
const major = parseInt(v.replace('v','').split('.')[0]);
|
|
249
|
+
if (major >= 18) { console.log(c.ok(`Node.js ${v} detectado.`)); return true; }
|
|
250
|
+
console.log(c.warn(`Node.js ${v} detectado, mas requer v18.17+.`));
|
|
251
|
+
} else {
|
|
252
|
+
console.log(c.err('Node.js não encontrado no sistema.'));
|
|
431
253
|
}
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
254
|
+
|
|
255
|
+
// PERGUNTA antes de instalar — aguarda resposta do usuário
|
|
256
|
+
const answer = await askYesNo('Deseja instalar o Node.js automaticamente?');
|
|
257
|
+
if (!answer) {
|
|
258
|
+
console.log(c.err('Node.js é necessário para rodar o PrimoCode.'));
|
|
259
|
+
console.log(c.muted('Instale manualmente em: https://nodejs.org/'));
|
|
260
|
+
process.exit(1);
|
|
439
261
|
}
|
|
440
|
-
await sendPrompt(prompt.join(' '));
|
|
441
|
-
return true;
|
|
442
|
-
}
|
|
443
262
|
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
console.log(`${c.bold('Uso')}`);
|
|
447
|
-
console.log(` primocode Interativo (Multi-Agente)`);
|
|
448
|
-
console.log(` primocode "crie um site" Pipeline completo`);
|
|
449
|
-
console.log(` primocode --chat "duvida" Modo conversa`);
|
|
450
|
-
console.log(HELP);
|
|
451
|
-
console.log(`${c.bold('Comandos de Sistema')}`);
|
|
452
|
-
console.log(` /app <nome> Abrir aplicativo`);
|
|
453
|
-
console.log(` /terminal Abrir terminal`);
|
|
454
|
-
console.log(` /run <arquivo> Executar arquivo (Python, JS, HTML)`);
|
|
455
|
-
console.log(` /screenshot Capturar tela`);
|
|
456
|
-
console.log(` /mouse <x> <y> Mover mouse`);
|
|
457
|
-
console.log(` /click <x> <y> Clicar`);
|
|
458
|
-
console.log(` /search <termo> Pesquisar na web`);
|
|
459
|
-
console.log(` /project Ver projeto atual`);
|
|
460
|
-
console.log(` /projects Listar projetos`);
|
|
461
|
-
}
|
|
263
|
+
const platform = os.platform();
|
|
264
|
+
const pb = new ProgressBar('Instalando Node.js');
|
|
462
265
|
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
266
|
+
try {
|
|
267
|
+
if (isTermux()) {
|
|
268
|
+
// Termux — usa pkg
|
|
269
|
+
pb.start();
|
|
270
|
+
const child = spawn('pkg', ['install', '-y', 'nodejs'], { stdio: 'pipe' });
|
|
271
|
+
let stderr = '';
|
|
272
|
+
child.stderr.on('data', d => { stderr += d; pb.tick(); });
|
|
273
|
+
await new Promise((resolve, reject) => {
|
|
274
|
+
child.on('close', code => { pb.stop(); code === 0 ? resolve() : reject(new Error(stderr || 'pkg failed')); });
|
|
275
|
+
});
|
|
276
|
+
} else if (platform === 'darwin' || platform === 'linux') {
|
|
277
|
+
const hasNvm = () => { try { execSync('command -v nvm', {stdio:'ignore'}); return true; } catch { return false; } };
|
|
278
|
+
const hasFnm = () => { try { execSync('command -v fnm', {stdio:'ignore'}); return true; } catch { return false; } };
|
|
279
|
+
|
|
280
|
+
if (hasNvm() || fs.existsSync(path.join(os.homedir(), '.nvm'))) {
|
|
281
|
+
pb.start();
|
|
282
|
+
const nvmDir = path.join(os.homedir(), '.nvm');
|
|
283
|
+
const child = spawn('bash', ['-c', `export NVM_DIR="${nvmDir}" && [ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh" && nvm install 20 && nvm use 20 && nvm alias default 20`], { stdio: 'pipe' });
|
|
284
|
+
let stderr = '';
|
|
285
|
+
child.stderr.on('data', d => { stderr += d; pb.tick(); });
|
|
286
|
+
await new Promise((resolve, reject) => {
|
|
287
|
+
child.on('close', code => { pb.stop(); code === 0 ? resolve() : reject(new Error(stderr || 'nvm failed')); });
|
|
288
|
+
});
|
|
289
|
+
} else if (hasFnm()) {
|
|
290
|
+
pb.start();
|
|
291
|
+
const child = spawn('bash', ['-c', 'fnm install 20 && fnm use 20 && fnm default 20'], { stdio: 'pipe' });
|
|
292
|
+
let stderr = '';
|
|
293
|
+
child.stderr.on('data', d => { stderr += d; pb.tick(); });
|
|
294
|
+
await new Promise((resolve, reject) => {
|
|
295
|
+
child.on('close', code => { pb.stop(); code === 0 ? resolve() : reject(new Error(stderr || 'fnm failed')); });
|
|
296
|
+
});
|
|
297
|
+
} else {
|
|
298
|
+
pb.start();
|
|
299
|
+
// Instala nvm primeiro
|
|
300
|
+
const child1 = spawn('bash', ['-c', 'curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash'], { stdio: 'pipe' });
|
|
301
|
+
let stderr1 = '';
|
|
302
|
+
child1.stderr.on('data', d => { stderr1 += d; pb.tick(); });
|
|
303
|
+
await new Promise((resolve, reject) => {
|
|
304
|
+
child1.on('close', code => { code === 0 ? resolve() : reject(new Error(stderr1)); });
|
|
305
|
+
});
|
|
306
|
+
|
|
307
|
+
// Instala Node via nvm
|
|
308
|
+
const nvmDir = path.join(os.homedir(), '.nvm');
|
|
309
|
+
const child2 = spawn('bash', ['-c', `export NVM_DIR="${nvmDir}" && [ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh" && nvm install 20 && nvm use 20 && nvm alias default 20`], { stdio: 'pipe' });
|
|
310
|
+
let stderr2 = '';
|
|
311
|
+
child2.stderr.on('data', d => { stderr2 += d; pb.tick(); });
|
|
312
|
+
await new Promise((resolve, reject) => {
|
|
313
|
+
child2.on('close', code => { pb.stop(); code === 0 ? resolve() : reject(new Error(stderr2 || 'nvm install failed')); });
|
|
314
|
+
});
|
|
472
315
|
}
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
316
|
+
} else if (platform === 'win32') {
|
|
317
|
+
pb.start();
|
|
318
|
+
const child = spawn('cmd', ['/c', 'winget install OpenJS.NodeJS.LTS'], { stdio: 'pipe' });
|
|
319
|
+
let stderr = '';
|
|
320
|
+
child.stderr.on('data', d => { stderr += d; pb.tick(); });
|
|
321
|
+
await new Promise((resolve, reject) => {
|
|
322
|
+
child.on('close', code => { pb.stop(); code === 0 ? resolve() : reject(new Error(stderr || 'winget failed')); });
|
|
323
|
+
});
|
|
477
324
|
}
|
|
478
|
-
}
|
|
479
|
-
}
|
|
480
325
|
|
|
481
|
-
//
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
if (projects.length > 0) {
|
|
485
|
-
console.log(c.muted(`\n 📁 Projetos existentes encontrados:`));
|
|
486
|
-
for (const p of projects) {
|
|
487
|
-
console.log(c.muted(` • ${p}`));
|
|
326
|
+
// Verifica instalação
|
|
327
|
+
if (!nodeExists()) {
|
|
328
|
+
throw new Error('Node.js não foi instalado corretamente');
|
|
488
329
|
}
|
|
489
|
-
|
|
330
|
+
const v = execSync('node --version', {encoding:'utf-8'}).trim();
|
|
331
|
+
console.log(c.ok(`Node.js ${v} instalado com sucesso!`));
|
|
332
|
+
return true;
|
|
333
|
+
} catch (e) {
|
|
334
|
+
pb.stop();
|
|
335
|
+
console.log(c.err(`Falha ao instalar Node.js: ${e.message}`));
|
|
336
|
+
console.log(c.muted('Por favor, instale manualmente: https://nodejs.org/'));
|
|
337
|
+
process.exit(1);
|
|
490
338
|
}
|
|
491
339
|
}
|
|
492
340
|
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
process.
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
output: process.stdout,
|
|
505
|
-
prompt: makePrompt(),
|
|
506
|
-
historySize: 200,
|
|
507
|
-
});
|
|
508
|
-
rl.prompt();
|
|
509
|
-
|
|
510
|
-
const queue = [];
|
|
511
|
-
let busy = false;
|
|
512
|
-
async function drain() {
|
|
513
|
-
if (busy) return;
|
|
514
|
-
busy = true;
|
|
515
|
-
while (queue.length) {
|
|
516
|
-
const input = queue.shift();
|
|
517
|
-
try {
|
|
518
|
-
if (input.startsWith('/')) await handleSlash(input);
|
|
519
|
-
else await sendPrompt(input);
|
|
520
|
-
} catch (e) {
|
|
521
|
-
// Silencia erro geral
|
|
522
|
-
}
|
|
341
|
+
async function main() {
|
|
342
|
+
await checkAndInstallNode();
|
|
343
|
+
const args = process.argv.slice(2);
|
|
344
|
+
if (args.length && !args[0].startsWith('-')) {
|
|
345
|
+
const prompt = args.join(' ');
|
|
346
|
+
const isAgent = args.includes('--agent');
|
|
347
|
+
const fileFlag = args.indexOf('-f');
|
|
348
|
+
let promptText = prompt;
|
|
349
|
+
if (fileFlag >= 0 && args[fileFlag+1]) {
|
|
350
|
+
try { const fc = fs.readFileSync(path.resolve(args[fileFlag+1]), 'utf-8'); promptText = `Arquivo: ${args[fileFlag+1]}\n\`\`\`\n${fc}\n\`\`\`\n\n${prompt}`; }
|
|
351
|
+
catch { console.log(c.err(`Não consegui ler: ${args[fileFlag+1]}`)); process.exit(1); }
|
|
523
352
|
}
|
|
524
|
-
|
|
525
|
-
|
|
353
|
+
if (isAgent) await runAgent(promptText, prompt);
|
|
354
|
+
else { const r = await runAct(promptText, {server:state.config.server, model:state.config.model, history:[]}); console.log('\n'+c.white(r.assistantMessage.content)); }
|
|
355
|
+
process.exit(0);
|
|
526
356
|
}
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
const check = () => {
|
|
536
|
-
if (!busy && queue.length === 0) { console.log(c.muted('\nEncerrado.\n')); process.exit(0); }
|
|
537
|
-
setTimeout(check, 100);
|
|
538
|
-
};
|
|
539
|
-
check();
|
|
357
|
+
console.log(welcomeBox(VERSION, state.config.server));
|
|
358
|
+
rl = readline.createInterface({ input: process.stdin, output: process.stdout, prompt: makePrompt() });
|
|
359
|
+
rl.prompt();
|
|
360
|
+
rl.on('line', async (line) => {
|
|
361
|
+
const text = line.trim();
|
|
362
|
+
if (!text) { rl.prompt(); return; }
|
|
363
|
+
if (isSlash(text)) await handleSlash(text); else await sendPrompt(text);
|
|
364
|
+
rl.prompt();
|
|
540
365
|
});
|
|
366
|
+
rl.on('close', () => { console.log(c.muted('\nAté logo!')); process.exit(0); });
|
|
541
367
|
}
|
|
542
368
|
|
|
543
|
-
|
|
544
|
-
(async () => {
|
|
545
|
-
const flags = process.argv.slice(2);
|
|
546
|
-
const hasPrompt = flags.some(a => !a.startsWith('-'));
|
|
547
|
-
const helpFlag = flags.some(a => a === '-h' || a === '--help');
|
|
548
|
-
const versionFlag = flags.some(a => a === '-v' || a === '--version');
|
|
549
|
-
if (helpFlag) { printCliHelp(); process.exit(0); }
|
|
550
|
-
if (versionFlag) { console.log('PrimoCode v4.2 — Windows | macOS | Linux | Termux'); process.exit(0); }
|
|
551
|
-
if (hasPrompt) { await runOneShot(process.argv); process.exit(0); }
|
|
552
|
-
startInteractive();
|
|
553
|
-
})().catch((err) => {
|
|
554
|
-
// Silencia erro fatal
|
|
555
|
-
process.exit(1);
|
|
556
|
-
});
|
|
369
|
+
main().catch(e => { console.error(c.err(e.message||e)); process.exit(1); });
|