Files
ai-agents/src/review.mjs

110 lines
4.0 KiB
JavaScript

#!/usr/bin/env node
import {Ai} from '@ztimson/ai-utils';
import {$} from '@ztimson/node-utils';
import * as os from 'node:os';
import * as path from 'node:path';
import * as fs from 'node:fs';
import * as dotenv from 'dotenv';
dotenv.config({quiet: true, debug: false});
dotenv.config({path: '.env.local', override: true, quiet: true, debug: false});
(async () => {
let p = process.argv[process.argv.length - 1];
if(p === 'review' || p.endsWith('review.mjs')) p = null;
const root = p || process.cwd(),
git = process.env['GIT_HOST'],
owner = process.env['GIT_OWNER'],
repo = process.env['GIT_REPO'],
auth = process.env['GIT_TOKEN'],
pr = process.env['PULL_REQUEST'],
host = process.env['AI_HOST'],
model = process.env['AI_MODEL'],
token = process.env['AI_TOKEN'];
console.log(`Reviewing: ${root}\n`);
const branch = process.env['GIT_BRANCH'] || await $`cd ${root} && git symbolic-ref refs/remotes/origin/HEAD`;
const comments = [];
const commit = await $`cd ${root} && git log -1 --pretty=format:%H`;
const gitDiff = await $`cd ${root} && git diff ${branch}`;
if(!gitDiff) {
console.warn('No diff found');
return process.exit();
}
let existingComments = 'Existing Comments:\n';
if(git && pr) {
const reviews = await fetch(`${git}/api/v1/repos/${owner}/${repo}/pulls/${pr}/reviews`, {
headers: {'Authorization': `token ${auth}`}
}).then(resp => resp.ok ? resp.json() : []);
const comments = await Promise.all(reviews.map(r => fetch(`${git}/api/v1/repos/${owner}/${repo}/pulls/${pr}/reviews/${r.id}/comments`, {
headers: {'Authorization': `token ${auth}`}
}).then(resp => resp.ok ? resp.json() : [])));
existingComments += comments.flatten().map(c => `${c.path}:${c.position}\n${c.body}`).join('\n\n');
}
let options = {ollama: {model, host}};
if(host === 'anthropic') options = {anthropic: {model, token}};
else if(host === 'openai') options = {openAi: {model, token}};
const ai = new Ai({
...options,
model: [host, model],
path: process.env['path'] || os.tmpdir(),
system: `You are a code reviewer. Analyze the git diff and use the \`recommend\` tool for EACH issue you find. You must call \`recommend\` exactly once for every bug or improvement opportunity directly related to changes. Ignore formatting recommendations. After making all recommendations, provide some concluding remarks about the overall state of the changes.${existingComments}`,
tools: [{
name: 'read_file',
description: 'Read contents of a file',
args: {
path: {type: 'string', description: 'Path to file relative to project root'}
},
fn: (args) => fs.readFileSync(path.join(root, args.path), 'utf-8')
}, {
name: 'get_diff',
description: 'Check a file for differences using git',
args: {
path: {type: 'string', description: 'Path to file relative to project root'}
},
fn: async (args) => await $`git diff HEAD^..HEAD -- ${path.join(root, args.path)}`
}, {
name: 'recommend',
description: 'REQUIRED: Call this once for every bug, improvement, or concern identified in the review.',
args: {
file: {type: 'string', description: 'File path'},
line: {type: 'number', description: 'Line number in new file'},
comment: {type: 'string', description: 'Review comment explaining the issue'}
},
fn: (args) => {
comments.push({
path: args.file,
new_position: args.line,
body: args.comment,
});
return 'Comment recorded, continue reviewing';
}
}]
});
const messages = await ai.language.ask(gitDiff);
const summary = messages.pop().content;
if(git) {
const res = await fetch(`${git}/api/v1/repos/${owner}/${repo}/pulls/${pr}/reviews`, {
method: 'POST',
headers: {
'Authorization': `token ${auth}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
body: summary,
commit_id: commit,
event: 'COMMENT',
comments,
})
});
if(!res.ok) throw new Error(`${res.status} ${await res.text()}`);
}
console.log(comments.map(c => `${c.path}${c.new_position ? `:${c.new_position}` : ''}\n${c.body}`).join('\n\n') + '\n\n' + summary);
})();