genaicode 0.0.31

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +130 -0
  3. package/bin/genaicode.cjs +8 -0
  4. package/bin/genaicode.js +5 -0
  5. package/bin/vertex-monkey-patch.cjs +33 -0
  6. package/media/demo-for-readme.gif +0 -0
  7. package/media/logo-dark.png +0 -0
  8. package/media/logo.png +0 -0
  9. package/package.json +58 -0
  10. package/src/ai-service/anthropic.js +91 -0
  11. package/src/ai-service/chat-gpt.js +96 -0
  12. package/src/ai-service/common.js +40 -0
  13. package/src/ai-service/dall-e.js +29 -0
  14. package/src/ai-service/function-calling.js +320 -0
  15. package/src/ai-service/vertex-ai-claude.js +95 -0
  16. package/src/ai-service/vertex-ai.js +155 -0
  17. package/src/cli/cli-options.js +106 -0
  18. package/src/cli/cli-options.test.js +25 -0
  19. package/src/cli/cli-params.js +84 -0
  20. package/src/cli/cli-params.test.js +43 -0
  21. package/src/cli/service-autodetect.js +11 -0
  22. package/src/cli/service-autodetect.test.js +43 -0
  23. package/src/cli/validate-cli-params.js +90 -0
  24. package/src/cli/validate-cli-params.test.js +103 -0
  25. package/src/files/find-files.js +148 -0
  26. package/src/files/read-files.js +41 -0
  27. package/src/files/update-files.js +118 -0
  28. package/src/main/codegen.js +113 -0
  29. package/src/main/codegen.test.js +186 -0
  30. package/src/prompt/limits.js +23 -0
  31. package/src/prompt/limits.test.js +40 -0
  32. package/src/prompt/prompt-codegen.js +106 -0
  33. package/src/prompt/prompt-codegen.test.js +116 -0
  34. package/src/prompt/prompt-consts.js +1 -0
  35. package/src/prompt/prompt-service.js +211 -0
  36. package/src/prompt/prompt-service.test.js +486 -0
  37. package/src/prompt/systemprompt.js +32 -0
  38. package/src/prompt/systemprompt.test.js +60 -0
@@ -0,0 +1,116 @@
1
+ /*eslint-disable no-import-assign*/
2
+
3
+ import { describe, it, expect, vi, beforeEach } from 'vitest';
4
+ import { getCodeGenPrompt, getLintFixPrompt } from './prompt-codegen.js';
5
+ import * as findFiles from '../files/find-files.js';
6
+ import * as cliParams from '../cli/cli-params.js';
7
+ import * as limits from './limits.js';
8
+ import '../files/read-files.js';
9
+
10
+ vi.mock('../files/find-files.js', () => ({
11
+ rcConfig: {},
12
+ getSourceFiles: vi.fn(),
13
+ }));
14
+ vi.mock('../files/read-files.js', () => ({
15
+ getSourceCode: () => ({}),
16
+ }));
17
+ vi.mock('../cli/cli-params.js', () => ({
18
+ requireExplanations: false,
19
+ considerAllFiles: false,
20
+ dependencyTree: false,
21
+ explicitPrompt: false,
22
+ allowFileCreate: false,
23
+ allowFileDelete: false,
24
+ allowDirectoryCreate: false,
25
+ allowFileMove: false,
26
+ verbosePrompt: false,
27
+ imagen: false,
28
+ vision: false,
29
+ }));
30
+ vi.mock('./limits.js');
31
+
32
+ describe('getCodeGenPrompt', () => {
33
+ beforeEach(() => {
34
+ vi.resetAllMocks();
35
+ });
36
+
37
+ it('should generate prompt for all files when considerAllFiles is true', () => {
38
+ vi.spyOn(findFiles, 'getSourceFiles').mockReturnValue(['file1.js', 'file2.js']);
39
+ cliParams.considerAllFiles = true;
40
+ cliParams.explicitPrompt = null;
41
+ cliParams.allowFileCreate = false;
42
+ cliParams.allowFileDelete = false;
43
+ cliParams.allowDirectoryCreate = false;
44
+ cliParams.allowFileMove = false;
45
+ vi.spyOn(limits, 'verifyCodegenPromptLimit').mockImplementation(() => {});
46
+
47
+ const prompt = getCodeGenPrompt();
48
+
49
+ expect(prompt).toContain('You are allowed to modify all files in the application');
50
+ expect(prompt).toContain('Do not create new files.');
51
+ expect(prompt).toContain('Do not delete files.');
52
+ expect(prompt).toContain('Do not create new directories.');
53
+ expect(prompt).toContain('Do not move files.');
54
+ });
55
+
56
+ // Add more test cases for getCodeGenPrompt as needed
57
+ });
58
+
59
+ describe('getLintFixPrompt', () => {
60
+ beforeEach(() => {
61
+ cliParams.verbosePrompt = false;
62
+ vi.spyOn(limits, 'verifyCodegenPromptLimit').mockImplementation(() => {});
63
+ });
64
+
65
+ it('should generate a lint fix prompt with provided command, stdout, and stderr', () => {
66
+ const command = 'eslint --fix';
67
+ const stdout = 'Fixed 2 errors';
68
+ const stderr = '';
69
+
70
+ const prompt = getLintFixPrompt(command, stdout, stderr);
71
+
72
+ expect(prompt).toContain('The following lint errors were encountered after the initial code generation:');
73
+ expect(prompt).toContain(`Lint command: ${command}`);
74
+ expect(prompt).toContain('Lint command stdout:');
75
+ expect(prompt).toContain(stdout);
76
+ expect(prompt).toContain('Lint command stderr:');
77
+ expect(prompt).toContain('Please suggest changes to fix these lint errors.');
78
+ });
79
+
80
+ it('should include stderr in the prompt when provided', () => {
81
+ const command = 'eslint --fix';
82
+ const stdout = '';
83
+ const stderr = 'Error: Unable to resolve path';
84
+
85
+ const prompt = getLintFixPrompt(command, stdout, stderr);
86
+
87
+ expect(prompt).toContain('Lint command stderr:');
88
+ expect(prompt).toContain(stderr);
89
+ });
90
+
91
+ it('should call verifyCodegenPromptLimit with the generated prompt', () => {
92
+ const command = 'eslint --fix';
93
+ const stdout = 'Fixed 1 error';
94
+ const stderr = '';
95
+
96
+ getLintFixPrompt(command, stdout, stderr);
97
+
98
+ expect(limits.verifyCodegenPromptLimit).toHaveBeenCalledWith(expect.any(String));
99
+ });
100
+
101
+ it('should log the prompt when verbosePrompt is true', () => {
102
+ cliParams.verbosePrompt = true;
103
+ const consoleSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
104
+
105
+ const command = 'eslint --fix';
106
+ const stdout = 'Fixed 1 error';
107
+ const stderr = '';
108
+
109
+ getLintFixPrompt(command, stdout, stderr);
110
+
111
+ expect(consoleSpy).toHaveBeenCalledWith('Lint fix prompt:');
112
+ expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining('The following lint errors were encountered'));
113
+
114
+ consoleSpy.mockRestore();
115
+ });
116
+ });
@@ -0,0 +1 @@
1
+ export const CODEGEN_TRIGGER = '@' + 'CODEGEN';
@@ -0,0 +1,211 @@
1
+ import assert from 'node:assert';
2
+ import fs from 'fs';
3
+ import * as diff from 'diff';
4
+ import mime from 'mime-types';
5
+
6
+ import { getSystemPrompt } from './systemprompt.js';
7
+ import { getCodeGenPrompt } from './prompt-codegen.js';
8
+ import { functionDefs } from '../ai-service/function-calling.js';
9
+ import { getSourceCode, getImageAssets } from '../files/read-files.js';
10
+ import { disableContextOptimization, temperature, vision, imagen } from '../cli/cli-params.js';
11
+ import { generateImage } from '../ai-service/dall-e.js';
12
+
13
+ /** A function that communicates with model using */
14
+ export async function promptService(generateContentFn, codegenPrompt = getCodeGenPrompt()) {
15
+ const messages = prepareMessages(codegenPrompt);
16
+
17
+ // First stage: generate code generation summary, which should not take a lot of output tokens
18
+ const getSourceCodeRequest = { name: 'getSourceCode' };
19
+
20
+ const prompt = [
21
+ { type: 'systemPrompt', systemPrompt: getSystemPrompt() },
22
+ { type: 'user', text: messages.suggestSourceCode },
23
+ { type: 'assistant', text: messages.requestSourceCode, functionCalls: [getSourceCodeRequest] },
24
+ ];
25
+
26
+ const getSourceCodeResponse = {
27
+ type: 'user',
28
+ functionResponses: [{ name: 'getSourceCode', content: messages.sourceCode }],
29
+ };
30
+ prompt.push(getSourceCodeResponse);
31
+
32
+ if (vision) {
33
+ prompt.slice(-1)[0].text = messages.suggestImageAssets;
34
+ prompt.push(
35
+ ...[
36
+ { type: 'assistant', text: messages.requestImageAssets, functionCalls: [{ name: 'getImageAssets' }] },
37
+ {
38
+ type: 'user',
39
+ functionResponses: [{ name: 'getImageAssets', content: messages.imageAssets }],
40
+ },
41
+ ],
42
+ );
43
+ }
44
+
45
+ prompt.slice(-1)[0].text = messages.prompt;
46
+
47
+ let baseResult = await generateContentFn(prompt, functionDefs, 'codegenSummary', temperature);
48
+
49
+ const codegenSummaryRequest = baseResult.find((call) => call.name === 'codegenSummary');
50
+
51
+ if (codegenSummaryRequest) {
52
+ // Second stage: for each file request the actual code updates
53
+ console.log('Received codegen summary, will collect partial updates', codegenSummaryRequest.args);
54
+
55
+ // Sometimes the result happens to be a string
56
+ assert(Array.isArray(codegenSummaryRequest.args.files), 'files is not an array');
57
+ assert(Array.isArray(codegenSummaryRequest.args.contextPaths), 'contextPaths is not an array');
58
+
59
+ if (codegenSummaryRequest.args.contextPaths.length > 0 && !disableContextOptimization) {
60
+ console.log('Optimize with context paths.');
61
+ // Monkey patch the initial getSourceCode, do not send parts of source code that are consider irrelevant
62
+ getSourceCodeRequest.args = {
63
+ filePaths: [
64
+ ...codegenSummaryRequest.args.files.map((file) => file.path),
65
+ ...codegenSummaryRequest.args.contextPaths,
66
+ ],
67
+ };
68
+ getSourceCodeResponse.functionResponses.find((item) => item.name === 'getSourceCode').content =
69
+ messages.contextSourceCode(getSourceCodeRequest.args.filePaths);
70
+ }
71
+
72
+ // Store the first stage response entirely in conversation history
73
+ prompt.push({ type: 'assistant', functionCalls: baseResult });
74
+ prompt.push({
75
+ type: 'user',
76
+ functionResponses: baseResult.map((call) => ({ name: call.name, call_id: call.id })),
77
+ });
78
+
79
+ const result = [];
80
+
81
+ for (const file of codegenSummaryRequest.args.files) {
82
+ console.log('Collecting partial update for: ' + file.path + ' using tool: ' + file.updateToolName);
83
+ console.log('- Prompt:', file.prompt);
84
+ console.log('- Temperature', file.temperature);
85
+ if (vision) {
86
+ console.log('- Context image assets', file.contextImageAssets);
87
+ }
88
+
89
+ // this is needed, otherwise we will get an error
90
+ if (prompt.slice(-1)[0].type === 'user') {
91
+ prompt.slice(-1)[0].text = file.prompt ?? messages.partialPromptTemplate(file.path);
92
+ } else {
93
+ prompt.push({ type: 'user', text: file.prompt ?? messages.partialPromptTemplate(file.path) });
94
+ }
95
+
96
+ if (vision) {
97
+ prompt.slice(-1)[0].images = file.contextImageAssets.map((path) => ({
98
+ path,
99
+ base64url: fs.readFileSync(path, 'base64'),
100
+ mediaType: mime.lookup(path),
101
+ }));
102
+ }
103
+
104
+ let partialResult = await generateContentFn(
105
+ prompt,
106
+ functionDefs,
107
+ file.updateToolName,
108
+ file.temperature ?? temperature,
109
+ );
110
+
111
+ let getSourceCodeCall = partialResult.find((call) => call.name === 'getSourceCode');
112
+ assert(!getSourceCodeCall, 'Unexpected getSourceCode: ' + JSON.stringify(getSourceCodeCall));
113
+
114
+ // Handle image generation requests
115
+ const generateImageCall = partialResult.find((call) => call.name === 'generateImage');
116
+ if (generateImageCall) {
117
+ assert(imagen, 'Image generation requested, but --imagen option not provided');
118
+
119
+ console.log('Processing image generation request:', generateImageCall.args);
120
+ try {
121
+ const { prompt: imagePrompt, filePath, size } = generateImageCall.args;
122
+ const generatedImageUrl = await generateImage(imagePrompt, size);
123
+
124
+ // Add a createFile call to the result to ensure the generated image is tracked
125
+ partialResult.push({
126
+ name: 'downloadFile',
127
+ args: {
128
+ filePath: filePath,
129
+ downloadUrl: generatedImageUrl,
130
+ explanation: `Downloading generated image`,
131
+ },
132
+ });
133
+ } catch (error) {
134
+ console.error('Error generating image:', error);
135
+ // Add an explanation about the failed image generation
136
+ partialResult.push({
137
+ name: 'explanation',
138
+ args: {
139
+ text: `Failed to generate image: ${error.message}`,
140
+ },
141
+ });
142
+ }
143
+ }
144
+
145
+ // Verify if patchFile is one of the functions called, and test if patch is valid and can be applied successfully
146
+ const patchFileCall = partialResult.find((call) => call.name === 'patchFile');
147
+ if (patchFileCall) {
148
+ const { filePath, patch } = patchFileCall.args;
149
+ console.log('Verification of patch for file:', filePath);
150
+
151
+ let updatedContent;
152
+ const currentContent = fs.readFileSync(filePath, 'utf-8');
153
+
154
+ try {
155
+ updatedContent = diff.applyPatch(currentContent, patch);
156
+ } catch (e) {
157
+ console.log('Error when applying patch', e);
158
+ }
159
+
160
+ if (!updatedContent) {
161
+ console.log(`Patch could not be applied for ${filePath}. Retrying without patchFile function.`);
162
+
163
+ // Rerun content generation without patchFile function
164
+ partialResult = await generateContentFn(prompt, functionDefs, 'updateFile', temperature);
165
+
166
+ let getSourceCodeCall = partialResult.find((call) => call.name === 'getSourceCode');
167
+ assert(!getSourceCodeCall, 'Unexpected getSourceCode: ' + JSON.stringify(getSourceCodeCall));
168
+ assert(!partialResult.find((call) => call.name === 'patchFile'), 'Unexpected patchFile in retry response');
169
+ } else {
170
+ console.log('Patch verified successfully');
171
+ }
172
+ }
173
+
174
+ // add the code gen result to the context, as the subsequent code gen may depend on the result
175
+ prompt.push(
176
+ { type: 'assistant', functionCalls: partialResult },
177
+ {
178
+ type: 'user',
179
+ functionResponses: partialResult.map((call) => ({ name: call.name, call_id: call.id })),
180
+ },
181
+ );
182
+
183
+ result.push(...partialResult);
184
+ }
185
+
186
+ return result;
187
+ } else {
188
+ // This is unexpected, if happens probably means no code updates.
189
+ console.log('Did not receive codegen summary, returning result.');
190
+ return baseResult;
191
+ }
192
+ }
193
+
194
+ /**
195
+ * Function to prepare messages for AI services
196
+ */
197
+ function prepareMessages(prompt) {
198
+ return {
199
+ suggestSourceCode: 'I should provide you with application source code.',
200
+ requestSourceCode: 'Please provide application source code.',
201
+ suggestImageAssets: 'I should also provide you with a summary of application image assets',
202
+ requestImageAssets: 'Please provide summary of application image assets.',
203
+ prompt: prompt + '\n Start from generating codegen summary, this summary will be used to generate updates.',
204
+ sourceCode: JSON.stringify(getSourceCode()),
205
+ contextSourceCode: (paths) => JSON.stringify(getSourceCode(paths)),
206
+ imageAssets: JSON.stringify(getImageAssets()),
207
+ partialPromptTemplate(path) {
208
+ return `Thank you for providing the summary, now suggest changes for the \`${path}\` file using appropriate tools.`;
209
+ },
210
+ };
211
+ }