forked from TrafficGuard/typedai
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcoder.xml
More file actions
2058 lines (1762 loc) · 120 KB
/
coder.xml
File metadata and controls
2058 lines (1762 loc) · 120 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
<file_content file_path="shared/files/fileSystemService.ts"><![CDATA[
import type { Ignore } from 'ignore';
import type { VersionControlSystem } from '#shared/scm/versionControlSystem';
export interface FileSystemNode {
path: string;
name: string;
type: 'file' | 'directory';
children?: FileSystemNode[];
summary?: string; // Optional summary from indexing agent
}
export interface IFileSystemService {
toJSON(): { basePath: string; workingDirectory: string };
fromJSON(obj: any): this | null;
/**
* The base path set from the constructor or environment variables or program args
*/
getBasePath(): string;
/**
* @returns the full path of the working directory on the filesystem
*/
getWorkingDirectory(): string;
/**
* Set the working directory. The dir argument may be an absolute filesystem path, otherwise relative to the current working directory.
* If the dir starts with / it will first be checked as an absolute directory, then as relative path to the working directory.
* @param dir the new working directory
*/
setWorkingDirectory(dir: string): void;
/**
* Returns the file contents of all the files under the provided directory path
* @param dirPath the directory to return all the files contents under
* @returns the contents of the file(s) as a Map keyed by the file path
*/
getFileContentsRecursively(dirPath: string, useGitIgnore?: boolean): Promise<Map<string, string>>;
/**
* Returns the file contents of all the files recursively under the provided directory path
* @param dirPath the directory to return all the files contents under
* @param storeToMemory if the file contents should be stored to memory. The key will be in the format file-contents-<FileSystem.workingDirectory>-<dirPath>
* @returns the contents of the file(s) in format <file_contents path="dir/file1">file1 contents</file_contents><file_contents path="dir/file2">file2 contents</file_contents>
*/
getFileContentsRecursivelyAsXml(dirPath: string, storeToMemory: boolean, filter?: (path: string) => boolean): Promise<string>;
/**
* Searches for files on the filesystem (using ripgrep) with contents matching the search regex.
* @param contentsRegex the regular expression to search the content all the files recursively for
* @returns the list of filenames (with postfix :<match_count>) which have contents matching the regular expression.
*/
searchFilesMatchingContents(contentsRegex: string): Promise<string>;
/**
* Searches for files on the filesystem (using ripgrep) with contents matching the search regex.
* The number of lines before/after the matching content will be included for context.
* The response format will be like
* <code>
* dir/subdir/filename
* 26-foo();
* 27-matchedString();
* 28-bar();
* </code>
* @param contentsRegex the regular expression to search the content all the files recursively for
* @param linesBeforeAndAfter the number of lines above/below the matching lines to include in the output
* @returns the matching lines from each files with additional lines above/below for context.
*/
searchExtractsMatchingContents(contentsRegex: string, linesBeforeAndAfter?: number): Promise<string>;
/**
* Searches for files on the filesystem where the filename matches the regex.
* @param fileNameRegex the regular expression to match the filename.
* @returns the list of filenames matching the regular expression.
*/
searchFilesMatchingName(fileNameRegex: string): Promise<string[]>;
/**
* Lists the file and folder names in a single directory.
* Folder names will end with a /
* @param dirPath the folder to list the files in. Defaults to the working directory
* @returns the list of file and folder names
*/
listFilesInDirectory(dirPath?: string): Promise<string[]>;
/**
* List all the files recursively under the given path, excluding any paths in a .gitignore file if it exists
* @param dirPath
* @returns the list of files
*/
listFilesRecursively(dirPath?: string, useGitIgnore?: boolean): Promise<string[]>;
listFilesRecurse(
rootPath: string,
dirPath: string,
parentIg: Ignore,
useGitIgnore: boolean,
gitRoot: string | null,
filter?: (file: string) => boolean,
): Promise<string[]>;
/**
* Gets the contents of a local file on the file system. If the user has only provided a filename you may need to find the full path using the searchFilesMatchingName function.
* @param filePath The file path to read the contents of (e.g. src/index.ts)
* @returns the contents of the file(s) in format <file_contents path="dir/file1">file1 contents</file_contents><file_contents path="dir/file2">file2 contents</file_contents>
*/
readFile(filePath: string): Promise<string>;
/**
* Gets the contents of a local file on the file system and returns it in XML tags
* @param filePath The file path to read the contents of (e.g. src/index.ts)
* @returns the contents of the file(s) in format <file_contents path="dir/file1">file1 contents</file_contents>
*/
readFileAsXML(filePath: string): Promise<string>;
/**
* Gets the contents of a list of local files. Input paths can be absolute or relative to the service's working directory.
* @param {Array<string>} filePaths The files paths to read the contents of.
* @returns {Promise<Map<string, string>>} the contents of the files in a Map object keyed by the file path *relative* to the service's working directory.
*/
readFiles(filePaths: string[]): Promise<Map<string, string>>;
/**
* Gets the contents of a list of files, returning a formatted XML string of all file contents
* @param {Array<string>} filePaths The files paths to read the contents of
* @returns {Promise<string>} the contents of the file(s) in format <file_contents path="dir/file1">file1 contents</file_contents><file_contents path="dir/file2">file2 contents</file_contents>
*/
readFilesAsXml(filePaths: string | string[]): Promise<string>;
formatFileContentsAsXml(fileContents: Map<string, string>): string;
/**
* Check if a file exists. A filePath starts with / is it relative to FileSystem.basePath, otherwise its relative to FileSystem.workingDirectory
* @param filePath The file path to check
* @returns true if the file exists, else false
*/
fileExists(filePath: string): Promise<boolean>;
directoryExists(dirPath: string): Promise<boolean>;
/**
* Writes to a file. If the file path already exists an Error will be thrown. This will create any parent directories required,
* @param filePath The file path (either full filesystem path or relative to current working directory)
* @param contents The contents to write to the file
*/
writeNewFile(filePath: string, contents: string): Promise<void>;
/**
* Writes to a file. If the file exists it will overwrite the contents. This will create any parent directories required,
* @param filePath The file path (either full filesystem path or relative to current working directory)
* @param contents The contents to write to the file
*/
writeFile(filePath: string, contents: string): Promise<void>;
deleteFile(filePath: string): Promise<void>;
/**
* Reads a file, then transforms the contents using a LLM to perform the described changes, then writes back to the file.
* @param {string} filePath The file to update
* @param {string} descriptionOfChanges A natual language description of the changes to make to the file contents
*/
editFileContents(filePath: string, descriptionOfChanges: string): Promise<void>;
loadGitignoreRules(startPath: string, gitRoot: string | null): Promise<Ignore>;
listFolders(dirPath?: string): Promise<string[]>;
/**
* Recursively lists all folders under the given root directory.
* @param dir The root directory to start the search from. Defaults to the current working directory.
* @returns A promise that resolves to an array of folder paths relative to the working directory.
*/
getAllFoldersRecursively(dir?: string): Promise<string[]>;
/**
* Generates a textual representation of a directory tree structure.
*
* This function uses listFilesRecursively to get all files and directories,
* respecting .gitignore rules, and produces an indented string representation
* of the file system hierarchy.
*
* @param {string} dirPath - The path of the directory to generate the tree for, defaulting to working directory
* @returns {Promise<string>} A string representation of the directory tree.
*
* @example
* Assuming the following directory structure:
* ./
* ├── file1.txt
* ├── images/
* │ ├── logo.png
* └── src/
* └── utils/
* └── helper.js
*
* The output would be:
* file1.txt
* images/
* logo.png
* src/utils/
* helper.js
*/
getFileSystemTree(dirPath?: string): Promise<string>;
/**
* Returns the filesystem structure
* @param dirPath
* @returns a record with the keys as the folders paths, and the list values as the files in the folder
*/
getFileSystemTreeStructure(dirPath?: string): Promise<Record<string, string[]>>;
/**
* Generates a hierarchical representation of the file system structure starting from a given path,
* respecting .gitignore rules if enabled.
*
* @param dirPath The starting directory path, relative to the working directory or absolute. Defaults to the working directory.
* @param useGitIgnore Whether to respect .gitignore rules. Defaults to true.
* @returns A Promise resolving to the root FileSystemNode representing the requested directory structure, or null if the path is not a directory.
*/
getFileSystemNodes(dirPath?: string, useGitIgnore?: boolean): Promise<FileSystemNode | null>;
/**
* Recursive helper function to build the FileSystemNode tree.
* @param currentPathAbs Absolute path of the directory currently being processed.
* @param serviceWorkingDir Absolute path of the service's working directory (for relative path calculation).
* @param parentIg Ignore rules inherited from the parent directory.
* @param useGitIgnore Whether to respect .gitignore rules.
* @param gitRoot Absolute path to the git repository root, if applicable.
* @returns A Promise resolving to an array of FileSystemNode children for the current directory.
*/
buildNodeTreeRecursive(
currentPathAbs: string,
serviceWorkingDir: string,
parentIg: Ignore,
useGitIgnore: boolean,
gitRoot: string | null,
): Promise<FileSystemNode[]>;
getVcs(): VersionControlSystem;
/**
* Gets the version control service (Git) repository root folder, if the current working directory is in a Git repo, else null.
*/
getVcsRoot(): string | null;
/**
* Rename/move a file or folder
* @param filePath
* @param newPath
*/
rename(filePath: string, newPath: string): Promise<void>;
}
]]></file_content>
<file_content file_path="shared/scm/versionControlSystem.ts"><![CDATA[
export interface Commit {
title: string;
description: string;
diffs: Map<string, string>;
}
/**
* Version control system
*/
export interface VersionControlSystem {
/**
* Returns the diff from the merge-base (common ancestor) of HEAD and a reference, up to HEAD.
* This effectively shows changes introduced on the current branch relative to that base.
*
* @param baseRef Optional commit SHA or branch name.
* - If provided: Uses `git merge-base <baseRef> HEAD` to find the diff start point.
* - If omitted: Attempts to guess the source branch (e.g., main, develop)
* by inspecting other local branches and uses that for the merge-base calculation.
* Note: Guessing the source branch may be unreliable in some cases.
* @returns The git diff.
*/
getDiff(baseRef?: string): Promise<string>;
/**
* Creates a new branch, or if it already exists then switches to it
* @param branchName
* @return if the branch was created, or false if switched to an existing one
*/
createBranch(branchName: string): Promise<boolean>;
switchToBranch(branchName: string): Promise<void>;
/** Pull the changes from the remote/origin server for the current branch */
pull(): Promise<void>;
/** Gets the current branch name */
getBranchName(): Promise<string>;
/** @return the SHA value for the HEAD commit */
getHeadSha(): Promise<string>;
/**
* Adds all files which are already tracked by version control to the index and commits
* @param commitMessage
*/
addAllTrackedAndCommit(commitMessage: string): Promise<void>;
/** Add and commit a specific list of files. */
addAndCommitFiles(files: string[], commitMessage: string): Promise<void>;
/**
* Merges the changes in specific files into the latest commit.
* This is useful for merging lint fixes and compiles fixes into the current commit, so that commit should build.
*/
mergeChangesIntoLatestCommit(files: string[]): Promise<void>;
commit(commitMessage: string): Promise<void>;
/**
* Gets the filenames which were added in the most recent commit
* @param commitSha The commit to search back to, otherwise is for the HEAD commit.
* @return the filenames which were added
*/
getAddedFiles(commitSha?: string): Promise<string[]>;
/**
* Gets the details of the most recent commits
* @param n the number of commits (defaults to 2)
* @returns an array of the commit details
*/
getRecentCommits(n?: number): Promise<Array<Commit>>;
/**
* @param path full file path
* @returns if the file has uncommitted changes.
*/
isDirty(path: string): Promise<boolean>;
/**
* @returns if the repository has any uncommitted changes.
*/
isRepoDirty(): Promise<boolean>;
/**
* @returns
*/
stashChanges(): Promise<void>;
/**
* Revert uncommitted changes to a file
* @param filePath
*/
revertFile(filePath: string): Promise<void>;
}
]]></file_content>
<file_content file_path="src/llm/services/mock-llm.ts"><![CDATA[
import { addCost, agentContext } from '#agent/agentContextLocalStorage';
import { appContext } from '#app/applicationContext';
import { callStack } from '#llm/llmCallService/llmCall';
import { logger } from '#o11y/logger';
import { withActiveSpan } from '#o11y/trace';
import type { AgentLLMs } from '#shared/agent/agent.model';
import { type GenerateTextOptions, type GenerationStats, type LLM, type LlmMessage, messageText, system, user } from '#shared/llm/llm.model';
import type { LlmCall } from '#shared/llmCall/llmCall.model';
import { BaseLLM } from '../base-llm';
// A discriminated union to represent the different types of calls that can be made to the mock.
export type MockLLMCall =
| {
type: 'generateMessage';
messages: ReadonlyArray<LlmMessage>;
options?: GenerateTextOptions;
}
| {
type: 'generateText';
systemPrompt: string | undefined;
userPrompt: string;
options?: GenerateTextOptions;
};
// Convenience alias for the “assistant” member of the union
type AssistantMessage = Extract<LlmMessage, { role: 'assistant' }>;
export class MockLLM extends BaseLLM {
private messageResponses: (() => Promise<LlmMessage>)[] = [];
private textResponses: (() => Promise<string>)[] = [];
private calls: MockLLMCall[] = [];
constructor(id = 'mock', service = 'mock', model = 'mock', maxInputTokens = 100000) {
super(id, service, model, maxInputTokens, () => ({ inputCost: 0, outputCost: 0, totalCost: 0 }));
}
// =================================================================
// Test-Facing API: For setting up and asserting on behavior in tests
// =================================================================
/**
* Resets all configured responses and clears the call history.
* Should be called in `beforeEach` or `afterEach` for test isolation.
*/
reset(): void {
this.messageResponses = [];
this.textResponses = [];
this.calls = [];
}
/**
* Queue a response for the next `generateMessage` call.
* The response is always treated as an *assistant* message.
*/
addMessageResponse(response: string | Partial<AssistantMessage>): this {
// 2. Build a guaranteed-to-be-assistant LlmMessage
const message: AssistantMessage =
typeof response === 'string' ? { role: 'assistant', content: response } : ({ ...response, role: 'assistant' } as AssistantMessage);
this.messageResponses.push(() => Promise.resolve(message));
return this;
}
/**
* Adds a successful response to the queue for the next `generateText` call.
* @param response The string content for the response.
* @returns The MockLLM instance for chaining.
*/
addResponse(response: string): this {
this.textResponses.push(() => Promise.resolve(response));
return this;
}
/**
* Configures the next `generateMessage` call to fail with the given error.
* @returns The MockLLM instance for chaining.
*/
rejectNextMessage(error: Error): this {
this.messageResponses.push(() => Promise.reject(error));
return this;
}
/**
* Configures the next `generateText` call to fail with the given error.
* @returns The MockLLM instance for chaining.
*/
rejectNextText(error: Error): this {
this.textResponses.push(() => Promise.reject(error));
return this;
}
/**
* Gets all calls made to this mock instance.
*/
getCalls(): ReadonlyArray<MockLLMCall> {
return this.calls;
}
/**
* Gets all `generateMessage` calls made to this mock instance for inspection.
*/
getMessageCalls(): Extract<MockLLMCall, { type: 'generateMessage' }>[] {
return this.calls.filter((c): c is Extract<MockLLMCall, { type: 'generateMessage' }> => c.type === 'generateMessage');
}
/**
* Gets all `generateText` calls made to this mock instance for inspection.
*/
getTextCalls(): Extract<MockLLMCall, { type: 'generateText' }>[] {
return this.calls.filter((c): c is Extract<MockLLMCall, { type: 'generateText' }> => c.type === 'generateText');
}
/**
* Gets the last call made to this mock instance.
*/
getLastCall(): MockLLMCall | undefined {
return this.calls.at(-1);
}
/**
* Gets the total number of calls (`generateMessage` and `generateText`) made to this mock.
*/
getCallCount(): number {
return this.calls.length;
}
/**
* Throws an error if any configured responses were not consumed by the test.
* Useful for calling in `afterEach` to ensure test configurations are precise.
*/
assertNoPendingResponses(): void {
const pendingMessages = this.messageResponses.length;
const pendingTexts = this.textResponses.length;
if (pendingMessages > 0 || pendingTexts > 0) {
this.reset(); // Clear to prevent cascading failures
throw new Error(`MockLLM Error: Test finished with ${pendingMessages} unconsumed message responses and ${pendingTexts} unconsumed text responses.`);
}
}
// =================================================================
// Production-Facing API: Implementation of the LLM interface
// =================================================================
/**
* Overrides `BaseLLM.generateText` to route calls to either `_generateText` or `_generateMessage`
* based on the arguments. This preserves the dual-queue system of `MockLLM` and allows it to
* handle both simple string prompts and complex message arrays.
*/
generateText(userPrompt: string, opts?: GenerateTextOptions): Promise<string>;
generateText(systemPrompt: string, userPrompt: string, opts?: GenerateTextOptions): Promise<string>;
generateText(messages: ReadonlyArray<LlmMessage>, opts?: GenerateTextOptions): Promise<string>;
async generateText(
userOrSystemOrMessages: string | ReadonlyArray<LlmMessage>,
userOrOpts?: string | GenerateTextOptions,
opts?: GenerateTextOptions,
): Promise<string> {
// If the original call was with a message array, use the message-based generation.
if (Array.isArray(userOrSystemOrMessages)) {
const assistantMessage = await this._generateMessage(userOrSystemOrMessages, userOrOpts as GenerateTextOptions);
return messageText(assistantMessage);
}
// Otherwise, it was a string-based call, so use the text-based generation.
const hasSystemPrompt = typeof userOrOpts === 'string';
const systemPrompt = hasSystemPrompt ? (userOrSystemOrMessages as string) : undefined;
const userPrompt = hasSystemPrompt ? (userOrOpts as string) : (userOrSystemOrMessages as string);
const theOpts = hasSystemPrompt ? opts : (userOrOpts as GenerateTextOptions);
return this._generateText(systemPrompt, userPrompt, theOpts);
}
protected async _generateMessage(messages: ReadonlyArray<LlmMessage>, opts?: GenerateTextOptions): Promise<LlmMessage> {
this.calls.push({ type: 'generateMessage', messages, options: opts });
const responseFn = this.messageResponses.shift();
if (!responseFn) {
throw new Error(`MockLLM: No more responses configured for generateMessage. Call count: ${this.getCallCount()}`);
}
const assistantMessage = await responseFn();
await this.saveLlmCall(messages, assistantMessage, opts);
return assistantMessage;
}
protected async _generateText(systemPrompt: string | undefined, userPrompt: string, opts?: GenerateTextOptions): Promise<string> {
this.calls.push({ type: 'generateText', systemPrompt, userPrompt, options: opts });
const responseFn = this.textResponses.shift();
if (!responseFn) {
throw new Error(`MockLLM: No more responses configured for generateText. Call count: ${this.getCallCount()}`);
}
const messages: LlmMessage[] = [];
if (systemPrompt) messages.push(system(systemPrompt));
messages.push(user(userPrompt));
const responseText = await responseFn();
const assistantMessage: LlmMessage = { role: 'assistant', content: responseText };
await this.saveLlmCall(messages, assistantMessage, opts);
return responseText;
}
/**
* Shared logic to persist the LLM call for both generateMessage and generateText,
* simulating the behavior of a real LLM integration.
*/
private async saveLlmCall(requestMessages: ReadonlyArray<LlmMessage>, assistantMessage: LlmMessage, opts?: GenerateTextOptions): Promise<void> {
const description = opts?.id ?? '';
return withActiveSpan(`saveLlmCall ${description}`, async (span) => {
const fullPromptText = requestMessages.map((m) => messageText(m)).join('\n');
const responseText = messageText(assistantMessage);
const llmCallSave: Promise<LlmCall> = appContext().llmCallService.saveRequest({
messages: requestMessages as LlmMessage[],
llmId: this.getId(),
agentId: agentContext()?.agentId,
callStack: callStack(),
description,
settings: opts,
});
const requestTime = Date.now();
const timeToFirstToken = 1;
const finishTime = Date.now();
const llmCall: LlmCall = await llmCallSave;
const inputTokens = await this.countTokens(fullPromptText);
const outputTokens = await this.countTokens(responseText);
const { totalCost } = this.calculateCosts(inputTokens, outputTokens);
addCost(totalCost);
llmCall.timeToFirstToken = timeToFirstToken;
llmCall.totalTime = finishTime - requestTime;
llmCall.cost = totalCost;
llmCall.inputTokens = inputTokens;
llmCall.outputTokens = outputTokens;
assistantMessage.stats = {
llmId: this.getId(),
cost: totalCost,
inputTokens,
outputTokens,
requestTime,
timeToFirstToken,
totalTime: llmCall.totalTime,
};
llmCall.messages = [...llmCall.messages, assistantMessage];
span.setAttributes({
inputChars: fullPromptText.length,
outputChars: responseText.length,
inputTokens,
outputTokens,
cost: totalCost,
model: this.model,
service: this.service,
description,
});
try {
await appContext().llmCallService.saveResponse(llmCall);
} catch (e) {
logger.error(e, 'Failed to save MockLLM response');
}
});
}
}
export const mockLLM = new MockLLM();
export function mockLLMRegistry(): Record<string, () => LLM> {
return {
// Tests need the same instance returned
'mock:mock': () => mockLLM,
};
}
export function mockLLMs(): AgentLLMs {
return {
easy: mockLLM,
medium: mockLLM,
hard: mockLLM,
xhard: mockLLM,
};
}
]]></file_content>
<file_content file_path="src/swe/coder/validators/moduleAliasRule.ts"><![CDATA[
import type { EditBlock } from '../coderTypes';
import type { ValidationIssue, ValidationRule } from './validationRule';
/**
* Sometimes the search/replace coder will write a file with the module alias e.g. #shard/common.service.ts instead of src/shard/common.service.ts
* We want to detect and prevent this.
*/
export class ModuleAliasRule implements ValidationRule {
readonly name = 'ModuleAliasRule';
async check(block: EditBlock, _repoFiles: string[]): Promise<ValidationIssue | null> {
// Make sure we haven't parsed a markdown header (e.g starting with '# ', '## ', '### '). Regex match on #'s then space.
const pathIsMarkdownHeader = block.filePath.match(/^#\s/);
if ((block.filePath.startsWith('#') && !pathIsMarkdownHeader) || block.filePath.startsWith('@')) {
return {
file: block.filePath,
reason: `File path "${block.filePath}" should not begin with '${block.filePath.charAt(0)}'. It seems like you're writing to a module alias. You need to write to a real file path.`,
};
}
return null;
}
}
]]></file_content>
<file_content file_path="src/swe/coder/validators/compositeValidator.ts"><![CDATA[
import type { EditBlock } from '../coderTypes';
import type { ValidationIssue, ValidationRule } from './validationRule';
export interface ValidateBlocksResult {
valid: EditBlock[];
issues: ValidationIssue[];
}
/**
* Validates a list of edit blocks against a set of validation rules.
* @param blocks The edit blocks to validate.
* @param repoFiles A list of all file paths in the repository.
* @param rules An array of validation rules to apply.
* @returns An object containing arrays of valid blocks and any validation issues found.
*/
export async function validateBlocks(blocks: EditBlock[], repoFiles: string[], rules: ValidationRule[]): Promise<ValidateBlocksResult> {
const valid: EditBlock[] = [];
const issues: ValidationIssue[] = [];
const blockIssuesCache = new Map<EditBlock, ValidationIssue[]>();
for (const block of blocks) {
let blockIsValid = true;
const currentBlockIssues: ValidationIssue[] = [];
for (const rule of rules) {
const issue: ValidationIssue | null = await rule.check(block, repoFiles);
if (issue) {
currentBlockIssues.push(issue);
blockIsValid = false;
// Do not break here, collect all issues for this block from all rules
}
}
if (blockIsValid) {
valid.push(block);
} else {
issues.push(...currentBlockIssues);
// Optionally, store per-block issues if needed later, though current return aggregates all issues.
// blockIssuesCache.set(block, currentBlockIssues);
}
}
// If a block has any issue, it's not in `valid`. `issues` contains all found issues.
// If a block is invalid, it should not be processed. The current logic correctly excludes them from `valid`.
// The requirement is to return {valid: EditBlock[], issues: ValidationIssue[]}
// where `issues` are for the blocks that were *not* valid.
return { valid, issues };
}
]]></file_content>
<file_content file_path="src/swe/coder/fixSearchReplaceBlock.ts"><![CDATA[
import path from 'node:path';
import { logger } from '#o11y/logger';
import { LLM, LlmMessage, user } from '#shared/llm/llm.model';
import { EditBlock } from './coderTypes';
import { parseEditResponse } from './editBlockParser';
export async function tryFixSearchBlock(failedEdit: EditBlock, fileContentSnapshot: string, llm: LLM, fence: [string, string]): Promise<EditBlock | null> {
const lang = path.extname(failedEdit.filePath).substring(1) || 'text';
const fixPromptMessages: LlmMessage[] = [
user(
`You are an expert at correcting SEARCH/REPLACE blocks for code editing.
You will be given the content of a file and a SEARCH/REPLACE block that failed to apply, likely because the SEARCH part does not exactly match any segment of the file.
Your task is to:
1. Analyze the provided file content for the file: ${failedEdit.filePath}
2. Analyze the failed SEARCH/REPLACE block.
3. Modify *only* the SEARCH part of the block so that it exactly matches a contiguous segment of the provided file content.
- The corrected SEARCH part should be as short as possible while still being unique and accurately targeting the intended change location.
- Aim to preserve the original intent of the change.
4. Do *NOT* change the file path.
5. Do *NOT* change the REPLACE part.
6. Return *only* the complete, corrected SEARCH/REPLACE block in the specified format. Do not add any explanations or other text.
File content for: ${failedEdit.filePath}
${fence[0]}${lang}
${fileContentSnapshot}
${fence[1]}
Failed SEARCH/REPLACE block for: ${failedEdit.filePath}
${fence[0]}${lang}
<<<<<<< SEARCH
${failedEdit.originalText}=======
${failedEdit.updatedText}>>>>>>> REPLACE
${fence[1]}
Correct the SEARCH part and provide the full block:`,
),
];
// logger.debug({ prompt: fixPromptMessages[0].content }, 'SearchReplaceCoder: Sending prompt to fix search block.');
const fixedBlockText = await llm.generateText(fixPromptMessages, {
id: `SearchReplaceCoder.fixSearchBlock.${failedEdit.filePath}`,
temperature: 0.05, // Low temperature for precise correction
});
if (!fixedBlockText?.trim()) {
logger.warn('LLM returned empty response for search block fix.', { filePath: failedEdit.filePath });
return null;
}
const parsedFix = parseEditResponse(fixedBlockText, 'diff', fence); // Assuming 'diff' format for the fix
if (parsedFix.length === 1 && parsedFix[0].filePath === failedEdit.filePath) {
// Basic validation: ensure it's one block and for the same file.
// More validation could be added (e.g., REPLACE part is unchanged).
if (parsedFix[0].updatedText.trim() === failedEdit.updatedText.trim()) {
logger.info(`Successfully parsed corrected block for ${failedEdit.filePath}.`);
return parsedFix[0];
}
logger.warn('Corrected block changed the REPLACE part. Discarding.', {
filePath: failedEdit.filePath,
originalReplace: failedEdit.updatedText,
newReplace: parsedFix[0].updatedText,
});
return null;
}
logger.warn('Failed to parse corrected block or filePath mismatch.', {
filePath: failedEdit.filePath,
parsedCount: parsedFix.length,
parsedFilePath: parsedFix[0]?.filePath,
rawResponse: fixedBlockText,
});
return null;
}
]]></file_content>
<file_content file_path="src/swe/coder/editSession.ts"><![CDATA[
import { v4 as uuidv4 } from 'uuid';
import type { EditBlock } from './coderTypes'; // Assuming EditBlock is still in applySearchReplace
export interface RequestedFileEntry {
filePath: string;
reason: string;
}
export interface RequestedQueryEntry {
query: string;
reason?: string; // Optional: if LLM provides a reason for the query
}
export interface RequestedPackageInstallEntry {
packageName: string;
reason: string;
}
export interface EditSession {
id: string; // uuid()
workingDir: string;
attempt: number;
// input & result
llmRequest: string;
llmResponse?: string;
parsedBlocks?: EditBlock[];
validatedBlocks?: EditBlock[];
appliedFiles?: Set<string>; // Relative paths of successfully edited files
reflectionMessages: string[];
requestedFiles?: RequestedFileEntry[]; // To store parsed file requests from LLM
requestedQueries?: RequestedQueryEntry[]; // New: To store parsed query requests
requestedPackageInstalls?: RequestedPackageInstallEntry[]; // New: To store parsed package install requests
// state snapshots
absFnamesInChat?: Set<string>; // Absolute paths of files explicitly in chat
initiallyDirtyFiles?: Set<string>; // Relative paths of files that were dirty when we started
fileContentSnapshots: Map<string, string | null>; // Snapshots of file contents before an attempt
}
export function newSession(workingDir: string, llmRequest: string): EditSession {
return {
id: uuidv4(),
workingDir,
attempt: 0,
llmRequest,
reflectionMessages: [],
absFnamesInChat: new Set(),
initiallyDirtyFiles: new Set(),
fileContentSnapshots: new Map<string, string | null>(),
requestedFiles: undefined,
requestedQueries: undefined, // Initialize as undefined
requestedPackageInstalls: undefined, // Initialize as undefined
};
}
]]></file_content>
<file_content file_path="src/swe/coder/editApplier.ts"><![CDATA[
import * as path from 'node:path';
import { logger } from '#o11y/logger';
import type { IFileSystemService } from '#shared/files/fileSystemService';
import type { VersionControlSystem } from '#shared/scm/versionControlSystem';
import type { EditBlock } from './coderTypes';
import { doReplace } from './patchUtils'; // Updated import
export class EditApplier {
constructor(
private fs: IFileSystemService,
private vcs: VersionControlSystem | null,
private lenientWhitespace: boolean,
private fence: [string, string],
private rootPath: string, // Absolute path to the project root
private absFnamesInChat: Set<string>, // Absolute paths of files explicitly in chat for fallback
private autoCommit: boolean, // For committing successful edits
private dryRun: boolean,
) {}
private getRepoFilePath(relativePath: string): string {
return path.resolve(this.rootPath, relativePath);
}
private getRelativeFilePath(absolutePath: string): string {
return path.relative(this.rootPath, absolutePath);
}
private async fileExists(absolutePath: string): Promise<boolean> {
return this.fs.fileExists(absolutePath);
}
private async readText(absolutePath: string): Promise<string | null> {
try {
return await this.fs.readFile(absolutePath);
} catch (e: any) {
logger.warn(`Failed to read file at ${absolutePath}: ${e.message}`);
return null;
}
}
private async writeText(absolutePath: string, content: string): Promise<void> {
// Note: content is expected to end with a newline, as ensured by the _doReplace processing chain.
await this.fs.writeFile(absolutePath, content);
}
async apply(blocks: EditBlock[]): Promise<{ appliedFilePaths: Set<string>; failedEdits: EditBlock[] }> {
const appliedFilePaths = new Set<string>(); // Stores relative paths
const failedEdits: EditBlock[] = [];
for (const edit of blocks) {
const originalRelativePath = edit.filePath;
const originalAbsolutePath = this.getRepoFilePath(originalRelativePath);
let currentContent: string | null = null;
if (await this.fileExists(originalAbsolutePath)) {
currentContent = await this.readText(originalAbsolutePath);
}
let newContent = doReplace(originalRelativePath, currentContent, edit.originalText, edit.updatedText, this.fence, this.lenientWhitespace);
let appliedToAbsolutePath = originalAbsolutePath;
let appliedRelativePath = originalRelativePath;
// Fallback logic
if (newContent === undefined && currentContent !== null) {
logger.debug(`Edit for ${originalRelativePath} failed. Attempting fallback on other in-chat files.`);
for (const chatFileAbs of this.absFnamesInChat) {
if (chatFileAbs === originalAbsolutePath) continue;
const chatFileRel = this.getRelativeFilePath(chatFileAbs);
let fallbackContent: string | null = null;
if (await this.fileExists(chatFileAbs)) {
fallbackContent = await this.readText(chatFileAbs);
}
if (fallbackContent !== null) {
const fallbackNewContent = doReplace(chatFileRel, fallbackContent, edit.originalText, edit.updatedText, this.fence, this.lenientWhitespace);
if (fallbackNewContent !== undefined) {
logger.info(`Applied edit originally for ${originalRelativePath} to ${chatFileRel} as a fallback.`);
newContent = fallbackNewContent;
appliedToAbsolutePath = chatFileAbs;
appliedRelativePath = chatFileRel;
break; // Found a successful fallback
}
}
}
}
if (newContent !== undefined) {
if (!this.dryRun) {
try {
await this.writeText(appliedToAbsolutePath, newContent);
} catch (e: any) {
logger.error(`Failed to write applied edit to ${appliedRelativePath}: ${e.message}`);
failedEdits.push({ ...edit, filePath: originalRelativePath }); // Report failure against original path
continue;
}
}
logger.info(`Successfully applied edit to ${appliedRelativePath}${this.dryRun ? ' (dry run)' : ''}`);
appliedFilePaths.add(appliedRelativePath);
} else {
logger.warn(`Failed to apply edit for ${originalRelativePath}, no suitable match or fallback found.`);
failedEdits.push(edit);
}
}
if (this.autoCommit && !this.dryRun && this.vcs && appliedFilePaths.size > 0) {
const commitMessage = 'Applied LLM-generated edits';
try {
const filesToCommit = Array.from(appliedFilePaths);
// Use the more precise method already available in the interface
await this.vcs.addAndCommitFiles(filesToCommit, commitMessage);
logger.info(`Auto-committed changes for ${filesToCommit.length} files: ${filesToCommit.join(', ')}.`);
} catch (commitError: any) {
logger.error({ err: commitError }, 'Auto-commit failed after applying edits.');
// This error is logged, but doesn't make the apply operation fail at this stage.
// The orchestrator (SearchReplaceCoder) might handle this if it's critical.
}
}
return { appliedFilePaths, failedEdits };
}
}
]]></file_content>
<file_content file_path="src/swe/coder/reflectionUtils.ts"><![CDATA[
import * as path from 'node:path';
import { logger } from '#o11y/logger'; // Added for potential logging within utils if needed
import type { IFileSystemService } from '#shared/files/fileSystemService';
import type { EditBlock } from './coderTypes';
import type { ValidationIssue } from './validators/validationRule';
export function buildValidationIssuesReflection(issues: ValidationIssue[]): string {
let reflectionText = 'There were issues with the file paths or structure of your proposed changes:\n';
for (const issue of issues) {
reflectionText += `- File "${issue.file}": ${issue.reason}\n`;
}
reflectionText += 'Please correct these issues and resubmit your changes.';
return reflectionText;
}
export async function buildFailedEditsReflection(
failedEdits: EditBlock[],
numPassed: number,
fs: IFileSystemService,
rootPath: string, // Equivalent to session.workingDir