-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommand.ts
More file actions
1320 lines (1210 loc) · 63.3 KB
/
Copy pathcommand.ts
File metadata and controls
1320 lines (1210 loc) · 63.3 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
import * as path from 'path';
import * as fs from 'fs';
import * as hjson from 'hjson';
import { execSync, spawn } from 'child_process';
import { getDefinitions, collectProjectFiles } from './scanner.ts';
import { getServerForFile, applyWorkspaceEdit, findSymbolsInTree } from './lsp.ts';
import type { Session } from './session.ts';
const SCRIPT_DIR = path.dirname(new URL(import.meta.url).pathname);
const DEVCONTAINER_BIN = path.join(SCRIPT_DIR, 'node_modules', '.bin', 'devcontainer');
const MACA_TEST_MODE = !!process.env.MACA_TEST_MODE;
export type Phase = 'PLAN' | 'RED' | 'GREEN' | 'REFACTOR';
export type CapabilityLevel = 'medium' | 'high' | 'extreme';
export type PhasePlanSpec = {
globalInstruction: string;
todos: {title: string, description: string}[];
capability: CapabilityLevel;
initialViewIds: number[];
};
// Model shortcuts for common OpenRouter models
export const MODEL_SHORTCUTS: Record<string, string> = {
'g3f': 'google/gemini-3-flash-preview',
'cs46': 'anthropic/claude-sonnet-4.6',
'cs': 'cs46',
'ch45': 'anthropic/claude-haiku-4.5',
'ch': 'ch45',
'co46': 'anthropic/claude-opus-4-5',
'co': 'co46',
'glm5': 'z-ai/glm-5',
'mm': 'minimax/minimax-m2.5',
'kimi': 'moonshotai/kimi-k2.5',
};
export const DEFAULT_MODEL = 'glm5';
// Map capability levels to model shortcuts
export const CAPABILITY_MODELS: Record<CapabilityLevel, string> = {
medium: 'glm5',
high: 'cs',
extreme: 'co',
};
export function resolveModel(model: string): string {
// Resolve shortcuts recursively (e.g., 'cs' -> 'cs46' -> 'anthropic/claude-sonnet-4.6')
model = model.trim().toLowerCase();
for (let i = 0; i < 5 && model in MODEL_SHORTCUTS; i++) {
model = MODEL_SHORTCUTS[model];
}
return model;
}
export type View = {
command: 'VIEW_FILE';
path: string;
startLine?: number;
maxLineCount?: number;
} | {
command: 'VIEW_DEFINITION';
path: string;
name: string;
} | {
command: 'VIEW_SEARCH';
include?: string;
exclude?: string;
regexp?: string;
linesBefore?: number;
linesAfter?: number;
matchCase?: boolean;
};
type ClientContentBlock = {
type: 'content';
content: ContentBlock;
} | {
type: 'diff';
path: string;
oldText: string;
newText: string;
}
interface ContentBlock {
type: 'text';
text: string;
}
export interface ToolUpdate {
kind?: string;
title?: string;
status?: 'in_progress' | 'completed' | 'failed' | 'expired';
content?: string | ClientContentBlock | (string | ClientContentBlock)[];
locations?: ({path: string; line?: number} | string)[];
}
export type TestRunResult = {
command: string;
passed: boolean;
output: string;
};
// --- Helper functions for command implementations ---
function writeAndDiff(filePath: string, original: string, result: string, updateTool: (u: ToolUpdate) => void): void {
fs.mkdirSync(path.dirname(filePath), {recursive: true});
fs.writeFileSync(filePath, result, 'utf-8');
updateTool({content: {type: 'diff', path: filePath, oldText: original, newText: result}});
}
function readProjectFile(filePath: string, relPath: string, onMissing: 'throw' | 'empty' = 'throw'): string {
try { return fs.readFileSync(filePath, 'utf-8'); } catch (e: any) {
if (e.code !== 'ENOENT') throw new Error(`Failed to read ${relPath}: ${e.message}`);
if (onMissing === 'empty') return '';
throw new Error(`File not found: ${relPath}`);
}
}
export function detectAndRunTests(workRoot: string): TestRunResult | null {
// Detect test runner (re-detect each call to support LLM-created ./test)
let command: string | null = null;
const testExec = path.join(workRoot, 'test');
if (fs.existsSync(testExec)) {
try {
fs.accessSync(testExec, fs.constants.X_OK);
command = './test';
} catch {}
}
if (!command && fs.existsSync(path.join(workRoot, 'package.json'))) {
try {
const pkg = JSON.parse(fs.readFileSync(path.join(workRoot, 'package.json'), 'utf-8'));
if (pkg.scripts?.test) command = 'npm test';
} catch {}
}
if (!command && fs.existsSync(path.join(workRoot, 'Makefile'))) {
const makefile = fs.readFileSync(path.join(workRoot, 'Makefile'), 'utf-8');
if (/^test:/m.test(makefile)) command = 'make test';
}
if (!command) {
for (const f of ['pytest.ini', 'setup.cfg', 'pyproject.toml']) {
if (fs.existsSync(path.join(workRoot, f))) { command = 'python -m pytest'; break; }
}
}
if (!command && fs.existsSync(path.join(workRoot, 'Cargo.toml'))) command = 'cargo test';
if (!command && fs.existsSync(path.join(workRoot, 'go.mod'))) command = 'go test ./...';
if (!command) {
if (MACA_TEST_MODE) {
// In test mode skip test runner requirement so phase transitions always succeed
return {command: 'echo (test mode — no test runner)', passed: true, output: '(tests skipped in test mode)'};
}
return null;
}
try {
const result = execSync(command, {
cwd: workRoot,
encoding: 'utf-8',
stdio: 'pipe',
timeout: 120_000,
});
return {command, passed: true, output: result};
} catch (e: any) {
const output = (e.stdout || '') + (e.stderr ? '\n' + e.stderr : '');
return {command, passed: false, output};
}
}
// --- Unified command definitions ---
export interface CommandDefinition {
schema: Record<string, any>;
phases: Phase[];
implement: (p: any, session: Session, updateTool: (u: ToolUpdate) => void, previousErrors: boolean) => Promise<any>;
render: (p: any, session: Session) => ToolUpdate;
}
export const COMMAND_DEFS = {
THINK: {
schema: {
type: 'object',
additionalProperties: false,
description: 'Think out loud what (more) useful work you can do right *now*. THINK whenever you are unsure how to proceed, and at least as the first and last command.',
properties: {
command: { type: 'string', const: 'THINK'},
_thoughts: { type: 'string', description: 'Your thoughts about what file edits you can do right now, what shell commands to run, what views to create to make the next turn maximally effective, and what active views are not or no longer useful and should be dropped. Thoughts are just for you and transient (not part of the context in the next turn). Be brief. No social niceties. Sacrifice grammar for conciseness. No large code snippets.' },
keyTakeaways: {type: 'string', description: 'If there are key takeaways that you need to remember, summarize them here. Be VERY brief!' },
},
required: ['command', '_thoughts'],
},
phases: ['RED', 'GREEN', 'REFACTOR'],
async implement(p: {command: 'THINK', _thoughts: string, keyTakeaways: string}) {},
render(p) {
return {
title: p.keyTakeaways ? `Thinking: ${p.keyTakeaways}` : `Thinking`,
kind: 'think',
content: p._thoughts,
};
},
},
THOUGHTS: {
schema: {
type: 'object',
additionalProperties: false,
description: 'Think out loud. Do this as often as you need. At least do THOUGHTS when considering ending the list of commands or calling a _READY command.',
properties: {
command: { type: 'string', const: 'THOUGHTS'},
thoughts: { type: 'string', description: 'This is just for you. Keep it short and to the point. You can always have some more THOUGHTS later, if needed.'},
},
required: ['command', 'thoughts'],
},
phases: ['PLAN'],
async implement(p: {command: 'THOUGHTS', thoughts: string}) {},
render(p) {
return {
title: `Thinking`,
kind: 'think',
content: p.thoughts,
};
},
},
ASK_USER: {
schema: {
type: 'object',
additionalProperties: false,
description: 'Ask a clarifying question if the prompt is ambiguous or if major architectural decisions are needed.',
properties: {
command: { type: 'string', const: 'ASK_USER', },
question: { type: 'string' },
},
required: ['command', 'question'],
},
phases: ['PLAN'],
async implement(p: {command: 'ASK_USER', question: string}, session) {
const answer = await new Promise<any[]>((resolve) => {
session.userAnswerCallback = (_msgId: string, content: any[]) => resolve(content);
});
session.userAnswerCallback = undefined;
const answerText = answer.map(b => b.text || '').join('');
return {humanAnswer: answerText};
},
render(p, session) {
session.sendClientUpdate(p.question);
return {
title: 'Ask user',
kind: 'fetch',
};
},
},
WRITE_FILE: {
schema: {
type: 'object',
additionalProperties: false,
description: 'Create or overwrite a file.',
properties: {
command: { type: 'string', const: 'WRITE_FILE' },
path: { type: 'string' },
_text: { type: 'string' },
summary: { type: 'string', description: 'Describe _text in a few words.' },
},
required: ['command', 'path', '_text', 'summary'],
},
phases: ['RED', 'GREEN', 'REFACTOR'],
async implement(p: {command: 'WRITE_FILE', path: string, _text: string, summary: string}, session, updateTool) {
const filePath = path.join(session.workRoot, p.path);
const text: string = p._text ?? '';
const oldText = fs.existsSync(filePath) ? fs.readFileSync(filePath, 'utf-8') : '';
writeAndDiff(filePath, oldText, text, updateTool);
},
render(p) {
return {
title: `Write file ${p.path}: ${p.summary}`,
kind: 'edit',
locations: [p.path],
};
},
},
PATCH_FILE: {
schema: {
type: 'object',
additionalProperties: false,
description: 'Replace unique verbatim text span (line-boundary match). Add context lines for uniqueness.',
properties: {
command: { type: 'string', const: 'PATCH_FILE' },
path: { type: 'string' },
_searchText: { type: 'string' },
_replaceText: { type: 'string' },
summary: { type: 'string', description: 'Describe change in a few words.' },
},
required: ['command', 'path', '_searchText', '_replaceText', 'summary'],
},
phases: ['RED', 'GREEN', 'REFACTOR'],
async implement(p: {command: 'PATCH_FILE', path: string, _searchText: string, _replaceText: string, summary: string}, session, updateTool) {
const filePath = path.join(session.workRoot, p.path);
const searchText: string = p._searchText;
const replaceText: string = p._replaceText;
if (searchText === replaceText) throw new Error('searchText and replaceText are identical.');
const original = readProjectFile(filePath, p.path);
// Padded string matching to ensure line-boundary replacements
const padded = '\n' + original + '\n';
let orgText = searchText, replText = replaceText;
if (!orgText.startsWith('\n')) { orgText = '\n' + orgText; replText = '\n' + replText; }
if (!orgText.endsWith('\n')) { orgText = orgText + '\n'; replText = replText + '\n'; }
const idx = padded.indexOf(orgText);
if (idx === -1) throw new Error(`searchText not found in ${p.path} (or not on line boundaries).`);
if (padded.indexOf(orgText, idx + 1) !== -1) throw new Error(`searchText matches multiple locations in ${p.path}. Add context lines.`);
const replaced = padded.slice(0, idx) + replText + padded.slice(idx + orgText.length);
if (!replaced.startsWith('\n') || !replaced.endsWith('\n')) throw new Error(`searchText not found in ${p.path} (boundary error).`);
writeAndDiff(filePath, original, replaced.slice(1, -1), updateTool);
},
render(p) {
return {
title: `Patch file ${p.path}: ${p.summary}`,
kind: 'edit',
locations: [p.path],
};
},
},
ADD_TO_FILE: {
schema: {
type: 'object',
additionalProperties: false,
description: 'Insert line(s) in an existing file.',
properties: {
command: { type: 'string', const: 'ADD_TO_FILE' },
path: { type: 'string' },
line: { type: 'number', description: '1-based line number to insert before. -1 means append at end.' },
_text: { type: 'string', description: 'Prefix/suffix newlines are auto-added if needed.' },
summary: { type: 'string', description: 'Describe _text in a few words.' },
},
required: ['command', 'path', 'line', '_text', 'summary'],
},
phases: ['RED', 'GREEN', 'REFACTOR'],
async implement(p: {command: 'ADD_TO_FILE', path: string, line: number, _text: string, summary: string}, session, updateTool) {
const filePath = path.join(session.workRoot, p.path);
const text: string = p._text ?? '';
const line: number = p.line;
if (line < 0) {
// Append at end
const original = readProjectFile(filePath, p.path, 'empty');
const sep = original.endsWith('\n') || original === '' ? '' : '\n';
const suffix = text.endsWith('\n') ? text : text + '\n';
writeAndDiff(filePath, original, original + sep + suffix, updateTool);
} else {
// Insert before line
const original = readProjectFile(filePath, p.path, 'empty');
const lines = original === '' ? [] : original.split('\n');
if (line < 1 || line > lines.length + 1) throw new Error(`line ${line} out of range (${lines.length} lines).`);
const insertion = text.endsWith('\n') ? text : text + '\n';
const before = lines.slice(0, line - 1).join('\n');
const after = lines.slice(line - 1).join('\n');
writeAndDiff(filePath, original, (before ? before + '\n' : '') + insertion + after, updateTool);
}
},
render(p) {
return {
title: p.line < 0 ? `Append to ${p.path}: ${p.summary}` : `Insert into ${p.path} before line ${p.line}: ${p.summary}`,
kind: 'edit',
locations: [p.path],
};
},
},
RENAME_SYMBOL: {
schema: {
type: 'object',
additionalProperties: false,
description: 'Rename a symbol definition (function, variable, class, etc) across the project using the language server.',
properties: {
command: { type: 'string', const: 'RENAME_SYMBOL' },
path: { type: 'string', description: 'File containing the definition.' },
oldName: { type: 'string', description: 'The current name of the symbol definition to rename.' },
newName: { type: 'string' },
withinDefinition: { type: 'string', description: 'Optional: qualified name of the containing definition (e.g. "MyClass.myMethod") to narrow the search scope. Useful for renaming a local variable inside a specific function.' },
line: { type: 'number', description: 'Optional proximity hint: 1-based line near the definition (picks closest within 5 lines). Use to disambiguate multiple definitions for the same name within the same path. Prefer `withinDefinition` over this.' },
},
required: ['command', 'oldName', 'path', 'newName'],
},
phases: ['RED', 'GREEN', 'REFACTOR'],
async implement(p: {command: 'RENAME_SYMBOL', path: string, oldName: string, newName: string, withinDefinition?: string, line?: number}, session, updateTool) {
const filePath = path.join(session.workRoot, p.path);
const oldName: string = p.oldName;
const newName: string = p.newName;
const server = await getServerForFile(filePath, session.workRoot);
if (!server) throw new Error(`No language server available for ${p.path}.`);
if (!server.supportsRename()) throw new Error(`Rename not supported for this language.`);
const symbols = await server.getDocumentSymbols(filePath);
let matches = findSymbolsInTree(symbols, oldName, p.withinDefinition);
if (p.withinDefinition && matches.length === 0) {
throw new Error(`No definition "${oldName}" found within "${p.withinDefinition}" in ${p.path}.`);
}
if (p.line && matches.length > 1) {
// Pick the closest definition within 5 lines of the hint
const nearby = matches
.map(m => ({ symbol: m, dist: Math.abs(m.nameLine - p.line) }))
.filter(m => m.dist <= 5)
.sort((a, b) => a.dist - b.dist);
matches = nearby.length ? [nearby[0].symbol] : [];
}
if (!matches.length) throw new Error(`No matching definition.`);
if (matches.length > 1) throw new Error(`Multiple matching definitions.`);
const renameLine = matches[0].nameLine;
const renameCharacter = matches[0].nameCharacter;
const edit = await server.rename(filePath, renameLine, renameCharacter, newName);
if (!edit || Object.keys(edit.changes).length === 0) {
throw new Error(`Rename failed or produced no changes.`);
}
updateTool({content: applyWorkspaceEdit(edit)});
return {replacedInFiles: Object.keys(edit.changes)};
},
render(p) {
const at = [`path ${p.path}`];
if (p.withinDefinition) at.push(`within ${p.withinDefinition}`);
if (p.line) at.push(`line ${p.line}`);
return {
title: `Rename "${p.oldName}" (at ${at.join(', ')}) to "${p.newName}"`,
kind: 'edit',
locations: [p.path]
};
},
},
WRITE_DEFINITION_VIEW: {
schema: {
type: 'object',
additionalProperties: false,
description: 'Replace the contents of a VIEW_DEFINITION view.',
properties: {
command: { type: 'string', const: 'WRITE_DEFINITION_VIEW' },
viewId: { type: 'number' },
_text: { type: 'string', description: 'Replaces all lines included in the specified view.' },
summary: { type: 'string', description: 'Describe _text in a few words.' },
},
required: ['command', 'viewId', '_text', 'summary'],
},
phases: ['RED', 'GREEN', 'REFACTOR'],
async implement(p: {command: 'WRITE_DEFINITION_VIEW', viewId: number, _text: string, summary: string}, session, updateTool) {
const viewId: number = p.viewId;
const text: string = p._text ?? '';
const dr = session.views[viewId];
if (!dr) throw new Error(`No view with id "${viewId}".`);
if (dr.command !== 'VIEW_DEFINITION') throw new Error(`View "${viewId}" is a ${dr.command} view, which does not support WRITE_DEFINITION_VIEW.`);
const drFilePath = path.join(session.workRoot, dr.path);
const defs = await getDefinitions(drFilePath, session.workRoot);
const dotIdx = dr.name.lastIndexOf('.');
const nameToFind = (dotIdx >= 0 ? dr.name.slice(dotIdx + 1) : dr.name).toLowerCase();
const matches = defs.filter((d: any) => d.name.toLowerCase() === nameToFind);
if (matches.length === 0) throw new Error(`No definition for '${dr.name}' in ${dr.path}.`);
if (matches.length > 1) throw new Error(`Multiple definitions for '${dr.name}' in ${dr.path}. Use PATCH_FILE instead.`);
const startIdx = matches[0].startLine - 1;
const endIdx = matches[0].endLine;
const content = fs.readFileSync(drFilePath, 'utf-8');
const lines = content.split('\n');
const newLines = (text.endsWith('\n') ? text.slice(0, -1) : text).split('\n');
lines.splice(startIdx, endIdx - startIdx, ...newLines);
writeAndDiff(drFilePath, content, lines.join('\n'), updateTool);
},
render(p) {
return {
title: `Replace view contents: ${p.summary}`,
kind: 'edit',
};
},
},
SHELL: {
schema: {
type: 'object',
additionalProperties: false,
description: 'Run a bash command inside the project devcontainer (defined by .devcontainer/devcontainer.json). The project directory is mounted as the cwd. If no devcontainer.json exists yet, you MUST create one first (use WRITE_FILE) and verify it works before using SHELL. DO NOT USE for exploring the codebase, use view commands (or the Project summary) instead! *NO* `cat`, `grep`, `find`, etc should be needed! Also, DO NOT use it for editing files, use the proper commands for that.',
properties: {
command: { type: 'string', const: 'SHELL', },
shellCommand: { type: 'string', description: 'The bash command. Do not head/tail; use headLineLimit/tailLineLimit. Never use commands longer than ~100 characters; use WRITE_FILE to create a script in `.tmp/` and run it.' },
headLineLimit: { type: 'number', default: 20 },
tailLineLimit: { type: 'number', default: 40 },
timeoutSeconds: { type: 'number', default: 60, description: 'Maximum seconds to wait for the command. Increase for long-running builds/tests.' },
valid: {type: 'boolean', description: 'Set to `true` only if this shell command cannot possibly be replaced by more specific commands. When `false` this command will be ignored, and you should continue to add the more specific commands right after this.'},
},
required: ['command', 'shellCommand', 'valid'],
},
phases: ['RED', 'GREEN', 'REFACTOR'],
async implement(p: {command: 'SHELL', shellCommand: string, valid: boolean, headLineLimit?: number, tailLineLimit?: number, timeoutSeconds?: number}, session, updateTool) {
if (!p.valid) throw new Error("Not 'valid'");
const shellCommand: string = p.shellCommand;
const maxHead: number = p.headLineLimit ?? 20;
let maxTail: number = p.tailLineLimit ?? 40;
const timeoutMs: number = (p.timeoutSeconds ?? 60) * 1000;
// Check for devcontainer.json
const devcontainerJsonPath = path.join(session.workRoot, '.devcontainer', 'devcontainer.json');
if (!fs.existsSync(devcontainerJsonPath)) {
throw new Error('No .devcontainer/devcontainer.json found. You MUST create a .devcontainer/devcontainer.json file (using WRITE_FILE) that defines the development environment for this project before running any SHELL commands. Include all necessary tools, runtimes, and dependencies. Then run a SHELL command to verify the devcontainer builds and works correctly.');
}
// Start (or restart) the devcontainer once per session, unless devcontainer.json changed.
// We keep the container running and use `devcontainer exec` for each command.
const configContent = fs.readFileSync(devcontainerJsonPath, 'utf-8');
if (!session.devcontainerReady || session.devcontainerConfigHash !== configContent) {
// Remove previous container if config changed
if (session.devcontainerReady) {
session.destroyDevcontainer();
}
execSync(
`"${DEVCONTAINER_BIN}" up --workspace-folder "$WORKSPACE_FOLDER" --docker-path podman`,
{cwd: session.workRoot, stdio: 'pipe', env: {...process.env, WORKSPACE_FOLDER: session.workRoot}}
);
session.devcontainerReady = true;
session.devcontainerConfigHash = configContent;
}
const tmpDir = path.join(session.workRoot, '.tmp');
fs.mkdirSync(tmpDir, {recursive: true});
const existingShells = fs.readdirSync(tmpDir).filter(f => /^shell\d+\.txt$/.test(f));
const nextN = existingShells.length > 0
? Math.max(...existingShells.map(f => parseInt(f.match(/\d+/)![0], 10))) + 1
: 1;
const outputFile = path.join(tmpDir, `shell${nextN}.txt`);
const relOutputFile = path.relative(session.workRoot, outputFile);
// Run command inside the devcontainer using spawn for streaming output.
let rawOutput = '';
let exitCode = 0;
// Spawn with detached:true so sh gets its own process group.
// On timeout we kill the entire group (-pgid) to ensure devcontainer exec is also killed.
const child = spawn(
'sh',
['-c', `"${DEVCONTAINER_BIN}" exec --workspace-folder "$WORKSPACE_FOLDER" --docker-path podman sh -c "$SHELL_CMD"`],
{cwd: session.workRoot, env: {...process.env, WORKSPACE_FOLDER: session.workRoot, SHELL_CMD: shellCommand}, detached: true}
);
// Throttle intermediate output updates to at most once per 500ms.
let lastUpdateTime = 0;
let pendingUpdateTimer: ReturnType<typeof setTimeout> | null = null;
const sendOutputUpdate = () => {
pendingUpdateTimer = null;
lastUpdateTime = Date.now();
updateTool({content: rawOutput});
};
const scheduleOutputUpdate = () => {
if (pendingUpdateTimer !== null) return;
const elapsed = Date.now() - lastUpdateTime;
const delay = elapsed >= 500 ? 0 : 500 - elapsed;
pendingUpdateTimer = setTimeout(sendOutputUpdate, delay);
};
child.on('error', (err) => {
rawOutput += `\nProcess error: ${err.message}`;
});
child.stdout.on('data', (data: Buffer) => {
rawOutput += data.toString();
scheduleOutputUpdate();
});
child.stderr.on('data', (data: Buffer) => {
rawOutput += data.toString();
scheduleOutputUpdate();
});
let timedOut = false;
const timeoutHandle = setTimeout(() => {
timedOut = true;
try { process.kill(-child.pid!, 'SIGKILL'); } catch (_) {}
}, timeoutMs);
exitCode = await new Promise<number>((resolve) => {
child.on('close', (code: number | null) => resolve(code ?? 0));
});
clearTimeout(timeoutHandle);
if (pendingUpdateTimer !== null) clearTimeout(pendingUpdateTimer);
fs.writeFileSync(outputFile, rawOutput, 'utf-8');
if (timedOut || exitCode !== 0) {
updateTool({status: 'failed'});
}
const warning = timedOut ? `Command timed out after ${p.timeoutSeconds ?? 60}s; output may be incomplete` : undefined;
if (rawOutput.endsWith("\n")) maxTail += 1; // don't count trailing newline as a line
const outLines = rawOutput.split('\n');
if (outLines.length > maxHead + maxTail) {
const head = outLines.slice(0, maxHead).join('\n');
const skippedLines = outLines.length - maxHead - maxTail;
const tail = outLines.slice(outLines.length - maxTail).join('\n');
updateTool({content: `${head}\n... (${skippedLines} lines skipped) ...\n${tail}`});
return {_head: head, _skippedLines: skippedLines, _tail: tail, lineCount: outLines.length, exitCode, outputFile: relOutputFile, ...(warning ? {warning} : {})};
} else {
updateTool({content: rawOutput});
return {_content: rawOutput, lineCount: outLines.length, exitCode, outputFile: relOutputFile, ...(warning ? {warning} : {})};
}
},
render(p) {
return {
title: `Run: ${String(p.shellCommand).slice(0, 80)}`,
kind: 'execute',
content: p.shellCommand,
};
},
},
VIEW_DEFINITION: {
schema: {
type: 'object',
description: 'View the implementation of a named function/method/class, as listed in the *Project summary*. It makes no sense to re-request definitions already in *Active views*.',
additionalProperties: false,
properties: {
command: { type: 'string', const: 'VIEW_DEFINITION' },
path: { type: 'string', description: 'File path relative to project root where the symbol is defined. Eg: "src/x.ts"' },
name: { type: 'string', description: 'Name of the symbol to read the definition for. Eg: "myFunction" or "MyClass.myMethod"' },
},
required: ['command', 'path', 'name'],
},
phases: ['PLAN', 'RED', 'GREEN', 'REFACTOR'],
async implement(p: {command: 'VIEW_DEFINITION', path: string, name: string}, session) {
return {viewId: session.addView(p)};
},
render(p) {
return { title: `View definition ${p.name} in ${p.path}` };
},
},
VIEW_FILE: {
schema: {
type: 'object',
description: 'Create a *view* on the (partial) contents of a file. LAST RESORT — almost always use VIEW_DEFINITION instead! Only use VIEW_FILE for non-code files (config, docs, test data) or when you need a specific line range that does not correspond to a definition. If the file has definitions listed in the project summary, you MUST use VIEW_DEFINITION!',
additionalProperties: false,
properties: {
command: { type: 'string', const: 'VIEW_FILE' },
path: { type: 'string', description: 'File path relative to project root.' },
startLine: { type: 'number', description: '1-based line number to start reading from. Use 1 to start at the top.', default: 1 },
maxLineCount: { type: 'number', default: 250, description: 'Max lines to include. Default 250. Use a small value!' },
},
required: ['command', 'path'],
},
phases: ['PLAN', 'RED', 'GREEN', 'REFACTOR'],
async implement(p: {command: 'VIEW_FILE', path: string, startLine?: number, maxLineCount?: number}, session) {
return {viewId: session.addView(p)};
},
render(p) {
return { title: `View file ${p.path} [${p.startLine || 1}-${(p.startLine || 1) + (p.maxLineCount || 5000) - 1}]` };
},
},
SEARCH_EMBEDDINGS: {
schema: {
type: 'object',
description: 'Search the codebase in natural language, using vector embeddings. Creates VIEW_DEFINITION views for results.',
additionalProperties: false,
properties: {
command: { type: 'string', const: 'SEARCH_EMBEDDINGS' },
query: { type: 'string' },
},
required: ['command', 'query'],
},
phases: ['PLAN', 'RED', 'GREEN', 'REFACTOR'],
async implement(p: {command: 'SEARCH_EMBEDDINGS', query: string}, session, updateTool) {
const searchResults = await session.vectorEmbeddings.searchVectors(p.query, session.embeddingVectors, 4);
const resultViewIds = [];
const content = [];
for (const {index, score} of searchResults) {
const path = session.embeddingPaths[index];
const name = session.embeddingNames[index];
const viewDef = {command: 'VIEW_DEFINITION' as const, path, name};
resultViewIds.push(session.addView(viewDef));
content.push({path, name, score: score.toFixed(4)})
}
updateTool({content: hjson.stringify(content)});
return {resultViewIds};
},
render(p) {
return {
title: `Vector embeddings search: ${p.query}`,
kind: 'search',
};
},
},
VIEW_SEARCH: {
schema: {
type: 'object',
description: 'View for searching the codebase with a regular expression.',
additionalProperties: false,
properties: {
command: { type: 'string', const: 'VIEW_SEARCH' },
include: { type: 'string', description: 'Glob pattern for files to include in search.', default: '**' },
exclude: { type: 'string', description: 'Glob pattern for files to exclude from search.' },
regexp: { type: 'string', description: 'A JavaScript RegExp string. Example: "function\\s+myFunc"' },
linesBefore: { type: 'number', default: 2, description: 'Number of lines of context to include before each match.' },
linesAfter: { type: 'number', default: 2, description: 'Number of lines of context to include after each match.' },
matchCase: { type: 'boolean', default: false, description: 'Whether the search is case-sensitive.' },
},
required: ['command', 'regexp'],
},
phases: ['PLAN', 'RED', 'GREEN', 'REFACTOR'],
async implement(p: {command: 'VIEW_SEARCH', regexp: string, include?: string, exclude?: string, linesBefore?: number, linesAfter?: number, matchCase?: boolean}, session) {
return {viewId: session.addView(p)};
},
render(p) {
return {
title: `Regexp search: ${p.regexp}`,
kind: 'search',
};
},
},
DROP_VIEW: {
schema: {
type: 'object',
additionalProperties: false,
description: 'Drop a view by id to free up context. Do this aggressively whenever you think a view is irrelevant to the task or too broad. DO NOT drop views that contain info you used or may use, unless you are replacing them with a narrower view. DO NOT drop views when you are fully DONE with the task.',
properties: {
command: { type: 'string', const: 'DROP_VIEW' },
viewId: { type: 'number' },
summary: { type: 'string', description: 'SHORT summary of what was in the *view* (relevant to the task), so future turns know if they should recreate a *view* for it.' },
},
required: ['command', 'viewId', 'summary'],
},
phases: ['PLAN', 'RED', 'GREEN', 'REFACTOR'],
async implement(p: {command: 'DROP_VIEW', viewId: number, summary: string}, session, _updateTool, previousErrors) {
const viewId: number = p.viewId;
if (!(viewId in session.views)) {
throw new Error("Invalid viewId");
}
if (previousErrors) {
throw new Error('Skipped due to earlier errors.');
}
delete session.views[viewId];
},
render(_p) {
return { title: `Drop view` };
},
},
// ---- Phase transition commands ----
PLAN_READY: {
schema: {
type: 'object',
additionalProperties: false,
description: 'Signals that the planning phase is complete and delivers a structured plan for RED and GREEN TDD phases. The REFACTOR phase does not need planning — it reviews changes independently. Call this when you fully understand the task and have a clear plan. Set valid:false if you realize mid-command that you still lack information or spotted an error — the command will be ignored and you can keep exploring.',
properties: {
command: { type: 'string', const: 'PLAN_READY' },
valid: { type: 'boolean', description: 'Set to false to cancel this command (e.g. you noticed missing info while filling it in). Set to true when the plan is solid.' },
red: {
type: 'object', additionalProperties: false,
description: 'Plan for the RED (write tests) phase.',
properties: {
globalInstruction: { type: 'string', description: 'High-level instruction for what tests to write.' },
todos: { type: 'array', items: { type: 'object', additionalProperties: false, properties: { title: { type: 'string', description: 'Short task title.' }, description: { type: 'string', description: 'Detailed description of the task.' } }, required: ['title', 'description'] }, description: 'Ordered list of specific tasks for this phase.' },
capability: { type: 'string', enum: ['medium', 'high', 'extreme'], description: 'Required model capability.' },
initialViewIds: { type: 'array', items: { type: 'number' }, description: 'View IDs from the current PLAN session that should be passed to this phase.' },
},
required: ['globalInstruction', 'todos', 'capability', 'initialViewIds'],
},
green: {
type: 'object', additionalProperties: false,
description: 'Plan for the GREEN (implement) phase.',
properties: {
globalInstruction: { type: 'string' },
todos: { type: 'array', items: { type: 'object', additionalProperties: false, properties: { title: { type: 'string', description: 'Short task title.' }, description: { type: 'string', description: 'Detailed description of the task.' } }, required: ['title', 'description'] } },
capability: { type: 'string', enum: ['medium', 'high', 'extreme'] },
initialViewIds: { type: 'array', items: { type: 'number' } },
},
required: ['globalInstruction', 'todos', 'capability', 'initialViewIds'],
},
},
required: ['command', 'valid', 'red', 'green'],
},
phases: ['PLAN'],
async implement(p: {command: 'PLAN_READY', valid: boolean, red: PhasePlanSpec, green: PhasePlanSpec}, session, _updateTool, previousErrors) {
if (previousErrors) throw new Error('Skipped due to earlier errors.');
if (!p.valid) return {ignored: true, reason: 'valid:false — command cancelled by model.'};
session.planResult = {red: p.red, green: p.green};
session.phaseTransition = 'PLAN_READY';
return {planned: true};
},
render(p, session) {
const entries: any[] = [];
// RED items first (higher priority)
entries.push({content: 'RED phase', priority: 'high', status: 'pending'});
for (const todo of p.red.todos) {
entries.push({content: todo.title, priority: 'high', status: 'pending'});
}
// GREEN items
entries.push({content: 'GREEN phase', priority: 'medium', status: 'pending'});
for (const todo of p.green.todos) {
entries.push({content: todo.title, priority: 'medium', status: 'pending'});
}
// REFACTOR phase item (not planned, but tracked)
entries.push({content: 'REFACTOR phase', priority: 'medium', status: 'pending'});
session.sendClientUpdate({sessionUpdate: 'plan', entries});
return {title: 'Plan ready', kind: 'transition'};
},
},
PLAN_WITHOUT_RED_READY: {
schema: {
type: 'object',
additionalProperties: false,
description: 'Signals that the planning phase is complete WITHOUT a RED (testing) phase. Use when writing tests is not needed or appropriate. Requires a rationale for skipping tests.',
properties: {
command: { type: 'string', const: 'PLAN_WITHOUT_RED_READY' },
valid: { type: 'boolean', description: 'Set to false to cancel this command. Set to true when the plan is solid.' },
noRedRationale: { type: 'string', description: 'Why no tests are being written for this task.' },
green: {
type: 'object', additionalProperties: false,
description: 'Plan for the GREEN (implement) phase.',
properties: {
globalInstruction: { type: 'string' },
todos: { type: 'array', items: { type: 'object', additionalProperties: false, properties: { title: { type: 'string', description: 'Short task title.' }, description: { type: 'string', description: 'Detailed description of the task.' } }, required: ['title', 'description'] } },
capability: { type: 'string', enum: ['medium', 'high', 'extreme'] },
initialViewIds: { type: 'array', items: { type: 'number' } },
},
required: ['globalInstruction', 'todos', 'capability', 'initialViewIds'],
},
},
required: ['command', 'valid', 'noRedRationale', 'green'],
},
phases: ['PLAN'],
async implement(p: {command: 'PLAN_WITHOUT_RED_READY', valid: boolean, noRedRationale: string, green: PhasePlanSpec}, session, _updateTool, previousErrors) {
if (previousErrors) throw new Error('Skipped due to earlier errors.');
if (!p.valid) return {ignored: true, reason: 'valid:false — command cancelled by model.'};
session.planResult = {green: p.green, noRedRationale: p.noRedRationale};
session.phaseTransition = 'PLAN_READY';
return {planned: true, noRedRationale: p.noRedRationale};
},
render(p, session) {
const entries: any[] = [];
// GREEN items (highest priority since no RED)
entries.push({content: 'GREEN phase', priority: 'high', status: 'pending'});
for (const todo of p.green.todos) {
entries.push({content: todo.title, priority: 'high', status: 'pending'});
}
// REFACTOR phase item (not planned, but tracked)
entries.push({content: 'REFACTOR phase', priority: 'medium', status: 'pending'});
session.sendClientUpdate({sessionUpdate: 'plan', entries});
return {title: 'Plan ready (no RED phase)', kind: 'transition'};
},
},
ANSWER_READY: {
schema: {
type: 'object',
additionalProperties: false,
description: 'Use when no code changes are requested or possible. Provide the answer or explanation directly to the user.',
properties: {
command: { type: 'string', const: 'ANSWER_READY' },
valid: { type: 'boolean', description: 'Set to false to cancel this command. Set to true when the answer is complete.' },
answer: { type: 'string', description: 'The answer or explanation for the user.' },
},
required: ['command', 'valid', 'answer'],
},
phases: ['PLAN'],
async implement(p: {command: 'ANSWER_READY', valid: boolean, answer: string}, session, _updateTool, previousErrors) {
if (previousErrors) throw new Error('Skipped due to earlier errors.');
if (!p.valid) return {ignored: true, reason: 'valid:false — command cancelled by model.'};
session.taskResult = {answer: p.answer};
session.phaseTransition = 'ANSWER_READY';
return {answered: true};
},
render(p, session) {
session.sendClientUpdate(p.answer);
return {title: 'Answer ready', kind: 'transition'};
},
},
ESCALATE: {
schema: {
type: 'object',
additionalProperties: false,
description: 'Escalate to the most capable available model. Use when the task is harder than expected and requires deep reasoning. Only available in PLAN phase.',
properties: {
command: { type: 'string', const: 'ESCALATE' },
reason: { type: 'string', description: 'Why escalation is needed.' },
},
required: ['command', 'reason'],
},
phases: ['PLAN'],
async implement(p: {command: 'ESCALATE', reason: string}, session) {
if (session.escalated) {
return {escalated: false, message: 'Already at highest capability. No change.'};
}
session.escalated = true;
session.model = resolveModel(CAPABILITY_MODELS.extreme);
return {escalated: true, message: `Switched to best available model (${session.model}). Calling ESCALATE again will have no further effect.`};
},
render(_p) {
return {
title: 'Escalate to extreme model',
kind: 'other',
};
},
},
TODO_DONE: {
schema: {
type: 'object',
additionalProperties: false,
description: 'Mark a TODO item from the phase plan as completed.',
properties: {
command: { type: 'string', const: 'TODO_DONE' },
todoIndex: { type: 'number', description: '0-based index of the completed TODO item.' },
},
required: ['command', 'todoIndex'],
},
phases: ['RED', 'GREEN'],
async implement(p: {command: 'TODO_DONE', todoIndex: number}, session) {
session.phaseTodosDone.add(p.todoIndex);
},
render(p) {
return {
title: `TODO #${p.todoIndex} done`,
kind: 'other',
};
},
},
RED_READY: {
schema: {
type: 'object',
additionalProperties: false,
description: 'Signals that the RED phase is complete: tests have been written. Tests will be run automatically — they should fail (that confirms the tests are real). Set valid:false to cancel if you noticed an issue mid-command.',
properties: {
command: { type: 'string', const: 'RED_READY' },
valid: { type: 'boolean', description: 'Set to false to cancel this command (e.g. you noticed missing tests while filling it in).' },
summary: { type: 'string', description: 'Brief description of what tests were created/modified.' },
},
required: ['command', 'valid', 'summary'],
},
phases: ['RED'],
async implement(p: {command: 'RED_READY', valid: boolean, summary: string}, session, _updateTool, previousErrors) {
if (previousErrors) throw new Error('Skipped due to earlier errors.');
if (!p.valid) return {ignored: true, reason: 'valid:false — command cancelled by model.'};
const redPending = (session.planResult?.red?.todos?.length ?? 0) - session.phaseTodosDone.size;
if (redPending > 0) return {rejected: true, reason: `${redPending} todo(s) still pending. Mark them done with TODO_DONE first.`};
// Run tests — they should FAIL (proves tests are real)
const testResult = detectAndRunTests(session.workRoot);
if (!testResult) {
session.transitionMessages.push('[MACA] No test runner detected. Please create an executable `./test` file that runs the tests, then call RED_READY again.');
return {rejected: true, reason: 'No test runner detected.'};
}
const testSummary = `$ ${testResult.command}\n\n${testResult.output.slice(0, 4000)}`;
if (testResult.passed) {
session.transitionMessages.push(`[MACA] Tests passed after RED_READY — expected them to fail! Make sure the tests actually test new functionality. Proceeding to GREEN anyway.\n\n${testSummary}`);
} else {
session.transitionMessages.push(`[MACA] Tests failed as expected (RED phase confirmed).\n\n${testSummary}`);
}
session.phaseTransition = 'RED_READY';
return {summary: p.summary};
},
render(p) {
return {
title: `Tests written: ${p.summary}`,
kind: 'transition',
};
},
},
GREEN_READY: {
schema: {
type: 'object',
additionalProperties: false,
description: 'Signals that the GREEN phase is complete: implementation is done. Tests will be run automatically — they must pass. Set valid:false to cancel if you noticed an issue mid-command.',
properties: {
command: { type: 'string', const: 'GREEN_READY' },
valid: { type: 'boolean', description: 'Set to false to cancel this command (e.g. you realized the implementation is incomplete).' },
summary: { type: 'string', description: 'Brief description of the implementation.' },
},
required: ['command', 'valid', 'summary'],
},
phases: ['GREEN'],
async implement(p: {command: 'GREEN_READY', valid: boolean, summary: string}, session, _updateTool, previousErrors) {
if (previousErrors) throw new Error('Skipped due to earlier errors.');
if (!p.valid) return {ignored: true, reason: 'valid:false — command cancelled by model.'};
const greenPending = (session.planResult?.green?.todos?.length ?? 0) - session.phaseTodosDone.size;