-
-
Notifications
You must be signed in to change notification settings - Fork 81
Expand file tree
/
Copy pathcodinitTask.ts
More file actions
452 lines (430 loc) · 15.5 KB
/
Copy pathcodinitTask.ts
File metadata and controls
452 lines (430 loc) · 15.5 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
import { type CoreMessage, generateText, type LanguageModelUsage } from 'ai';
import * as walkdir from 'walkdir';
import { path } from 'codinit-agent/utils/path';
import type { CodinitResult, CodinitModel } from './types';
import { copyFileSync, mkdirSync, readFileSync, statSync, writeFileSync } from 'fs';
import { execFileSync } from 'child_process';
import { ChatContextManager } from 'codinit-agent/ChatContextManager';
import type { UIMessage } from 'ai';
import { deploy, npmInstall, runTypecheck } from './codinitBackend';
import { StreamingMessageParser } from 'codinit-agent/message-parser';
import { withCodinitBackend } from './codinitBackend';
import { initializeCodinitAuth } from 'codinit-agent/codinitAuth';
import { deployTool } from 'codinit-agent/tools/deploy';
import { ROLE_SYSTEM_PROMPT } from 'codinit-agent/prompts/system';
import { generateId } from 'ai';
import type { CodinitToolSet, SystemPromptOptions } from 'codinit-agent/types';
import { npmInstallTool, npmInstallToolParameters } from 'codinit-agent/tools/npmInstall';
import { lookupDocsTool } from 'codinit-agent/tools/lookupDocs';
import { getCodinitDeploymentNameTool } from 'codinit-agent/tools/getCodinitDeploymentName';
import { cleanupAssistantMessages } from 'codinit-agent/cleanupAssistantMessages';
import { generalSystemPrompt } from 'codinit-agent/prompts/system';
import { makePartId } from 'codinit-agent/partId';
import { logger } from 'codinit-agent/utils/logger';
import { traced, wrapTraced } from 'braintrust';
import { viewTool } from 'codinit-agent/tools/view';
import { editTool, editToolParameters } from 'codinit-agent/tools/edit';
import { renderFile } from 'codinit-agent/utils/renderFile';
import { renderDirectory } from 'codinit-agent/utils/renderDirectory';
import { viewParameters } from 'codinit-agent/tools/view';
import { lookupDocsParameters, docs, type DocKey } from 'codinit-agent/tools/lookupDocs';
const MAX_STEPS = 32;
const MAX_DEPLOYS = 10;
const OUTPUT_EXTENSIONS = ['.ts', '.tsx', '.js', '.jsx', '.json'];
const IGNORED_FILENAMES = [
'.gitignore',
'node_modules',
'package-lock.json',
'tsconfig.node.json',
'tailwind.config.js',
'tsconfig.app.json',
'tsconfig.json',
'components.json',
'vite.config.ts',
'vite-env.d.ts',
];
const TEMPLATE_DIR = '../template';
export async function codinitTask(model: CodinitModel, outputDir: string, userMessage: string): Promise<CodinitResult> {
if (!path.isAbsolute(outputDir)) {
throw new Error(`outputDir ${outputDir} must be an absolute path`);
}
const taskDir = path.join(outputDir, `task-${generateId()}`);
mkdirSync(taskDir, { recursive: true });
const repoDir = await setupRepoDir(taskDir);
const backendDir = path.join(taskDir, 'backend');
mkdirSync(backendDir, { recursive: true });
const { numDeploys, usage, success } = await withCodinitBackend(backendDir, async (backend) => {
const contextManager = new ChatContextManager(
() => undefined,
() => ({}),
() => new Map(),
);
const messageParser = new StreamingMessageParser({
callbacks: {
onActionClose: (data) => {
if (data.action.type === 'file' && !IGNORED_FILENAMES.includes(data.action.filePath)) {
const filePath = path.join(repoDir, data.action.filePath);
logger.info(`Writing to ${filePath}`);
mkdirSync(path.dirname(filePath), { recursive: true });
writeFileSync(filePath, data.action.content);
}
},
},
});
// TODO: Set up OpenAI + Resend proxies.
logger.info('Initializing codinit auth');
await wrapTraced(initializeCodinitAuth)(backend.project);
await deploy(repoDir, backend);
const initialUserMessage: UIMessage = {
id: generateId(),
role: 'user',
content: userMessage,
parts: [
{
type: 'text',
text: userMessage,
},
],
};
const opts: SystemPromptOptions = {
enableBulkEdits: true,
includeTemplate: true,
usingOpenAi: model.name.startsWith('gpt-'),
usingGoogle: model.name.startsWith('gemini-'),
// TODO: We need to set up a Codinit deployment running the `codinit`
// app to setup the OpenAI and Resend proxies + manage their tokens.
// For now, we are enabling the proxies to mirror the behavior of production. These
// proxies should never be used in the test kitchen.
openaiProxyEnabled: true,
resendProxyEnabled: true,
enableResend: false,
};
const assistantMessage: UIMessage = {
id: generateId(),
role: 'assistant',
content: '',
parts: [],
};
let numDeploys = 0;
let success: boolean;
let lastDeploySuccess = false;
const totalUsage: LanguageModelUsage = {
promptTokens: 0,
completionTokens: 0,
totalTokens: 0,
};
while (true) {
if (assistantMessage.parts.length >= MAX_STEPS) {
logger.error('Reached max steps, ending test.');
success = false;
break;
}
if (numDeploys >= MAX_DEPLOYS) {
logger.error('Reached max deploys, ending test.');
success = false;
break;
}
const messages = [initialUserMessage];
if (assistantMessage.parts.length > 0) {
messages.push(assistantMessage);
}
const minCollapsedMessagesSize = 8192;
const maxCollapsedMessagesSize = 65536;
const { messages: context } = contextManager.prepareContext(
messages,
maxCollapsedMessagesSize,
minCollapsedMessagesSize,
);
const start = performance.now();
logger.info('Generating...');
const response = await invokeGenerateText(model, opts, context);
const partId = makePartId(assistantMessage.id, assistantMessage.parts.length);
assistantMessage.content += response.text;
if (response.text) {
assistantMessage.parts.push({
type: 'text',
text: response.text,
});
}
const parsed = messageParser.parse(partId, response.text);
logger.info(
`Time taken: ${performance.now() - start}ms\nUsage: ${JSON.stringify(response.usage)}\nMessage: ${parsed}`,
);
totalUsage.promptTokens += response.usage.promptTokens;
totalUsage.completionTokens += response.usage.completionTokens;
totalUsage.totalTokens += response.usage.totalTokens;
if (response.finishReason == 'stop') {
success = lastDeploySuccess;
break;
}
if (response.finishReason === 'length') {
continue;
}
if (response.finishReason != 'tool-calls') {
throw new Error(`Unknown finish reason: ${response.finishReason}`);
}
if (response.toolCalls.length < 1) {
throw new Error('Expected at least one tool call');
}
for (const toolCall of response.toolCalls) {
if (!toolCall) {
throw new Error('Expected tool call to be non-null');
}
let toolCallResult: string;
try {
switch (toolCall.toolName) {
case 'edit': {
const args = editToolParameters.parse(toolCall.args);
const filePath = path.join(repoDir, cleanFilePath(args.path));
let content: string;
try {
content = readFileSync(filePath, 'utf8');
} catch (e: any) {
throw new Error(`Could not read ${args.path}: ${e.message}`);
}
if (args.old.length > 1024) {
throw new Error(`Old text must be less than 1024 characters: ${args.old}`);
}
if (args.new.length > 1024) {
throw new Error(`New text must be less than 1024 characters: ${args.new}`);
}
const matchPos = content.indexOf(args.old);
if (matchPos === -1) {
throw new Error(`Old text not found: ${args.old}`);
}
const secondMatchPos = content.indexOf(args.old, matchPos + args.old.length);
if (secondMatchPos !== -1) {
throw new Error(`Old text found multiple times: ${args.old}`);
}
content = content.replace(args.old, args.new);
writeFileSync(filePath, content);
toolCallResult = `Successfully edited ${args.path}`;
break;
}
case 'view': {
const args = viewParameters.parse(toolCall.args);
const filePath = path.join(repoDir, cleanFilePath(args.path));
try {
const stats = statSync(filePath);
if (stats.isDirectory()) {
const files = walkdir.sync(filePath);
toolCallResult = renderDirectory(
files.map((file: string) => ({
name: file,
isFile: () => !stats.isDirectory(),
isDirectory: () => stats.isDirectory(),
})),
);
} else {
const fileContent = readFileSync(filePath, 'utf8');
if (args.view_range && args.view_range.length !== 2) {
throw new Error('When provided, view_range must be an array of two numbers');
}
toolCallResult = renderFile(fileContent, args.view_range as [number, number]);
}
} catch (e: any) {
throw new Error(`Could not read ${args.path}: ${e.message}`);
}
break;
}
case 'lookupDocs': {
const args = lookupDocsParameters.parse(toolCall.args);
const docsToLookup = args.docs;
const results: string[] = [];
for (const doc of docsToLookup) {
if (doc in docs) {
results.push(docs[doc as DocKey]);
} else {
throw new Error(`Could not find documentation for component: ${doc}. It may not yet be supported.`);
}
}
toolCallResult = results.join('\n\n');
break;
}
case 'deploy': {
numDeploys++;
try {
toolCallResult = await deploy(repoDir, backend);
} catch (e: any) {
toolCallResult = `\n\nError: [CodinitTypecheck] ${e.message}`;
lastDeploySuccess = false;
break;
}
try {
toolCallResult += await runTypecheck(repoDir);
} catch (e: any) {
toolCallResult += `\n\nError: [FrontendTypecheck] ${e.message}`;
lastDeploySuccess = false;
break;
}
lastDeploySuccess = true;
if (numDeploys == 1 && lastDeploySuccess) {
toolCallResult += '\n\nDev server started successfully!';
}
logger.info('Successfully deployed');
break;
}
case 'npmInstall': {
const args = npmInstallToolParameters.parse(toolCall.args);
const packages = args.packages.split(' ');
toolCallResult = await npmInstall(repoDir, packages);
break;
}
case 'getCodinitDeploymentName': {
toolCallResult = backend.project.deploymentName;
break;
}
default:
throw new Error(`Unknown tool call: ${JSON.stringify(toolCall)}`);
}
} catch (e: any) {
logger.info('Tool call failed', e);
let message = e.toString();
if (!message.startsWith('Error:')) {
message = 'Error: ' + message;
}
toolCallResult = message;
}
assistantMessage.parts.push({
type: 'tool-invocation',
toolInvocation: {
toolCallId: toolCall.toolCallId,
toolName: toolCall.toolName,
state: 'result',
args: toolCall.args,
result: toolCallResult,
},
});
}
}
return {
success,
numDeploys,
usage: totalUsage,
};
});
const files: Record<string, string> = {};
const repoPaths = walkdir.sync(repoDir, {
filter: (directory: string, files: string[]) => {
return files.filter((file: string) => !IGNORED_FILENAMES.includes(file));
},
});
for (const repoPath of repoPaths) {
const relativePath = path.relative(repoDir, repoPath);
if (relativePath.startsWith('codinit/_generated/')) {
continue;
}
const ext = path.extname(relativePath);
if (!OUTPUT_EXTENSIONS.includes(ext)) {
continue;
}
if (!statSync(repoPath).isFile()) {
continue;
}
if (IGNORED_FILENAMES.includes(relativePath)) {
continue;
}
files[relativePath] = readFileSync(repoPath, 'utf8');
}
return {
success,
numDeploys,
usage,
files,
};
}
const setupRepoDir = wrapTraced(async function setupRepoDir(taskDir: string) {
const repoDir = path.join(taskDir, 'repo');
mkdirSync(repoDir, { recursive: true });
await copyFiles(repoDir);
await installDependencies(repoDir);
return repoDir;
});
const copyFiles = wrapTraced(async function copyFiles(repoDir: string) {
logger.info('Setting up template in', repoDir);
mkdirSync(repoDir, { recursive: true });
const stdout = execFileSync('/usr/bin/git', ['ls-files'], {
cwd: TEMPLATE_DIR,
encoding: 'utf8',
});
if (!stdout) {
throw new Error('No output from git ls-files');
}
const templateFiles = stdout
.trim()
.split('\n')
.filter((file) => file.length > 0);
for (const file of templateFiles) {
const sourcePath = path.join(TEMPLATE_DIR, file);
const targetPath = path.join(repoDir, file);
// Create parent directories if they don't exist
mkdirSync(path.dirname(targetPath), { recursive: true });
// Copy the file
copyFileSync(sourcePath, targetPath);
}
});
const installDependencies = wrapTraced(async function installDependencies(repoDir: string) {
execFileSync('npm', ['install'], { cwd: repoDir });
});
async function invokeGenerateText(model: CodinitModel, opts: SystemPromptOptions, context: UIMessage[]) {
return traced(
async (span: any) => {
const messages: CoreMessage[] = [
{
role: 'system',
content: ROLE_SYSTEM_PROMPT,
},
{
role: 'system',
content: generalSystemPrompt(opts),
},
...cleanupAssistantMessages(context),
];
try {
const tools: CodinitToolSet = {
deploy: deployTool,
npmInstall: npmInstallTool,
lookupDocs: lookupDocsTool(),
getCodinitDeploymentName: getCodinitDeploymentNameTool,
};
tools.view = viewTool;
tools.edit = editTool;
const result = await generateText({
model: model.ai,
maxTokens: model.maxTokens,
messages,
tools,
maxSteps: 64,
});
span.log({
input: messages,
output: {
text: result.text,
toolCalls: result.toolCalls,
},
metrics: {
prompt_tokens: result.usage.promptTokens,
completion_tokens: result.usage.completionTokens,
total_tokens: result.usage.totalTokens,
},
metadata: {
model: model.model_slug,
},
});
return result;
} catch (e: any) {
span.log({
input: messages,
});
throw e;
}
},
{
type: 'llm',
name: model.name,
},
);
}
function cleanFilePath(filePath: string) {
return filePath.replace('/home/project/', '/');
}