1
0

main.js 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874
  1. // METADATA // {"ai-params":{"service":"claude"},"comment-verbosity": "high","ai-commented":{"service":"claude"}}
  2. const enq = require('enquirer');
  3. const wrap = require('word-wrap');
  4. const dedent = require('dedent');
  5. const axios = require('axios');
  6. const { walk, EXCLUDE_LISTS } = require('../file-walker/test');
  7. const https = require('https');
  8. const fs = require('fs');
  9. const path_ = require('path');
  10. const FILE_EXCLUDES = [
  11. /^\.git/,
  12. /^node_modules\//,
  13. /\/node_modules$/,
  14. /^node_modules$/,
  15. /package-lock\.json/,
  16. /^src\/dev-center\/js/,
  17. /src\/backend\/src\/public\/assets/,
  18. /^src\/gui\/src\/lib/,
  19. /^eslint\.config\.js$/,
  20. ];
  21. const models_to_try = [
  22. {
  23. service: 'openai-completion',
  24. model: 'gpt-4o-mini',
  25. },
  26. {
  27. service: 'openai-completion',
  28. model: 'gpt-4o',
  29. },
  30. {
  31. service: 'claude',
  32. },
  33. {
  34. service: 'xai',
  35. },
  36. // llama broke code - that's a "one strike you're out" situation
  37. // {
  38. // service: 'together-ai',
  39. // model: 'meta-llama/Meta-Llama-3-70B-Instruct-Turbo',
  40. // },
  41. {
  42. service: 'mistral',
  43. model: 'mistral-large-latest',
  44. }
  45. ];
  46. const axi = axios.create({
  47. httpsAgent: new https.Agent({
  48. rejectUnauthorized: false
  49. })
  50. });
  51. const cwd = process.cwd();
  52. const context = {};
  53. context.config = JSON.parse(
  54. fs.readFileSync('config.json')
  55. );
  56. /**
  57. * @class AI
  58. * @description A class that handles interactions with the Puter API for AI-powered chat completions.
  59. * This class provides an interface to make requests to the Puter chat completion service,
  60. * handling authentication and message formatting. It supports various AI models through
  61. * the puter-chat-completion driver interface.
  62. */
  63. class AI {
  64. constructor (context) {
  65. //
  66. }
  67. /**
  68. * Sends a chat completion request to the Puter API and returns the response message.
  69. *
  70. * @param {Object} params - The parameters for the completion request
  71. * @param {Array} params.messages - Array of message objects to send to the API
  72. * @param {Object} params.driver_params - Additional parameters for the driver interface
  73. * @returns {Promise<Object>} The response message from the API
  74. *
  75. * Makes a POST request to the configured API endpoint with the provided messages and
  76. * driver parameters. Authenticates using the configured auth token and returns the
  77. * message content from the response.
  78. */
  79. async complete ({ messages, driver_params }) {
  80. const response = await axi.post(`${context.config.api_url}/drivers/call`, {
  81. interface: 'puter-chat-completion',
  82. method: 'complete',
  83. ...driver_params,
  84. args: {
  85. messages,
  86. },
  87. }, {
  88. headers: {
  89. "Content-Type": "application/json",
  90. Origin: 'https://puter.local',
  91. Authorization: `Bearer ${context.config.auth_token}`,
  92. },
  93. });
  94. return response.data.result.message;
  95. }
  96. }
  97. const ai_message_to_lines = text => {
  98. // Extract text content from message object, handling various formats
  99. while ( typeof text === 'object' ) {
  100. if ( Array.isArray(text) ) text = text[0];
  101. else if ( text.content ) text = text.content;
  102. else if ( text.text ) text = text.text;
  103. else {
  104. console.log('Invalid message object', text);
  105. throw new Error('Invalid message object');
  106. }
  107. }
  108. return text.split('\n');
  109. }
  110. /**
  111. * @class JavascriptFileProcessor
  112. * @description A class responsible for processing JavaScript source files to identify and extract
  113. * various code definitions and structures. It analyzes the file content line by line using
  114. * configurable pattern matchers to detect classes, methods, functions, control structures,
  115. * and constants. The processor maintains context and parameters for consistent processing
  116. * across multiple files.
  117. */
  118. class JavascriptFileProcessor {
  119. constructor (context, parameters) {
  120. this.context = context;
  121. this.parameters = parameters;
  122. }
  123. process (lines) {
  124. const definitions = [];
  125. // Collect definitions by iterating through each line
  126. for ( let i = 0 ; i < lines.length ; i++ ) {
  127. const line = lines[i];
  128. // Iterate through each line in the file
  129. for ( const matcher of this.parameters.definition_matchers ) {
  130. const match = matcher.pattern.exec(line);
  131. console.log('match object', match);
  132. // Check if there is a match for any of the definition patterns
  133. if ( match ) {
  134. definitions.push({
  135. ...matcher.handler(match),
  136. line: i,
  137. });
  138. break;
  139. }
  140. }
  141. }
  142. return { definitions };
  143. }
  144. }
  145. const js_processor = new JavascriptFileProcessor(context, {
  146. definition_matchers: [
  147. // {
  148. // name: 'require',
  149. // pattern: /const (\w+) = require\(['"](.+)['"]\);/,
  150. // handler: (match) => {
  151. // const [ , name, path ] = match;
  152. // return {
  153. // type: 'require',
  154. // name,
  155. // path,
  156. // };
  157. // }
  158. // },
  159. {
  160. name: 'class',
  161. pattern: /class (\w+)(?: extends (.+))? {/,
  162. handler: (match) => {
  163. const [ , name, parent ] = match;
  164. return {
  165. type: 'class',
  166. name,
  167. parent,
  168. };
  169. }
  170. },
  171. {
  172. name: 'if',
  173. pattern: /^\s*if\s*\(.*\)\s*{/,
  174. /**
  175. * Matches code patterns against a line to identify if it's an if statement
  176. * @param {string} line - The line of code to check
  177. * @returns {Object} Returns an object with type: 'if' if pattern matches
  178. * @description Identifies if statements by matching the pattern /^\s*if\s*\(.*\)\s*{/
  179. * This handles basic if statement syntax with optional whitespace and any condition
  180. * within the parentheses
  181. */
  182. handler: () => {
  183. return { type: 'if' };
  184. }
  185. },
  186. {
  187. name: 'while',
  188. pattern: /^\s*while\s*\(.*\)\s*{/,
  189. /**
  190. * Matches lines that begin with a while loop structure.
  191. * @param {void} - Takes no parameters
  192. * @returns {Object} Returns an object with type: 'while' to indicate this is a while loop definition
  193. * @description Used by the definition matcher system to identify while loop structures in code.
  194. * The pattern looks for lines that start with optional whitespace, followed by 'while',
  195. * followed by parentheses containing any characters, and ending with an opening curly brace.
  196. */
  197. handler: () => {
  198. return { type: 'while' };
  199. }
  200. },
  201. {
  202. name: 'for',
  203. pattern: /^\s*for\s*\(.*\)\s*{/,
  204. /**
  205. * Matches for loop patterns in code and returns a 'for' type definition.
  206. * Used by the JavascriptFileProcessor to identify for loop structures.
  207. * @returns {Object} An object with type 'for' indicating a for loop was found
  208. */
  209. handler: () => {
  210. return { type: 'for' };
  211. }
  212. },
  213. {
  214. name: 'method',
  215. pattern: /^\s*async .*\(.*\).*{/,
  216. handler: (match) => {
  217. const [ , name ] = match;
  218. return {
  219. async: true,
  220. type: 'method',
  221. name,
  222. };
  223. }
  224. },
  225. {
  226. name: 'method',
  227. pattern: /^\s*[A-Za-z_\$]+.*\(\).*{/,
  228. handler: (match) => {
  229. const [ , name ] = match;
  230. // Extract method name from match array and handle special cases for 'if' and 'while'
  231. if ( name === 'if' ) {
  232. return { type: 'if' };
  233. }
  234. // Check if the name is 'while' and return appropriate type
  235. if ( name === 'while' ) {
  236. return { type: 'while' };
  237. }
  238. return {
  239. type: 'method',
  240. name,
  241. };
  242. }
  243. },
  244. {
  245. name: 'function',
  246. pattern: /^\s*function .*\(.*\).*{/,
  247. handler: (match) => {
  248. const [ , name ] = match;
  249. return {
  250. type: 'function',
  251. scope: 'function',
  252. name,
  253. };
  254. }
  255. },
  256. {
  257. name: 'function',
  258. pattern: /const [A-Za-z_]+\s*=\s*\(.*\)\s*=>\s*{/,
  259. handler: (match) => {
  260. const [ , name, args ] = match;
  261. return {
  262. type: 'function',
  263. scope: 'lexical',
  264. name,
  265. args: (args ?? '').split(',').map(arg => arg.trim()),
  266. };
  267. }
  268. },
  269. {
  270. name: 'const',
  271. // pattern to match only uppercase-lettered variable names
  272. pattern: /const ([A-Z_]+) = (.+);/,
  273. handler: (match) => {
  274. const [ , name, value ] = match;
  275. return {
  276. type: 'const',
  277. name,
  278. value,
  279. };
  280. }
  281. }
  282. ],
  283. });
  284. /**
  285. * Creates a limited view of the code file by showing specific ranges around key lines.
  286. * Takes an array of lines and key places (anchors with context ranges) and returns
  287. * a formatted string showing relevant code sections with line numbers and descriptions.
  288. * Merges overlapping ranges to avoid duplication.
  289. * @param {string[]} lines - Array of code lines from the file
  290. * @param {Object[]} key_places - Array of objects defining important locations and context
  291. * @returns {string} Formatted string containing the limited code view
  292. */
  293. const create_limited_view = (lines, key_places) => {
  294. // Sort key places by starting line
  295. key_places.sort((a, b) => {
  296. const a_start = Math.max(0, a.anchor - a.lines_above);
  297. const b_start = Math.max(0, b.anchor - b.lines_above);
  298. return a_start - b_start;
  299. });
  300. const visible_ranges = [];
  301. // Create visible ranges for each key place
  302. // Create visible ranges for each key place in the limited view
  303. for ( const key_place of key_places ) {
  304. const anchor = key_place.anchor;
  305. const lines_above = key_place.lines_above;
  306. const lines_below = key_place.lines_below;
  307. const start = Math.max(0, anchor - lines_above);
  308. const end = Math.min(lines.length, anchor + lines_below);
  309. visible_ranges.push({
  310. anchor: key_place.anchor,
  311. comment: key_place.comment,
  312. start,
  313. end,
  314. });
  315. }
  316. // Merge overlapping visible ranges
  317. const merged_ranges = [];
  318. // Iterate through each visible range and merge overlapping ones
  319. for ( const range of visible_ranges ) {
  320. range.comments = [{
  321. anchor: range.anchor,
  322. text: range.comment
  323. }];
  324. // If no merged ranges exist yet, add this range as the first one
  325. if ( ! merged_ranges.length ) {
  326. merged_ranges.push(range);
  327. continue;
  328. }
  329. const last_range = merged_ranges[merged_ranges.length - 1];
  330. // Check if the current range overlaps with the last range in merged_ranges
  331. if ( last_range.end >= range.start ) {
  332. last_range.end = Math.max(last_range.end, range.end);
  333. last_range.comments.push({
  334. anchor: range.anchor,
  335. text: range.comment
  336. });
  337. } else {
  338. merged_ranges.push(range);
  339. }
  340. }
  341. // Create the limited view, adding line numbers and comments
  342. let limited_view = '';
  343. let previous_visible_range = null;
  344. // Iterate through visible ranges and add line numbers and comments
  345. for ( let i = 0 ; i < lines.length ; i++ ) {
  346. const line = lines[i];
  347. let visible_range = null;
  348. if ( i === 22 ) debugger;
  349. // Iterate through merged ranges to find which range contains the current line
  350. for ( const range of merged_ranges ) {
  351. // Check if current line is within any of the merged ranges
  352. if ( i >= range.start && i < range.end ) {
  353. visible_range = range;
  354. break;
  355. }
  356. }
  357. // console.log('visible_range', visible_range, i);
  358. // Check if this line is visible in the current range
  359. if ( visible_range === null ) {
  360. continue;
  361. }
  362. // Check if visible range is different from previous range
  363. if ( visible_range !== previous_visible_range ) {
  364. if ( i !== 0 ) limited_view += '\n';
  365. // Check if we're starting a new visible range and add appropriate header
  366. if ( visible_range.comments.length === 1 ) {
  367. const comment = visible_range.comments[0];
  368. limited_view += `window around line ${comment.anchor}: ${comment.text}\n`;
  369. } else {
  370. limited_view += `window around lines ${visible_range.comments.length} key lines:\n`;
  371. // Iterate through visible range comments and add them to the limited view
  372. for ( const comment of visible_range.comments ) {
  373. limited_view += `- line ${comment.anchor}: ${comment.text}\n`;
  374. }
  375. }
  376. }
  377. previous_visible_range = visible_range;
  378. limited_view += `${i + 1}: ${line}\n`;
  379. }
  380. return limited_view;
  381. };
  382. /**
  383. * Inject comments into lines
  384. * @param {*} lines - Array of original file lines
  385. * @param {*} comments - Array of comment objects
  386. *
  387. * Comment object structure:
  388. * {
  389. * position: 0, // Position in lines array
  390. * lines: [ 'comment line 1', 'comment line 2', ... ]
  391. * }
  392. */
  393. /**
  394. * Injects comments into an array of code lines at specified positions
  395. * @param {string[]} lines - Array of original file lines
  396. * @param {Object[]} comments - Array of comment objects specifying where and what to inject
  397. * @param {number} comments[].position - Line number where comment should be inserted
  398. * @param {string[]} comments[].lines - Array of comment text lines to insert
  399. */
  400. const inject_comments = (lines, comments) => {
  401. // Sort comments in reverse order
  402. comments.sort((a, b) => b.position - a.position);
  403. // Inject comments into lines
  404. // Inject comments into lines array based on comment objects
  405. for ( const comment of comments ) {
  406. // AI might have been stupid and added a comment above a blank line,
  407. // despite that we told it not to do that. So we need to adjust the position.
  408. // Adjust comment position if it would be above a blank line
  409. while ( comment.position < lines.length && ! lines[comment.position].trim() ) {
  410. comment.position++;
  411. }
  412. const indentation = lines[comment.position].match(/^\s*/)[0];
  413. console.log('????', comment.position, lines[comment.position], '|' + indentation + '|');
  414. const comment_lines = comment.lines.map(line => `${indentation}${line}`);
  415. lines.splice(comment.position, 0, ...comment_lines);
  416. // If the first line of the comment lines starts with '/*`, ensure there is
  417. // a blank line above it.
  418. // Check if comment starts with '/*' to ensure proper spacing above JSDoc comments
  419. if ( comment_lines[0].trim().startsWith('/*') ) {
  420. // Check if comment starts with JSDoc style to add blank line above
  421. if ( comment.position > 0 && lines[comment.position - 1].trim() === '' ) {
  422. lines.splice(comment.position, 0, '');
  423. }
  424. }
  425. }
  426. }
  427. const textutil = {};
  428. textutil.format = text => {
  429. return wrap(dedent(text), {
  430. width: 80,
  431. indent: '| '
  432. });
  433. };
  434. context.ai = new AI(context);
  435. /**
  436. * Creates a new AI instance for handling chat completions
  437. * @param {Object} context - The application context object
  438. * @description Initializes an AI instance that interfaces with the Puter chat completion API.
  439. * The AI instance is used to generate comments and other text responses through the
  440. * chat completion interface.
  441. */
  442. const main = async () => {
  443. // const message = await context.ai.complete({
  444. // messages: [
  445. // {
  446. // role: 'user',
  447. // content: `
  448. // Introduce yourself as the Puter Comment Writer. You are an AI that will
  449. // write comments in code files. A file walker will be used to iterate over
  450. // the source files and present them one at a time, and the user will accept,
  451. // reject, or request edits interactively. For each new file, a clean AI
  452. // context will be created.
  453. // `.trim()
  454. // }
  455. // ]
  456. // });
  457. // const intro = message.content;
  458. const intro = textutil.format(`
  459. Hello! I am the Puter Comment Writer, an AI designed to enhance your code files with meaningful comments. As you walk through your source files, I will provide insights, explanations, and clarifications tailored to the specific content of each file. You can choose to accept my comments, request edits for more clarity or detail, or even reject them if they don't meet your needs. Each time we move to a new file, I'll start fresh with a clean context, ready to help you improve your code documentation. Let's get started!
  460. `);
  461. console.log(intro);
  462. console.log(`Enter a path relative to: ${process.cwd()}`);
  463. console.log('arg?', process.argv[2]);
  464. let rootpath = process.argv[2] ? { path: process.argv[2] } : await enq.prompt({
  465. type: 'input',
  466. name: 'path',
  467. message: 'Enter path:'
  468. });
  469. rootpath = path_.resolve(rootpath.path);
  470. console.log('rootpath:', rootpath);
  471. const walk_iter = walk({
  472. excludes: FILE_EXCLUDES,
  473. }, rootpath);
  474. let i = 0, limit = undefined;
  475. for await ( const value of walk_iter ) {
  476. if ( limit !== undefined && i >= limit ) break;
  477. i++;
  478. // Exit after processing 12 files
  479. if ( value.is_dir ) {
  480. console.log('directory:', value.path);
  481. continue;
  482. }
  483. // Check if file is not a JavaScript file and skip it
  484. if ( ! value.name.endsWith('.js') ) {
  485. continue;
  486. }
  487. console.log('file:', value.path);
  488. const lines = fs.readFileSync(value.path, 'utf8').split('\n');
  489. let metadata, has_metadata_line = false;
  490. // Check if metadata line exists and parse it
  491. if ( lines[0].startsWith('// METADATA // ') ) {
  492. has_metadata_line = true;
  493. metadata = JSON.parse(lines[0].slice('// METADATA // '.length));
  494. // Check if metadata exists and has been parsed from the first line
  495. if ( metadata['ai-commented'] ) {
  496. console.log('File was already commented by AI; skipping...');
  497. continue;
  498. }
  499. } else metadata = {};
  500. let refs = null;
  501. // Check if there are any references in the metadata
  502. if ( metadata['ai-refs'] ) {
  503. const relative_file_paths = metadata['ai-refs'];
  504. // name of file is the key, value is the contents
  505. const references = {};
  506. let n = 0;
  507. // Iterate through each relative file path in the metadata
  508. for ( const relative_file_path of relative_file_paths ) {
  509. n++;
  510. const full_path = path_.join(path_.dirname(value.path), relative_file_path);
  511. const ref_text = fs.readFileSync(full_path, 'utf8');
  512. references[relative_file_path] = ref_text;
  513. }
  514. // Check if there are any references in the metadata and process them
  515. if ( n === 1 ) {
  516. refs = dedent(`
  517. The following documentation contains relevant information about the code.
  518. The code will follow after this documentation.
  519. `);
  520. refs += '\n\n' + dedent(references[Object.keys(references)[0]]);
  521. } else if ( n > 2 ) {
  522. refs = dedent(`
  523. The following documentation contains relevant information about the code.
  524. The code will follow after a number of documentation files.
  525. `);
  526. // Iterate through each key in the references object
  527. for ( const key of Object.keys(references) ) {
  528. refs += '\n\n' + dedent(references[key]);
  529. }
  530. }
  531. }
  532. const action = limit === undefined ? await enq.prompt({
  533. type: 'select',
  534. name: 'action',
  535. message: 'Select action:',
  536. choices: [
  537. 'generate',
  538. 'skip',
  539. 'all',
  540. 'limit',
  541. 'exit',
  542. ]
  543. }) : 'generate';
  544. // const action = 'generate';
  545. // Check if user wants to exit the program
  546. if ( action.action === 'exit' ) {
  547. break;
  548. }
  549. // Skip if user chose to exit
  550. if ( action.action === 'skip' ) {
  551. continue;
  552. }
  553. if ( action.action === 'limit' ) {
  554. limit = await enq.prompt({
  555. type: 'input',
  556. name: 'limit',
  557. message: 'Enter limit:'
  558. });
  559. i = 1;
  560. limit = Number(limit.limit);
  561. }
  562. if ( action.action === 'all' ) {
  563. limit = await enq.prompt({
  564. type: 'input',
  565. name: 'limit',
  566. message: 'Enter limit:'
  567. });
  568. i = 1;
  569. limit = Number(limit.limit);
  570. }
  571. const { definitions } = js_processor.process(lines);
  572. const key_places = [];
  573. key_places.push({
  574. anchor: 0,
  575. lines_above: 2,
  576. lines_below: 200,
  577. comment: `Top of file: ${value.path}`
  578. });
  579. key_places.push({
  580. anchor: lines.length - 1,
  581. lines_above: 200,
  582. lines_below: 2,
  583. comment: `Bottom of ${value.name}`
  584. });
  585. // Iterate through each definition and add comments based on its type
  586. for ( const definition of definitions ) {
  587. key_places.push({
  588. anchor: definition.line,
  589. lines_above: 40,
  590. lines_below: 40,
  591. comment: `${definition.type}.`
  592. });
  593. }
  594. let limited_view = create_limited_view(lines, key_places);
  595. console.log('--- view ---');
  596. console.log(limited_view);
  597. const comments = [];
  598. // comments.push({
  599. // position: 0,
  600. // });
  601. // for ( const definition of definitions ) {
  602. // comments.push({
  603. // position: definition.line,
  604. // definition,
  605. // });
  606. // }
  607. // This was worth a try but the LLM is very bad at this
  608. /*
  609. const message = await context.ai.complete({
  610. messages: [
  611. {
  612. role: 'user',
  613. content: dedent(`
  614. Respond with comma-separated numbers only, with no surrounding text.
  615. Please write the numbers of the lines above which a comment should be added.
  616. Do not include numbers of lines that are blank, already have comments, or are part of a comment.
  617. Prefer comment locations in a higher level scope, such as a classes, function definitions and class methods,
  618. `).trim() + '\n\n' + limited_view
  619. }
  620. ]
  621. });
  622. const numbers = message.content.split(',').map(n => Number(n));
  623. // Iterate through each number in the array of line numbers
  624. for ( const n of numbers ) {
  625. // Check if the line number is valid and not NaN before adding comment
  626. if ( Number.isNaN(n) ) {
  627. console.log('Invalid number:', n);
  628. continue;
  629. }
  630. comments.push({
  631. position: n - 1,
  632. });
  633. }
  634. */
  635. // Iterate through each definition to add comments
  636. for ( const def of definitions ) {
  637. console.log('def?', def);
  638. let instruction = '';
  639. // Check if the line starts with an if statement and has curly braces
  640. if ( def.type === 'class' ) {
  641. instruction = dedent(`
  642. Since the comment is going above a class definition, please write a JSDoc style comment.
  643. Make the comment as descriptive as possible, including the class name and its purpose.
  644. `);
  645. }
  646. // Check if comment is for an if/while/for control structure
  647. if ( def.type === 'if' || def.type === 'while' || def.type === 'for' ) {
  648. if ( metadata['comment-verbosity'] !== 'high' ) continue;
  649. instruction = dedent(`
  650. Since the comment is going above a control structure, please write a short concise comment.
  651. The comment should be only one or two lines long, and should use line comments.
  652. `);
  653. }
  654. // Check if comment is going above a method definition
  655. if ( def.type === 'method' ) {
  656. instruction = dedent(`
  657. Since the comment is going above a method, please write a JSDoc style comment.
  658. The comment should include a short concise description of the method's purpose,
  659. notes about its behavior, and any parameters or return values.
  660. `);
  661. }
  662. // Check if comment is for a constant definition and set appropriate instruction
  663. if ( def.type === 'const' ) {
  664. instruction = dedent(`
  665. Since the comment is going above a constant definition, please write a comment that explains
  666. the purpose of the constant and how it is used in the code.
  667. The comment should be only one or two lines long, and should use line comments.
  668. `);
  669. }
  670. comments.push({
  671. position: def.line,
  672. instruction: instruction,
  673. });
  674. }
  675. const driver_params = metadata['ai-params'] ??
  676. models_to_try[Math.floor(Math.random() * models_to_try.length)];
  677. // Iterate through each comment object to add comments to the code
  678. for ( const comment of comments ) {
  679. // This doesn't work very well yet
  680. /*
  681. const ranges_message = await context.ai.complete({
  682. messages: [
  683. {
  684. role: 'user',
  685. content: dedent(`
  686. Please only respond with comma-separated number ranges in this format with no surrounding text:
  687. 11-21, 25-30, 35-40
  688. You may also respond with "none".
  689. A comment will be added above line ${comment.position} in the code which follows.
  690. You are seeing a limited view of the code that includes chunks around interesting lines.
  691. Please specify ranges of lines that might provide useful context for this comment.
  692. Do not include in any range lines which are already visible in the limited view.
  693. Avoid specifying more than a couple hundred lines.
  694. `).trim() + '\n\n' + limited_view
  695. }
  696. ]
  697. });
  698. // Check if the comment lines start with '/*' and ensure there's a blank line above it
  699. if ( ranges_message.content.trim() !== 'none' ) {
  700. const ranges = ranges_message.content.split(',').map(range => {
  701. const [ start, end ] = range.split('-').map(n => Number(n));
  702. return { start, end };
  703. });
  704. // Iterate through ranges and add key places for each range
  705. for ( const range of ranges ) {
  706. key_places.push({
  707. anchor: range.start,
  708. lines_above: 0,
  709. lines_below: range.end - range.start,
  710. comment: `Requested range by AI agent: ${range.start}-${range.end}`
  711. });
  712. }
  713. limited_view = create_limited_view(lines, key_places);
  714. console.log('--- updated view ---');
  715. console.log(limited_view);
  716. }
  717. */
  718. const prompt =
  719. dedent(`
  720. Please write a comment to be added above line ${comment.position}.
  721. Do not write any surrounding text; just the comment itself.
  722. Please include comment markers. If the comment is on a class, function, or method, please use jsdoc style.
  723. The code is written in JavaScript.
  724. `).trim() +
  725. (refs ? '\n\n' + dedent(refs) : '') +
  726. (comment.instruction ? '\n\n' + dedent(comment.instruction) : '') +
  727. '\n\n' + limited_view
  728. ;
  729. // console.log('prompt:', prompt);
  730. const message = await context.ai.complete({
  731. messages: [
  732. {
  733. role: 'user',
  734. content: prompt
  735. }
  736. ],
  737. driver_params,
  738. });
  739. console.log('message:', message);
  740. comment.lines = ai_message_to_lines(message.content);
  741. // Remove leading and trailing blank lines
  742. // Remove leading and trailing blank lines from comment lines array
  743. while ( comment.lines.length && ! comment.lines[0].trim() ) {
  744. comment.lines.shift();
  745. }
  746. // Remove trailing blank lines from comment lines array
  747. while ( comment.lines.length && ! comment.lines[comment.lines.length - 1].trim() ) {
  748. comment.lines.pop();
  749. }
  750. // Remove leading "```" or "```<language>" lines
  751. // Remove leading "```" or "```<language>" lines
  752. if ( comment.lines[0].startsWith('```') ) {
  753. comment.lines.shift();
  754. }
  755. // Remove trailing "```" lines
  756. // Remove trailing "```" lines if present
  757. if ( comment.lines[comment.lines.length - 1].startsWith('```') ) {
  758. comment.lines.pop();
  759. }
  760. comment.lines = dedent(comment.lines.join('\n')).split('\n');
  761. }
  762. inject_comments(lines, comments);
  763. console.log('--- lines ---');
  764. console.log(lines);
  765. // Check if file has metadata line and remove it before adding new metadata
  766. if ( has_metadata_line ) {
  767. lines.shift();
  768. }
  769. lines.unshift('// METADATA // ' + JSON.stringify({
  770. ...metadata,
  771. 'ai-commented': driver_params,
  772. }));
  773. // Write the modified file
  774. fs.writeFileSync(value.path, lines.join('\n'));
  775. }
  776. };
  777. main();