sapper-iq 1.1.37 → 1.1.39

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.
@@ -1,483 +0,0 @@
1
- #!/usr/bin/env node
2
- import ollama from 'ollama';
3
- import fs from 'fs';
4
- import { spawn } from 'child_process';
5
- import chalk from 'chalk';
6
- import ora from 'ora';
7
- import readline from 'readline';
8
- import { fileURLToPath } from 'url';
9
- import { dirname, join } from 'path';
10
-
11
- const __filename = fileURLToPath(import.meta.url);
12
- const __dirname = dirname(__filename);
13
- const packageJson = JSON.parse(fs.readFileSync(join(__dirname, 'package.json'), 'utf8'));
14
- const CURRENT_VERSION = packageJson.version;
15
-
16
- const spinner = ora();
17
- const CONTEXT_FILE = '.sapper_context.json';
18
-
19
- let stepMode = false;
20
- let rl = readline.createInterface({
21
- input: process.stdin,
22
- output: process.stdout,
23
- terminal: true,
24
- historySize: 100
25
- });
26
-
27
- // Helper function to safely prompt for input
28
- async function safeQuestion(query) {
29
- return new Promise((resolve) => {
30
- process.stdout.write(query);
31
- rl.once('line', (answer) => {
32
- resolve(answer.trim());
33
- });
34
- });
35
- }
36
-
37
- // Helper function to check for updates
38
- async function checkForUpdates() {
39
- try {
40
- const response = await fetch('https://registry.npmjs.org/sapper-iq/latest');
41
- const data = await response.json();
42
- const latestVersion = data.version;
43
-
44
- if (latestVersion && latestVersion !== CURRENT_VERSION) {
45
- console.log(chalk.yellow('šŸ”„ UPDATE AVAILABLE!'));
46
- console.log(chalk.gray(` Current: v${CURRENT_VERSION}`));
47
- console.log(chalk.green(` Latest: v${latestVersion}`));
48
- console.log(chalk.cyan(' Run: npm update -g sapper-iq\n'));
49
- }
50
- } catch (error) {
51
- // Silently fail if update check fails
52
- }
53
- }
54
-
55
- // Helper function to update sapper
56
- async function updateSapper() {
57
- console.log(chalk.cyan('šŸ”„ Updating Sapper...'));
58
- const confirm = await safeQuestion(chalk.yellow('Continue with update? (y/n): '));
59
- if (confirm.toLowerCase() === 'y') {
60
- return new Promise((resolve) => {
61
- const proc = spawn('npm', ['update', '-g', 'sapper-iq'], {
62
- stdio: 'inherit'
63
- });
64
-
65
- proc.on('close', (code) => {
66
- recreateReadline();
67
- if (code === 0) {
68
- console.log(chalk.green('\nāœ… Sapper updated successfully!'));
69
- console.log(chalk.gray('Please restart Sapper to use the new version.\n'));
70
- } else {
71
- console.log(chalk.red('\nāŒ Update failed. Try manually: npm update -g sapper-iq\n'));
72
- }
73
- resolve();
74
- });
75
-
76
- proc.on('error', (err) => {
77
- recreateReadline();
78
- console.log(chalk.red(`\nāŒ Update error: ${err.message}\n`));
79
- resolve();
80
- });
81
- });
82
- }
83
- }
84
-
85
- // Helper function to recreate readline after shell commands
86
- function recreateReadline() {
87
- rl.close();
88
- rl = readline.createInterface({
89
- input: process.stdin,
90
- output: process.stdout,
91
- terminal: true,
92
- historySize: 100
93
- });
94
- }
95
-
96
- // --- Tool Logic ---
97
- const tools = {
98
- read: (path) => {
99
- try {
100
- return fs.readFileSync(path.trim(), 'utf8');
101
- } catch (error) {
102
- return `Error reading file: ${error.message}`;
103
- }
104
- },
105
- write: (path, content) => {
106
- try {
107
- fs.writeFileSync(path.trim(), content);
108
- return `Successfully saved changes to ${path}`;
109
- } catch (error) {
110
- return `Error writing file: ${error.message}`;
111
- }
112
- },
113
- mkdir: (path) => {
114
- try {
115
- fs.mkdirSync(path.trim(), { recursive: true });
116
- return `Directory created: ${path}`;
117
- } catch (error) {
118
- return `Error creating directory: ${error.message}`;
119
- }
120
- },
121
- shell: async (cmd) => {
122
- console.log(chalk.red.bold(`\n[SECURITY] Sapper wants to execute: `) + chalk.white(cmd));
123
- const confirm = await safeQuestion(chalk.yellow('Allow? (y/n): '));
124
- if (confirm.toLowerCase() === 'y') {
125
- return new Promise((resolve) => {
126
- // Use shell for complex commands with pipes, redirects, cd, &&, ||, etc
127
- const useShell = cmd.includes('&&') || cmd.includes('||') || cmd.includes('|') || cmd.includes('cd ') || cmd.includes('>');
128
-
129
- console.log(chalk.cyan(`\n[RUNNING] ${cmd}\n`));
130
-
131
- let proc;
132
- if (useShell) {
133
- // For complex commands, use shell
134
- proc = spawn('sh', ['-c', cmd], {
135
- stdio: 'inherit',
136
- shell: true
137
- });
138
- } else {
139
- // For simple commands, parse and use direct execution
140
- const parts = cmd.trim().split(/\s+/);
141
- const executable = parts[0];
142
- const args = parts.slice(1);
143
- proc = spawn(executable, args, {
144
- stdio: 'inherit',
145
- shell: false
146
- });
147
- }
148
-
149
- proc.on('close', (code) => {
150
- // Recreate readline after shell command completes
151
- recreateReadline();
152
- console.log(chalk.green(`\n[āœ“] Command completed with exit code ${code}\n`));
153
- resolve(`Command completed with exit code ${code}.`);
154
- });
155
-
156
- proc.on('error', (err) => {
157
- recreateReadline();
158
- console.log(chalk.red(`\n[āœ—] Command error: ${err.message}\n`));
159
- resolve(`Execution Error: ${err.message}`);
160
- });
161
- });
162
- }
163
- return "Command blocked by user.";
164
- },
165
- list: (path) => {
166
- try {
167
- return fs.readdirSync(path || '.').join('\n');
168
- } catch (error) {
169
- return `Error listing directory: ${error.message}`;
170
- }
171
- },
172
- search: (pattern) => {
173
- try {
174
- const { execSync } = require('child_process');
175
- const cmd = `grep -rnEi "${pattern.trim()}" . --exclude-dir=node_modules --exclude-dir=.git`;
176
- return execSync(cmd, { encoding: 'utf8' }) || "No matches found.";
177
- } catch (e) {
178
- return "No matches found.";
179
- }
180
- }
181
- };
182
-
183
- async function selectModel() {
184
- try {
185
- const localModels = await ollama.list();
186
- if (localModels.models.length === 0) {
187
- console.log(chalk.red('āŒ No Ollama models found!'));
188
- console.log(chalk.yellow('Please install at least one model:'));
189
- console.log(chalk.gray(' ollama pull llama2'));
190
- console.log(chalk.gray(' ollama pull codellama'));
191
- process.exit(1);
192
- }
193
- console.log(chalk.magenta.bold("\nAvailable Models:"));
194
- localModels.models.forEach((m, i) => console.log(`${i + 1}. ${chalk.white(m.name)}`));
195
- const choice = await safeQuestion(chalk.yellow('\nChoose model: '));
196
- const index = parseInt(choice) - 1;
197
- return localModels.models[index]?.name || localModels.models[0].name;
198
- } catch (error) {
199
- console.log(chalk.red('āŒ Failed to connect to Ollama!'));
200
- console.log(chalk.yellow('Please make sure Ollama is running:'));
201
- console.log(chalk.gray(' 1. Install Ollama: https://ollama.ai'));
202
- console.log(chalk.gray(' 2. Start Ollama: ollama serve'));
203
- console.log(chalk.gray(' 3. Install a model: ollama pull llama2'));
204
- console.log(chalk.red(`\nError details: ${error.message}`));
205
- process.exit(1);
206
- }
207
- }
208
-
209
- async function runSapper() {
210
- console.clear();
211
- console.log(chalk.cyan.bold(` SAPPER v${CURRENT_VERSION} | Multi-Tool Execution Mode`));
212
- console.log(chalk.gray("Commands: /reset, /session-info, /step, /version, /update, /help, exit\n"));
213
-
214
- // Check for updates on startup
215
- await checkForUpdates();
216
-
217
- // Early Ollama connectivity check
218
- console.log(chalk.gray('šŸ” Checking Ollama connection...'));
219
-
220
- let messages = [];
221
- if (fs.existsSync(CONTEXT_FILE)) {
222
- const resume = await safeQuestion(chalk.green('Resume previous session? (y/n): '));
223
- if (resume.toLowerCase() === 'y') {
224
- messages = JSON.parse(fs.readFileSync(CONTEXT_FILE, 'utf8'));
225
- }
226
- }
227
-
228
- const selectedModel = await selectModel();
229
-
230
- if (messages.length === 0) {
231
- messages = [{
232
- role: 'system',
233
- content: `You are Sapper, a senior software engineer AI assistant.
234
-
235
- **CRITICAL - Tool Format Rules:**
236
- - NEVER use JSON format
237
- - ONLY use this EXACT format for tools: [TOOL:TYPE:path:content]
238
- - Types: SHELL, READ, WRITE, MKDIR, LIST, SEARCH
239
-
240
- **Examples:**
241
- [TOOL:SHELL:npm install]
242
- [TOOL:READ:./package.json]
243
- [TOOL:WRITE:./app.js:console.log('hello')]
244
- [TOOL:MKDIR:./src/components]
245
- [TOOL:LIST:./src]
246
- [TOOL:SEARCH:function myFunction]
247
-
248
- **Shell Command Rules:**
249
- - For operations in a specific directory, chain with cd: cd /path/to/project && npm install
250
- - Use && to chain commands that depend on each other
251
- - Use | for pipes and > for redirects
252
- - Use relative paths after cd into a directory
253
- - Chain multiple commands: cd /path && npm install && npm run dev
254
- - User will specify which directory to work in - always use that path
255
-
256
- **Critical for npm/npx commands:**
257
- - ALWAYS use non-interactive flags (--typescript, --tailwind, --eslint, --no-git, etc)
258
- - Create projects with non-interactive flags
259
- - Install dependencies with: cd /path && npm install
260
- - Run apps with: cd /path && npm run dev
261
-
262
- **Workflow:**
263
- 1. For complex tasks, start with [PLAN:step1,step2,step3]
264
- 2. Execute tools immediately using the exact format above
265
- 3. You can provide MULTIPLE tools in one message
266
- 4. Always end with [SUMMARY:description of what was completed]
267
-
268
- **Important:**
269
- - No JSON responses
270
- - No markdown code blocks for tools
271
- - Only the exact bracket format: [TOOL:TYPE:path:content]
272
- - User will see live command output in terminal
273
- - Execute all tools needed to complete the task
274
- - Work flexibly with ANY directory the user specifies
275
- - Always chain cd with your command when working in a specific directory`
276
- }];
277
- }
278
-
279
- // Display working directory awareness
280
- console.log(chalk.yellow(`Working Directory: ${process.cwd()}\n`));
281
-
282
- const ask = () => {
283
- safeQuestion(chalk.blue.bold('\nIbrahim āž” ')).then(async (input) => {
284
- if (input.toLowerCase() === 'exit') process.exit();
285
- if (input.toLowerCase() === '/reset' || input.toLowerCase() === '/clear-session') {
286
- if (fs.existsSync(CONTEXT_FILE)) {
287
- const fileSize = fs.statSync(CONTEXT_FILE).size;
288
- console.log(chalk.yellow(`\nšŸ—‘ļø Clearing session (${(fileSize / 1024).toFixed(2)}KB)...`));
289
- fs.unlinkSync(CONTEXT_FILE);
290
- console.log(chalk.green('āœ… Session cleared! Starting fresh...\n'));
291
- } else {
292
- console.log(chalk.yellow('\nā„¹ļø No session to clear.\n'));
293
- }
294
- return runSapper();
295
- }
296
- if (input.toLowerCase() === '/session-info') {
297
- if (fs.existsSync(CONTEXT_FILE)) {
298
- const data = JSON.parse(fs.readFileSync(CONTEXT_FILE, 'utf8'));
299
- const fileSize = fs.statSync(CONTEXT_FILE).size;
300
- console.log(chalk.cyan(`\nšŸ“Š Session Info:`));
301
- console.log(chalk.gray(` Messages: ${data.length}`));
302
- console.log(chalk.gray(` File Size: ${(fileSize / 1024).toFixed(2)}KB`));
303
- console.log(chalk.gray(` Last Message: ${data[data.length - 1]?.role || 'N/A'}`));
304
- } else {
305
- console.log(chalk.yellow('\nā„¹ļø No active session.\n'));
306
- }
307
- return ask();
308
- }
309
- if (input.toLowerCase() === '/version') {
310
- console.log(chalk.cyan(`\nšŸ“¦ Sapper Version: v${CURRENT_VERSION}`));
311
- console.log(chalk.gray(` Node.js: ${process.version}`));
312
- console.log(chalk.gray(` Platform: ${process.platform}\n`));
313
- // Check for updates
314
- await checkForUpdates();
315
- return ask();
316
- }
317
- if (input.toLowerCase() === '/update') {
318
- await updateSapper();
319
- return ask();
320
- }
321
- if (input.toLowerCase() === '/step') {
322
- stepMode = !stepMode;
323
- console.log(chalk.yellow(`Step Mode is ${stepMode ? 'ON' : 'OFF'}`));
324
- return ask();
325
- }
326
- if (input.toLowerCase() === '/help') {
327
- console.log(chalk.cyan(`\nšŸ“š Sapper Commands:`));
328
- console.log(chalk.gray(` /reset or /clear-session - Start a new session`));
329
- console.log(chalk.gray(` /session-info - Show current session details`));
330
- console.log(chalk.gray(` /version - Show version and check for updates`));
331
- console.log(chalk.gray(` /update - Update Sapper to latest version`));
332
- console.log(chalk.gray(` /step - Toggle step-by-step mode`));
333
- console.log(chalk.gray(` /help - Show this help menu`));
334
- console.log(chalk.gray(` exit - Exit Sapper\n`));
335
- return ask();
336
- }
337
-
338
- // Check if user mentioned a directory and provide context
339
- const dirMatch = input.match(/\/Users\/[^\s]+|\/[a-zA-Z0-9_\/-]+/g);
340
- let contextMsg = input;
341
-
342
- if (dirMatch && dirMatch[0]) {
343
- const mentionedDir = dirMatch[0];
344
- try {
345
- if (fs.existsSync(mentionedDir) && fs.statSync(mentionedDir).isDirectory()) {
346
- const files = fs.readdirSync(mentionedDir).slice(0, 10).join(', ');
347
- contextMsg = `${input}\n\n[CONTEXT: Directory "${mentionedDir}" contains: ${files}${fs.readdirSync(mentionedDir).length > 10 ? '...' : ''}]`;
348
- }
349
- } catch (e) {
350
- // Silently ignore if directory doesn't exist
351
- }
352
- }
353
-
354
- messages.push({ role: 'user', content: contextMsg });
355
-
356
- let active = true;
357
- let iterations = 0;
358
- while (active && iterations < 30) {
359
- iterations++;
360
-
361
- if (stepMode) {
362
- const proceed = await safeQuestion(chalk.gray('\n[STEP-MODE] Press Enter to continue (or type "/stop"): '));
363
- if (proceed.toLowerCase() === '/stop') break;
364
- }
365
-
366
- spinner.stop();
367
- console.log(chalk.blue(`\n${selectedModel} is thinking...`));
368
-
369
- let response;
370
- try {
371
- response = await ollama.chat({
372
- model: selectedModel,
373
- messages,
374
- stream: true,
375
- options: { num_ctx: 16384 }
376
- });
377
- } catch (error) {
378
- console.log(chalk.red('\nāŒ Failed to communicate with Ollama!'));
379
- console.log(chalk.yellow('Possible issues:'));
380
- console.log(chalk.gray(' - Ollama service stopped'));
381
- console.log(chalk.gray(' - Model was removed'));
382
- console.log(chalk.gray(' - Network connection issue'));
383
- console.log(chalk.red(`Error: ${error.message}`));
384
- console.log(chalk.cyan('\nšŸ’” Try restarting Sapper or check Ollama status'));
385
- active = false;
386
- ask();
387
- return;
388
- }
389
-
390
- let msg = '';
391
- process.stdout.write(chalk.white('Sapper: '));
392
-
393
- try {
394
- for await (const chunk of response) {
395
- if (chunk.message && chunk.message.content) {
396
- process.stdout.write(chunk.message.content);
397
- msg += chunk.message.content;
398
- }
399
- }
400
- } catch (error) {
401
- console.log(chalk.red('\n\nāŒ Connection interrupted while streaming response!'));
402
- console.log(chalk.yellow(`Error: ${error.message}`));
403
- console.log(chalk.cyan('šŸ’” The conversation will continue, but you may want to restart Sapper'));
404
- msg += `\n[ERROR: Response interrupted - ${error.message}]`;
405
- }
406
- console.log();
407
-
408
- messages.push({ role: 'assistant', content: msg });
409
-
410
- const summaryMatch = msg.match(/\[SUMMARY:(.*?)\]/s);
411
- const toolMatches = [...msg.matchAll(/\[TOOL:(\w+):([^:\]]+):?([\s\S]*?)\]/g)];
412
-
413
- if (summaryMatch) {
414
- console.log(chalk.green.bold("\nāœ… MISSION COMPLETE:"));
415
- console.log(chalk.white(summaryMatch[1].trim()));
416
- active = false;
417
- continue;
418
- }
419
-
420
- if (toolMatches.length > 0) {
421
- for (const match of toolMatches) {
422
- const [_, name, path, content] = match;
423
- const toolName = name.toLowerCase();
424
- console.log(chalk.cyan(`\n[ACTION] Executing ${toolName} on: ${path}`));
425
-
426
- let result;
427
- try {
428
- if (toolName === 'shell') result = await tools.shell(path);
429
- else if (toolName === 'write') result = tools.write(path, content);
430
- else if (toolName === 'mkdir') result = tools.mkdir(path);
431
- else if (toolName === 'read') result = tools.read(path);
432
- else if (toolName === 'list') result = tools.list(path);
433
- else if (toolName === 'search') result = tools.search(path);
434
- else result = `Unknown tool: ${name}`;
435
- } catch (e) {
436
- result = `Error: ${e.message}`;
437
- }
438
-
439
- console.log(chalk.gray(`> Result: ${result.substring(0, 60)}...`));
440
- messages.push({ role: 'user', content: `TOOL_RESULT for ${path}: ${result}` });
441
- }
442
- fs.writeFileSync(CONTEXT_FILE, JSON.stringify(messages));
443
-
444
- // Add interrupt check after tool execution
445
- console.log(chalk.gray('\n[Press Enter to continue or type "/stop" to halt execution]'));
446
- const userChoice = await safeQuestion('');
447
- if (userChoice.toLowerCase() === '/stop') {
448
- console.log(chalk.yellow('\nā¹ļø Execution halted by user'));
449
- active = false;
450
- break;
451
- }
452
- } else {
453
- const planMatch = msg.match(/\[PLAN:(.*?)\]/);
454
- if (planMatch) {
455
- const feedback = await safeQuestion(chalk.yellow('\nModify plan or type "go": '));
456
- if (feedback.toLowerCase() === '/stop') { active = false; break; }
457
- messages.push({ role: 'user', content: feedback.toLowerCase() === 'go' ? "Plan approved. Proceed with all steps." : feedback });
458
- } else {
459
- active = false;
460
- }
461
- }
462
-
463
- // Safety check: if model is repeating itself, break the loop
464
- if (iterations > 5) {
465
- const recentMessages = messages.slice(-4);
466
- const isRepeating = recentMessages.every(m =>
467
- m.role === 'assistant' &&
468
- recentMessages[0].content &&
469
- m.content === recentMessages[0].content
470
- );
471
- if (isRepeating) {
472
- console.log(chalk.yellow('\nāš ļø Detected repetitive behavior, stopping execution'));
473
- active = false;
474
- }
475
- }
476
- }
477
- ask();
478
- });
479
- };
480
- ask();
481
- }
482
-
483
- runSapper();