genaicode 0.0.37 → 0.1.1

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 (244) hide show
  1. package/bin/genaicode-dev.js +11 -0
  2. package/bin/genaicode.cjs +8 -1
  3. package/dist/ai-service/ai-studio.d.ts +5 -0
  4. package/dist/ai-service/ai-studio.js +135 -0
  5. package/dist/ai-service/ai-studio.js.map +1 -0
  6. package/dist/ai-service/anthropic.d.ts +5 -0
  7. package/dist/ai-service/anthropic.js +133 -0
  8. package/dist/ai-service/anthropic.js.map +1 -0
  9. package/dist/ai-service/chat-gpt.d.ts +5 -0
  10. package/dist/ai-service/chat-gpt.js +131 -0
  11. package/dist/ai-service/chat-gpt.js.map +1 -0
  12. package/dist/ai-service/common.d.ts +57 -0
  13. package/dist/ai-service/common.js +38 -0
  14. package/dist/ai-service/common.js.map +1 -0
  15. package/dist/ai-service/common.test.d.ts +1 -0
  16. package/dist/ai-service/common.test.js +85 -0
  17. package/dist/ai-service/common.test.js.map +1 -0
  18. package/dist/ai-service/dall-e.d.ts +14 -0
  19. package/dist/ai-service/dall-e.js +47 -0
  20. package/dist/ai-service/dall-e.js.map +1 -0
  21. package/dist/ai-service/vertex-ai-claude.d.ts +5 -0
  22. package/dist/ai-service/vertex-ai-claude.js +93 -0
  23. package/dist/ai-service/vertex-ai-claude.js.map +1 -0
  24. package/dist/ai-service/vertex-ai-imagen.d.ts +14 -0
  25. package/dist/ai-service/vertex-ai-imagen.js +74 -0
  26. package/dist/ai-service/vertex-ai-imagen.js.map +1 -0
  27. package/dist/ai-service/vertex-ai.d.ts +7 -0
  28. package/dist/ai-service/vertex-ai.js +147 -0
  29. package/dist/ai-service/vertex-ai.js.map +1 -0
  30. package/dist/cli/cli-options.d.ts +10 -0
  31. package/dist/cli/cli-options.js +124 -0
  32. package/dist/cli/cli-options.js.map +1 -0
  33. package/dist/cli/cli-options.test.d.ts +1 -0
  34. package/dist/cli/cli-options.test.js +34 -0
  35. package/dist/cli/cli-options.test.js.map +1 -0
  36. package/dist/cli/cli-params.d.ts +29 -0
  37. package/dist/cli/cli-params.js +103 -0
  38. package/dist/cli/cli-params.js.map +1 -0
  39. package/dist/cli/cli-params.test.d.ts +1 -0
  40. package/dist/cli/cli-params.test.js +38 -0
  41. package/dist/cli/cli-params.test.js.map +1 -0
  42. package/dist/cli/service-autodetect.d.ts +2 -0
  43. package/dist/cli/service-autodetect.js +17 -0
  44. package/dist/cli/service-autodetect.js.map +1 -0
  45. package/dist/cli/service-autodetect.test.d.ts +1 -0
  46. package/dist/cli/service-autodetect.test.js +38 -0
  47. package/dist/cli/service-autodetect.test.js.map +1 -0
  48. package/dist/cli/validate-cli-params.d.ts +18 -0
  49. package/dist/cli/validate-cli-params.js +128 -0
  50. package/dist/cli/validate-cli-params.js.map +1 -0
  51. package/dist/cli/validate-cli-params.test.d.ts +1 -0
  52. package/dist/cli/validate-cli-params.test.js +106 -0
  53. package/dist/cli/validate-cli-params.test.js.map +1 -0
  54. package/dist/files/file-utils.d.ts +2 -0
  55. package/dist/files/file-utils.js +7 -0
  56. package/dist/files/file-utils.js.map +1 -0
  57. package/dist/files/file-utils.test.d.ts +1 -0
  58. package/dist/files/file-utils.test.js +18 -0
  59. package/dist/files/file-utils.test.js.map +1 -0
  60. package/dist/files/find-files.d.ts +8 -0
  61. package/dist/files/find-files.js +76 -0
  62. package/dist/files/find-files.js.map +1 -0
  63. package/dist/files/read-files.d.ts +13 -0
  64. package/dist/files/read-files.js +61 -0
  65. package/dist/files/read-files.js.map +1 -0
  66. package/dist/files/read-files.test.d.ts +1 -0
  67. package/dist/files/read-files.test.js +89 -0
  68. package/dist/files/read-files.test.js.map +1 -0
  69. package/dist/files/temp-buffer.d.ts +2 -0
  70. package/dist/files/temp-buffer.js +12 -0
  71. package/dist/files/temp-buffer.js.map +1 -0
  72. package/dist/files/update-files.d.ts +5 -0
  73. package/dist/files/update-files.js +197 -0
  74. package/dist/files/update-files.js.map +1 -0
  75. package/dist/images/ensure-alpha.d.ts +1 -0
  76. package/dist/images/ensure-alpha.js +5 -0
  77. package/dist/images/ensure-alpha.js.map +1 -0
  78. package/dist/images/imgly-remove-background.d.ts +2 -0
  79. package/dist/images/imgly-remove-background.js +21 -0
  80. package/dist/images/imgly-remove-background.js.map +1 -0
  81. package/dist/images/resize-image.d.ts +19 -0
  82. package/dist/images/resize-image.js +22 -0
  83. package/dist/images/resize-image.js.map +1 -0
  84. package/dist/images/split-image.d.ts +18 -0
  85. package/dist/images/split-image.js +25 -0
  86. package/dist/images/split-image.js.map +1 -0
  87. package/dist/main/codegen.d.ts +2 -0
  88. package/dist/main/codegen.js +101 -0
  89. package/dist/main/codegen.js.map +1 -0
  90. package/dist/main/codegen.test.d.ts +2 -0
  91. package/dist/main/codegen.test.js +259 -0
  92. package/dist/main/codegen.test.js.map +1 -0
  93. package/dist/main/config-lib.d.ts +8 -0
  94. package/dist/main/config-lib.js +28 -0
  95. package/dist/main/config-lib.js.map +1 -0
  96. package/dist/main/config-lib.test.d.ts +1 -0
  97. package/dist/main/config-lib.test.js +64 -0
  98. package/dist/main/config-lib.test.js.map +1 -0
  99. package/dist/main/config.d.ts +5 -0
  100. package/{src → dist}/main/config.js +16 -22
  101. package/dist/main/config.js.map +1 -0
  102. package/dist/prompt/function-calling-validate.d.ts +3 -0
  103. package/dist/prompt/function-calling-validate.js +27 -0
  104. package/dist/prompt/function-calling-validate.js.map +1 -0
  105. package/dist/prompt/function-calling.d.ts +5 -0
  106. package/{src → dist}/prompt/function-calling.js +25 -24
  107. package/dist/prompt/function-calling.js.map +1 -0
  108. package/dist/prompt/function-defs/ask-question.d.ts +31 -0
  109. package/dist/prompt/function-defs/ask-question.js +32 -0
  110. package/dist/prompt/function-defs/ask-question.js.map +1 -0
  111. package/dist/prompt/function-defs/codegen-summary.d.ts +63 -0
  112. package/dist/prompt/function-defs/codegen-summary.js +80 -0
  113. package/dist/prompt/function-defs/codegen-summary.js.map +1 -0
  114. package/dist/prompt/function-defs/create-directory.d.ts +21 -0
  115. package/dist/prompt/function-defs/create-directory.js +22 -0
  116. package/dist/prompt/function-defs/create-directory.js.map +1 -0
  117. package/dist/prompt/function-defs/create-file.d.ts +25 -0
  118. package/dist/prompt/function-defs/create-file.js +26 -0
  119. package/dist/prompt/function-defs/create-file.js.map +1 -0
  120. package/dist/prompt/function-defs/delete-file.d.ts +21 -0
  121. package/dist/prompt/function-defs/delete-file.js +22 -0
  122. package/dist/prompt/function-defs/delete-file.js.map +1 -0
  123. package/dist/prompt/function-defs/download-file.d.ts +25 -0
  124. package/dist/prompt/function-defs/download-file.js +26 -0
  125. package/dist/prompt/function-defs/download-file.js.map +1 -0
  126. package/dist/prompt/function-defs/explanation.d.ts +17 -0
  127. package/dist/prompt/function-defs/explanation.js +18 -0
  128. package/dist/prompt/function-defs/explanation.js.map +1 -0
  129. package/dist/prompt/function-defs/generate-image.d.ts +48 -0
  130. package/dist/prompt/function-defs/generate-image.js +49 -0
  131. package/dist/prompt/function-defs/generate-image.js.map +1 -0
  132. package/dist/prompt/function-defs/get-image-assets.d.ts +20 -0
  133. package/dist/prompt/function-defs/get-image-assets.js +21 -0
  134. package/dist/prompt/function-defs/get-image-assets.js.map +1 -0
  135. package/dist/prompt/function-defs/get-source-code.d.ts +20 -0
  136. package/dist/prompt/function-defs/get-source-code.js +21 -0
  137. package/dist/prompt/function-defs/get-source-code.js.map +1 -0
  138. package/dist/prompt/function-defs/imgly-remove-background.d.ts +25 -0
  139. package/dist/prompt/function-defs/imgly-remove-background.js +26 -0
  140. package/dist/prompt/function-defs/imgly-remove-background.js.map +1 -0
  141. package/dist/prompt/function-defs/move-file.d.ts +25 -0
  142. package/dist/prompt/function-defs/move-file.js +26 -0
  143. package/dist/prompt/function-defs/move-file.js.map +1 -0
  144. package/dist/prompt/function-defs/patch-file.d.ts +25 -0
  145. package/dist/prompt/function-defs/patch-file.js +39 -0
  146. package/dist/prompt/function-defs/patch-file.js.map +1 -0
  147. package/dist/prompt/function-defs/resize-image.d.ts +36 -0
  148. package/dist/prompt/function-defs/resize-image.js +37 -0
  149. package/dist/prompt/function-defs/resize-image.js.map +1 -0
  150. package/dist/prompt/function-defs/split-image.d.ts +57 -0
  151. package/dist/prompt/function-defs/split-image.js +46 -0
  152. package/dist/prompt/function-defs/split-image.js.map +1 -0
  153. package/dist/prompt/function-defs/update-file.d.ts +25 -0
  154. package/dist/prompt/function-defs/update-file.js +26 -0
  155. package/dist/prompt/function-defs/update-file.js.map +1 -0
  156. package/dist/prompt/limits.d.ts +3 -0
  157. package/dist/prompt/limits.js +19 -0
  158. package/dist/prompt/limits.js.map +1 -0
  159. package/dist/prompt/limits.test.d.ts +1 -0
  160. package/dist/prompt/limits.test.js +35 -0
  161. package/dist/prompt/limits.test.js.map +1 -0
  162. package/dist/prompt/prompt-codegen.d.ts +4 -0
  163. package/dist/prompt/prompt-codegen.js +81 -0
  164. package/dist/prompt/prompt-codegen.js.map +1 -0
  165. package/dist/prompt/prompt-codegen.test.d.ts +1 -0
  166. package/dist/prompt/prompt-codegen.test.js +94 -0
  167. package/dist/prompt/prompt-codegen.test.js.map +1 -0
  168. package/dist/prompt/prompt-consts.d.ts +1 -0
  169. package/{src → dist}/prompt/prompt-consts.js +1 -0
  170. package/dist/prompt/prompt-consts.js.map +1 -0
  171. package/dist/prompt/prompt-service-ask-question.test.d.ts +3 -0
  172. package/dist/prompt/prompt-service-ask-question.test.js +146 -0
  173. package/dist/prompt/prompt-service-ask-question.test.js.map +1 -0
  174. package/dist/prompt/prompt-service.d.ts +13 -0
  175. package/dist/prompt/prompt-service.js +278 -0
  176. package/dist/prompt/prompt-service.js.map +1 -0
  177. package/dist/prompt/prompt-service.test.d.ts +1 -0
  178. package/dist/prompt/prompt-service.test.js +511 -0
  179. package/dist/prompt/prompt-service.test.js.map +1 -0
  180. package/dist/prompt/systemprompt.d.ts +2 -0
  181. package/dist/prompt/systemprompt.js +43 -0
  182. package/dist/prompt/systemprompt.js.map +1 -0
  183. package/dist/prompt/systemprompt.test.d.ts +2 -0
  184. package/dist/prompt/systemprompt.test.js +47 -0
  185. package/dist/prompt/systemprompt.test.js.map +1 -0
  186. package/package.json +13 -4
  187. package/bin/genaicode.js +0 -5
  188. package/src/ai-service/anthropic.js +0 -126
  189. package/src/ai-service/chat-gpt.js +0 -126
  190. package/src/ai-service/common.js +0 -49
  191. package/src/ai-service/common.test.js +0 -107
  192. package/src/ai-service/dall-e.js +0 -50
  193. package/src/ai-service/vertex-ai-claude.js +0 -99
  194. package/src/ai-service/vertex-ai-imagen.js +0 -78
  195. package/src/ai-service/vertex-ai.js +0 -156
  196. package/src/cli/cli-options.js +0 -132
  197. package/src/cli/cli-options.test.js +0 -50
  198. package/src/cli/cli-params.js +0 -114
  199. package/src/cli/cli-params.test.js +0 -43
  200. package/src/cli/service-autodetect.js +0 -11
  201. package/src/cli/service-autodetect.test.js +0 -43
  202. package/src/cli/validate-cli-params.js +0 -137
  203. package/src/cli/validate-cli-params.test.js +0 -134
  204. package/src/files/file-utils.js +0 -7
  205. package/src/files/file-utils.test.js +0 -21
  206. package/src/files/find-files.js +0 -86
  207. package/src/files/read-files.js +0 -65
  208. package/src/files/read-files.test.js +0 -103
  209. package/src/files/temp-buffer.js +0 -13
  210. package/src/files/update-files.js +0 -205
  211. package/src/images/ensure-alpha.js +0 -5
  212. package/src/images/imgly-remove-background.js +0 -23
  213. package/src/images/resize-image.js +0 -23
  214. package/src/images/split-image.js +0 -26
  215. package/src/main/codegen.js +0 -120
  216. package/src/main/codegen.test.js +0 -335
  217. package/src/main/config-lib.js +0 -33
  218. package/src/main/config-lib.test.js +0 -80
  219. package/src/prompt/function-calling-validate.js +0 -25
  220. package/src/prompt/function-defs/ask-question.js +0 -33
  221. package/src/prompt/function-defs/codegen-summary.js +0 -87
  222. package/src/prompt/function-defs/create-directory.js +0 -21
  223. package/src/prompt/function-defs/create-file.js +0 -26
  224. package/src/prompt/function-defs/delete-file.js +0 -21
  225. package/src/prompt/function-defs/download-file.js +0 -25
  226. package/src/prompt/function-defs/explanation.js +0 -17
  227. package/src/prompt/function-defs/generate-image.js +0 -51
  228. package/src/prompt/function-defs/get-image-assets.js +0 -21
  229. package/src/prompt/function-defs/get-source-code.js +0 -21
  230. package/src/prompt/function-defs/imgly-remove-background.js +0 -25
  231. package/src/prompt/function-defs/move-file.js +0 -25
  232. package/src/prompt/function-defs/patch-file.js +0 -39
  233. package/src/prompt/function-defs/resize-image.js +0 -36
  234. package/src/prompt/function-defs/split-image.js +0 -45
  235. package/src/prompt/function-defs/update-file.js +0 -26
  236. package/src/prompt/limits.js +0 -23
  237. package/src/prompt/limits.test.js +0 -40
  238. package/src/prompt/prompt-codegen.js +0 -106
  239. package/src/prompt/prompt-codegen.test.js +0 -116
  240. package/src/prompt/prompt-service-ask-question.test.js +0 -163
  241. package/src/prompt/prompt-service.js +0 -335
  242. package/src/prompt/prompt-service.test.js +0 -602
  243. package/src/prompt/systemprompt.js +0 -39
  244. package/src/prompt/systemprompt.test.js +0 -64
@@ -1,163 +0,0 @@
1
- import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
2
- import { promptService } from './prompt-service.js';
3
- import * as vertexAi from '../ai-service/vertex-ai.js';
4
- import * as readline from 'readline';
5
- import '../cli/cli-params.js';
6
- import '../files/read-files.js';
7
- import '../files/find-files.js';
8
-
9
- vi.mock('../ai-service/vertex-ai.js', () => ({ generateContent: vi.fn() }));
10
- vi.mock('readline', () => ({
11
- createInterface: vi.fn(),
12
- }));
13
- vi.mock('../cli/cli-params.js', () => ({
14
- requireExplanations: false,
15
- considerAllFiles: false,
16
- dependencyTree: false,
17
- explicitPrompt: false,
18
- allowFileCreate: false,
19
- allowFileDelete: false,
20
- allowDirectoryCreate: false,
21
- allowFileMove: false,
22
- verbosePrompt: false,
23
- disableContextOptimization: false,
24
- vision: false,
25
- imagen: false,
26
- temperature: 0.7,
27
- cheap: false,
28
- askQuestion: true,
29
- }));
30
-
31
- // Mock find-files module
32
- vi.mock('../files/find-files.js', () => ({
33
- getSourceFiles: () => [],
34
- getImageAssetFiles: () => [],
35
- }));
36
-
37
- // Mock read-files module
38
- vi.mock('../files/read-files.js', () => ({
39
- getSourceCode: () => ({}),
40
- getImageAssets: vi.fn(() => ({})),
41
- }));
42
-
43
- vi.mock('../main/config.js', () => ({
44
- rootDir: '/mocked/root/dir',
45
- rcConfig: {
46
- rootDir: '.',
47
- extensions: ['.js', '.ts', '.tsx', '.jsx'],
48
- },
49
- }));
50
-
51
- describe('promptService with askQuestion', () => {
52
- let mockReadline;
53
-
54
- beforeEach(() => {
55
- vi.resetAllMocks();
56
- console.log = vi.fn();
57
-
58
- mockReadline = {
59
- question: vi.fn(),
60
- close: vi.fn(),
61
- };
62
- vi.spyOn(readline, 'createInterface').mockReturnValue(mockReadline);
63
- });
64
-
65
- afterEach(() => {
66
- vi.clearAllMocks();
67
- });
68
-
69
- it('should handle askQuestion when enabled', async () => {
70
- const mockAskQuestionCall = [
71
- {
72
- name: 'askQuestion',
73
- args: {
74
- content: 'Do you want to proceed with code generation?',
75
- shouldPrompt: true,
76
- promptNecessity: 80,
77
- stopCodegen: false,
78
- },
79
- },
80
- ];
81
- const mockAskQuestionCall2 = [
82
- {
83
- name: 'askQuestion',
84
- args: {
85
- content: 'Ok lets go',
86
- shouldPrompt: false,
87
- promptNecessity: 80,
88
- stopCodegen: false,
89
- },
90
- },
91
- ];
92
- const mockCodegenSummary = [
93
- {
94
- name: 'codegenSummary',
95
- args: {
96
- fileUpdates: [],
97
- contextPaths: [],
98
- explanation: 'No updates needed',
99
- },
100
- },
101
- ];
102
-
103
- vertexAi.generateContent
104
- .mockResolvedValueOnce(mockAskQuestionCall)
105
- .mockResolvedValueOnce(mockAskQuestionCall2)
106
- .mockResolvedValueOnce(mockCodegenSummary);
107
-
108
- mockReadline.question.mockImplementationOnce((_, callback) => {
109
- callback('Yes');
110
- });
111
-
112
- await promptService(vertexAi.generateContent);
113
-
114
- expect(vertexAi.generateContent).toHaveBeenCalledTimes(3);
115
- expect(mockReadline.question).toHaveBeenCalledWith('Your answer: ', expect.any(Function));
116
- expect(console.log).toHaveBeenCalledWith('Assistant asks:', expect.any(Object));
117
- expect(console.log).toHaveBeenCalledWith('The question was answered');
118
- });
119
-
120
- it('should stop code generation when askQuestion returns stopCodegen: true', async () => {
121
- const mockAskQuestionCall = [
122
- {
123
- name: 'askQuestion',
124
- args: {
125
- content: 'Stopping code generation as requested.',
126
- shouldPrompt: false,
127
- promptNecessity: 100,
128
- stopCodegen: true,
129
- },
130
- },
131
- ];
132
-
133
- vertexAi.generateContent.mockResolvedValueOnce(mockAskQuestionCall);
134
-
135
- const result = await promptService(vertexAi.generateContent);
136
-
137
- expect(vertexAi.generateContent).toHaveBeenCalledTimes(1);
138
- expect(result).toEqual([]);
139
- expect(console.log).toHaveBeenCalledWith('Assistant requested to stop code generation. Exiting...');
140
- });
141
-
142
- it('should proceed with code generation when askQuestion returns shouldPrompt: false', async () => {
143
- const mockAskQuestionCall = [];
144
- const mockCodegenSummary = [
145
- {
146
- name: 'codegenSummary',
147
- args: {
148
- fileUpdates: [],
149
- contextPaths: [],
150
- explanation: 'No updates needed',
151
- },
152
- },
153
- ];
154
-
155
- vertexAi.generateContent.mockResolvedValueOnce(mockAskQuestionCall).mockResolvedValueOnce(mockCodegenSummary);
156
-
157
- await promptService(vertexAi.generateContent);
158
-
159
- expect(vertexAi.generateContent).toHaveBeenCalledTimes(2);
160
- expect(mockReadline.question).not.toHaveBeenCalled();
161
- expect(console.log).toHaveBeenCalledWith('Assistant did not ask a question. Proceeding with code generation.');
162
- });
163
- });
@@ -1,335 +0,0 @@
1
- import assert from 'node:assert';
2
- import fs from 'fs';
3
- import * as diff from 'diff';
4
- import mime from 'mime-types';
5
- import { createInterface } from 'readline';
6
-
7
- import { getSystemPrompt } from './systemprompt.js';
8
- import { getCodeGenPrompt } from './prompt-codegen.js';
9
- import { functionDefs } from './function-calling.js';
10
- import { getSourceCode, getImageAssets } from '../files/read-files.js';
11
- import { disableContextOptimization, temperature, vision, cheap, askQuestion } from '../cli/cli-params.js';
12
- import { validateFunctionCall } from './function-calling-validate.js';
13
-
14
- /** A function that communicates with model using */
15
- export async function promptService(generateContentFn, generateImageFn, codegenPrompt = getCodeGenPrompt()) {
16
- const messages = prepareMessages(codegenPrompt);
17
-
18
- // First stage: generate code generation summary, which should not take a lot of output tokens
19
- const getSourceCodeRequest = { name: 'getSourceCode' };
20
-
21
- const prompt = [
22
- { type: 'systemPrompt', systemPrompt: getSystemPrompt() },
23
- { type: 'user', text: messages.suggestSourceCode },
24
- { type: 'assistant', text: messages.requestSourceCode, functionCalls: [getSourceCodeRequest] },
25
- ];
26
-
27
- const getSourceCodeResponse = {
28
- type: 'user',
29
- functionResponses: [{ name: 'getSourceCode', content: messages.sourceCode }],
30
- cache: true,
31
- };
32
- prompt.push(getSourceCodeResponse);
33
-
34
- if (vision) {
35
- prompt.slice(-1)[0].text = messages.suggestImageAssets;
36
- prompt.push(
37
- { type: 'assistant', text: messages.requestImageAssets, functionCalls: [{ name: 'getImageAssets' }] },
38
- { type: 'user', functionResponses: [{ name: 'getImageAssets', content: messages.imageAssets }] },
39
- );
40
- }
41
-
42
- prompt.slice(-1)[0].text = messages.prompt;
43
-
44
- // New step: Allow the assistant to ask a question if --ask-question is enabled
45
- if (askQuestion) {
46
- console.log('Allowing the assistant to ask a question...');
47
- let questionAsked = false;
48
- while (!questionAsked) {
49
- const askQuestionResult = await generateContentFn(prompt, functionDefs, 'askQuestion', temperature, cheap);
50
- const askQuestionCall = askQuestionResult.find((call) => call.name === 'askQuestion');
51
- if (askQuestionCall) {
52
- console.log('Assistant asks:', askQuestionCall.args);
53
- const userAnswer = askQuestionCall.args.shouldPrompt
54
- ? await getUserInput('Your answer: ')
55
- : 'Lets proceed with code generation.';
56
- prompt.push(
57
- { type: 'assistant', functionCalls: [askQuestionCall] },
58
- {
59
- type: 'user',
60
- text: userAnswer,
61
- functionResponses: [{ name: 'askQuestion', call_id: askQuestionCall.id }],
62
- },
63
- );
64
- console.log('The question was answered');
65
- if (askQuestionCall.args.stopCodegen) {
66
- console.log('Assistant requested to stop code generation. Exiting...');
67
- return [];
68
- }
69
- if (!askQuestionCall.args.shouldPrompt) {
70
- console.log('Proceeding with code generation.');
71
- break;
72
- }
73
- } else {
74
- console.log('Assistant did not ask a question. Proceeding with code generation.');
75
- break;
76
- }
77
- }
78
- }
79
-
80
- let baseRequest = [prompt, functionDefs, 'codegenSummary', temperature, cheap];
81
- let baseResult = await generateContentFn(...baseRequest);
82
-
83
- let codegenSummaryRequest = baseResult.find((call) => call.name === 'codegenSummary');
84
-
85
- if (codegenSummaryRequest) {
86
- // Second stage: for each file request the actual code updates
87
- console.log('Received codegen summary, will collect partial updates', codegenSummaryRequest.args);
88
-
89
- baseResult = await validateAndRecoverSingleResult(baseRequest, baseResult, messages, generateContentFn);
90
- codegenSummaryRequest = baseResult.find((call) => call.name === 'codegenSummary');
91
-
92
- // Sometimes the result happens to be a string
93
- assert(Array.isArray(codegenSummaryRequest.args.fileUpdates), 'fileUpdates is not an array');
94
- assert(Array.isArray(codegenSummaryRequest.args.contextPaths), 'contextPaths is not an array');
95
-
96
- if (codegenSummaryRequest.args.contextPaths.length > 0 && !disableContextOptimization) {
97
- console.log('Optimize with context paths.');
98
- // Monkey patch the initial getSourceCode, do not send parts of source code that are consider irrelevant
99
- getSourceCodeRequest.args = {
100
- filePaths: [
101
- ...codegenSummaryRequest.args.fileUpdates.map((file) => file.path),
102
- ...codegenSummaryRequest.args.contextPaths,
103
- ],
104
- };
105
- getSourceCodeResponse.functionResponses.find((item) => item.name === 'getSourceCode').content =
106
- messages.contextSourceCode(getSourceCodeRequest.args.filePaths);
107
- }
108
-
109
- // Store the first stage response entirely in conversation history
110
- prompt.push({ type: 'assistant', functionCalls: baseResult });
111
- prompt.push({
112
- type: 'user',
113
- functionResponses: baseResult.map((call) => ({ name: call.name, call_id: call.id })),
114
- cache: true,
115
- });
116
-
117
- const result = [];
118
-
119
- for (const file of codegenSummaryRequest.args.fileUpdates) {
120
- console.log('Collecting partial update for: ' + file.path + ' using tool: ' + file.updateToolName);
121
- console.log('- Prompt:', file.prompt);
122
- console.log('- Temperature', file.temperature);
123
- console.log('- Cheap', file.cheap);
124
- if (vision) {
125
- console.log('- Context image assets', file.contextImageAssets);
126
- }
127
-
128
- // this is needed, otherwise we will get an error
129
- if (prompt.slice(-1)[0].type === 'user') {
130
- prompt.slice(-1)[0].text = file.prompt ?? messages.partialPromptTemplate(file.path);
131
- } else {
132
- prompt.push({ type: 'user', text: file.prompt ?? messages.partialPromptTemplate(file.path) });
133
- }
134
-
135
- if (vision && file.contextImageAssets) {
136
- prompt.slice(-1)[0].images = file.contextImageAssets.map((path) => ({
137
- path,
138
- base64url: fs.readFileSync(path, 'base64'),
139
- mediaType: mime.lookup(path),
140
- }));
141
- }
142
-
143
- let partialRequest = [
144
- prompt,
145
- functionDefs,
146
- file.updateToolName,
147
- file.temperature ?? temperature,
148
- file.cheap === true,
149
- ];
150
- let partialResult = await generateContentFn(...partialRequest);
151
-
152
- let getSourceCodeCall = partialResult.find((call) => call.name === 'getSourceCode');
153
- assert(!getSourceCodeCall, 'Unexpected getSourceCode: ' + JSON.stringify(getSourceCodeCall));
154
-
155
- // Handle image generation requests
156
- const generateImageCall = partialResult.find((call) => call.name === 'generateImage');
157
- if (generateImageCall) {
158
- assert(!!generateImageFn, 'Image generation requested, but a image generation service was not provided');
159
-
160
- console.log('Processing image generation request:', generateImageCall.args);
161
- try {
162
- const { prompt: imagePrompt, filePath, contextImagePath, size, cheap } = generateImageCall.args;
163
- const generatedImageUrl = await generateImageFn(imagePrompt, contextImagePath, size, cheap === true);
164
-
165
- // Add a createFile call to the result to ensure the generated image is tracked
166
- partialResult.push({
167
- name: 'downloadFile',
168
- args: {
169
- filePath: filePath,
170
- downloadUrl: generatedImageUrl,
171
- explanation: `Downloading generated image`,
172
- },
173
- });
174
- } catch (error) {
175
- console.error('Error generating image:', error);
176
- // Add an explanation about the failed image generation
177
- partialResult.push({
178
- name: 'explanation',
179
- args: {
180
- text: `Failed to generate image: ${error.message}`,
181
- },
182
- });
183
- }
184
- } else {
185
- partialResult = await validateAndRecoverSingleResult(
186
- partialRequest,
187
- partialResult,
188
- messages,
189
- generateContentFn,
190
- );
191
- }
192
-
193
- // Verify if patchFile is one of the functions called, and test if patch is valid and can be applied successfully
194
- const patchFileCall = partialResult.find((call) => call.name === 'patchFile');
195
- if (patchFileCall) {
196
- const { filePath, patch } = patchFileCall.args;
197
- console.log('Verification of patch for file:', filePath);
198
-
199
- let updatedContent;
200
- const currentContent = fs.readFileSync(filePath, 'utf-8');
201
-
202
- try {
203
- updatedContent = diff.applyPatch(currentContent, patch);
204
- } catch (e) {
205
- console.log('Error when applying patch', e);
206
- }
207
-
208
- if (!updatedContent) {
209
- console.log(`Patch could not be applied for ${filePath}. Retrying without patchFile function.`);
210
-
211
- // Rerun content generation without patchFile function
212
- partialRequest = [prompt, functionDefs, 'updateFile', file.temperature ?? temperature, file.cheap === true];
213
- partialResult = await generateContentFn(...partialRequest);
214
-
215
- partialResult = await validateAndRecoverSingleResult(
216
- partialRequest,
217
- partialResult,
218
- messages,
219
- generateContentFn,
220
- );
221
-
222
- let getSourceCodeCall = partialResult.find((call) => call.name === 'getSourceCode');
223
- assert(!getSourceCodeCall, 'Unexpected getSourceCode: ' + JSON.stringify(getSourceCodeCall));
224
- assert(!partialResult.find((call) => call.name === 'patchFile'), 'Unexpected patchFile in retry response');
225
- } else {
226
- console.log('Patch verified successfully');
227
- }
228
- }
229
-
230
- // add the code gen result to the context, as the subsequent code gen may depend on the result
231
- prompt.push(
232
- { type: 'assistant', functionCalls: partialResult },
233
- {
234
- type: 'user',
235
- functionResponses: partialResult.map((call) => ({ name: call.name, call_id: call.id })),
236
- },
237
- );
238
-
239
- result.push(...partialResult);
240
- }
241
-
242
- return result;
243
- } else {
244
- // This is unexpected, if happens probably means no code updates.
245
- console.log('Did not receive codegen summary, returning result.');
246
- return baseResult;
247
- }
248
- }
249
-
250
- async function validateAndRecoverSingleResult(
251
- [prompt, functionDefs, requiredFunctionName, temperature, cheap],
252
- result,
253
- messages,
254
- generateContentFn,
255
- ) {
256
- if (result.length !== 1) {
257
- return result;
258
- }
259
-
260
- const call = result[0];
261
- const validatorError = validateFunctionCall(call);
262
- if (validatorError) {
263
- console.log('Invalid function call', call, validatorError);
264
-
265
- prompt.push(
266
- { type: 'assistant', functionCalls: [call] },
267
- {
268
- type: 'user',
269
- text: messages.invalidFunctionCall,
270
- functionResponses: [
271
- {
272
- name: call.name,
273
- call_id: call.id,
274
- content: JSON.stringify({ args: call.args, error: validatorError }),
275
- isError: true,
276
- },
277
- ],
278
- },
279
- );
280
-
281
- console.log('Trying to recover...');
282
- if (cheap) {
283
- console.log('Disabling --cheap for recovery.');
284
- }
285
- result = await generateContentFn(prompt, functionDefs, requiredFunctionName, temperature, false);
286
- console.log('Recover result:', result);
287
-
288
- if (result.length === 1) {
289
- const recoveryError = validateFunctionCall(result[0]);
290
- assert(!recoveryError, 'Recovery failed');
291
- console.log('Recovery was sucessful');
292
- } else {
293
- console.log('Unexpected number of function calls', result);
294
- }
295
- }
296
-
297
- return result;
298
- }
299
-
300
- /**
301
- * Function to prepare messages for AI services
302
- */
303
- function prepareMessages(prompt) {
304
- return {
305
- suggestSourceCode: 'I should provide you with application source code.',
306
- requestSourceCode: 'Please provide application source code.',
307
- suggestImageAssets: 'I should also provide you with a summary of application image assets',
308
- requestImageAssets: 'Please provide summary of application image assets.',
309
- prompt:
310
- prompt +
311
- '\n Start from generating codegen summary, this summary will be used as a context to generate updates, so make sure that it contains useful information.',
312
- sourceCode: JSON.stringify(getSourceCode()),
313
- contextSourceCode: (paths) => JSON.stringify(getSourceCode(paths)),
314
- imageAssets: JSON.stringify(getImageAssets()),
315
- partialPromptTemplate(path) {
316
- return `Thank you for providing the summary, now suggest changes for the \`${path}\` file using appropriate tools.`;
317
- },
318
- invalidFunctionCall:
319
- 'Function call was invalid, please analyze the error and respond with corrected function call.',
320
- };
321
- }
322
-
323
- async function getUserInput(prompt) {
324
- const rl = createInterface({
325
- input: process.stdin,
326
- output: process.stdout,
327
- });
328
-
329
- return new Promise((resolve) => {
330
- rl.question(prompt, (answer) => {
331
- rl.close();
332
- resolve(answer);
333
- });
334
- });
335
- }