-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.js
More file actions
1548 lines (1384 loc) · 44.7 KB
/
main.js
File metadata and controls
1548 lines (1384 loc) · 44.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env node
import inquirer from "inquirer";
import axios from "axios";
import fs from "fs";
import path from "path";
import { spawn } from "child_process";
import os from "os";
// Configuration storage path
const CONFIG_DIR = path.join(os.homedir(), ".ai-file-assistant");
const CONFIG_FILE = path.join(CONFIG_DIR, "config.json");
// Color definitions for beautiful UI
const colors = {
primary: "\x1b[36m", // Cyan
secondary: "\x1b[35m", // Magenta
success: "\x1b[32m", // Green
warning: "\x1b[33m", // Yellow
error: "\x1b[31m", // Red
info: "\x1b[34m", // Blue
highlight: "\x1b[95m", // Bright Magenta
reset: "\x1b[0m", // Reset
bold: "\x1b[1m", // Bold
dim: "\x1b[2m", // Dim
};
const PROVIDERS = {
ollama: {
name: "Ollama",
apiUrl: "http://localhost:11434/api/chat",
streamUrl: "http://localhost:11434/api/chat",
models: [
"llama3.2:3b",
"llama3.1:8b",
"codellama:7b",
"qwen2.5-coder:7b",
"custom",
],
defaultModel: "qwen2.5-coder:7b",
requiresApiKey: false,
color: colors.info,
},
mistral: {
name: "Mistral",
apiUrl: "https://api.mistral.ai/v1/chat/completions",
streamUrl: "https://api.mistral.ai/v1/chat/completions",
models: [
"mistral-tiny",
"mistral-small",
"mistral-medium",
"mistral-large-latest",
"codestral-latest",
"custom",
],
defaultModel: "mistral-small",
requiresApiKey: true,
apiKey: null,
color: colors.primary,
},
openai: {
name: "OpenAI",
apiUrl: "https://api.openai.com/v1/chat/completions",
streamUrl: "https://api.openai.com/v1/chat/completions",
models: [
"gpt-4",
"gpt-4-turbo",
"gpt-3.5-turbo",
"gpt-4o",
"o1-preview",
"custom",
],
defaultModel: "gpt-4o",
requiresApiKey: true,
apiKey: null,
color: colors.success,
},
claude: {
name: "Claude",
apiUrl: "https://api.anthropic.com/v1/messages",
streamUrl: "https://api.anthropic.com/v1/messages",
models: [
"claude-3-5-sonnet-20241022",
"claude-3-opus-20240229",
"claude-3-haiku-20240307",
"custom",
],
defaultModel: "claude-3-5-sonnet-20241022",
requiresApiKey: true,
apiKey: null,
color: colors.highlight,
},
google: {
name: "Google Gemini",
apiUrl: "https://generativelanguage.googleapis.com/v1beta/models",
streamUrl: "https://generativelanguage.googleapis.com/v1beta/models",
models: ["gemini-1.5-pro", "gemini-1.5-flash", "gemini-pro", "custom"],
defaultModel: "gemini-1.5-pro",
requiresApiKey: true,
apiKey: null,
color: colors.warning,
},
};
// Memory Buffer System - Simplified
class MemoryBuffer {
constructor() {
this.files = new Map(); // Store file contents
this.actions = []; // Store recent actions
this.conversations = []; // Store conversation history
}
storeFile(filePath, content) {
this.files.set(filePath, {
content,
lastModified: new Date().toISOString(),
size: content.length,
});
console.log(
colors.success +
"📄 " +
path.basename(filePath) +
" stored" +
colors.reset
);
}
getFile(filePath) {
return this.files.get(filePath);
}
listFiles() {
return Array.from(this.files.keys());
}
addAction(action, target, result) {
this.actions.push({
action,
target,
result,
timestamp: new Date().toISOString(),
});
// Keep only last 50 actions
if (this.actions.length > 50) {
this.actions = this.actions.slice(-50);
}
}
getContext() {
const recentActions = this.actions.slice(-5);
const availableFiles = Array.from(this.files.keys());
return {
recentActions,
availableFiles,
totalFiles: this.files.size,
// Add more detailed file info for the AI
fileDetails: Array.from(this.files.entries()).map(([filePath, info]) => ({
path: filePath,
name: path.basename(filePath),
size: info.size,
lastModified: info.lastModified,
})),
};
}
}
// Configuration Management
function loadConfig() {
try {
if (!fs.existsSync(CONFIG_DIR)) {
fs.mkdirSync(CONFIG_DIR, { recursive: true });
}
if (fs.existsSync(CONFIG_FILE)) {
const config = JSON.parse(fs.readFileSync(CONFIG_FILE, "utf-8"));
// Load saved API keys and models into PROVIDERS
for (const [providerKey, providerConfig] of Object.entries(
config.providers || {}
)) {
if (PROVIDERS[providerKey]) {
PROVIDERS[providerKey].apiKey = providerConfig.apiKey;
PROVIDERS[providerKey].selectedModel =
providerConfig.selectedModel || PROVIDERS[providerKey].defaultModel;
}
}
return config;
}
} catch (error) {
console.log(
colors.warning +
"Warning: Could not load config: " +
error.message +
colors.reset
);
}
return { providers: {}, preferences: {} };
}
function saveConfig(config) {
try {
if (!fs.existsSync(CONFIG_DIR)) {
fs.mkdirSync(CONFIG_DIR, { recursive: true });
}
fs.writeFileSync(CONFIG_FILE, JSON.stringify(config, null, 2));
console.log(
colors.success + "Configuration saved successfully" + colors.reset
);
} catch (error) {
console.log(
colors.error + "Could not save config: " + error.message + colors.reset
);
}
}
function updateProviderConfig(provider, apiKey, model) {
const config = loadConfig();
if (!config.providers) config.providers = {};
config.providers[provider] = {
apiKey: apiKey,
selectedModel: model,
};
saveConfig(config);
PROVIDERS[provider].apiKey = apiKey;
PROVIDERS[provider].selectedModel = model;
}
// Special Tokens for Unvibe Commands
const UNVIBE_TOKENS = {
READ: "<|unvibe_read|>",
DELETE: "<|unvibe_delete|>",
EDIT: "<|unvibe_edit|>",
CREATE_FILE: "<|unvibe_create_file|>",
CREATE_FOLDER: "<|unvibe_create_folder|>",
RENAME: "<|unvibe_rename|>",
TERMINAL: "<|unvibe_terminal|>",
LIST: "<|unvibe_list|>",
SEARCH: "<|unvibe_search|>",
END: "<|unvibe_end|>",
SEPARATOR: "<|parameter_separator|>",
};
// Parse special tokens from AI response
function parseUnvibeTokens(text) {
const commands = [];
// Only parse if we have potential complete tokens
if (!text.includes("<|unvibe_") || !text.includes("<|/unvibe_")) {
return commands;
}
// Look for complete token patterns: <|token|>content<|parameter_separator|>target<|/token|>
const tokenPattern =
/<\|unvibe_(\w+)\|>([\s\S]*?)<\|parameter_separator\|>([\s\S]*?)<\|\/unvibe_\1\|>/g;
let match;
while ((match = tokenPattern.exec(text)) !== null) {
const action = match[1];
const parameter = match[2].trim();
const target = match[3].trim();
commands.push({
action,
parameter,
target,
fullMatch: match[0],
});
}
if (commands.length > 0) {
console.log(
colors.info +
"Found " +
commands.length +
" complete token(s)" +
colors.reset
);
// Debug: show what tokens were found
commands.forEach((cmd, index) => {
console.log(
colors.dim +
`Token ${index + 1}: ${cmd.action} -> ${cmd.target}` +
colors.reset
);
});
}
return commands;
}
// Execute Unvibe commands
async function executeUnvibeCommand(command, memory) {
const { action, parameter, target } = command;
console.log(
colors.info +
"Executing: " +
action.toUpperCase() +
" " +
(action === "terminal" ? parameter : target) +
colors.reset
);
try {
switch (action) {
case "read":
return await executeRead(target, memory);
case "delete":
return await executeDelete(target, memory);
case "edit":
return await executeEdit(target, parameter, memory);
case "create_file":
return await executeCreateFile(target, parameter, memory);
case "create_folder":
return await executeCreateFolder(target, memory);
case "rename":
return await executeRename(parameter, target, memory);
case "terminal":
// For terminal commands, parameter is the command, target is the description
return await executeTerminal(parameter, memory);
case "list":
return await executeList(target, memory);
case "search":
return await executeSearch(parameter, target, memory);
default:
return { success: false, message: "Unknown action: " + action };
}
} catch (error) {
console.log(
colors.error +
"Error executing " +
action +
": " +
error.message +
colors.reset
);
return { success: false, message: error.message };
}
}
// Command implementations
async function executeRead(filePath, memory) {
try {
// Try to resolve file path
const resolvedPath = resolveFilePath(filePath);
if (!fs.existsSync(resolvedPath)) {
return { success: false, message: "File not found: " + filePath };
}
const content = fs.readFileSync(resolvedPath, "utf-8");
memory.storeFile(resolvedPath, content);
memory.addAction("read", filePath, { success: true });
console.log(
colors.success +
"📄 " +
path.basename(resolvedPath) +
" read (" +
content.length +
" chars)" +
colors.reset
);
return {
success: true,
message: "File read successfully",
content,
path: resolvedPath,
};
} catch (error) {
return { success: false, message: error.message };
}
}
async function executeDelete(filePath, memory) {
try {
const resolvedPath = resolveFilePath(filePath);
if (!fs.existsSync(resolvedPath)) {
return { success: false, message: "File not found: " + filePath };
}
const stats = fs.statSync(resolvedPath);
if (stats.isDirectory()) {
fs.rmSync(resolvedPath, { recursive: true, force: true });
} else {
fs.unlinkSync(resolvedPath);
}
memory.addAction("delete", filePath, { success: true });
console.log(
colors.success +
"🗑️ " +
path.basename(resolvedPath) +
" deleted" +
colors.reset
);
return { success: true, message: "Deleted successfully" };
} catch (error) {
return { success: false, message: error.message };
}
}
async function executeEdit(filePath, newContent, memory) {
try {
const resolvedPath = resolveFilePath(filePath);
// Create directories if they don't exist
const dir = path.dirname(resolvedPath);
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true });
}
fs.writeFileSync(resolvedPath, newContent, "utf-8");
memory.storeFile(resolvedPath, newContent);
memory.addAction("edit", filePath, { success: true });
console.log(
colors.success +
"✏️ " +
path.basename(resolvedPath) +
" edited (" +
newContent.length +
" chars)" +
colors.reset
);
return { success: true, message: "File edited successfully" };
} catch (error) {
return { success: false, message: error.message };
}
}
async function executeCreateFile(filePath, content, memory) {
try {
const resolvedPath = resolveFilePath(filePath);
// Create directories if they don't exist
const dir = path.dirname(resolvedPath);
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true });
}
fs.writeFileSync(resolvedPath, content, "utf-8");
memory.storeFile(resolvedPath, content);
memory.addAction("create_file", filePath, { success: true });
console.log(
colors.success +
"📝 " +
path.basename(resolvedPath) +
" created (" +
content.length +
" chars)" +
colors.reset
);
return { success: true, message: "File created successfully" };
} catch (error) {
return { success: false, message: error.message };
}
}
async function executeCreateFolder(folderPath, memory) {
try {
const resolvedPath = resolveFilePath(folderPath);
if (!fs.existsSync(resolvedPath)) {
fs.mkdirSync(resolvedPath, { recursive: true });
}
memory.addAction("create_folder", folderPath, { success: true });
console.log(
colors.success +
"📁 " +
path.basename(resolvedPath) +
" created" +
colors.reset
);
return { success: true, message: "Folder created successfully" };
} catch (error) {
return { success: false, message: error.message };
}
}
async function executeRename(oldPath, newPath, memory) {
try {
const resolvedOldPath = resolveFilePath(oldPath);
const resolvedNewPath = resolveFilePath(newPath);
if (!fs.existsSync(resolvedOldPath)) {
return { success: false, message: "File not found: " + oldPath };
}
fs.renameSync(resolvedOldPath, resolvedNewPath);
memory.addAction("rename", oldPath + " -> " + newPath, { success: true });
console.log(
colors.success +
"🔄 " +
path.basename(oldPath) +
" → " +
path.basename(newPath) +
colors.reset
);
return { success: true, message: "Renamed successfully" };
} catch (error) {
return { success: false, message: error.message };
}
}
async function executeTerminal(command, memory) {
return new Promise((resolve) => {
// Clean the command - remove any description prefixes that might have been parsed incorrectly
let cleanCommand = command.replace(
/^(Installing dependencies|Starting development server|Creating React app|Running command|Executing)\s*/,
""
);
// Additional cleaning for common issues
cleanCommand = cleanCommand.replace(
/^(Creating React app|Installing dependencies|Starting development server)\s*$/,
""
);
// If command looks like a description rather than actual command, try to infer the command
if (cleanCommand === "Creating React app" || cleanCommand === "") {
cleanCommand = "npx create-react-app calculator-app";
}
if (cleanCommand === "Installing dependencies") {
cleanCommand = "cd calculator-app && npm install";
}
if (cleanCommand === "Starting development server") {
cleanCommand = "cd calculator-app && npm start";
}
console.log(colors.info + "→ " + cleanCommand + colors.reset);
const child = spawn(cleanCommand, [], {
shell: true,
stdio: ["inherit", "pipe", "pipe"],
cwd: process.cwd(),
});
let output = "";
let error = "";
child.stdout.on("data", (data) => {
const text = data.toString();
output += text;
// Show more useful output for common operations
if (
text.includes("error") ||
text.includes("Error") ||
text.includes("SUCCESS") ||
text.includes("Done") ||
text.includes("installed") ||
text.includes("dependencies") ||
text.includes("Local:") ||
text.includes("http://") ||
text.includes("Creating a new React app") ||
text.includes("Installing packages") ||
text.includes("Happy hacking!")
) {
process.stdout.write(colors.dim + text.trim() + colors.reset + "\n");
}
});
child.stderr.on("data", (data) => {
const text = data.toString();
error += text;
// Show errors but keep them concise
if (text.trim()) {
process.stderr.write(
colors.error + "⚠ " + text.trim() + colors.reset + "\n"
);
}
});
child.on("close", (code) => {
memory.addAction("terminal", cleanCommand, {
success: code === 0,
output,
error,
});
if (code === 0) {
console.log(colors.success + "✓ Command completed" + colors.reset);
resolve({
success: true,
message: "Command executed successfully",
output,
});
} else {
console.log(
colors.error +
"✗ Command failed (exit code " +
code +
")" +
colors.reset
);
resolve({
success: false,
message: "Command failed with code " + code,
error,
});
}
});
});
}
async function executeList(target, memory) {
try {
const resolvedPath = target ? resolveFilePath(target) : process.cwd();
if (!fs.existsSync(resolvedPath)) {
return { success: false, message: "Path not found: " + target };
}
const stats = fs.statSync(resolvedPath);
if (!stats.isDirectory()) {
return { success: false, message: "Not a directory: " + target };
}
const entries = fs.readdirSync(resolvedPath, { withFileTypes: true });
const files = entries
.filter((entry) => entry.isFile())
.map((entry) => entry.name);
const folders = entries
.filter((entry) => entry.isDirectory())
.map((entry) => entry.name);
memory.addAction("list", target || ".", { success: true });
console.log(
colors.success +
"📁 " +
path.basename(resolvedPath) +
" (" +
(files.length + folders.length) +
" items)" +
colors.reset
);
return {
success: true,
message: "Listed directory contents",
files,
folders,
path: resolvedPath,
};
} catch (error) {
return { success: false, message: error.message };
}
}
async function executeSearch(query, target, memory) {
try {
const searchPath = target ? resolveFilePath(target) : process.cwd();
const results = [];
function searchInFile(filePath) {
try {
const content = fs.readFileSync(filePath, "utf-8");
const lines = content.split("\n");
const matches = [];
lines.forEach((line, index) => {
if (line.toLowerCase().includes(query.toLowerCase())) {
matches.push({
line: index + 1,
content: line.trim(),
});
}
});
if (matches.length > 0) {
results.push({
file: filePath,
matches,
});
}
} catch (err) {
// Skip files that can't be read
}
}
function searchRecursive(dir) {
const entries = fs.readdirSync(dir, { withFileTypes: true });
for (const entry of entries) {
if (entry.name.startsWith(".") || entry.name === "node_modules")
continue;
const fullPath = path.join(dir, entry.name);
if (entry.isFile()) {
searchInFile(fullPath);
} else if (entry.isDirectory()) {
searchRecursive(fullPath);
}
}
}
if (fs.statSync(searchPath).isFile()) {
searchInFile(searchPath);
} else {
searchRecursive(searchPath);
}
memory.addAction("search", '"' + query + '" in ' + (target || "."), {
success: true,
});
console.log(
colors.success +
"🔍 " +
results.length +
' files contain "' +
query +
'"' +
colors.reset
);
return {
success: true,
message: "Search completed",
results,
query,
};
} catch (error) {
return { success: false, message: error.message };
}
}
// Helper function to resolve file paths
function resolveFilePath(filePath) {
if (path.isAbsolute(filePath)) {
return filePath;
}
return path.resolve(process.cwd(), filePath);
}
// Helper function to detect project type
function detectProjectType(directory = process.cwd()) {
try {
const packageJsonPath = path.join(directory, "package.json");
if (fs.existsSync(packageJsonPath)) {
const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, "utf-8"));
// Check for React
if (
packageJson.dependencies?.react ||
packageJson.devDependencies?.react
) {
return "react";
}
// Check for Next.js
if (packageJson.dependencies?.next || packageJson.devDependencies?.next) {
return "nextjs";
}
// Check for Vue
if (packageJson.dependencies?.vue || packageJson.devDependencies?.vue) {
return "vue";
}
// Check for Angular
if (
packageJson.dependencies?.["@angular/core"] ||
packageJson.devDependencies?.["@angular/core"]
) {
return "angular";
}
// Check for Express/Node.js server
if (
packageJson.dependencies?.express ||
packageJson.dependencies?.fastify
) {
return "node-server";
}
return "node";
}
// Check for other project indicators
if (
fs.existsSync(path.join(directory, "requirements.txt")) ||
fs.existsSync(path.join(directory, "pyproject.toml"))
) {
return "python";
}
if (fs.existsSync(path.join(directory, "Cargo.toml"))) {
return "rust";
}
if (fs.existsSync(path.join(directory, "go.mod"))) {
return "go";
}
return "generic";
} catch (error) {
return "generic";
}
}
// Helper function to check if dependencies need to be installed
function needsDependencyInstall(directory = process.cwd()) {
const packageJsonPath = path.join(directory, "package.json");
const nodeModulesPath = path.join(directory, "node_modules");
if (fs.existsSync(packageJsonPath) && !fs.existsSync(nodeModulesPath)) {
return true;
}
return false;
}
// Helper function to get smart install command based on project type
function getSmartInstallCommand(projectType, directory = process.cwd()) {
const hasYarnLock = fs.existsSync(path.join(directory, "yarn.lock"));
const hasPnpmLock = fs.existsSync(path.join(directory, "pnpm-lock.yaml"));
let packageManager = "npm";
if (hasPnpmLock) packageManager = "pnpm";
else if (hasYarnLock) packageManager = "yarn";
switch (projectType) {
case "react":
case "nextjs":
case "vue":
case "angular":
case "node":
return `${packageManager} install`;
case "python":
return "pip install -r requirements.txt";
case "rust":
return "cargo build";
case "go":
return "go mod download";
default:
return null;
}
}
// Helper function to check and execute tokens from buffer
async function checkAndExecuteTokens(
buffer,
executedCommands,
memory,
onCommand
) {
const commands = parseUnvibeTokens(buffer);
let updatedBuffer = buffer;
let executionContext = "";
for (const command of commands) {
const commandKey = command.fullMatch;
if (!executedCommands.has(commandKey)) {
executedCommands.add(commandKey);
const result = await executeUnvibeCommand(command, memory);
// Create immediate context feedback for the AI
const contextUpdate = `[EXECUTION_RESULT: ${command.action.toUpperCase()} ${
command.target
} - ${result.success ? "SUCCESS" : "FAILED: " + result.message}]`;
executionContext += contextUpdate + "\n";
if (onCommand) onCommand(command, result, contextUpdate);
// Remove executed command from buffer to avoid re-execution
updatedBuffer = updatedBuffer.replace(command.fullMatch, contextUpdate);
}
}
return { buffer: updatedBuffer, context: executionContext };
}
// Streaming AI Response Handler
async function streamAIResponse(prompt, provider, memory, onToken, onCommand) {
const selectedModel =
PROVIDERS[provider].selectedModel || PROVIDERS[provider].defaultModel;
try {
let buffer = "";
const executedCommands = new Set();
if (provider === "ollama") {
const response = await axios({
method: "post",
url: PROVIDERS.ollama.streamUrl,
data: {
model: selectedModel,
messages: [{ role: "user", content: prompt }],
stream: true,
options: {
temperature: 0.3,
top_p: 0.8,
},
},
responseType: "stream",
});
response.data.on("data", async (chunk) => {
const lines = chunk
.toString()
.split("\n")
.filter((line) => line.trim());
for (const line of lines) {
try {
const data = JSON.parse(line);
if (data.message && data.message.content) {
const content = data.message.content;
buffer += content;
// Call onToken callback
if (onToken) onToken(content);
// Check for unvibe tokens periodically (every few tokens or when closing tag detected)
if (buffer.includes("<|/unvibe_")) {
const result = await checkAndExecuteTokens(
buffer,
executedCommands,
memory,
onCommand
);
buffer = result.buffer;
// Inject execution context back into the stream so AI knows what happened
if (result.context && onToken) {
onToken(result.context);
}
}
}
} catch (e) {
// Skip invalid JSON lines
}
}
});
return new Promise((resolve) => {
response.data.on("end", () => {
resolve(buffer);
});
});
} else if (provider === "openai") {
const response = await axios({
method: "post",
url: PROVIDERS.openai.streamUrl,
headers: {
Authorization: "Bearer " + PROVIDERS.openai.apiKey,
"Content-Type": "application/json",
},
data: {
model: selectedModel,
messages: [{ role: "user", content: prompt }],
stream: true,
temperature: 0.3,
},
responseType: "stream",
});
response.data.on("data", async (chunk) => {
const lines = chunk
.toString()
.split("\n")
.filter((line) => line.trim());
for (const line of lines) {
if (line.startsWith("data: ")) {
const data = line.slice(6);
if (data === "[DONE]") return;
try {
const parsed = JSON.parse(data);
const content = parsed.choices?.[0]?.delta?.content;
if (content) {
buffer += content;
// Call onToken callback
if (onToken) onToken(content);
// Check for unvibe tokens periodically (when closing tag detected)
if (buffer.includes("<|/unvibe_")) {
const result = await checkAndExecuteTokens(
buffer,
executedCommands,
memory,
onCommand