Repository navigation
Expand file tree
/
Copy pathuserInterface.js
More file actions
476 lines (442 loc) Β· 19.1 KB
/
Copy pathuserInterface.js
File metadata and controls
476 lines (442 loc) Β· 19.1 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
import inquirer from "inquirer";
import chalk from "chalk";
import { CONFIG } from "./config.js";
import FileManager from "./fileManager.js";
import CodeAnalyzer from "./codeAnalyzer.js";
import CodeGenerator from "./codeGenerator.js";
import DocumentationGenerator from "./documentationGenerator.js";
import LicenseManager from "./licenseManager.js";
import ProjectManagerAgent from "./ProjectManagerAgent.js";
import DevOpsAgent from "./DevOpsAgent.js";
import InternationalizationAgent from "./InternationalizationAgent.js";
import TesterAgent from "./TesterAgent.js";
import MarketingAgent from "./MarketingAgent.js";
import BusinessAnalystAgent from "./BusinessAnalystAgent.js";
import ProductOwnerAgent from "./ProductOwnerAgent.js";
import AppStorePublisherAgent from "./AppStorePublisherAgent.js";
import path from "path";
import ora from "ora";
import fs from "fs/promises";
import os from "os";
import { getResponse } from "./model.js";
const UserInterface = {
async promptForAction() {
return inquirer.prompt({
type: "list",
name: "action",
message: "What would you like to do next?",
choices: [
"π 1. Brainstorm README.md",
"π§ 2. Generate code",
"π 3. Detect missing dependencies",
"π 4. Run static code quality checks",
"π 5. Generate documentation",
"π 6. Optimize and refactor file",
"π¬ 7. Chat interface",
"π 8. Generate project documentation",
"π€ 9. Analyze code quality",
"π 10. Optimize project structure",
"β 11. Add new file",
"π€ 12. Run AI Agents",
"π 13. Security analysis",
"π§ͺ 14. Generate unit tests",
"π 15. Analyze performance",
"π 16. Generate landing page",
"π 17. Generate API documentation",
"π 18. Generate full project",
"π‘οΈ Change temperature",
"π€ Change model",
"π Login",
"πͺ Exit",
],
});
},
async promptForModel() {
const currentModel = await this.getModel();
return inquirer.prompt({
type: "list",
name: "model",
message: "Select model to use",
default: currentModel,
choices: [
"claude-sonnet-4-20250514",
"claude-sonnet-4-5",
"o3-mini",
"o4-mini",
"gpt-5-mini",
"deepseek-reasoner",
"deepseek-chat",
"gemini-2.0-flash-thinking-exp-01-21",
"gemini-2.5-flash",
"gemini-flash-latest",
"gemini-2.5-pro",
"grok-4-fast"
],
});
},
async setModel() {
const { model } = await this.promptForModel();
await FileManager.write(
path.join(os.homedir(), ".settings.json"),
JSON.stringify(
{
model,
temperature: await this.getTemperature(),
},
null,
2
)
);
console.log(chalk.green(`Model set to ${model}`));
},
async getModel() {
try {
const settings = await fs.readFile(path.join(os.homedir(), ".settings.json"), "utf8");
const { model } = JSON.parse(settings);
return model || "claude-4-sonnet-20250514";
} catch {
return "claude-4-sonnet-20250514";
}
},
async promptForFiles(files) {
return inquirer.prompt({
type: "checkbox",
name: "selectedFiles",
message: "Select files for processing:",
choices: files,
});
},
async promptForNewFile() {
return inquirer.prompt({
type: "input",
name: "newFile",
message: "Enter the name of the new file to create (include path if in subfolder):",
});
},
async promptForLanguage() {
return inquirer.prompt({
type: "list",
name: "language",
message: "Select the programming language:",
choices: Object.keys(CONFIG.languageConfigs),
});
},
async promptForTemperature() {
const currentTemperature = await this.getTemperature();
return inquirer.prompt({
type: "list",
name: "temperature",
message: "Select the temperature for AI generation",
default: currentTemperature.toString(),
choices: CONFIG.temperatureOptions.map(String),
});
},
async promptForLogin() {
return inquirer.prompt([
{
type: "input",
name: "email",
message: "Enter your email:",
},
{
type: "password",
name: "password",
message: "Enter your password:",
},
]);
},
async chatInterface(projectStructure, readme) {
const { input } = await inquirer.prompt({
type: "input",
name: "input",
message: "Enter your suggestion (or 'Enter' to quit):",
});
if (input.toLowerCase() === "") {
return { continue: false, updatedReadme: readme };
}
const filesToProcess = await FileManager.getFilesToProcess();
const { selectedFile } = await inquirer.prompt({
type: "list",
name: "selectedFile",
message: "Select a file to process with your suggestion:",
choices: filesToProcess,
});
const filePath = path.join(process.cwd(), selectedFile);
const fileContent = await FileManager.read(filePath);
const prompt = `
You are AutoCode, an automatic coding assistant. The user has made the following suggestion:
${input}
For the file: ${selectedFile}
Current file content:
${fileContent}
README.md content:
${readme}
Project structure:
${JSON.stringify(projectStructure, null, 2)}
Please generate or update the ${selectedFile} file to implement the features described in the README. Ensure the code is complete, functional, and follows best practices. Consider the project structure when making changes or adding new features. Reuse functionality from other modules and avoid duplicating code. Do not include any explanations or comments in your response, just provide the code.
`;
const spinner = ora("Processing AI request...").start();
try {
const response = await getResponse(prompt);
spinner.succeed("AI request completed");
await FileManager.write(filePath, CodeGenerator.cleanGeneratedCode(response.content[0].text));
console.log(chalk.green(`β
${selectedFile} has been updated with the extracted code snippet.`));
await CodeGenerator.calculateTokenStats(response.usage?.input_tokens, response.usage?.output_tokens);
} catch (error) {
spinner.fail("AI request failed");
console.error(chalk.red(`Error: ${error.message}`));
}
return { continue: true, updatedReadme: readme };
},
async generateAIAgents(projectStructure, readme) {
console.log(chalk.cyan("π€ Generating AI Agents..."));
// eslint-disable-next-line no-unused-vars
for (const [agentKey, agentConfig] of Object.entries(CONFIG.aiAgents)) {
console.log(chalk.yellow(`Generating ${agentConfig.name}...`));
await CodeGenerator.generateAIAgentCode(
agentConfig.name,
agentConfig.description,
projectStructure,
readme
);
}
console.log(chalk.green("β
All AI Agents have completed their tasks."));
},
async runAIAgents(projectStructure, readme) {
console.log(chalk.cyan("π€ Running AI Agents..."));
const agents = [
{ name: "Project Manager Agent", agent: ProjectManagerAgent },
{ name: "DevOps Agent", agent: DevOpsAgent },
{ name: "Internationalization Agent", agent: InternationalizationAgent },
{ name: "Tester Agent", agent: TesterAgent },
{ name: "Marketing Agent", agent: MarketingAgent },
{ name: "Business Analyst Agent", agent: BusinessAnalystAgent },
{ name: "Product Owner Agent", agent: ProductOwnerAgent },
{ name: "App Store Publisher Agent", agent: AppStorePublisherAgent },
];
const { selectedAgent } = await inquirer.prompt({
type: "list",
name: "selectedAgent",
message: "Select an AI Agent to run:",
choices: agents.map((a) => a.name),
});
const agentToRun = agents.find((a) => a.name === selectedAgent);
if (agentToRun) {
console.log(chalk.yellow(`Running ${agentToRun.name}...`));
await agentToRun.agent.run(projectStructure, readme);
console.log(chalk.green(`β
${agentToRun.name} has completed its tasks.`));
} else {
console.log(chalk.red("Invalid agent selection."));
}
},
async processFiles(files, readme, projectStructure, model, apiKey) {
const allFileContents = {};
for (const file of files) {
const filePath = path.join(process.cwd(), file);
allFileContents[file] = await FileManager.read(filePath);
}
for (const file of files) {
const filePath = path.join(process.cwd(), file);
console.log(chalk.cyan(`π§ Processing ${file}...`));
const currentContent = allFileContents[file];
const spinner = ora("Generating content...").start();
try {
const generatedContent = await CodeGenerator.generate(
readme,
currentContent,
file,
projectStructure,
allFileContents,
model,
apiKey
);
spinner.succeed("Content generated");
await FileManager.write(filePath, generatedContent);
if (!model && generatedContent.split("\n").length > CONFIG.maxFileLines) {
const { confirm } = await inquirer.prompt({
type: "confirm",
name: "confirm",
message: `The generated file ${file} is large. Do you want to split it?`,
default: true,
});
if (confirm) {
await CodeGenerator.splitLargeFile(filePath, generatedContent, projectStructure);
}
}
} catch (error) {
spinner.fail("Content generation failed");
console.error(chalk.red(`Error processing ${file}: ${error.message}`));
}
}
},
async handleAction(action, readme, readmePath, projectStructure) {
let continueExecution = true;
switch (action) {
case "π 1. Brainstorm README.md": {
console.log(chalk.cyan("π Updating README.md with new design ideas and considerations..."));
const spinner = ora("Generating updated README...").start();
try {
const updatedReadme = await CodeGenerator.updateReadme(readme, projectStructure);
spinner.succeed("README updated");
await FileManager.write(readmePath, updatedReadme);
readme = updatedReadme;
} catch (error) {
spinner.fail("README update failed");
console.error(chalk.red(`Error: ${error.message}`));
}
break;
}
case "π§ 2. Generate code": {
const filesToProcess = await FileManager.getFilesToProcess();
const { selectedFiles } = await UserInterface.promptForFiles(filesToProcess);
await this.processFiles(selectedFiles, readme, projectStructure);
console.log(chalk.green("β
AutoCode has successfully generated/updated your project files."));
break;
}
case "π 3. Detect missing dependencies":
await CodeAnalyzer.detectMissingDependencies(projectStructure);
break;
case "π 4. Run static code quality checks": {
const filesToCheck = await FileManager.getFilesToProcess();
const { selectedFiles } = await UserInterface.promptForFiles(filesToCheck);
for (const file of selectedFiles) {
if (file.includes("package.json")) continue;
const lintOutput = await CodeAnalyzer.runLintChecks(file);
if (lintOutput) {
await CodeAnalyzer.fixLintErrors(file, lintOutput, projectStructure);
await CodeAnalyzer.createMissingFilesFromLint(lintOutput, projectStructure);
}
}
break;
}
case "π 5. Generate documentation": {
const filesToDocument = await FileManager.getFilesToProcess();
const { selectedFiles } = await UserInterface.promptForFiles(filesToDocument);
for (const file of selectedFiles) {
const content = await FileManager.read(file);
await DocumentationGenerator.generate(file, content, projectStructure);
}
break;
}
case "π 6. Optimize and refactor file": {
const filesToOptimize = await FileManager.getFilesToProcess();
const { selectedFiles } = await UserInterface.promptForFiles(filesToOptimize);
for (const file of selectedFiles) {
await CodeGenerator.optimizeAndRefactorFile(file, projectStructure);
}
break;
}
case "π¬ 7. Chat interface": {
let chatContinue = true;
while (chatContinue) {
const result = await UserInterface.chatInterface(projectStructure, readme);
chatContinue = result.continue;
readme = result.updatedReadme;
}
break;
}
case "π 8. Generate project documentation":
await DocumentationGenerator.generateProjectDocumentation(projectStructure);
break;
case "π€ 9. Analyze code quality": {
const filesToAnalyze = await FileManager.getFilesToProcess();
const { selectedFiles } = await UserInterface.promptForFiles(filesToAnalyze);
for (const file of selectedFiles) {
await CodeAnalyzer.analyzeCodeQuality(file);
}
break;
}
case "π 10. Optimize project structure":
await CodeAnalyzer.optimizeProjectStructure(projectStructure);
break;
case "β 11. Add new file": {
const { newFile } = await UserInterface.promptForNewFile();
if (newFile) {
await CodeAnalyzer.addNewFile(path.join(process.cwd(), newFile));
}
break;
}
case "π€ 12. Run AI Agents":
await this.runAIAgents(projectStructure, readme);
break;
case "π 13. Security analysis": {
const filesToAnalyze = await FileManager.getFilesToProcess();
const { selectedFiles } = await UserInterface.promptForFiles(filesToAnalyze);
for (const file of selectedFiles) {
await CodeAnalyzer.checkSecurityVulnerabilities(file);
}
break;
}
case "π§ͺ 14. Generate unit tests": {
const filesToTest = await FileManager.getFilesToProcess();
const { selectedFiles } = await UserInterface.promptForFiles(filesToTest);
for (const file of selectedFiles) {
await CodeAnalyzer.generateUnitTests(file, projectStructure);
}
break;
}
case "π 15. Analyze performance": {
const filesToAnalyze = await FileManager.getFilesToProcess();
const { selectedFiles } = await UserInterface.promptForFiles(filesToAnalyze);
for (const file of selectedFiles) {
await CodeAnalyzer.analyzePerformance(file);
}
break;
}
case "π 16. Generate landing page":
await CodeGenerator.generateLandingPage(projectStructure, readme);
break;
case "π 17. Generate API documentation":
await DocumentationGenerator.generateAPIDocumentation(projectStructure, readme);
break;
case "π 18. Generate full project":
await CodeGenerator.generateFullProject(projectStructure, readme);
break;
case "π‘οΈ Change temperature":
await this.setTemperature();
break;
case "π€ Change model":
await this.setModel();
break;
case "π Login":
await this.handleLogin();
break;
case "πͺ Exit":
console.log(chalk.yellow("π Thanks for using AutoCode. See you next time!"));
continueExecution = false;
break;
}
return continueExecution;
},
async getTemperature() {
try {
const settings = await fs.readFile(path.join(os.homedir(), ".settings.json"), "utf8");
const { temperature } = JSON.parse(settings);
return temperature || 0.7;
} catch {
return 0.7;
}
},
async setTemperature() {
const { temperature } = await this.promptForTemperature();
const settings = {
temperature: parseFloat(temperature),
model: await this.getModel(),
};
await FileManager.write(path.join(os.homedir(), ".settings.json"), JSON.stringify(settings, null, 2));
console.log(chalk.green(`Temperature set to ${temperature}`));
},
async handleLogin() {
console.log(chalk.cyan("Please visit https://autocode.work to register if you haven't already."));
const { email, password } = await this.promptForLogin();
const loggedIn = await LicenseManager.login(email, password);
if (loggedIn) {
console.log(chalk.green("Login successful!"));
return true;
} else {
console.log(chalk.red("Login failed. Please try again."));
return false;
}
},
};
export default UserInterface;