git-coco 0.19.0 → 0.20.0

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.
@@ -18,13 +18,13 @@ import prettyMilliseconds from 'pretty-ms';
18
18
  import { ChatAnthropic } from '@langchain/anthropic';
19
19
  import { ChatOllama } from '@langchain/ollama';
20
20
  import { ChatOpenAI } from '@langchain/openai';
21
- import { StructuredOutputParser, BaseOutputParser, OutputParserException, StringOutputParser } from '@langchain/core/output_parsers';
22
- import { simpleGit } from 'simple-git';
21
+ import { BaseOutputParser, OutputParserException, StructuredOutputParser, StringOutputParser } from '@langchain/core/output_parsers';
23
22
  import { BaseLangChain, BaseLanguageModel } from '@langchain/core/language_models/base';
24
23
  import { ensureConfig, Runnable } from '@langchain/core/runnables';
25
24
  import { RUN_KEY } from '@langchain/core/outputs';
26
25
  import { CallbackManager, parseCallbackConfigArg } from '@langchain/core/callbacks/manager';
27
26
  import '@langchain/core/utils/json_patch';
27
+ import { simpleGit } from 'simple-git';
28
28
  import pQueue from 'p-queue';
29
29
  import { Document, BaseDocumentTransformer } from '@langchain/core/documents';
30
30
  import { createTwoFilesPatch } from 'diff';
@@ -46,7 +46,7 @@ import * as readline from 'readline';
46
46
  /**
47
47
  * Current build version from package.json
48
48
  */
49
- const BUILD_VERSION = "0.19.0";
49
+ const BUILD_VERSION = "0.20.0";
50
50
 
51
51
  const isInteractive = (config) => {
52
52
  return config?.mode === 'interactive' || !!config?.interactive;
@@ -6201,1421 +6201,1424 @@ function getPrompt({ template, variables, fallback }) {
6201
6201
  throw new LangChainExecutionError('getPrompt: Unexpected execution path - neither template nor fallback available', { template, fallback, variables });
6202
6202
  }
6203
6203
 
6204
+ new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");
6205
+
6204
6206
  /**
6205
- * Executes a LangChain pipeline with the provided LLM, prompt, variables, and parser.
6206
- * @param params - The execution parameters
6207
- * @returns The parsed result from the LLM chain
6208
- * @throws LangChainExecutionError if the chain execution fails or returns empty results
6207
+ * Base interface that all chains must implement.
6209
6208
  */
6210
- const executeChain = async ({ llm, prompt, variables, parser }) => {
6211
- validateRequired(llm, 'llm', 'executeChain');
6212
- validateRequired(prompt, 'prompt', 'executeChain');
6213
- validateRequired(variables, 'variables', 'executeChain');
6214
- validateRequired(parser, 'parser', 'executeChain');
6215
- // Validate that variables is an object
6216
- if (typeof variables !== 'object' || Array.isArray(variables)) {
6217
- throw new LangChainExecutionError('executeChain: Variables must be a non-array object', { variables, type: typeof variables, isArray: Array.isArray(variables) });
6209
+ class BaseChain extends BaseLangChain {
6210
+ get lc_namespace() {
6211
+ return ["langchain", "chains", this._chainType()];
6218
6212
  }
6219
- try {
6220
- const chain = prompt.pipe(llm).pipe(parser);
6221
- const result = await chain.invoke(variables);
6222
- if (result === null || result === undefined) {
6223
- throw new LangChainExecutionError('executeChain: Chain execution returned null or undefined result', { variables, promptInputVariables: prompt.inputVariables });
6213
+ constructor(fields,
6214
+ /** @deprecated */
6215
+ verbose,
6216
+ /** @deprecated */
6217
+ callbacks) {
6218
+ if (arguments.length === 1 &&
6219
+ typeof fields === "object" &&
6220
+ !("saveContext" in fields)) {
6221
+ // fields is not a BaseMemory
6222
+ const { memory, callbackManager, ...rest } = fields;
6223
+ super({ ...rest, callbacks: callbackManager ?? rest.callbacks });
6224
+ this.memory = memory;
6225
+ }
6226
+ else {
6227
+ // fields is a BaseMemory
6228
+ super({ verbose, callbacks });
6229
+ this.memory = fields;
6224
6230
  }
6225
- return result;
6226
6231
  }
6227
- catch (error) {
6228
- // Re-throw LangChain errors as-is
6229
- if (error instanceof LangChainExecutionError) {
6230
- throw error;
6232
+ /** @ignore */
6233
+ _selectMemoryInputs(values) {
6234
+ const valuesForMemory = { ...values };
6235
+ if ("signal" in valuesForMemory) {
6236
+ delete valuesForMemory.signal;
6231
6237
  }
6232
- // Wrap other errors with context
6233
- handleLangChainError(error, 'executeChain: Chain execution failed', {
6234
- promptInputVariables: prompt.inputVariables,
6235
- variableKeys: Object.keys(variables),
6236
- parserType: parser.constructor.name
6238
+ if ("timeout" in valuesForMemory) {
6239
+ delete valuesForMemory.timeout;
6240
+ }
6241
+ return valuesForMemory;
6242
+ }
6243
+ /**
6244
+ * Invoke the chain with the provided input and returns the output.
6245
+ * @param input Input values for the chain run.
6246
+ * @param config Optional configuration for the Runnable.
6247
+ * @returns Promise that resolves with the output of the chain run.
6248
+ */
6249
+ async invoke(input, options) {
6250
+ const config = ensureConfig(options);
6251
+ const fullValues = await this._formatValues(input);
6252
+ const callbackManager_ = await CallbackManager.configure(config?.callbacks, this.callbacks, config?.tags, this.tags, config?.metadata, this.metadata, { verbose: this.verbose });
6253
+ const runManager = await callbackManager_?.handleChainStart(this.toJSON(), fullValues, undefined, undefined, undefined, undefined, config?.runName);
6254
+ let outputValues;
6255
+ try {
6256
+ outputValues = await (fullValues.signal
6257
+ ? Promise.race([
6258
+ this._call(fullValues, runManager, config),
6259
+ new Promise((_, reject) => {
6260
+ fullValues.signal?.addEventListener("abort", () => {
6261
+ reject(new Error("AbortError"));
6262
+ });
6263
+ }),
6264
+ ])
6265
+ : this._call(fullValues, runManager, config));
6266
+ }
6267
+ catch (e) {
6268
+ await runManager?.handleChainError(e);
6269
+ throw e;
6270
+ }
6271
+ if (!(this.memory == null)) {
6272
+ await this.memory.saveContext(this._selectMemoryInputs(input), outputValues);
6273
+ }
6274
+ await runManager?.handleChainEnd(outputValues);
6275
+ // add the runManager's currentRunId to the outputValues
6276
+ Object.defineProperty(outputValues, RUN_KEY, {
6277
+ value: runManager ? { runId: runManager?.runId } : undefined,
6278
+ configurable: true,
6237
6279
  });
6280
+ return outputValues;
6238
6281
  }
6239
- };
6240
-
6241
- function extractTicketIdFromBranchName(branchName) {
6242
- const regex = /((?<!([A-Z]+)-?)[A-Z]+-\d+)/;
6243
- const match = branchName.match(regex);
6244
- return match ? match[0] : null;
6245
- }
6246
-
6247
- /**
6248
- * Formats a commit log into a readable string format.
6249
- *
6250
- * @param commitLog - The commit log result containing an array of commit details.
6251
- * @returns An array of formatted commit log strings.
6252
- *
6253
- * Each formatted string includes:
6254
- * - The date of the commit in square brackets.
6255
- * - The commit message.
6256
- * - The commit body.
6257
- * - The commit hash in parentheses.
6258
- * - The author's name and email in angle brackets.
6259
- */
6260
- const formatCommitLog = (commitLog) => {
6261
- return commitLog.all.map(({ message, date, body, author_name, hash, author_email }) => `[${date}] ${message}\n${body}\n(${hash}) - ${author_name}<${author_email}>`);
6262
- };
6263
-
6264
- const getChangesSinceLastTag = async ({ git }) => {
6265
- const tags = await git.tags();
6266
- if (tags.all.length > 0) {
6267
- const lastTag = tags.latest;
6268
- const commitLog = await git.log({ from: lastTag });
6269
- return formatCommitLog(commitLog);
6282
+ _validateOutputs(outputs) {
6283
+ const missingKeys = this.outputKeys.filter((k) => !(k in outputs));
6284
+ if (missingKeys.length) {
6285
+ throw new Error(`Missing output keys: ${missingKeys.join(", ")} from chain ${this._chainType()}`);
6286
+ }
6270
6287
  }
6271
- else {
6272
- return ['No tags found in the repository.'];
6288
+ async prepOutputs(inputs, outputs, returnOnlyOutputs = false) {
6289
+ this._validateOutputs(outputs);
6290
+ if (this.memory) {
6291
+ await this.memory.saveContext(inputs, outputs);
6292
+ }
6293
+ if (returnOnlyOutputs) {
6294
+ return outputs;
6295
+ }
6296
+ return { ...inputs, ...outputs };
6273
6297
  }
6274
- };
6275
-
6276
- /**
6277
- * Retrieves the commit log range between two specified commits (inclusive of both commits).
6278
- *
6279
- * @param from - The starting commit (can be a commit hash, HEAD reference, or branch name). This commit will be included in the results.
6280
- * @param to - The ending commit (can be a commit hash, HEAD reference, or branch name). This commit will be included in the results.
6281
- * @param options - Additional options for retrieving the commit log range.
6282
- * @returns A promise that resolves to an array of commit log messages, including both the 'from' and 'to' commits.
6283
- * @throws If there is an error retrieving the commit log range.
6284
- */
6285
- async function getCommitLogRange(from, to, { noMerges, git }) {
6286
- try {
6287
- // Use from^..to to include the 'from' commit in the range
6288
- // This works because from^..to means "commits reachable from 'to' but not from the parent of 'from'"
6289
- const logOptions = {
6290
- from: `${from}^`,
6291
- to,
6292
- '--no-merges': noMerges
6293
- };
6294
- const commitLog = await git.log(logOptions);
6295
- return commitLog.all.map(({ message, date, body, author_name, hash, author_email }) => `[${date}] ${message}\n${body}\n(${hash}) - ${author_name}<${author_email}>`);
6298
+ /**
6299
+ * Return a json-like object representing this chain.
6300
+ */
6301
+ serialize() {
6302
+ throw new Error("Method not implemented.");
6296
6303
  }
6297
- catch (error) {
6298
- // If from^ fails (e.g., 'from' is the first commit), fall back to using from..to and manually adding the 'from' commit
6299
- if (error instanceof Error && error.message.includes('unknown revision')) {
6300
- try {
6301
- // Get the 'from' commit separately
6302
- const fromCommitLog = await git.log({ from: from, maxCount: 1 });
6303
- const fromCommit = fromCommitLog.latest;
6304
- // Get the range from..to (excluding 'from')
6305
- const rangeLogOptions = {
6306
- from,
6307
- to,
6308
- '--no-merges': noMerges
6309
- };
6310
- const rangeCommitLog = await git.log(rangeLogOptions);
6311
- // Combine the 'from' commit with the range commits
6312
- const allCommits = fromCommit
6313
- ? [fromCommit, ...rangeCommitLog.all]
6314
- : rangeCommitLog.all;
6315
- return allCommits.map(({ message, date, body, author_name, hash, author_email }) => `[${date}] ${message}\n${body}\n(${hash}) - ${author_name}<${author_email}>`);
6316
- }
6317
- catch (fallbackError) {
6318
- throw fallbackError;
6319
- }
6304
+ /** @deprecated Use .invoke() instead. Will be removed in 0.2.0. */
6305
+ async run(
6306
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
6307
+ input, config) {
6308
+ const inputKeys = this.inputKeys.filter((k) => !this.memory?.memoryKeys.includes(k) ?? true);
6309
+ const isKeylessInput = inputKeys.length <= 1;
6310
+ if (!isKeylessInput) {
6311
+ throw new Error(`Chain ${this._chainType()} expects multiple inputs, cannot use 'run' `);
6320
6312
  }
6321
- throw error;
6322
- }
6323
- }
6324
-
6325
- /**
6326
- * Retrieves the name of the current branch.
6327
- *
6328
- * @param {GetCurrentBranchName} options - The options for retrieving the branch name.
6329
- * @returns {Promise<string>} - A promise that resolves to the name of the current branch.
6330
- */
6331
- async function getCurrentBranchName({ git }) {
6332
- return await git.revparse(['--abbrev-ref', 'HEAD']);
6333
- }
6334
-
6335
- /**
6336
- * Retrieves the commit log between the current branch and a specified target branch.
6337
- *
6338
- * @param {Object} options - The options for retrieving the commit log.
6339
- * @param {SimpleGit} options.git - The SimpleGit instance.
6340
- * @param {Logger} options.logger - The logger for logging messages.
6341
- * @param {string} options.targetBranch - The target branch to compare against.
6342
- * @returns {Promise<string[]>} The array of commit messages in the commit log.
6343
- */
6344
- async function getCommitLogAgainstBranch({ git, logger, targetBranch, }) {
6345
- try {
6346
- // Get the current branch name
6347
- const currentBranch = await getCurrentBranchName({ git });
6348
- // Get the list of commits that are unique to the current branch compared to the target branch
6349
- const uniqueCommits = (await git.raw(['rev-list', `${targetBranch}..${currentBranch}`]))
6350
- .split('\n')
6351
- .filter(Boolean)
6352
- .reverse();
6353
- logger?.verbose(`Found ${uniqueCommits.length} unique commits between "${currentBranch}" and "${targetBranch}"`, { color: 'blue' });
6354
- const firstCommit = uniqueCommits[0];
6355
- const lastCommit = uniqueCommits[uniqueCommits.length - 1];
6356
- if (!firstCommit || !lastCommit) {
6357
- logger?.log('Unable to determine first and last commit between branches', { color: 'yellow' });
6358
- return [];
6313
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
6314
+ const values = inputKeys.length ? { [inputKeys[0]]: input } : {};
6315
+ const returnValues = await this.call(values, config);
6316
+ const keys = Object.keys(returnValues);
6317
+ if (keys.length === 1) {
6318
+ return returnValues[keys[0]];
6359
6319
  }
6360
- // Retrieve commit log with messages
6361
- return await getCommitLogRange(firstCommit, lastCommit, { git, noMerges: true });
6362
- }
6363
- catch (error) {
6364
- logger?.log('Encountered an error getting commit log between branches', { color: 'red' });
6320
+ throw new Error("return values have multiple keys, `run` only supported when one key currently");
6365
6321
  }
6366
- return [];
6367
- }
6368
-
6369
- /**
6370
- * Retrieves the commit log for the current branch.
6371
- *
6372
- * @param {Object} options - The options for retrieving the commit log.
6373
- * @param {SimpleGit} options.git - The SimpleGit instance.
6374
- * @param {Logger} options.logger - The logger for logging messages.
6375
- * @param {string} [options.comparisonBranch='main'] - The branch to compare against.
6376
- * @param {string} [options.comparisonRemote='origin'] - The remote to compare against.
6377
- * @returns {Promise<string[]>} The array of commit messages in the commit log.
6378
- */
6379
- async function getCommitLogCurrentBranch({ git, logger, comparisonBranch = 'main', comparisonRemote = 'origin', }) {
6380
- try {
6381
- const branchName = await getCurrentBranchName({ git });
6382
- const hasCommits = (await git.raw(['rev-list', '--count', branchName])) !== '0';
6383
- if (!hasCommits) {
6384
- logger?.log('No commits on the current branch.');
6385
- return [];
6386
- }
6387
- let uniqueCommits;
6388
- if (comparisonBranch === branchName) {
6389
- // If the comparison branch is the same as the current branch, we compare against the remote.
6390
- uniqueCommits = (await git.raw(['rev-list', `${comparisonRemote}/${comparisonBranch}..${branchName}`]))
6391
- .split('\n')
6392
- .filter(Boolean)
6393
- .reverse();
6394
- }
6395
- else {
6396
- // Your existing code for different branches
6397
- uniqueCommits = (await git.raw(['rev-list', `${comparisonBranch}..${branchName}`]))
6398
- .split('\n')
6399
- .filter(Boolean)
6400
- .reverse();
6322
+ async _formatValues(values) {
6323
+ const fullValues = { ...values };
6324
+ if (fullValues.timeout && !fullValues.signal) {
6325
+ fullValues.signal = AbortSignal.timeout(fullValues.timeout);
6326
+ delete fullValues.timeout;
6401
6327
  }
6402
- logger?.verbose(`Found ${uniqueCommits.length} unique commits on "${branchName}"`, {
6403
- color: 'blue',
6404
- });
6405
- const firstCommit = uniqueCommits[0];
6406
- const lastCommit = uniqueCommits[uniqueCommits.length - 1];
6407
- if (!firstCommit || !lastCommit) {
6408
- logger?.log('Unable to determine first and last commit on the current branch', {
6409
- color: 'yellow',
6410
- });
6411
- return [];
6328
+ if (!(this.memory == null)) {
6329
+ const newValues = await this.memory.loadMemoryVariables(this._selectMemoryInputs(values));
6330
+ for (const [key, value] of Object.entries(newValues)) {
6331
+ fullValues[key] = value;
6332
+ }
6412
6333
  }
6413
- return await getCommitLogRange(firstCommit, lastCommit, { git, noMerges: true });
6334
+ return fullValues;
6414
6335
  }
6415
- catch (error) {
6416
- logger?.log('Encountered an error getting commit log from current branch', { color: 'red' });
6336
+ /**
6337
+ * @deprecated Use .invoke() instead. Will be removed in 0.2.0.
6338
+ *
6339
+ * Run the core logic of this chain and add to output if desired.
6340
+ *
6341
+ * Wraps _call and handles memory.
6342
+ */
6343
+ async call(values, config,
6344
+ /** @deprecated */
6345
+ tags) {
6346
+ const parsedConfig = { tags, ...parseCallbackConfigArg(config) };
6347
+ return this.invoke(values, parsedConfig);
6348
+ }
6349
+ /**
6350
+ * @deprecated Use .batch() instead. Will be removed in 0.2.0.
6351
+ *
6352
+ * Call the chain on all inputs in the list
6353
+ */
6354
+ async apply(inputs, config) {
6355
+ return Promise.all(inputs.map(async (i, idx) => this.call(i, config?.[idx])));
6356
+ }
6357
+ /**
6358
+ * Load a chain from a json-like object describing it.
6359
+ */
6360
+ static async deserialize(data, values = {}) {
6361
+ switch (data._type) {
6362
+ case "llm_chain": {
6363
+ const { LLMChain } = await Promise.resolve().then(function () { return llm_chain; });
6364
+ return LLMChain.deserialize(data);
6365
+ }
6366
+ case "sequential_chain": {
6367
+ const { SequentialChain } = await Promise.resolve().then(function () { return sequential_chain; });
6368
+ return SequentialChain.deserialize(data);
6369
+ }
6370
+ case "simple_sequential_chain": {
6371
+ const { SimpleSequentialChain } = await Promise.resolve().then(function () { return sequential_chain; });
6372
+ return SimpleSequentialChain.deserialize(data);
6373
+ }
6374
+ case "stuff_documents_chain": {
6375
+ const { StuffDocumentsChain } = await Promise.resolve().then(function () { return combine_docs_chain; });
6376
+ return StuffDocumentsChain.deserialize(data);
6377
+ }
6378
+ case "map_reduce_documents_chain": {
6379
+ const { MapReduceDocumentsChain } = await Promise.resolve().then(function () { return combine_docs_chain; });
6380
+ return MapReduceDocumentsChain.deserialize(data);
6381
+ }
6382
+ case "refine_documents_chain": {
6383
+ const { RefineDocumentsChain } = await Promise.resolve().then(function () { return combine_docs_chain; });
6384
+ return RefineDocumentsChain.deserialize(data);
6385
+ }
6386
+ case "vector_db_qa": {
6387
+ const { VectorDBQAChain } = await Promise.resolve().then(function () { return vector_db_qa; });
6388
+ return VectorDBQAChain.deserialize(data, values);
6389
+ }
6390
+ case "api_chain": {
6391
+ const { APIChain } = await Promise.resolve().then(function () { return api_chain; });
6392
+ return APIChain.deserialize(data);
6393
+ }
6394
+ default:
6395
+ throw new Error(`Invalid prompt type in config: ${data._type}`);
6396
+ }
6417
6397
  }
6418
- return [];
6419
6398
  }
6420
6399
 
6421
6400
  /**
6422
- * Retrieves the SimpleGit instance for the repository.
6423
- * @returns {SimpleGit} The SimpleGit instance.
6401
+ * The NoOpOutputParser class is a type of output parser that does not
6402
+ * perform any operations on the output. It extends the BaseOutputParser
6403
+ * class and is part of the LangChain's output parsers module. This class
6404
+ * is useful in scenarios where the raw output of the Large Language
6405
+ * Models (LLMs) is required.
6424
6406
  */
6425
- const getRepo = () => {
6426
- let git;
6427
- try {
6428
- git = simpleGit();
6407
+ class NoOpOutputParser extends BaseOutputParser {
6408
+ constructor() {
6409
+ super(...arguments);
6410
+ Object.defineProperty(this, "lc_namespace", {
6411
+ enumerable: true,
6412
+ configurable: true,
6413
+ writable: true,
6414
+ value: ["langchain", "output_parsers", "default"]
6415
+ });
6416
+ Object.defineProperty(this, "lc_serializable", {
6417
+ enumerable: true,
6418
+ configurable: true,
6419
+ writable: true,
6420
+ value: true
6421
+ });
6429
6422
  }
6430
- catch (e) {
6431
- console.log('Error initializing git repo', e);
6432
- process.exit(1);
6423
+ static lc_name() {
6424
+ return "NoOpOutputParser";
6433
6425
  }
6434
- return git;
6435
- };
6426
+ /**
6427
+ * This method takes a string as input and returns the same string as
6428
+ * output. It does not perform any operations on the input string.
6429
+ * @param text The input string to be parsed.
6430
+ * @returns The same input string without any operations performed on it.
6431
+ */
6432
+ parse(text) {
6433
+ return Promise.resolve(text);
6434
+ }
6435
+ /**
6436
+ * This method returns an empty string. It does not provide any formatting
6437
+ * instructions.
6438
+ * @returns An empty string, indicating no formatting instructions.
6439
+ */
6440
+ getFormatInstructions() {
6441
+ return "";
6442
+ }
6443
+ }
6436
6444
 
6445
+ function isBaseLanguageModel(llmLike) {
6446
+ return typeof llmLike._llmType === "function";
6447
+ }
6448
+ function _getLanguageModel(llmLike) {
6449
+ if (isBaseLanguageModel(llmLike)) {
6450
+ return llmLike;
6451
+ }
6452
+ else if ("bound" in llmLike && Runnable.isRunnable(llmLike.bound)) {
6453
+ return _getLanguageModel(llmLike.bound);
6454
+ }
6455
+ else if ("runnable" in llmLike &&
6456
+ "fallbacks" in llmLike &&
6457
+ Runnable.isRunnable(llmLike.runnable)) {
6458
+ return _getLanguageModel(llmLike.runnable);
6459
+ }
6460
+ else if ("default" in llmLike && Runnable.isRunnable(llmLike.default)) {
6461
+ return _getLanguageModel(llmLike.default);
6462
+ }
6463
+ else {
6464
+ throw new Error("Unable to extract BaseLanguageModel from llmLike object.");
6465
+ }
6466
+ }
6437
6467
  /**
6438
- * Template for generating git commit messages based on code changes
6468
+ * @deprecated This class will be removed in 1.0.0. Use the LangChain Expression Language (LCEL) instead.
6469
+ * See the example below for how to use LCEL with the LLMChain class:
6439
6470
  *
6440
- * Variables:
6441
- * - summary: Contains the diff summary of staged changes
6442
- * - format_instructions: Instructions for the output format (JSON with title and body)
6443
- * - additional_context: Optional user-provided context to guide the commit message generation
6444
- * - commit_history: Optional history of previous commits for context
6445
- * - branch_name_context: String containing formatted branch name (or empty if disabled)
6471
+ * Chain to run queries against LLMs.
6472
+ *
6473
+ * @example
6474
+ * ```ts
6475
+ * import { ChatPromptTemplate } from "@langchain/core/prompts";
6476
+ * import { ChatOpenAI } from "@langchain/openai";
6477
+ *
6478
+ * const prompt = ChatPromptTemplate.fromTemplate("Tell me a {adjective} joke");
6479
+ * const llm = new ChatOpenAI();
6480
+ * const chain = prompt.pipe(llm);
6481
+ *
6482
+ * const response = await chain.invoke({ adjective: "funny" });
6483
+ * ```
6446
6484
  */
6447
- const template$4 = `Write informative git commit message, in the imperative, based on the diffs & file changes provided in the "Diff Summary" section.
6448
- Commit Messages must have a short description that is less than 50 characters and a longer detailed summary around 300 characters, the shorter and more concise the better.
6449
-
6450
- Please follow the guidelines below when writing your commit message:
6451
-
6452
- - Write concisely using an informal tone
6453
- - Avoid phrases like "this commit", "this change", "this function", etc. Instead refer to the function, variable, or class by name
6454
- - Avoid referencing specific files names or long paths in the commit message
6455
- - DO NOT include any diffs or file changes in the commit message
6456
- - Wrap variable, class, function, components, and dependency names in back ticks e.g. \`variable\`
6457
-
6458
- """"""
6459
- {{summary}}
6460
- """"""
6461
-
6462
- {{branch_name_context}}
6463
-
6464
- {{format_instructions}}
6465
-
6466
- {{commit_history}}
6467
-
6468
- {{additional_context}}
6469
- `;
6470
- // Define the variables that will be passed to the prompt template
6471
- const inputVariables$3 = ['summary', 'format_instructions', 'additional_context', 'commit_history', 'branch_name_context'];
6472
- const COMMIT_PROMPT = new PromptTemplate({
6473
- template: template$4,
6474
- inputVariables: inputVariables$3,
6475
- });
6476
- const CONVENTIONAL_TEMPLATE = `Generate a commit message that strictly adheres to the Conventional Commits specification. Follow these rules precisely:
6477
-
6478
- 1. Type Selection:
6479
- - Choose ONE of these types based on the changes:
6480
- * feat: A new feature
6481
- * fix: A bug fix
6482
- * docs: Documentation only changes
6483
- * style: Changes that don't affect the code's meaning (white-space, formatting, etc)
6484
- * refactor: Code changes that neither fix a bug nor add a feature
6485
- * perf: Code changes that improve performance
6486
- * test: Adding missing tests or correcting existing tests
6487
- * build: Changes that affect the build system or external dependencies
6488
- * ci: Changes to CI configuration files and scripts
6489
- * chore: Other changes that don't modify src or test files
6490
- * revert: Reverts a previous commit
6491
-
6492
- 2. Format Requirements:
6493
- - Title format: <type>(<optional-scope>): <description>
6494
- - Title must be 50 characters or less
6495
- - Description should be in imperative mood (e.g., "add" not "adds/added")
6496
- - Body MUST be 280 characters or less
6497
- - Separate body from title with a blank line
6498
- - Body should explain the motivation for the change and contrast it with previous behavior
6499
-
6500
- 3. Scope Guidelines:
6501
- - If the change affects a specific component/area, include it as a scope
6502
- - Scope should be a noun in parentheses (e.g., (parser), (ui), (config))
6503
- - Omit scope if the change is broad or affects multiple areas
6504
-
6505
- Based on the following diff summary, generate a conventional commit message that follows these rules exactly:
6506
-
6507
- """"""
6508
- {{summary}}
6509
- """"""
6510
-
6511
- {{branch_name_context}}
6512
-
6513
- {{format_instructions}}
6514
-
6515
- {{commit_history}}
6516
-
6517
- {{additional_context}}
6518
-
6519
- Remember:
6520
- - Be concise and precise
6521
- - Focus on WHAT and WHY, not HOW
6522
- - Use imperative mood in both title and body
6523
- - Ensure the title alone provides enough context to understand the change`;
6524
- const conventionalInputVariables = [
6525
- 'summary',
6526
- 'additional_context',
6527
- 'commit_history',
6528
- 'format_instructions',
6529
- 'branch_name_context',
6530
- ];
6531
- const CONVENTIONAL_COMMIT_PROMPT = new PromptTemplate({
6532
- template: CONVENTIONAL_TEMPLATE,
6533
- inputVariables: conventionalInputVariables,
6534
- });
6535
-
6536
- /**
6537
- * Verify template string contains all required input variables
6538
- *
6539
- * @param text template string
6540
- * @param inputVariables template variables
6541
- * @throws Error if validation fails
6542
- */
6543
- function validatePromptTemplate(text, inputVariables) {
6544
- if (!text || text.trim() === '') {
6545
- throw new Error('Prompt template cannot be empty');
6546
- }
6547
- if (!inputVariables || inputVariables.length === 0) {
6548
- return; // No variables to validate
6549
- }
6550
- // Extract variables from template using regex to find {variable} patterns
6551
- // This regex matches {variable_name} with no whitespace inside braces
6552
- // Excludes JSON-like patterns with quotes, colons, or whitespace
6553
- const templateVariableRegex = /\{([^}\s:"']+)\}/g;
6554
- const foundVariables = new Set();
6555
- let match;
6556
- while ((match = templateVariableRegex.exec(text)) !== null) {
6557
- foundVariables.add(match[1]);
6485
+ class LLMChain extends BaseChain {
6486
+ static lc_name() {
6487
+ return "LLMChain";
6558
6488
  }
6559
- // Check if all required variables are present in template
6560
- const missingVariables = inputVariables.filter(variable => !foundVariables.has(variable));
6561
- if (missingVariables.length > 0) {
6562
- throw new Error(`Prompt template is missing required variables: ${missingVariables.map(v => `{${v}}`).join(', ')}. ` +
6563
- `Found variables: ${Array.from(foundVariables).map(v => `{${v}}`).join(', ') || 'none'}`);
6489
+ get inputKeys() {
6490
+ return this.prompt.inputVariables;
6564
6491
  }
6565
- // Warn about unused variables in template (optional check)
6566
- const unusedVariables = Array.from(foundVariables).filter(variable => !inputVariables.includes(variable));
6567
- if (unusedVariables.length > 0) {
6568
- console.warn(`Prompt template contains undefined variables: ${unusedVariables.map(v => `{${v}}`).join(', ')}`);
6492
+ get outputKeys() {
6493
+ return [this.outputKey];
6569
6494
  }
6570
- }
6571
-
6572
- async function editPrompt(options) {
6573
- return await editor({
6574
- message: 'Edit the prompt',
6575
- default: options.prompt?.length ? options.prompt : COMMIT_PROMPT.template,
6576
- waitForUseInput: false,
6577
- postfix: 'Press ENTER to continue',
6578
- validate: (text) => {
6579
- try {
6580
- validatePromptTemplate(text, COMMIT_PROMPT.inputVariables);
6581
- return true;
6582
- }
6583
- catch (error) {
6584
- return error instanceof Error ? error.message : 'Invalid prompt template';
6585
- }
6586
- },
6587
- });
6588
- }
6589
-
6590
- async function editResult(result, options) {
6591
- if (options.openInEditor) {
6592
- return await editor({
6593
- message: 'Edit the commit message',
6594
- default: result,
6595
- waitForUseInput: false,
6596
- validate: (text) => (text ? true : 'Commit message cannot be empty'),
6495
+ constructor(fields) {
6496
+ super(fields);
6497
+ Object.defineProperty(this, "lc_serializable", {
6498
+ enumerable: true,
6499
+ configurable: true,
6500
+ writable: true,
6501
+ value: true
6597
6502
  });
6598
- }
6599
- return result;
6600
- }
6601
-
6602
- async function getUserReviewDecision({ label, descriptions, labels, enableEdit = true, enableRetry = true, enableFullRetry = true, enableModifyPrompt = true, selectLabel, }) {
6603
- const choices = [
6604
- {
6605
- name: labels?.approve || '✨ Looks good!',
6606
- value: 'approve',
6607
- description: descriptions?.approve || `Continue with the generated ${label}`,
6608
- },
6609
- ];
6610
- if (enableEdit) {
6611
- choices.push({
6612
- name: '📝 Edit',
6613
- value: 'edit',
6614
- description: descriptions?.edit || `Edit the generated ${label} before proceeding`,
6503
+ Object.defineProperty(this, "prompt", {
6504
+ enumerable: true,
6505
+ configurable: true,
6506
+ writable: true,
6507
+ value: void 0
6615
6508
  });
6616
- }
6617
- if (enableModifyPrompt) {
6618
- choices.push({
6619
- name: '🪶 Modify Prompt',
6620
- value: 'modifyPrompt',
6621
- description: descriptions?.modifyPrompt || `Modify the prompt template and regenerate the ${label}`,
6509
+ Object.defineProperty(this, "llm", {
6510
+ enumerable: true,
6511
+ configurable: true,
6512
+ writable: true,
6513
+ value: void 0
6622
6514
  });
6623
- }
6624
- if (enableRetry) {
6625
- choices.push({
6626
- name: labels?.retryMessageOnly || '🔄 Retry',
6627
- value: 'retryMessageOnly',
6628
- description: descriptions?.retryMessageOnly ||
6629
- `Restart the function execution from generating the ${label}`,
6515
+ Object.defineProperty(this, "llmKwargs", {
6516
+ enumerable: true,
6517
+ configurable: true,
6518
+ writable: true,
6519
+ value: void 0
6630
6520
  });
6631
- }
6632
- if (enableFullRetry) {
6633
- choices.push({
6634
- name: labels?.retryFull || '🔄 Retry Full',
6635
- value: 'retryFull',
6636
- description: descriptions?.retryFull ||
6637
- `Restart the function execution from the beginning, regenerating both the summary and ${label}`,
6521
+ Object.defineProperty(this, "outputKey", {
6522
+ enumerable: true,
6523
+ configurable: true,
6524
+ writable: true,
6525
+ value: "text"
6638
6526
  });
6527
+ Object.defineProperty(this, "outputParser", {
6528
+ enumerable: true,
6529
+ configurable: true,
6530
+ writable: true,
6531
+ value: void 0
6532
+ });
6533
+ this.prompt = fields.prompt;
6534
+ this.llm = fields.llm;
6535
+ this.llmKwargs = fields.llmKwargs;
6536
+ this.outputKey = fields.outputKey ?? this.outputKey;
6537
+ this.outputParser =
6538
+ fields.outputParser ?? new NoOpOutputParser();
6539
+ if (this.prompt.outputParser) {
6540
+ if (fields.outputParser) {
6541
+ throw new Error("Cannot set both outputParser and prompt.outputParser");
6542
+ }
6543
+ this.outputParser = this.prompt.outputParser;
6544
+ }
6639
6545
  }
6640
- choices.push({
6641
- name: labels?.cancel || '💣 Cancel',
6642
- value: 'cancel',
6643
- description: descriptions?.cancel || `Cancel the ${label}`,
6644
- });
6645
- return (await select({
6646
- message: selectLabel || `Would you like to make any changes to the ${label}?`,
6647
- choices,
6648
- }));
6649
- }
6650
-
6651
- function logResult(label, result) {
6652
- console.log(`\n${chalk.bgBlue(chalk.bold(`Proposed ${label}:`))}\n${SEPERATOR}\n${result}\n${SEPERATOR}\n`);
6653
- }
6654
-
6655
- async function generateAndReviewLoop({ label, factory, parser, noResult, agent, reviewParser, options, }) {
6656
- const { logger } = options;
6657
- let continueLoop = true;
6658
- let modifyPrompt = false;
6659
- let context = '';
6660
- let result = '';
6661
- const changes = await factory();
6662
- // if we don't have any changes, bail.
6663
- if (!changes || !Object.keys(changes).length) {
6664
- await noResult(options);
6546
+ getCallKeys() {
6547
+ const callKeys = "callKeys" in this.llm ? this.llm.callKeys : [];
6548
+ return callKeys;
6665
6549
  }
6666
- while (continueLoop) {
6667
- if (!context.length) {
6668
- context = await parser(changes, result, options);
6550
+ /** @ignore */
6551
+ _selectMemoryInputs(values) {
6552
+ const valuesForMemory = super._selectMemoryInputs(values);
6553
+ const callKeys = this.getCallKeys();
6554
+ for (const key of callKeys) {
6555
+ if (key in values) {
6556
+ delete valuesForMemory[key];
6557
+ }
6669
6558
  }
6670
- // if we still don't have a context, bail.
6671
- if (!context.length) {
6672
- await noResult(options);
6559
+ return valuesForMemory;
6560
+ }
6561
+ /** @ignore */
6562
+ async _getFinalOutput(generations, promptValue, runManager) {
6563
+ let finalCompletion;
6564
+ if (this.outputParser) {
6565
+ finalCompletion = await this.outputParser.parseResultWithPrompt(generations, promptValue, runManager?.getChild());
6673
6566
  }
6674
- if (modifyPrompt) {
6675
- options.prompt = await editPrompt(options);
6567
+ else {
6568
+ finalCompletion = generations[0].text;
6676
6569
  }
6677
- logger.startTimer().startSpinner(`Generating ${label}\n`, {
6678
- color: 'blue',
6679
- });
6680
- try {
6681
- result = await agent(context, options);
6682
- if (!result) {
6683
- logger.stopSpinner('💀 Agent failed to return content.', {
6684
- mode: 'fail',
6685
- color: 'red',
6686
- });
6687
- process.exit(0);
6570
+ return finalCompletion;
6571
+ }
6572
+ /**
6573
+ * Run the core logic of this chain and add to output if desired.
6574
+ *
6575
+ * Wraps _call and handles memory.
6576
+ */
6577
+ call(values, config) {
6578
+ return super.call(values, config);
6579
+ }
6580
+ /** @ignore */
6581
+ async _call(values, runManager) {
6582
+ const valuesForPrompt = { ...values };
6583
+ const valuesForLLM = {
6584
+ ...this.llmKwargs,
6585
+ };
6586
+ const callKeys = this.getCallKeys();
6587
+ for (const key of callKeys) {
6588
+ if (key in values) {
6589
+ if (valuesForLLM) {
6590
+ valuesForLLM[key] =
6591
+ values[key];
6592
+ delete valuesForPrompt[key];
6593
+ }
6688
6594
  }
6689
6595
  }
6690
- catch (error) {
6691
- // Handle special regeneration request from validation
6692
- if (error.message === 'REGENERATE_COMMIT_MESSAGE') {
6693
- logger.stopSpinner('Regenerating commit message...', {
6694
- mode: 'stop',
6695
- color: 'blue',
6696
- });
6697
- result = '';
6698
- continue;
6699
- }
6700
- // Re-throw other errors
6701
- throw error;
6596
+ const promptValue = await this.prompt.formatPromptValue(valuesForPrompt);
6597
+ if ("generatePrompt" in this.llm) {
6598
+ const { generations } = await this.llm.generatePrompt([promptValue], valuesForLLM, runManager?.getChild());
6599
+ return {
6600
+ [this.outputKey]: await this._getFinalOutput(generations[0], promptValue, runManager),
6601
+ };
6702
6602
  }
6703
- logger
6704
- .stopSpinner(`Generated ${label}`, {
6705
- color: 'green',
6706
- mode: 'succeed',
6707
- })
6708
- .stopTimer();
6709
- if (options?.interactive) {
6710
- logResult(label, reviewParser ? reviewParser(result, options) : result);
6711
- const reviewAnswer = await getUserReviewDecision({
6712
- label,
6713
- ...(options?.review || {}),
6714
- });
6715
- if (reviewAnswer === 'cancel') {
6716
- process.exit(0);
6717
- }
6718
- if (reviewAnswer === 'edit') {
6719
- options.openInEditor = true;
6720
- }
6721
- if (reviewAnswer === 'retryFull') {
6722
- context = '';
6723
- result = '';
6724
- options.prompt = '';
6725
- continue;
6726
- }
6727
- if (reviewAnswer === 'retryMessageOnly') {
6728
- modifyPrompt = false;
6729
- result = '';
6730
- continue;
6731
- }
6732
- if (reviewAnswer === 'modifyPrompt') {
6733
- modifyPrompt = true;
6734
- result = '';
6735
- continue;
6736
- }
6737
- // Only edit the result in interactive mode if approved
6738
- result = await editResult(result, options);
6603
+ const modelWithParser = this.outputParser
6604
+ ? this.llm.pipe(this.outputParser)
6605
+ : this.llm;
6606
+ const response = await modelWithParser.invoke(promptValue, runManager?.getChild());
6607
+ return {
6608
+ [this.outputKey]: response,
6609
+ };
6610
+ }
6611
+ /**
6612
+ * Format prompt with values and pass to LLM
6613
+ *
6614
+ * @param values - keys to pass to prompt template
6615
+ * @param callbackManager - CallbackManager to use
6616
+ * @returns Completion from LLM.
6617
+ *
6618
+ * @example
6619
+ * ```ts
6620
+ * llm.predict({ adjective: "funny" })
6621
+ * ```
6622
+ */
6623
+ async predict(values, callbackManager) {
6624
+ const output = await this.call(values, callbackManager);
6625
+ return output[this.outputKey];
6626
+ }
6627
+ _chainType() {
6628
+ return "llm";
6629
+ }
6630
+ static async deserialize(data) {
6631
+ const { llm, prompt } = data;
6632
+ if (!llm) {
6633
+ throw new Error("LLMChain must have llm");
6739
6634
  }
6740
- else {
6741
- // In non-interactive mode, we return the result as is to be output to stdout by the caller.
6742
- const displayResult = reviewParser ? reviewParser(result, options) : result;
6743
- // In non-interactive mode, ensure we return the properly formatted result
6744
- result = displayResult;
6635
+ if (!prompt) {
6636
+ throw new Error("LLMChain must have prompt");
6745
6637
  }
6746
- // if we're here, we're done.
6747
- continueLoop = false;
6638
+ return new LLMChain({
6639
+ llm: await BaseLanguageModel.deserialize(llm),
6640
+ prompt: await BasePromptTemplate.deserialize(prompt),
6641
+ });
6748
6642
  }
6749
- return result;
6750
- }
6751
-
6752
- const logSuccess = () => {
6753
- console.log(chalk.green(chalk.bold('\nAll set! 🦾🤖')));
6754
- };
6755
-
6756
- async function handleResult({ result, mode, interactiveModeCallback }) {
6757
- switch (mode) {
6758
- case 'interactive':
6759
- if (interactiveModeCallback) {
6760
- await interactiveModeCallback(result);
6761
- }
6762
- else {
6763
- console.warn('No result handler provided for interactive mode.');
6764
- logSuccess();
6765
- }
6766
- break;
6767
- case 'stdout':
6768
- default:
6769
- // Ensure we write the result to stdout in non-interactive mode
6770
- process.stdout.write(result + '\n', 'utf8');
6771
- break;
6643
+ /** @deprecated */
6644
+ serialize() {
6645
+ const serialize = "serialize" in this.llm ? this.llm.serialize() : undefined;
6646
+ return {
6647
+ _type: `${this._chainType()}_chain`,
6648
+ llm: serialize,
6649
+ prompt: this.prompt.serialize(),
6650
+ };
6651
+ }
6652
+ _getNumTokens(text) {
6653
+ return _getLanguageModel(this.llm).getNumTokens(text);
6772
6654
  }
6773
- process.exit(0);
6774
6655
  }
6775
6656
 
6776
- const template$3 = `Write informative git changelog, in the imperative, based on a series of individual messages.
6657
+ var llm_chain = /*#__PURE__*/Object.freeze({
6658
+ __proto__: null,
6659
+ LLMChain: LLMChain
6660
+ });
6777
6661
 
6778
- - Annotate each change with the git commit hash as reference, including just the first 7 characters
6779
- - Logically group changes, and if necessary, summarize dependency updates
6780
- - Include a descriptive title for the changelog, to give a high-level overview of the changes
6781
- - Depending on the size of the changes, consider breaking the changelog into sections
6782
- - Avoid generlizations like "various bug fixes" or "improvements" or "enhancements"
6662
+ const NAIVE_FIX_TEMPLATE = `Instructions:
6663
+ --------------
6664
+ {instructions}
6665
+ --------------
6666
+ Completion:
6667
+ --------------
6668
+ {completion}
6669
+ --------------
6783
6670
 
6784
- {{format_instructions}}
6671
+ Above, the Completion did not satisfy the constraints given in the Instructions.
6672
+ Error:
6673
+ --------------
6674
+ {error}
6675
+ --------------
6785
6676
 
6786
- """{{summary}}"""`;
6787
- const inputVariables$2 = ['format_instructions', 'summary'];
6788
- const CHANGELOG_PROMPT = new PromptTemplate({
6789
- template: template$3,
6790
- inputVariables: inputVariables$2,
6791
- });
6677
+ Please try again. Please only respond with an answer that satisfies the constraints laid out in the Instructions:`;
6678
+ const NAIVE_FIX_PROMPT =
6679
+ /* #__PURE__ */ PromptTemplate.fromTemplate(NAIVE_FIX_TEMPLATE);
6792
6680
 
6793
- const handler$4 = async (argv, logger) => {
6794
- const config = loadConfig(argv);
6795
- const git = getRepo();
6796
- const key = getApiKeyForModel(config);
6797
- const { provider, model } = getModelAndProviderFromConfig(config);
6798
- if (config.service.authentication.type !== 'None' && !key) {
6799
- logger.log(`No API Key found. 🗝️🚪`, { color: 'red' });
6800
- process.exit(1);
6681
+ function isLLMChain(x) {
6682
+ return (x.prompt !== undefined && x.llm !== undefined);
6683
+ }
6684
+ /**
6685
+ * Class that extends the BaseOutputParser to handle situations where the
6686
+ * initial parsing attempt fails. It contains a retryChain for retrying
6687
+ * the parsing process in case of a failure.
6688
+ */
6689
+ class OutputFixingParser extends BaseOutputParser {
6690
+ static lc_name() {
6691
+ return "OutputFixingParser";
6801
6692
  }
6802
- const llm = getLlm(provider, model, config);
6803
- const INTERACTIVE = isInteractive(config);
6804
- if (INTERACTIVE) {
6805
- if (!config.hideCocoBanner) {
6806
- logger.log(LOGO);
6807
- }
6693
+ /**
6694
+ * Static method to create a new instance of OutputFixingParser using a
6695
+ * given language model, parser, and optional fields.
6696
+ * @param llm The language model to be used.
6697
+ * @param parser The parser to be used.
6698
+ * @param fields Optional fields which may contain a prompt.
6699
+ * @returns A new instance of OutputFixingParser.
6700
+ */
6701
+ static fromLLM(llm, parser, fields) {
6702
+ const prompt = fields?.prompt ?? NAIVE_FIX_PROMPT;
6703
+ const chain = new LLMChain({ llm, prompt });
6704
+ return new OutputFixingParser({ parser, retryChain: chain });
6808
6705
  }
6809
- async function factory() {
6810
- const branchName = await getCurrentBranchName({ git });
6811
- if (config.sinceLastTag) {
6812
- logger.verbose(`Generating commit log since the last tag`, { color: 'yellow' });
6813
- return {
6814
- branch: branchName,
6815
- commits: await getChangesSinceLastTag({ git, logger }),
6816
- };
6817
- }
6818
- if (config.range && config.range.includes(':')) {
6819
- const [from, to] = config.range.split(':');
6820
- if (!from || !to) {
6821
- logger.log(`Invalid range provided. Expected format is <from>:<to>`, { color: 'red' });
6822
- process.exit(1);
6823
- }
6824
- return {
6825
- branch: branchName,
6826
- commits: await getCommitLogRange(from, to, { git, noMerges: true }),
6827
- };
6828
- }
6829
- if (argv.branch) {
6830
- logger.verbose(`Generating commit log against branch: ${argv.branch}`, { color: 'yellow' });
6831
- return {
6832
- branch: branchName,
6833
- commits: await getCommitLogAgainstBranch({ git, logger, targetBranch: argv.branch }),
6834
- };
6835
- }
6836
- logger.verbose(`No range, branch, or tag option provided. Defaulting to current branch`, {
6837
- color: 'yellow',
6706
+ constructor({ parser, retryChain, }) {
6707
+ super(...arguments);
6708
+ Object.defineProperty(this, "lc_namespace", {
6709
+ enumerable: true,
6710
+ configurable: true,
6711
+ writable: true,
6712
+ value: ["langchain", "output_parsers", "fix"]
6838
6713
  });
6839
- const commits = await getCommitLogCurrentBranch({ git, logger });
6840
- return {
6841
- branch: branchName,
6842
- commits,
6843
- };
6714
+ Object.defineProperty(this, "lc_serializable", {
6715
+ enumerable: true,
6716
+ configurable: true,
6717
+ writable: true,
6718
+ value: true
6719
+ });
6720
+ Object.defineProperty(this, "parser", {
6721
+ enumerable: true,
6722
+ configurable: true,
6723
+ writable: true,
6724
+ value: void 0
6725
+ });
6726
+ Object.defineProperty(this, "retryChain", {
6727
+ enumerable: true,
6728
+ configurable: true,
6729
+ writable: true,
6730
+ value: void 0
6731
+ });
6732
+ this.parser = parser;
6733
+ this.retryChain = retryChain;
6844
6734
  }
6845
- async function parser({ branch, commits }) {
6846
- let result;
6847
- if (!commits || commits.length === 0) {
6848
- result = `## ${branch}\n\nNo commits found.`;
6735
+ /**
6736
+ * Method to parse the completion using the parser. If the initial parsing
6737
+ * fails, it uses the retryChain to attempt to fix the output and retry
6738
+ * the parsing process.
6739
+ * @param completion The completion to be parsed.
6740
+ * @param callbacks Optional callbacks to be used during parsing.
6741
+ * @returns The parsed output.
6742
+ */
6743
+ async parse(completion, callbacks) {
6744
+ try {
6745
+ return await this.parser.parse(completion, callbacks);
6849
6746
  }
6850
- else {
6851
- result = `## ${branch}\n\n${commits.map((commit) => commit.trim()).join('\n\n')}`;
6747
+ catch (e) {
6748
+ // eslint-disable-next-line no-instanceof/no-instanceof
6749
+ if (e instanceof OutputParserException) {
6750
+ const retryInput = {
6751
+ instructions: this.parser.getFormatInstructions(),
6752
+ completion,
6753
+ error: e,
6754
+ };
6755
+ if (isLLMChain(this.retryChain)) {
6756
+ const result = await this.retryChain.call(retryInput, callbacks);
6757
+ const newCompletion = result[this.retryChain.outputKey];
6758
+ return this.parser.parse(newCompletion, callbacks);
6759
+ }
6760
+ else {
6761
+ const result = await this.retryChain.invoke(retryInput, {
6762
+ callbacks,
6763
+ });
6764
+ return result;
6765
+ }
6766
+ }
6767
+ throw e;
6768
+ }
6769
+ }
6770
+ /**
6771
+ * Method to get the format instructions for the parser.
6772
+ * @returns The format instructions for the parser.
6773
+ */
6774
+ getFormatInstructions() {
6775
+ return this.parser.getFormatInstructions();
6776
+ }
6777
+ }
6778
+
6779
+ /**
6780
+ * Creates a parser with built-in retry logic for schema-based generation
6781
+ * @param schema - Zod schema for the expected output structure
6782
+ * @param llm - LLM instance for retry attempts
6783
+ * @param options - Configuration options for retry behavior
6784
+ * @returns OutputFixingParser configured with retry logic
6785
+ * @throws LangChainExecutionError if parser creation fails
6786
+ */
6787
+ function createSchemaParser(schema, llm, options = {}) {
6788
+ validateRequired(schema, 'schema', 'createSchemaParser');
6789
+ validateRequired(llm, 'llm', 'createSchemaParser');
6790
+ validateRequired(options, 'options', 'createSchemaParser');
6791
+ // Validate schema is actually a Zod schema
6792
+ if (typeof schema.parse !== 'function') {
6793
+ throw new LangChainExecutionError('createSchemaParser: Schema must be a valid Zod schema with a parse method', { schemaType: typeof schema, hasParseMethod: typeof schema.parse });
6794
+ }
6795
+ // Validate options structure
6796
+ if (typeof options !== 'object' || Array.isArray(options)) {
6797
+ throw new LangChainExecutionError('createSchemaParser: Options must be a non-array object', { options, type: typeof options, isArray: Array.isArray(options) });
6798
+ }
6799
+ const { retryTemplate } = options;
6800
+ // Validate retryTemplate if provided
6801
+ if (retryTemplate !== undefined && typeof retryTemplate !== 'string') {
6802
+ throw new LangChainExecutionError('createSchemaParser: retryTemplate must be a string when provided', { retryTemplate, type: typeof retryTemplate });
6803
+ }
6804
+ try {
6805
+ // @ts-expect-error - StructuredOutputParser constructor type issue with Zod schema
6806
+ const baseParser = new StructuredOutputParser(schema);
6807
+ const defaultRetryTemplate = `The following text failed to parse as valid JSON. Please convert it into a valid JSON object that matches the required schema.
6808
+
6809
+ ## Text to fix:
6810
+ {completion}
6811
+
6812
+ ## Instructions:
6813
+ {instructions}
6814
+
6815
+ You must return ONLY valid JSON that matches the schema exactly. Do not include any additional text, explanations, or markdown formatting:`;
6816
+ const retryPromptTemplate = new PromptTemplate({
6817
+ template: retryTemplate || defaultRetryTemplate,
6818
+ inputVariables: ['completion', 'instructions'],
6819
+ });
6820
+ const retryChain = retryPromptTemplate.pipe(llm).pipe(baseParser);
6821
+ return new OutputFixingParser({
6822
+ parser: baseParser,
6823
+ retryChain: retryChain,
6824
+ });
6825
+ }
6826
+ catch (error) {
6827
+ handleLangChainError(error, 'createSchemaParser: Failed to create schema parser', {
6828
+ schemaName: schema.constructor.name,
6829
+ llmType: llm.constructor.name,
6830
+ hasRetryTemplate: !!retryTemplate
6831
+ });
6832
+ }
6833
+ }
6834
+
6835
+ /**
6836
+ * Executes a LangChain pipeline with the provided LLM, prompt, variables, and parser.
6837
+ * @param params - The execution parameters
6838
+ * @returns The parsed result from the LLM chain
6839
+ * @throws LangChainExecutionError if the chain execution fails or returns empty results
6840
+ */
6841
+ const executeChain = async ({ llm, prompt, variables, parser }) => {
6842
+ validateRequired(llm, 'llm', 'executeChain');
6843
+ validateRequired(prompt, 'prompt', 'executeChain');
6844
+ validateRequired(variables, 'variables', 'executeChain');
6845
+ validateRequired(parser, 'parser', 'executeChain');
6846
+ // Validate that variables is an object
6847
+ if (typeof variables !== 'object' || Array.isArray(variables)) {
6848
+ throw new LangChainExecutionError('executeChain: Variables must be a non-array object', { variables, type: typeof variables, isArray: Array.isArray(variables) });
6849
+ }
6850
+ try {
6851
+ const chain = prompt.pipe(llm).pipe(parser);
6852
+ const result = await chain.invoke(variables);
6853
+ if (result === null || result === undefined) {
6854
+ throw new LangChainExecutionError('executeChain: Chain execution returned null or undefined result', { variables, promptInputVariables: prompt.inputVariables });
6852
6855
  }
6853
6856
  return result;
6854
6857
  }
6855
- const changelogMsg = await generateAndReviewLoop({
6856
- label: 'changelog',
6857
- options: {
6858
- ...config,
6859
- prompt: config.prompt || CHANGELOG_PROMPT.template,
6860
- logger,
6861
- interactive: INTERACTIVE,
6862
- review: {
6863
- enableFullRetry: false,
6864
- },
6865
- },
6866
- factory,
6867
- parser,
6868
- agent: async (context, options) => {
6869
- const parser = new StructuredOutputParser(ChangelogResponseSchema);
6870
- const prompt = getPrompt({
6871
- template: options.prompt,
6872
- variables: CHANGELOG_PROMPT.inputVariables,
6873
- fallback: CHANGELOG_PROMPT,
6874
- });
6875
- const formatInstructions = "Only respond with a valid JSON object, containing two fields: 'title' an escaped string, no more than 65 characters, and 'content' also an escaped string.";
6876
- const changelog = await executeChain({
6877
- llm,
6878
- prompt,
6879
- variables: {
6880
- summary: context,
6881
- format_instructions: formatInstructions,
6882
- },
6883
- parser,
6884
- });
6885
- const branchName = await getCurrentBranchName({ git });
6886
- const ticketId = extractTicketIdFromBranchName(branchName);
6887
- const footer = ticketId ? `\n\nPart of **${ticketId}**` : '';
6888
- return `${changelog.title}\n\n${changelog.content}${footer}`;
6889
- },
6890
- noResult: async () => {
6891
- if (config.range) {
6892
- logger.log(`No commits found in the provided range.`, { color: 'red' });
6893
- process.exit(0);
6894
- }
6895
- logger.log(`No commits found in the current branch.`, { color: 'red' });
6896
- process.exit(0);
6897
- },
6898
- });
6899
- const MODE = (INTERACTIVE && 'interactive') || (config.commit && 'interactive') || config?.mode || 'stdout';
6900
- handleResult({
6901
- result: changelogMsg,
6902
- interactiveModeCallback: async () => {
6903
- logSuccess();
6904
- },
6905
- mode: MODE,
6906
- });
6858
+ catch (error) {
6859
+ // Re-throw LangChain errors as-is
6860
+ if (error instanceof LangChainExecutionError) {
6861
+ throw error;
6862
+ }
6863
+ // Wrap other errors with context
6864
+ handleLangChainError(error, 'executeChain: Chain execution failed', {
6865
+ promptInputVariables: prompt.inputVariables,
6866
+ variableKeys: Object.keys(variables),
6867
+ parserType: parser.constructor.name
6868
+ });
6869
+ }
6907
6870
  };
6908
6871
 
6909
- var changelog = {
6910
- command: command$4,
6911
- desc: 'Generate a changelog from current or target branch, provided commit range, or since the last tag.',
6912
- builder: builder$4,
6913
- handler: commandExecutor(handler$4),
6914
- options: options$4,
6915
- };
6872
+ function extractTicketIdFromBranchName(branchName) {
6873
+ const regex = /((?<!([A-Z]+)-?)[A-Z]+-\d+)/;
6874
+ const match = branchName.match(regex);
6875
+ return match ? match[0] : null;
6876
+ }
6916
6877
 
6917
- const conventionalTypeRegex = /^(feat|fix|docs|style|refactor|perf|test|build|ci|chore|revert)(\(.+\))?:/;
6918
- // Regular commit message schema with basic validation
6919
- const CommitMessageResponseSchema = objectType({
6920
- title: stringType(),
6921
- body: stringType(),
6922
- });
6923
- // Conventional commit message schema with strict formatting rules
6924
- const ConventionalCommitMessageResponseSchema = objectType({
6925
- title: stringType()
6926
- .max(50, "Title must be 50 characters or less")
6927
- .refine((title) => conventionalTypeRegex.test(title), "Title must follow Conventional Commits format (e.g., 'feat: add new feature' or 'fix(scope): fix bug')"),
6928
- body: stringType()
6929
- // .max(280, "Body must be 280 characters or less"),
6930
- });
6931
- const command$3 = 'commit';
6932
6878
  /**
6933
- * Command line options via yargs
6879
+ * Formats a commit log into a readable string format.
6880
+ *
6881
+ * @param commitLog - The commit log result containing an array of commit details.
6882
+ * @returns An array of formatted commit log strings.
6883
+ *
6884
+ * Each formatted string includes:
6885
+ * - The date of the commit in square brackets.
6886
+ * - The commit message.
6887
+ * - The commit body.
6888
+ * - The commit hash in parentheses.
6889
+ * - The author's name and email in angle brackets.
6934
6890
  */
6935
- const options$3 = {
6936
- i: {
6937
- alias: 'interactive',
6938
- description: 'Toggle interactive mode',
6939
- type: 'boolean',
6940
- },
6941
- ignoredFiles: {
6942
- description: 'Ignored files',
6943
- type: 'array',
6944
- },
6945
- ignoredExtensions: {
6946
- description: 'Ignored extensions',
6947
- type: 'array',
6948
- },
6949
- append: {
6950
- description: 'Add content to the end of the generated commit message',
6951
- type: 'string',
6952
- },
6953
- appendTicket: {
6954
- description: 'Append ticket ID from branch name to the commit message',
6955
- type: 'boolean',
6956
- alias: 't',
6957
- },
6958
- additional: {
6959
- description: 'Add extra contextual information to the prompt',
6960
- type: 'string',
6961
- alias: 'a',
6962
- },
6963
- withPreviousCommits: {
6964
- description: 'Include previous commits as context (specify number of commits, 0 for none)',
6965
- type: 'number',
6966
- default: 0,
6967
- alias: 'p',
6968
- },
6969
- conventional: {
6970
- description: 'Generate commit message in Conventional Commits format',
6971
- type: 'boolean',
6972
- default: false,
6973
- alias: 'c',
6974
- },
6975
- includeBranchName: {
6976
- description: 'Include the current branch name in the commit prompt for context',
6977
- type: 'boolean',
6978
- default: true,
6979
- },
6980
- noDiff: {
6981
- description: 'Only pass basic "git status" result instead of providing entire diff',
6982
- type: 'boolean',
6983
- default: false,
6984
- },
6891
+ const formatCommitLog = (commitLog) => {
6892
+ return commitLog.all.map(({ message, date, body, author_name, hash, author_email }) => `[${date}] ${message}\n${body}\n(${hash}) - ${author_name}<${author_email}>`);
6985
6893
  };
6986
- const builder$3 = (yargs) => {
6987
- return yargs.options(options$3).usage(getCommandUsageHeader(command$3));
6894
+
6895
+ const getChangesSinceLastTag = async ({ git }) => {
6896
+ const tags = await git.tags();
6897
+ if (tags.all.length > 0) {
6898
+ const lastTag = tags.latest;
6899
+ const commitLog = await git.log({ from: lastTag });
6900
+ return formatCommitLog(commitLog);
6901
+ }
6902
+ else {
6903
+ return ['No tags found in the repository.'];
6904
+ }
6988
6905
  };
6989
6906
 
6990
- new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");
6907
+ /**
6908
+ * Retrieves the commit log range between two specified commits (inclusive of both commits).
6909
+ *
6910
+ * @param from - The starting commit (can be a commit hash, HEAD reference, or branch name). This commit will be included in the results.
6911
+ * @param to - The ending commit (can be a commit hash, HEAD reference, or branch name). This commit will be included in the results.
6912
+ * @param options - Additional options for retrieving the commit log range.
6913
+ * @returns A promise that resolves to an array of commit log messages, including both the 'from' and 'to' commits.
6914
+ * @throws If there is an error retrieving the commit log range.
6915
+ */
6916
+ async function getCommitLogRange(from, to, { noMerges, git }) {
6917
+ try {
6918
+ // Use from^..to to include the 'from' commit in the range
6919
+ // This works because from^..to means "commits reachable from 'to' but not from the parent of 'from'"
6920
+ const logOptions = {
6921
+ from: `${from}^`,
6922
+ to,
6923
+ '--no-merges': noMerges
6924
+ };
6925
+ const commitLog = await git.log(logOptions);
6926
+ return commitLog.all.map(({ message, date, body, author_name, hash, author_email }) => `[${date}] ${message}\n${body}\n(${hash}) - ${author_name}<${author_email}>`);
6927
+ }
6928
+ catch (error) {
6929
+ // If from^ fails (e.g., 'from' is the first commit), fall back to using from..to and manually adding the 'from' commit
6930
+ if (error instanceof Error && error.message.includes('unknown revision')) {
6931
+ try {
6932
+ // Get the 'from' commit separately
6933
+ const fromCommitLog = await git.log({ from: from, maxCount: 1 });
6934
+ const fromCommit = fromCommitLog.latest;
6935
+ // Get the range from..to (excluding 'from')
6936
+ const rangeLogOptions = {
6937
+ from,
6938
+ to,
6939
+ '--no-merges': noMerges
6940
+ };
6941
+ const rangeCommitLog = await git.log(rangeLogOptions);
6942
+ // Combine the 'from' commit with the range commits
6943
+ const allCommits = fromCommit
6944
+ ? [fromCommit, ...rangeCommitLog.all]
6945
+ : rangeCommitLog.all;
6946
+ return allCommits.map(({ message, date, body, author_name, hash, author_email }) => `[${date}] ${message}\n${body}\n(${hash}) - ${author_name}<${author_email}>`);
6947
+ }
6948
+ catch (fallbackError) {
6949
+ throw fallbackError;
6950
+ }
6951
+ }
6952
+ throw error;
6953
+ }
6954
+ }
6955
+
6956
+ /**
6957
+ * Retrieves the name of the current branch.
6958
+ *
6959
+ * @param {GetCurrentBranchName} options - The options for retrieving the branch name.
6960
+ * @returns {Promise<string>} - A promise that resolves to the name of the current branch.
6961
+ */
6962
+ async function getCurrentBranchName({ git }) {
6963
+ return await git.revparse(['--abbrev-ref', 'HEAD']);
6964
+ }
6991
6965
 
6992
6966
  /**
6993
- * Base interface that all chains must implement.
6967
+ * Retrieves the commit log between the current branch and a specified target branch.
6968
+ *
6969
+ * @param {Object} options - The options for retrieving the commit log.
6970
+ * @param {SimpleGit} options.git - The SimpleGit instance.
6971
+ * @param {Logger} options.logger - The logger for logging messages.
6972
+ * @param {string} options.targetBranch - The target branch to compare against.
6973
+ * @returns {Promise<string[]>} The array of commit messages in the commit log.
6994
6974
  */
6995
- class BaseChain extends BaseLangChain {
6996
- get lc_namespace() {
6997
- return ["langchain", "chains", this._chainType()];
6998
- }
6999
- constructor(fields,
7000
- /** @deprecated */
7001
- verbose,
7002
- /** @deprecated */
7003
- callbacks) {
7004
- if (arguments.length === 1 &&
7005
- typeof fields === "object" &&
7006
- !("saveContext" in fields)) {
7007
- // fields is not a BaseMemory
7008
- const { memory, callbackManager, ...rest } = fields;
7009
- super({ ...rest, callbacks: callbackManager ?? rest.callbacks });
7010
- this.memory = memory;
7011
- }
7012
- else {
7013
- // fields is a BaseMemory
7014
- super({ verbose, callbacks });
7015
- this.memory = fields;
6975
+ async function getCommitLogAgainstBranch({ git, logger, targetBranch, }) {
6976
+ try {
6977
+ // Get the current branch name
6978
+ const currentBranch = await getCurrentBranchName({ git });
6979
+ // Get the list of commits that are unique to the current branch compared to the target branch
6980
+ const uniqueCommits = (await git.raw(['rev-list', `${targetBranch}..${currentBranch}`]))
6981
+ .split('\n')
6982
+ .filter(Boolean)
6983
+ .reverse();
6984
+ logger?.verbose(`Found ${uniqueCommits.length} unique commits between "${currentBranch}" and "${targetBranch}"`, { color: 'blue' });
6985
+ const firstCommit = uniqueCommits[0];
6986
+ const lastCommit = uniqueCommits[uniqueCommits.length - 1];
6987
+ if (!firstCommit || !lastCommit) {
6988
+ logger?.log('Unable to determine first and last commit between branches', { color: 'yellow' });
6989
+ return [];
7016
6990
  }
6991
+ // Retrieve commit log with messages
6992
+ return await getCommitLogRange(firstCommit, lastCommit, { git, noMerges: true });
7017
6993
  }
7018
- /** @ignore */
7019
- _selectMemoryInputs(values) {
7020
- const valuesForMemory = { ...values };
7021
- if ("signal" in valuesForMemory) {
7022
- delete valuesForMemory.signal;
7023
- }
7024
- if ("timeout" in valuesForMemory) {
7025
- delete valuesForMemory.timeout;
7026
- }
7027
- return valuesForMemory;
6994
+ catch (error) {
6995
+ logger?.log('Encountered an error getting commit log between branches', { color: 'red' });
7028
6996
  }
7029
- /**
7030
- * Invoke the chain with the provided input and returns the output.
7031
- * @param input Input values for the chain run.
7032
- * @param config Optional configuration for the Runnable.
7033
- * @returns Promise that resolves with the output of the chain run.
7034
- */
7035
- async invoke(input, options) {
7036
- const config = ensureConfig(options);
7037
- const fullValues = await this._formatValues(input);
7038
- const callbackManager_ = await CallbackManager.configure(config?.callbacks, this.callbacks, config?.tags, this.tags, config?.metadata, this.metadata, { verbose: this.verbose });
7039
- const runManager = await callbackManager_?.handleChainStart(this.toJSON(), fullValues, undefined, undefined, undefined, undefined, config?.runName);
7040
- let outputValues;
7041
- try {
7042
- outputValues = await (fullValues.signal
7043
- ? Promise.race([
7044
- this._call(fullValues, runManager, config),
7045
- new Promise((_, reject) => {
7046
- fullValues.signal?.addEventListener("abort", () => {
7047
- reject(new Error("AbortError"));
7048
- });
7049
- }),
7050
- ])
7051
- : this._call(fullValues, runManager, config));
6997
+ return [];
6998
+ }
6999
+
7000
+ /**
7001
+ * Retrieves the commit log for the current branch.
7002
+ *
7003
+ * @param {Object} options - The options for retrieving the commit log.
7004
+ * @param {SimpleGit} options.git - The SimpleGit instance.
7005
+ * @param {Logger} options.logger - The logger for logging messages.
7006
+ * @param {string} [options.comparisonBranch='main'] - The branch to compare against.
7007
+ * @param {string} [options.comparisonRemote='origin'] - The remote to compare against.
7008
+ * @returns {Promise<string[]>} The array of commit messages in the commit log.
7009
+ */
7010
+ async function getCommitLogCurrentBranch({ git, logger, comparisonBranch = 'main', comparisonRemote = 'origin', }) {
7011
+ try {
7012
+ const branchName = await getCurrentBranchName({ git });
7013
+ const hasCommits = (await git.raw(['rev-list', '--count', branchName])) !== '0';
7014
+ if (!hasCommits) {
7015
+ logger?.log('No commits on the current branch.');
7016
+ return [];
7052
7017
  }
7053
- catch (e) {
7054
- await runManager?.handleChainError(e);
7055
- throw e;
7018
+ let uniqueCommits;
7019
+ if (comparisonBranch === branchName) {
7020
+ // If the comparison branch is the same as the current branch, we compare against the remote.
7021
+ uniqueCommits = (await git.raw(['rev-list', `${comparisonRemote}/${comparisonBranch}..${branchName}`]))
7022
+ .split('\n')
7023
+ .filter(Boolean)
7024
+ .reverse();
7056
7025
  }
7057
- if (!(this.memory == null)) {
7058
- await this.memory.saveContext(this._selectMemoryInputs(input), outputValues);
7026
+ else {
7027
+ // Your existing code for different branches
7028
+ uniqueCommits = (await git.raw(['rev-list', `${comparisonBranch}..${branchName}`]))
7029
+ .split('\n')
7030
+ .filter(Boolean)
7031
+ .reverse();
7059
7032
  }
7060
- await runManager?.handleChainEnd(outputValues);
7061
- // add the runManager's currentRunId to the outputValues
7062
- Object.defineProperty(outputValues, RUN_KEY, {
7063
- value: runManager ? { runId: runManager?.runId } : undefined,
7064
- configurable: true,
7033
+ logger?.verbose(`Found ${uniqueCommits.length} unique commits on "${branchName}"`, {
7034
+ color: 'blue',
7065
7035
  });
7066
- return outputValues;
7067
- }
7068
- _validateOutputs(outputs) {
7069
- const missingKeys = this.outputKeys.filter((k) => !(k in outputs));
7070
- if (missingKeys.length) {
7071
- throw new Error(`Missing output keys: ${missingKeys.join(", ")} from chain ${this._chainType()}`);
7072
- }
7073
- }
7074
- async prepOutputs(inputs, outputs, returnOnlyOutputs = false) {
7075
- this._validateOutputs(outputs);
7076
- if (this.memory) {
7077
- await this.memory.saveContext(inputs, outputs);
7078
- }
7079
- if (returnOnlyOutputs) {
7080
- return outputs;
7081
- }
7082
- return { ...inputs, ...outputs };
7083
- }
7084
- /**
7085
- * Return a json-like object representing this chain.
7086
- */
7087
- serialize() {
7088
- throw new Error("Method not implemented.");
7089
- }
7090
- /** @deprecated Use .invoke() instead. Will be removed in 0.2.0. */
7091
- async run(
7092
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
7093
- input, config) {
7094
- const inputKeys = this.inputKeys.filter((k) => !this.memory?.memoryKeys.includes(k) ?? true);
7095
- const isKeylessInput = inputKeys.length <= 1;
7096
- if (!isKeylessInput) {
7097
- throw new Error(`Chain ${this._chainType()} expects multiple inputs, cannot use 'run' `);
7098
- }
7099
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
7100
- const values = inputKeys.length ? { [inputKeys[0]]: input } : {};
7101
- const returnValues = await this.call(values, config);
7102
- const keys = Object.keys(returnValues);
7103
- if (keys.length === 1) {
7104
- return returnValues[keys[0]];
7105
- }
7106
- throw new Error("return values have multiple keys, `run` only supported when one key currently");
7107
- }
7108
- async _formatValues(values) {
7109
- const fullValues = { ...values };
7110
- if (fullValues.timeout && !fullValues.signal) {
7111
- fullValues.signal = AbortSignal.timeout(fullValues.timeout);
7112
- delete fullValues.timeout;
7113
- }
7114
- if (!(this.memory == null)) {
7115
- const newValues = await this.memory.loadMemoryVariables(this._selectMemoryInputs(values));
7116
- for (const [key, value] of Object.entries(newValues)) {
7117
- fullValues[key] = value;
7118
- }
7119
- }
7120
- return fullValues;
7121
- }
7122
- /**
7123
- * @deprecated Use .invoke() instead. Will be removed in 0.2.0.
7124
- *
7125
- * Run the core logic of this chain and add to output if desired.
7126
- *
7127
- * Wraps _call and handles memory.
7128
- */
7129
- async call(values, config,
7130
- /** @deprecated */
7131
- tags) {
7132
- const parsedConfig = { tags, ...parseCallbackConfigArg(config) };
7133
- return this.invoke(values, parsedConfig);
7134
- }
7135
- /**
7136
- * @deprecated Use .batch() instead. Will be removed in 0.2.0.
7137
- *
7138
- * Call the chain on all inputs in the list
7139
- */
7140
- async apply(inputs, config) {
7141
- return Promise.all(inputs.map(async (i, idx) => this.call(i, config?.[idx])));
7142
- }
7143
- /**
7144
- * Load a chain from a json-like object describing it.
7145
- */
7146
- static async deserialize(data, values = {}) {
7147
- switch (data._type) {
7148
- case "llm_chain": {
7149
- const { LLMChain } = await Promise.resolve().then(function () { return llm_chain; });
7150
- return LLMChain.deserialize(data);
7151
- }
7152
- case "sequential_chain": {
7153
- const { SequentialChain } = await Promise.resolve().then(function () { return sequential_chain; });
7154
- return SequentialChain.deserialize(data);
7155
- }
7156
- case "simple_sequential_chain": {
7157
- const { SimpleSequentialChain } = await Promise.resolve().then(function () { return sequential_chain; });
7158
- return SimpleSequentialChain.deserialize(data);
7159
- }
7160
- case "stuff_documents_chain": {
7161
- const { StuffDocumentsChain } = await Promise.resolve().then(function () { return combine_docs_chain; });
7162
- return StuffDocumentsChain.deserialize(data);
7163
- }
7164
- case "map_reduce_documents_chain": {
7165
- const { MapReduceDocumentsChain } = await Promise.resolve().then(function () { return combine_docs_chain; });
7166
- return MapReduceDocumentsChain.deserialize(data);
7167
- }
7168
- case "refine_documents_chain": {
7169
- const { RefineDocumentsChain } = await Promise.resolve().then(function () { return combine_docs_chain; });
7170
- return RefineDocumentsChain.deserialize(data);
7171
- }
7172
- case "vector_db_qa": {
7173
- const { VectorDBQAChain } = await Promise.resolve().then(function () { return vector_db_qa; });
7174
- return VectorDBQAChain.deserialize(data, values);
7175
- }
7176
- case "api_chain": {
7177
- const { APIChain } = await Promise.resolve().then(function () { return api_chain; });
7178
- return APIChain.deserialize(data);
7179
- }
7180
- default:
7181
- throw new Error(`Invalid prompt type in config: ${data._type}`);
7036
+ const firstCommit = uniqueCommits[0];
7037
+ const lastCommit = uniqueCommits[uniqueCommits.length - 1];
7038
+ if (!firstCommit || !lastCommit) {
7039
+ logger?.log('Unable to determine first and last commit on the current branch', {
7040
+ color: 'yellow',
7041
+ });
7042
+ return [];
7182
7043
  }
7044
+ return await getCommitLogRange(firstCommit, lastCommit, { git, noMerges: true });
7045
+ }
7046
+ catch (error) {
7047
+ logger?.log('Encountered an error getting commit log from current branch', { color: 'red' });
7183
7048
  }
7049
+ return [];
7184
7050
  }
7185
7051
 
7186
7052
  /**
7187
- * The NoOpOutputParser class is a type of output parser that does not
7188
- * perform any operations on the output. It extends the BaseOutputParser
7189
- * class and is part of the LangChain's output parsers module. This class
7190
- * is useful in scenarios where the raw output of the Large Language
7191
- * Models (LLMs) is required.
7053
+ * Retrieves the SimpleGit instance for the repository.
7054
+ * @returns {SimpleGit} The SimpleGit instance.
7192
7055
  */
7193
- class NoOpOutputParser extends BaseOutputParser {
7194
- constructor() {
7195
- super(...arguments);
7196
- Object.defineProperty(this, "lc_namespace", {
7197
- enumerable: true,
7198
- configurable: true,
7199
- writable: true,
7200
- value: ["langchain", "output_parsers", "default"]
7201
- });
7202
- Object.defineProperty(this, "lc_serializable", {
7203
- enumerable: true,
7204
- configurable: true,
7205
- writable: true,
7206
- value: true
7207
- });
7208
- }
7209
- static lc_name() {
7210
- return "NoOpOutputParser";
7211
- }
7212
- /**
7213
- * This method takes a string as input and returns the same string as
7214
- * output. It does not perform any operations on the input string.
7215
- * @param text The input string to be parsed.
7216
- * @returns The same input string without any operations performed on it.
7217
- */
7218
- parse(text) {
7219
- return Promise.resolve(text);
7056
+ const getRepo = () => {
7057
+ let git;
7058
+ try {
7059
+ git = simpleGit();
7220
7060
  }
7221
- /**
7222
- * This method returns an empty string. It does not provide any formatting
7223
- * instructions.
7224
- * @returns An empty string, indicating no formatting instructions.
7225
- */
7226
- getFormatInstructions() {
7227
- return "";
7061
+ catch (e) {
7062
+ console.log('Error initializing git repo', e);
7063
+ process.exit(1);
7228
7064
  }
7229
- }
7065
+ return git;
7066
+ };
7230
7067
 
7231
- function isBaseLanguageModel(llmLike) {
7232
- return typeof llmLike._llmType === "function";
7233
- }
7234
- function _getLanguageModel(llmLike) {
7235
- if (isBaseLanguageModel(llmLike)) {
7236
- return llmLike;
7237
- }
7238
- else if ("bound" in llmLike && Runnable.isRunnable(llmLike.bound)) {
7239
- return _getLanguageModel(llmLike.bound);
7240
- }
7241
- else if ("runnable" in llmLike &&
7242
- "fallbacks" in llmLike &&
7243
- Runnable.isRunnable(llmLike.runnable)) {
7244
- return _getLanguageModel(llmLike.runnable);
7245
- }
7246
- else if ("default" in llmLike && Runnable.isRunnable(llmLike.default)) {
7247
- return _getLanguageModel(llmLike.default);
7248
- }
7249
- else {
7250
- throw new Error("Unable to extract BaseLanguageModel from llmLike object.");
7251
- }
7252
- }
7253
7068
  /**
7254
- * @deprecated This class will be removed in 1.0.0. Use the LangChain Expression Language (LCEL) instead.
7255
- * See the example below for how to use LCEL with the LLMChain class:
7256
- *
7257
- * Chain to run queries against LLMs.
7258
- *
7259
- * @example
7260
- * ```ts
7261
- * import { ChatPromptTemplate } from "@langchain/core/prompts";
7262
- * import { ChatOpenAI } from "@langchain/openai";
7069
+ * Template for generating git commit messages based on code changes
7263
7070
  *
7264
- * const prompt = ChatPromptTemplate.fromTemplate("Tell me a {adjective} joke");
7265
- * const llm = new ChatOpenAI();
7266
- * const chain = prompt.pipe(llm);
7071
+ * Variables:
7072
+ * - summary: Contains the diff summary of staged changes
7073
+ * - format_instructions: Instructions for the output format (JSON with title and body)
7074
+ * - additional_context: Optional user-provided context to guide the commit message generation
7075
+ * - commit_history: Optional history of previous commits for context
7076
+ * - branch_name_context: String containing formatted branch name (or empty if disabled)
7077
+ */
7078
+ const template$4 = `Write informative git commit message, in the imperative, based on the diffs & file changes provided in the "Diff Summary" section.
7079
+ Commit Messages must have a short description that is less than 50 characters and a longer detailed summary around 300 characters, the shorter and more concise the better.
7080
+
7081
+ Please follow the guidelines below when writing your commit message:
7082
+
7083
+ - Write concisely using an informal tone
7084
+ - Avoid phrases like "this commit", "this change", "this function", etc. Instead refer to the function, variable, or class by name
7085
+ - Avoid referencing specific files names or long paths in the commit message
7086
+ - DO NOT include any diffs or file changes in the commit message
7087
+ - Wrap variable, class, function, components, and dependency names in back ticks e.g. \`variable\`
7088
+
7089
+ """"""
7090
+ {{summary}}
7091
+ """"""
7092
+
7093
+ {{branch_name_context}}
7094
+
7095
+ {{format_instructions}}
7096
+
7097
+ {{commit_history}}
7098
+
7099
+ {{additional_context}}
7100
+ `;
7101
+ // Define the variables that will be passed to the prompt template
7102
+ const inputVariables$3 = ['summary', 'format_instructions', 'additional_context', 'commit_history', 'branch_name_context'];
7103
+ const COMMIT_PROMPT = new PromptTemplate({
7104
+ template: template$4,
7105
+ inputVariables: inputVariables$3,
7106
+ });
7107
+ const CONVENTIONAL_TEMPLATE = `Generate a commit message that strictly adheres to the Conventional Commits specification. Follow these rules precisely:
7108
+
7109
+ 1. Type Selection:
7110
+ - Choose ONE of these types based on the changes:
7111
+ * feat: A new feature
7112
+ * fix: A bug fix
7113
+ * docs: Documentation only changes
7114
+ * style: Changes that don't affect the code's meaning (white-space, formatting, etc)
7115
+ * refactor: Code changes that neither fix a bug nor add a feature
7116
+ * perf: Code changes that improve performance
7117
+ * test: Adding missing tests or correcting existing tests
7118
+ * build: Changes that affect the build system or external dependencies
7119
+ * ci: Changes to CI configuration files and scripts
7120
+ * chore: Other changes that don't modify src or test files
7121
+ * revert: Reverts a previous commit
7122
+
7123
+ 2. Format Requirements:
7124
+ - Title format: <type>(<optional-scope>): <description>
7125
+ - Title must be 50 characters or less
7126
+ - Description should be in imperative mood (e.g., "add" not "adds/added")
7127
+ - Body MUST be 280 characters or less
7128
+ - Separate body from title with a blank line
7129
+ - Body should explain the motivation for the change and contrast it with previous behavior
7130
+
7131
+ 3. Scope Guidelines:
7132
+ - If the change affects a specific component/area, include it as a scope
7133
+ - Scope should be a noun in parentheses (e.g., (parser), (ui), (config))
7134
+ - Omit scope if the change is broad or affects multiple areas
7135
+
7136
+ Based on the following diff summary, generate a conventional commit message that follows these rules exactly:
7137
+
7138
+ """"""
7139
+ {{summary}}
7140
+ """"""
7141
+
7142
+ {{branch_name_context}}
7143
+
7144
+ {{format_instructions}}
7145
+
7146
+ {{commit_history}}
7147
+
7148
+ {{additional_context}}
7149
+
7150
+ Remember:
7151
+ - Be concise and precise
7152
+ - Focus on WHAT and WHY, not HOW
7153
+ - Use imperative mood in both title and body
7154
+ - Ensure the title alone provides enough context to understand the change`;
7155
+ const conventionalInputVariables = [
7156
+ 'summary',
7157
+ 'additional_context',
7158
+ 'commit_history',
7159
+ 'format_instructions',
7160
+ 'branch_name_context',
7161
+ ];
7162
+ const CONVENTIONAL_COMMIT_PROMPT = new PromptTemplate({
7163
+ template: CONVENTIONAL_TEMPLATE,
7164
+ inputVariables: conventionalInputVariables,
7165
+ });
7166
+
7167
+ /**
7168
+ * Verify template string contains all required input variables
7267
7169
  *
7268
- * const response = await chain.invoke({ adjective: "funny" });
7269
- * ```
7170
+ * @param text template string
7171
+ * @param inputVariables template variables
7172
+ * @throws Error if validation fails
7270
7173
  */
7271
- class LLMChain extends BaseChain {
7272
- static lc_name() {
7273
- return "LLMChain";
7174
+ function validatePromptTemplate(text, inputVariables) {
7175
+ if (!text || text.trim() === '') {
7176
+ throw new Error('Prompt template cannot be empty');
7274
7177
  }
7275
- get inputKeys() {
7276
- return this.prompt.inputVariables;
7178
+ if (!inputVariables || inputVariables.length === 0) {
7179
+ return; // No variables to validate
7277
7180
  }
7278
- get outputKeys() {
7279
- return [this.outputKey];
7181
+ // Extract variables from template using regex to find {variable} patterns
7182
+ // This regex matches {variable_name} with no whitespace inside braces
7183
+ // Excludes JSON-like patterns with quotes, colons, or whitespace
7184
+ const templateVariableRegex = /\{([^}\s:"']+)\}/g;
7185
+ const foundVariables = new Set();
7186
+ let match;
7187
+ while ((match = templateVariableRegex.exec(text)) !== null) {
7188
+ foundVariables.add(match[1]);
7280
7189
  }
7281
- constructor(fields) {
7282
- super(fields);
7283
- Object.defineProperty(this, "lc_serializable", {
7284
- enumerable: true,
7285
- configurable: true,
7286
- writable: true,
7287
- value: true
7288
- });
7289
- Object.defineProperty(this, "prompt", {
7290
- enumerable: true,
7291
- configurable: true,
7292
- writable: true,
7293
- value: void 0
7190
+ // Check if all required variables are present in template
7191
+ const missingVariables = inputVariables.filter(variable => !foundVariables.has(variable));
7192
+ if (missingVariables.length > 0) {
7193
+ throw new Error(`Prompt template is missing required variables: ${missingVariables.map(v => `{${v}}`).join(', ')}. ` +
7194
+ `Found variables: ${Array.from(foundVariables).map(v => `{${v}}`).join(', ') || 'none'}`);
7195
+ }
7196
+ // Warn about unused variables in template (optional check)
7197
+ const unusedVariables = Array.from(foundVariables).filter(variable => !inputVariables.includes(variable));
7198
+ if (unusedVariables.length > 0) {
7199
+ console.warn(`Prompt template contains undefined variables: ${unusedVariables.map(v => `{${v}}`).join(', ')}`);
7200
+ }
7201
+ }
7202
+
7203
+ async function editPrompt(options) {
7204
+ return await editor({
7205
+ message: 'Edit the prompt',
7206
+ default: options.prompt?.length ? options.prompt : COMMIT_PROMPT.template,
7207
+ waitForUseInput: false,
7208
+ postfix: 'Press ENTER to continue',
7209
+ validate: (text) => {
7210
+ try {
7211
+ validatePromptTemplate(text, COMMIT_PROMPT.inputVariables);
7212
+ return true;
7213
+ }
7214
+ catch (error) {
7215
+ return error instanceof Error ? error.message : 'Invalid prompt template';
7216
+ }
7217
+ },
7218
+ });
7219
+ }
7220
+
7221
+ async function editResult(result, options) {
7222
+ if (options.openInEditor) {
7223
+ return await editor({
7224
+ message: 'Edit the commit message',
7225
+ default: result,
7226
+ waitForUseInput: false,
7227
+ validate: (text) => (text ? true : 'Commit message cannot be empty'),
7294
7228
  });
7295
- Object.defineProperty(this, "llm", {
7296
- enumerable: true,
7297
- configurable: true,
7298
- writable: true,
7299
- value: void 0
7229
+ }
7230
+ return result;
7231
+ }
7232
+
7233
+ async function getUserReviewDecision({ label, descriptions, labels, enableEdit = true, enableRetry = true, enableFullRetry = true, enableModifyPrompt = true, selectLabel, }) {
7234
+ const choices = [
7235
+ {
7236
+ name: labels?.approve || '✨ Looks good!',
7237
+ value: 'approve',
7238
+ description: descriptions?.approve || `Continue with the generated ${label}`,
7239
+ },
7240
+ ];
7241
+ if (enableEdit) {
7242
+ choices.push({
7243
+ name: '📝 Edit',
7244
+ value: 'edit',
7245
+ description: descriptions?.edit || `Edit the generated ${label} before proceeding`,
7300
7246
  });
7301
- Object.defineProperty(this, "llmKwargs", {
7302
- enumerable: true,
7303
- configurable: true,
7304
- writable: true,
7305
- value: void 0
7247
+ }
7248
+ if (enableModifyPrompt) {
7249
+ choices.push({
7250
+ name: '🪶 Modify Prompt',
7251
+ value: 'modifyPrompt',
7252
+ description: descriptions?.modifyPrompt || `Modify the prompt template and regenerate the ${label}`,
7306
7253
  });
7307
- Object.defineProperty(this, "outputKey", {
7308
- enumerable: true,
7309
- configurable: true,
7310
- writable: true,
7311
- value: "text"
7254
+ }
7255
+ if (enableRetry) {
7256
+ choices.push({
7257
+ name: labels?.retryMessageOnly || '🔄 Retry',
7258
+ value: 'retryMessageOnly',
7259
+ description: descriptions?.retryMessageOnly ||
7260
+ `Restart the function execution from generating the ${label}`,
7312
7261
  });
7313
- Object.defineProperty(this, "outputParser", {
7314
- enumerable: true,
7315
- configurable: true,
7316
- writable: true,
7317
- value: void 0
7262
+ }
7263
+ if (enableFullRetry) {
7264
+ choices.push({
7265
+ name: labels?.retryFull || '🔄 Retry Full',
7266
+ value: 'retryFull',
7267
+ description: descriptions?.retryFull ||
7268
+ `Restart the function execution from the beginning, regenerating both the summary and ${label}`,
7318
7269
  });
7319
- this.prompt = fields.prompt;
7320
- this.llm = fields.llm;
7321
- this.llmKwargs = fields.llmKwargs;
7322
- this.outputKey = fields.outputKey ?? this.outputKey;
7323
- this.outputParser =
7324
- fields.outputParser ?? new NoOpOutputParser();
7325
- if (this.prompt.outputParser) {
7326
- if (fields.outputParser) {
7327
- throw new Error("Cannot set both outputParser and prompt.outputParser");
7328
- }
7329
- this.outputParser = this.prompt.outputParser;
7330
- }
7331
7270
  }
7332
- getCallKeys() {
7333
- const callKeys = "callKeys" in this.llm ? this.llm.callKeys : [];
7334
- return callKeys;
7271
+ choices.push({
7272
+ name: labels?.cancel || '💣 Cancel',
7273
+ value: 'cancel',
7274
+ description: descriptions?.cancel || `Cancel the ${label}`,
7275
+ });
7276
+ return (await select({
7277
+ message: selectLabel || `Would you like to make any changes to the ${label}?`,
7278
+ choices,
7279
+ }));
7280
+ }
7281
+
7282
+ function logResult(label, result) {
7283
+ console.log(`\n${chalk.bgBlue(chalk.bold(`Proposed ${label}:`))}\n${SEPERATOR}\n${result}\n${SEPERATOR}\n`);
7284
+ }
7285
+
7286
+ async function generateAndReviewLoop({ label, factory, parser, noResult, agent, reviewParser, options, }) {
7287
+ const { logger } = options;
7288
+ let continueLoop = true;
7289
+ let modifyPrompt = false;
7290
+ let context = '';
7291
+ let result = '';
7292
+ const changes = await factory();
7293
+ // if we don't have any changes, bail.
7294
+ if (!changes || !Object.keys(changes).length) {
7295
+ await noResult(options);
7335
7296
  }
7336
- /** @ignore */
7337
- _selectMemoryInputs(values) {
7338
- const valuesForMemory = super._selectMemoryInputs(values);
7339
- const callKeys = this.getCallKeys();
7340
- for (const key of callKeys) {
7341
- if (key in values) {
7342
- delete valuesForMemory[key];
7343
- }
7297
+ while (continueLoop) {
7298
+ if (!context.length) {
7299
+ context = await parser(changes, result, options);
7344
7300
  }
7345
- return valuesForMemory;
7346
- }
7347
- /** @ignore */
7348
- async _getFinalOutput(generations, promptValue, runManager) {
7349
- let finalCompletion;
7350
- if (this.outputParser) {
7351
- finalCompletion = await this.outputParser.parseResultWithPrompt(generations, promptValue, runManager?.getChild());
7301
+ // if we still don't have a context, bail.
7302
+ if (!context.length) {
7303
+ await noResult(options);
7352
7304
  }
7353
- else {
7354
- finalCompletion = generations[0].text;
7305
+ if (modifyPrompt) {
7306
+ options.prompt = await editPrompt(options);
7355
7307
  }
7356
- return finalCompletion;
7357
- }
7358
- /**
7359
- * Run the core logic of this chain and add to output if desired.
7360
- *
7361
- * Wraps _call and handles memory.
7362
- */
7363
- call(values, config) {
7364
- return super.call(values, config);
7365
- }
7366
- /** @ignore */
7367
- async _call(values, runManager) {
7368
- const valuesForPrompt = { ...values };
7369
- const valuesForLLM = {
7370
- ...this.llmKwargs,
7371
- };
7372
- const callKeys = this.getCallKeys();
7373
- for (const key of callKeys) {
7374
- if (key in values) {
7375
- if (valuesForLLM) {
7376
- valuesForLLM[key] =
7377
- values[key];
7378
- delete valuesForPrompt[key];
7379
- }
7308
+ logger.startTimer().startSpinner(`Generating ${label}\n`, {
7309
+ color: 'blue',
7310
+ });
7311
+ try {
7312
+ result = await agent(context, options);
7313
+ if (!result) {
7314
+ logger.stopSpinner('💀 Agent failed to return content.', {
7315
+ mode: 'fail',
7316
+ color: 'red',
7317
+ });
7318
+ process.exit(0);
7380
7319
  }
7381
7320
  }
7382
- const promptValue = await this.prompt.formatPromptValue(valuesForPrompt);
7383
- if ("generatePrompt" in this.llm) {
7384
- const { generations } = await this.llm.generatePrompt([promptValue], valuesForLLM, runManager?.getChild());
7385
- return {
7386
- [this.outputKey]: await this._getFinalOutput(generations[0], promptValue, runManager),
7387
- };
7321
+ catch (error) {
7322
+ // Handle special regeneration request from validation
7323
+ if (error.message === 'REGENERATE_COMMIT_MESSAGE') {
7324
+ logger.stopSpinner('Regenerating commit message...', {
7325
+ mode: 'stop',
7326
+ color: 'blue',
7327
+ });
7328
+ result = '';
7329
+ continue;
7330
+ }
7331
+ // Re-throw other errors
7332
+ throw error;
7388
7333
  }
7389
- const modelWithParser = this.outputParser
7390
- ? this.llm.pipe(this.outputParser)
7391
- : this.llm;
7392
- const response = await modelWithParser.invoke(promptValue, runManager?.getChild());
7393
- return {
7394
- [this.outputKey]: response,
7395
- };
7396
- }
7397
- /**
7398
- * Format prompt with values and pass to LLM
7399
- *
7400
- * @param values - keys to pass to prompt template
7401
- * @param callbackManager - CallbackManager to use
7402
- * @returns Completion from LLM.
7403
- *
7404
- * @example
7405
- * ```ts
7406
- * llm.predict({ adjective: "funny" })
7407
- * ```
7408
- */
7409
- async predict(values, callbackManager) {
7410
- const output = await this.call(values, callbackManager);
7411
- return output[this.outputKey];
7412
- }
7413
- _chainType() {
7414
- return "llm";
7415
- }
7416
- static async deserialize(data) {
7417
- const { llm, prompt } = data;
7418
- if (!llm) {
7419
- throw new Error("LLMChain must have llm");
7334
+ logger
7335
+ .stopSpinner(`Generated ${label}`, {
7336
+ color: 'green',
7337
+ mode: 'succeed',
7338
+ })
7339
+ .stopTimer();
7340
+ if (options?.interactive) {
7341
+ logResult(label, reviewParser ? reviewParser(result, options) : result);
7342
+ const reviewAnswer = await getUserReviewDecision({
7343
+ label,
7344
+ ...(options?.review || {}),
7345
+ });
7346
+ if (reviewAnswer === 'cancel') {
7347
+ process.exit(0);
7348
+ }
7349
+ if (reviewAnswer === 'edit') {
7350
+ options.openInEditor = true;
7351
+ }
7352
+ if (reviewAnswer === 'retryFull') {
7353
+ context = '';
7354
+ result = '';
7355
+ options.prompt = '';
7356
+ continue;
7357
+ }
7358
+ if (reviewAnswer === 'retryMessageOnly') {
7359
+ modifyPrompt = false;
7360
+ result = '';
7361
+ continue;
7362
+ }
7363
+ if (reviewAnswer === 'modifyPrompt') {
7364
+ modifyPrompt = true;
7365
+ result = '';
7366
+ continue;
7367
+ }
7368
+ // Only edit the result in interactive mode if approved
7369
+ result = await editResult(result, options);
7420
7370
  }
7421
- if (!prompt) {
7422
- throw new Error("LLMChain must have prompt");
7371
+ else {
7372
+ // In non-interactive mode, we return the result as is to be output to stdout by the caller.
7373
+ const displayResult = reviewParser ? reviewParser(result, options) : result;
7374
+ // In non-interactive mode, ensure we return the properly formatted result
7375
+ result = displayResult;
7423
7376
  }
7424
- return new LLMChain({
7425
- llm: await BaseLanguageModel.deserialize(llm),
7426
- prompt: await BasePromptTemplate.deserialize(prompt),
7427
- });
7377
+ // if we're here, we're done.
7378
+ continueLoop = false;
7428
7379
  }
7429
- /** @deprecated */
7430
- serialize() {
7431
- const serialize = "serialize" in this.llm ? this.llm.serialize() : undefined;
7432
- return {
7433
- _type: `${this._chainType()}_chain`,
7434
- llm: serialize,
7435
- prompt: this.prompt.serialize(),
7436
- };
7380
+ return result;
7381
+ }
7382
+
7383
+ const logSuccess = () => {
7384
+ console.log(chalk.green(chalk.bold('\nAll set! 🦾🤖')));
7385
+ };
7386
+
7387
+ async function handleResult({ result, mode, interactiveModeCallback }) {
7388
+ switch (mode) {
7389
+ case 'interactive':
7390
+ if (interactiveModeCallback) {
7391
+ await interactiveModeCallback(result);
7392
+ }
7393
+ else {
7394
+ console.warn('No result handler provided for interactive mode.');
7395
+ logSuccess();
7396
+ }
7397
+ break;
7398
+ case 'stdout':
7399
+ default:
7400
+ // Ensure we write the result to stdout in non-interactive mode
7401
+ process.stdout.write(result + '\n', 'utf8');
7402
+ break;
7437
7403
  }
7438
- _getNumTokens(text) {
7439
- return _getLanguageModel(this.llm).getNumTokens(text);
7404
+ if (process.env.NODE_ENV !== 'test') {
7405
+ process.exit(0);
7440
7406
  }
7441
7407
  }
7442
7408
 
7443
- var llm_chain = /*#__PURE__*/Object.freeze({
7444
- __proto__: null,
7445
- LLMChain: LLMChain
7446
- });
7409
+ const template$3 = `Write informative git changelog, in the imperative, based on a series of individual messages.
7447
7410
 
7448
- const NAIVE_FIX_TEMPLATE = `Instructions:
7449
- --------------
7450
- {instructions}
7451
- --------------
7452
- Completion:
7453
- --------------
7454
- {completion}
7455
- --------------
7411
+ - Annotate each change with the git commit hash as reference, including just the first 7 characters
7412
+ - Logically group changes, and if necessary, summarize dependency updates
7413
+ - Include a descriptive title for the changelog, to give a high-level overview of the changes
7414
+ - Depending on the size of the changes, consider breaking the changelog into sections
7415
+ - Avoid generlizations like "various bug fixes" or "improvements" or "enhancements"
7456
7416
 
7457
- Above, the Completion did not satisfy the constraints given in the Instructions.
7458
- Error:
7459
- --------------
7460
- {error}
7461
- --------------
7417
+ {{format_instructions}}
7462
7418
 
7463
- Please try again. Please only respond with an answer that satisfies the constraints laid out in the Instructions:`;
7464
- const NAIVE_FIX_PROMPT =
7465
- /* #__PURE__ */ PromptTemplate.fromTemplate(NAIVE_FIX_TEMPLATE);
7419
+ """{{summary}}"""`;
7420
+ const inputVariables$2 = ['format_instructions', 'summary'];
7421
+ const CHANGELOG_PROMPT = new PromptTemplate({
7422
+ template: template$3,
7423
+ inputVariables: inputVariables$2,
7424
+ });
7466
7425
 
7467
- function isLLMChain(x) {
7468
- return (x.prompt !== undefined && x.llm !== undefined);
7469
- }
7470
- /**
7471
- * Class that extends the BaseOutputParser to handle situations where the
7472
- * initial parsing attempt fails. It contains a retryChain for retrying
7473
- * the parsing process in case of a failure.
7474
- */
7475
- class OutputFixingParser extends BaseOutputParser {
7476
- static lc_name() {
7477
- return "OutputFixingParser";
7478
- }
7479
- /**
7480
- * Static method to create a new instance of OutputFixingParser using a
7481
- * given language model, parser, and optional fields.
7482
- * @param llm The language model to be used.
7483
- * @param parser The parser to be used.
7484
- * @param fields Optional fields which may contain a prompt.
7485
- * @returns A new instance of OutputFixingParser.
7486
- */
7487
- static fromLLM(llm, parser, fields) {
7488
- const prompt = fields?.prompt ?? NAIVE_FIX_PROMPT;
7489
- const chain = new LLMChain({ llm, prompt });
7490
- return new OutputFixingParser({ parser, retryChain: chain });
7426
+ const handler$4 = async (argv, logger) => {
7427
+ const config = loadConfig(argv);
7428
+ const git = getRepo();
7429
+ const key = getApiKeyForModel(config);
7430
+ const { provider, model } = getModelAndProviderFromConfig(config);
7431
+ if (config.service.authentication.type !== 'None' && !key) {
7432
+ logger.log(`No API Key found. 🗝️🚪`, { color: 'red' });
7433
+ process.exit(1);
7491
7434
  }
7492
- constructor({ parser, retryChain, }) {
7493
- super(...arguments);
7494
- Object.defineProperty(this, "lc_namespace", {
7495
- enumerable: true,
7496
- configurable: true,
7497
- writable: true,
7498
- value: ["langchain", "output_parsers", "fix"]
7499
- });
7500
- Object.defineProperty(this, "lc_serializable", {
7501
- enumerable: true,
7502
- configurable: true,
7503
- writable: true,
7504
- value: true
7505
- });
7506
- Object.defineProperty(this, "parser", {
7507
- enumerable: true,
7508
- configurable: true,
7509
- writable: true,
7510
- value: void 0
7511
- });
7512
- Object.defineProperty(this, "retryChain", {
7513
- enumerable: true,
7514
- configurable: true,
7515
- writable: true,
7516
- value: void 0
7517
- });
7518
- this.parser = parser;
7519
- this.retryChain = retryChain;
7435
+ const llm = getLlm(provider, model, config);
7436
+ const INTERACTIVE = isInteractive(config);
7437
+ if (INTERACTIVE) {
7438
+ if (!config.hideCocoBanner) {
7439
+ logger.log(LOGO);
7440
+ }
7520
7441
  }
7521
- /**
7522
- * Method to parse the completion using the parser. If the initial parsing
7523
- * fails, it uses the retryChain to attempt to fix the output and retry
7524
- * the parsing process.
7525
- * @param completion The completion to be parsed.
7526
- * @param callbacks Optional callbacks to be used during parsing.
7527
- * @returns The parsed output.
7528
- */
7529
- async parse(completion, callbacks) {
7530
- try {
7531
- return await this.parser.parse(completion, callbacks);
7442
+ async function factory() {
7443
+ const branchName = await getCurrentBranchName({ git });
7444
+ if (config.sinceLastTag) {
7445
+ logger.verbose(`Generating commit log since the last tag`, { color: 'yellow' });
7446
+ return {
7447
+ branch: branchName,
7448
+ commits: await getChangesSinceLastTag({ git, logger }),
7449
+ };
7532
7450
  }
7533
- catch (e) {
7534
- // eslint-disable-next-line no-instanceof/no-instanceof
7535
- if (e instanceof OutputParserException) {
7536
- const retryInput = {
7537
- instructions: this.parser.getFormatInstructions(),
7538
- completion,
7539
- error: e,
7540
- };
7541
- if (isLLMChain(this.retryChain)) {
7542
- const result = await this.retryChain.call(retryInput, callbacks);
7543
- const newCompletion = result[this.retryChain.outputKey];
7544
- return this.parser.parse(newCompletion, callbacks);
7545
- }
7546
- else {
7547
- const result = await this.retryChain.invoke(retryInput, {
7548
- callbacks,
7549
- });
7550
- return result;
7551
- }
7451
+ if (config.range && config.range.includes(':')) {
7452
+ const [from, to] = config.range.split(':');
7453
+ if (!from || !to) {
7454
+ logger.log(`Invalid range provided. Expected format is <from>:<to>`, { color: 'red' });
7455
+ process.exit(1);
7552
7456
  }
7553
- throw e;
7457
+ return {
7458
+ branch: branchName,
7459
+ commits: await getCommitLogRange(from, to, { git, noMerges: true }),
7460
+ };
7461
+ }
7462
+ if (argv.branch) {
7463
+ logger.verbose(`Generating commit log against branch: ${argv.branch}`, { color: 'yellow' });
7464
+ return {
7465
+ branch: branchName,
7466
+ commits: await getCommitLogAgainstBranch({ git, logger, targetBranch: argv.branch }),
7467
+ };
7554
7468
  }
7469
+ logger.verbose(`No range, branch, or tag option provided. Defaulting to current branch`, {
7470
+ color: 'yellow',
7471
+ });
7472
+ const commits = await getCommitLogCurrentBranch({ git, logger });
7473
+ return {
7474
+ branch: branchName,
7475
+ commits,
7476
+ };
7555
7477
  }
7556
- /**
7557
- * Method to get the format instructions for the parser.
7558
- * @returns The format instructions for the parser.
7559
- */
7560
- getFormatInstructions() {
7561
- return this.parser.getFormatInstructions();
7478
+ async function parser({ branch, commits }) {
7479
+ let result;
7480
+ if (!commits || commits.length === 0) {
7481
+ result = `## ${branch}\n\nNo commits found.`;
7482
+ }
7483
+ else {
7484
+ result = `## ${branch}\n\n${commits.map((commit) => commit.trim()).join('\n\n')}`;
7485
+ }
7486
+ return result;
7562
7487
  }
7563
- }
7488
+ const changelogMsg = await generateAndReviewLoop({
7489
+ label: 'changelog',
7490
+ options: {
7491
+ ...config,
7492
+ prompt: config.prompt || CHANGELOG_PROMPT.template,
7493
+ logger,
7494
+ interactive: INTERACTIVE,
7495
+ review: {
7496
+ enableFullRetry: false,
7497
+ },
7498
+ },
7499
+ factory,
7500
+ parser,
7501
+ agent: async (context, options) => {
7502
+ const parser = createSchemaParser(ChangelogResponseSchema, llm);
7503
+ const prompt = getPrompt({
7504
+ template: options.prompt,
7505
+ variables: CHANGELOG_PROMPT.inputVariables,
7506
+ fallback: CHANGELOG_PROMPT,
7507
+ });
7508
+ const formatInstructions = "Only respond with a valid JSON object, containing two fields: 'title' an escaped string, no more than 65 characters, and 'content' also an escaped string.";
7509
+ const changelog = await executeChain({
7510
+ llm,
7511
+ prompt,
7512
+ variables: {
7513
+ summary: context,
7514
+ format_instructions: formatInstructions,
7515
+ },
7516
+ parser,
7517
+ });
7518
+ const branchName = await getCurrentBranchName({ git });
7519
+ const ticketId = extractTicketIdFromBranchName(branchName);
7520
+ const footer = ticketId ? `\n\nPart of **${ticketId}**` : '';
7521
+ return `${changelog.title}\n\n${changelog.content}${footer}`;
7522
+ },
7523
+ noResult: async () => {
7524
+ if (config.range) {
7525
+ logger.log(`No commits found in the provided range.`, { color: 'red' });
7526
+ process.exit(0);
7527
+ }
7528
+ logger.log(`No commits found in the current branch.`, { color: 'red' });
7529
+ process.exit(0);
7530
+ },
7531
+ });
7532
+ const MODE = (INTERACTIVE && 'interactive') || (config.commit && 'interactive') || config?.mode || 'stdout';
7533
+ handleResult({
7534
+ result: changelogMsg,
7535
+ interactiveModeCallback: async () => {
7536
+ logSuccess();
7537
+ },
7538
+ mode: MODE,
7539
+ });
7540
+ };
7541
+
7542
+ var changelog = {
7543
+ command: command$4,
7544
+ desc: 'Generate a changelog from current or target branch, provided commit range, or since the last tag.',
7545
+ builder: builder$4,
7546
+ handler: commandExecutor(handler$4),
7547
+ options: options$4,
7548
+ };
7564
7549
 
7550
+ const conventionalTypeRegex = /^(feat|fix|docs|style|refactor|perf|test|build|ci|chore|revert)(\(.+\))?:/;
7551
+ // Regular commit message schema with basic validation
7552
+ const CommitMessageResponseSchema = objectType({
7553
+ title: stringType(),
7554
+ body: stringType(),
7555
+ });
7556
+ // Conventional commit message schema with strict formatting rules
7557
+ const ConventionalCommitMessageResponseSchema = objectType({
7558
+ title: stringType()
7559
+ .max(50, "Title must be 50 characters or less")
7560
+ .refine((title) => conventionalTypeRegex.test(title), "Title must follow Conventional Commits format (e.g., 'feat: add new feature' or 'fix(scope): fix bug')"),
7561
+ body: stringType()
7562
+ // .max(280, "Body must be 280 characters or less"),
7563
+ });
7564
+ const command$3 = 'commit';
7565
7565
  /**
7566
- * Creates a parser with built-in retry logic for schema-based generation
7567
- * @param schema - Zod schema for the expected output structure
7568
- * @param llm - LLM instance for retry attempts
7569
- * @param options - Configuration options for retry behavior
7570
- * @returns OutputFixingParser configured with retry logic
7571
- * @throws LangChainExecutionError if parser creation fails
7566
+ * Command line options via yargs
7572
7567
  */
7573
- function createSchemaParser(schema, llm, options = {}) {
7574
- validateRequired(schema, 'schema', 'createSchemaParser');
7575
- validateRequired(llm, 'llm', 'createSchemaParser');
7576
- validateRequired(options, 'options', 'createSchemaParser');
7577
- // Validate schema is actually a Zod schema
7578
- if (typeof schema.parse !== 'function') {
7579
- throw new LangChainExecutionError('createSchemaParser: Schema must be a valid Zod schema with a parse method', { schemaType: typeof schema, hasParseMethod: typeof schema.parse });
7580
- }
7581
- // Validate options structure
7582
- if (typeof options !== 'object' || Array.isArray(options)) {
7583
- throw new LangChainExecutionError('createSchemaParser: Options must be a non-array object', { options, type: typeof options, isArray: Array.isArray(options) });
7584
- }
7585
- const { retryTemplate } = options;
7586
- // Validate retryTemplate if provided
7587
- if (retryTemplate !== undefined && typeof retryTemplate !== 'string') {
7588
- throw new LangChainExecutionError('createSchemaParser: retryTemplate must be a string when provided', { retryTemplate, type: typeof retryTemplate });
7589
- }
7590
- try {
7591
- const baseParser = new StructuredOutputParser(schema);
7592
- const defaultRetryTemplate = `The following text failed to parse as valid JSON. Please convert it into a valid JSON object that matches the required schema.
7593
-
7594
- ## Text to fix:
7595
- {completion}
7596
-
7597
- ## Instructions:
7598
- {instructions}
7599
-
7600
- You must return ONLY valid JSON that matches the schema exactly. Do not include any additional text, explanations, or markdown formatting:`;
7601
- const retryPromptTemplate = new PromptTemplate({
7602
- template: retryTemplate || defaultRetryTemplate,
7603
- inputVariables: ['completion', 'instructions'],
7604
- });
7605
- const retryChain = retryPromptTemplate.pipe(llm).pipe(baseParser);
7606
- return new OutputFixingParser({
7607
- parser: baseParser,
7608
- retryChain: retryChain,
7609
- });
7610
- }
7611
- catch (error) {
7612
- handleLangChainError(error, 'createSchemaParser: Failed to create schema parser', {
7613
- schemaName: schema.constructor.name,
7614
- llmType: llm.constructor.name,
7615
- hasRetryTemplate: !!retryTemplate
7616
- });
7617
- }
7618
- }
7568
+ const options$3 = {
7569
+ i: {
7570
+ alias: 'interactive',
7571
+ description: 'Toggle interactive mode',
7572
+ type: 'boolean',
7573
+ },
7574
+ ignoredFiles: {
7575
+ description: 'Ignored files',
7576
+ type: 'array',
7577
+ },
7578
+ ignoredExtensions: {
7579
+ description: 'Ignored extensions',
7580
+ type: 'array',
7581
+ },
7582
+ append: {
7583
+ description: 'Add content to the end of the generated commit message',
7584
+ type: 'string',
7585
+ },
7586
+ appendTicket: {
7587
+ description: 'Append ticket ID from branch name to the commit message',
7588
+ type: 'boolean',
7589
+ alias: 't',
7590
+ },
7591
+ additional: {
7592
+ description: 'Add extra contextual information to the prompt',
7593
+ type: 'string',
7594
+ alias: 'a',
7595
+ },
7596
+ withPreviousCommits: {
7597
+ description: 'Include previous commits as context (specify number of commits, 0 for none)',
7598
+ type: 'number',
7599
+ default: 0,
7600
+ alias: 'p',
7601
+ },
7602
+ conventional: {
7603
+ description: 'Generate commit message in Conventional Commits format',
7604
+ type: 'boolean',
7605
+ default: false,
7606
+ alias: 'c',
7607
+ },
7608
+ includeBranchName: {
7609
+ description: 'Include the current branch name in the commit prompt for context',
7610
+ type: 'boolean',
7611
+ default: true,
7612
+ },
7613
+ noDiff: {
7614
+ description: 'Only pass basic "git status" result instead of providing entire diff',
7615
+ type: 'boolean',
7616
+ default: false,
7617
+ },
7618
+ };
7619
+ const builder$3 = (yargs) => {
7620
+ return yargs.options(options$3).usage(getCommandUsageHeader(command$3));
7621
+ };
7619
7622
 
7620
7623
  /**
7621
7624
  * High-level function that combines chain execution with schema-based parsing
@@ -7901,7 +7904,38 @@ async function parseDefaultFileDiff(nodeFile, commit = '--staged', git) {
7901
7904
  throw new Error(`Error reading untracked file: ${error?.message || 'Unknown error'}`);
7902
7905
  }
7903
7906
  }
7904
- return await git.diff([commit, nodeFile.filePath]);
7907
+ // For branch comparisons, handle files that may not exist in the base branch
7908
+ try {
7909
+ return await git.diff([commit, nodeFile.filePath]);
7910
+ }
7911
+ catch (error) {
7912
+ const errorMessage = error instanceof Error ? error.message : String(error);
7913
+ // If the error indicates the file doesn't exist in the base branch, handle it gracefully
7914
+ if (errorMessage.includes('unknown revision or path not in the working tree') ||
7915
+ errorMessage.includes('ambiguous argument')) {
7916
+ // This is likely a newly added file - show the entire file content as an addition
7917
+ if (nodeFile.status === 'added') {
7918
+ try {
7919
+ const fileContent = await promises.readFile(nodeFile.filePath, 'utf-8');
7920
+ return `+++ ${nodeFile.filePath}\n${fileContent.split('\n').map(line => `+${line}`).join('\n')}`;
7921
+ }
7922
+ catch (fsError) {
7923
+ return `Error reading added file ${nodeFile.filePath}: ${fsError instanceof Error ? fsError.message : String(fsError)}`;
7924
+ }
7925
+ }
7926
+ // For other cases, try to get the file content from the current HEAD
7927
+ try {
7928
+ const fileContent = await git.show([`HEAD:${nodeFile.filePath}`]);
7929
+ return `File content from current version:\n${fileContent}`;
7930
+ }
7931
+ catch (showError) {
7932
+ // If all else fails, provide a meaningful error message
7933
+ return `Unable to retrieve diff for ${nodeFile.filePath}. File may be newly added or renamed.`;
7934
+ }
7935
+ }
7936
+ // Re-throw other types of errors
7937
+ throw error;
7938
+ }
7905
7939
  }
7906
7940
  /**
7907
7941
  * Parses the diff for a renamed file.
@@ -11756,6 +11790,10 @@ const options$1 = {
11756
11790
  type: 'boolean',
11757
11791
  description: 'Recap for last tag',
11758
11792
  },
11793
+ currentBranch: {
11794
+ type: 'boolean',
11795
+ description: 'Recap for the current branch',
11796
+ },
11759
11797
  i: {
11760
11798
  type: 'boolean',
11761
11799
  alias: 'interactive',
@@ -11771,8 +11809,89 @@ const getChangesByTimestamp = async ({ since, git }) => {
11771
11809
  return formatCommitLog(commitLog);
11772
11810
  };
11773
11811
 
11812
+ /**
11813
+ * Retrieves the diff between the current branch and a specified target branch.
11814
+ *
11815
+ * @param {Object} options - The options for retrieving the diff.
11816
+ * @param {SimpleGit} options.git - The SimpleGit instance.
11817
+ * @param {Logger} options.logger - The logger for logging messages.
11818
+ * @param {string} options.baseBranch - The base branch to compare against.
11819
+ * @param {string} options.headBranch - The head branch to compare.
11820
+ * @param {string[]} options.ignoredFiles - Array of specific files to ignore.
11821
+ * @param {string[]} options.ignoredExtensions - Array of file extensions to ignore.
11822
+ * @returns {Promise<GetChangesResult>} The diff between the current branch and the target branch.
11823
+ */
11824
+ async function getDiffForBranch({ git, logger, baseBranch, headBranch, options, }) {
11825
+ try {
11826
+ logger?.verbose(`Getting diff for branches: baseBranch="${baseBranch}", headBranch="${headBranch}"`, {
11827
+ color: 'blue',
11828
+ });
11829
+ // Validate branch names
11830
+ if (!baseBranch || !headBranch) {
11831
+ throw new Error(`Invalid branch names: baseBranch="${baseBranch}", headBranch="${headBranch}"`);
11832
+ }
11833
+ const { ignoredFiles = [], ignoredExtensions = [] } = options || {};
11834
+ // Prepare ignore patterns
11835
+ const ignorePatterns = [
11836
+ ...ignoredFiles.map((file) => `:!${file}`),
11837
+ ...ignoredExtensions.map((ext) => `:!*${ext}`),
11838
+ ];
11839
+ // Construct the diff command
11840
+ const diffArgs = [`${baseBranch}..${headBranch}`];
11841
+ if (ignorePatterns.length > 0) {
11842
+ diffArgs.push('--');
11843
+ diffArgs.push(...ignorePatterns);
11844
+ }
11845
+ logger?.verbose(`Running git diff with args: ${diffArgs.join(' ')}`, {
11846
+ color: 'blue',
11847
+ });
11848
+ // Get the diff
11849
+ const diff = await git.diff(diffArgs);
11850
+ logger?.verbose(`Generated diff between "${headBranch}" and "${baseBranch}"`, {
11851
+ color: 'blue',
11852
+ });
11853
+ const changes = diff.split('diff --git').slice(1).map((fileDiff) => {
11854
+ const lines = fileDiff.split('\n');
11855
+ const filePathLine = lines[0];
11856
+ const filePath = filePathLine.split('b/')[1]?.split(' ')[0];
11857
+ const oldFilePath = filePathLine.split('a/')[1]?.split(' ')[0];
11858
+ // Determine status based on diff headers
11859
+ let status = 'modified';
11860
+ if (fileDiff.includes('new file mode')) {
11861
+ status = 'added';
11862
+ }
11863
+ else if (fileDiff.includes('deleted file mode')) {
11864
+ status = 'deleted';
11865
+ }
11866
+ else if (fileDiff.includes('rename from')) {
11867
+ status = 'renamed';
11868
+ }
11869
+ return {
11870
+ filePath: filePath || '',
11871
+ oldFilePath: oldFilePath || '',
11872
+ status,
11873
+ summary: getSummaryText({ path: filePath || '', index: '', working_dir: '' }, { filePath: filePath || '', status }),
11874
+ };
11875
+ });
11876
+ return {
11877
+ staged: changes,
11878
+ unstaged: [],
11879
+ untracked: [],
11880
+ };
11881
+ }
11882
+ catch (error) {
11883
+ const errorMessage = error instanceof Error ? error.message : String(error);
11884
+ console.error('Error in getDiffForBranch:', error);
11885
+ logger?.log(`Encountered an error getting diff between branches: ${errorMessage}`, { color: 'red' });
11886
+ logger?.log(`Branch details: baseBranch="${baseBranch}", headBranch="${headBranch}"`, { color: 'red' });
11887
+ // Re-throw the error so the caller can handle it appropriately
11888
+ throw error;
11889
+ }
11890
+ }
11891
+
11774
11892
  async function noResult$1({ logger }) {
11775
11893
  logger.log('No repo changes detected. 👀', { color: 'blue' });
11894
+ throw new Error('NO_CHANGES_DETECTED');
11776
11895
  }
11777
11896
 
11778
11897
  const template$1 = `Following the formatting instructions, summarize the following changes in the underlying git repository/branch.
@@ -11820,7 +11939,9 @@ const handler$1 = async (argv, logger) => {
11820
11939
  ? 'yesterday'
11821
11940
  : lastWeek
11822
11941
  ? 'last-week'
11823
- : 'current';
11942
+ : argv.currentBranch || config.currentBranch
11943
+ ? 'currentBranch'
11944
+ : 'current';
11824
11945
  logger.log(`Generating recap for timeframe: ${timeframe}`);
11825
11946
  async function factory() {
11826
11947
  switch (timeframe) {
@@ -11861,6 +11982,25 @@ const handler$1 = async (argv, logger) => {
11861
11982
  case 'last-tag':
11862
11983
  const tags = await getChangesSinceLastTag({ git });
11863
11984
  return tags;
11985
+ case 'currentBranch':
11986
+ const currentBranch = await getCurrentBranchName({ git });
11987
+ const baseBranch = config.defaultBranch || 'main';
11988
+ logger.log(`Recapping changes on branch '${currentBranch}' compared to '${baseBranch}'`);
11989
+ const changes = await getDiffForBranch({
11990
+ git,
11991
+ baseBranch,
11992
+ headBranch: currentBranch,
11993
+ options: {
11994
+ ignoredFiles: config.ignoredFiles || undefined,
11995
+ ignoredExtensions: config.ignoredExtensions || undefined,
11996
+ },
11997
+ });
11998
+ const branchChanges = await fileChangeParser({
11999
+ changes: changes.staged,
12000
+ commit: baseBranch,
12001
+ options: { tokenizer, git, llm, logger },
12002
+ });
12003
+ return [branchChanges];
11864
12004
  default:
11865
12005
  logger.log(`Invalid timeframe: ${timeframe}`, { color: 'red' });
11866
12006
  return [];
@@ -11901,7 +12041,7 @@ const handler$1 = async (argv, logger) => {
11901
12041
  fallback: RECAP_PROMPT,
11902
12042
  });
11903
12043
  try {
11904
- const parser = new StructuredOutputParser(RecapLlmResponseSchema);
12044
+ const parser = createSchemaParser(RecapLlmResponseSchema, llm);
11905
12045
  const response = await executeChain({
11906
12046
  llm,
11907
12047
  prompt,
@@ -11933,11 +12073,13 @@ ${errorMessage}
11933
12073
  },
11934
12074
  noResult: async () => {
11935
12075
  await noResult$1({ git, logger });
11936
- process.exit(0);
12076
+ if (process.env.NODE_ENV !== 'test') {
12077
+ process.exit(0);
12078
+ }
11937
12079
  },
11938
12080
  });
11939
12081
  // Handle the result based on the mode (interactive or stdout)
11940
- const MODE = (INTERACTIVE && 'interactive') || (config.recap && 'interactive') || config?.mode || 'stdout'; // Default to stdout
12082
+ const MODE = (INTERACTIVE && 'interactive') ?? (config.recap && 'interactive') ?? config?.mode ?? 'stdout'; // Default to stdout
11941
12083
  handleResult({
11942
12084
  result: recapResult,
11943
12085
  interactiveModeCallback: async () => {
@@ -11995,46 +12137,6 @@ const builder = (yargs) => {
11995
12137
  return yargs.options(options).usage(getCommandUsageHeader(command));
11996
12138
  };
11997
12139
 
11998
- /**
11999
- * Retrieves the diff between the current branch and a specified target branch.
12000
- *
12001
- * @param {Object} options - The options for retrieving the diff.
12002
- * @param {SimpleGit} options.git - The SimpleGit instance.
12003
- * @param {Logger} options.logger - The logger for logging messages.
12004
- * @param {string} options.targetBranch - The target branch to compare against.
12005
- * @param {string[]} options.ignoredFiles - Array of specific files to ignore.
12006
- * @param {string[]} options.ignoredExtensions - Array of file extensions to ignore.
12007
- * @returns {Promise<string>} The diff between the current branch and the target branch.
12008
- */
12009
- async function getDiffForBranch({ git, logger, targetBranch, ignoredFiles = [], ignoredExtensions = [], }) {
12010
- try {
12011
- // Get the current branch name
12012
- const currentBranch = await getCurrentBranchName({ git });
12013
- // Prepare ignore patterns
12014
- const ignorePatterns = [
12015
- ...ignoredFiles.map((file) => `:!${file}`),
12016
- ...ignoredExtensions.map((ext) => `:!*${ext}`),
12017
- ];
12018
- // Construct the diff command
12019
- const diffArgs = [`${targetBranch}..${currentBranch}`];
12020
- if (ignorePatterns.length > 0) {
12021
- diffArgs.push('--');
12022
- diffArgs.push(...ignorePatterns);
12023
- }
12024
- // Get the diff
12025
- const diff = await git.diff(diffArgs);
12026
- logger?.verbose(`Generated diff between "${currentBranch}" and "${targetBranch}"`, {
12027
- color: 'blue',
12028
- });
12029
- return diff;
12030
- }
12031
- catch (error) {
12032
- console.error('Error in getDiffForBranch:', error);
12033
- logger?.log('Encountered an error getting diff between branches', { color: 'red' });
12034
- return '';
12035
- }
12036
- }
12037
-
12038
12140
  /******************************************************************************
12039
12141
  Copyright (c) Microsoft Corporation.
12040
12142
 
@@ -14251,14 +14353,23 @@ const handler = async (argv, logger) => {
14251
14353
  async function factory() {
14252
14354
  if (argv.branch) {
14253
14355
  logger.verbose(`Generating diff for branch: ${argv.branch}`, { color: 'yellow' });
14356
+ const currentBranch = await getCurrentBranchName({ git });
14254
14357
  const diff = await getDiffForBranch({
14255
14358
  git,
14256
14359
  logger,
14257
- targetBranch: argv.branch,
14258
- ignoredFiles: config.ignoredFiles || [],
14259
- ignoredExtensions: config.ignoredExtensions || [],
14360
+ baseBranch: argv.branch,
14361
+ headBranch: currentBranch,
14362
+ options: {
14363
+ ignoredFiles: config.ignoredFiles || [],
14364
+ ignoredExtensions: config.ignoredExtensions || [],
14365
+ },
14366
+ });
14367
+ const branchChanges = await fileChangeParser({
14368
+ changes: diff.staged,
14369
+ commit: `--branch-diff-${argv.branch}`,
14370
+ options: { tokenizer, git, llm, logger },
14260
14371
  });
14261
- return [diff];
14372
+ return [branchChanges];
14262
14373
  }
14263
14374
  else {
14264
14375
  const { staged, unstaged, untracked } = await getChanges({
@@ -14322,7 +14433,7 @@ const handler = async (argv, logger) => {
14322
14433
  factory,
14323
14434
  parser,
14324
14435
  agent: async (context, options) => {
14325
- const parser = new StructuredOutputParser(ReviewFeedbackItemArraySchema);
14436
+ const parser = createSchemaParser(ReviewFeedbackItemArraySchema, llm);
14326
14437
  const formatInstructions = "Respond with a valid JSON object, containing four fields:'title' a string, 'summary' a short summary of the problem (include line number if big file), 'severity' a numeric enum up to ten, 'category' an enum string, and 'filePath' a relative filepath to file as string.";
14327
14438
  const prompt = getPrompt({
14328
14439
  template: options.prompt,