-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathagent.js
More file actions
1648 lines (1462 loc) · 65.8 KB
/
Copy pathagent.js
File metadata and controls
1648 lines (1462 loc) · 65.8 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
/**
* Agent Mode Runtime
* Multi-pass agentic generation with tool calling
* Enhanced with model-specific prompts and surgical edit tools
*/
import { state } from './state.js';
import { security } from './security.js';
import { thinking, devLog, devError } from './thinking.js';
import { analyzeProjectHealth, generateCodeMap, estimateTokens, formatTokenCount } from './tokens.js';
import { checkModelToolSupport } from './ai.js';
import { getApiKey } from './job-queue.js';
import { getModelProfile, getPromptStyle } from './model-profiles.js';
import { applyEdits, validateEdits, validateFileSyntax, validateAndRepairFiles, analyzeDomReferences } from './file-ops.js';
import { getPreviewErrors, clearPreviewErrors, renderProject } from './renderer.js';
import { TECHNICAL_GUIDELINES, getLibraryInstructions } from './protocol-data.js';
import { formatLibraryDocs, detectLibraries, analyzeLibraryError, searchLibraries, getCategories } from './library-catalog.js';
import {
buildAgentSystemPrompt as buildAgentSystemPromptBase,
buildAgentUserMessage,
TECHNOLOGY_STACK,
IMAGE_HANDLING,
INTERACTIVE_FEATURES
} from './prompts.js';
// Agent configuration
const MAX_ITERATIONS = 10;
const API_TIMEOUT = 180000;
// Starter template for new projects - minimal foundation
// No styling frameworks are forced - models choose what they need
const STARTER_FILES = [
{
path: 'index.html',
content: `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>New Project</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<script src="script.js"></script>
</body>
</html>`
},
{
path: 'style.css',
content: `/* Add your styles here */`
},
{
path: 'script.js',
content: `// Add your JavaScript here`
}
];
// Working files state during agent execution
let workingFiles = [];
let iterationCount = 0;
// Validation tracking - ensures agent checks for errors before finishing
let validationState = {
errorCheckPerformed: false, // True if check_dom or get_preview_errors was called
previewRendered: false, // True if preview_site was called
lastDomCheckResult: null, // Result of last check_dom call
lastPreviewErrors: null, // Result of last get_preview_errors call
filesModifiedSinceCheck: false // True if files changed after last error check
};
/**
* Available tools for the agent
* Enhanced with edit_file, read_file_section, and validate_file
*/
const TOOLS = [
{
type: "function",
function: {
name: "read_file",
description: "Read the full content of a file in the project",
parameters: {
type: "object",
properties: {
path: {
type: "string",
description: "The file path to read (e.g., 'index.html', 'styles.css')"
}
},
required: ["path"]
}
}
},
{
type: "function",
function: {
name: "read_file_section",
description: "Read a specific section of a file by line numbers. Use for large files to avoid reading everything.",
parameters: {
type: "object",
properties: {
path: {
type: "string",
description: "The file path to read"
},
start_line: {
type: "number",
description: "Starting line number (1-indexed)"
},
end_line: {
type: "number",
description: "Ending line number (inclusive)"
}
},
required: ["path", "start_line", "end_line"]
}
}
},
{
type: "function",
function: {
name: "write_file",
description: "Create or overwrite a file with new content. Use for new files or complete rewrites.",
parameters: {
type: "object",
properties: {
path: {
type: "string",
description: "The file path to write (e.g., 'index.html', 'components/header.js')"
},
content: {
type: "string",
description: "The complete file content to write"
}
},
required: ["path", "content"]
}
}
},
{
type: "function",
function: {
name: "edit_file",
description: "Make surgical edits to a file using search/replace. More efficient than rewriting entire file. Use for small to medium changes.",
parameters: {
type: "object",
properties: {
path: {
type: "string",
description: "The file path to edit"
},
edits: {
type: "array",
description: "Array of search/replace operations",
items: {
type: "object",
properties: {
search: {
type: "string",
description: "Exact text to find (must be unique in file)"
},
replace: {
type: "string",
description: "Text to replace it with"
}
},
required: ["search", "replace"]
}
}
},
required: ["path", "edits"]
}
}
},
{
type: "function",
function: {
name: "delete_file",
description: "Delete a file from the project",
parameters: {
type: "object",
properties: {
path: {
type: "string",
description: "The file path to delete"
}
},
required: ["path"]
}
}
},
{
type: "function",
function: {
name: "list_files",
description: "List all files in the project with their sizes and line counts",
parameters: {
type: "object",
properties: {},
required: []
}
}
},
{
type: "function",
function: {
name: "search_files",
description: "Search for text across all project files",
parameters: {
type: "object",
properties: {
query: {
type: "string",
description: "Text or regex pattern to search for"
}
},
required: ["query"]
}
}
},
{
type: "function",
function: {
name: "validate_file",
description: "Check if a file is valid (parseable HTML/JS/CSS). Call after edits to verify changes.",
parameters: {
type: "object",
properties: {
path: {
type: "string",
description: "The file path to validate"
}
},
required: ["path"]
}
}
},
{
type: "function",
function: {
name: "preview_site",
description: "Render the current project files in the preview and return any JavaScript errors or console messages. Use this to test your changes and catch runtime errors.",
parameters: {
type: "object",
properties: {},
required: []
}
}
},
{
type: "function",
function: {
name: "get_preview_errors",
description: "Get any JavaScript errors or console.error/warn messages from the most recent preview render. Call after preview_site to check for runtime issues.",
parameters: {
type: "object",
properties: {},
required: []
}
}
},
{
type: "function",
function: {
name: "check_dom",
description: "Statically analyze HTML and JavaScript files to detect DOM element mismatches. Finds when JavaScript references elements (via getElementById, querySelector) that don't exist in HTML. Call this BEFORE finish() to catch common runtime errors.",
parameters: {
type: "object",
properties: {},
required: []
}
}
},
{
type: "function",
function: {
name: "get_library_docs",
description: "Get documentation, CDN links, usage examples, and troubleshooting info for a library. Use this when you need to use a library you're not familiar with, or when debugging library-related errors. Available libraries include: Three.js, Chart.js, GSAP, PixiJS, Leaflet, React, Vue, D3, Tone.js, Zod, Day.js, and more. Also covers Web APIs like localStorage, IndexedDB, and WebAudio.",
parameters: {
type: "object",
properties: {
library: {
type: "string",
description: "Library name (e.g., 'three', 'chart.js', 'gsap', 'localStorage')"
},
query_type: {
type: "string",
enum: ["overview", "usage", "errors", "cdn"],
description: "Type of information needed: 'overview' (summary), 'usage' (examples), 'errors' (troubleshooting), 'cdn' (import links)"
}
},
required: ["library"]
}
}
},
{
type: "function",
function: {
name: "search_libraries",
description: "Search for libraries by name, category, or description. Use when you're not sure which library to use for a task. Categories include: 3d, 2d, animation, charts, audio, maps, ui-framework, styling, web-api, validation, utility.",
parameters: {
type: "object",
properties: {
query: {
type: "string",
description: "Search query (library name, category, or description)"
}
},
required: ["query"]
}
}
},
{
type: "function",
function: {
name: "validate_and_preview",
description: "RECOMMENDED before finish(). Runs comprehensive validation: checks DOM references, validates file syntax, and renders preview to catch runtime errors. Returns all issues in one response. Call this before finish() to ensure your code works.",
parameters: {
type: "object",
properties: {},
required: []
}
}
},
{
type: "function",
function: {
name: "finish",
description: "Signal that all changes are complete and ready to commit. IMPORTANT: Will fail if you haven't called check_dom(), validate_and_preview(), or get_preview_errors() first, or if there are unresolved errors.",
parameters: {
type: "object",
properties: {
summary: {
type: "string",
description: "Brief summary of all changes made"
}
},
required: ["summary"]
}
}
}
];
/**
* Validate the project before allowing finish
* Ensures we have a complete, working website
* CRITICAL: Now enforces error checking before finish
*/
function validateProjectBeforeFinish() {
const issues = [];
const criticalIssues = [];
// 0. CRITICAL: Check if error validation was performed
// The agent MUST call check_dom or get_preview_errors before finishing
if (!validationState.errorCheckPerformed) {
devLog('finish: BLOCKED - no error check performed');
return {
valid: false,
issues: ['You must check for errors before calling finish()'],
hint: 'Call check_dom() to verify element IDs match between HTML and JS, or call preview_site() followed by get_preview_errors() to check for runtime errors.'
};
}
// 0b. Check if files were modified AFTER the last error check
if (validationState.filesModifiedSinceCheck) {
devLog('finish: BLOCKED - files modified after last error check');
return {
valid: false,
issues: ['Files were modified after the last error check'],
hint: 'Call check_dom() or get_preview_errors() again to validate your recent changes before calling finish().'
};
}
// 0c. Check if there are UNRESOLVED errors from the last check
if (validationState.lastDomCheckResult && !validationState.lastDomCheckResult.valid) {
const domIssues = validationState.lastDomCheckResult.issues || [];
for (const issue of domIssues) {
let msg = `UNRESOLVED DOM mismatch in ${issue.file}: ${issue.ids.join(', ')}`;
if (issue.suggestions && Object.keys(issue.suggestions).length > 0) {
const firstSuggestion = Object.entries(issue.suggestions)[0];
msg += ` (did you mean "${firstSuggestion[1][0]}" instead of "${firstSuggestion[0]}"?)`;
}
criticalIssues.push(msg);
}
devLog('finish: BLOCKED - unresolved DOM mismatches:', domIssues.length);
}
// 0d. Check if there are UNRESOLVED preview errors
if (validationState.lastPreviewErrors && validationState.lastPreviewErrors.hasErrors) {
const errors = validationState.lastPreviewErrors.errors || [];
const consoleErrors = validationState.lastPreviewErrors.consoleErrors || [];
for (const err of errors) {
criticalIssues.push(`UNRESOLVED runtime error: ${err.message} (line ${err.line || '?'})`);
}
for (const err of consoleErrors) {
criticalIssues.push(`UNRESOLVED console error: ${err.message}`);
}
devLog('finish: BLOCKED - unresolved preview errors:', errors.length + consoleErrors.length);
}
// If there are unresolved errors from checks, block immediately
if (criticalIssues.length > 0) {
return {
valid: false,
issues: criticalIssues,
hint: 'Fix the errors reported by check_dom() or get_preview_errors() before calling finish(). DOM mismatches and runtime errors will cause the site to fail.'
};
}
// 1. Check if index.html exists
const indexFile = workingFiles.find(f => f.path === 'index.html' || f.path === './index.html');
if (!indexFile) {
issues.push('index.html is missing - this is required as the main entry point');
return {
valid: false,
issues,
hint: 'Create index.html with write_file before calling finish'
};
}
// 2. Check if index.html has meaningful content (not just the starter template)
const indexContent = indexFile.content;
const contentLength = indexContent.length;
const hasBody = /<body[^>]*>[\s\S]*<\/body>/i.test(indexContent);
const hasContent = indexContent.includes('<h1') || indexContent.includes('<main') ||
indexContent.includes('<section') || indexContent.includes('<div class') ||
indexContent.includes('<canvas');
if (contentLength < 500 || !hasBody || !hasContent) {
issues.push('index.html appears to have minimal content - ensure you\'ve added the requested features');
}
// 3. Validate HTML syntax
const htmlValidation = validateFileSyntax('index.html', indexContent);
if (!htmlValidation.valid) {
criticalIssues.push(`index.html has syntax errors: ${htmlValidation.error}`);
}
// 4. Check for referenced files that don't exist
const cssLinks = indexContent.match(/href=["']([^"']+\.css)["']/gi) || [];
const jsScripts = indexContent.match(/src=["']([^"']+\.js)["']/gi) || [];
for (const link of cssLinks) {
const path = link.match(/["']([^"']+)["']/)[1];
// Skip external URLs
if (path.startsWith('http') || path.startsWith('//')) continue;
const exists = workingFiles.some(f => f.path === path || f.path === `./${path}`);
if (!exists) {
criticalIssues.push(`CSS file referenced but not found: ${path}`);
}
}
for (const script of jsScripts) {
const path = script.match(/["']([^"']+)["']/)[1];
// Skip external URLs and CDN scripts
if (path.startsWith('http') || path.startsWith('//')) continue;
const exists = workingFiles.some(f => f.path === path || f.path === `./${path}`);
if (!exists) {
criticalIssues.push(`JS file referenced but not found: ${path}`);
}
}
// 5. Validate other files in the project
for (const file of workingFiles) {
if (file.path === 'index.html') continue;
const validation = validateFileSyntax(file.path, file.content);
if (!validation.valid) {
criticalIssues.push(`${file.path} has syntax errors: ${validation.error}`);
}
}
// 6. Run a fresh DOM check as final safety (in case validation state got out of sync)
const domAnalysis = analyzeDomReferences(workingFiles);
if (!domAnalysis.valid) {
for (const issue of domAnalysis.issues) {
let msg = `DOM mismatch in ${issue.file}: ${issue.ids.join(', ')}`;
if (issue.suggestions && Object.keys(issue.suggestions).length > 0) {
const firstSuggestion = Object.entries(issue.suggestions)[0];
msg += ` (did you mean "${firstSuggestion[1][0]}" instead of "${firstSuggestion[0]}"?)`;
}
criticalIssues.push(msg);
}
}
// Block on critical issues
if (criticalIssues.length > 0) {
devLog('finish: BLOCKED - critical issues:', criticalIssues);
return {
valid: false,
issues: criticalIssues,
hint: 'Fix these critical issues before calling finish(). DOM mismatches will cause null reference errors at runtime.'
};
}
// Log warnings but allow finish
if (issues.length > 0) {
devLog('Finish validation warnings:', issues);
}
devLog('finish: Validation passed');
return { valid: true, warnings: issues };
}
/**
* Get a human-readable status message for a tool call
* Used to show the user what the agent is currently doing
*/
function getToolStatusMessage(toolName, args) {
switch (toolName) {
case 'read_file':
return `Reading ${args.path || 'file'}...`;
case 'read_file_section':
return `Reading lines ${args.start_line}-${args.end_line} of ${args.path}...`;
case 'write_file':
return `Writing ${args.path || 'file'}...`;
case 'edit_file':
const editCount = args.edits?.length || 0;
return `Editing ${args.path} (${editCount} change${editCount !== 1 ? 's' : ''})...`;
case 'delete_file':
return `Deleting ${args.path}...`;
case 'list_files':
return 'Listing project files...';
case 'search_files':
return `Searching for "${args.query?.substring(0, 30) || ''}"...`;
case 'validate_file':
return `Validating ${args.path}...`;
case 'preview_site':
return 'Rendering preview...';
case 'get_preview_errors':
return 'Checking for runtime errors...';
case 'check_dom':
return 'Checking DOM element references...';
case 'get_library_docs':
return `Looking up ${args.library || 'library'} documentation...`;
case 'search_libraries':
return `Searching libraries for "${args.query || ''}"...`;
case 'validate_and_preview':
return 'Running comprehensive validation...';
case 'finish':
return 'Validating and finishing...';
default:
return `Running ${toolName}...`;
}
}
/**
* Execute a tool call
* Enhanced with edit_file, read_file_section, and validate_file
*/
function executeTool(name, args) {
devLog(`Executing tool: ${name}`, args);
switch (name) {
case 'read_file': {
const file = workingFiles.find(f => f.path === args.path);
if (file) {
const lines = file.content.split('\n').length;
return {
success: true,
content: file.content,
lines: lines,
hint: lines > 200 ? 'Large file. Consider using read_file_section for specific parts.' : undefined
};
}
return { success: false, error: `File not found: ${args.path}` };
}
case 'read_file_section': {
const file = workingFiles.find(f => f.path === args.path);
if (!file) {
return { success: false, error: `File not found: ${args.path}` };
}
const lines = file.content.split('\n');
const startLine = Math.max(1, args.start_line || 1);
const endLine = Math.min(lines.length, args.end_line || lines.length);
if (startLine > lines.length) {
return { success: false, error: `Start line ${startLine} exceeds file length (${lines.length} lines)` };
}
const section = lines.slice(startLine - 1, endLine);
return {
success: true,
content: section.join('\n'),
start_line: startLine,
end_line: endLine,
total_lines: lines.length
};
}
case 'write_file': {
const existingIndex = workingFiles.findIndex(f => f.path === args.path);
if (existingIndex !== -1) {
workingFiles[existingIndex].content = args.content;
devLog(`Updated file: ${args.path}`);
} else {
workingFiles.push({ path: args.path, content: args.content });
devLog(`Created file: ${args.path}`);
}
// Track that files changed - requires new error check before finish
validationState.filesModifiedSinceCheck = true;
return { success: true, message: `File written: ${args.path}` };
}
case 'edit_file': {
const file = workingFiles.find(f => f.path === args.path);
if (!file) {
return { success: false, error: `File not found: ${args.path}` };
}
if (!args.edits || !Array.isArray(args.edits) || args.edits.length === 0) {
return { success: false, error: 'No edits provided. Expected array of {search, replace} objects.' };
}
// Validate edits first
const validation = validateEdits(file.content, args.edits);
if (!validation.valid) {
return {
success: false,
error: 'Edit validation failed',
issues: validation.errors,
hint: 'Make sure search strings are unique and match exactly. Include more context if needed.'
};
}
// Apply edits
const result = applyEdits(file.content, args.edits);
if (!result.success) {
return {
success: false,
error: result.error,
failedEdit: result.failedEdit,
suggestion: result.suggestion
};
}
// Update file content
file.content = result.content;
devLog(`Edited file: ${args.path} (${args.edits.length} changes)`);
// Track that files changed - requires new error check before finish
validationState.filesModifiedSinceCheck = true;
return {
success: true,
message: `Applied ${args.edits.length} edit(s) to ${args.path}`,
hint: 'Call validate_file to verify changes are valid.'
};
}
case 'delete_file': {
const index = workingFiles.findIndex(f => f.path === args.path);
if (index !== -1) {
workingFiles.splice(index, 1);
devLog(`Deleted file: ${args.path}`);
return { success: true, message: `File deleted: ${args.path}` };
}
return { success: false, error: `File not found: ${args.path}` };
}
case 'list_files': {
const fileList = workingFiles.map(f => ({
path: f.path,
size: f.content.length,
tokens: estimateTokens(f.content),
lines: f.content.split('\n').length
}));
return { success: true, files: fileList };
}
case 'search_files': {
const results = [];
let regex;
try {
regex = new RegExp(args.query, 'gi');
} catch (e) {
// Fall back to literal search if regex is invalid
regex = new RegExp(args.query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'gi');
}
for (const file of workingFiles) {
const matches = [];
const lines = file.content.split('\n');
lines.forEach((line, i) => {
regex.lastIndex = 0; // Reset regex state
if (regex.test(line)) {
matches.push({ line: i + 1, content: line.trim().substring(0, 100) });
}
});
if (matches.length > 0) {
results.push({ path: file.path, matches: matches.slice(0, 5) });
}
}
return { success: true, results };
}
case 'validate_file': {
const file = workingFiles.find(f => f.path === args.path);
if (!file) {
return { success: false, error: `File not found: ${args.path}` };
}
const validation = validateFileSyntax(args.path, file.content);
return {
success: true,
valid: validation.valid,
error: validation.error,
warnings: validation.warnings
};
}
case 'preview_site': {
// Render the current project files in the preview iframe
try {
// Clear previous errors before render
clearPreviewErrors();
// Render the project
renderProject(workingFiles);
// Track that preview was rendered
validationState.previewRendered = true;
devLog('preview_site: Preview rendered, awaiting error check');
// Wait a moment for JavaScript to execute and errors to be captured
// The actual waiting happens in the agent loop via async delay
return {
success: true,
message: 'Preview rendered. Call get_preview_errors after a moment to check for runtime errors.',
hint: 'Wait briefly then call get_preview_errors() to see any JavaScript errors.'
};
} catch (error) {
return {
success: false,
error: `Failed to render preview: ${error.message}`
};
}
}
case 'get_preview_errors': {
const errors = getPreviewErrors();
// Track that error check was performed
validationState.errorCheckPerformed = true;
validationState.lastPreviewErrors = errors;
validationState.filesModifiedSinceCheck = false;
devLog('get_preview_errors: hasErrors=', errors.hasErrors);
if (!errors.hasErrors && errors.consoleWarns.length === 0) {
return {
success: true,
hasErrors: false,
message: 'No errors detected in the preview.',
lastRenderTime: errors.lastRenderTime
};
}
// Format errors for the agent
const formattedErrors = errors.errors.map(e => ({
type: e.type,
message: e.message,
line: e.line,
column: e.column
}));
const formattedConsoleErrors = errors.consoleErrors.map(e => e.message);
const formattedWarns = errors.consoleWarns.map(e => e.message);
// Analyze errors for library-specific issues
const allCode = workingFiles.map(f => f.content).join('\n');
const allErrorMessages = [
...errors.errors.map(e => e.message),
...errors.consoleErrors.map(e => e.message)
].join(' ');
const libraryAnalysis = analyzeLibraryError(allErrorMessages, allCode);
// Build hint with library-specific suggestions
let hint = errors.hasErrors
? 'Fix the errors above. Common issues: null element references, undefined variables, missing DOM elements.'
: 'Only warnings detected. Consider reviewing if they indicate potential issues.';
if (libraryAnalysis.hasLibraryRelatedError) {
const libSuggestions = libraryAnalysis.suggestions.map(s =>
`${s.library}: ${s.solution}`
).join('\n ');
hint += `\n\nLibrary-specific suggestions:\n ${libSuggestions}`;
hint += '\n\nUse get_library_docs("' + libraryAnalysis.suggestions[0]?.library + '", "errors") for more troubleshooting info.';
}
return {
success: true,
hasErrors: errors.hasErrors,
runtimeErrors: formattedErrors,
consoleErrors: formattedConsoleErrors,
warnings: formattedWarns,
detectedLibraries: libraryAnalysis.detectedLibraries,
librarySuggestions: libraryAnalysis.suggestions.length > 0 ? libraryAnalysis.suggestions : undefined,
hint
};
}
case 'check_dom': {
// Static analysis to detect DOM element mismatches
const analysis = analyzeDomReferences(workingFiles);
// Track that error check was performed
validationState.errorCheckPerformed = true;
validationState.lastDomCheckResult = analysis;
validationState.filesModifiedSinceCheck = false;
if (analysis.valid) {
devLog('check_dom: All DOM references valid');
return {
success: true,
valid: true,
message: 'All JavaScript element references match HTML IDs.',
htmlIds: analysis.htmlIds,
jsIds: analysis.jsIds
};
}
// Format issues with suggestions
const formattedIssues = analysis.issues.map(issue => {
let msg = issue.message;
if (issue.suggestions && Object.keys(issue.suggestions).length > 0) {
const suggestionParts = Object.entries(issue.suggestions)
.map(([missing, similar]) => `"${missing}" -> did you mean "${similar[0]}"?`)
.join('; ');
msg += ` Suggestions: ${suggestionParts}`;
}
return {
file: issue.file,
missingIds: issue.ids,
message: msg
};
});
devLog('check_dom: Found DOM mismatches:', formattedIssues.length, 'issues');
return {
success: true,
valid: false,
issues: formattedIssues,
htmlIds: analysis.htmlIds,
jsIds: analysis.jsIds,
hint: 'CRITICAL: JavaScript references elements that do not exist in HTML. This will cause "Cannot read properties of null" errors. You MUST fix these before calling finish().'
};
}
case 'get_library_docs': {
const queryType = args.query_type || 'overview';
const docs = formatLibraryDocs(args.library, queryType);
return {
success: true,
documentation: docs,
hint: 'Use this documentation to implement the library correctly. Check "errors" query_type if you encounter issues.'
};
}
case 'search_libraries': {
const results = searchLibraries(args.query);
if (results.length === 0) {
// Also try category search
const categories = getCategories();
return {
success: true,
results: [],
message: `No libraries found matching "${args.query}".`,
availableCategories: categories,
hint: `Try searching by category: ${categories.join(', ')}`
};
}
return {
success: true,
results: results.map(lib => ({
id: lib.id,
name: lib.name,
category: lib.category,
description: lib.description
})),
message: `Found ${results.length} library(ies). Use get_library_docs for detailed information.`
};
}
case 'validate_and_preview': {
// Comprehensive validation combining DOM check, syntax validation, and preview
devLog('validate_and_preview: Running comprehensive validation...');
const allIssues = [];
const warnings = [];
// 1. DOM reference analysis (static)
const domAnalysis = analyzeDomReferences(workingFiles);
if (!domAnalysis.valid) {
for (const issue of domAnalysis.issues) {
let msg = `DOM mismatch in ${issue.file}: ${issue.ids.join(', ')}`;
if (issue.suggestions && Object.keys(issue.suggestions).length > 0) {
const firstSuggestion = Object.entries(issue.suggestions)[0];
msg += ` (did you mean "${firstSuggestion[1][0]}" instead of "${firstSuggestion[0]}"?)`;
}
allIssues.push({ type: 'dom', message: msg });
}
}
// 2. Syntax validation for all files
for (const file of workingFiles) {
const validation = validateFileSyntax(file.path, file.content);
if (!validation.valid) {
allIssues.push({ type: 'syntax', file: file.path, message: validation.error });
}
if (validation.warnings) {
warnings.push(...validation.warnings.map(w => ({ file: file.path, message: w })));
}
}
// 3. Check for missing referenced files
const indexFile = workingFiles.find(f => f.path === 'index.html');
if (indexFile) {
const cssLinks = indexFile.content.match(/href=["']([^"']+\.css)["']/gi) || [];
const jsScripts = indexFile.content.match(/src=["']([^"']+\.js)["']/gi) || [];
for (const link of cssLinks) {
const path = link.match(/["']([^"']+)["']/)[1];
if (path.startsWith('http') || path.startsWith('//')) continue;
const exists = workingFiles.some(f => f.path === path || f.path === `./${path}`);
if (!exists) {
allIssues.push({ type: 'missing', message: `CSS file referenced but not found: ${path}` });
}
}
for (const script of jsScripts) {
const path = script.match(/["']([^"']+)["']/)[1];
if (path.startsWith('http') || path.startsWith('//')) continue;
const exists = workingFiles.some(f => f.path === path || f.path === `./${path}`);
if (!exists) {
allIssues.push({ type: 'missing', message: `JS file referenced but not found: ${path}` });
}
}
} else {
allIssues.push({ type: 'missing', message: 'index.html is missing' });
}
// 4. Render preview and capture errors
try {
clearPreviewErrors();
renderProject(workingFiles);
validationState.previewRendered = true;
// Wait a bit for JS to execute (in browser context)
// Note: In actual execution, errors are captured asynchronously
// The agent should call get_preview_errors() after for runtime errors
} catch (err) {
allIssues.push({ type: 'render', message: `Preview render failed: ${err.message}` });
}
// Track validation state
validationState.errorCheckPerformed = true;
validationState.lastDomCheckResult = domAnalysis;
validationState.filesModifiedSinceCheck = false;
devLog('validate_and_preview: Found', allIssues.length, 'issues,', warnings.length, 'warnings');
if (allIssues.length === 0) {
return {
success: true,
valid: true,
message: 'All validations passed! Preview rendered. You can now call finish().',
warnings: warnings.length > 0 ? warnings : undefined,
hint: 'Call get_preview_errors() if you want to check for runtime JavaScript errors, or proceed to finish().'
};
}
return {
success: true,
valid: false,
issues: allIssues,
warnings: warnings.length > 0 ? warnings : undefined,
hint: 'Fix the issues above before calling finish(). DOM mismatches will cause null reference errors. After fixing, call validate_and_preview() again to verify.'
};
}
case 'finish': {
devLog('finish: Agent attempting to finish...');
devLog('finish: Validation state:', {
errorCheckPerformed: validationState.errorCheckPerformed,
previewRendered: validationState.previewRendered,
filesModifiedSinceCheck: validationState.filesModifiedSinceCheck,
hasUnresolvedDomIssues: validationState.lastDomCheckResult && !validationState.lastDomCheckResult.valid,
hasUnresolvedPreviewErrors: validationState.lastPreviewErrors && validationState.lastPreviewErrors.hasErrors
});
// Pre-finish validation: ensure we have a complete, valid project
const validation = validateProjectBeforeFinish();
if (!validation.valid) {
devLog('finish: BLOCKED -', validation.issues.length, 'issues');