aicommit2 2.4.6 → 2.4.8
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.
- package/README.md +29 -20
- package/dist/cli.mjs +60 -66
- package/package.json +2 -2
package/dist/cli.mjs
CHANGED
|
@@ -1,21 +1,21 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{command as oe,cli as Yo}from"cleye";import{createRequire as Vo}from"module";import B from"fs";import Ee from"os";import S from"path";import{Buffer as qo}from"node:buffer";import ae from"node:path";import dr,{ChildProcess as Xo,exec as Qo}from"node:child_process";import se from"node:process";import Zo,{execSync as _e}from"child_process";import{fileURLToPath as mr}from"node:url";import es,{constants as fr}from"node:os";import pr from"assert";import hr from"events";import{createWriteStream as ts,createReadStream as rs}from"node:fs";import os from"buffer";import ut from"stream";import gr from"util";import{debuglog as ss,promisify as ns}from"node:util";import Ge from"inquirer";import P from"chalk";import{of as dt,concatMap as L,from as M,map as I,catchError as R,mergeMap as yr,BehaviorSubject as wr,ReplaySubject as is,Subscription as mt,lastValueFrom as vr,filter as br,toArray as Cr,Subject as ft}from"rxjs";import as from"@anthropic-ai/sdk";import{fromPromise as j}from"rxjs/internal/observable/innerFrom";import{xxh64 as Pr}from"@pacote/xxhash";import U from"winston";import O from"fs/promises";import"winston-daily-rotate-file";import cs from"axios";import{CohereClient as ls}from"cohere-ai";import $r from"openai";import{GoogleGenerativeAI as us,HarmCategory as Be,HarmBlockThreshold as He}from"@google/generative-ai";import ds from"http";import ms from"https";import fs from"net";import ps from"tls";import hs,{fileURLToPath as gs,pathToFileURL as ys}from"url";import Er from"tty";import ws from"groq-sdk";import{Ollama as vs}from"ollama";import{fetch as bs,Agent as Cs}from"undici";import Ue from"readline";import Ps from"figlet";import kr from"ora";import $s from"inquirer-reactive-list-prompt";import{readdir as xr,stat as Es,rm as ks}from"node:fs/promises";import xs from"chokidar";import{takeUntil as pt,finalize as Sr}from"rxjs/operators";var Ss="aicommit2",Ar="2.4.6",As="A Reactive CLI that generates commit messages for Git and Jujutsu with various AI",Ms=["cli","ai","git","jujutsu","jj","vcs","version-control","commit","git-commit","jujutsu-commit","command-line","commandline","aipick","aicommit","aicommits","aicommit2","openai","huggingface","anthropic","claude","claude3","gemini","gemini-pro","generative-ai","mistral","ollama","llama3","llama3.2","llama3.3","gemma","llm","chatgpt","cohere","groq","codestral","perplexity","deepseek","deepseek-r1","pre-commit"],Is="MIT",Rs="tak-bro/aicommit2",Os="Hyungtak Jin(@tak-bro)",Ls="module",js=["dist"],Ds={aicommit2:"./dist/cli.mjs",aic2:"./dist/cli.mjs"},Fs={prepare:"simple-git-hooks",build:"pkgroll --minify",lint:"eslint --cache .","type-check":"tsc",test:"tsx tests",prepack:"pnpm build && clean-pkg-json",prettier:"prettier"},Ts={"@anthropic-ai/sdk":"^0.39.0","@dqbd/tiktoken":"^1.0.21","@google/generative-ai":"^0.24.1","@inquirer/prompts":"^3.3.2","@pacote/xxhash":"^0.3.2","@types/winston":"^2.4.4",axios:"^1.9.0",chalk:"^5.4.1",chokidar:"^4.0.3",cleye:"^1.3.4","cohere-ai":"^7.17.1","copy-paste":"^1.5.3",figlet:"^1.8.1","formdata-node":"^6.0.3","groq-sdk":"^0.7.0",inquirer:"9.2.8","inquirer-reactive-list-prompt":"^1.0.15",ollama:"^0.5.15",openai:"^5.0.1",ora:"^8.2.0",readline:"^1.3.0",rxjs:"^7.8.2",undici:"^7.10.0",uuid:"^9.0.1",winston:"^3.17.0","winston-daily-rotate-file":"^5.0.0"},Ns={"@pvtnbr/eslint-config":"^0.33.0","@semantic-release/changelog":"^6.0.3","@semantic-release/commit-analyzer":"^12.0.0","@semantic-release/git":"^10.0.1","@semantic-release/github":"^10.3.5","@semantic-release/npm":"^12.0.1","@semantic-release/release-notes-generator":"^13.0.0","@types/figlet":"^1.7.0","@types/ini":"^1.3.34","@types/inquirer":"^9.0.8","@types/node":"^18.19.103","@types/uuid":"^9.0.8","@typescript-eslint/eslint-plugin":"^6.21.0","@typescript-eslint/parser":"^6.21.0","clean-pkg-json":"^1.3.0","conventional-changelog-conventionalcommits":"^7.0.2","conventional-commits-parser":"^5.0.0",eslint:"^8.57.1","eslint-config-prettier":"^8.10.0","eslint-plugin-eslint-comments":"^3.2.0","eslint-plugin-import":"^2.31.0","eslint-plugin-jsonc":"^2.20.1","eslint-plugin-no-use-extend-native":"^0.5.0","eslint-plugin-promise":"^6.6.0","eslint-plugin-unicorn":"^49.0.0","eslint-plugin-unused-imports":"^3.2.0",execa:"^7.2.0","fs-fixture":"^1.2.0","https-proxy-agent":"^5.0.1",ini:"^3.0.1","lint-staged":"^13.3.0",manten:"^0.7.0",pkgroll:"^1.11.1",prettier:"^3.5.3","semantic-release":"^23.1.1","simple-git-hooks":"^2.13.0",tsx:"^3.14.0",typescript:"^4.9.5","undici-types":"^7.10.0"},_s={extends:["@pvtnbr","prettier"],rules:{"unicorn/no-process-exit":"off"},overrides:[{files:"./src/commands/prepare-commit-msg-hook.ts",rules:{"unicorn/prevent-abbreviations":"off"}}]},Gs={branches:["main"],plugins:[["@semantic-release/commit-analyzer",{preset:"conventionalcommits",releaseRules:[{type:"refactor",release:"patch"},{type:"chore",release:"patch"},{type:"feat",release:"patch"},{scope:"major",release:"major"},{scope:"minor",release:"minor"},{scope:"patch",release:"patch"}]}],"@semantic-release/release-notes-generator",["@semantic-release/changelog",{changelogFile:"CHANGELOG.md"}],"@semantic-release/github",["@semantic-release/git",{assets:["CHANGELOG.md"],message:"chore(release): ${nextRelease.version} [skip ci]\n\n${nextRelease.notes}"}],"@semantic-release/npm"]},Bs={name:Ss,version:Ar,description:As,keywords:Ms,license:Is,repository:Rs,author:Os,type:Ls,files:js,bin:Ds,scripts:Fs,"simple-git-hooks":{"pre-commit":"pnpm lint-staged"},"lint-staged":{"*.ts":["prettier --config ./.prettierrc --write","eslint --fix"]},dependencies:Ts,devDependencies:Ns,eslintConfig:_s,release:Gs},Hs=Vo(import.meta.url),G=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function de(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var me={exports:{}},ht,Mr;function Us(){if(Mr)return ht;Mr=1,ht=o,o.sync=s;var t=B;function e(n,i){var c=i.pathExt!==void 0?i.pathExt:process.env.PATHEXT;if(!c||(c=c.split(";"),c.indexOf("")!==-1))return!0;for(var a=0;a<c.length;a++){var m=c[a].toLowerCase();if(m&&n.substr(-m.length).toLowerCase()===m)return!0}return!1}function r(n,i,c){return!n.isSymbolicLink()&&!n.isFile()?!1:e(i,c)}function o(n,i,c){t.stat(n,function(a,m){c(a,a?!1:r(m,n,i))})}function s(n,i){return r(t.statSync(n),n,i)}return ht}var gt,Ir;function zs(){if(Ir)return gt;Ir=1,gt=e,e.sync=r;var t=B;function e(n,i,c){t.stat(n,function(a,m){c(a,a?!1:o(m,i))})}function r(n,i){return o(t.statSync(n),i)}function o(n,i){return n.isFile()&&s(n,i)}function s(n,i){var c=n.mode,a=n.uid,m=n.gid,d=i.uid!==void 0?i.uid:process.getuid&&process.getuid(),l=i.gid!==void 0?i.gid:process.getgid&&process.getgid(),p=parseInt("100",8),u=parseInt("010",8),h=parseInt("001",8),g=p|u,y=c&h||c&u&&m===l||c&p&&a===d||c&g&&d===0;return y}return gt}var ze;process.platform==="win32"||G.TESTING_WINDOWS?ze=Us():ze=zs();var Js=yt;yt.sync=Ks;function yt(t,e,r){if(typeof e=="function"&&(r=e,e={}),!r){if(typeof Promise!="function")throw new TypeError("callback not provided");return new Promise(function(o,s){yt(t,e||{},function(n,i){n?s(n):o(i)})})}ze(t,e||{},function(o,s){o&&(o.code==="EACCES"||e&&e.ignoreErrors)&&(o=null,s=!1),r(o,s)})}function Ks(t,e){try{return ze.sync(t,e||{})}catch(r){if(e&&e.ignoreErrors||r.code==="EACCES")return!1;throw r}}const fe=process.platform==="win32"||process.env.OSTYPE==="cygwin"||process.env.OSTYPE==="msys",Rr=S,Ws=fe?";":":",Or=Js,Lr=t=>Object.assign(new Error(`not found: ${t}`),{code:"ENOENT"}),jr=(t,e)=>{const r=e.colon||Ws,o=t.match(/\//)||fe&&t.match(/\\/)?[""]:[...fe?[process.cwd()]:[],...(e.path||process.env.PATH||"").split(r)],s=fe?e.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",n=fe?s.split(r):[""];return fe&&t.indexOf(".")!==-1&&n[0]!==""&&n.unshift(""),{pathEnv:o,pathExt:n,pathExtExe:s}},Dr=(t,e,r)=>{typeof e=="function"&&(r=e,e={}),e||(e={});const{pathEnv:o,pathExt:s,pathExtExe:n}=jr(t,e),i=[],c=m=>new Promise((d,l)=>{if(m===o.length)return e.all&&i.length?d(i):l(Lr(t));const p=o[m],u=/^".*"$/.test(p)?p.slice(1,-1):p,h=Rr.join(u,t),g=!u&&/^\.[\\\/]/.test(t)?t.slice(0,2)+h:h;d(a(g,m,0))}),a=(m,d,l)=>new Promise((p,u)=>{if(l===s.length)return p(c(d+1));const h=s[l];Or(m+h,{pathExt:n},(g,y)=>{if(!g&&y)if(e.all)i.push(m+h);else return p(m+h);return p(a(m,d,l+1))})});return r?c(0).then(m=>r(null,m),r):c(0)},Ys=(t,e)=>{e=e||{};const{pathEnv:r,pathExt:o,pathExtExe:s}=jr(t,e),n=[];for(let i=0;i<r.length;i++){const c=r[i],a=/^".*"$/.test(c)?c.slice(1,-1):c,m=Rr.join(a,t),d=!a&&/^\.[\\\/]/.test(t)?t.slice(0,2)+m:m;for(let l=0;l<o.length;l++){const p=d+o[l];try{if(Or.sync(p,{pathExt:s}))if(e.all)n.push(p);else return p}catch{}}}if(e.all&&n.length)return n;if(e.nothrow)return null;throw Lr(t)};var Vs=Dr;Dr.sync=Ys;var wt={exports:{}};const Fr=(t={})=>{const e=t.env||process.env;return(t.platform||process.platform)!=="win32"?"PATH":Object.keys(e).reverse().find(o=>o.toUpperCase()==="PATH")||"Path"};wt.exports=Fr,wt.exports.default=Fr;var qs=wt.exports;const Tr=S,Xs=Vs,Qs=qs;function Nr(t,e){const r=t.options.env||process.env,o=process.cwd(),s=t.options.cwd!=null,n=s&&process.chdir!==void 0&&!process.chdir.disabled;if(n)try{process.chdir(t.options.cwd)}catch{}let i;try{i=Xs.sync(t.command,{path:r[Qs({env:r})],pathExt:e?Tr.delimiter:void 0})}catch{}finally{n&&process.chdir(o)}return i&&(i=Tr.resolve(s?t.options.cwd:"",i)),i}function Zs(t){return Nr(t)||Nr(t,!0)}var en=Zs,vt={};const bt=/([()\][%!^"`<>&|;, *?])/g;function tn(t){return t=t.replace(bt,"^$1"),t}function rn(t,e){return t=`${t}`,t=t.replace(/(?=(\\+?)?)\1"/g,'$1$1\\"'),t=t.replace(/(?=(\\+?)?)\1$/,"$1$1"),t=`"${t}"`,t=t.replace(bt,"^$1"),e&&(t=t.replace(bt,"^$1")),t}vt.command=tn,vt.argument=rn;var on=/^#!(.*)/;const sn=on;var nn=(t="")=>{const e=t.match(sn);if(!e)return null;const[r,o]=e[0].replace(/#! ?/,"").split(" "),s=r.split("/").pop();return s==="env"?o:o?`${s} ${o}`:s};const Ct=B,an=nn;function cn(t){const r=Buffer.alloc(150);let o;try{o=Ct.openSync(t,"r"),Ct.readSync(o,r,0,150,0),Ct.closeSync(o)}catch{}return an(r.toString())}var ln=cn;const un=S,_r=en,Gr=vt,dn=ln,mn=process.platform==="win32",fn=/\.(?:com|exe)$/i,pn=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function hn(t){t.file=_r(t);const e=t.file&&dn(t.file);return e?(t.args.unshift(t.file),t.command=e,_r(t)):t.file}function gn(t){if(!mn)return t;const e=hn(t),r=!fn.test(e);if(t.options.forceShell||r){const o=pn.test(e);t.command=un.normalize(t.command),t.command=Gr.command(t.command),t.args=t.args.map(n=>Gr.argument(n,o));const s=[t.command].concat(t.args).join(" ");t.args=["/d","/s","/c",`"${s}"`],t.command=process.env.comspec||"cmd.exe",t.options.windowsVerbatimArguments=!0}return t}function yn(t,e,r){e&&!Array.isArray(e)&&(r=e,e=null),e=e?e.slice(0):[],r=Object.assign({},r);const o={command:t,args:e,options:r,file:void 0,original:{command:t,args:e}};return r.shell?o:gn(o)}var wn=yn;const Pt=process.platform==="win32";function $t(t,e){return Object.assign(new Error(`${e} ${t.command} ENOENT`),{code:"ENOENT",errno:"ENOENT",syscall:`${e} ${t.command}`,path:t.command,spawnargs:t.args})}function vn(t,e){if(!Pt)return;const r=t.emit;t.emit=function(o,s){if(o==="exit"){const n=Br(s,e);if(n)return r.call(t,"error",n)}return r.apply(t,arguments)}}function Br(t,e){return Pt&&t===1&&!e.file?$t(e.original,"spawn"):null}function bn(t,e){return Pt&&t===1&&!e.file?$t(e.original,"spawnSync"):null}var Cn={hookChildProcess:vn,verifyENOENT:Br,verifyENOENTSync:bn,notFoundError:$t};const Hr=Zo,Et=wn,kt=Cn;function Ur(t,e,r){const o=Et(t,e,r),s=Hr.spawn(o.command,o.args,o.options);return kt.hookChildProcess(s,o),s}function Pn(t,e,r){const o=Et(t,e,r),s=Hr.spawnSync(o.command,o.args,o.options);return s.error=s.error||kt.verifyENOENTSync(s.status,o),s}me.exports=Ur,me.exports.spawn=Ur,me.exports.sync=Pn,me.exports._parse=Et,me.exports._enoent=kt;var $n=me.exports,En=de($n);function kn(t){const e=typeof t=="string"?`
|
|
2
|
+
import{command as oe,cli as Yo}from"cleye";import{createRequire as Vo}from"module";import U from"fs";import Ee from"os";import x from"path";import{Buffer as qo}from"node:buffer";import ae from"node:path";import ur,{ChildProcess as Xo,exec as Qo}from"node:child_process";import se from"node:process";import Zo,{execSync as _e,exec as es}from"child_process";import{fileURLToPath as dr}from"node:url";import ts,{constants as mr}from"node:os";import fr from"assert";import pr from"events";import{createWriteStream as rs,createReadStream as os}from"node:fs";import ss from"buffer";import ut from"stream";import hr,{promisify as ns}from"util";import{debuglog as is,promisify as as}from"node:util";import Ge from"inquirer";import P from"chalk";import{of as dt,concatMap as L,from as M,map as I,catchError as R,mergeMap as gr,BehaviorSubject as yr,ReplaySubject as cs,Subscription as mt,lastValueFrom as wr,filter as vr,toArray as br,Subject as ft}from"rxjs";import ls from"@anthropic-ai/sdk";import{fromPromise as D}from"rxjs/internal/observable/innerFrom";import{xxh64 as Cr}from"@pacote/xxhash";import B from"winston";import O from"fs/promises";import"winston-daily-rotate-file";import us from"axios";import{CohereClient as ds}from"cohere-ai";import Pr from"openai";import{GoogleGenerativeAI as ms,HarmCategory as He,HarmBlockThreshold as Be}from"@google/generative-ai";import fs from"http";import ps from"https";import hs from"net";import gs from"tls";import ys,{fileURLToPath as ws,pathToFileURL as vs}from"url";import $r from"tty";import bs from"groq-sdk";import{Ollama as Cs}from"ollama";import{fetch as Ps,Agent as $s}from"undici";import Ue from"readline";import Es from"figlet";import Er from"ora";import xs from"inquirer-reactive-list-prompt";import{readdir as xr,stat as ks,rm as As}from"node:fs/promises";import Ss from"chokidar";import{takeUntil as kr,finalize as Ar}from"rxjs/operators";var Ms="aicommit2",Sr="2.4.8",Is="A Reactive CLI that generates commit messages for Git and Jujutsu with various AI",Rs=["cli","ai","git","jujutsu","jj","vcs","version-control","commit","git-commit","jujutsu-commit","command-line","commandline","aipick","aicommit","aicommits","aicommit2","openai","huggingface","anthropic","claude","claude3","gemini","gemini-pro","generative-ai","mistral","ollama","llama3","llama3.2","llama3.3","gemma","llm","chatgpt","cohere","groq","codestral","perplexity","deepseek","deepseek-r1","pre-commit"],Os="MIT",Ls="tak-bro/aicommit2",Ds="Hyungtak Jin(@tak-bro)",Ts="module",Fs=["dist"],Ns={aicommit2:"./dist/cli.mjs",aic2:"./dist/cli.mjs"},js={prepare:"simple-git-hooks",build:"pkgroll --minify",lint:"eslint --cache .","type-check":"tsc",test:"tsx tests",prepack:"pnpm build && clean-pkg-json",prettier:"prettier"},_s={"@anthropic-ai/sdk":"^0.39.0","@dqbd/tiktoken":"^1.0.21","@google/generative-ai":"^0.24.1","@inquirer/prompts":"^3.3.2","@pacote/xxhash":"^0.3.2","@types/winston":"^2.4.4",axios:"^1.9.0",chalk:"^5.4.1",chokidar:"^4.0.3",cleye:"^1.3.4","cohere-ai":"^7.17.1","copy-paste":"^1.5.3",figlet:"^1.8.1","formdata-node":"^6.0.3","groq-sdk":"^0.7.0",inquirer:"9.2.8","inquirer-reactive-list-prompt":"^1.0.16",ollama:"^0.5.15",openai:"^5.0.1",ora:"^8.2.0",readline:"^1.3.0",rxjs:"^7.8.2",undici:"^7.10.0",uuid:"^9.0.1",winston:"^3.17.0","winston-daily-rotate-file":"^5.0.0"},Gs={"@pvtnbr/eslint-config":"^0.33.0","@semantic-release/changelog":"^6.0.3","@semantic-release/commit-analyzer":"^12.0.0","@semantic-release/git":"^10.0.1","@semantic-release/github":"^10.3.5","@semantic-release/npm":"^12.0.1","@semantic-release/release-notes-generator":"^13.0.0","@types/figlet":"^1.7.0","@types/ini":"^1.3.34","@types/inquirer":"^9.0.8","@types/node":"^18.19.103","@types/uuid":"^9.0.8","@typescript-eslint/eslint-plugin":"^6.21.0","@typescript-eslint/parser":"^6.21.0","clean-pkg-json":"^1.3.0","conventional-changelog-conventionalcommits":"^7.0.2","conventional-commits-parser":"^5.0.0",eslint:"^8.57.1","eslint-config-prettier":"^8.10.0","eslint-plugin-eslint-comments":"^3.2.0","eslint-plugin-import":"^2.31.0","eslint-plugin-jsonc":"^2.20.1","eslint-plugin-no-use-extend-native":"^0.5.0","eslint-plugin-promise":"^6.6.0","eslint-plugin-unicorn":"^49.0.0","eslint-plugin-unused-imports":"^3.2.0",execa:"^7.2.0","fs-fixture":"^1.2.0","https-proxy-agent":"^5.0.1",ini:"^3.0.1","lint-staged":"^13.3.0",manten:"^0.7.0",pkgroll:"^1.11.1",prettier:"^3.5.3","semantic-release":"^23.1.1","simple-git-hooks":"^2.13.0",tsx:"^3.14.0",typescript:"^4.9.5","undici-types":"^7.10.0"},Hs={extends:["@pvtnbr","prettier"],rules:{"unicorn/no-process-exit":"off"},overrides:[{files:"./src/commands/prepare-commit-msg-hook.ts",rules:{"unicorn/prevent-abbreviations":"off"}}]},Bs={branches:["main"],plugins:[["@semantic-release/commit-analyzer",{preset:"conventionalcommits",releaseRules:[{type:"refactor",release:"patch"},{type:"chore",release:"patch"},{type:"feat",release:"patch"},{scope:"major",release:"major"},{scope:"minor",release:"minor"},{scope:"patch",release:"patch"}]}],"@semantic-release/release-notes-generator",["@semantic-release/changelog",{changelogFile:"CHANGELOG.md"}],"@semantic-release/github",["@semantic-release/git",{assets:["CHANGELOG.md"],message:"chore(release): ${nextRelease.version} [skip ci]\n\n${nextRelease.notes}"}],"@semantic-release/npm"]},Us={name:Ms,version:Sr,description:Is,keywords:Rs,license:Os,repository:Ls,author:Ds,type:Ts,files:Fs,bin:Ns,scripts:js,"simple-git-hooks":{"pre-commit":"pnpm lint-staged"},"lint-staged":{"*.ts":["prettier --config ./.prettierrc --write","eslint --fix"]},dependencies:_s,devDependencies:Gs,eslintConfig:Hs,release:Bs},zs=Vo(import.meta.url),G=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function de(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var me={exports:{}},pt,Mr;function Ks(){if(Mr)return pt;Mr=1,pt=o,o.sync=s;var t=U;function e(n,i){var c=i.pathExt!==void 0?i.pathExt:process.env.PATHEXT;if(!c||(c=c.split(";"),c.indexOf("")!==-1))return!0;for(var a=0;a<c.length;a++){var m=c[a].toLowerCase();if(m&&n.substr(-m.length).toLowerCase()===m)return!0}return!1}function r(n,i,c){return!n.isSymbolicLink()&&!n.isFile()?!1:e(i,c)}function o(n,i,c){t.stat(n,function(a,m){c(a,a?!1:r(m,n,i))})}function s(n,i){return r(t.statSync(n),n,i)}return pt}var ht,Ir;function Ws(){if(Ir)return ht;Ir=1,ht=e,e.sync=r;var t=U;function e(n,i,c){t.stat(n,function(a,m){c(a,a?!1:o(m,i))})}function r(n,i){return o(t.statSync(n),i)}function o(n,i){return n.isFile()&&s(n,i)}function s(n,i){var c=n.mode,a=n.uid,m=n.gid,d=i.uid!==void 0?i.uid:process.getuid&&process.getuid(),l=i.gid!==void 0?i.gid:process.getgid&&process.getgid(),p=parseInt("100",8),u=parseInt("010",8),h=parseInt("001",8),g=p|u,y=c&h||c&u&&m===l||c&p&&a===d||c&g&&d===0;return y}return ht}var ze;process.platform==="win32"||G.TESTING_WINDOWS?ze=Ks():ze=Ws();var Js=gt;gt.sync=Ys;function gt(t,e,r){if(typeof e=="function"&&(r=e,e={}),!r){if(typeof Promise!="function")throw new TypeError("callback not provided");return new Promise(function(o,s){gt(t,e||{},function(n,i){n?s(n):o(i)})})}ze(t,e||{},function(o,s){o&&(o.code==="EACCES"||e&&e.ignoreErrors)&&(o=null,s=!1),r(o,s)})}function Ys(t,e){try{return ze.sync(t,e||{})}catch(r){if(e&&e.ignoreErrors||r.code==="EACCES")return!1;throw r}}const fe=process.platform==="win32"||process.env.OSTYPE==="cygwin"||process.env.OSTYPE==="msys",Rr=x,Vs=fe?";":":",Or=Js,Lr=t=>Object.assign(new Error(`not found: ${t}`),{code:"ENOENT"}),Dr=(t,e)=>{const r=e.colon||Vs,o=t.match(/\//)||fe&&t.match(/\\/)?[""]:[...fe?[process.cwd()]:[],...(e.path||process.env.PATH||"").split(r)],s=fe?e.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",n=fe?s.split(r):[""];return fe&&t.indexOf(".")!==-1&&n[0]!==""&&n.unshift(""),{pathEnv:o,pathExt:n,pathExtExe:s}},Tr=(t,e,r)=>{typeof e=="function"&&(r=e,e={}),e||(e={});const{pathEnv:o,pathExt:s,pathExtExe:n}=Dr(t,e),i=[],c=m=>new Promise((d,l)=>{if(m===o.length)return e.all&&i.length?d(i):l(Lr(t));const p=o[m],u=/^".*"$/.test(p)?p.slice(1,-1):p,h=Rr.join(u,t),g=!u&&/^\.[\\\/]/.test(t)?t.slice(0,2)+h:h;d(a(g,m,0))}),a=(m,d,l)=>new Promise((p,u)=>{if(l===s.length)return p(c(d+1));const h=s[l];Or(m+h,{pathExt:n},(g,y)=>{if(!g&&y)if(e.all)i.push(m+h);else return p(m+h);return p(a(m,d,l+1))})});return r?c(0).then(m=>r(null,m),r):c(0)},qs=(t,e)=>{e=e||{};const{pathEnv:r,pathExt:o,pathExtExe:s}=Dr(t,e),n=[];for(let i=0;i<r.length;i++){const c=r[i],a=/^".*"$/.test(c)?c.slice(1,-1):c,m=Rr.join(a,t),d=!a&&/^\.[\\\/]/.test(t)?t.slice(0,2)+m:m;for(let l=0;l<o.length;l++){const p=d+o[l];try{if(Or.sync(p,{pathExt:s}))if(e.all)n.push(p);else return p}catch{}}}if(e.all&&n.length)return n;if(e.nothrow)return null;throw Lr(t)};var Xs=Tr;Tr.sync=qs;var yt={exports:{}};const Fr=(t={})=>{const e=t.env||process.env;return(t.platform||process.platform)!=="win32"?"PATH":Object.keys(e).reverse().find(o=>o.toUpperCase()==="PATH")||"Path"};yt.exports=Fr,yt.exports.default=Fr;var Qs=yt.exports;const Nr=x,Zs=Xs,en=Qs;function jr(t,e){const r=t.options.env||process.env,o=process.cwd(),s=t.options.cwd!=null,n=s&&process.chdir!==void 0&&!process.chdir.disabled;if(n)try{process.chdir(t.options.cwd)}catch{}let i;try{i=Zs.sync(t.command,{path:r[en({env:r})],pathExt:e?Nr.delimiter:void 0})}catch{}finally{n&&process.chdir(o)}return i&&(i=Nr.resolve(s?t.options.cwd:"",i)),i}function tn(t){return jr(t)||jr(t,!0)}var rn=tn,wt={};const vt=/([()\][%!^"`<>&|;, *?])/g;function on(t){return t=t.replace(vt,"^$1"),t}function sn(t,e){return t=`${t}`,t=t.replace(/(?=(\\+?)?)\1"/g,'$1$1\\"'),t=t.replace(/(?=(\\+?)?)\1$/,"$1$1"),t=`"${t}"`,t=t.replace(vt,"^$1"),e&&(t=t.replace(vt,"^$1")),t}wt.command=on,wt.argument=sn;var nn=/^#!(.*)/;const an=nn;var cn=(t="")=>{const e=t.match(an);if(!e)return null;const[r,o]=e[0].replace(/#! ?/,"").split(" "),s=r.split("/").pop();return s==="env"?o:o?`${s} ${o}`:s};const bt=U,ln=cn;function un(t){const r=Buffer.alloc(150);let o;try{o=bt.openSync(t,"r"),bt.readSync(o,r,0,150,0),bt.closeSync(o)}catch{}return ln(r.toString())}var dn=un;const mn=x,_r=rn,Gr=wt,fn=dn,pn=process.platform==="win32",hn=/\.(?:com|exe)$/i,gn=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function yn(t){t.file=_r(t);const e=t.file&&fn(t.file);return e?(t.args.unshift(t.file),t.command=e,_r(t)):t.file}function wn(t){if(!pn)return t;const e=yn(t),r=!hn.test(e);if(t.options.forceShell||r){const o=gn.test(e);t.command=mn.normalize(t.command),t.command=Gr.command(t.command),t.args=t.args.map(n=>Gr.argument(n,o));const s=[t.command].concat(t.args).join(" ");t.args=["/d","/s","/c",`"${s}"`],t.command=process.env.comspec||"cmd.exe",t.options.windowsVerbatimArguments=!0}return t}function vn(t,e,r){e&&!Array.isArray(e)&&(r=e,e=null),e=e?e.slice(0):[],r=Object.assign({},r);const o={command:t,args:e,options:r,file:void 0,original:{command:t,args:e}};return r.shell?o:wn(o)}var bn=vn;const Ct=process.platform==="win32";function Pt(t,e){return Object.assign(new Error(`${e} ${t.command} ENOENT`),{code:"ENOENT",errno:"ENOENT",syscall:`${e} ${t.command}`,path:t.command,spawnargs:t.args})}function Cn(t,e){if(!Ct)return;const r=t.emit;t.emit=function(o,s){if(o==="exit"){const n=Hr(s,e);if(n)return r.call(t,"error",n)}return r.apply(t,arguments)}}function Hr(t,e){return Ct&&t===1&&!e.file?Pt(e.original,"spawn"):null}function Pn(t,e){return Ct&&t===1&&!e.file?Pt(e.original,"spawnSync"):null}var $n={hookChildProcess:Cn,verifyENOENT:Hr,verifyENOENTSync:Pn,notFoundError:Pt};const Br=Zo,$t=bn,Et=$n;function Ur(t,e,r){const o=$t(t,e,r),s=Br.spawn(o.command,o.args,o.options);return Et.hookChildProcess(s,o),s}function En(t,e,r){const o=$t(t,e,r),s=Br.spawnSync(o.command,o.args,o.options);return s.error=s.error||Et.verifyENOENTSync(s.status,o),s}me.exports=Ur,me.exports.spawn=Ur,me.exports.sync=En,me.exports._parse=$t,me.exports._enoent=Et;var xn=me.exports,kn=de(xn);function An(t){const e=typeof t=="string"?`
|
|
3
3
|
`:`
|
|
4
|
-
`.charCodeAt(),r=typeof t=="string"?"\r":"\r".charCodeAt();return t[t.length-1]===e&&(t=t.slice(0,-1)),t[t.length-1]===r&&(t=t.slice(0,-1)),t}function zr(t={}){const{env:e=process.env,platform:r=process.platform}=t;return r!=="win32"?"PATH":Object.keys(e).reverse().find(o=>o.toUpperCase()==="PATH")||"Path"}const
|
|
5
|
-
${e}`,
|
|
4
|
+
`.charCodeAt(),r=typeof t=="string"?"\r":"\r".charCodeAt();return t[t.length-1]===e&&(t=t.slice(0,-1)),t[t.length-1]===r&&(t=t.slice(0,-1)),t}function zr(t={}){const{env:e=process.env,platform:r=process.platform}=t;return r!=="win32"?"PATH":Object.keys(e).reverse().find(o=>o.toUpperCase()==="PATH")||"Path"}const Sn=({cwd:t=se.cwd(),path:e=se.env[zr()],preferLocal:r=!0,execPath:o=se.execPath,addExecPath:s=!0}={})=>{const n=t instanceof URL?dr(t):t,i=ae.resolve(n),c=[];return r&&Mn(c,i),s&&In(c,o,i),[...c,e].join(ae.delimiter)},Mn=(t,e)=>{let r;for(;r!==e;)t.push(ae.join(e,"node_modules/.bin")),r=e,e=ae.resolve(e,"..")},In=(t,e,r)=>{const o=e instanceof URL?dr(e):e;t.push(ae.resolve(r,o,".."))},Rn=({env:t=se.env,...e}={})=>{t={...t};const r=zr({env:t});return e.path=t[r],t[r]=Sn(e),t},On=(t,e,r,o)=>{if(r==="length"||r==="prototype"||r==="arguments"||r==="caller")return;const s=Object.getOwnPropertyDescriptor(t,r),n=Object.getOwnPropertyDescriptor(e,r);!Ln(s,n)&&o||Object.defineProperty(t,r,n)},Ln=function(t,e){return t===void 0||t.configurable||t.writable===e.writable&&t.enumerable===e.enumerable&&t.configurable===e.configurable&&(t.writable||t.value===e.value)},Dn=(t,e)=>{const r=Object.getPrototypeOf(e);r!==Object.getPrototypeOf(t)&&Object.setPrototypeOf(t,r)},Tn=(t,e)=>`/* Wrapped ${t}*/
|
|
5
|
+
${e}`,Fn=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),Nn=Object.getOwnPropertyDescriptor(Function.prototype.toString,"name"),jn=(t,e,r)=>{const o=r===""?"":`with ${r.trim()}() `,s=Tn.bind(null,o,e.toString());Object.defineProperty(s,"name",Nn),Object.defineProperty(t,"toString",{...Fn,value:s})};function _n(t,e,{ignoreNonConfigurable:r=!1}={}){const{name:o}=t;for(const s of Reflect.ownKeys(e))On(t,e,s,r);return Dn(t,e),jn(t,e,o),t}const Ke=new WeakMap,Kr=(t,e={})=>{if(typeof t!="function")throw new TypeError("Expected a function");let r,o=0;const s=t.displayName||t.name||"<anonymous>",n=function(...i){if(Ke.set(n,++o),o===1)r=t.apply(this,i),t=null;else if(e.throw===!0)throw new Error(`Function \`${s}\` can only be called once`);return r};return _n(n,t),Ke.set(n,o),n};Kr.callCount=t=>{if(!Ke.has(t))throw new Error(`The given function \`${t.name}\` is not wrapped by the \`onetime\` package`);return Ke.get(t)};const Gn=()=>{const t=Jr-Wr+1;return Array.from({length:t},Hn)},Hn=(t,e)=>({name:`SIGRT${e+1}`,number:Wr+e,action:"terminate",description:"Application-specific signal (realtime)",standard:"posix"}),Wr=34,Jr=64,Bn=[{name:"SIGHUP",number:1,action:"terminate",description:"Terminal closed",standard:"posix"},{name:"SIGINT",number:2,action:"terminate",description:"User interruption with CTRL-C",standard:"ansi"},{name:"SIGQUIT",number:3,action:"core",description:"User interruption with CTRL-\\",standard:"posix"},{name:"SIGILL",number:4,action:"core",description:"Invalid machine instruction",standard:"ansi"},{name:"SIGTRAP",number:5,action:"core",description:"Debugger breakpoint",standard:"posix"},{name:"SIGABRT",number:6,action:"core",description:"Aborted",standard:"ansi"},{name:"SIGIOT",number:6,action:"core",description:"Aborted",standard:"bsd"},{name:"SIGBUS",number:7,action:"core",description:"Bus error due to misaligned, non-existing address or paging error",standard:"bsd"},{name:"SIGEMT",number:7,action:"terminate",description:"Command should be emulated but is not implemented",standard:"other"},{name:"SIGFPE",number:8,action:"core",description:"Floating point arithmetic error",standard:"ansi"},{name:"SIGKILL",number:9,action:"terminate",description:"Forced termination",standard:"posix",forced:!0},{name:"SIGUSR1",number:10,action:"terminate",description:"Application-specific signal",standard:"posix"},{name:"SIGSEGV",number:11,action:"core",description:"Segmentation fault",standard:"ansi"},{name:"SIGUSR2",number:12,action:"terminate",description:"Application-specific signal",standard:"posix"},{name:"SIGPIPE",number:13,action:"terminate",description:"Broken pipe or socket",standard:"posix"},{name:"SIGALRM",number:14,action:"terminate",description:"Timeout or timer",standard:"posix"},{name:"SIGTERM",number:15,action:"terminate",description:"Termination",standard:"ansi"},{name:"SIGSTKFLT",number:16,action:"terminate",description:"Stack is empty or overflowed",standard:"other"},{name:"SIGCHLD",number:17,action:"ignore",description:"Child process terminated, paused or unpaused",standard:"posix"},{name:"SIGCLD",number:17,action:"ignore",description:"Child process terminated, paused or unpaused",standard:"other"},{name:"SIGCONT",number:18,action:"unpause",description:"Unpaused",standard:"posix",forced:!0},{name:"SIGSTOP",number:19,action:"pause",description:"Paused",standard:"posix",forced:!0},{name:"SIGTSTP",number:20,action:"pause",description:'Paused using CTRL-Z or "suspend"',standard:"posix"},{name:"SIGTTIN",number:21,action:"pause",description:"Background process cannot read terminal input",standard:"posix"},{name:"SIGBREAK",number:21,action:"terminate",description:"User interruption with CTRL-BREAK",standard:"other"},{name:"SIGTTOU",number:22,action:"pause",description:"Background process cannot write to terminal output",standard:"posix"},{name:"SIGURG",number:23,action:"ignore",description:"Socket received out-of-band data",standard:"bsd"},{name:"SIGXCPU",number:24,action:"core",description:"Process timed out",standard:"bsd"},{name:"SIGXFSZ",number:25,action:"core",description:"File too big",standard:"bsd"},{name:"SIGVTALRM",number:26,action:"terminate",description:"Timeout or timer",standard:"bsd"},{name:"SIGPROF",number:27,action:"terminate",description:"Timeout or timer",standard:"bsd"},{name:"SIGWINCH",number:28,action:"ignore",description:"Terminal window size changed",standard:"bsd"},{name:"SIGIO",number:29,action:"terminate",description:"I/O is available",standard:"other"},{name:"SIGPOLL",number:29,action:"terminate",description:"Watched event",standard:"other"},{name:"SIGINFO",number:29,action:"ignore",description:"Request for process information",standard:"other"},{name:"SIGPWR",number:30,action:"terminate",description:"Device running out of power",standard:"systemv"},{name:"SIGSYS",number:31,action:"core",description:"Invalid system call",standard:"other"},{name:"SIGUNUSED",number:31,action:"terminate",description:"Invalid system call",standard:"other"}],Yr=()=>{const t=Gn();return[...Bn,...t].map(Un)},Un=({name:t,number:e,description:r,action:o,forced:s=!1,standard:n})=>{const{signals:{[t]:i}}=mr,c=i!==void 0;return{name:t,number:c?i:e,description:r,supported:c,action:o,forced:s,standard:n}},zn=()=>{const t=Yr();return Object.fromEntries(t.map(Kn))},Kn=({name:t,number:e,description:r,supported:o,action:s,forced:n,standard:i})=>[t,{name:t,number:e,description:r,supported:o,action:s,forced:n,standard:i}],Wn=zn(),Jn=()=>{const t=Yr(),e=Jr+1,r=Array.from({length:e},(o,s)=>Yn(s,t));return Object.assign({},...r)},Yn=(t,e)=>{const r=Vn(t,e);if(r===void 0)return{};const{name:o,description:s,supported:n,action:i,forced:c,standard:a}=r;return{[t]:{name:o,number:t,description:s,supported:n,action:i,forced:c,standard:a}}},Vn=(t,e)=>{const r=e.find(({name:o})=>mr.signals[o]===t);return r!==void 0?r:e.find(o=>o.number===t)};Jn();const qn=({timedOut:t,timeout:e,errorCode:r,signal:o,signalDescription:s,exitCode:n,isCanceled:i})=>t?`timed out after ${e} milliseconds`:i?"was canceled":r!==void 0?`failed with ${r}`:o!==void 0?`was killed with ${o} (${s})`:n!==void 0?`failed with exit code ${n}`:"failed",Vr=({stdout:t,stderr:e,all:r,error:o,signal:s,exitCode:n,command:i,escapedCommand:c,timedOut:a,isCanceled:m,killed:d,parsed:{options:{timeout:l,cwd:p=se.cwd()}}})=>{n=n===null?void 0:n,s=s===null?void 0:s;const u=s===void 0?void 0:Wn[s].description,h=o&&o.code,y=`Command ${qn({timedOut:a,timeout:l,errorCode:h,signal:s,signalDescription:u,exitCode:n,isCanceled:m})}: ${i}`,w=Object.prototype.toString.call(o)==="[object Error]",v=w?`${y}
|
|
6
6
|
${o.message}`:y,E=[v,e,t].filter(Boolean).join(`
|
|
7
|
-
`);return w?(o.originalMessage=o.message,o.message=E):o=new Error(E),o.shortMessage=v,o.command=i,o.escapedCommand=c,o.exitCode=n,o.signal=s,o.signalDescription=u,o.stdout=t,o.stderr=e,o.cwd=p,r!==void 0&&(o.all=r),"bufferedData"in o&&delete o.bufferedData,o.failed=!0,o.timedOut=!!a,o.isCanceled=m,o.killed=d&&!a,o},
|
|
8
|
-
`)},
|
|
7
|
+
`);return w?(o.originalMessage=o.message,o.message=E):o=new Error(E),o.shortMessage=v,o.command=i,o.escapedCommand=c,o.exitCode=n,o.signal=s,o.signalDescription=u,o.stdout=t,o.stderr=e,o.cwd=p,r!==void 0&&(o.all=r),"bufferedData"in o&&delete o.bufferedData,o.failed=!0,o.timedOut=!!a,o.isCanceled=m,o.killed=d&&!a,o},We=["stdin","stdout","stderr"],Xn=t=>We.some(e=>t[e]!==void 0),Qn=t=>{if(!t)return;const{stdio:e}=t;if(e===void 0)return We.map(o=>t[o]);if(Xn(t))throw new Error(`It's not possible to provide \`stdio\` in combination with one of ${We.map(o=>`\`${o}\``).join(", ")}`);if(typeof e=="string")return e;if(!Array.isArray(e))throw new TypeError(`Expected \`stdio\` to be of type \`string\` or \`Array\`, got \`${typeof e}\``);const r=Math.max(e.length,We.length);return Array.from({length:r},(o,s)=>e[s])};var pe={exports:{}},Je={exports:{}};Je.exports;var qr;function Zn(){return qr||(qr=1,function(t){t.exports=["SIGABRT","SIGALRM","SIGHUP","SIGINT","SIGTERM"],process.platform!=="win32"&&t.exports.push("SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT"),process.platform==="linux"&&t.exports.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT","SIGUNUSED")}(Je)),Je.exports}var F=G.process;const ce=function(t){return t&&typeof t=="object"&&typeof t.removeListener=="function"&&typeof t.emit=="function"&&typeof t.reallyExit=="function"&&typeof t.listeners=="function"&&typeof t.kill=="function"&&typeof t.pid=="number"&&typeof t.on=="function"};if(!ce(F))pe.exports=function(){return function(){}};else{var ei=fr,xe=Zn(),ti=/^win/i.test(F.platform),Ye=pr;typeof Ye!="function"&&(Ye=Ye.EventEmitter);var H;F.__signal_exit_emitter__?H=F.__signal_exit_emitter__:(H=F.__signal_exit_emitter__=new Ye,H.count=0,H.emitted={}),H.infinite||(H.setMaxListeners(1/0),H.infinite=!0),pe.exports=function(t,e){if(!ce(G.process))return function(){};ei.equal(typeof t,"function","a callback must be provided for exit handler"),ke===!1&&Xr();var r="exit";e&&e.alwaysLast&&(r="afterexit");var o=function(){H.removeListener(r,t),H.listeners("exit").length===0&&H.listeners("afterexit").length===0&&xt()};return H.on(r,t),o};var xt=function(){!ke||!ce(G.process)||(ke=!1,xe.forEach(function(e){try{F.removeListener(e,kt[e])}catch{}}),F.emit=At,F.reallyExit=Qr,H.count-=1)};pe.exports.unload=xt;var he=function(e,r,o){H.emitted[e]||(H.emitted[e]=!0,H.emit(e,r,o))},kt={};xe.forEach(function(t){kt[t]=function(){if(ce(G.process)){var r=F.listeners(t);r.length===H.count&&(xt(),he("exit",null,t),he("afterexit",null,t),ti&&t==="SIGHUP"&&(t="SIGINT"),F.kill(F.pid,t))}}}),pe.exports.signals=function(){return xe};var ke=!1,Xr=function(){ke||!ce(G.process)||(ke=!0,H.count+=1,xe=xe.filter(function(e){try{return F.on(e,kt[e]),!0}catch{return!1}}),F.emit=oi,F.reallyExit=ri)};pe.exports.load=Xr;var Qr=F.reallyExit,ri=function(e){ce(G.process)&&(F.exitCode=e||0,he("exit",F.exitCode,null),he("afterexit",F.exitCode,null),Qr.call(F,F.exitCode))},At=F.emit,oi=function(e,r){if(e==="exit"&&ce(G.process)){r!==void 0&&(F.exitCode=r);var o=At.apply(this,arguments);return he("exit",F.exitCode,null),he("afterexit",F.exitCode,null),o}else return At.apply(this,arguments)}}var si=pe.exports,ni=de(si);const ii=1e3*5,ai=(t,e="SIGTERM",r={})=>{const o=t(e);return ci(t,e,r,o),o},ci=(t,e,r,o)=>{if(!li(e,r,o))return;const s=di(r),n=setTimeout(()=>{t("SIGKILL")},s);n.unref&&n.unref()},li=(t,{forceKillAfterTimeout:e},r)=>ui(t)&&e!==!1&&r,ui=t=>t===ts.constants.signals.SIGTERM||typeof t=="string"&&t.toUpperCase()==="SIGTERM",di=({forceKillAfterTimeout:t=!0})=>{if(t===!0)return ii;if(!Number.isFinite(t)||t<0)throw new TypeError(`Expected the \`forceKillAfterTimeout\` option to be a non-negative integer, got \`${t}\` (${typeof t})`);return t},mi=(t,e)=>{t.kill()&&(e.isCanceled=!0)},fi=(t,e,r)=>{t.kill(e),r(Object.assign(new Error("Timed out"),{timedOut:!0,signal:e}))},pi=(t,{timeout:e,killSignal:r="SIGTERM"},o)=>{if(e===0||e===void 0)return o;let s;const n=new Promise((c,a)=>{s=setTimeout(()=>{fi(t,r,a)},e)}),i=o.finally(()=>{clearTimeout(s)});return Promise.race([n,i])},hi=({timeout:t})=>{if(t!==void 0&&(!Number.isFinite(t)||t<0))throw new TypeError(`Expected the \`timeout\` option to be a non-negative integer, got \`${t}\` (${typeof t})`)},gi=async(t,{cleanup:e,detached:r},o)=>{if(!e||r)return o;const s=ni(()=>{t.kill()});return o.finally(()=>{s()})};function Zr(t){return t!==null&&typeof t=="object"&&typeof t.pipe=="function"}function eo(t){return Zr(t)&&t.writable!==!1&&typeof t._write=="function"&&typeof t._writableState=="object"}const yi=t=>t instanceof Xo&&typeof t.then=="function",St=(t,e,r)=>{if(typeof r=="string")return t[e].pipe(rs(r)),t;if(eo(r))return t[e].pipe(r),t;if(!yi(r))throw new TypeError("The second argument must be a string, a stream or an Execa child process.");if(!eo(r.stdin))throw new TypeError("The target child process's stdin must be available.");return t[e].pipe(r.stdin),r},wi=t=>{t.stdout!==null&&(t.pipeStdout=St.bind(void 0,t,"stdout")),t.stderr!==null&&(t.pipeStderr=St.bind(void 0,t,"stderr")),t.all!==void 0&&(t.pipeAll=St.bind(void 0,t,"all"))};var Ae={exports:{}};const{PassThrough:vi}=ut;var bi=t=>{t={...t};const{array:e}=t;let{encoding:r}=t;const o=r==="buffer";let s=!1;e?s=!(r||o):r=r||"utf8",o&&(r=null);const n=new vi({objectMode:s});r&&n.setEncoding(r);let i=0;const c=[];return n.on("data",a=>{c.push(a),s?i=c.length:i+=a.length}),n.getBufferedValue=()=>e?c:o?Buffer.concat(c,i):c.join(""),n.getBufferedLength=()=>i,n};const{constants:Ci}=ss,Pi=ut,{promisify:$i}=hr,Ei=bi,xi=$i(Pi.pipeline);class to extends Error{constructor(){super("maxBuffer exceeded"),this.name="MaxBufferError"}}async function Mt(t,e){if(!t)throw new Error("Expected a stream");e={maxBuffer:1/0,...e};const{maxBuffer:r}=e,o=Ei(e);return await new Promise((s,n)=>{const i=c=>{c&&o.getBufferedLength()<=Ci.MAX_LENGTH&&(c.bufferedData=o.getBufferedValue()),n(c)};(async()=>{try{await xi(t,o),s()}catch(c){i(c)}})(),o.on("data",()=>{o.getBufferedLength()>r&&i(new to)})}),o.getBufferedValue()}Ae.exports=Mt,Ae.exports.buffer=(t,e)=>Mt(t,{...e,encoding:"buffer"}),Ae.exports.array=(t,e)=>Mt(t,{...e,array:!0}),Ae.exports.MaxBufferError=to;var ki=Ae.exports,ro=de(ki);const{PassThrough:Ai}=ut;var Si=function(){var t=[],e=new Ai({objectMode:!0});return e.setMaxListeners(0),e.add=r,e.isEmpty=o,e.on("unpipe",s),Array.prototype.slice.call(arguments).forEach(r),e;function r(n){return Array.isArray(n)?(n.forEach(r),this):(t.push(n),n.once("end",s.bind(null,n)),n.once("error",e.emit.bind(e,"error")),n.pipe(e,{end:!1}),this)}function o(){return t.length==0}function s(n){t=t.filter(function(i){return i!==n}),!t.length&&e.readable&&e.end()}},Mi=de(Si);const Ii=t=>{if(t!==void 0)throw new TypeError("The `input` and `inputFile` options cannot be both set.")},Ri=({input:t,inputFile:e})=>typeof e!="string"?t:(Ii(t),os(e)),Oi=(t,e)=>{const r=Ri(e);r!==void 0&&(Zr(r)?r.pipe(t.stdin):t.stdin.end(r))},Li=(t,{all:e})=>{if(!e||!t.stdout&&!t.stderr)return;const r=Mi();return t.stdout&&r.add(t.stdout),t.stderr&&r.add(t.stderr),r},It=async(t,e)=>{if(!(!t||e===void 0)){t.destroy();try{return await e}catch(r){return r.bufferedData}}},Rt=(t,{encoding:e,buffer:r,maxBuffer:o})=>{if(!(!t||!r))return e?ro(t,{encoding:e,maxBuffer:o}):ro.buffer(t,{maxBuffer:o})},Di=async({stdout:t,stderr:e,all:r},{encoding:o,buffer:s,maxBuffer:n},i)=>{const c=Rt(t,{encoding:o,buffer:s,maxBuffer:n}),a=Rt(e,{encoding:o,buffer:s,maxBuffer:n}),m=Rt(r,{encoding:o,buffer:s,maxBuffer:n*2});try{return await Promise.all([i,c,a,m])}catch(d){return Promise.all([{error:d,signal:d.signal,timedOut:d.timedOut},It(t,c),It(e,a),It(r,m)])}},Ti=(async()=>{})().constructor.prototype,Fi=["then","catch","finally"].map(t=>[t,Reflect.getOwnPropertyDescriptor(Ti,t)]),oo=(t,e)=>{for(const[r,o]of Fi){const s=typeof e=="function"?(...n)=>Reflect.apply(o.value,e(),n):o.value.bind(e);Reflect.defineProperty(t,r,{...o,value:s})}},Ni=t=>new Promise((e,r)=>{t.on("exit",(o,s)=>{e({exitCode:o,signal:s})}),t.on("error",o=>{r(o)}),t.stdin&&t.stdin.on("error",o=>{r(o)})}),so=(t,e=[])=>Array.isArray(e)?[t,...e]:[t],ji=/^[\w.-]+$/,_i=/"/g,Gi=t=>typeof t!="string"||ji.test(t)?t:`"${t.replace(_i,'\\"')}"`,Hi=(t,e)=>so(t,e).join(" "),Bi=(t,e)=>so(t,e).map(r=>Gi(r)).join(" "),Ui=is("execa").enabled,Ve=(t,e)=>String(t).padStart(e,"0"),zi=()=>{const t=new Date;return`${Ve(t.getHours(),2)}:${Ve(t.getMinutes(),2)}:${Ve(t.getSeconds(),2)}.${Ve(t.getMilliseconds(),3)}`},Ki=(t,{verbose:e})=>{e&&se.stderr.write(`[${zi()}] ${t}
|
|
8
|
+
`)},Wi=1e3*1e3*100,Ji=({env:t,extendEnv:e,preferLocal:r,localDir:o,execPath:s})=>{const n=e?{...se.env,...t}:t;return r?Rn({env:n,cwd:o,execPath:s}):n},Yi=(t,e,r={})=>{const o=kn._parse(t,e,r);return t=o.command,e=o.args,r=o.options,r={maxBuffer:Wi,buffer:!0,stripFinalNewline:!0,extendEnv:!0,preferLocal:!1,localDir:r.cwd||se.cwd(),execPath:se.execPath,encoding:"utf8",reject:!0,cleanup:!0,all:!1,windowsHide:!0,verbose:Ui,...r},r.env=Ji(r),r.stdio=Qn(r),se.platform==="win32"&&ae.basename(t,".exe")==="cmd"&&e.unshift("/q"),{file:t,args:e,options:r,parsed:o}},Ot=(t,e,r)=>typeof e!="string"&&!qo.isBuffer(e)?r===void 0?void 0:"":t.stripFinalNewline?An(e):e;function N(t,e,r){const o=Yi(t,e,r),s=Hi(t,e),n=Bi(t,e);Ki(n,o.options),hi(o.options);let i;try{i=ur.spawn(o.file,o.args,o.options)}catch(u){const h=new ur.ChildProcess,g=Promise.reject(Vr({error:u,stdout:"",stderr:"",all:"",command:s,escapedCommand:n,parsed:o,timedOut:!1,isCanceled:!1,killed:!1}));return oo(h,g),h}const c=Ni(i),a=pi(i,o.options,c),m=gi(i,o.options,a),d={isCanceled:!1};i.kill=ai.bind(null,i.kill.bind(i)),i.cancel=mi.bind(null,i,d);const p=Kr(async()=>{const[{error:u,exitCode:h,signal:g,timedOut:y},w,v,E]=await Di(i,o.options,m),A=Ot(o.options,w),$=Ot(o.options,v),C=Ot(o.options,E);if(u||h!==0||g!==null){const S=Vr({error:u,exitCode:h,signal:g,stdout:A,stderr:$,all:C,command:s,escapedCommand:n,parsed:o,timedOut:y,isCanceled:d.isCanceled||(o.options.signal?o.options.signal.aborted:!1),killed:i.killed});if(!o.options.reject)return S;throw S}return{command:s,escapedCommand:n,exitCode:0,stdout:A,stderr:$,all:C,failed:!1,timedOut:!1,isCanceled:!1,killed:!1}});return Oi(i,o.options),i.all=Li(i,o.options),wi(i),oo(i,p),i}class J{static create(e,r){return new e(r)}}const{hasOwnProperty:Lt}=Object.prototype,qe=typeof process<"u"&&process.platform==="win32"?`\r
|
|
9
9
|
`:`
|
|
10
|
-
`,Dt=(t,e)=>{const r=[];let o="";typeof e=="string"?e={section:e,whitespace:!1}:(e=e||Object.create(null),e.whitespace=e.whitespace===!0);const s=e.whitespace?" = ":"=";for(const n of Object.keys(t)){const i=t[n];if(i&&Array.isArray(i))for(const c of i)o+=ge(n+"[]")+s+ge(c)+qe;else i&&typeof i=="object"?r.push(n):o+=ge(n)+s+ge(i)+qe}e.section&&o.length&&(o="["+ge(e.section)+"]"+qe+o);for(const n of r){const i=no(n).join("\\."),c=(e.section?e.section+".":"")+i,{whitespace:a}=e,m=Dt(t[n],{section:c,whitespace:a});o.length&&m.length&&(o+=qe),o+=m}return o},no=t=>t.replace(/\1/g,"LITERAL\\1LITERAL").replace(/\\\./g,"").split(/\./).map(e=>e.replace(/\1/g,"\\.").replace(/\2LITERAL\\1LITERAL\2/g,"")),io=t=>{const e=Object.create(null);let r=e,o=null;const s=/^\[([^\]]*)\]$|^([^=]+)(=(.*))?$/i,n=t.split(/[\r\n]+/g);for(const c of n){if(!c||c.match(/^\s*[;#]/))continue;const a=c.match(s);if(!a)continue;if(a[1]!==void 0){if(o=Xe(a[1]),o==="__proto__"){r=Object.create(null);continue}r=e[o]=e[o]||Object.create(null);continue}const m=Xe(a[2]),d=m.length>2&&m.slice(-2)==="[]",l=d?m.slice(0,-2):m;if(l==="__proto__")continue;const p=a[3]?Xe(a[4]):!0,u=p==="true"||p==="false"||p==="null"?JSON.parse(p):p;d&&(
|
|
10
|
+
`,Dt=(t,e)=>{const r=[];let o="";typeof e=="string"?e={section:e,whitespace:!1}:(e=e||Object.create(null),e.whitespace=e.whitespace===!0);const s=e.whitespace?" = ":"=";for(const n of Object.keys(t)){const i=t[n];if(i&&Array.isArray(i))for(const c of i)o+=ge(n+"[]")+s+ge(c)+qe;else i&&typeof i=="object"?r.push(n):o+=ge(n)+s+ge(i)+qe}e.section&&o.length&&(o="["+ge(e.section)+"]"+qe+o);for(const n of r){const i=no(n).join("\\."),c=(e.section?e.section+".":"")+i,{whitespace:a}=e,m=Dt(t[n],{section:c,whitespace:a});o.length&&m.length&&(o+=qe),o+=m}return o},no=t=>t.replace(/\1/g,"LITERAL\\1LITERAL").replace(/\\\./g,"").split(/\./).map(e=>e.replace(/\1/g,"\\.").replace(/\2LITERAL\\1LITERAL\2/g,"")),io=t=>{const e=Object.create(null);let r=e,o=null;const s=/^\[([^\]]*)\]$|^([^=]+)(=(.*))?$/i,n=t.split(/[\r\n]+/g);for(const c of n){if(!c||c.match(/^\s*[;#]/))continue;const a=c.match(s);if(!a)continue;if(a[1]!==void 0){if(o=Xe(a[1]),o==="__proto__"){r=Object.create(null);continue}r=e[o]=e[o]||Object.create(null);continue}const m=Xe(a[2]),d=m.length>2&&m.slice(-2)==="[]",l=d?m.slice(0,-2):m;if(l==="__proto__")continue;const p=a[3]?Xe(a[4]):!0,u=p==="true"||p==="false"||p==="null"?JSON.parse(p):p;d&&(Lt.call(r,l)?Array.isArray(r[l])||(r[l]=[r[l]]):r[l]=[]),Array.isArray(r[l])?r[l].push(u):r[l]=u}const i=[];for(const c of Object.keys(e)){if(!Lt.call(e,c)||typeof e[c]!="object"||Array.isArray(e[c]))continue;const a=no(c);r=e;const m=a.pop(),d=m.replace(/\\\./g,".");for(const l of a)l!=="__proto__"&&((!Lt.call(r,l)||typeof r[l]!="object")&&(r[l]=Object.create(null)),r=r[l]);r===e&&d===m||(r[d]=e[c],i.push(c))}for(const c of i)delete e[c];return e},ao=t=>t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'"),ge=t=>typeof t!="string"||t.match(/[=\r\n]/)||t.match(/^\[/)||t.length>1&&ao(t)||t!==t.trim()?JSON.stringify(t):t.split(";").join("\\;").split("#").join("\\#"),Xe=(t,e)=>{if(t=(t||"").trim(),ao(t)){t.charAt(0)==="'"&&(t=t.slice(1,-1));try{t=JSON.parse(t)}catch{}}else{let r=!1,o="";for(let s=0,n=t.length;s<n;s++){const i=t.charAt(s);if(r)"\\;#".indexOf(i)!==-1?o+=i:o+="\\"+i,r=!1;else{if(";#".indexOf(i)!==-1)break;i==="\\"?r=!0:o+=i}}return r&&(o+="\\"),o.trim()}return t};var Vi={parse:io,decode:io,stringify:Dt,encode:Dt,safe:ge,unsafe:Xe},ye=de(Vi);class b extends Error{}const Tt=" ",ne=t=>{t instanceof Error&&(t instanceof b||(t.stack&&console.error(P.dim(t.stack.split(`
|
|
11
11
|
`).slice(1).join(`
|
|
12
12
|
`))),console.error(`
|
|
13
|
-
${
|
|
14
|
-
${Ft}Please open a Bug report with the information above:`),console.error(`${Ft}https://github.com/tak-bro/aicommit2/issues/new/choose`)))},co=t=>O.lstat(t).then(()=>!0,()=>!1),lo=async t=>{try{await O.mkdir(t,{recursive:!0})}catch(e){if(e.code!=="EEXIST")throw e}},Qe=t=>t&&`${t[0].toUpperCase()}${t.slice(1)}`,Ze=(t,e)=>{const r=Math.ceil(t),o=Math.floor(e);return Math.floor(Math.random()*(o-r+1))+r},Yi=(t,e)=>t.disabled&&!e.disabled?1:!t.disabled&&e.disabled?-1:0,et=t=>t.reduce((e,r)=>Array.isArray(r)?e.concat(et(r)):e.concat(r),[]),uo=(t,e=5)=>t.replace(/[\n\r]/g,"").split(" ").slice(0,e).join(" "),Vi=t=>{let e=0;for(let r=0;r<t.length;r++){const o=t.charCodeAt(r);e=(e<<5)-e+o,e=e&e}return Math.abs(e)},qi=t=>{const e=t%360,r=65+t%15,o=45+t%10;return`hsl(${e}, ${r}%, ${o}%)`},Xi=t=>{const[e,r,o]=t.match(/\d+/g).map((l,p)=>p===0?Number(l):Number(l)/100),s=(1-Math.abs(2*o-1))*r,n=s*(1-Math.abs(e/60%2-1)),i=o-s/2;let c,a,m;e<60?[c,a,m]=[s,n,0]:e<120?[c,a,m]=[n,s,0]:e<180?[c,a,m]=[0,s,n]:e<240?[c,a,m]=[0,n,s]:e<300?[c,a,m]=[n,0,s]:[c,a,m]=[s,0,n];const d=l=>{const p=Math.round((l+i)*255).toString(16);return p.length===1?"0"+p:p};return`#${d(c)}${d(a)}${d(m)}`},Qi=t=>{const e=Vi(t),r=qi(e);return{primary:Xi(r),secondary:"#FFFFFF"}},Zi=t=>{try{return{ok:!0,data:JSON.parse(t)}}catch(e){return{ok:!1,error:e}}},tt=t=>{if(!t||typeof t!="string")return"";if(S.isAbsolute(t))return S.resolve(t);if(Me){const e=S.dirname(Me),r=S.join(e,t);return S.resolve(r)}else return""},ea=["","conventional","gitmoji","jujutsu"],Tt="http://localhost:11434",{hasOwnProperty:ta}=Object.prototype,Nt=(t,e)=>ta.call(t,e),we=["OPENAI","OLLAMA","HUGGINGFACE","GEMINI","ANTHROPIC","MISTRAL","CODESTRAL","COHERE","GROQ","PERPLEXITY","DEEPSEEK","GITHUB_MODELS"],mo=t=>{const e=Ee.platform(),r=Ee.homedir();let o,s;switch(t){case"config":o=process.env.XDG_CONFIG_HOME;break;case"data":o=process.env.XDG_DATA_HOME;break;case"cache":o=process.env.XDG_CACHE_HOME;break;case"state":o=process.env.XDG_STATE_HOME;break;default:o=void 0}if(e==="darwin")t==="cache"?s=S.join(r,"Library","Caches"):s=S.join(r,"Library","Application Support");else if(e==="win32")s=process.env.LOCALAPPDATA||r;else switch(t){case"config":s=S.join(r,".config");break;case"data":s=S.join(r,".local","share");break;case"cache":s=S.join(r,".cache");break;case"state":s=S.join(r,".local","state");break;default:s=r}return o||s},ra=S.join(mo("config"),"aicommit2"),ee=S.join(mo("state"),"aicommit2","logs"),fo=S.join(ra,"config.ini"),po=S.join(ee,"aicommit2-%DATE%.log"),ho=S.join(ee,"exceptions-%DATE%.log"),oa=t=>{const e=Object.keys(t),r=new Set([...we,...e.filter(o=>/^[A-Z][A-Z0-9_]*$/.test(o))]);return Array.from(r)},k=(t,e,r)=>{if(!e)throw new b(`Invalid config property ${t}: ${r}`)},f={systemPrompt(t){return t||""},systemPromptPath(t){return t||""},codeReviewPromptPath(t){return t||""},timeout(t){if(!t)return 1e4;k("timeout",/^\d+$/.test(t),"Must be an integer");const e=Number(t);return k("timeout",e>=500,"Must be greater than 500ms"),e},temperature(t){if(!t)return .7;k("temperature",/^(2|\d)(\.\d{1,2})?$/.test(t),"Must be decimal between 0 and 2");const e=Number(t);return k("temperature",e>0,"Must be greater than 0"),k("temperature",e<=2,"Must be less than or equal to 2"),e},maxTokens(t){return t?(k("maxTokens",/^\d+$/.test(t),"Must be an integer"),Number(t)):1024},logging(t){return typeof t=="boolean"?t:t==null?!0:(k("logging",/^(?:true|false)$/.test(t),"Must be a boolean(true or false)"),t==="true")},logLevel(t){return t?(k("logLevel",/^(?:error|warn|info|http|verbose|debug|silly)$/.test(t),"Must be a valid log level (error, warn, info, http, verbose, debug, silly)"),t):"info"},logFilePath(t){return t||po},exceptionLogFilePath(t){return t||ho},locale(t){return t?(k("locale",t,"Cannot be empty"),k("locale",/^[a-z-]+$/i.test(t),"Must be a valid locale (letters and dashes/underscores). You can consult the list of codes in: https://wikipedia.org/wiki/List_of_ISO_639-1_codes"),t):"en"},generate(t){if(!t)return 1;k("generate",/^\d+$/.test(t),"Must be an integer");const e=Number(t);return k("generate",e>0,"Must be greater than 0"),k("generate",e<=5,"Must be less or equal to 5"),e},type(t){return t?(k("type",ea.includes(t),"Invalid commit type"),t):"conventional"},maxLength(t){if(!t)return 50;k("maxLength",/^\d+$/.test(t),"Must be an integer");const e=Number(t);return k("maxLength",e>=20,"Must be greater than 20 characters"),e},includeBody(t){return typeof t=="boolean"?t:t==null?!1:(k("includeBody",/^(?:true|false)$/.test(t),"Must be a boolean(true or false)"),t==="true")},exclude:t=>t?(typeof t=="string"?t?.split(","):t).map(r=>r.trim()).filter(r=>!!r&&r.length>0):[],topP:t=>{if(!t)return .9;k("topP",/^(1|\d)(\.\d{1,2})?$/.test(t),"Must be decimal between 0 and 1");const e=Number(t);return k("topP",e>0,"Must be greater than 0"),k("topP",e<=1,"Must be less than or equal to 1"),e},codeReview(t){return typeof t=="boolean"?t:t==null?!1:(k("codeReview",/^(?:true|false)$/.test(t),"Must be a boolean(true or false)"),t==="true")},disabled(t){return typeof t=="boolean"?t:t==null?!1:(k("disabled",/^(?:true|false)$/.test(t),"Must be a boolean(true or false)"),t==="true")},watchMode(t){return typeof t=="boolean"?t:t==null?!1:(k("watchMode",/^(?:true|false)$/.test(t),"Must be a boolean(true or false)"),t==="true")},jujutsu(t){return typeof t=="boolean"?t:t==null?!1:(k("jujutsu",/^(?:true|false)$/.test(t),"Must be a boolean(true or false)"),t==="true")},disableLowerCase(t){return typeof t=="boolean"?t:t==null?!1:(k("disableLowerCase",/^(?:true|false)$/.test(t),"Must be a boolean(true or false)"),t==="true")}},Ae={OPENAI:{key:t=>t||"",envKey:t=>t||"",model:t=>t?(typeof t=="string"?t?.split(","):t).map(r=>r.trim()).filter(r=>!!r&&r.length>0):["gpt-4o-mini"],url:t=>t?(k("OPENAI.url",/^https?:\/\//.test(t),"Must be a valid URL"),t):"https://api.openai.com",path:t=>t||"/v1/chat/completions",proxy:t=>t||"",topP:f.topP,systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,timeout:f.timeout,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode,disableLowerCase:f.disableLowerCase},HUGGINGFACE:{cookie:t=>t||"",model:t=>t?(typeof t=="string"?t?.split(","):t).map(r=>r.trim()).filter(r=>!!r&&r.length>0):["CohereForAI/c4ai-command-r-plus"],systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,timeout:f.timeout,temperature:f.temperature,maxTokens:f.maxTokens,topP:f.topP,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode,disableLowerCase:f.disableLowerCase},GEMINI:{key:t=>t||"",envKey:t=>t||"",model:t=>t?(typeof t=="string"?t?.split(","):t).map(r=>r.trim()).filter(r=>!!r&&r.length>0):["gemini-2.0-flash"],systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,topP:f.topP,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode,disableLowerCase:f.disableLowerCase},ANTHROPIC:{key:t=>t||"",envKey:t=>t||"",model:t=>t?(typeof t=="string"?t?.split(","):t).map(r=>r.trim()).filter(r=>!!r&&r.length>0):["claude-3-5-haiku-20241022"],systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,topP:f.topP,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode,disableLowerCase:f.disableLowerCase},MISTRAL:{key:t=>t||"",envKey:t=>t||"",model:t=>t?(typeof t=="string"?t?.split(","):t).map(r=>r.trim()).filter(r=>!!r&&r.length>0):["mistral-small-latest"],systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,timeout:f.timeout,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,topP:f.topP,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode,disableLowerCase:f.disableLowerCase},CODESTRAL:{key:t=>t||"",envKey:t=>t||"",model:t=>t?(typeof t=="string"?t?.split(","):t).map(r=>r.trim()).filter(r=>!!r&&r.length>0):["codestral-latest"],topP:f.topP,systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,timeout:f.timeout,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode,disableLowerCase:f.disableLowerCase},OLLAMA:{model:t=>t?(typeof t=="string"?t?.split(","):t).map(r=>r.trim()).filter(r=>!!r&&r.length>0):[],host:t=>t?(k("OLLAMA.host",/^https?:\/\//.test(t),"Must be a valid URL"),t):Tt,timeout:t=>{if(!t)return 1e5;k("OLLAMA.timeout",/^\d+$/.test(t),"Must be an integer");const e=Number(t);return k("OLLAMA.timeout",e>=500,"Must be greater than 500ms"),e},auth:t=>t||"",key:t=>t||"",envKey:t=>t||"",numCtx:t=>{if(!t)return 2048;k("OLLAMA.numCtx",/^\d+$/.test(t),"Must be an integer");const e=Number(t);return k("OLLAMA.numCtx",e>=2048,"Must be greater than 2048"),e},systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,topP:f.topP,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode,disableLowerCase:f.disableLowerCase},COHERE:{key:t=>t||"",envKey:t=>t||"",model:t=>t?(typeof t=="string"?t?.split(","):t).map(r=>r.trim()).filter(r=>!!r&&r.length>0):["command-r"],systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,topP:f.topP,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode,disableLowerCase:f.disableLowerCase},GROQ:{key:t=>t||"",envKey:t=>t||"",model:t=>t?(typeof t=="string"?t?.split(","):t).map(r=>r.trim()).filter(r=>!!r&&r.length>0):["llama-3.3-70b-versatile"],systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,timeout:f.timeout,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,topP:f.topP,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode,disableLowerCase:f.disableLowerCase},PERPLEXITY:{key:t=>t||"",envKey:t=>t||"",model:t=>t?(typeof t=="string"?t?.split(","):t).map(r=>r.trim()).filter(r=>!!r&&r.length>0):["sonar"],topP:f.topP,systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,timeout:f.timeout,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode,disableLowerCase:f.disableLowerCase},DEEPSEEK:{key:t=>t||"",envKey:t=>t||"",model:t=>t?(typeof t=="string"?t?.split(","):t).map(r=>r.trim()).filter(r=>!!r&&r.length>0):["deepseek-coder"],topP:f.topP,systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,timeout:f.timeout,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode,disableLowerCase:f.disableLowerCase},GITHUB_MODELS:{key:t=>t||"",envKey:t=>t||"",model:t=>t?(typeof t=="string"?t?.split(","):t).map(r=>r.trim()).filter(r=>!!r&&r.length>0):["gpt-4o-mini"],systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,timeout:f.timeout,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,topP:f.topP,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode,disableLowerCase:f.disableLowerCase}};let Me;const sa=(t=[])=>{const e={};for(const r of t)if(r.startsWith("--")){const[o,s]=r.slice(2).split("="),[n,i]=o.split(".");n&&i&&n in Ae?(e[n]||(e[n]={}),e[n][i]=s):e[o]=s}return e},na=()=>{const t=Ee.homedir(),e=process.env.AICOMMIT_CONFIG_PATH,r=fo,o=S.join(t,".aicommit2");return[e,r,o].filter(s=>!!s)},ve=async()=>{const t=na();for(const e of t)if(await co(e))return e;return fo},Ie=async()=>{const t=await ve();Me=t;try{const e=await O.readFile(t,"utf8");return ye.parse(e)}catch(e){return e.code==="ENOENT"?(Me=void 0,{}):(console.error(`Error reading config file ${t}:`,e),Me=void 0,{})}},le=async(t,e=[])=>{const r=await Ie(),o=sa(e),s={...t,...o},n={},i=oa(r),c={};for(const m of i){const l=r[m]?.envKey||`${m}_API_KEY`,p=process.env[l];p&&(c[m]={key:p})}const a=(m,d)=>{const l=s[`${m}.${d}`]??s[m]?.[d],p=c[m]?.[d],u=r[m]?.[d],h=s[d]??r[d];return l!==void 0?l:p!==void 0?p:u!==void 0?u:h};for(const[m,d]of Object.entries(f)){const l=s[m]??r[m];n[m]=d(l)}for(const m of i){n[m]={};const d=Ae[m]||rt(m);for(const[l,p]of Object.entries(d)){const u=a(m,l);n[m][l]=p(u)}}return n},_t=async t=>{const e=await Ie();for(const[s,n]of t){const[i,c]=s.split(".");if(!c){const d=f[s];if(!d)throw new b(`Invalid config property: ${s}`);e[s]=d(n);continue}if(e[i]||(e[i]={}),we.includes(i)){const d=Ae[i][c];if(!d)throw new b(`Invalid config property: ${s}`);e[i][c]=d(n);continue}if(!/^[A-Z][A-Z0-9_]*$/.test(i))throw new b(`Invalid service name: ${i}. Service names must be uppercase letters, numbers, and underscores.`);const m=rt(i);if(!m[c])throw new b(`Invalid config property for custom service: ${s}`);try{e[i][c]=m[c](n)}catch(d){throw d instanceof b?d:new b(`Invalid value for ${s}: ${d.message}`)}}const r=await ve(),o=S.dirname(r);await O.mkdir(o,{recursive:!0}),await O.writeFile(r,ye.stringify(e),"utf8")},ia=async t=>{const e=await Ie();for(const[s,n]of t){const[i,c]=s.split("."),a=e[i];if(c==="model"){a||(e[i]={});const d=e[i][c]||[],l=typeof n=="string"?n.split(",").map(p=>p.trim()).filter(p=>!!p):n;e[i][c]=et([...d,...l]);continue}if(a&&a.compatible===!0){a||(e[i]={});const d=rt(i);if(!d[c])throw new b(`Invalid config property: ${s}`);try{e[i][c]=d[c](n)}catch(l){throw l instanceof b?l:new b(`Invalid value for ${s}: ${l.message}`)}continue}if(i in Ae){a||(e[i]={});const d=Ae[i][c];if(!d)throw new b(`Invalid config property: ${s}`);e[i][c]=d(n)}else{const d=rt(i);if(!d[c])throw new b(`Invalid config property: ${s}`);e[i]||(e[i]={}),e[i][c]=d[c](n)}}const r=await ve(),o=S.dirname(r);await O.mkdir(o,{recursive:!0}),await O.writeFile(r,ye.stringify(e),"utf8")},aa=async()=>{const t=await Ie();console.log(ye.stringify(t))},ca=async()=>{console.log(await ve())},rt=t=>({compatible:e=>typeof e=="boolean"?e:e==null?!1:(k("compatible",/^(?:true|false)$/.test(e),"Must be a boolean(true or false)"),e==="true"),stream:e=>typeof e=="boolean"?e:e==null?!1:(k("stream",/^(?:true|false)$/.test(e),"Must be a boolean(true or false)"),e==="true"),url:e=>e?(k(`${t}.url`,/^https?:\/\//.test(e),"Must be a valid URL"),e):"",path:e=>e||"",key:e=>e||"",envKey:e=>e||"",model:e=>e?(typeof e=="string"?e?.split(","):e).map(o=>o.trim()).filter(o=>!!o&&o.length>0):[],systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,timeout:f.timeout,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,topP:f.topP,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode,disableLowerCase:f.disableLowerCase}),Re=new Map,ue=(t,e,r)=>{const o=Pr(0).update(e).digest("hex").substring(0,8),s=`${t}_${o}_${r}`;if(Re.has(s))return Re.get(s);const n=new Date,i=da(n,t,e,r),c=`${ee}/${i}`,a=U.createLogger({level:"info",format:U.format.combine(U.format.timestamp({format:"YYYY-MM-DDTHH:mm:ss.SSSZ"}),U.format.printf(({timestamp:m,level:d,message:l,...p})=>p&&Object.keys(p).length>0?`[${m}] ${d}: ${l} ${JSON.stringify(p,null,2)}`:`[${m}] ${d}: ${l}`)),transports:[new U.transports.File({filename:c})]});return a.info(`=== ${t.toUpperCase()} AI SERVICE LOG ===`),a.info(`Diff Hash: ${o}`),a.info(`Request Type: ${r.toUpperCase()}`),a.info(`Start Time: ${n.toISOString()}`),a.info("=".repeat(50)),a.info(""),Re.set(s,a),a},la=t=>{const e={...t},r=["authorization","x-api-key","x-goog-api-key","api-key"];for(const o of r){const s=o.toLowerCase(),n=Object.keys(e).find(i=>i.toLowerCase()===s);n&&e[n]&&typeof e[n]=="string"&&(e[n].startsWith("Bearer ")?e[n]="Bearer [MASKED]":e[n]="[MASKED]")}return e},Y=(t,e,r,o,s,n,i=!0)=>{if(!i)return;const c=ue(r,t,e);c.info(`Making request to ${r} API with model: ${o}`),c.info(`Request URL: ${s}`),c.info("Request headers:",la(n))},te=(t,e,r,o,s=!0)=>{if(!s)return;ue(r,t,e).info("Request payload:",o)},V=(t,e,r,o,s,n=!0)=>{if(!n)return;const i=ue(r,t,e);i.info("System prompt:",{prompt:o}),i.info("User prompt:",{prompt:s})},q=(t,e,r,o,s=!0)=>{if(!s)return;ue(r,t,e).info("Response received:",o)},_=(t,e,r,o,s=!0)=>{if(!s)return;ue(r,t,e).error("API request failed:",o)},z=(t,e,r,o,s,n=!0)=>{if(!n)return;const i=ue(r,t,e);o?i.info(`Request completed successfully in ${o}ms`):i.info("Request completed successfully"),s&&i.info("Final processed response:",{response:s}),i.info(""),i.info("=".repeat(50)),i.info(`End Time: ${new Date().toISOString()}`),i.info("=== REQUEST COMPLETED ===")},ua=(t,e,r,o,s,n,i,c=!0)=>{if(!c)return;const a=ue(r,t,e);i?a.error(`Request failed after ${n}ms:`,{error:i}):(a.info(`Request completed in ${n}ms`),a.info("Response:",{response:s})),z(t,e,r,n,s,c)},da=(t,e,r,o)=>{const{year:s,month:n,day:i,hours:c,minutes:a,seconds:m}=ma(t),l=Pr(0).update(r).digest("hex").substring(0,8),p=e.toLowerCase().replace(/[^a-z0-9]/g,"").substring(0,20);return o==="review"?`${s}-${n}-${i}_${c}-${a}-${m}_${l}_${p}_review.log`:`${s}-${n}-${i}_${c}-${a}-${m}_${l}_${p}_commit.log`},ma=t=>{const e=t.getFullYear().toString(),r=(t.getMonth()+1).toString().padStart(2,"0"),o=t.getDate().toString().padStart(2,"0"),s=t.getHours().toString().padStart(2,"0"),n=t.getMinutes().toString().padStart(2,"0"),i=t.getSeconds().toString().padStart(2,"0");return{year:e,month:r,day:o,hours:s,minutes:n,seconds:i}},Gt=()=>{for(const[t,e]of Re.entries())try{e.close()}catch(r){console.error(`Failed to close logger ${t}:`,r)}Re.clear()};process.on("exit",Gt),process.on("SIGINT",()=>{Gt(),process.exit(0)}),process.on("SIGTERM",()=>{Gt(),process.exit(0)});let ot;async function fa(t){if(ot){console.warn("Logger already initialized. Skipping re-initialization.");return}const e=t?.logLevel||"info",r=t?.logFilePath||po,o=t?.exceptionLogFilePath||ho,s=t?.logging??!0;await lo(S.dirname(r)),await lo(S.dirname(o));const n=[];s?n.push(new U.transports.DailyRotateFile({filename:r,datePattern:"YYYY-MM-DD",zippedArchive:!0,maxSize:"20m",maxFiles:"14d",level:e,format:U.format.combine(U.format.timestamp(),U.format.printf(({level:i,message:c,timestamp:a})=>`[${a}] ${i}: ${c}`))})):n.push(new U.transports.Console({silent:!0})),ot=U.createLogger({level:e,format:U.format.json(),transports:n,exceptionHandlers:s?[new U.transports.DailyRotateFile({filename:o,datePattern:"YYYY-MM-DD",zippedArchive:!0,maxSize:"20m",maxFiles:"14d",format:U.format.combine(U.format.timestamp(),U.format.json())})]:[],exitOnError:!1,silent:!s})}const be=new Proxy({},{get:(t,e,r)=>{if(!ot)throw new Error("Logger not initialized. Call initializeLogger() first.");return Reflect.get(ot,e,r)}});class X{constructor(e){this.handleError$=r=>{const o=this.getDetailedErrorMessage(r),s=r.status?`HTTP ${r.status}: ${o}`:o;if(this.params.config.logging){const n=this.params.stagedDiff.diff,i=this.serviceName.replace(/\[|\]/g,"").trim();ua(n,"commit",i,"Error occurred","",void 0,s)}return be.error(`${this.errorPrefix} ${s}`),r.stack&&be.error(` ${r.stack}`),r.content&&be.error(` Problematic content: ${r.content}`),r.originalError&&be.error(` Original error: ${r.originalError}`),dt({name:`${this.errorPrefix} ${s}`,value:s,isError:!0,disabled:!0})},this.serviceName="AI",this.errorPrefix="ERROR",this.colors={primary:""},this.params=e,this.logSessionId=e.logSessionId}getDetailedErrorMessage(e){const r=e.message||"";return r.includes("API key")||r.includes("api_key")?"Invalid API key. Check your API key configuration":r.includes("rate_limit")||r.includes("Rate limit")||r.includes("429")||r.includes("Too Many Requests")?"Rate limit exceeded. Wait a moment and try again, or upgrade your plan":r.includes("model")||r.includes("Model")?"Model not found or not accessible. Check if the model name is correct":r.includes("timeout")||r.includes("Timeout")?"Request timed out. Try again or increase the timeout setting":r.includes("network")||r.includes("connection")||r.includes("ECONNREFUSED")?"Network error. Check your internet connection and try again":r.includes("quota")||r.includes("usage")||r.includes("QUOTA_EXCEEDED")?"API quota exceeded. Check your usage limits":r.includes("401")||r.includes("Unauthorized")?"Authentication failed. Your API key may be invalid or expired":r.includes("403")||r.includes("Forbidden")?"Access denied. Your API key may not have permission for this model":r.includes("404")||r.includes("Not Found")?"Model or endpoint not found. Check your model configuration":r.includes("500")||r.includes("Internal Server Error")?"Server error. Try again later":r.includes("overloaded")||r.includes("capacity")||r.includes("SERVICE_UNAVAILABLE")||r.includes("unavailable")?"Service is temporarily unavailable. Try again in a few minutes":this.getServiceSpecificErrorMessage(e)||r||"Unknown error occurred"}getServiceSpecificErrorMessage(e){return null}cleanJsonCodeBlock(e){const r=/```(?:json|JSON)?\s*([\s\S]*?)\s*```/,o=e.match(r);return o?o[1].trim():e}parseMessage(e,r,o){const s=this.cleanJsonCodeBlock(e),n=/(\[\s*\{[\s\S]*?\}\s*\]|\{[\s\S]*?\})/,i=s.match(n);if(!i){const u=new Error("AI response did not contain a valid JSON object or array.");throw u.name="InvalidJsonResponse",u.content=e,u}const c=i[0],a=Zi(c);if(!a.ok){const u=new Error("Failed to parse AI response as JSON");throw u.name="JsonParseError",u.content=c,u.originalError=a.error,u}const m=a.data,d=Array.isArray(m)?m:[m];if(!d.length||!d.every(u=>typeof u.subject=="string")){const u=new Error("AI response contained malformed commit message data.");throw u.name="MalformedCommitMessage",u.content=e,u}const p=d.map(u=>this.extractMessageAsType(u,r)).map(u=>({title:`${u.subject}`,value:`${u.subject}${u.body?`
|
|
13
|
+
${Tt}${P.dim(`aicommit2 v${Sr}`)}`),console.error(`
|
|
14
|
+
${Tt}Please open a Bug report with the information above:`),console.error(`${Tt}https://github.com/tak-bro/aicommit2/issues/new/choose`)))},co=t=>O.lstat(t).then(()=>!0,()=>!1),lo=async t=>{try{await O.mkdir(t,{recursive:!0})}catch(e){if(e.code!=="EEXIST")throw e}},Qe=t=>t&&`${t[0].toUpperCase()}${t.slice(1)}`,Ze=(t,e)=>{const r=Math.ceil(t),o=Math.floor(e);return Math.floor(Math.random()*(o-r+1))+r},qi=(t,e)=>t.disabled&&!e.disabled?1:!t.disabled&&e.disabled?-1:0,et=t=>t.reduce((e,r)=>Array.isArray(r)?e.concat(et(r)):e.concat(r),[]),uo=(t,e=5)=>t.replace(/[\n\r]/g,"").split(" ").slice(0,e).join(" "),Xi=t=>{let e=0;for(let r=0;r<t.length;r++){const o=t.charCodeAt(r);e=(e<<5)-e+o,e=e&e}return Math.abs(e)},Qi=t=>{const e=t%360,r=65+t%15,o=45+t%10;return`hsl(${e}, ${r}%, ${o}%)`},Zi=t=>{const[e,r,o]=t.match(/\d+/g).map((l,p)=>p===0?Number(l):Number(l)/100),s=(1-Math.abs(2*o-1))*r,n=s*(1-Math.abs(e/60%2-1)),i=o-s/2;let c,a,m;e<60?[c,a,m]=[s,n,0]:e<120?[c,a,m]=[n,s,0]:e<180?[c,a,m]=[0,s,n]:e<240?[c,a,m]=[0,n,s]:e<300?[c,a,m]=[n,0,s]:[c,a,m]=[s,0,n];const d=l=>{const p=Math.round((l+i)*255).toString(16);return p.length===1?"0"+p:p};return`#${d(c)}${d(a)}${d(m)}`},ea=t=>{const e=Xi(t),r=Qi(e);return{primary:Zi(r),secondary:"#FFFFFF"}},ta=t=>{try{return{ok:!0,data:JSON.parse(t)}}catch(e){return{ok:!1,error:e}}},tt=t=>{if(!t||typeof t!="string")return"";if(x.isAbsolute(t))return x.resolve(t);if(Me){const e=x.dirname(Me),r=x.join(e,t);return x.resolve(r)}else return""},ra=["","conventional","gitmoji"],Ft="http://localhost:11434",{hasOwnProperty:oa}=Object.prototype,Nt=(t,e)=>oa.call(t,e),we=["OPENAI","OLLAMA","HUGGINGFACE","GEMINI","ANTHROPIC","MISTRAL","CODESTRAL","COHERE","GROQ","PERPLEXITY","DEEPSEEK","GITHUB_MODELS"],mo=t=>{const e=Ee.platform(),r=Ee.homedir();let o,s;switch(t){case"config":o=process.env.XDG_CONFIG_HOME;break;case"data":o=process.env.XDG_DATA_HOME;break;case"cache":o=process.env.XDG_CACHE_HOME;break;case"state":o=process.env.XDG_STATE_HOME;break;default:o=void 0}if(e==="darwin")t==="cache"?s=x.join(r,"Library","Caches"):s=x.join(r,"Library","Application Support");else if(e==="win32")s=process.env.LOCALAPPDATA||r;else switch(t){case"config":s=x.join(r,".config");break;case"data":s=x.join(r,".local","share");break;case"cache":s=x.join(r,".cache");break;case"state":s=x.join(r,".local","state");break;default:s=r}return o||s},sa=x.join(mo("config"),"aicommit2"),ee=x.join(mo("state"),"aicommit2","logs"),fo=x.join(sa,"config.ini"),po=x.join(ee,"aicommit2-%DATE%.log"),ho=x.join(ee,"exceptions-%DATE%.log"),na=t=>{const e=Object.keys(t),r=new Set([...we,...e.filter(o=>/^[A-Z][A-Z0-9_]*$/.test(o))]);return Array.from(r)},k=(t,e,r)=>{if(!e)throw new b(`Invalid config property ${t}: ${r}`)},f={systemPrompt(t){return t||""},systemPromptPath(t){return t||""},codeReviewPromptPath(t){return t||""},timeout(t){if(!t)return 1e4;k("timeout",/^\d+$/.test(t),"Must be an integer");const e=Number(t);return k("timeout",e>=500,"Must be greater than 500ms"),e},temperature(t){if(!t)return .7;k("temperature",/^(2|\d)(\.\d{1,2})?$/.test(t),"Must be decimal between 0 and 2");const e=Number(t);return k("temperature",e>0,"Must be greater than 0"),k("temperature",e<=2,"Must be less than or equal to 2"),e},maxTokens(t){return t?(k("maxTokens",/^\d+$/.test(t),"Must be an integer"),Number(t)):1024},logging(t){return typeof t=="boolean"?t:t==null?!0:(k("logging",/^(?:true|false)$/.test(t),"Must be a boolean(true or false)"),t==="true")},logLevel(t){return t?(k("logLevel",/^(?:error|warn|info|http|verbose|debug|silly)$/.test(t),"Must be a valid log level (error, warn, info, http, verbose, debug, silly)"),t):"info"},logFilePath(t){return t||po},exceptionLogFilePath(t){return t||ho},locale(t){return t?(k("locale",t,"Cannot be empty"),k("locale",/^[a-z-]+$/i.test(t),"Must be a valid locale (letters and dashes/underscores). You can consult the list of codes in: https://wikipedia.org/wiki/List_of_ISO_639-1_codes"),t):"en"},generate(t){if(!t)return 1;k("generate",/^\d+$/.test(t),"Must be an integer");const e=Number(t);return k("generate",e>0,"Must be greater than 0"),k("generate",e<=5,"Must be less or equal to 5"),e},type(t){return t?(k("type",ra.includes(t),"Invalid commit type"),t):"conventional"},maxLength(t){if(!t)return 50;k("maxLength",/^\d+$/.test(t),"Must be an integer");const e=Number(t);return k("maxLength",e>=20,"Must be greater than 20 characters"),e},includeBody(t){return typeof t=="boolean"?t:t==null?!1:(k("includeBody",/^(?:true|false)$/.test(t),"Must be a boolean(true or false)"),t==="true")},exclude:t=>t?(typeof t=="string"?t?.split(","):t).map(r=>r.trim()).filter(r=>!!r&&r.length>0):[],topP:t=>{if(!t)return .9;k("topP",/^(1|\d)(\.\d{1,2})?$/.test(t),"Must be decimal between 0 and 1");const e=Number(t);return k("topP",e>0,"Must be greater than 0"),k("topP",e<=1,"Must be less than or equal to 1"),e},codeReview(t){return typeof t=="boolean"?t:t==null?!1:(k("codeReview",/^(?:true|false)$/.test(t),"Must be a boolean(true or false)"),t==="true")},disabled(t){return typeof t=="boolean"?t:t==null?!1:(k("disabled",/^(?:true|false)$/.test(t),"Must be a boolean(true or false)"),t==="true")},watchMode(t){return typeof t=="boolean"?t:t==null?!1:(k("watchMode",/^(?:true|false)$/.test(t),"Must be a boolean(true or false)"),t==="true")},forceGit(t){return typeof t=="boolean"?t:t==null?!1:(k("forceGit",/^(?:true|false)$/.test(t),"Must be a boolean(true or false)"),t==="true")},disableLowerCase(t){return typeof t=="boolean"?t:t==null?!1:(k("disableLowerCase",/^(?:true|false)$/.test(t),"Must be a boolean(true or false)"),t==="true")}},Se={OPENAI:{key:t=>t||"",envKey:t=>t||"",model:t=>t?(typeof t=="string"?t?.split(","):t).map(r=>r.trim()).filter(r=>!!r&&r.length>0):["gpt-4o-mini"],url:t=>t?(k("OPENAI.url",/^https?:\/\//.test(t),"Must be a valid URL"),t):"https://api.openai.com",path:t=>t||"/v1/chat/completions",proxy:t=>t||"",topP:f.topP,systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,timeout:f.timeout,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode,disableLowerCase:f.disableLowerCase},HUGGINGFACE:{cookie:t=>t||"",model:t=>t?(typeof t=="string"?t?.split(","):t).map(r=>r.trim()).filter(r=>!!r&&r.length>0):["CohereForAI/c4ai-command-r-plus"],systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,timeout:f.timeout,temperature:f.temperature,maxTokens:f.maxTokens,topP:f.topP,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode,disableLowerCase:f.disableLowerCase},GEMINI:{key:t=>t||"",envKey:t=>t||"",model:t=>t?(typeof t=="string"?t?.split(","):t).map(r=>r.trim()).filter(r=>!!r&&r.length>0):["gemini-2.0-flash"],systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,topP:f.topP,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode,disableLowerCase:f.disableLowerCase},ANTHROPIC:{key:t=>t||"",envKey:t=>t||"",model:t=>t?(typeof t=="string"?t?.split(","):t).map(r=>r.trim()).filter(r=>!!r&&r.length>0):["claude-3-5-haiku-20241022"],systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,topP:f.topP,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode,disableLowerCase:f.disableLowerCase},MISTRAL:{key:t=>t||"",envKey:t=>t||"",model:t=>t?(typeof t=="string"?t?.split(","):t).map(r=>r.trim()).filter(r=>!!r&&r.length>0):["mistral-small-latest"],systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,timeout:f.timeout,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,topP:f.topP,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode,disableLowerCase:f.disableLowerCase},CODESTRAL:{key:t=>t||"",envKey:t=>t||"",model:t=>t?(typeof t=="string"?t?.split(","):t).map(r=>r.trim()).filter(r=>!!r&&r.length>0):["codestral-latest"],topP:f.topP,systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,timeout:f.timeout,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode,disableLowerCase:f.disableLowerCase},OLLAMA:{model:t=>t?(typeof t=="string"?t?.split(","):t).map(r=>r.trim()).filter(r=>!!r&&r.length>0):[],host:t=>t?(k("OLLAMA.host",/^https?:\/\//.test(t),"Must be a valid URL"),t):Ft,timeout:t=>{if(!t)return 1e5;k("OLLAMA.timeout",/^\d+$/.test(t),"Must be an integer");const e=Number(t);return k("OLLAMA.timeout",e>=500,"Must be greater than 500ms"),e},auth:t=>t||"",key:t=>t||"",envKey:t=>t||"",numCtx:t=>{if(!t)return 2048;k("OLLAMA.numCtx",/^\d+$/.test(t),"Must be an integer");const e=Number(t);return k("OLLAMA.numCtx",e>=2048,"Must be greater than 2048"),e},systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,topP:f.topP,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode,disableLowerCase:f.disableLowerCase},COHERE:{key:t=>t||"",envKey:t=>t||"",model:t=>t?(typeof t=="string"?t?.split(","):t).map(r=>r.trim()).filter(r=>!!r&&r.length>0):["command-r"],systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,topP:f.topP,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode,disableLowerCase:f.disableLowerCase},GROQ:{key:t=>t||"",envKey:t=>t||"",model:t=>t?(typeof t=="string"?t?.split(","):t).map(r=>r.trim()).filter(r=>!!r&&r.length>0):["llama-3.3-70b-versatile"],systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,timeout:f.timeout,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,topP:f.topP,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode,disableLowerCase:f.disableLowerCase},PERPLEXITY:{key:t=>t||"",envKey:t=>t||"",model:t=>t?(typeof t=="string"?t?.split(","):t).map(r=>r.trim()).filter(r=>!!r&&r.length>0):["sonar"],topP:f.topP,systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,timeout:f.timeout,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode,disableLowerCase:f.disableLowerCase},DEEPSEEK:{key:t=>t||"",envKey:t=>t||"",model:t=>t?(typeof t=="string"?t?.split(","):t).map(r=>r.trim()).filter(r=>!!r&&r.length>0):["deepseek-coder"],topP:f.topP,systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,timeout:f.timeout,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode,disableLowerCase:f.disableLowerCase},GITHUB_MODELS:{key:t=>t||"",envKey:t=>t||"",model:t=>t?(typeof t=="string"?t?.split(","):t).map(r=>r.trim()).filter(r=>!!r&&r.length>0):["gpt-4o-mini"],systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,timeout:f.timeout,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,topP:f.topP,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode,disableLowerCase:f.disableLowerCase}};let Me;const ia=(t=[])=>{const e={};for(const r of t)if(r.startsWith("--")){const[o,s]=r.slice(2).split("="),[n,i]=o.split(".");n&&i&&n in Se?(e[n]||(e[n]={}),e[n][i]=s):e[o]=s}return e},aa=()=>{const t=Ee.homedir(),e=process.env.AICOMMIT_CONFIG_PATH,r=fo,o=x.join(t,".aicommit2");return[e,r,o].filter(s=>!!s)},ve=async()=>{const t=aa();for(const e of t)if(await co(e))return e;return fo},Ie=async()=>{const t=await ve();Me=t;try{const e=await O.readFile(t,"utf8");return ye.parse(e)}catch(e){return e.code==="ENOENT"?(Me=void 0,{}):(console.error(`Error reading config file ${t}:`,e),Me=void 0,{})}},le=async(t,e=[])=>{const r=await Ie(),o=ia(e),s={...t,...o},n={},i=na(r),c={};for(const m of i){const l=r[m]?.envKey||`${m}_API_KEY`,p=process.env[l];p&&(c[m]={key:p})}const a=(m,d)=>{const l=s[`${m}.${d}`]??s[m]?.[d],p=c[m]?.[d],u=r[m]?.[d],h=s[d]??r[d];return l!==void 0?l:p!==void 0?p:u!==void 0?u:h};for(const[m,d]of Object.entries(f)){const l=s[m]??r[m];n[m]=d(l)}for(const m of i){n[m]={};const d=Se[m]||rt(m);for(const[l,p]of Object.entries(d)){const u=a(m,l);n[m][l]=p(u)}}return n},jt=async t=>{const e=await Ie();for(const[s,n]of t){const[i,c]=s.split(".");if(!c){const d=f[s];if(!d)throw new b(`Invalid config property: ${s}`);e[s]=d(n);continue}if(e[i]||(e[i]={}),we.includes(i)){const d=Se[i][c];if(!d)throw new b(`Invalid config property: ${s}`);e[i][c]=d(n);continue}if(!/^[A-Z][A-Z0-9_]*$/.test(i))throw new b(`Invalid service name: ${i}. Service names must be uppercase letters, numbers, and underscores.`);const m=rt(i);if(!m[c])throw new b(`Invalid config property for custom service: ${s}`);try{e[i][c]=m[c](n)}catch(d){throw d instanceof b?d:new b(`Invalid value for ${s}: ${d.message}`)}}const r=await ve(),o=x.dirname(r);await O.mkdir(o,{recursive:!0}),await O.writeFile(r,ye.stringify(e),"utf8")},ca=async t=>{const e=await Ie();for(const[s,n]of t){const[i,c]=s.split("."),a=e[i];if(c==="model"){a||(e[i]={});const d=e[i][c]||[],l=typeof n=="string"?n.split(",").map(p=>p.trim()).filter(p=>!!p):n;e[i][c]=et([...d,...l]);continue}if(a&&a.compatible===!0){a||(e[i]={});const d=rt(i);if(!d[c])throw new b(`Invalid config property: ${s}`);try{e[i][c]=d[c](n)}catch(l){throw l instanceof b?l:new b(`Invalid value for ${s}: ${l.message}`)}continue}if(i in Se){a||(e[i]={});const d=Se[i][c];if(!d)throw new b(`Invalid config property: ${s}`);e[i][c]=d(n)}else{const d=rt(i);if(!d[c])throw new b(`Invalid config property: ${s}`);e[i]||(e[i]={}),e[i][c]=d[c](n)}}const r=await ve(),o=x.dirname(r);await O.mkdir(o,{recursive:!0}),await O.writeFile(r,ye.stringify(e),"utf8")},la=async()=>{const t=await Ie();console.log(ye.stringify(t))},ua=async()=>{console.log(await ve())},rt=t=>({compatible:e=>typeof e=="boolean"?e:e==null?!1:(k("compatible",/^(?:true|false)$/.test(e),"Must be a boolean(true or false)"),e==="true"),stream:e=>typeof e=="boolean"?e:e==null?!1:(k("stream",/^(?:true|false)$/.test(e),"Must be a boolean(true or false)"),e==="true"),url:e=>e?(k(`${t}.url`,/^https?:\/\//.test(e),"Must be a valid URL"),e):"",path:e=>e||"",key:e=>e||"",envKey:e=>e||"",model:e=>e?(typeof e=="string"?e?.split(","):e).map(o=>o.trim()).filter(o=>!!o&&o.length>0):[],systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,timeout:f.timeout,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,topP:f.topP,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode,disableLowerCase:f.disableLowerCase}),Re=new Map,ue=(t,e,r)=>{const o=Cr(0).update(e).digest("hex").substring(0,8),s=`${t}_${o}_${r}`;if(Re.has(s))return Re.get(s);const n=new Date,i=fa(n,t,e,r),c=`${ee}/${i}`,a=B.createLogger({level:"info",format:B.format.combine(B.format.timestamp({format:"YYYY-MM-DDTHH:mm:ss.SSSZ"}),B.format.printf(({timestamp:m,level:d,message:l,...p})=>p&&Object.keys(p).length>0?`[${m}] ${d}: ${l} ${JSON.stringify(p,null,2)}`:`[${m}] ${d}: ${l}`)),transports:[new B.transports.File({filename:c})]});return a.info(`=== ${t.toUpperCase()} AI SERVICE LOG ===`),a.info(`Diff Hash: ${o}`),a.info(`Request Type: ${r.toUpperCase()}`),a.info(`Start Time: ${n.toISOString()}`),a.info("=".repeat(50)),a.info(""),Re.set(s,a),a},da=t=>{const e={...t},r=["authorization","x-api-key","x-goog-api-key","api-key"];for(const o of r){const s=o.toLowerCase(),n=Object.keys(e).find(i=>i.toLowerCase()===s);n&&e[n]&&typeof e[n]=="string"&&(e[n].startsWith("Bearer ")?e[n]="Bearer [MASKED]":e[n]="[MASKED]")}return e},Y=(t,e,r,o,s,n,i=!0)=>{if(!i)return;const c=ue(r,t,e);c.info(`Making request to ${r} API with model: ${o}`),c.info(`Request URL: ${s}`),c.info("Request headers:",da(n))},te=(t,e,r,o,s=!0)=>{if(!s)return;ue(r,t,e).info("Request payload:",o)},V=(t,e,r,o,s,n=!0)=>{if(!n)return;const i=ue(r,t,e);i.info("System prompt:",{prompt:o}),i.info("User prompt:",{prompt:s})},q=(t,e,r,o,s=!0)=>{if(!s)return;ue(r,t,e).info("Response received:",o)},_=(t,e,r,o,s=!0)=>{if(!s)return;ue(r,t,e).error("API request failed:",o)},z=(t,e,r,o,s,n=!0)=>{if(!n)return;const i=ue(r,t,e);o?i.info(`Request completed successfully in ${o}ms`):i.info("Request completed successfully"),s&&i.info("Final processed response:",{response:s}),i.info(""),i.info("=".repeat(50)),i.info(`End Time: ${new Date().toISOString()}`),i.info("=== REQUEST COMPLETED ===")},ma=(t,e,r,o,s,n,i,c=!0)=>{if(!c)return;const a=ue(r,t,e);i?a.error(`Request failed after ${n}ms:`,{error:i}):(a.info(`Request completed in ${n}ms`),a.info("Response:",{response:s})),z(t,e,r,n,s,c)},fa=(t,e,r,o)=>{const{year:s,month:n,day:i,hours:c,minutes:a,seconds:m}=pa(t),l=Cr(0).update(r).digest("hex").substring(0,8),p=e.toLowerCase().replace(/[^a-z0-9]/g,"").substring(0,20);return o==="review"?`${s}-${n}-${i}_${c}-${a}-${m}_${l}_${p}_review.log`:`${s}-${n}-${i}_${c}-${a}-${m}_${l}_${p}_commit.log`},pa=t=>{const e=t.getFullYear().toString(),r=(t.getMonth()+1).toString().padStart(2,"0"),o=t.getDate().toString().padStart(2,"0"),s=t.getHours().toString().padStart(2,"0"),n=t.getMinutes().toString().padStart(2,"0"),i=t.getSeconds().toString().padStart(2,"0");return{year:e,month:r,day:o,hours:s,minutes:n,seconds:i}},_t=()=>{for(const[t,e]of Re.entries())try{e.close()}catch(r){console.error(`Failed to close logger ${t}:`,r)}Re.clear()};process.on("exit",_t),process.on("SIGINT",()=>{_t(),process.exit(0)}),process.on("SIGTERM",()=>{_t(),process.exit(0)});let ot;async function ha(t){if(ot){console.warn("Logger already initialized. Skipping re-initialization.");return}const e=t?.logLevel||"info",r=t?.logFilePath||po,o=t?.exceptionLogFilePath||ho,s=t?.logging??!0;await lo(x.dirname(r)),await lo(x.dirname(o));const n=[];s?n.push(new B.transports.DailyRotateFile({filename:r,datePattern:"YYYY-MM-DD",zippedArchive:!0,maxSize:"20m",maxFiles:"14d",level:e,format:B.format.combine(B.format.timestamp(),B.format.printf(({level:i,message:c,timestamp:a})=>`[${a}] ${i}: ${c}`))})):n.push(new B.transports.Console({silent:!0})),ot=B.createLogger({level:e,format:B.format.json(),transports:n,exceptionHandlers:s?[new B.transports.DailyRotateFile({filename:o,datePattern:"YYYY-MM-DD",zippedArchive:!0,maxSize:"20m",maxFiles:"14d",format:B.format.combine(B.format.timestamp(),B.format.json())})]:[],exitOnError:!1,silent:!s})}const be=new Proxy({},{get:(t,e,r)=>{if(!ot)throw new Error("Logger not initialized. Call initializeLogger() first.");return Reflect.get(ot,e,r)}});class X{constructor(e){this.handleError$=r=>{const o=this.getDetailedErrorMessage(r),s=r.status?`HTTP ${r.status}: ${o}`:o;if(this.params.config.logging){const n=this.params.stagedDiff.diff,i=this.serviceName.replace(/\[|\]/g,"").trim();ma(n,"commit",i,"Error occurred","",void 0,s)}return be.error(`${this.errorPrefix} ${s}`),r.stack&&be.error(` ${r.stack}`),r.content&&be.error(` Problematic content: ${r.content}`),r.originalError&&be.error(` Original error: ${r.originalError}`),dt({name:`${this.errorPrefix} ${s}`,value:s,isError:!0,disabled:!0})},this.serviceName="AI",this.errorPrefix="ERROR",this.colors={primary:""},this.params=e,this.logSessionId=e.logSessionId}getDetailedErrorMessage(e){const r=e.message||"";return r.includes("API key")||r.includes("api_key")?"Invalid API key. Check your API key configuration":r.includes("rate_limit")||r.includes("Rate limit")||r.includes("429")||r.includes("Too Many Requests")?"Rate limit exceeded. Wait a moment and try again, or upgrade your plan":r.includes("model")||r.includes("Model")?"Model not found or not accessible. Check if the model name is correct":r.includes("timeout")||r.includes("Timeout")?"Request timed out. Try again or increase the timeout setting":r.includes("network")||r.includes("connection")||r.includes("ECONNREFUSED")?"Network error. Check your internet connection and try again":r.includes("quota")||r.includes("usage")||r.includes("QUOTA_EXCEEDED")?"API quota exceeded. Check your usage limits":r.includes("401")||r.includes("Unauthorized")?"Authentication failed. Your API key may be invalid or expired":r.includes("403")||r.includes("Forbidden")?"Access denied. Your API key may not have permission for this model":r.includes("404")||r.includes("Not Found")?"Model or endpoint not found. Check your model configuration":r.includes("500")||r.includes("Internal Server Error")?"Server error. Try again later":r.includes("overloaded")||r.includes("capacity")||r.includes("SERVICE_UNAVAILABLE")||r.includes("unavailable")?"Service is temporarily unavailable. Try again in a few minutes":this.getServiceSpecificErrorMessage(e)||r||"Unknown error occurred"}getServiceSpecificErrorMessage(e){return null}cleanJsonCodeBlock(e){const r=/```(?:json|JSON)?\s*([\s\S]*?)\s*```/,o=e.match(r);return o?o[1].trim():e}parseMessage(e,r,o){const s=this.cleanJsonCodeBlock(e),n=/(\[\s*\{[\s\S]*?\}\s*\]|\{[\s\S]*?\})/,i=s.match(n);if(!i){const u=new Error("AI response did not contain a valid JSON object or array.");throw u.name="InvalidJsonResponse",u.content=e,u}const c=i[0],a=ta(c);if(!a.ok){const u=new Error("Failed to parse AI response as JSON");throw u.name="JsonParseError",u.content=c,u.originalError=a.error,u}const m=a.data,d=Array.isArray(m)?m:[m];if(!d.length||!d.every(u=>typeof u.subject=="string")){const u=new Error("AI response contained malformed commit message data.");throw u.name="MalformedCommitMessage",u.content=e,u}const p=d.map(u=>this.extractMessageAsType(u,r)).map(u=>({title:`${u.subject}`,value:`${u.subject}${u.body?`
|
|
15
15
|
|
|
16
16
|
${u.body}`:""}${u.footer?`
|
|
17
17
|
|
|
18
|
-
${u.footer}`:""}`})).slice(0,o);if(this.isLoggingEnabled()){const u=p.map(h=>h.title).join(", ");be.info(`${this.serviceName} Parsed ${p.length} commit messages: ${u}`)}return p}extractMessageAsType(e,r){switch(r){case"conventional":const o=/(\w+)(?:\(.*?\))?:\s*(.*)/,s=e.subject.match(o),n=s?s[0]:e.subject;return{...e,subject:this.normalizeCommitMessage(n)};case"gitmoji":const i=/:\w*:\s*(.*)/,c=e.subject.match(i),a=this.params.config.disableLowerCase??!1;return{...e,subject:c&&!a?c[0].toLowerCase():e.subject};default:return e}}normalizeCommitMessage(e){const r=/^(\w+)(\(.*?\))?:\s(.*)$/,o=e.match(r);if(o){const[,s,n,i]=o,c=this.params.config.disableLowerCase??!1,a=s.toLowerCase(),m=c?i:i.charAt(0).toLowerCase()+i.slice(1);e=`${a}${n||""}: ${m}`}return e}sanitizeResponse(e){if(typeof e=="string")try{return[{title:`${uo(e)}...`,value:e}]}catch{return[]}return e.map(r=>{try{return{title:`${uo(r)}...`,value:r}}catch{return{title:"",value:""}}})}isLoggingEnabled(){return this.params.config.logging&&!!this.logSessionId}}const
|
|
18
|
+
${u.footer}`:""}`})).slice(0,o);if(this.isLoggingEnabled()){const u=p.map(h=>h.title).join(", ");be.info(`${this.serviceName} Parsed ${p.length} commit messages: ${u}`)}return p}extractMessageAsType(e,r){switch(r){case"conventional":const o=/(\w+)(?:\(.*?\))?:\s*(.*)/,s=e.subject.match(o),n=s?s[0]:e.subject;return{...e,subject:this.normalizeCommitMessage(n)};case"gitmoji":const i=/:\w*:\s*(.*)/,c=e.subject.match(i),a=this.params.config.disableLowerCase??!1;return{...e,subject:c&&!a?c[0].toLowerCase():e.subject};default:return e}}normalizeCommitMessage(e){const r=/^(\w+)(\(.*?\))?:\s(.*)$/,o=e.match(r);if(o){const[,s,n,i]=o,c=this.params.config.disableLowerCase??!1,a=s.toLowerCase(),m=c?i:i.charAt(0).toLowerCase()+i.slice(1);e=`${a}${n||""}: ${m}`}return e}sanitizeResponse(e){if(typeof e=="string")try{return[{title:`${uo(e)}...`,value:e}]}catch{return[]}return e.map(r=>{try{return{title:`${uo(r)}...`,value:r}}catch{return{title:"",value:""}}})}isLoggingEnabled(){return this.params.config.logging&&!!this.logSessionId}}const K={locale:"en",maxLength:50,type:"conventional",generate:1,systemPrompt:"",systemPromptPath:"",codeReviewPromptPath:""},ga={"":"<commit message>",conventional:`<type>(<optional scope>): <description>
|
|
19
19
|
|
|
20
20
|
[optional body]
|
|
21
21
|
|
|
@@ -23,14 +23,11 @@ ${u.footer}`:""}`})).slice(0,o);if(this.isLoggingEnabled()){const u=p.map(h=>h.t
|
|
|
23
23
|
|
|
24
24
|
[optional body]
|
|
25
25
|
|
|
26
|
-
[optional footer(s)]
|
|
27
|
-
|
|
28
|
-
[optional detailed explanation]`},ha={"":"",jujutsu:"",gitmoji:`
|
|
26
|
+
[optional footer(s)]`},ya={"":"",gitmoji:`
|
|
29
27
|
${Object.entries({":sparkles:":"Introduce new features.",":bug:":"Fix a bug.",":memo:":"Add or update documentation.",":art:":"Improve structure / format of the code.",":zap:":"Improve performance.",":fire:":"Remove code or files.",":ambulance:":"Critical hotfix.",":white_check_mark:":"Add, update, or pass tests.",":lock:":"Fix security or privacy issues.",":rocket:":"Deploy stuff.",":lipstick:":"Add or update the UI and style files.",":tada:":"Begin a project.",":recycle:":"Refactor code.",":wrench:":"Add or update configuration files.",":bulb:":"Add or update comments in source code.",":twisted_rightwards_arrows:":"Merge branches."}).map(([t,e])=>` - ${t}: ${e}`).join(`
|
|
30
28
|
`)}`,conventional:`
|
|
31
29
|
${Object.entries({docs:"Documentation only changes",style:"Changes that do not affect the meaning of the code (white-space, formatting, missing semi-colons, etc)",refactor:"A code change that neither fixes a bug nor adds a feature",perf:"A code change that improves performance",test:"Adding missing tests or correcting existing tests",build:"Changes that affect the build system or external dependencies",ci:"Changes to CI configuration files, scripts",chore:"Other changes that don't modify src or test files",revert:"Reverts a previous commit",feat:"A new feature",fix:"A bug fix"}).map(([t,e])=>` - ${t}: ${e}`).join(`
|
|
32
|
-
`)}`},go=(t,e)=>t.replace(/{(\w+)}/g,(r,o)=>e[o]?.toString()||
|
|
33
|
-
`):["## Requirements:",`1. Language: Write all messages in ${s}`,`2. Format: Strictly follow the ${e} commit format:`,`${pa[e]}`,`3. Allowed Types:${ha[e]}`,"","## Guidelines:",`- Subject line: Max ${r} characters, imperative mood, no period`,"- Analyze the diff to understand:"," * What files were changed"," * What functionality was added, modified, or removed"," * The scope and impact of changes","- For the commit type, choose based on:"," * feat: New functionality or feature"," * fix: Bug fixes or error corrections"," * refactor: Code restructuring without changing functionality"," * docs: Documentation changes only"," * style: Formatting, missing semi-colons, etc"," * test: Adding or modifying tests"," * chore: Maintenance tasks, dependency updates"," * perf: Performance improvements"," * build: Build system or external dependency changes"," * ci: CI configuration changes","- Scope: Extract from file paths or logical grouping (e.g., auth, api, ui)","- Body (when needed):"," * Explain the motivation for the change"," * Compare previous behavior with new behavior"," * Note any breaking changes or important details","- Footer: Include references to issues, breaking changes if applicable","","## Analysis Approach:","1. Identify the primary purpose of the changes","2. Group related changes together","3. Determine the most appropriate type and scope","4. Write a clear, concise subject line","5. Add body details for complex changes","","Remember: The commit message should help future developers understand WHY this change was made, not just WHAT was changed."].join(`
|
|
30
|
+
`)}`},go=(t,e)=>t.replace(/{(\w+)}/g,(r,o)=>e[o]?.toString()||K[o]?.toString()),yo=t=>{const{type:e,maxLength:r,generate:o,locale:s}=t,n="You are an expert Git commit message writer specializing in analyzing code changes and creating precise, meaningful commit messages.",i=`Your task is to generate exactly ${o} ${e} style commit message${o!==1?"s":""} based on the provided git diff.`;return[n,i,"",["## Requirements:",`1. Language: Write all messages in ${s}`,`2. Format: Strictly follow the ${e} commit format:`,`${ga[e]}`,`3. Allowed Types:${ya[e]}`,"","## Guidelines:",`- Subject line: Max ${r} characters, imperative mood, no period`,"- Analyze the diff to understand:"," * What files were changed"," * What functionality was added, modified, or removed"," * The scope and impact of changes","- For the commit type, choose based on:"," * feat: New functionality or feature"," * fix: Bug fixes or error corrections"," * refactor: Code restructuring without changing functionality"," * docs: Documentation changes only"," * style: Formatting, missing semi-colons, etc"," * test: Adding or modifying tests"," * chore: Maintenance tasks, dependency updates"," * perf: Performance improvements"," * build: Build system or external dependency changes"," * ci: CI configuration changes","- Scope: Extract from file paths or logical grouping (e.g., auth, api, ui)","- Body (when needed):"," * Explain the motivation for the change"," * Compare previous behavior with new behavior"," * Note any breaking changes or important details","- Footer: Include references to issues, breaking changes if applicable","","## Analysis Approach:","1. Identify the primary purpose of the changes","2. Group related changes together","3. Determine the most appropriate type and scope","4. Write a clear, concise subject line","5. Add body details for complex changes","","Remember: The commit message should help future developers understand WHY this change was made, not just WHAT was changed."].join(`
|
|
34
31
|
`)].filter(Boolean).join(`
|
|
35
32
|
`)},st=(t,e)=>{const r=o=>o==="conventional"?`${Array(e).fill(null).map((s,n)=>`
|
|
36
33
|
{
|
|
@@ -43,13 +40,12 @@ ${Object.entries({docs:"Documentation only changes",style:"Changes that do not a
|
|
|
43
40
|
"body": "- Implement WebSocket connection\\n- Add message encryption\\n- Include typing indicators",
|
|
44
41
|
"footer": ""
|
|
45
42
|
}`).join(",")}`:"";return[`
|
|
46
|
-
Lastly, Provide your response as a JSON array containing exactly ${e} object${e!==1?"s":""}, each with the following keys:`,`- "subject": The main commit message using the ${t} style. It should be a concise summary of the changes.`,'- "body": An optional detailed explanation of the changes. If not needed, use an empty string.','- "footer": An optional footer for metadata like BREAKING CHANGES. If not needed, use an empty string.',`The array must always contain ${e} element${e!==1?"s":""}, no more and no less
|
|
47
|
-
`:`Example response format:
|
|
43
|
+
Lastly, Provide your response as a JSON array containing exactly ${e} object${e!==1?"s":""}, each with the following keys:`,`- "subject": The main commit message using the ${t} style. It should be a concise summary of the changes.`,'- "body": An optional detailed explanation of the changes. If not needed, use an empty string.','- "footer": An optional footer for metadata like BREAKING CHANGES. If not needed, use an empty string.',`The array must always contain ${e} element${e!==1?"s":""}, no more and no less.`,`Example response format:
|
|
48
44
|
[${r(t)}
|
|
49
45
|
]`,`Ensure you generate exactly ${e} commit message${e!==1?"s":""}, even if it requires creating slightly varied versions for similar changes.`,"The response should be valid JSON that can be parsed without errors."].filter(Boolean).join(`
|
|
50
46
|
`)},Q=t=>{const{systemPrompt:e,systemPromptPath:r,type:o,generate:s}=t;if(e)return`${e}
|
|
51
47
|
${st(o,s)}`;if(!r)return`${yo(t)}
|
|
52
|
-
${st(o,s)}`;try{const n=
|
|
48
|
+
${st(o,s)}`;try{const n=U.readFileSync(tt(r),"utf-8");return`${go(n,t)}
|
|
53
49
|
${st(o,s)}`}catch{return`${yo(t)}
|
|
54
50
|
${st(o,s)}`}},Z=t=>{const{codeReviewPromptPath:e,locale:r}=t,o=`I'll give you the output of the "git diff" command as an input. Please review the following code and provide your feedback in Markdown format. Focus on:
|
|
55
51
|
|
|
@@ -59,7 +55,7 @@ ${st(o,s)}`}},Z=t=>{const{codeReviewPromptPath:e,locale:r}=t,o=`I'll give you th
|
|
|
59
55
|
4. Performance improvements
|
|
60
56
|
5. Readability and maintainability
|
|
61
57
|
|
|
62
|
-
Please structure your response with appropriate Markdown headings, code blocks, and bullet points.`;if(!e)return o;try{const s=
|
|
58
|
+
Please structure your response with appropriate Markdown headings, code blocks, and bullet points.`;if(!e)return o;try{const s=U.readFileSync(tt(e),"utf-8");return`${go(s,t)}`}catch{return o}},wo=async t=>{if(t.systemPromptPath)try{U.readFileSync(tt(t.systemPromptPath),"utf-8")}catch(e){throw new b(`Error reading system prompt file: ${t.systemPromptPath}, ${e}`)}if(t.codeReview&&t.codeReviewPromptPath)try{U.readFileSync(tt(t.codeReviewPromptPath),"utf-8")}catch(e){throw new b(`Error reading code review prompt file: ${t.codeReviewPromptPath}, ${e}`)}},Ce=(t,e="commit")=>e==="review"?`Please analyze the following diff and provide a comprehensive code review:
|
|
63
59
|
|
|
64
60
|
\`\`\`diff
|
|
65
61
|
${t}
|
|
@@ -71,46 +67,46 @@ Focus on code quality, potential issues, and improvement suggestions.`:`Please a
|
|
|
71
67
|
${t}
|
|
72
68
|
\`\`\`
|
|
73
69
|
|
|
74
|
-
Focus on understanding the purpose and impact of these changes to create meaningful commit message(s).`,ga=10*60*1e3;class ya extends X{constructor(e){super(e),this.params=e,this.colors={primary:"#AE5630",secondary:"#fff"},this.serviceName=P.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[Anthropic]"),this.errorPrefix=P.red.bold("[Anthropic]"),this.anthropic=new as({apiKey:this.params.config.key,...this.params.config.timeout>ga&&{timeout:this.params.config.timeout}})}getServiceSpecificErrorMessage(e){const r=e.message||"";return r.includes("API key")||r.includes("api_key")?"Invalid API key. Check your Anthropic API key in configuration":r.includes("quota")||r.includes("usage")?"API quota exceeded. Check your Anthropic usage limits":r.includes("model")||r.includes("Model")?"Model not found or not accessible. Check if the Claude model name is correct":r.includes("403")||r.includes("Forbidden")?"Access denied. Your API key may not have permission for this Claude model":r.includes("404")||r.includes("Not Found")?"Model or endpoint not found. Check your Claude model configuration":r.includes("500")||r.includes("Internal Server Error")?"Anthropic server error. Try again later":null}generateCommitMessage$(){return j(this.generateMessage("commit")).pipe(L(e=>M(e)),I(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:this.params.config.includeBody?e.value:e.title,description:this.params.config.includeBody?e.value:"",isError:!1})),R(this.handleError$))}generateCodeReview$(){return j(this.generateMessage("review")).pipe(L(e=>M(e)),I(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),R(this.handleError$))}async generateMessage(e){const r=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n,logging:i,temperature:c,locale:a,generate:m,type:d,maxLength:l,maxTokens:p,topP:u,model:h}=this.params.config,g={...J,locale:a,maxLength:l,type:d,generate:m,systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n},y=e==="review"?Z(g):Q(g),w=Ce(r,e),E=`${this.params.config.url||"https://api.anthropic.com"}/v1/messages`,x={"Content-Type":"application/json","x-api-key":this.params.config.key,"anthropic-version":"2023-06-01"};Y(r,e,"Anthropic",h,E,x,i),V(r,e,"Anthropic",y,w,i);const $={max_tokens:p,temperature:c,system:y,messages:[{role:"user",content:w}],top_p:u,model:h};te(r,e,"Anthropic",$,i);const C=Date.now();try{const A=await this.anthropic.messages.create($),D=Date.now()-C;q(r,e,"Anthropic",A,i);const N=A.content.map(({text:ie})=>ie).join("");return z(r,e,"Anthropic",D,N,i),e==="review"?this.sanitizeResponse(N):this.parseMessage(N,d,m)}catch(A){throw _(r,e,"Anthropic",A,i),A}}}class Oe{constructor(e={}){if(!e.method)throw new Error("method should be defined!");if(!e.baseURL)throw new Error("baseURL should be defined!");this.config={...e},this.axiosInstance=cs.create(this.config)}setHeaders(e){return this.config.headers=e,this}setParams(e){return this.config.params=e,this}setBody(e){return this.config.data=e,this}addBody(e){return this.config.data={...this.config.data,...e},this}setMethod(e){return this.config.method=e,this}async execute(){try{return await this.axiosInstance.request(this.config)}catch(e){throw e}}}class wa extends X{constructor(e){super(e),this.params=e,this.apiKey="",this.colors={primary:"#e28c58",secondary:"#fff"},this.serviceName=P.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[Codestral]"),this.errorPrefix=P.red.bold("[Codestral]"),this.apiKey=this.params.config.key}getServiceSpecificErrorMessage(e){const r=e.message||"";return r.includes("API key")||r.includes("api_key")?"Invalid API key. Check your Codestral API key in configuration":r.includes("rate_limit")||r.includes("Rate limit")?"Rate limit exceeded. Wait a moment and try again, or upgrade your Codestral plan":r.includes("model")||r.includes("Model")?"Model not found or not accessible. Check if the Codestral model name is correct":r.includes("Invalid model type")?"Invalid model type. Use supported models: codestral-latest, codestral-2501":r.includes("overloaded")||r.includes("capacity")?"Codestral service is overloaded. Try again in a few minutes":r.includes("403")||r.includes("Forbidden")?"Access denied. Your API key may not have permission for this Codestral model":r.includes("404")||r.includes("Not Found")?"Model or endpoint not found. Check your Codestral model configuration":r.includes("500")||r.includes("Internal Server Error")?"Codestral server error. Try again later":null}generateCommitMessage$(){return j(this.generateMessage("commit")).pipe(L(e=>M(e)),I(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:this.params.config.includeBody?e.value:e.title,description:this.params.config.includeBody?e.value:"",isError:!1})),R(this.handleError$))}generateCodeReview$(){return j(this.generateMessage("review")).pipe(L(e=>M(e)),I(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),R(this.handleError$))}async generateMessage(e){const r=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n,logging:i,locale:c,generate:a,type:m,maxLength:d}=this.params.config,l={...J,locale:c,maxLength:d,type:m,generate:a,systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n},p=e==="review"?Z(l):Q(l);this.checkAvailableModels();const u=Ce(r,e),g=`${this.params.config.url||"https://codestral.mistral.ai"}/v1/chat/completions`,y={Authorization:`Bearer ${this.apiKey}`,"content-type":"application/json"};Y(r,e,"Codestral",this.params.config.model,g,y,i),V(r,e,"Codestral",p,u,i);const w=await this.createChatCompletions(p,e);return e==="review"?this.sanitizeResponse(w):this.parseMessage(w,m,a)}checkAvailableModels(){if(["codestral-latest","codestral-2501"].includes(this.params.config.model))return!0;throw new Error("Invalid model type of Codestral AI")}async createChatCompletions(e,r){const o=this.params.stagedDiff.diff,{logging:s}=this.params.config,n=this.params.config.url||"https://codestral.mistral.ai",i={model:this.params.config.model,messages:[{role:"system",content:e},{role:"user",content:Ce(this.params.stagedDiff.diff,r)}],temperature:this.params.config.temperature,top_p:this.params.config.topP,max_tokens:this.params.config.maxTokens,stream:!1,safe_prompt:!1,random_seed:Ze(10,1e3)};r==="commit"&&(i.response_format={type:"json_object"}),te(o,r,"Codestral",i,s);const c=Date.now();try{const m=await new Oe({method:"POST",baseURL:`${n}/v1/chat/completions`,timeout:this.params.config.timeout}).setHeaders({Authorization:`Bearer ${this.apiKey}`,"content-type":"application/json"}).setBody(i).execute(),d=Date.now()-c,l=m.data;if(q(o,r,"Codestral",l,s),!l.choices||l.choices.length===0||!l.choices[0].message?.content)throw _(o,r,"Codestral",{message:"No Content on response",result:l},s),new Error("No Content on response. Please open a Bug report");const u=l.choices[0].message.content;return z(o,r,"Codestral",d,u,s),u}catch(a){throw _(o,r,"Codestral",a,s),a}}}class va extends X{constructor(e){super(e),this.params=e,this.colors={primary:"#D18EE2",secondary:"#fff"},this.serviceName=P.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[Cohere]"),this.errorPrefix=P.red.bold("[Cohere]"),this.cohere=new ls({token:this.params.config.key})}getServiceSpecificErrorMessage(e){const r=e.message||"";return r.includes("API key")||r.includes("api_key")?"Invalid API key. Check your Cohere API key in configuration":r.includes("rate_limit")||r.includes("Rate limit")?"Rate limit exceeded. Wait a moment and try again, or upgrade your Cohere plan":r.includes("model")||r.includes("Model")?"Model not found or not accessible. Check if the Cohere model name is correct":r.includes("overloaded")||r.includes("capacity")?"Cohere service is overloaded. Try again in a few minutes":r.includes("403")||r.includes("Forbidden")?"Access denied. Your API key may not have permission for this Cohere model":r.includes("404")||r.includes("Not Found")?"Model or endpoint not found. Check your Cohere model configuration":r.includes("500")||r.includes("Internal Server Error")?"Cohere server error. Try again later":null}generateCommitMessage$(){return j(this.generateMessage("commit")).pipe(L(e=>M(e)),I(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:this.params.config.includeBody?e.value:e.title,description:this.params.config.includeBody?e.value:"",isError:!1})),R(this.handleError$))}generateCodeReview$(){return j(this.generateMessage("review")).pipe(L(e=>M(e)),I(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),R(this.handleError$))}async generateMessage(e){const r=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n,logging:i,temperature:c,locale:a,generate:m,type:d,maxLength:l,maxTokens:p}=this.params.config,u={...J,locale:a,maxLength:l,type:d,generate:m,systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n},h=e==="review"?Z(u):Q(u),g=`Here is the diff: ${r}`,w=`${this.params.config.url||"https://api.cohere.ai"}/v1/chat`,v={Authorization:`Bearer ${this.params.config.key}`,"Content-Type":"application/json"};Y(r,e,"Cohere",this.params.config.model,w,v,i),V(r,e,"Cohere",h,g,i);const E={chatHistory:h?[{role:"SYSTEM",message:h}]:[],message:g,connectors:[{id:"web-search"}],maxTokens:p,temperature:c,model:this.params.config.model,seed:Ze(10,1e3),p:this.params.config.topP};te(r,e,"Cohere",E,i);const x=Date.now();try{const $=await this.cohere.chat(E,{timeoutInSeconds:Math.floor(this.params.config.timeout/1e3)}),C=Date.now()-x,A=$.text;return q(r,e,"Cohere",$,i),z(r,e,"Cohere",C,A,i),e==="review"?this.sanitizeResponse(A):this.parseMessage(A,d,m)}catch($){throw _(r,e,"Cohere",$,i),$}}}class ba extends X{constructor(e){super(e),this.params=e,this.colors={primary:"#53a3f9",secondary:"#fff"},this.serviceName=P.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[DeepSeek]"),this.errorPrefix=P.red.bold("[DeepSeek]");const r=this.params.config.url||"https://api.deepseek.com";this.deepSeek=new $r({baseURL:r,apiKey:this.params.config.key})}getServiceSpecificErrorMessage(e){const r=e.message||"";return r.includes("API key")||r.includes("api_key")?"Invalid API key. Check your DeepSeek API key in configuration":r.includes("rate_limit")||r.includes("Rate limit")?"Rate limit exceeded. Wait a moment and try again, or upgrade your DeepSeek plan":r.includes("model")||r.includes("Model")?"Model not found or not accessible. Check if the DeepSeek model name is correct":r.includes("Invalid model type")?"Invalid model type. Use supported models: deepseek-reasoner, deepseek-chat":r.includes("overloaded")||r.includes("capacity")?"DeepSeek service is overloaded. Try again in a few minutes":r.includes("403")||r.includes("Forbidden")?"Access denied. Your API key may not have permission for this DeepSeek model":r.includes("404")||r.includes("Not Found")?"Model or endpoint not found. Check your DeepSeek model configuration":r.includes("500")||r.includes("Internal Server Error")?"DeepSeek server error. Try again later":null}generateCommitMessage$(){return j(this.generateMessage("commit")).pipe(L(e=>M(e)),I(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:this.params.config.includeBody?e.value:e.title,description:this.params.config.includeBody?e.value:"",isError:!1})),R(this.handleError$))}generateCodeReview$(){return j(this.generateMessage("review")).pipe(L(e=>M(e)),I(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),R(this.handleError$))}async generateMessage(e){const r=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n,logging:i,locale:c,generate:a,type:m,maxLength:d}=this.params.config,l={...J,locale:c,maxLength:d,type:m,generate:a,systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n},p=e==="review"?Z(l):Q(l);this.checkAvailableModels();const u=Ce(r,e),g=`${this.params.config.url||"https://api.deepseek.com"}/chat/completions`,y={Authorization:`Bearer ${this.params.config.key}`,"Content-Type":"application/json"};Y(r,e,"DeepSeek",this.params.config.model,g,y,i),V(r,e,"DeepSeek",p,u,i);const w=await this.createChatCompletions(p,u,e);return e==="review"?this.sanitizeResponse(w):this.parseMessage(w,m,a)}checkAvailableModels(){if(["deepseek-reasoner","deepseek-chat"].includes(this.params.config.model))return!0;throw new Error("Invalid model type of DeepSeek")}async createChatCompletions(e,r,o){const s=this.params.stagedDiff.diff,{logging:n}=this.params.config,i={messages:[{role:"system",content:e},{role:"user",content:r}],model:this.params.config.model,max_tokens:this.params.config.maxTokens,top_p:this.params.config.topP,temperature:this.params.config.temperature};te(s,o,"DeepSeek",i,n);const c=Date.now();try{const a=await this.deepSeek.chat.completions.create(i,{timeout:this.params.config.timeout}),m=Date.now()-c,d=a.choices[0].message.content||"";return q(s,o,"DeepSeek",a,n),z(s,o,"DeepSeek",m,d,n),d}catch(a){throw _(s,o,"DeepSeek",a,n),a}}}class Ca extends X{constructor(e){super(e),this.params=e,this.colors={primary:"#0077FF",secondary:"#fff"},this.serviceName=P.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[Gemini]"),this.errorPrefix=P.red.bold("[Gemini]"),this.genAI=new us(this.params.config.key)}getServiceSpecificErrorMessage(e){const r=e.message||"";return r.includes("API key")||r.includes("api_key")?"Invalid API key. Check your Google AI Studio API key in configuration":r.includes("quota")||r.includes("QUOTA_EXCEEDED")?"API quota exceeded. Check your Google AI Studio usage limits":r.includes("model")||r.includes("Model")?"Model not found or not accessible. Check if the Gemini model name is correct":r.includes("SAFETY")||r.includes("safety")?"Content blocked by safety filters. Try rephrasing your request":r.includes("RECITATION")||r.includes("recitation")?"Content blocked due to recitation concerns. Try a different approach":r.includes("403")||r.includes("Forbidden")?"Access denied. Your API key may not have permission for this Gemini model":r.includes("404")||r.includes("Not Found")?"Model or endpoint not found. Check your Gemini model configuration":r.includes("500")||r.includes("Internal Server Error")?"Google AI service error. Try again later":null}generateCommitMessage$(){return j(this.generateMessage("commit")).pipe(L(e=>M(e)),I(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:this.params.config.includeBody?e.value:e.title,description:this.params.config.includeBody?e.value:"",isError:!1})),R(this.handleError$))}generateCodeReview$(){return j(this.generateMessage("review")).pipe(L(e=>M(e)),I(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),R(this.handleError$))}async generateMessage(e){const r=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:s,logging:n,locale:i,codeReviewPromptPath:c,generate:a,type:m,maxLength:d}=this.params.config,l=this.params.config.maxTokens,p={...J,locale:i,maxLength:d,type:m,generate:a,systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:c},u=e==="review"?Z(p):Q(p),h={maxOutputTokens:l,temperature:this.params.config.temperature,topP:this.params.config.topP},g=this.genAI.getGenerativeModel({model:this.params.config.model,systemInstruction:u,generationConfig:h,safetySettings:[{category:Be.HARM_CATEGORY_HATE_SPEECH,threshold:He.BLOCK_LOW_AND_ABOVE},{category:Be.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:He.BLOCK_LOW_AND_ABOVE},{category:Be.HARM_CATEGORY_HARASSMENT,threshold:He.BLOCK_LOW_AND_ABOVE},{category:Be.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:He.BLOCK_LOW_AND_ABOVE}]}),y=Ce(r,e),v=`${this.params.config.url||"https://generativelanguage.googleapis.com"}/v1beta/models/${this.params.config.model}:generateContent`,E={"Content-Type":"application/json","x-goog-api-key":this.params.config.key};Y(r,e,"Gemini",this.params.config.model,v,E,n),V(r,e,"Gemini",u,y,n),te(r,e,"Gemini",{systemInstruction:{parts:[{text:u}]},contents:[{parts:[{text:y}]}],generationConfig:h},n);const $=Date.now();try{const C=this.params.config.timeout>1e4?{request:{timeout:this.params.config.timeout}}:void 0,A=await g.generateContent(y,C),N=A.response.text(),ie=Date.now()-$;return q(r,e,"Gemini",{response:N,candidates:A.response.candidates,usageMetadata:A.response.usageMetadata},n),z(r,e,"Gemini",ie,N,n),e==="review"?this.sanitizeResponse(N):this.parseMessage(N,m,a)}catch(C){throw _(r,e,"Gemini",C,n),C}}}var Bt={},Ht={exports:{}},Le={exports:{}},Ut,vo;function Pa(){if(vo)return Ut;vo=1;var t=1e3,e=t*60,r=e*60,o=r*24,s=o*7,n=o*365.25;Ut=function(d,l){l=l||{};var p=typeof d;if(p==="string"&&d.length>0)return i(d);if(p==="number"&&isFinite(d))return l.long?a(d):c(d);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(d))};function i(d){if(d=String(d),!(d.length>100)){var l=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(d);if(l){var p=parseFloat(l[1]),u=(l[2]||"ms").toLowerCase();switch(u){case"years":case"year":case"yrs":case"yr":case"y":return p*n;case"weeks":case"week":case"w":return p*s;case"days":case"day":case"d":return p*o;case"hours":case"hour":case"hrs":case"hr":case"h":return p*r;case"minutes":case"minute":case"mins":case"min":case"m":return p*e;case"seconds":case"second":case"secs":case"sec":case"s":return p*t;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return p;default:return}}}}function c(d){var l=Math.abs(d);return l>=o?Math.round(d/o)+"d":l>=r?Math.round(d/r)+"h":l>=e?Math.round(d/e)+"m":l>=t?Math.round(d/t)+"s":d+"ms"}function a(d){var l=Math.abs(d);return l>=o?m(d,l,o,"day"):l>=r?m(d,l,r,"hour"):l>=e?m(d,l,e,"minute"):l>=t?m(d,l,t,"second"):d+" ms"}function m(d,l,p,u){var h=l>=p*1.5;return Math.round(d/p)+" "+u+(h?"s":"")}return Ut}var zt,bo;function Co(){if(bo)return zt;bo=1;function t(e){o.debug=o,o.default=o,o.coerce=m,o.disable=c,o.enable=n,o.enabled=a,o.humanize=Pa(),o.destroy=d,Object.keys(e).forEach(l=>{o[l]=e[l]}),o.names=[],o.skips=[],o.formatters={};function r(l){let p=0;for(let u=0;u<l.length;u++)p=(p<<5)-p+l.charCodeAt(u),p|=0;return o.colors[Math.abs(p)%o.colors.length]}o.selectColor=r;function o(l){let p,u=null,h,g;function y(...w){if(!y.enabled)return;const v=y,E=Number(new Date),x=E-(p||E);v.diff=x,v.prev=p,v.curr=E,p=E,w[0]=o.coerce(w[0]),typeof w[0]!="string"&&w.unshift("%O");let $=0;w[0]=w[0].replace(/%([a-zA-Z%])/g,(A,D)=>{if(A==="%%")return"%";$++;const N=o.formatters[D];if(typeof N=="function"){const ie=w[$];A=N.call(v,ie),w.splice($,1),$--}return A}),o.formatArgs.call(v,w),(v.log||o.log).apply(v,w)}return y.namespace=l,y.useColors=o.useColors(),y.color=o.selectColor(l),y.extend=s,y.destroy=o.destroy,Object.defineProperty(y,"enabled",{enumerable:!0,configurable:!1,get:()=>u!==null?u:(h!==o.namespaces&&(h=o.namespaces,g=o.enabled(l)),g),set:w=>{u=w}}),typeof o.init=="function"&&o.init(y),y}function s(l,p){const u=o(this.namespace+(typeof p>"u"?":":p)+l);return u.log=this.log,u}function n(l){o.save(l),o.namespaces=l,o.names=[],o.skips=[];const p=(typeof l=="string"?l:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(const u of p)u[0]==="-"?o.skips.push(u.slice(1)):o.names.push(u)}function i(l,p){let u=0,h=0,g=-1,y=0;for(;u<l.length;)if(h<p.length&&(p[h]===l[u]||p[h]==="*"))p[h]==="*"?(g=h,y=u,h++):(u++,h++);else if(g!==-1)h=g+1,y++,u=y;else return!1;for(;h<p.length&&p[h]==="*";)h++;return h===p.length}function c(){const l=[...o.names,...o.skips.map(p=>"-"+p)].join(",");return o.enable(""),l}function a(l){for(const p of o.skips)if(i(l,p))return!1;for(const p of o.names)if(i(l,p))return!0;return!1}function m(l){return l instanceof Error?l.stack||l.message:l}function d(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return o.enable(o.load()),o}return zt=t,zt}Le.exports;var Po;function $a(){return Po||(Po=1,function(t,e){e.formatArgs=o,e.save=s,e.load=n,e.useColors=r,e.storage=i(),e.destroy=(()=>{let a=!1;return()=>{a||(a=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),e.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function r(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let a;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&(a=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(a[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function o(a){if(a[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+a[0]+(this.useColors?"%c ":" ")+"+"+t.exports.humanize(this.diff),!this.useColors)return;const m="color: "+this.color;a.splice(1,0,m,"color: inherit");let d=0,l=0;a[0].replace(/%[a-zA-Z%]/g,p=>{p!=="%%"&&(d++,p==="%c"&&(l=d))}),a.splice(l,0,m)}e.log=console.debug||console.log||(()=>{});function s(a){try{a?e.storage.setItem("debug",a):e.storage.removeItem("debug")}catch{}}function n(){let a;try{a=e.storage.getItem("debug")||e.storage.getItem("DEBUG")}catch{}return!a&&typeof process<"u"&&"env"in process&&(a=process.env.DEBUG),a}function i(){try{return localStorage}catch{}}t.exports=Co()(e);const{formatters:c}=t.exports;c.j=function(a){try{return JSON.stringify(a)}catch(m){return"[UnexpectedJSONParseError]: "+m.message}}}(Le,Le.exports)),Le.exports}var je={exports:{}},Jt,$o;function Ea(){return $o||($o=1,Jt=(t,e=process.argv)=>{const r=t.startsWith("-")?"":t.length===1?"-":"--",o=e.indexOf(r+t),s=e.indexOf("--");return o!==-1&&(s===-1||o<s)}),Jt}var Kt,Eo;function ka(){if(Eo)return Kt;Eo=1;const t=Ee,e=Er,r=Ea(),{env:o}=process;let s;r("no-color")||r("no-colors")||r("color=false")||r("color=never")?s=0:(r("color")||r("colors")||r("color=true")||r("color=always"))&&(s=1),"FORCE_COLOR"in o&&(o.FORCE_COLOR==="true"?s=1:o.FORCE_COLOR==="false"?s=0:s=o.FORCE_COLOR.length===0?1:Math.min(parseInt(o.FORCE_COLOR,10),3));function n(a){return a===0?!1:{level:a,hasBasic:!0,has256:a>=2,has16m:a>=3}}function i(a,m){if(s===0)return 0;if(r("color=16m")||r("color=full")||r("color=truecolor"))return 3;if(r("color=256"))return 2;if(a&&!m&&s===void 0)return 0;const d=s||0;if(o.TERM==="dumb")return d;if(process.platform==="win32"){const l=t.release().split(".");return Number(l[0])>=10&&Number(l[2])>=10586?Number(l[2])>=14931?3:2:1}if("CI"in o)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE"].some(l=>l in o)||o.CI_NAME==="codeship"?1:d;if("TEAMCITY_VERSION"in o)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(o.TEAMCITY_VERSION)?1:0;if(o.COLORTERM==="truecolor")return 3;if("TERM_PROGRAM"in o){const l=parseInt((o.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(o.TERM_PROGRAM){case"iTerm.app":return l>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(o.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(o.TERM)||"COLORTERM"in o?1:d}function c(a){const m=i(a,a&&a.isTTY);return n(m)}return Kt={supportsColor:c,stdout:n(i(!0,e.isatty(1))),stderr:n(i(!0,e.isatty(2)))},Kt}je.exports;var ko;function xa(){return ko||(ko=1,function(t,e){const r=Er,o=gr;e.init=d,e.log=c,e.formatArgs=n,e.save=a,e.load=m,e.useColors=s,e.destroy=o.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."),e.colors=[6,2,3,4,5,1];try{const p=ka();p&&(p.stderr||p).level>=2&&(e.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221])}catch{}e.inspectOpts=Object.keys(process.env).filter(p=>/^debug_/i.test(p)).reduce((p,u)=>{const h=u.substring(6).toLowerCase().replace(/_([a-z])/g,(y,w)=>w.toUpperCase());let g=process.env[u];return/^(yes|on|true|enabled)$/i.test(g)?g=!0:/^(no|off|false|disabled)$/i.test(g)?g=!1:g==="null"?g=null:g=Number(g),p[h]=g,p},{});function s(){return"colors"in e.inspectOpts?!!e.inspectOpts.colors:r.isatty(process.stderr.fd)}function n(p){const{namespace:u,useColors:h}=this;if(h){const g=this.color,y="\x1B[3"+(g<8?g:"8;5;"+g),w=` ${y};1m${u} \x1B[0m`;p[0]=w+p[0].split(`
|
|
70
|
+
Focus on understanding the purpose and impact of these changes to create meaningful commit message(s).`,wa=10*60*1e3;class va extends X{constructor(e){super(e),this.params=e,this.colors={primary:"#AE5630",secondary:"#fff"},this.serviceName=P.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[Anthropic]"),this.errorPrefix=P.red.bold("[Anthropic]"),this.anthropic=new ls({apiKey:this.params.config.key,...this.params.config.timeout>wa&&{timeout:this.params.config.timeout}})}getServiceSpecificErrorMessage(e){const r=e.message||"";return r.includes("API key")||r.includes("api_key")?"Invalid API key. Check your Anthropic API key in configuration":r.includes("quota")||r.includes("usage")?"API quota exceeded. Check your Anthropic usage limits":r.includes("model")||r.includes("Model")?"Model not found or not accessible. Check if the Claude model name is correct":r.includes("403")||r.includes("Forbidden")?"Access denied. Your API key may not have permission for this Claude model":r.includes("404")||r.includes("Not Found")?"Model or endpoint not found. Check your Claude model configuration":r.includes("500")||r.includes("Internal Server Error")?"Anthropic server error. Try again later":null}generateCommitMessage$(){return D(this.generateMessage("commit")).pipe(L(e=>M(e)),I(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:this.params.config.includeBody?e.value:e.title,description:this.params.config.includeBody?e.value:"",isError:!1})),R(this.handleError$))}generateCodeReview$(){return D(this.generateMessage("review")).pipe(L(e=>M(e)),I(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),R(this.handleError$))}async generateMessage(e){const r=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n,logging:i,temperature:c,locale:a,generate:m,type:d,maxLength:l,maxTokens:p,topP:u,model:h}=this.params.config,g={...K,locale:a,maxLength:l,type:d,generate:m,systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n},y=e==="review"?Z(g):Q(g),w=Ce(r,e),E=`${this.params.config.url||"https://api.anthropic.com"}/v1/messages`,A={"Content-Type":"application/json","x-api-key":this.params.config.key,"anthropic-version":"2023-06-01"};Y(r,e,"Anthropic",h,E,A,i),V(r,e,"Anthropic",y,w,i);const $={max_tokens:p,temperature:c,system:y,messages:[{role:"user",content:w}],top_p:u,model:h};te(r,e,"Anthropic",$,i);const C=Date.now();try{const S=await this.anthropic.messages.create($),T=Date.now()-C;q(r,e,"Anthropic",S,i);const j=S.content.map(({text:ie})=>ie).join("");return z(r,e,"Anthropic",T,j,i),e==="review"?this.sanitizeResponse(j):this.parseMessage(j,d,m)}catch(S){throw _(r,e,"Anthropic",S,i),S}}}class Oe{constructor(e={}){if(!e.method)throw new Error("method should be defined!");if(!e.baseURL)throw new Error("baseURL should be defined!");this.config={...e},this.axiosInstance=us.create(this.config)}setHeaders(e){return this.config.headers=e,this}setParams(e){return this.config.params=e,this}setBody(e){return this.config.data=e,this}addBody(e){return this.config.data={...this.config.data,...e},this}setMethod(e){return this.config.method=e,this}async execute(){try{return await this.axiosInstance.request(this.config)}catch(e){throw e}}}class ba extends X{constructor(e){super(e),this.params=e,this.apiKey="",this.colors={primary:"#e28c58",secondary:"#fff"},this.serviceName=P.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[Codestral]"),this.errorPrefix=P.red.bold("[Codestral]"),this.apiKey=this.params.config.key}getServiceSpecificErrorMessage(e){const r=e.message||"";return r.includes("API key")||r.includes("api_key")?"Invalid API key. Check your Codestral API key in configuration":r.includes("rate_limit")||r.includes("Rate limit")?"Rate limit exceeded. Wait a moment and try again, or upgrade your Codestral plan":r.includes("model")||r.includes("Model")?"Model not found or not accessible. Check if the Codestral model name is correct":r.includes("Invalid model type")?"Invalid model type. Use supported models: codestral-latest, codestral-2501":r.includes("overloaded")||r.includes("capacity")?"Codestral service is overloaded. Try again in a few minutes":r.includes("403")||r.includes("Forbidden")?"Access denied. Your API key may not have permission for this Codestral model":r.includes("404")||r.includes("Not Found")?"Model or endpoint not found. Check your Codestral model configuration":r.includes("500")||r.includes("Internal Server Error")?"Codestral server error. Try again later":null}generateCommitMessage$(){return D(this.generateMessage("commit")).pipe(L(e=>M(e)),I(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:this.params.config.includeBody?e.value:e.title,description:this.params.config.includeBody?e.value:"",isError:!1})),R(this.handleError$))}generateCodeReview$(){return D(this.generateMessage("review")).pipe(L(e=>M(e)),I(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),R(this.handleError$))}async generateMessage(e){const r=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n,logging:i,locale:c,generate:a,type:m,maxLength:d}=this.params.config,l={...K,locale:c,maxLength:d,type:m,generate:a,systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n},p=e==="review"?Z(l):Q(l);this.checkAvailableModels();const u=Ce(r,e),g=`${this.params.config.url||"https://codestral.mistral.ai"}/v1/chat/completions`,y={Authorization:`Bearer ${this.apiKey}`,"content-type":"application/json"};Y(r,e,"Codestral",this.params.config.model,g,y,i),V(r,e,"Codestral",p,u,i);const w=await this.createChatCompletions(p,e);return e==="review"?this.sanitizeResponse(w):this.parseMessage(w,m,a)}checkAvailableModels(){if(["codestral-latest","codestral-2501"].includes(this.params.config.model))return!0;throw new Error("Invalid model type of Codestral AI")}async createChatCompletions(e,r){const o=this.params.stagedDiff.diff,{logging:s}=this.params.config,n=this.params.config.url||"https://codestral.mistral.ai",i={model:this.params.config.model,messages:[{role:"system",content:e},{role:"user",content:Ce(this.params.stagedDiff.diff,r)}],temperature:this.params.config.temperature,top_p:this.params.config.topP,max_tokens:this.params.config.maxTokens,stream:!1,safe_prompt:!1,random_seed:Ze(10,1e3)};r==="commit"&&(i.response_format={type:"json_object"}),te(o,r,"Codestral",i,s);const c=Date.now();try{const m=await new Oe({method:"POST",baseURL:`${n}/v1/chat/completions`,timeout:this.params.config.timeout}).setHeaders({Authorization:`Bearer ${this.apiKey}`,"content-type":"application/json"}).setBody(i).execute(),d=Date.now()-c,l=m.data;if(q(o,r,"Codestral",l,s),!l.choices||l.choices.length===0||!l.choices[0].message?.content)throw _(o,r,"Codestral",{message:"No Content on response",result:l},s),new Error("No Content on response. Please open a Bug report");const u=l.choices[0].message.content;return z(o,r,"Codestral",d,u,s),u}catch(a){throw _(o,r,"Codestral",a,s),a}}}class Ca extends X{constructor(e){super(e),this.params=e,this.colors={primary:"#D18EE2",secondary:"#fff"},this.serviceName=P.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[Cohere]"),this.errorPrefix=P.red.bold("[Cohere]"),this.cohere=new ds({token:this.params.config.key})}getServiceSpecificErrorMessage(e){const r=e.message||"";return r.includes("API key")||r.includes("api_key")?"Invalid API key. Check your Cohere API key in configuration":r.includes("rate_limit")||r.includes("Rate limit")?"Rate limit exceeded. Wait a moment and try again, or upgrade your Cohere plan":r.includes("model")||r.includes("Model")?"Model not found or not accessible. Check if the Cohere model name is correct":r.includes("overloaded")||r.includes("capacity")?"Cohere service is overloaded. Try again in a few minutes":r.includes("403")||r.includes("Forbidden")?"Access denied. Your API key may not have permission for this Cohere model":r.includes("404")||r.includes("Not Found")?"Model or endpoint not found. Check your Cohere model configuration":r.includes("500")||r.includes("Internal Server Error")?"Cohere server error. Try again later":null}generateCommitMessage$(){return D(this.generateMessage("commit")).pipe(L(e=>M(e)),I(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:this.params.config.includeBody?e.value:e.title,description:this.params.config.includeBody?e.value:"",isError:!1})),R(this.handleError$))}generateCodeReview$(){return D(this.generateMessage("review")).pipe(L(e=>M(e)),I(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),R(this.handleError$))}async generateMessage(e){const r=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n,logging:i,temperature:c,locale:a,generate:m,type:d,maxLength:l,maxTokens:p}=this.params.config,u={...K,locale:a,maxLength:l,type:d,generate:m,systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n},h=e==="review"?Z(u):Q(u),g=`Here is the diff: ${r}`,w=`${this.params.config.url||"https://api.cohere.ai"}/v1/chat`,v={Authorization:`Bearer ${this.params.config.key}`,"Content-Type":"application/json"};Y(r,e,"Cohere",this.params.config.model,w,v,i),V(r,e,"Cohere",h,g,i);const E={chatHistory:h?[{role:"SYSTEM",message:h}]:[],message:g,connectors:[{id:"web-search"}],maxTokens:p,temperature:c,model:this.params.config.model,seed:Ze(10,1e3),p:this.params.config.topP};te(r,e,"Cohere",E,i);const A=Date.now();try{const $=await this.cohere.chat(E,{timeoutInSeconds:Math.floor(this.params.config.timeout/1e3)}),C=Date.now()-A,S=$.text;return q(r,e,"Cohere",$,i),z(r,e,"Cohere",C,S,i),e==="review"?this.sanitizeResponse(S):this.parseMessage(S,d,m)}catch($){throw _(r,e,"Cohere",$,i),$}}}class Pa extends X{constructor(e){super(e),this.params=e,this.colors={primary:"#53a3f9",secondary:"#fff"},this.serviceName=P.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[DeepSeek]"),this.errorPrefix=P.red.bold("[DeepSeek]");const r=this.params.config.url||"https://api.deepseek.com";this.deepSeek=new Pr({baseURL:r,apiKey:this.params.config.key})}getServiceSpecificErrorMessage(e){const r=e.message||"";return r.includes("API key")||r.includes("api_key")?"Invalid API key. Check your DeepSeek API key in configuration":r.includes("rate_limit")||r.includes("Rate limit")?"Rate limit exceeded. Wait a moment and try again, or upgrade your DeepSeek plan":r.includes("model")||r.includes("Model")?"Model not found or not accessible. Check if the DeepSeek model name is correct":r.includes("Invalid model type")?"Invalid model type. Use supported models: deepseek-reasoner, deepseek-chat":r.includes("overloaded")||r.includes("capacity")?"DeepSeek service is overloaded. Try again in a few minutes":r.includes("403")||r.includes("Forbidden")?"Access denied. Your API key may not have permission for this DeepSeek model":r.includes("404")||r.includes("Not Found")?"Model or endpoint not found. Check your DeepSeek model configuration":r.includes("500")||r.includes("Internal Server Error")?"DeepSeek server error. Try again later":null}generateCommitMessage$(){return D(this.generateMessage("commit")).pipe(L(e=>M(e)),I(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:this.params.config.includeBody?e.value:e.title,description:this.params.config.includeBody?e.value:"",isError:!1})),R(this.handleError$))}generateCodeReview$(){return D(this.generateMessage("review")).pipe(L(e=>M(e)),I(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),R(this.handleError$))}async generateMessage(e){const r=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n,logging:i,locale:c,generate:a,type:m,maxLength:d}=this.params.config,l={...K,locale:c,maxLength:d,type:m,generate:a,systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n},p=e==="review"?Z(l):Q(l);this.checkAvailableModels();const u=Ce(r,e),g=`${this.params.config.url||"https://api.deepseek.com"}/chat/completions`,y={Authorization:`Bearer ${this.params.config.key}`,"Content-Type":"application/json"};Y(r,e,"DeepSeek",this.params.config.model,g,y,i),V(r,e,"DeepSeek",p,u,i);const w=await this.createChatCompletions(p,u,e);return e==="review"?this.sanitizeResponse(w):this.parseMessage(w,m,a)}checkAvailableModels(){if(["deepseek-reasoner","deepseek-chat"].includes(this.params.config.model))return!0;throw new Error("Invalid model type of DeepSeek")}async createChatCompletions(e,r,o){const s=this.params.stagedDiff.diff,{logging:n}=this.params.config,i={messages:[{role:"system",content:e},{role:"user",content:r}],model:this.params.config.model,max_tokens:this.params.config.maxTokens,top_p:this.params.config.topP,temperature:this.params.config.temperature};te(s,o,"DeepSeek",i,n);const c=Date.now();try{const a=await this.deepSeek.chat.completions.create(i,{timeout:this.params.config.timeout}),m=Date.now()-c,d=a.choices[0].message.content||"";return q(s,o,"DeepSeek",a,n),z(s,o,"DeepSeek",m,d,n),d}catch(a){throw _(s,o,"DeepSeek",a,n),a}}}class $a extends X{constructor(e){super(e),this.params=e,this.colors={primary:"#0077FF",secondary:"#fff"},this.serviceName=P.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[Gemini]"),this.errorPrefix=P.red.bold("[Gemini]"),this.genAI=new ms(this.params.config.key)}getServiceSpecificErrorMessage(e){const r=e.message||"";return r.includes("API key")||r.includes("api_key")?"Invalid API key. Check your Google AI Studio API key in configuration":r.includes("quota")||r.includes("QUOTA_EXCEEDED")?"API quota exceeded. Check your Google AI Studio usage limits":r.includes("model")||r.includes("Model")?"Model not found or not accessible. Check if the Gemini model name is correct":r.includes("SAFETY")||r.includes("safety")?"Content blocked by safety filters. Try rephrasing your request":r.includes("RECITATION")||r.includes("recitation")?"Content blocked due to recitation concerns. Try a different approach":r.includes("403")||r.includes("Forbidden")?"Access denied. Your API key may not have permission for this Gemini model":r.includes("404")||r.includes("Not Found")?"Model or endpoint not found. Check your Gemini model configuration":r.includes("500")||r.includes("Internal Server Error")?"Google AI service error. Try again later":null}generateCommitMessage$(){return D(this.generateMessage("commit")).pipe(L(e=>M(e)),I(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:this.params.config.includeBody?e.value:e.title,description:this.params.config.includeBody?e.value:"",isError:!1})),R(this.handleError$))}generateCodeReview$(){return D(this.generateMessage("review")).pipe(L(e=>M(e)),I(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),R(this.handleError$))}async generateMessage(e){const r=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:s,logging:n,locale:i,codeReviewPromptPath:c,generate:a,type:m,maxLength:d}=this.params.config,l=this.params.config.maxTokens,p={...K,locale:i,maxLength:d,type:m,generate:a,systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:c},u=e==="review"?Z(p):Q(p),h={maxOutputTokens:l,temperature:this.params.config.temperature,topP:this.params.config.topP},g=this.genAI.getGenerativeModel({model:this.params.config.model,systemInstruction:u,generationConfig:h,safetySettings:[{category:He.HARM_CATEGORY_HATE_SPEECH,threshold:Be.BLOCK_LOW_AND_ABOVE},{category:He.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:Be.BLOCK_LOW_AND_ABOVE},{category:He.HARM_CATEGORY_HARASSMENT,threshold:Be.BLOCK_LOW_AND_ABOVE},{category:He.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:Be.BLOCK_LOW_AND_ABOVE}]}),y=Ce(r,e),v=`${this.params.config.url||"https://generativelanguage.googleapis.com"}/v1beta/models/${this.params.config.model}:generateContent`,E={"Content-Type":"application/json","x-goog-api-key":this.params.config.key};Y(r,e,"Gemini",this.params.config.model,v,E,n),V(r,e,"Gemini",u,y,n),te(r,e,"Gemini",{systemInstruction:{parts:[{text:u}]},contents:[{parts:[{text:y}]}],generationConfig:h},n);const $=Date.now();try{const C=this.params.config.timeout>1e4?{request:{timeout:this.params.config.timeout}}:void 0,S=await g.generateContent(y,C),j=S.response.text(),ie=Date.now()-$;return q(r,e,"Gemini",{response:j,candidates:S.response.candidates,usageMetadata:S.response.usageMetadata},n),z(r,e,"Gemini",ie,j,n),e==="review"?this.sanitizeResponse(j):this.parseMessage(j,m,a)}catch(C){throw _(r,e,"Gemini",C,n),C}}}var Gt={},Ht={exports:{}},Le={exports:{}},Bt,vo;function Ea(){if(vo)return Bt;vo=1;var t=1e3,e=t*60,r=e*60,o=r*24,s=o*7,n=o*365.25;Bt=function(d,l){l=l||{};var p=typeof d;if(p==="string"&&d.length>0)return i(d);if(p==="number"&&isFinite(d))return l.long?a(d):c(d);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(d))};function i(d){if(d=String(d),!(d.length>100)){var l=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(d);if(l){var p=parseFloat(l[1]),u=(l[2]||"ms").toLowerCase();switch(u){case"years":case"year":case"yrs":case"yr":case"y":return p*n;case"weeks":case"week":case"w":return p*s;case"days":case"day":case"d":return p*o;case"hours":case"hour":case"hrs":case"hr":case"h":return p*r;case"minutes":case"minute":case"mins":case"min":case"m":return p*e;case"seconds":case"second":case"secs":case"sec":case"s":return p*t;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return p;default:return}}}}function c(d){var l=Math.abs(d);return l>=o?Math.round(d/o)+"d":l>=r?Math.round(d/r)+"h":l>=e?Math.round(d/e)+"m":l>=t?Math.round(d/t)+"s":d+"ms"}function a(d){var l=Math.abs(d);return l>=o?m(d,l,o,"day"):l>=r?m(d,l,r,"hour"):l>=e?m(d,l,e,"minute"):l>=t?m(d,l,t,"second"):d+" ms"}function m(d,l,p,u){var h=l>=p*1.5;return Math.round(d/p)+" "+u+(h?"s":"")}return Bt}var Ut,bo;function Co(){if(bo)return Ut;bo=1;function t(e){o.debug=o,o.default=o,o.coerce=m,o.disable=c,o.enable=n,o.enabled=a,o.humanize=Ea(),o.destroy=d,Object.keys(e).forEach(l=>{o[l]=e[l]}),o.names=[],o.skips=[],o.formatters={};function r(l){let p=0;for(let u=0;u<l.length;u++)p=(p<<5)-p+l.charCodeAt(u),p|=0;return o.colors[Math.abs(p)%o.colors.length]}o.selectColor=r;function o(l){let p,u=null,h,g;function y(...w){if(!y.enabled)return;const v=y,E=Number(new Date),A=E-(p||E);v.diff=A,v.prev=p,v.curr=E,p=E,w[0]=o.coerce(w[0]),typeof w[0]!="string"&&w.unshift("%O");let $=0;w[0]=w[0].replace(/%([a-zA-Z%])/g,(S,T)=>{if(S==="%%")return"%";$++;const j=o.formatters[T];if(typeof j=="function"){const ie=w[$];S=j.call(v,ie),w.splice($,1),$--}return S}),o.formatArgs.call(v,w),(v.log||o.log).apply(v,w)}return y.namespace=l,y.useColors=o.useColors(),y.color=o.selectColor(l),y.extend=s,y.destroy=o.destroy,Object.defineProperty(y,"enabled",{enumerable:!0,configurable:!1,get:()=>u!==null?u:(h!==o.namespaces&&(h=o.namespaces,g=o.enabled(l)),g),set:w=>{u=w}}),typeof o.init=="function"&&o.init(y),y}function s(l,p){const u=o(this.namespace+(typeof p>"u"?":":p)+l);return u.log=this.log,u}function n(l){o.save(l),o.namespaces=l,o.names=[],o.skips=[];const p=(typeof l=="string"?l:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(const u of p)u[0]==="-"?o.skips.push(u.slice(1)):o.names.push(u)}function i(l,p){let u=0,h=0,g=-1,y=0;for(;u<l.length;)if(h<p.length&&(p[h]===l[u]||p[h]==="*"))p[h]==="*"?(g=h,y=u,h++):(u++,h++);else if(g!==-1)h=g+1,y++,u=y;else return!1;for(;h<p.length&&p[h]==="*";)h++;return h===p.length}function c(){const l=[...o.names,...o.skips.map(p=>"-"+p)].join(",");return o.enable(""),l}function a(l){for(const p of o.skips)if(i(l,p))return!1;for(const p of o.names)if(i(l,p))return!0;return!1}function m(l){return l instanceof Error?l.stack||l.message:l}function d(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return o.enable(o.load()),o}return Ut=t,Ut}Le.exports;var Po;function xa(){return Po||(Po=1,function(t,e){e.formatArgs=o,e.save=s,e.load=n,e.useColors=r,e.storage=i(),e.destroy=(()=>{let a=!1;return()=>{a||(a=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),e.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function r(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let a;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&(a=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(a[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function o(a){if(a[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+a[0]+(this.useColors?"%c ":" ")+"+"+t.exports.humanize(this.diff),!this.useColors)return;const m="color: "+this.color;a.splice(1,0,m,"color: inherit");let d=0,l=0;a[0].replace(/%[a-zA-Z%]/g,p=>{p!=="%%"&&(d++,p==="%c"&&(l=d))}),a.splice(l,0,m)}e.log=console.debug||console.log||(()=>{});function s(a){try{a?e.storage.setItem("debug",a):e.storage.removeItem("debug")}catch{}}function n(){let a;try{a=e.storage.getItem("debug")||e.storage.getItem("DEBUG")}catch{}return!a&&typeof process<"u"&&"env"in process&&(a=process.env.DEBUG),a}function i(){try{return localStorage}catch{}}t.exports=Co()(e);const{formatters:c}=t.exports;c.j=function(a){try{return JSON.stringify(a)}catch(m){return"[UnexpectedJSONParseError]: "+m.message}}}(Le,Le.exports)),Le.exports}var De={exports:{}},zt,$o;function ka(){return $o||($o=1,zt=(t,e=process.argv)=>{const r=t.startsWith("-")?"":t.length===1?"-":"--",o=e.indexOf(r+t),s=e.indexOf("--");return o!==-1&&(s===-1||o<s)}),zt}var Kt,Eo;function Aa(){if(Eo)return Kt;Eo=1;const t=Ee,e=$r,r=ka(),{env:o}=process;let s;r("no-color")||r("no-colors")||r("color=false")||r("color=never")?s=0:(r("color")||r("colors")||r("color=true")||r("color=always"))&&(s=1),"FORCE_COLOR"in o&&(o.FORCE_COLOR==="true"?s=1:o.FORCE_COLOR==="false"?s=0:s=o.FORCE_COLOR.length===0?1:Math.min(parseInt(o.FORCE_COLOR,10),3));function n(a){return a===0?!1:{level:a,hasBasic:!0,has256:a>=2,has16m:a>=3}}function i(a,m){if(s===0)return 0;if(r("color=16m")||r("color=full")||r("color=truecolor"))return 3;if(r("color=256"))return 2;if(a&&!m&&s===void 0)return 0;const d=s||0;if(o.TERM==="dumb")return d;if(process.platform==="win32"){const l=t.release().split(".");return Number(l[0])>=10&&Number(l[2])>=10586?Number(l[2])>=14931?3:2:1}if("CI"in o)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE"].some(l=>l in o)||o.CI_NAME==="codeship"?1:d;if("TEAMCITY_VERSION"in o)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(o.TEAMCITY_VERSION)?1:0;if(o.COLORTERM==="truecolor")return 3;if("TERM_PROGRAM"in o){const l=parseInt((o.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(o.TERM_PROGRAM){case"iTerm.app":return l>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(o.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(o.TERM)||"COLORTERM"in o?1:d}function c(a){const m=i(a,a&&a.isTTY);return n(m)}return Kt={supportsColor:c,stdout:n(i(!0,e.isatty(1))),stderr:n(i(!0,e.isatty(2)))},Kt}De.exports;var xo;function Sa(){return xo||(xo=1,function(t,e){const r=$r,o=hr;e.init=d,e.log=c,e.formatArgs=n,e.save=a,e.load=m,e.useColors=s,e.destroy=o.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."),e.colors=[6,2,3,4,5,1];try{const p=Aa();p&&(p.stderr||p).level>=2&&(e.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221])}catch{}e.inspectOpts=Object.keys(process.env).filter(p=>/^debug_/i.test(p)).reduce((p,u)=>{const h=u.substring(6).toLowerCase().replace(/_([a-z])/g,(y,w)=>w.toUpperCase());let g=process.env[u];return/^(yes|on|true|enabled)$/i.test(g)?g=!0:/^(no|off|false|disabled)$/i.test(g)?g=!1:g==="null"?g=null:g=Number(g),p[h]=g,p},{});function s(){return"colors"in e.inspectOpts?!!e.inspectOpts.colors:r.isatty(process.stderr.fd)}function n(p){const{namespace:u,useColors:h}=this;if(h){const g=this.color,y="\x1B[3"+(g<8?g:"8;5;"+g),w=` ${y};1m${u} \x1B[0m`;p[0]=w+p[0].split(`
|
|
75
71
|
`).join(`
|
|
76
72
|
`+w),p.push(y+"m+"+t.exports.humanize(this.diff)+"\x1B[0m")}else p[0]=i()+u+" "+p[0]}function i(){return e.inspectOpts.hideDate?"":new Date().toISOString()+" "}function c(...p){return process.stderr.write(o.formatWithOptions(e.inspectOpts,...p)+`
|
|
77
73
|
`)}function a(p){p?process.env.DEBUG=p:delete process.env.DEBUG}function m(){return process.env.DEBUG}function d(p){p.inspectOpts={};const u=Object.keys(e.inspectOpts);for(let h=0;h<u.length;h++)p.inspectOpts[u[h]]=e.inspectOpts[u[h]]}t.exports=Co()(e);const{formatters:l}=t.exports;l.o=function(p){return this.inspectOpts.colors=this.useColors,o.inspect(p,this.inspectOpts).split(`
|
|
78
|
-
`).map(u=>u.trim()).join(" ")},l.O=function(p){return this.inspectOpts.colors=this.useColors,o.inspect(p,this.inspectOpts)}}(
|
|
79
|
-
`).some(e=>e.indexOf("(https.js:")!==-1||e.indexOf("node:https:")!==-1)}function nt(t,e){return new nt.Agent(t,e)}(function(t){class e extends
|
|
74
|
+
`).map(u=>u.trim()).join(" ")},l.O=function(p){return this.inspectOpts.colors=this.useColors,o.inspect(p,this.inspectOpts)}}(De,De.exports)),De.exports}typeof process>"u"||process.type==="renderer"||process.browser===!0||process.__nwjs?Ht.exports=xa():Ht.exports=Sa();var Wt=Ht.exports,Jt={};Object.defineProperty(Jt,"__esModule",{value:!0});function Ma(t){return function(e,r){return new Promise((o,s)=>{t.call(this,e,r,(n,i)=>{n?s(n):o(i)})})}}Jt.default=Ma;var ko=G&&G.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};const Ia=pr,Ra=ko(Wt),Oa=ko(Jt),Te=Ra.default("agent-base");function La(t){return!!t&&typeof t.addRequest=="function"}function Yt(){const{stack:t}=new Error;return typeof t!="string"?!1:t.split(`
|
|
75
|
+
`).some(e=>e.indexOf("(https.js:")!==-1||e.indexOf("node:https:")!==-1)}function nt(t,e){return new nt.Agent(t,e)}(function(t){class e extends Ia.EventEmitter{constructor(o,s){super();let n=s;typeof o=="function"?this.callback=o:o&&(n=o),this.timeout=null,n&&typeof n.timeout=="number"&&(this.timeout=n.timeout),this.maxFreeSockets=1,this.maxSockets=1,this.maxTotalSockets=1/0,this.sockets={},this.freeSockets={},this.requests={},this.options={}}get defaultPort(){return typeof this.explicitDefaultPort=="number"?this.explicitDefaultPort:Yt()?443:80}set defaultPort(o){this.explicitDefaultPort=o}get protocol(){return typeof this.explicitProtocol=="string"?this.explicitProtocol:Yt()?"https:":"http:"}set protocol(o){this.explicitProtocol=o}callback(o,s,n){throw new Error('"agent-base" has no default implementation, you must subclass and override `callback()`')}addRequest(o,s){const n=Object.assign({},s);typeof n.secureEndpoint!="boolean"&&(n.secureEndpoint=Yt()),n.host==null&&(n.host="localhost"),n.port==null&&(n.port=n.secureEndpoint?443:80),n.protocol==null&&(n.protocol=n.secureEndpoint?"https:":"http:"),n.host&&n.path&&delete n.path,delete n.agent,delete n.hostname,delete n._defaultAgent,delete n.defaultPort,delete n.createConnection,o._last=!0,o.shouldKeepAlive=!1;let i=!1,c=null;const a=n.timeout||this.timeout,m=u=>{o._hadError||(o.emit("error",u),o._hadError=!0)},d=()=>{c=null,i=!0;const u=new Error(`A "socket" was not created for HTTP request before ${a}ms`);u.code="ETIMEOUT",m(u)},l=u=>{i||(c!==null&&(clearTimeout(c),c=null),m(u))},p=u=>{if(i)return;if(c!=null&&(clearTimeout(c),c=null),La(u)){Te("Callback returned another Agent instance %o",u.constructor.name),u.addRequest(o,n);return}if(u){u.once("free",()=>{this.freeSocket(u,n)}),o.onSocket(u);return}const h=new Error(`no Duplex stream was returned to agent-base for \`${o.method} ${o.path}\``);m(h)};if(typeof this.callback!="function"){m(new Error("`callback` is not defined"));return}this.promisifiedCallback||(this.callback.length>=3?(Te("Converting legacy callback function to promise"),this.promisifiedCallback=Oa.default(this.callback)):this.promisifiedCallback=this.callback),typeof a=="number"&&a>0&&(c=setTimeout(d,a)),"port"in n&&typeof n.port!="number"&&(n.port=Number(n.port));try{Te("Resolving socket for %o request: %o",n.protocol,`${o.method} ${o.path}`),Promise.resolve(this.promisifiedCallback(o,n)).then(p,l)}catch(u){Promise.reject(u).catch(l)}}freeSocket(o,s){Te("Freeing socket %o %o",o.constructor.name,s),o.destroy()}destroy(){Te("Destroying agent %o",this.constructor.name)}}t.Agent=e,t.prototype=t.Agent.prototype})(nt||(nt={}));var Da=nt,Vt={},Ta=G&&G.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Vt,"__esModule",{value:!0});const Fa=Ta(Wt),Fe=Fa.default("https-proxy-agent:parse-proxy-response");function Na(t){return new Promise((e,r)=>{let o=0;const s=[];function n(){const l=t.read();l?d(l):t.once("readable",n)}function i(){t.removeListener("end",a),t.removeListener("error",m),t.removeListener("close",c),t.removeListener("readable",n)}function c(l){Fe("onclose had error %o",l)}function a(){Fe("onend")}function m(l){i(),Fe("onerror %o",l),r(l)}function d(l){s.push(l),o+=l.length;const p=Buffer.concat(s,o);if(p.indexOf(`\r
|
|
80
76
|
\r
|
|
81
77
|
`)===-1){Fe("have not received end of HTTP headers yet..."),n();return}const h=p.toString("ascii",0,p.indexOf(`\r
|
|
82
|
-
`)),g=+h.split(" ")[1];Fe("got proxy server response: %o",h),e({statusCode:g,buffered:p})}t.on("error",m),t.on("close",c),t.on("end",a),n()})}
|
|
83
|
-
`;o.auth&&(i["Proxy-Authorization"]=`Basic ${Buffer.from(o.auth).toString("base64")}`);let{host:m,port:d,secureEndpoint:l}=r;
|
|
84
|
-
`;const p=
|
|
85
|
-
`);const{statusCode:u,buffered:h}=yield p;if(u===200){if(e.once("socket",
|
|
78
|
+
`)),g=+h.split(" ")[1];Fe("got proxy server response: %o",h),e({statusCode:g,buffered:p})}t.on("error",m),t.on("close",c),t.on("end",a),n()})}Vt.default=Na;var ja=G&&G.__awaiter||function(t,e,r,o){function s(n){return n instanceof r?n:new r(function(i){i(n)})}return new(r||(r=Promise))(function(n,i){function c(d){try{m(o.next(d))}catch(l){i(l)}}function a(d){try{m(o.throw(d))}catch(l){i(l)}}function m(d){d.done?n(d.value):s(d.value).then(c,a)}m((o=o.apply(t,e||[])).next())})},Pe=G&&G.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Gt,"__esModule",{value:!0});const Ao=Pe(hs),So=Pe(gs),_a=Pe(ys),Ga=Pe(fr),Ha=Pe(Wt),Ba=Da,Ua=Pe(Vt),Ne=Ha.default("https-proxy-agent:agent");class za extends Ba.Agent{constructor(e){let r;if(typeof e=="string"?r=_a.default.parse(e):r=e,!r)throw new Error("an HTTP(S) proxy server `host` and `port` must be specified!");Ne("creating new HttpsProxyAgent instance: %o",r),super(r);const o=Object.assign({},r);this.secureProxy=r.secureProxy||Ja(o.protocol),o.host=o.hostname||o.host,typeof o.port=="string"&&(o.port=parseInt(o.port,10)),!o.port&&o.host&&(o.port=this.secureProxy?443:80),this.secureProxy&&!("ALPNProtocols"in o)&&(o.ALPNProtocols=["http 1.1"]),o.host&&o.path&&(delete o.path,delete o.pathname),this.proxy=o}callback(e,r){return ja(this,void 0,void 0,function*(){const{proxy:o,secureProxy:s}=this;let n;s?(Ne("Creating `tls.Socket`: %o",o),n=So.default.connect(o)):(Ne("Creating `net.Socket`: %o",o),n=Ao.default.connect(o));const i=Object.assign({},o.headers);let a=`CONNECT ${`${r.host}:${r.port}`} HTTP/1.1\r
|
|
79
|
+
`;o.auth&&(i["Proxy-Authorization"]=`Basic ${Buffer.from(o.auth).toString("base64")}`);let{host:m,port:d,secureEndpoint:l}=r;Wa(d,l)||(m+=`:${d}`),i.Host=m,i.Connection="close";for(const y of Object.keys(i))a+=`${y}: ${i[y]}\r
|
|
80
|
+
`;const p=Ua.default(n);n.write(`${a}\r
|
|
81
|
+
`);const{statusCode:u,buffered:h}=yield p;if(u===200){if(e.once("socket",Ka),r.secureEndpoint){Ne("Upgrading socket connection to TLS");const y=r.servername||r.host;return So.default.connect(Object.assign(Object.assign({},Ya(r,"host","hostname","path","port")),{socket:n,servername:y}))}return n}n.destroy();const g=new Ao.default.Socket({writable:!1});return g.readable=!0,e.once("socket",y=>{Ne("replaying proxy buffer for failed request"),Ga.default(y.listenerCount("data")>0),y.push(h),y.push(null)}),g})}}Gt.default=za;function Ka(t){t.resume()}function Wa(t,e){return!!(!e&&t===80||e&&t===443)}function Ja(t){return typeof t=="string"?/^https:?$/i.test(t):!1}function Ya(t,...e){const r={};let o;for(o in t)e.includes(o)||(r[o]=t[o]);return r}var Va=G&&G.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};const qt=Va(Gt);function Xt(t){return new qt.default(t)}(function(t){t.HttpsProxyAgent=qt.default,t.prototype=qt.default.prototype})(Xt||(Xt={}));var qa=Xt,Xa=de(qa);const Qa=async(t,e,r,o,s,n,i)=>new Promise((c,a)=>{const m=JSON.stringify(o),l=(t.protocol.includes("https")?ps:fs).request({port:i||void 0,hostname:t.hostname,path:e,method:"POST",headers:{"Content-Type":"application/json","Content-Length":Buffer.byteLength(m),...r},timeout:s,agent:n?Xa(n):void 0},p=>{const u=[];p.on("data",h=>u.push(h)),p.on("end",()=>{c({request:l,response:p,data:Buffer.concat(u).toString()})})});l.on("error",a),l.on("timeout",()=>{l.destroy(),a(new b(`Time out error: request took over ${s}ms. Try increasing the \`timeout\` config`))}),l.write(m),l.end()}),Za=async(t,e,r,o,s,n)=>{const i=new URL(t),{response:c,data:a}=await Qa(i,e,{Authorization:`Bearer ${r}`},o,s,n);if(!c.statusCode||c.statusCode<200||c.statusCode>299){let m=`API Error: ${c.statusCode} - ${c.statusMessage}`;throw a&&(m+=`
|
|
86
82
|
|
|
87
83
|
${a}`),c.statusCode===500&&(m+=`
|
|
88
84
|
|
|
89
|
-
Check the API status: ${t}`),new b(m)}return JSON.parse(a)},Mo=t=>t.trim(),
|
|
85
|
+
Check the API status: ${t}`),new b(m)}return JSON.parse(a)},Mo=t=>t.trim(),Qt=t=>["gpt-5","gpt-5-mini","gpt-5-nano"].some(e=>t.includes(e)),ec=async(t,e,r,o,s,n,i,c,a,m,d,l,p,u)=>{try{const h=Ce(n,p),g=Qt(s),y={model:s,messages:[{role:"system",content:d},{role:"user",content:h}],stream:!1,n:1,frequency_penalty:0,presence_penalty:0,...g?{max_completion_tokens:c,temperature:1}:{max_tokens:c,top_p:m,temperature:a}},w=new URL(e),v=`${w.protocol}//${w.host}${r}`,E={Authorization:`Bearer ${o}`,"Content-Type":"application/json"};Y(n,p,t,s,v,E,l),V(n,p,t,d,h,l),te(n,p,t,y,l);const A=Date.now(),$=await Za(e,r,o,y,i,u),C=Date.now()-A;q(n,p,t,$,l);const S=$.choices.filter(T=>T.message?.content).map(T=>Mo(T.message.content)).join();return z(n,p,t,C,S,l),$.choices.filter(T=>T.message?.content).map(T=>Mo(T.message.content))}catch(h){_(n,p,t,h,l);const g=h;throw g.code==="ENOTFOUND"?new b(`Error connecting to ${g.hostname} (${g.syscall})`):g}};class tc extends X{constructor(e){super(e),this.params=e,this.baseURL="https://models.github.ai",this.colors={primary:"#24292e",secondary:"#FFF"},this.serviceName=P.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[GitHub Models]"),this.errorPrefix=P.red.bold("[GitHub Models]")}getServiceSpecificErrorMessage(e){switch(e.code){case"MISSING_TOKEN":return"GitHub token is required. Run: aicommit2 github-login";case"AUTHENTICATION_FAILED":return"Authentication failed. Your GitHub token may be expired or invalid. Run: aicommit2 github-login";case"ACCESS_DENIED":return'Access denied. Make sure your GitHub token has "Models" permission in GitHub settings';case"NO_CONTENT":return"No content received from GitHub Models. The model may have failed to generate a response";default:return null}}generateCommitMessage$(){return D(this.generateMessage("commit")).pipe(L(e=>M(e)),I(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:this.params.config.includeBody?e.value:e.title,description:this.params.config.includeBody?e.value:"",isError:!1})),R(this.handleError$))}generateCodeReview$(){return D(this.generateMessage("review")).pipe(L(e=>M(e)),I(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),R(this.handleError$))}async generateMessage(e){if(!this.params.config.key){const u=new Error("GitHub token is required for GitHub Models. Use: aicommit2 github-login");throw u.code="MISSING_TOKEN",u}const r=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n,locale:i,generate:c,type:a,maxLength:m}=this.params.config,d={...K,locale:i,maxLength:m,type:a,generate:c,systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n},l=e==="review"?Z(d):Q(d),p=await this.makeRequest(l,r,e);return e==="review"?this.sanitizeResponse(p):this.parseMessage(p,a,c)}async makeRequest(e,r,o){const s=Array.isArray(this.params.config.model)?this.params.config.model[0]:this.params.config.model||"gpt-4o-mini",n=[{role:"system",content:e},{role:"user",content:o==="review"?r:`Here's the diff:
|
|
90
86
|
|
|
91
|
-
${r}`}],i=
|
|
87
|
+
${r}`}],i=Qt(s),c={messages:n,model:s,stream:!1,...i?{max_completion_tokens:this.params.config.maxTokens||1024,temperature:1}:{max_tokens:this.params.config.maxTokens||1024,top_p:this.params.config.topP||.95,temperature:this.params.config.temperature||.7}},a=`${this.baseURL}/inference/chat/completions`,m={"Content-Type":"application/json",Accept:"application/vnd.github+json",Authorization:`Bearer ${this.params.config.key}`},{logging:d}=this.params.config;Y(r,o,"GitHub Models",s,a,m,d),V(r,o,"GitHub Models",e,o==="review"?r:`Here's the diff:
|
|
92
88
|
|
|
93
|
-
${r}`,d),te(r,o,"GitHub Models",c,d);const l=new AbortController,p=setTimeout(()=>l.abort(),this.params.config.timeout);try{const u=Date.now(),h=await fetch(a,{method:"POST",headers:m,body:JSON.stringify(c),signal:l.signal});if(clearTimeout(p),!h.ok){const v=await h.text(),E={status:h.status,statusText:h.statusText,url:a,headers:Object.fromEntries(h.headers),body:v};_(r,o,"GitHub Models",E,d);let x=`GitHub API request failed: ${h.status} ${h.statusText}`;try{const C=JSON.parse(v);C.error?.message?x+=` - ${C.error.message}`:C.message&&(x+=` - ${C.message}`)}catch{v&&(x+=` - ${v}`)}if(h.status===401){const C=new Error("GitHub authentication failed. Please run: aicommit2 github-login");throw C.status=h.status,C.code="AUTHENTICATION_FAILED",C.content=v,C}else if(h.status===403){const C=new Error('GitHub Models access denied. Make sure your token has "Models" permission.');throw C.status=h.status,C.code="ACCESS_DENIED",C.content=v,C}else if(h.status===404){const C=new Error(`Model "${s}" not found. Please check the model name.`);throw C.status=h.status,C.code="MODEL_NOT_FOUND",C.content=v,C}else if(h.status===429){const C=new Error("Rate limit exceeded. Please try again later.");throw C.status=h.status,C.code="RATE_LIMIT_EXCEEDED",C.content=v,C}const $=new Error(x);throw $.status=h.status,$.code="API_ERROR",$.content=v,$}const g=await h.json(),y=Date.now()-u;q(r,o,"GitHub Models",g,d);const w=g.choices?.[0]?.message?.content?.trim();if(!w){_(r,o,"GitHub Models",{message:"No content found in GitHub Models response",result:g},d);const E=new Error("No response content received from GitHub Models");throw E.code="NO_CONTENT",E.content=JSON.stringify(g,null,2),E}return z(r,o,"GitHub Models",y,w,d),w}catch(u){if(clearTimeout(p),u instanceof Error&&u.name==="AbortError"){const y={message:`GitHub Models request timeout after ${this.params.config.timeout}ms`,error:u};_(r,o,"GitHub Models",y,d);const w=new Error(`GitHub Models request timed out after ${this.params.config.timeout}ms`);throw w.code="REQUEST_TIMEOUT",w.originalError=u,w}if(u.code)throw u;_(r,o,"GitHub Models",{message:"GitHub Models request failed",error:u},d);const g=new Error(`GitHub Models request failed: ${u instanceof Error?u.message:String(u)}`);throw g.code="REQUEST_FAILED",g.originalError=u,g}}}class ec extends X{constructor(e){super(e),this.params=e,this.colors={primary:"#f55036",secondary:"#fff"},this.serviceName=P.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[Groq]"),this.errorPrefix=P.red.bold("[Groq]"),this.groq=new ws({apiKey:this.params.config.key})}getServiceSpecificErrorMessage(e){const r=e.message||"";return r.includes("API key")||r.includes("api_key")?"Invalid API key. Check your Groq API key in configuration":r.includes("rate_limit")||r.includes("Rate limit")?"Rate limit exceeded. Wait a moment and try again, or upgrade your Groq plan":r.includes("model")||r.includes("Model")?"Model not found or not accessible. Check if the Groq model name is correct":r.includes("overloaded")||r.includes("capacity")?"Groq service is overloaded. Try again in a few minutes":r.includes("403")||r.includes("Forbidden")?"Access denied. Your API key may not have permission for this Groq model":r.includes("404")||r.includes("Not Found")?"Model or endpoint not found. Check your Groq model configuration":r.includes("500")||r.includes("Internal Server Error")?"Groq server error. Try again later":null}generateCommitMessage$(){return j(this.generateMessage("commit")).pipe(L(e=>M(e)),I(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:this.params.config.includeBody?e.value:e.title,description:this.params.config.includeBody?e.value:"",isError:!1})),R(this.handleError$))}generateCodeReview$(){return j(this.generateMessage("review")).pipe(L(e=>M(e)),I(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),R(this.handleError$))}async generateMessage(e){const r=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n,logging:i,locale:c,temperature:a,generate:m,type:d,maxLength:l}=this.params.config,p=this.params.config.maxTokens,u={...J,locale:c,maxLength:l,type:d,generate:m,systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n},h=e==="review"?Z(u):Q(u),g=`Here is the diff: ${r}`,w=`${this.params.config.url||"https://api.groq.com"}/openai/v1/chat/completions`,v={Authorization:`Bearer ${this.params.config.key}`,"Content-Type":"application/json"};Y(r,e,"Groq",this.params.config.model,w,v,i),V(r,e,"Groq",h,g,i);const E={messages:[{role:"system",content:h},{role:"user",content:g}],model:this.params.config.model,max_tokens:p,top_p:this.params.config.topP,temperature:a};te(r,e,"Groq",E,i);const x=Date.now();try{const $=await this.groq.chat.completions.create(E,{timeout:this.params.config.timeout}),C=Date.now()-x,A=$.choices[0].message.content||"";return q(r,e,"Groq",$,i),z(r,e,"Groq",C,A,i),e==="review"?this.sanitizeResponse(A):this.parseMessage(A,d,m)}catch($){throw _(r,e,"Groq",$,i),$}}}class tc extends X{constructor(e){super(e),this.params=e,this.headers={},this.models=[],this.currentModelId=null,this.currentConversation=void 0,this.currentConversionID=void 0,this.cookie="",this.colors={primary:"#FED21F",secondary:"#000"},this.serviceName=P.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[HuggingFace]"),this.errorPrefix=P.red.bold("[HuggingFace]"),this.cookie=this.params.config.cookie;const r=this.params.config.url||"https://huggingface.co";this.headers={accept:"*/*","accept-language":"en-US,en;q=0.9","sec-ch-ua":'"Chromium";v="116", "Not)A;Brand";v="24", "Google Chrome";v="116"',"sec-ch-ua-mobile":"?0","sec-ch-ua-platform":'"Windows"',"sec-fetch-dest":"empty","sec-fetch-mode":"cors","sec-fetch-site":"same-origin",origin:r,"Referrer-Policy":"strict-origin-when-cross-origin"}}getServiceSpecificErrorMessage(e){const r=e.message||"";return r.includes("cookie")||r.includes("Cookie")?"Invalid cookie. Check your Hugging Face session cookie in configuration":r.includes("model")||r.includes("Model")?"Model not found or not accessible. Check if the Hugging Face model name is correct":r.includes("conversation")||r.includes("conversion")?"Failed to create conversation. Try again or check your session":r.includes("401")||r.includes("Unauthorized")?"Authentication failed. Your Hugging Face session may have expired":r.includes("403")||r.includes("Forbidden")?"Access denied. You may not have permission to access this model":r.includes("404")||r.includes("Not Found")?"Model not found. Check your Hugging Face model configuration":r.includes("500")||r.includes("Internal Server Error")?"Hugging Face server error. Try again later":r.includes("overloaded")||r.includes("capacity")?"Hugging Face service is overloaded. Try again in a few minutes":null}generateCommitMessage$(){return j(this.generateMessage("commit")).pipe(L(e=>M(e)),I(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:this.params.config.includeBody?e.value:e.title,description:this.params.config.includeBody?e.value:"",isError:!1})),R(this.handleError$))}generateCodeReview$(){return j(this.generateMessage("review")).pipe(L(e=>M(e)),I(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),R(this.handleError$))}async generateMessage(e){await this.initialize();const r=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n,logging:i,locale:c,generate:a,type:m,maxLength:d,temperature:l,maxTokens:p,topP:u,timeout:h}=this.params.config,g={...J,locale:c,maxLength:d,type:m,generate:a,systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n},y=e==="review"?Z(g):Q(g),w=`Here is the diff: ${r}`,E=`${this.params.config.url||"https://huggingface.co"}/chat/conversation`,x={...this.headers,cookie:this.cookie};Y(r,e,"HuggingFace",this.params.config.model,E,x,i),V(r,e,"HuggingFace",y,w,i);const $=Date.now();try{const C=await this.getNewChat(y),D=await(await this.sendMessage(w,C.id)).completeResponsePromise();await this.deleteConversation(C.id);const N=Date.now()-$;return q(r,e,"HuggingFace",{response:D},i),z(r,e,"HuggingFace",N,D,i),e==="review"?this.sanitizeResponse(D):this.parseMessage(D,m,a)}catch(C){throw _(r,e,"HuggingFace",C,i),C}}async initialize(){const e=await this.getRemoteLlms(),r=e.find(o=>o.name?.toLowerCase()===this.params.config.model.toLowerCase());if(r){this.currentModel=r,this.currentModelId=r.id;return}this.currentModel=e[0],this.currentModelId=e[0].id}async getRemoteLlms(){const e=this.params.config.url||"https://huggingface.co",r=await fetch(`${e}/chat/__data.json`,{headers:{...this.headers,cookie:this.cookie},body:null,method:"GET"});if(r.status!==200)throw new Error(`Failed to get remote LLMs with status code: ${r.status}`);const s=(await r.json()).nodes[0].data,n=s[s[0].models],i=[],c=a=>a===-1?null:s[a];for(const a of n){const m=s[a];if(s[m.unlisted])continue;const d={id:c(m.id),name:c(m.name),displayName:c(m.displayName),preprompt:c(m.preprompt),promptExamples:[],websiteUrl:c(m.websiteUrl),description:c(m.description),datasetName:c(m.datasetName),datasetUrl:c(m.datasetUrl),modelUrl:c(m.modelUrl),parameters:{}},l=c(m.promptExamples);if(l!==null){const h=l.map(g=>c(g));d.promptExamples=h.map(g=>({title:s[g.title],prompt:s[g.prompt]}))}const p=c(m.parameters),u={};for(const[h,g]of Object.entries(p)){if(g===-1){u[h]=null;continue}if(Array.isArray(s[g])){u[h]=s[g].map(y=>s[y]);continue}u[h]=s[g]}d.parameters=u,i.push(d)}return this.models=i,i}async getNewChat(e){const r={model:this.currentModelId,preprompt:e};let o=0;const s=this.params.config.url||"https://huggingface.co";for(;o<5;){const n=await fetch(`${s}/chat/conversation`,{headers:{...this.headers,"content-type":"application/json",cookie:this.cookie,Referer:`${s}/chat/`},body:JSON.stringify(r),method:"POST"}),{conversationId:i}=await n.json();if(i){this.currentConversionID=i;break}else o++}if(!this.currentConversionID)throw new Error("Failed to create new conversion");return await this.getConversationHistory(this.currentConversionID)}async getConversationHistory(e){if(!e)throw new Error("conversationId is required for getConversationHistory");const r=this.params.config.url||"https://huggingface.co",o=await fetch(`${r}/chat/conversation/${e}/__data.json`,{headers:{...this.headers,cookie:this.cookie,Referer:`${r}/chat/`},body:null,method:"GET"});if(o.status!=200)throw new Error("Unable get conversation details "+o);{const s=await o.json();return this.metadataParser(s,e)}}metadataParser(e,r){const o={id:"",model:"",systemPrompt:"",title:"",history:[]},s=e.nodes[1].data,n=s[s[0].model],i=s[s[0].preprompt],c=s[s[0].title],a=s[s[0].messages],m=[];for(const d of a){const l=s[d],p=new Date(s[l.createdAt][1]).getTime()/1e3,u=new Date(s[l.updatedAt][1]).getTime()/1e3;m.push({id:s[l.id],role:s[l.from],content:s[l.content],createdAt:p,updatedAt:u})}return o.id=r,o.model=n,o.systemPrompt=i,o.title=c,o.history=m,this.currentConversation=o,o}async sendMessage(e,r){if(e==="")throw new Error("the prompt can not be empty.");if(!r&&!this.currentConversionID?await this.getNewChat():r?(this.currentConversionID=r,await this.getConversationHistory(r)):this.currentConversionID&&await this.getConversationHistory(this.currentConversionID),!this.currentConversation)throw new Error("Failed to create new conversion");const o={inputs:e,id:this.currentConversation.history[this.currentConversation.history.length-1].id,is_retry:!1,is_continue:!1,web_search:!1,tools:[]},s=new FormData;s.append("data",JSON.stringify(o));const n=this.params.config.url||"https://huggingface.co",i=new AbortController,c=setTimeout(()=>i.abort(),this.params.config.timeout),a=await fetch(`${n}/chat/conversation/${this.currentConversionID}`,{headers:{...this.headers,cookie:this.cookie,Referer:`${n}/chat/conversation/${this.currentConversionID}`},body:s,method:"POST",signal:i.signal});clearTimeout(c);function m(g){try{const y=g.split(`
|
|
94
|
-
`),w=[];for(const v of y)v.trim()&&w.push(JSON.parse(v));return w}catch{return[{}]}}const d=new TextDecoder;let l="";const p=new TransformStream({async transform(g,y){const w=d.decode(g);try{const v=m(w);for(const E of v)E.type==="finalAnswer"?(l=E?.text||"",y.terminate()):E.type==="stream"&&y.enqueue(E?.token||"")}catch{throw new Error("Error during parsing response")}}}),u=a.body?.pipeThrough(p);async function h(){return new Promise(async(g,y)=>{try{if(!u)y("ModifiedStream undefined");else{const w=u.getReader();for(;;){const{done:v,value:E}=await w.read();if(v){g(l);break}}}}catch(w){y(w)}})}return{id:this.currentConversionID,stream:u,completeResponsePromise:h}}async deleteConversation(e){const r=this.params.config.url||"https://huggingface.co";return(await fetch(`${r}/chat/conversation/${e}`,{headers:{...this.headers,cookie:this.cookie,Referer:`${r}/chat/`},body:null,method:"DELETE"})).json()}}class rc extends X{constructor(e){super(e),this.params=e,this.apiKey="",this.colors={primary:"#ff7000",secondary:"#fff"},this.serviceName=P.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[MistralAI]"),this.errorPrefix=P.red.bold("[MistralAI]"),this.apiKey=this.params.config.key}getServiceSpecificErrorMessage(e){const r=e.message||"";return r.includes("API key")||r.includes("api_key")?"Invalid API key. Check your Mistral AI API key in configuration":r.includes("quota")||r.includes("usage")?"API quota exceeded. Check your Mistral AI usage limits":r.includes("model")||r.includes("Model")?"Model not found or not accessible. Check if the Mistral model name is correct":r.includes("403")||r.includes("Forbidden")?"Access denied. Your API key may not have permission for this Mistral model":r.includes("404")||r.includes("Not Found")?"Model or endpoint not found. Check your Mistral model configuration":r.includes("500")||r.includes("Internal Server Error")?"Mistral AI server error. Try again later":null}generateCommitMessage$(){return j(this.generateMessage("commit")).pipe(L(e=>M(e)),I(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:this.params.config.includeBody?e.value:e.title,description:this.params.config.includeBody?e.value:"",isError:!1})),R(this.handleError$))}generateCodeReview$(){return j(this.generateMessage("review")).pipe(L(e=>M(e)),I(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),R(this.handleError$))}async generateMessage(e){const r=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n,logging:i,locale:c,generate:a,type:m,maxLength:d}=this.params.config,l={...J,locale:c,maxLength:d,type:m,generate:a,systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n},p=e==="review"?Z(l):Q(l);await this.checkAvailableModels();const u=`Here is the diff: ${r}`,g=`${this.params.config.url||"https://api.mistral.ai"}/v1/chat/completions`,y={Authorization:`Bearer ${this.apiKey}`,"content-type":"application/json"};Y(r,e,"MistralAI",this.params.config.model,g,y,i),V(r,e,"MistralAI",p,u,i);const w=await this.createChatCompletions(p,u,e);return e==="review"?this.sanitizeResponse(w):this.parseMessage(w,m,a)}async checkAvailableModels(){if((await this.getAvailableModels()).includes(this.params.config.model))return!0;throw new Error(`Invalid model type of Mistral AI: ${this.params.config.model}`)}async getAvailableModels(){const e=this.params.config.url||"https://api.mistral.ai";return(await new Oe({method:"GET",baseURL:`${e}/v1/models`,timeout:this.params.config.timeout}).setHeaders({Authorization:`Bearer ${this.apiKey}`,"content-type":"application/json"}).execute()).data.data.filter(o=>o.object==="model").map(o=>o.id)}async createChatCompletions(e,r,o){const s=this.params.stagedDiff.diff,{logging:n}=this.params.config,i={model:this.params.config.model,messages:[{role:"system",content:e},{role:"user",content:r}],temperature:this.params.config.temperature,top_p:this.params.config.topP,max_tokens:this.params.config.maxTokens,stream:!1,safe_prompt:!1,random_seed:Ze(10,1e3)};te(s,o,"MistralAI",i,n);const c=Date.now();try{const a=this.params.config.url||"https://api.mistral.ai",m=await new Oe({method:"POST",baseURL:`${a}/v1/chat/completions`,timeout:this.params.config.timeout}).setHeaders({Authorization:`Bearer ${this.apiKey}`,"content-type":"application/json"}).setBody(i).execute(),d=Date.now()-c,l=m.data;if(q(s,o,"MistralAI",l,n),!l.choices||l.choices.length===0||!l.choices[0].message?.content)throw _(s,o,"MistralAI",{message:"No Content on response",result:l},n),new Error("No Content on response. Please open a Bug report");const u=l.choices[0].message.content;return z(s,o,"MistralAI",d,u,n),u}catch(a){throw _(s,o,"MistralAI",a,n),a}}}class oc extends X{constructor(e){super(e),this.params=e,this.host=Tt,this.model="",this.key="",this.auth="",this.setupFetch=(r,o={})=>bs(r,{...o,dispatcher:new Cs({headersTimeout:this.params.config.timeout})}),this.colors={primary:"#FFF",secondary:"#000"},this.model=this.params.keyName,this.serviceName=P.bgHex(this.colors.primary).hex(this.colors.secondary).bold(`[${Qe(this.model)}]`),this.errorPrefix=P.red.bold(`[${Qe(this.model)}]`),this.host=this.params.config.host||Tt,this.auth=this.params.config.auth||"Bearer",this.key=this.params.config.key||"",this.ollama=new vs({host:this.host,fetch:this.setupFetch,...this.key&&{headers:{Authorization:`${this.auth} ${this.key}`}}})}getServiceSpecificErrorMessage(e){const r=e.message||"";return r.includes("ECONNREFUSED")||r.includes("connection")?`Cannot connect to Ollama server at ${this.host}. Make sure Ollama is running`:r.includes("model")||r.includes("Model")?`Model '${this.model}' not found. Pull the model with: ollama pull ${this.model}`:r.includes("401")||r.includes("Unauthorized")?"Authentication failed. Check your Ollama API key if authentication is enabled":r.includes("403")||r.includes("Forbidden")?"Access denied. Check your Ollama server permissions":r.includes("404")||r.includes("Not Found")?`Model '${this.model}' not found on Ollama server. Pull it first with: ollama pull ${this.model}`:r.includes("500")||r.includes("Internal Server Error")?"Ollama server error. Check server logs and try again":r.includes("overloaded")||r.includes("capacity")?"Ollama server is overloaded. Try again in a few minutes":null}generateCommitMessage$(){return j(this.generateMessage("commit")).pipe(L(e=>M(e)),I(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:this.params.config.includeBody?e.value:e.title,description:this.params.config.includeBody?e.value:"",isError:!1})),R(this.handleError$))}generateCodeReview$(){return j(this.generateMessage("review")).pipe(L(e=>M(e)),I(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),R(this.handleError$))}async generateMessage(e){const r=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n,logging:i,locale:c,generate:a,type:m,maxLength:d}=this.params.config,l={...J,locale:c,maxLength:d,type:m,generate:a,systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n},p=e==="review"?Z(l):Q(l);await this.checkIsAvailableOllama();const u=`Here is the diff: ${r}`,h=`Ollama_${this.model}`,g=`${this.host}/api/chat`,y=this.key?{Authorization:`${this.auth} ${this.key}`}:{};Y(r,e,h,this.model,g,y,i),V(r,e,h,p,u,i);const w=await this.createChatCompletions(p,u,e);return e==="review"?this.sanitizeResponse(w):this.parseMessage(w,m,a)}async checkIsAvailableOllama(){const e=new Oe({method:"GET",baseURL:`${this.host}`,timeout:this.params.config.timeout});return this.key&&e.setHeaders({Authorization:`${this.auth} ${this.key}`}),(await e.execute()).data}async createChatCompletions(e,r,o){const{stream:s,numCtx:n,temperature:i,topP:c,timeout:a,maxTokens:m,logging:d}=this.params.config,l=s||!1,p=this.params.stagedDiff.diff,u=`Ollama_${this.model}`,h={model:this.model,messages:[{role:"system",content:e},{role:"user",content:r}],stream:l,keep_alive:a,options:{num_ctx:n,temperature:i,top_p:c,seed:Ze(10,1e3),num_predict:m??-1}};te(p,o,u,h,d);const g=Date.now();try{const y=await this.ollama.chat(h),w=Date.now()-g;let v="";if(l){if(y)for await(const E of y)v+=E.message.content}else v=y.message.content;return q(p,o,u,{response:v,fullResponse:y},d),z(p,o,u,w,v,d),v}catch(y){throw _(p,o,u,y,d),y}}}class sc extends X{constructor(e){super(e),this.params=e;const r=this.params.keyName||"OPENAI_COMPATIBLE";this.colors=Qi(r),this.serviceName=P.bgHex(this.colors.primary).hex(this.colors.secondary).bold(`[${Qe(r)}]`),this.errorPrefix=P.red.bold(`[${Qe(r)}]`),this.openAI=new $r({apiKey:this.params.config.key,baseURL:`${this.params.config.url}${this.params.config.path}`})}getServiceSpecificErrorMessage(e){const r=e.message||"";return r.includes("API key")||r.includes("api_key")?"Invalid API key. Check your OpenAI-compatible API key in configuration":r.includes("rate_limit")||r.includes("Rate limit")?"Rate limit exceeded. Wait a moment and try again, or check your service limits":r.includes("model")||r.includes("Model")?"Model not found or not accessible. Check if the model name is correct":r.includes("network")||r.includes("connection")?"Network error. Check your internet connection and API endpoint":r.includes("quota")||r.includes("usage")?"API quota exceeded. Check your usage limits":r.includes("403")||r.includes("Forbidden")?"Access denied. Your API key may not have permission for this model":r.includes("404")||r.includes("Not Found")?"Model or endpoint not found. Check your API configuration":r.includes("500")||r.includes("Internal Server Error")?"Server error. Try again later":r.includes("overloaded")||r.includes("capacity")?"Service is overloaded. Try again in a few minutes":null}generateCommitMessage$(){return j(this.generateMessage("commit")).pipe(L(e=>M(e)),I(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:this.params.config.includeBody?e.value:e.title,description:this.params.config.includeBody?e.value:"",isError:!1})),R(this.handleError$))}generateCodeReview$(){return j(this.generateMessage("review")).pipe(L(e=>M(e)),I(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),R(this.handleError$))}async generateMessage(e){const r=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n,logging:i,locale:c,temperature:a,generate:m,type:d,maxLength:l,timeout:p,stream:u=!1}=this.params.config,h=this.params.config.maxTokens,g={...J,locale:c,maxLength:l,type:d,generate:m,systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n},y=e==="review"?Z(g):Q(g),w=`Here is the diff: ${r}`,v=this.params.keyName||"OpenAI-Compatible",E=`${this.params.config.url}${this.params.config.path}`,x={Authorization:`Bearer ${this.params.config.key}`,"Content-Type":"application/json"};Y(r,e,v,this.params.config.model,E,x,i),V(r,e,v,y,w,i);const $=Zt(this.params.config.model),C={messages:[{role:"system",content:y},{role:"user",content:w}],model:this.params.config.model,stream:u,...$?{max_completion_tokens:h,temperature:1}:{max_tokens:h,top_p:this.params.config.topP,temperature:a}};te(r,e,v,C,i);const A=Date.now();try{const D=await this.openAI.chat.completions.create(C,{timeout:p});let N="";if(u&&D){const zo=D;for await(const ur of zo){const Jo=ur.choices?.[0]?.delta?.content||"",Ko=ur.choices?.[0]?.delta?.reasoning_content||"",Wo=`${Jo}${Ko}`;N+=Wo}}else N=D.choices?.[0]?.message.content||"";const ie=Date.now()-A;return q(r,e,v,D,i),z(r,e,v,ie,N,i),e==="review"?this.sanitizeResponse(N):this.parseMessage(N,d,m)}catch(D){throw _(r,e,v,D,i),D}}}class nc extends X{constructor(e){super(e),this.params=e,this.colors={primary:"#74AA9C",secondary:"#FFF"},this.serviceName=P.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[ChatGPT]"),this.errorPrefix=P.red.bold("[ChatGPT]")}getServiceSpecificErrorMessage(e){const r=e.message||"";return r.includes("API key")?"Invalid API key. Check your OpenAI API key in configuration":r.includes("quota")?"API quota exceeded. Check your OpenAI usage limits":r.includes("500")?"OpenAI server error. Try again later":null}generateCommitMessage$(){return j(this.generateMessage("commit")).pipe(L(e=>M(e)),I(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:this.params.config.includeBody?e.value:e.title,description:this.params.config.includeBody?e.value:"",isError:!1})),R(this.handleError$))}generateCodeReview$(){return j(this.generateMessage("review")).pipe(L(e=>M(e)),I(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),R(this.handleError$))}extractJSONFromError(e){const r=/[{[]{1}([,:{}[\]0-9.\-+Eaeflnr-u \n\r\t]|".*?")+[}\]]{1}/gis,o=e.match(r);return o?Object.assign({},...o.map(s=>JSON.parse(s))):{error:{message:"Unknown error"}}}async generateMessage(e){const r=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n,temperature:i,logging:c,locale:a,generate:m,type:d,maxLength:l,proxy:p,maxTokens:u,timeout:h}=this.params.config,g={...J,locale:a,maxLength:l,type:d,generate:m,systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n},y=e==="review"?Z(g):Q(g),w=await Qa("ChatGPT",this.params.config.url,this.params.config.path,this.params.config.key,this.params.config.model,r,h,u,i,this.params.config.topP,y,c,e,p);return et(e==="review"?w.map(v=>this.sanitizeResponse(v)):w.map(v=>this.parseMessage(v,d,m)))}}class ic extends X{constructor(e){super(e),this.params=e,this.apiKey="",this.colors={primary:"#20808D",secondary:"#FFF"},this.serviceName=P.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[Perplexity]"),this.errorPrefix=P.red.bold("[Perplexity]"),this.apiKey=this.params.config.key}getServiceSpecificErrorMessage(e){const r=e.message||"";return r.includes("API key")||r.includes("api_key")?"Invalid API key. Check your Perplexity API key in configuration":r.includes("rate_limit")||r.includes("Rate limit")?"Rate limit exceeded. Wait a moment and try again, or upgrade your Perplexity plan":r.includes("model")||r.includes("Model")?"Model not found or not accessible. Check if the Perplexity model name is correct":r.includes("overloaded")||r.includes("capacity")?"Perplexity service is overloaded. Try again in a few minutes":r.includes("403")||r.includes("Forbidden")?"Access denied. Your API key may not have permission for this Perplexity model":r.includes("404")||r.includes("Not Found")?"Model or endpoint not found. Check your Perplexity model configuration":r.includes("500")||r.includes("Internal Server Error")?"Perplexity server error. Try again later":null}generateCommitMessage$(){return j(this.generateMessage("commit")).pipe(L(e=>M(e)),I(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:this.params.config.includeBody?e.value:e.title,description:this.params.config.includeBody?e.value:"",isError:!1})),R(this.handleError$))}generateCodeReview$(){return j(this.generateMessage("review")).pipe(L(e=>M(e)),I(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),R(this.handleError$))}extractJSONFromError(e){const r=/[{[]{1}([,:{}[\]0-9.\-+Eaeflnr-u \n\r\t]|".*?")+[}\]]{1}/gis,o=e.match(r);return o?Object.assign({},...o.map(s=>JSON.parse(s))):{error:{message:"Unknown error"}}}async generateMessage(e){const r=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n,logging:i,locale:c,generate:a,type:m,maxLength:d}=this.params.config,l={...J,locale:c,maxLength:d,type:m,generate:a,systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n},p=e==="review"?Z(l):Q(l),u=`Here is the diff: ${r}`,g=`${this.params.config.url||"https://api.perplexity.ai"}/chat/completions`,y={Authorization:`Bearer ${this.apiKey}`,"content-type":"application/json"};Y(r,e,"Perplexity",this.params.config.model,g,y,i),V(r,e,"Perplexity",p,u,i);const w=await this.createChatCompletions(p,u,e);return this.parseMessage(w,m,a)}async createChatCompletions(e,r,o){const s=this.params.stagedDiff.diff,{logging:n}=this.params.config,i={model:this.params.config.model,messages:[{role:"system",content:e},{role:"user",content:r}],temperature:this.params.config.temperature,top_p:this.params.config.topP,max_tokens:this.params.config.maxTokens,stream:!1};te(s,o,"Perplexity",i,n);const c=Date.now();try{const a=this.params.config.url||"https://api.perplexity.ai",m=await new Oe({method:"POST",baseURL:`${a}/chat/completions`,timeout:this.params.config.timeout}).setHeaders({Authorization:`Bearer ${this.apiKey}`,"content-type":"application/json"}).setBody(i).execute(),d=Date.now()-c,l=m.data;if(q(s,o,"Perplexity",l,n),!l.choices||l.choices.length===0||!l.choices[0].message?.content)throw _(s,o,"Perplexity",{message:"No Content on response",result:l},n),new Error("No Content on response. Please open a Bug report");const u=l.choices[0].message.content;return z(s,o,"Perplexity",d,u,n),u}catch(a){throw _(s,o,"Perplexity",a,n),a}}}class it{constructor(e,r){this.config=e,this.stagedDiff=r}createCommitMsgRequests$(e){return this.createServiceRequests$(e,"commit")}createCodeReviewRequests$(e){return this.createServiceRequests$(e,"review")}createServiceRequests$(e,r){return M(e).pipe(yr(o=>{const s=this.config[o],n=Array.isArray(s.model)?s.model:[s.model];return M(n).pipe(yr(i=>{if(s.compatible){const c=W.create(sc,{config:{...s,url:s.url||"",path:s.path||"",model:i},stagedDiff:this.stagedDiff,keyName:i});return r==="commit"?c.generateCommitMessage$():c.generateCodeReview$()}switch(o){case"OPENAI":{const a=W.create(nc,{config:{...this.config.OPENAI,model:i},stagedDiff:this.stagedDiff,keyName:i});return r==="commit"?a.generateCommitMessage$():a.generateCodeReview$()}case"GEMINI":{const a=W.create(Ca,{config:{...this.config.GEMINI,model:i},stagedDiff:this.stagedDiff,keyName:i});return r==="commit"?a.generateCommitMessage$():a.generateCodeReview$()}case"ANTHROPIC":{const a=W.create(ya,{config:{...this.config.ANTHROPIC,model:i},stagedDiff:this.stagedDiff,keyName:i});return r==="commit"?a.generateCommitMessage$():a.generateCodeReview$()}case"HUGGINGFACE":{const a=W.create(tc,{config:{...this.config.HUGGINGFACE,model:i},stagedDiff:this.stagedDiff,keyName:i});return r==="commit"?a.generateCommitMessage$():a.generateCodeReview$()}case"MISTRAL":{const a=W.create(rc,{config:{...this.config.MISTRAL,model:i},stagedDiff:this.stagedDiff,keyName:i});return r==="commit"?a.generateCommitMessage$():a.generateCodeReview$()}case"CODESTRAL":{const a=W.create(wa,{config:{...this.config.CODESTRAL,model:i},stagedDiff:this.stagedDiff,keyName:i});return r==="commit"?a.generateCommitMessage$():a.generateCodeReview$()}case"OLLAMA":{const a=W.create(oc,{config:{...this.config.OLLAMA,model:i},keyName:i,stagedDiff:this.stagedDiff});return r==="commit"?a.generateCommitMessage$():a.generateCodeReview$()}case"COHERE":{const a=W.create(va,{config:{...this.config.COHERE,model:i},stagedDiff:this.stagedDiff,keyName:i});return r==="commit"?a.generateCommitMessage$():a.generateCodeReview$()}case"GROQ":{const a=W.create(ec,{config:{...this.config.GROQ,model:i},stagedDiff:this.stagedDiff,keyName:i});return r==="commit"?a.generateCommitMessage$():a.generateCodeReview$()}case"PERPLEXITY":{const a=W.create(ic,{config:{...this.config.PERPLEXITY,model:i},stagedDiff:this.stagedDiff,keyName:i});return r==="commit"?a.generateCommitMessage$():a.generateCodeReview$()}case"GITHUB_MODELS":{const a=W.create(Za,{config:{...this.config.GITHUB_MODELS,model:i},stagedDiff:this.stagedDiff,keyName:i});return r==="commit"?a.generateCommitMessage$():a.generateCodeReview$()}case"DEEPSEEK":{const a=W.create(ba,{config:{...this.config.DEEPSEEK,model:i},stagedDiff:this.stagedDiff,keyName:i});return r==="commit"?a.generateCommitMessage$():a.generateCodeReview$()}default:const c=P.red.bold(`[${o}]`);return dt({name:c+" Invalid AI type",value:"Invalid AI type",isError:!0,disabled:!0})}}))}),R(o=>{const s=P.red.bold("[UNKNOWN]");return dt({name:s+` ${o.message||""}`,value:"Unknown error",isError:!0,disabled:!0})}))}}class Io{getDetectedMessage(e){return`Detected ${e.files.length.toLocaleString()} changed file${e.files.length>1?"s":""} (${e.diff.length.toLocaleString()} characters)`}getDetectedFiles(e){return`Detected ${e.length.toLocaleString()} changed file${e.length>1?"s":""}`}}class ac extends Io{constructor(){super(...arguments),this.name="git",this.excludeFromDiff=e=>`:(exclude)${e}`,this.filesToExclude=["package-lock.json","pnpm-lock.yaml","*.lock","*.lockb"].map(this.excludeFromDiff)}async assertRepo(){try{const{stdout:e}=await T("git",["rev-parse","--show-toplevel"],{reject:!0});return e.trim()}catch(e){const r=e;if(r.code==="ENOENT")throw new b(`Git command not found!
|
|
89
|
+
${r}`,d),te(r,o,"GitHub Models",c,d);const l=new AbortController,p=setTimeout(()=>l.abort(),this.params.config.timeout);try{const u=Date.now(),h=await fetch(a,{method:"POST",headers:m,body:JSON.stringify(c),signal:l.signal});if(clearTimeout(p),!h.ok){const v=await h.text(),E={status:h.status,statusText:h.statusText,url:a,headers:Object.fromEntries(h.headers),body:v};_(r,o,"GitHub Models",E,d);let A=`GitHub API request failed: ${h.status} ${h.statusText}`;try{const C=JSON.parse(v);C.error?.message?A+=` - ${C.error.message}`:C.message&&(A+=` - ${C.message}`)}catch{v&&(A+=` - ${v}`)}if(h.status===401){const C=new Error("GitHub authentication failed. Please run: aicommit2 github-login");throw C.status=h.status,C.code="AUTHENTICATION_FAILED",C.content=v,C}else if(h.status===403){const C=new Error('GitHub Models access denied. Make sure your token has "Models" permission.');throw C.status=h.status,C.code="ACCESS_DENIED",C.content=v,C}else if(h.status===404){const C=new Error(`Model "${s}" not found. Please check the model name.`);throw C.status=h.status,C.code="MODEL_NOT_FOUND",C.content=v,C}else if(h.status===429){const C=new Error("Rate limit exceeded. Please try again later.");throw C.status=h.status,C.code="RATE_LIMIT_EXCEEDED",C.content=v,C}const $=new Error(A);throw $.status=h.status,$.code="API_ERROR",$.content=v,$}const g=await h.json(),y=Date.now()-u;q(r,o,"GitHub Models",g,d);const w=g.choices?.[0]?.message?.content?.trim();if(!w){_(r,o,"GitHub Models",{message:"No content found in GitHub Models response",result:g},d);const E=new Error("No response content received from GitHub Models");throw E.code="NO_CONTENT",E.content=JSON.stringify(g,null,2),E}return z(r,o,"GitHub Models",y,w,d),w}catch(u){if(clearTimeout(p),u instanceof Error&&u.name==="AbortError"){const y={message:`GitHub Models request timeout after ${this.params.config.timeout}ms`,error:u};_(r,o,"GitHub Models",y,d);const w=new Error(`GitHub Models request timed out after ${this.params.config.timeout}ms`);throw w.code="REQUEST_TIMEOUT",w.originalError=u,w}if(u.code)throw u;_(r,o,"GitHub Models",{message:"GitHub Models request failed",error:u},d);const g=new Error(`GitHub Models request failed: ${u instanceof Error?u.message:String(u)}`);throw g.code="REQUEST_FAILED",g.originalError=u,g}}}class rc extends X{constructor(e){super(e),this.params=e,this.colors={primary:"#f55036",secondary:"#fff"},this.serviceName=P.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[Groq]"),this.errorPrefix=P.red.bold("[Groq]"),this.groq=new bs({apiKey:this.params.config.key})}getServiceSpecificErrorMessage(e){const r=e.message||"";return r.includes("API key")||r.includes("api_key")?"Invalid API key. Check your Groq API key in configuration":r.includes("rate_limit")||r.includes("Rate limit")?"Rate limit exceeded. Wait a moment and try again, or upgrade your Groq plan":r.includes("model")||r.includes("Model")?"Model not found or not accessible. Check if the Groq model name is correct":r.includes("overloaded")||r.includes("capacity")?"Groq service is overloaded. Try again in a few minutes":r.includes("403")||r.includes("Forbidden")?"Access denied. Your API key may not have permission for this Groq model":r.includes("404")||r.includes("Not Found")?"Model or endpoint not found. Check your Groq model configuration":r.includes("500")||r.includes("Internal Server Error")?"Groq server error. Try again later":null}generateCommitMessage$(){return D(this.generateMessage("commit")).pipe(L(e=>M(e)),I(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:this.params.config.includeBody?e.value:e.title,description:this.params.config.includeBody?e.value:"",isError:!1})),R(this.handleError$))}generateCodeReview$(){return D(this.generateMessage("review")).pipe(L(e=>M(e)),I(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),R(this.handleError$))}async generateMessage(e){const r=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n,logging:i,locale:c,temperature:a,generate:m,type:d,maxLength:l}=this.params.config,p=this.params.config.maxTokens,u={...K,locale:c,maxLength:l,type:d,generate:m,systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n},h=e==="review"?Z(u):Q(u),g=`Here is the diff: ${r}`,w=`${this.params.config.url||"https://api.groq.com"}/openai/v1/chat/completions`,v={Authorization:`Bearer ${this.params.config.key}`,"Content-Type":"application/json"};Y(r,e,"Groq",this.params.config.model,w,v,i),V(r,e,"Groq",h,g,i);const E={messages:[{role:"system",content:h},{role:"user",content:g}],model:this.params.config.model,max_tokens:p,top_p:this.params.config.topP,temperature:a};te(r,e,"Groq",E,i);const A=Date.now();try{const $=await this.groq.chat.completions.create(E,{timeout:this.params.config.timeout}),C=Date.now()-A,S=$.choices[0].message.content||"";return q(r,e,"Groq",$,i),z(r,e,"Groq",C,S,i),e==="review"?this.sanitizeResponse(S):this.parseMessage(S,d,m)}catch($){throw _(r,e,"Groq",$,i),$}}}class oc extends X{constructor(e){super(e),this.params=e,this.headers={},this.models=[],this.currentModelId=null,this.currentConversation=void 0,this.currentConversionID=void 0,this.cookie="",this.colors={primary:"#FED21F",secondary:"#000"},this.serviceName=P.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[HuggingFace]"),this.errorPrefix=P.red.bold("[HuggingFace]"),this.cookie=this.params.config.cookie;const r=this.params.config.url||"https://huggingface.co";this.headers={accept:"*/*","accept-language":"en-US,en;q=0.9","sec-ch-ua":'"Chromium";v="116", "Not)A;Brand";v="24", "Google Chrome";v="116"',"sec-ch-ua-mobile":"?0","sec-ch-ua-platform":'"Windows"',"sec-fetch-dest":"empty","sec-fetch-mode":"cors","sec-fetch-site":"same-origin",origin:r,"Referrer-Policy":"strict-origin-when-cross-origin"}}getServiceSpecificErrorMessage(e){const r=e.message||"";return r.includes("cookie")||r.includes("Cookie")?"Invalid cookie. Check your Hugging Face session cookie in configuration":r.includes("model")||r.includes("Model")?"Model not found or not accessible. Check if the Hugging Face model name is correct":r.includes("conversation")||r.includes("conversion")?"Failed to create conversation. Try again or check your session":r.includes("401")||r.includes("Unauthorized")?"Authentication failed. Your Hugging Face session may have expired":r.includes("403")||r.includes("Forbidden")?"Access denied. You may not have permission to access this model":r.includes("404")||r.includes("Not Found")?"Model not found. Check your Hugging Face model configuration":r.includes("500")||r.includes("Internal Server Error")?"Hugging Face server error. Try again later":r.includes("overloaded")||r.includes("capacity")?"Hugging Face service is overloaded. Try again in a few minutes":null}generateCommitMessage$(){return D(this.generateMessage("commit")).pipe(L(e=>M(e)),I(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:this.params.config.includeBody?e.value:e.title,description:this.params.config.includeBody?e.value:"",isError:!1})),R(this.handleError$))}generateCodeReview$(){return D(this.generateMessage("review")).pipe(L(e=>M(e)),I(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),R(this.handleError$))}async generateMessage(e){await this.initialize();const r=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n,logging:i,locale:c,generate:a,type:m,maxLength:d,temperature:l,maxTokens:p,topP:u,timeout:h}=this.params.config,g={...K,locale:c,maxLength:d,type:m,generate:a,systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n},y=e==="review"?Z(g):Q(g),w=`Here is the diff: ${r}`,E=`${this.params.config.url||"https://huggingface.co"}/chat/conversation`,A={...this.headers,cookie:this.cookie};Y(r,e,"HuggingFace",this.params.config.model,E,A,i),V(r,e,"HuggingFace",y,w,i);const $=Date.now();try{const C=await this.getNewChat(y),T=await(await this.sendMessage(w,C.id)).completeResponsePromise();await this.deleteConversation(C.id);const j=Date.now()-$;return q(r,e,"HuggingFace",{response:T},i),z(r,e,"HuggingFace",j,T,i),e==="review"?this.sanitizeResponse(T):this.parseMessage(T,m,a)}catch(C){throw _(r,e,"HuggingFace",C,i),C}}async initialize(){const e=await this.getRemoteLlms(),r=e.find(o=>o.name?.toLowerCase()===this.params.config.model.toLowerCase());if(r){this.currentModel=r,this.currentModelId=r.id;return}this.currentModel=e[0],this.currentModelId=e[0].id}async getRemoteLlms(){const e=this.params.config.url||"https://huggingface.co",r=await fetch(`${e}/chat/__data.json`,{headers:{...this.headers,cookie:this.cookie},body:null,method:"GET"});if(r.status!==200)throw new Error(`Failed to get remote LLMs with status code: ${r.status}`);const s=(await r.json()).nodes[0].data,n=s[s[0].models],i=[],c=a=>a===-1?null:s[a];for(const a of n){const m=s[a];if(s[m.unlisted])continue;const d={id:c(m.id),name:c(m.name),displayName:c(m.displayName),preprompt:c(m.preprompt),promptExamples:[],websiteUrl:c(m.websiteUrl),description:c(m.description),datasetName:c(m.datasetName),datasetUrl:c(m.datasetUrl),modelUrl:c(m.modelUrl),parameters:{}},l=c(m.promptExamples);if(l!==null){const h=l.map(g=>c(g));d.promptExamples=h.map(g=>({title:s[g.title],prompt:s[g.prompt]}))}const p=c(m.parameters),u={};for(const[h,g]of Object.entries(p)){if(g===-1){u[h]=null;continue}if(Array.isArray(s[g])){u[h]=s[g].map(y=>s[y]);continue}u[h]=s[g]}d.parameters=u,i.push(d)}return this.models=i,i}async getNewChat(e){const r={model:this.currentModelId,preprompt:e};let o=0;const s=this.params.config.url||"https://huggingface.co";for(;o<5;){const n=await fetch(`${s}/chat/conversation`,{headers:{...this.headers,"content-type":"application/json",cookie:this.cookie,Referer:`${s}/chat/`},body:JSON.stringify(r),method:"POST"}),{conversationId:i}=await n.json();if(i){this.currentConversionID=i;break}else o++}if(!this.currentConversionID)throw new Error("Failed to create new conversion");return await this.getConversationHistory(this.currentConversionID)}async getConversationHistory(e){if(!e)throw new Error("conversationId is required for getConversationHistory");const r=this.params.config.url||"https://huggingface.co",o=await fetch(`${r}/chat/conversation/${e}/__data.json`,{headers:{...this.headers,cookie:this.cookie,Referer:`${r}/chat/`},body:null,method:"GET"});if(o.status!=200)throw new Error("Unable get conversation details "+o);{const s=await o.json();return this.metadataParser(s,e)}}metadataParser(e,r){const o={id:"",model:"",systemPrompt:"",title:"",history:[]},s=e.nodes[1].data,n=s[s[0].model],i=s[s[0].preprompt],c=s[s[0].title],a=s[s[0].messages],m=[];for(const d of a){const l=s[d],p=new Date(s[l.createdAt][1]).getTime()/1e3,u=new Date(s[l.updatedAt][1]).getTime()/1e3;m.push({id:s[l.id],role:s[l.from],content:s[l.content],createdAt:p,updatedAt:u})}return o.id=r,o.model=n,o.systemPrompt=i,o.title=c,o.history=m,this.currentConversation=o,o}async sendMessage(e,r){if(e==="")throw new Error("the prompt can not be empty.");if(!r&&!this.currentConversionID?await this.getNewChat():r?(this.currentConversionID=r,await this.getConversationHistory(r)):this.currentConversionID&&await this.getConversationHistory(this.currentConversionID),!this.currentConversation)throw new Error("Failed to create new conversion");const o={inputs:e,id:this.currentConversation.history[this.currentConversation.history.length-1].id,is_retry:!1,is_continue:!1,web_search:!1,tools:[]},s=new FormData;s.append("data",JSON.stringify(o));const n=this.params.config.url||"https://huggingface.co",i=new AbortController,c=setTimeout(()=>i.abort(),this.params.config.timeout),a=await fetch(`${n}/chat/conversation/${this.currentConversionID}`,{headers:{...this.headers,cookie:this.cookie,Referer:`${n}/chat/conversation/${this.currentConversionID}`},body:s,method:"POST",signal:i.signal});clearTimeout(c);function m(g){try{const y=g.split(`
|
|
90
|
+
`),w=[];for(const v of y)v.trim()&&w.push(JSON.parse(v));return w}catch{return[{}]}}const d=new TextDecoder;let l="";const p=new TransformStream({async transform(g,y){const w=d.decode(g);try{const v=m(w);for(const E of v)E.type==="finalAnswer"?(l=E?.text||"",y.terminate()):E.type==="stream"&&y.enqueue(E?.token||"")}catch{throw new Error("Error during parsing response")}}}),u=a.body?.pipeThrough(p);async function h(){return new Promise(async(g,y)=>{try{if(!u)y("ModifiedStream undefined");else{const w=u.getReader();for(;;){const{done:v,value:E}=await w.read();if(v){g(l);break}}}}catch(w){y(w)}})}return{id:this.currentConversionID,stream:u,completeResponsePromise:h}}async deleteConversation(e){const r=this.params.config.url||"https://huggingface.co";return(await fetch(`${r}/chat/conversation/${e}`,{headers:{...this.headers,cookie:this.cookie,Referer:`${r}/chat/`},body:null,method:"DELETE"})).json()}}class sc extends X{constructor(e){super(e),this.params=e,this.apiKey="",this.colors={primary:"#ff7000",secondary:"#fff"},this.serviceName=P.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[MistralAI]"),this.errorPrefix=P.red.bold("[MistralAI]"),this.apiKey=this.params.config.key}getServiceSpecificErrorMessage(e){const r=e.message||"";return r.includes("API key")||r.includes("api_key")?"Invalid API key. Check your Mistral AI API key in configuration":r.includes("quota")||r.includes("usage")?"API quota exceeded. Check your Mistral AI usage limits":r.includes("model")||r.includes("Model")?"Model not found or not accessible. Check if the Mistral model name is correct":r.includes("403")||r.includes("Forbidden")?"Access denied. Your API key may not have permission for this Mistral model":r.includes("404")||r.includes("Not Found")?"Model or endpoint not found. Check your Mistral model configuration":r.includes("500")||r.includes("Internal Server Error")?"Mistral AI server error. Try again later":null}generateCommitMessage$(){return D(this.generateMessage("commit")).pipe(L(e=>M(e)),I(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:this.params.config.includeBody?e.value:e.title,description:this.params.config.includeBody?e.value:"",isError:!1})),R(this.handleError$))}generateCodeReview$(){return D(this.generateMessage("review")).pipe(L(e=>M(e)),I(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),R(this.handleError$))}async generateMessage(e){const r=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n,logging:i,locale:c,generate:a,type:m,maxLength:d}=this.params.config,l={...K,locale:c,maxLength:d,type:m,generate:a,systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n},p=e==="review"?Z(l):Q(l);await this.checkAvailableModels();const u=`Here is the diff: ${r}`,g=`${this.params.config.url||"https://api.mistral.ai"}/v1/chat/completions`,y={Authorization:`Bearer ${this.apiKey}`,"content-type":"application/json"};Y(r,e,"MistralAI",this.params.config.model,g,y,i),V(r,e,"MistralAI",p,u,i);const w=await this.createChatCompletions(p,u,e);return e==="review"?this.sanitizeResponse(w):this.parseMessage(w,m,a)}async checkAvailableModels(){if((await this.getAvailableModels()).includes(this.params.config.model))return!0;throw new Error(`Invalid model type of Mistral AI: ${this.params.config.model}`)}async getAvailableModels(){const e=this.params.config.url||"https://api.mistral.ai";return(await new Oe({method:"GET",baseURL:`${e}/v1/models`,timeout:this.params.config.timeout}).setHeaders({Authorization:`Bearer ${this.apiKey}`,"content-type":"application/json"}).execute()).data.data.filter(o=>o.object==="model").map(o=>o.id)}async createChatCompletions(e,r,o){const s=this.params.stagedDiff.diff,{logging:n}=this.params.config,i={model:this.params.config.model,messages:[{role:"system",content:e},{role:"user",content:r}],temperature:this.params.config.temperature,top_p:this.params.config.topP,max_tokens:this.params.config.maxTokens,stream:!1,safe_prompt:!1,random_seed:Ze(10,1e3)};te(s,o,"MistralAI",i,n);const c=Date.now();try{const a=this.params.config.url||"https://api.mistral.ai",m=await new Oe({method:"POST",baseURL:`${a}/v1/chat/completions`,timeout:this.params.config.timeout}).setHeaders({Authorization:`Bearer ${this.apiKey}`,"content-type":"application/json"}).setBody(i).execute(),d=Date.now()-c,l=m.data;if(q(s,o,"MistralAI",l,n),!l.choices||l.choices.length===0||!l.choices[0].message?.content)throw _(s,o,"MistralAI",{message:"No Content on response",result:l},n),new Error("No Content on response. Please open a Bug report");const u=l.choices[0].message.content;return z(s,o,"MistralAI",d,u,n),u}catch(a){throw _(s,o,"MistralAI",a,n),a}}}class nc extends X{constructor(e){super(e),this.params=e,this.host=Ft,this.model="",this.key="",this.auth="",this.setupFetch=(r,o={})=>Ps(r,{...o,dispatcher:new $s({headersTimeout:this.params.config.timeout})}),this.colors={primary:"#FFF",secondary:"#000"},this.model=this.params.keyName,this.serviceName=P.bgHex(this.colors.primary).hex(this.colors.secondary).bold(`[${Qe(this.model)}]`),this.errorPrefix=P.red.bold(`[${Qe(this.model)}]`),this.host=this.params.config.host||Ft,this.auth=this.params.config.auth||"Bearer",this.key=this.params.config.key||"",this.ollama=new Cs({host:this.host,fetch:this.setupFetch,...this.key&&{headers:{Authorization:`${this.auth} ${this.key}`}}})}getServiceSpecificErrorMessage(e){const r=e.message||"";return r.includes("ECONNREFUSED")||r.includes("connection")?`Cannot connect to Ollama server at ${this.host}. Make sure Ollama is running`:r.includes("model")||r.includes("Model")?`Model '${this.model}' not found. Pull the model with: ollama pull ${this.model}`:r.includes("401")||r.includes("Unauthorized")?"Authentication failed. Check your Ollama API key if authentication is enabled":r.includes("403")||r.includes("Forbidden")?"Access denied. Check your Ollama server permissions":r.includes("404")||r.includes("Not Found")?`Model '${this.model}' not found on Ollama server. Pull it first with: ollama pull ${this.model}`:r.includes("500")||r.includes("Internal Server Error")?"Ollama server error. Check server logs and try again":r.includes("overloaded")||r.includes("capacity")?"Ollama server is overloaded. Try again in a few minutes":null}generateCommitMessage$(){return D(this.generateMessage("commit")).pipe(L(e=>M(e)),I(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:this.params.config.includeBody?e.value:e.title,description:this.params.config.includeBody?e.value:"",isError:!1})),R(this.handleError$))}generateCodeReview$(){return D(this.generateMessage("review")).pipe(L(e=>M(e)),I(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),R(this.handleError$))}async generateMessage(e){const r=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n,logging:i,locale:c,generate:a,type:m,maxLength:d}=this.params.config,l={...K,locale:c,maxLength:d,type:m,generate:a,systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n},p=e==="review"?Z(l):Q(l);await this.checkIsAvailableOllama();const u=`Here is the diff: ${r}`,h=`Ollama_${this.model}`,g=`${this.host}/api/chat`,y=this.key?{Authorization:`${this.auth} ${this.key}`}:{};Y(r,e,h,this.model,g,y,i),V(r,e,h,p,u,i);const w=await this.createChatCompletions(p,u,e);return e==="review"?this.sanitizeResponse(w):this.parseMessage(w,m,a)}async checkIsAvailableOllama(){const e=new Oe({method:"GET",baseURL:`${this.host}`,timeout:this.params.config.timeout});return this.key&&e.setHeaders({Authorization:`${this.auth} ${this.key}`}),(await e.execute()).data}async createChatCompletions(e,r,o){const{stream:s,numCtx:n,temperature:i,topP:c,timeout:a,maxTokens:m,logging:d}=this.params.config,l=s||!1,p=this.params.stagedDiff.diff,u=`Ollama_${this.model}`,h={model:this.model,messages:[{role:"system",content:e},{role:"user",content:r}],stream:l,keep_alive:a,options:{num_ctx:n,temperature:i,top_p:c,seed:Ze(10,1e3),num_predict:m??-1}};te(p,o,u,h,d);const g=Date.now();try{const y=await this.ollama.chat(h),w=Date.now()-g;let v="";if(l){if(y)for await(const E of y)v+=E.message.content}else v=y.message.content;return q(p,o,u,{response:v,fullResponse:y},d),z(p,o,u,w,v,d),v}catch(y){throw _(p,o,u,y,d),y}}}class ic extends X{constructor(e){super(e),this.params=e;const r=this.params.keyName||"OPENAI_COMPATIBLE";this.colors=ea(r),this.serviceName=P.bgHex(this.colors.primary).hex(this.colors.secondary).bold(`[${Qe(r)}]`),this.errorPrefix=P.red.bold(`[${Qe(r)}]`),this.openAI=new Pr({apiKey:this.params.config.key,baseURL:`${this.params.config.url}${this.params.config.path}`})}getServiceSpecificErrorMessage(e){const r=e.message||"";return r.includes("API key")||r.includes("api_key")?"Invalid API key. Check your OpenAI-compatible API key in configuration":r.includes("rate_limit")||r.includes("Rate limit")?"Rate limit exceeded. Wait a moment and try again, or check your service limits":r.includes("model")||r.includes("Model")?"Model not found or not accessible. Check if the model name is correct":r.includes("network")||r.includes("connection")?"Network error. Check your internet connection and API endpoint":r.includes("quota")||r.includes("usage")?"API quota exceeded. Check your usage limits":r.includes("403")||r.includes("Forbidden")?"Access denied. Your API key may not have permission for this model":r.includes("404")||r.includes("Not Found")?"Model or endpoint not found. Check your API configuration":r.includes("500")||r.includes("Internal Server Error")?"Server error. Try again later":r.includes("overloaded")||r.includes("capacity")?"Service is overloaded. Try again in a few minutes":null}generateCommitMessage$(){return D(this.generateMessage("commit")).pipe(L(e=>M(e)),I(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:this.params.config.includeBody?e.value:e.title,description:this.params.config.includeBody?e.value:"",isError:!1})),R(this.handleError$))}generateCodeReview$(){return D(this.generateMessage("review")).pipe(L(e=>M(e)),I(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),R(this.handleError$))}async generateMessage(e){const r=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n,logging:i,locale:c,temperature:a,generate:m,type:d,maxLength:l,timeout:p,stream:u=!1}=this.params.config,h=this.params.config.maxTokens,g={...K,locale:c,maxLength:l,type:d,generate:m,systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n},y=e==="review"?Z(g):Q(g),w=`Here is the diff: ${r}`,v=this.params.keyName||"OpenAI-Compatible",E=`${this.params.config.url}${this.params.config.path}`,A={Authorization:`Bearer ${this.params.config.key}`,"Content-Type":"application/json"};Y(r,e,v,this.params.config.model,E,A,i),V(r,e,v,y,w,i);const $=Qt(this.params.config.model),C={messages:[{role:"system",content:y},{role:"user",content:w}],model:this.params.config.model,stream:u,...$?{max_completion_tokens:h,temperature:1}:{max_tokens:h,top_p:this.params.config.topP,temperature:a}};te(r,e,v,C,i);const S=Date.now();try{const T=await this.openAI.chat.completions.create(C,{timeout:p});let j="";if(u&&T){const zo=T;for await(const lr of zo){const Ko=lr.choices?.[0]?.delta?.content||"",Wo=lr.choices?.[0]?.delta?.reasoning_content||"",Jo=`${Ko}${Wo}`;j+=Jo}}else j=T.choices?.[0]?.message.content||"";const ie=Date.now()-S;return q(r,e,v,T,i),z(r,e,v,ie,j,i),e==="review"?this.sanitizeResponse(j):this.parseMessage(j,d,m)}catch(T){throw _(r,e,v,T,i),T}}}class ac extends X{constructor(e){super(e),this.params=e,this.colors={primary:"#74AA9C",secondary:"#FFF"},this.serviceName=P.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[ChatGPT]"),this.errorPrefix=P.red.bold("[ChatGPT]")}getServiceSpecificErrorMessage(e){const r=e.message||"";return r.includes("API key")?"Invalid API key. Check your OpenAI API key in configuration":r.includes("quota")?"API quota exceeded. Check your OpenAI usage limits":r.includes("500")?"OpenAI server error. Try again later":null}generateCommitMessage$(){return D(this.generateMessage("commit")).pipe(L(e=>M(e)),I(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:this.params.config.includeBody?e.value:e.title,description:this.params.config.includeBody?e.value:"",isError:!1})),R(this.handleError$))}generateCodeReview$(){return D(this.generateMessage("review")).pipe(L(e=>M(e)),I(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),R(this.handleError$))}extractJSONFromError(e){const r=/[{[]{1}([,:{}[\]0-9.\-+Eaeflnr-u \n\r\t]|".*?")+[}\]]{1}/gis,o=e.match(r);return o?Object.assign({},...o.map(s=>JSON.parse(s))):{error:{message:"Unknown error"}}}async generateMessage(e){const r=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n,temperature:i,logging:c,locale:a,generate:m,type:d,maxLength:l,proxy:p,maxTokens:u,timeout:h}=this.params.config,g={...K,locale:a,maxLength:l,type:d,generate:m,systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n},y=e==="review"?Z(g):Q(g),w=await ec("ChatGPT",this.params.config.url,this.params.config.path,this.params.config.key,this.params.config.model,r,h,u,i,this.params.config.topP,y,c,e,p);return et(e==="review"?w.map(v=>this.sanitizeResponse(v)):w.map(v=>this.parseMessage(v,d,m)))}}class cc extends X{constructor(e){super(e),this.params=e,this.apiKey="",this.colors={primary:"#20808D",secondary:"#FFF"},this.serviceName=P.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[Perplexity]"),this.errorPrefix=P.red.bold("[Perplexity]"),this.apiKey=this.params.config.key}getServiceSpecificErrorMessage(e){const r=e.message||"";return r.includes("API key")||r.includes("api_key")?"Invalid API key. Check your Perplexity API key in configuration":r.includes("rate_limit")||r.includes("Rate limit")?"Rate limit exceeded. Wait a moment and try again, or upgrade your Perplexity plan":r.includes("model")||r.includes("Model")?"Model not found or not accessible. Check if the Perplexity model name is correct":r.includes("overloaded")||r.includes("capacity")?"Perplexity service is overloaded. Try again in a few minutes":r.includes("403")||r.includes("Forbidden")?"Access denied. Your API key may not have permission for this Perplexity model":r.includes("404")||r.includes("Not Found")?"Model or endpoint not found. Check your Perplexity model configuration":r.includes("500")||r.includes("Internal Server Error")?"Perplexity server error. Try again later":null}generateCommitMessage$(){return D(this.generateMessage("commit")).pipe(L(e=>M(e)),I(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:this.params.config.includeBody?e.value:e.title,description:this.params.config.includeBody?e.value:"",isError:!1})),R(this.handleError$))}generateCodeReview$(){return D(this.generateMessage("review")).pipe(L(e=>M(e)),I(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),R(this.handleError$))}extractJSONFromError(e){const r=/[{[]{1}([,:{}[\]0-9.\-+Eaeflnr-u \n\r\t]|".*?")+[}\]]{1}/gis,o=e.match(r);return o?Object.assign({},...o.map(s=>JSON.parse(s))):{error:{message:"Unknown error"}}}async generateMessage(e){const r=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n,logging:i,locale:c,generate:a,type:m,maxLength:d}=this.params.config,l={...K,locale:c,maxLength:d,type:m,generate:a,systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n},p=e==="review"?Z(l):Q(l),u=`Here is the diff: ${r}`,g=`${this.params.config.url||"https://api.perplexity.ai"}/chat/completions`,y={Authorization:`Bearer ${this.apiKey}`,"content-type":"application/json"};Y(r,e,"Perplexity",this.params.config.model,g,y,i),V(r,e,"Perplexity",p,u,i);const w=await this.createChatCompletions(p,u,e);return this.parseMessage(w,m,a)}async createChatCompletions(e,r,o){const s=this.params.stagedDiff.diff,{logging:n}=this.params.config,i={model:this.params.config.model,messages:[{role:"system",content:e},{role:"user",content:r}],temperature:this.params.config.temperature,top_p:this.params.config.topP,max_tokens:this.params.config.maxTokens,stream:!1};te(s,o,"Perplexity",i,n);const c=Date.now();try{const a=this.params.config.url||"https://api.perplexity.ai",m=await new Oe({method:"POST",baseURL:`${a}/chat/completions`,timeout:this.params.config.timeout}).setHeaders({Authorization:`Bearer ${this.apiKey}`,"content-type":"application/json"}).setBody(i).execute(),d=Date.now()-c,l=m.data;if(q(s,o,"Perplexity",l,n),!l.choices||l.choices.length===0||!l.choices[0].message?.content)throw _(s,o,"Perplexity",{message:"No Content on response",result:l},n),new Error("No Content on response. Please open a Bug report");const u=l.choices[0].message.content;return z(s,o,"Perplexity",d,u,n),u}catch(a){throw _(s,o,"Perplexity",a,n),a}}}class it{constructor(e,r){this.config=e,this.stagedDiff=r}createCommitMsgRequests$(e){return this.createServiceRequests$(e,"commit")}createCodeReviewRequests$(e){return this.createServiceRequests$(e,"review")}createServiceRequests$(e,r){return M(e).pipe(gr(o=>{const s=this.config[o],n=Array.isArray(s.model)?s.model:[s.model];return M(n).pipe(gr(i=>{if(s.compatible){const c=J.create(ic,{config:{...s,url:s.url||"",path:s.path||"",model:i},stagedDiff:this.stagedDiff,keyName:i});return r==="commit"?c.generateCommitMessage$():c.generateCodeReview$()}switch(o){case"OPENAI":{const a=J.create(ac,{config:{...this.config.OPENAI,model:i},stagedDiff:this.stagedDiff,keyName:i});return r==="commit"?a.generateCommitMessage$():a.generateCodeReview$()}case"GEMINI":{const a=J.create($a,{config:{...this.config.GEMINI,model:i},stagedDiff:this.stagedDiff,keyName:i});return r==="commit"?a.generateCommitMessage$():a.generateCodeReview$()}case"ANTHROPIC":{const a=J.create(va,{config:{...this.config.ANTHROPIC,model:i},stagedDiff:this.stagedDiff,keyName:i});return r==="commit"?a.generateCommitMessage$():a.generateCodeReview$()}case"HUGGINGFACE":{const a=J.create(oc,{config:{...this.config.HUGGINGFACE,model:i},stagedDiff:this.stagedDiff,keyName:i});return r==="commit"?a.generateCommitMessage$():a.generateCodeReview$()}case"MISTRAL":{const a=J.create(sc,{config:{...this.config.MISTRAL,model:i},stagedDiff:this.stagedDiff,keyName:i});return r==="commit"?a.generateCommitMessage$():a.generateCodeReview$()}case"CODESTRAL":{const a=J.create(ba,{config:{...this.config.CODESTRAL,model:i},stagedDiff:this.stagedDiff,keyName:i});return r==="commit"?a.generateCommitMessage$():a.generateCodeReview$()}case"OLLAMA":{const a=J.create(nc,{config:{...this.config.OLLAMA,model:i},keyName:i,stagedDiff:this.stagedDiff});return r==="commit"?a.generateCommitMessage$():a.generateCodeReview$()}case"COHERE":{const a=J.create(Ca,{config:{...this.config.COHERE,model:i},stagedDiff:this.stagedDiff,keyName:i});return r==="commit"?a.generateCommitMessage$():a.generateCodeReview$()}case"GROQ":{const a=J.create(rc,{config:{...this.config.GROQ,model:i},stagedDiff:this.stagedDiff,keyName:i});return r==="commit"?a.generateCommitMessage$():a.generateCodeReview$()}case"PERPLEXITY":{const a=J.create(cc,{config:{...this.config.PERPLEXITY,model:i},stagedDiff:this.stagedDiff,keyName:i});return r==="commit"?a.generateCommitMessage$():a.generateCodeReview$()}case"GITHUB_MODELS":{const a=J.create(tc,{config:{...this.config.GITHUB_MODELS,model:i},stagedDiff:this.stagedDiff,keyName:i});return r==="commit"?a.generateCommitMessage$():a.generateCodeReview$()}case"DEEPSEEK":{const a=J.create(Pa,{config:{...this.config.DEEPSEEK,model:i},stagedDiff:this.stagedDiff,keyName:i});return r==="commit"?a.generateCommitMessage$():a.generateCodeReview$()}default:const c=P.red.bold(`[${o}]`);return dt({name:c+" Invalid AI type",value:"Invalid AI type",isError:!0,disabled:!0})}}))}),R(o=>{const s=P.red.bold("[UNKNOWN]");return dt({name:s+` ${o.message||""}`,value:"Unknown error",isError:!0,disabled:!0})}))}}class Io{getDetectedMessage(e){return`Detected ${e.files.length.toLocaleString()} changed file${e.files.length>1?"s":""} (${e.diff.length.toLocaleString()} characters)`}getDetectedFiles(e){return`Detected ${e.length.toLocaleString()} changed file${e.length>1?"s":""}`}}class Zt extends Io{constructor(){super(...arguments),this.name="git",this.excludeFromDiff=e=>`:(exclude)${e}`,this.filesToExclude=["package-lock.json","pnpm-lock.yaml","*.lock","*.lockb"].map(this.excludeFromDiff)}async assertRepo(){try{const{stdout:e}=await N("git",["rev-parse","--show-toplevel"],{reject:!0});return e.trim()}catch(e){const r=e;if(r.code==="ENOENT")throw new b(`Git command not found!
|
|
95
91
|
|
|
96
92
|
Please install Git first: https://git-scm.com/downloads`);if(r.stderr){if(r.stderr.includes("not a git repository"))throw new b(`Not in a Git repository!
|
|
97
93
|
|
|
98
94
|
Initialize with: git init
|
|
99
95
|
Or navigate to an existing Git repository.`);if(r.stderr.includes("permission denied"))throw new b(`Git permission denied: ${r.stderr.trim()}
|
|
100
96
|
|
|
101
|
-
Check file permissions and repository access.`)}throw new b(`Failed to verify Git repository: ${r.message||"Unknown error"}`)}}async getStagedDiff(e,r){const o=["diff","--cached","--diff-algorithm=minimal"],{stdout:s}=await
|
|
102
|
-
`).filter(Boolean),{stdout:c}=await
|
|
97
|
+
Check file permissions and repository access.`)}throw new b(`Failed to verify Git repository: ${r.message||"Unknown error"}`)}}async getStagedDiff(e,r){const o=["diff","--cached","--diff-algorithm=minimal"],{stdout:s}=await N("git",[...o,"--name-only",...this.filesToExclude,...e?e.map(this.excludeFromDiff):[],...r?r.map(this.excludeFromDiff):[]]);if(!s)return null;const{stdout:n}=await N("git",[...o,...this.filesToExclude,...e?e.map(this.excludeFromDiff):[],...r?r.map(this.excludeFromDiff):[]]),i=s.split(`
|
|
98
|
+
`).filter(Boolean),{stdout:c}=await N("git",[...o,"--numstat",...e?e.map(this.excludeFromDiff):[],...r?r.map(this.excludeFromDiff):[]]),a=[],m=c.split(`
|
|
103
99
|
`).filter(Boolean);for(const p of m){const u=p.split(" ");u[0]==="-"&&u[1]==="-"&&u[2]&&a.push(u[2])}let d=n;if(a.length>0){n.trim()||(d=""),d+=`
|
|
104
100
|
|
|
105
101
|
--- Binary Files Changed ---
|
|
106
|
-
`;for(const p of a){const{stdout:u}=await
|
|
107
|
-
`}}const l=[...new Set([...i,...a])];return{files:l,diff:d||`Files changed: ${l.join(", ")}`}}async getCommitDiff(e,r,o){const s=["diff-tree","-r","--no-commit-id","--name-only",e],{stdout:n}=await
|
|
102
|
+
`;for(const p of a){const{stdout:u}=await N("git",["status","--porcelain",p]),h=u.substring(0,2).trim();d+=`Binary file ${p} ${h==="A"?"added":h==="M"?"modified":h==="D"?"deleted":"changed"}
|
|
103
|
+
`}}const l=[...new Set([...i,...a])];return{files:l,diff:d||`Files changed: ${l.join(", ")}`}}async getCommitDiff(e,r,o){const s=["diff-tree","-r","--no-commit-id","--name-only",e],{stdout:n}=await N("git",[...s,...this.filesToExclude,...r?r.map(this.excludeFromDiff):[],...o?o.map(this.excludeFromDiff):[]]);if(!n)return null;const{stdout:i}=await N("git",["show",e,"--",...this.filesToExclude,...r?r.map(this.excludeFromDiff):[],...o?o.map(this.excludeFromDiff):[]]),{stdout:c}=await N("git",["diff-tree","-r","--numstat",e,...r?r.map(this.excludeFromDiff):[],...o?o.map(this.excludeFromDiff):[]]),a=[],m=c.split(`
|
|
108
104
|
`).filter(Boolean);for(const p of m){const u=p.split(" ");u[0]==="-"&&u[1]==="-"&&u[2]&&a.push(u[2])}let d=i;if(a.length>0){i.trim()||(d=""),d+=`
|
|
109
105
|
|
|
110
106
|
--- Binary Files Changed ---
|
|
111
107
|
`;for(const p of a)d+=`Binary file ${p} changed
|
|
112
108
|
`}const l=[...new Set([...n.split(`
|
|
113
|
-
`).filter(Boolean),...a])];return{files:l,diff:d||`Files changed: ${l.join(", ")}`}}async commit(e,r=[]){try{await
|
|
109
|
+
`).filter(Boolean),...a])];return{files:l,diff:d||`Files changed: ${l.join(", ")}`}}async commit(e,r=[]){try{await N("git",["commit","-m",e,...r],{stdio:"inherit"})}catch(o){const s=o;throw s.stderr?s.stderr.includes("nothing to commit")?new b(`Nothing to commit.
|
|
114
110
|
|
|
115
111
|
Stage your changes with: git add <files>
|
|
116
112
|
Or use the --all flag to stage all changes.`):s.stderr.includes("Please enter the commit message")?new b(`Commit message cannot be empty.
|
|
@@ -121,20 +117,20 @@ Configure with:
|
|
|
121
117
|
git config --global user.name "Your Name"
|
|
122
118
|
git config --global user.email "your.email@example.com"`):s.stderr.includes("Permission denied")?new b(`Git permission error: ${s.stderr.trim()}
|
|
123
119
|
|
|
124
|
-
Check repository permissions and file access.`):new b(`Git commit failed: ${s.stderr.trim()}`):s.exitCode===1?new b("Git commit failed. Check your staged changes and try again."):new b(`Failed to commit with Git: ${s.message||"Unknown error"}`)}}async getCommentChar(){try{const{stdout:e}=await
|
|
120
|
+
Check repository permissions and file access.`):new b(`Git commit failed: ${s.stderr.trim()}`):s.exitCode===1?new b("Git commit failed. Check your staged changes and try again."):new b(`Failed to commit with Git: ${s.message||"Unknown error"}`)}}async getCommentChar(){try{const{stdout:e}=await N("git",["config","--get","core.commentChar"]);return e}catch{return"#"}}}class lc extends Io{constructor(){super(...arguments),this.name="jujutsu",this.excludeFromDiff=e=>e.includes("*")||e.includes("?")||e.includes("[")?`~glob:"${e}"`:`~"${e}"`,this.filesToExclude=["package-lock.json","pnpm-lock.yaml","*.lock","*.lockb"]}async assertRepo(){try{const{stdout:e}=await N("jj",["--version"],{reject:!0});process.env.DEBUG&&console.log(`Jujutsu version: ${e}`)}catch(e){const r=e;throw r.code==="ENOENT"?new b(`Jujutsu (jj) command not found!
|
|
125
121
|
|
|
126
122
|
Please install Jujutsu:
|
|
127
123
|
- macOS: brew install jj
|
|
128
124
|
- Linux: cargo install jj-cli
|
|
129
125
|
- Windows: cargo install jj-cli
|
|
130
|
-
- See: https://github.com/martinvonz/jj#installation`):new b(`Failed to execute jj command: ${r.message}`)}try{const{stdout:e,stderr:r}=await
|
|
126
|
+
- See: https://github.com/martinvonz/jj#installation`):new b(`Failed to execute jj command: ${r.message}`)}try{const{stdout:e,stderr:r}=await N("jj",["workspace","root"],{reject:!0}),o=e.trim();if(!o)throw new b("jj workspace root returned empty path");const s=x.join(o,".jj");if(!U.existsSync(s))throw new b(`Jujutsu repository directory not found at ${s}
|
|
131
127
|
|
|
132
128
|
Initialize a jj repository with: jj init`);return o}catch(e){if(e instanceof b)throw e;const r=e;throw r.stderr?r.stderr.includes("not in a jj repo")?new b(`Not in a Jujutsu repository!
|
|
133
129
|
|
|
134
130
|
Initialize with: jj init
|
|
135
131
|
Or navigate to an existing jj repository.`):r.stderr.includes("No workspace found")?new b(`No Jujutsu workspace found!
|
|
136
132
|
|
|
137
|
-
This may be a bare repository. Navigate to a workspace directory.`):new b(`Jujutsu error: ${r.stderr.trim()}`):new b(`Failed to verify Jujutsu repository: ${r.message||"Unknown error"}`)}}async getStagedDiff(e,r){try{const{stdout:o}=await
|
|
133
|
+
This may be a bare repository. Navigate to a workspace directory.`):new b(`Jujutsu error: ${r.stderr.trim()}`):new b(`Failed to verify Jujutsu repository: ${r.message||"Unknown error"}`)}}async getStagedDiff(e,r){try{const{stdout:o}=await N("jj",["status","--no-pager"]);if(process.env.DEBUG&&(console.log("jj status output:",JSON.stringify(o)),console.log("excludeFiles:",e),console.log("exclude:",r)),o.includes("No changes.")||o.includes("The working copy is clean"))return null;const s=this.filesToExclude.map(this.excludeFromDiff),n=[...e?e.map(this.excludeFromDiff):[],...r?r.map(this.excludeFromDiff):[]],i=[...s,...n];let c="all()";i.length>0&&(c=`all() & ${i.join(" & ")}`);const a=["diff","--name-only"],m=["diff","--git"];i.length>0&&(a.push(c),m.push(c)),process.env.DEBUG&&(console.log("jj diff command with fileset:",a),console.log("fileset expression:",c));const{stdout:d}=await N("jj",a);if(process.env.DEBUG&&console.log("jj diff --name-only output:",JSON.stringify(d)),!d.trim())return null;const{stdout:l}=await N("jj",m),{stdout:p}=await N("jj",["status","--no-pager"]),u=d.split(`
|
|
138
134
|
`).filter(Boolean),h=[],g=p.split(`
|
|
139
135
|
`);for(const v of g)if(v.includes("(binary)")||v.includes("Binary file")){const E=v.match(/([^\s]+)\s*\(binary\)/);E&&E[1]&&h.push(E[1])}let y=l;if(h.length>0){y+=`
|
|
140
136
|
|
|
@@ -146,8 +142,8 @@ Try: jj status --no-pager`);if(s.stderr.includes("Invalid revision"))throw new b
|
|
|
146
142
|
|
|
147
143
|
Check if you're in a valid workspace.`)}if(s.exitCode===1&&!s.stderr)return null;if(process.env.DEBUG)throw new b(`Jujutsu diff failed: ${s.message}
|
|
148
144
|
stderr: ${s.stderr}
|
|
149
|
-
exitCode: ${s.exitCode}`);return null}}async getCommitDiff(e,r,o){const s=[...r?r.map(this.excludeFromDiff):[],...o?o.map(this.excludeFromDiff):[]];try{const n=["diff","--name-only","--revision",e],i=["diff","--git","--revision",e];if(s.length>0){const d=`all() & ${s.join(" & ")}`;n.push(d),i.push(d),process.env.DEBUG&&console.log("jj getCommitDiff fileset expression:",d)}const{stdout:c}=await
|
|
150
|
-
`).filter(Boolean);return{files:m,diff:a||`Files changed: ${m.join(", ")}`}}catch(n){if(process.env.DEBUG){const i=n;console.log("jj getCommitDiff error:",i.message,i.stderr)}return null}}async commit(e,r=[]){try{await
|
|
145
|
+
exitCode: ${s.exitCode}`);return null}}async getCommitDiff(e,r,o){const s=[...r?r.map(this.excludeFromDiff):[],...o?o.map(this.excludeFromDiff):[]];try{const n=["diff","--name-only","--revision",e],i=["diff","--git","--revision",e];if(s.length>0){const d=`all() & ${s.join(" & ")}`;n.push(d),i.push(d),process.env.DEBUG&&console.log("jj getCommitDiff fileset expression:",d)}const{stdout:c}=await N("jj",n);if(!c.trim())return null;const{stdout:a}=await N("jj",i),m=c.split(`
|
|
146
|
+
`).filter(Boolean);return{files:m,diff:a||`Files changed: ${m.join(", ")}`}}catch(n){if(process.env.DEBUG){const i=n;console.log("jj getCommitDiff error:",i.message,i.stderr)}return null}}async commit(e,r=[]){try{await N("jj",["describe","-m",e,...r],{stdio:"inherit"}),await N("jj",["new"],{stdio:"inherit"})}catch(o){const s=o;throw s.stderr?s.stderr.includes("Empty commit message")?new b(`Commit message cannot be empty.
|
|
151
147
|
|
|
152
148
|
Provide a meaningful commit message.`):s.stderr.includes("No changes to commit")?new b(`No changes to commit.
|
|
153
149
|
|
|
@@ -155,22 +151,22 @@ Make some changes first, then try again.`):s.stderr.includes("Invalid revision")
|
|
|
155
151
|
|
|
156
152
|
Ensure you're in a valid workspace with changes.`):s.stderr.includes("Operation not allowed")?new b(`Jujutsu operation not allowed: ${s.stderr.trim()}
|
|
157
153
|
|
|
158
|
-
Check repository state with: jj status`):new b(`Jujutsu describe failed: ${s.stderr.trim()}`):s.exitCode===1?new b("Jujutsu commit failed. Check your changes and repository state."):new b(`Failed to commit with Jujutsu: ${s.message||"Unknown error"}`)}}async getCommentChar(){try{const{stdout:e}=await
|
|
159
|
-
${s instanceof Error?s.message:String(s)}`)}let e=!1;try{e=(await le({})).
|
|
160
|
-
${s instanceof Error?s.message:String(s)}`)}let r=null,o=null;try{const s=new
|
|
154
|
+
Check repository state with: jj status`):new b(`Jujutsu describe failed: ${s.stderr.trim()}`):s.exitCode===1?new b("Jujutsu commit failed. Check your changes and repository state."):new b(`Failed to commit with Jujutsu: ${s.message||"Unknown error"}`)}}async getCommentChar(){try{const{stdout:e}=await N("jj",["config","get","ui.comment-char"]);return e.trim()||"#"}catch{return"#"}}}let er=null;async function uc(){if(process.env.FORCE_GIT==="true")try{const s=new Zt;return await s.assertRepo(),s}catch(s){throw new b(`FORCE_GIT="true" environment variable is set, but Git is not available or not in a git repository.
|
|
155
|
+
${s instanceof Error?s.message:String(s)}`)}let e=!1;try{e=(await le({})).forceGit===!0}catch{e=!1}if(e)try{const s=new Zt;return await s.assertRepo(),s}catch(s){throw new b(`forceGit=true is set in config, but Git is not available or not in a git repository.
|
|
156
|
+
${s instanceof Error?s.message:String(s)}`)}let r=null,o=null;try{const s=new lc;return await s.assertRepo(),s}catch(s){r=s instanceof Error?s:new Error(String(s))}try{const s=new Zt;return await s.assertRepo(),s}catch(s){o=s instanceof Error?s:new Error(String(s))}if(r&&o){const s=r.message.replace("KnownError: ","").trim(),n=o.message.replace("KnownError: ","").trim();throw new b(`No supported VCS repository found.
|
|
161
157
|
|
|
162
|
-
|
|
158
|
+
Jujutsu Error:
|
|
163
159
|
${s}
|
|
164
160
|
|
|
165
|
-
|
|
161
|
+
Git Error:
|
|
166
162
|
${n}
|
|
167
163
|
|
|
168
164
|
Solutions:
|
|
169
|
-
\u2022 Initialize a Git repository: git init
|
|
170
165
|
\u2022 Initialize a Jujutsu repository: jj init
|
|
171
|
-
\u2022
|
|
172
|
-
\u2022
|
|
173
|
-
\u2022 Set
|
|
166
|
+
\u2022 Initialize a Git repository: git init
|
|
167
|
+
\u2022 Navigate to an existing Jujutsu or Git repository
|
|
168
|
+
\u2022 Set FORCE_GIT="true" environment variable to force Git detection in a jj repository
|
|
169
|
+
\u2022 Set forceGit=true in config file to prefer Git detection`)}throw new b("Unexpected error during VCS detection")}async function $e(){return er||(er=await uc()),er}const tr=async()=>(await $e()).assertRepo(),rr=async(t,e)=>(await $e()).getStagedDiff(t,e),dc=async(t,e,r)=>{const o=await $e();if(!o.getCommitDiff)throw new b(`Commit diff not supported for ${o.name}`);return o.getCommitDiff(t,e,r)},mc=async()=>(await $e()).getCommentChar(),fc=t=>`Detected ${t.files.length.toLocaleString()} changed file${t.files.length>1?"s":""} (${t.diff.length.toLocaleString()} characters)`,pc=async()=>(await $e()).name,hc=async(t,e)=>{await(await $e()).commit(t,e||[])};class re{constructor(){this.title="aicommit2"}printTitle(){console.log(Es.textSync(this.title,{font:"Small"}))}showLoader(e){if(this.loader){this.loader.text=e;return}this.loader=Er(e).start()}stopLoader(){this.loader?.stop(),this.loader=void 0}displaySpinner(e){return Er(e).start()}stopSpinner(e){e.stop(),e.clear()}printStagedFiles(e){console.log(P.bold.green("\u2714 ")+P.bold(`${fc(e)}:`)),console.log(`${e.files.map(r=>` ${r}`).join(`
|
|
174
170
|
`)}
|
|
175
171
|
`)}printAnalyzed(){console.log(`
|
|
176
172
|
${P.bold.green("\u2714")} ${P.bold("Changes analyzed")}`)}printCommitted(){console.log(`
|
|
@@ -182,16 +178,17 @@ ${P.bold.red("\u2716")} ${P.red(`${e}`)}`)}printWarning(e){console.log(`
|
|
|
182
178
|
${P.bold.yellow("\u26A0")} ${P.red(`${e}`)}`)}printSuccess(e){console.log(`
|
|
183
179
|
${P.bold.green("\u2714")} ${P.green(`${e}`)}`)}printInfo(e){console.log(`
|
|
184
180
|
${P.bold.blue("\u2139")} ${P.blue(`${e}`)}`)}printSetupGitEvent(e){console.log(`
|
|
185
|
-
${P.bold.green("\u2714")} ${P.bold(`Git ${e} hook has been set up`)}`)}moveCursorUp(){const e=Ue.createInterface({input:process.stdin,output:process.stdout});Ue.moveCursor(process.stdout,0,-1),e.close()}moveCursorDown(){const e=Ue.createInterface({input:process.stdin,output:process.stdout});Ue.moveCursor(process.stdout,0,2),e.close()}print(e){console.log(e)}}const
|
|
186
|
-
${
|
|
187
|
-
|
|
181
|
+
${P.bold.green("\u2714")} ${P.bold(`Git ${e} hook has been set up`)}`)}moveCursorUp(){const e=Ue.createInterface({input:process.stdin,output:process.stdout});Ue.moveCursor(process.stdout,0,-1),e.close()}moveCursorDown(){const e=Ue.createInterface({input:process.stdin,output:process.stdout});Ue.moveCursor(process.stdout,0,2),e.close()}print(e){console.log(e)}}const gc={isLoading:!1,startOption:{text:"AI is analyzing your changes"}},Ro={isLoading:!1,startOption:{text:"AI is performing a code review"}},or="No commit messages were generated",Oo="No code reviews were generated",sr={type:"reactiveListPrompt",name:"aicommit2Prompt",message:"Pick a commit message to use: ",emptyMessage:`\u26A0 ${or}`,loop:!1,descPageSize:15,showDescription:!0,pickKey:"short",isDescriptionDim:!0,stopMessage:"Changes analyzed"};class nr{constructor(e){this.choices$=new yr([]),this.destroyed$=new cs(1),this.stopMessage="Changes analyzed",this.isDestroyed=!1,this.subscriptions=new mt,this.inquirerInstance=null,this.loader$=new yr(e)}addSubscription(e){if(this.isDestroyed){e.unsubscribe();return}this.subscriptions.add(e)}initPrompt(e=sr){return this.stopMessage=e.stopMessage,Ge.registerPrompt("reactiveListPrompt",xs),this.inquirerInstance=Ge.prompt({choices$:this.choices$,loader$:this.loader$,...e}),this.inquirerInstance}startLoader(){this.loader$.next({isLoading:!0})}clearLoader(){this.inquirerInstance&&this.loader$.next({isLoading:!1,clear:!0})}refreshChoices(e){this.isDestroyed||!e||!e.value||this.choices$.next([...this.currentChoices,e].sort(qi))}checkErrorOnChoices(e=!0){if(this.choices$.getValue().map(o=>o).every(o=>o?.isError||o?.disabled)){this.alertNoGeneratedMessage(),this.logEmptyCommitMessage(),e&&process.exit(1);return}this.stopLoaderOnSuccess()}completeSubject(){try{this.destroyed$.next(!0),this.destroyed$.complete(),this.choices$.closed||this.choices$.complete(),this.loader$.closed||this.loader$.complete()}catch(e){console.warn("Error completing subjects:",e)}}closeInquirerInstance(){this.inquirerInstance&&this.inquirerInstance.ui.close()}cancel(){this.inquirerInstance?.ui?.activePrompt&&this.inquirerInstance.ui.activePrompt.abortPrompt()}destroy(){if(!this.isDestroyed){this.isDestroyed=!0;try{this.cancel(),this.closeInquirerInstance(),this.subscriptions.unsubscribe(),this.completeSubject()}catch(e){console.warn("Error during ReactivePromptManager destruction:",e)}finally{this.inquirerInstance=null}}}alertNoGeneratedMessage(){this.loader$.next({isLoading:!1,message:or,stopOption:{doneFrame:"\u26A0",color:"yellow"}})}stopLoaderOnSuccess(){this.loader$.next({isLoading:!1,message:this.stopMessage})}logEmptyCommitMessage(){console.log(`
|
|
182
|
+
${P.bold.yellow("\u26A0")} ${P.yellow(`${or}`)}`)}get currentChoices(){return this.choices$.getValue().map(e=>e)}}const W=new re;var yc=async(t,e,r,o,s,n,i,c,a,m,d,l,p)=>(async()=>{W.printTitle(),await tr(),o&&await pc()==="git"&&await N("git",["add","--update"]);const u=await le({locale:t?.toString(),generate:e?.toString(),type:s?.toString(),systemPrompt:c?.toString(),includeBody:a?.toString(),disableLowerCase:l?.toString()},p);(a===!0||u.includeBody===!0)&&Object.keys(u).forEach(C=>{typeof u[C]=="object"&&u[C]!==null&&"includeBody"in u[C]&&(u[C].includeBody=!0)}),l&&Object.keys(u).forEach(C=>{typeof u[C]=="object"&&u[C]!==null&&"disableLowerCase"in u[C]&&(u[C].disableLowerCase=!0)}),await wo(u);const g=W.displaySpinner("Detecting staged files"),y=await rr(r,u.exclude);if(g.stop(),!y)throw new b("No staged changes found. Stage your changes manually, or automatically stage all changes with the `--all` flag.");W.printStagedFiles(y);const w=Lo(u,"commit");if(w.length===0)throw new b("Please set at least one API key via the `aicommit2 config set` command");const v=new it(u,y),E=Lo(u,"review");E.length>0&&await wc(v,E);let A=await vc(v,w,m);if(d){if(W.printInfo("Opening editor to modify commit message..."),A=await bc(A),!A.trim())throw new b("Commit message cannot be empty");W.printSuccess("Commit message edited successfully!"),console.log(`
|
|
183
|
+
${A}
|
|
184
|
+
`)}i&&(zs("copy-paste").copy(A),W.printCopied(),process.exit()),(n||m&&w.length===1)&&(await Do(A,p),process.exit());const{confirmationPrompt:$}=await Ge.prompt([{type:"confirm",name:"confirmationPrompt",message:"Use selected message?",default:!0}]);$?await Do(A,p):W.printCancelledCommit(),process.exit()})().catch(u=>{W.printError(u.message),ne(u),process.exit(1)});function Lo(t,e){return Object.entries(t).map(([r,o])=>[r,o]).filter(([r,o])=>!o.disabled).filter(([r,o])=>we.includes(r)||o.compatible===!0).filter(([r,o])=>{switch(e){case"commit":return r==="OLLAMA"?!!o&&!!o.model&&o.model.length>0:r==="HUGGINGFACE"?!!o&&!!o.cookie:!!o.key&&o.key.length>0;case"review":const s=t.codeReview||o.codeReview;return r==="OLLAMA"?!!o&&!!o.model&&o.model.length>0&&s:r==="HUGGINGFACE"?!!o&&!!o.cookie&&s:!!o.key&&o.key.length>0&&s}}).map(([r])=>r)}async function wc(t,e){const r=new nr(Ro);let o=null;try{const s=r.initPrompt({...sr,name:"codeReviewPrompt",message:"Please check code reviews: ",emptyMessage:`\u26A0 ${Oo}`,isDescriptionDim:!1,stopMessage:"Code review completed",descPageSize:20});if(r.startLoader(),o=t.createCodeReviewRequests$(e).subscribe({next:a=>r.refreshChoices(a),error:a=>{console.error("Code review request error:",a),r.checkErrorOnChoices()},complete:()=>r.checkErrorOnChoices()}),!(await s).codeReviewPrompt?.value)throw new b("An error occurred! No selected code review");W.moveCursorUp();const{continuePrompt:c}=await Ge.prompt([{type:"confirm",name:"continuePrompt",message:"Will you continue without changing the code?",default:!0}]);c||(W.printCancelledCommit(),process.exit())}finally{o&&o.unsubscribe(),r.destroy()}}async function vc(t,e,r){const o=new nr(gc);let s=null;try{if(r&&e.length===1){const a=[];o.startLoader(),s=t.createCommitMsgRequests$(e).subscribe({next:d=>{a.push(d),o.refreshChoices(d)},error:d=>{console.error("Commit message generation error:",d),o.checkErrorOnChoices(!1)},complete:()=>o.checkErrorOnChoices(!1)}),await new Promise(d=>{s?.add(()=>d())}),o.clearLoader(),W.moveCursorUp();const m=a.find(d=>d.value&&!d.isError&&!d.disabled);if(!m||!m.value)throw new b("No valid commit message was generated");return W.print(`
|
|
188
185
|
${m.name}
|
|
189
|
-
`),m.value}const n=o.initPrompt();o.startLoader(),s=t.createCommitMsgRequests$(e).subscribe({next:a=>o.refreshChoices(a),error:a=>{console.error("Commit message generation error:",a),o.checkErrorOnChoices()},complete:()=>o.checkErrorOnChoices()});const i=await n;
|
|
186
|
+
`),m.value}const n=o.initPrompt();o.startLoader(),s=t.createCommitMsgRequests$(e).subscribe({next:a=>o.refreshChoices(a),error:a=>{console.error("Commit message generation error:",a),o.checkErrorOnChoices()},complete:()=>o.checkErrorOnChoices()});const i=await n;W.moveCursorUp();const c=i.aicommit2Prompt?.value;if(!c)throw new b("An error occurred! No selected message");return c}finally{s&&s.unsubscribe(),o.destroy()}}async function bc(t){const e=process.env.VISUAL||process.env.EDITOR||(process.platform==="win32"?"notepad":"vi"),r=x.join(Ee.tmpdir(),`aicommit2-${Date.now()}.txt`);try{U.writeFileSync(r,t,"utf8"),await N(e,[r],{stdio:"inherit"});const o=U.readFileSync(r,"utf8").trim();if(U.unlinkSync(r),!o)throw new b("Commit cancelled - empty message");return o}catch(o){throw U.existsSync(r)&&U.unlinkSync(r),o instanceof b?o:o&&typeof o=="object"&&"exitCode"in o&&o.exitCode!==0?new b("Commit cancelled"):process.env.VISUAL||process.env.EDITOR?new b(`Failed to open editor "${e}". Please check that the editor command is valid and available.`):new b(`Failed to open editor "${e}". Please set your EDITOR or VISUAL environment variable to a valid editor command.`)}}async function Do(t,e){await hc(t,e),W.printCommitted()}var Cc=oe({name:"config",parameters:["<mode>","[key=value...]"],help:{description:"Manage configuration settings",examples:["aic2 config set <key>=<value> [<key>=<value> ...]","aic2 config get [<key> [<key> ...]]","aic2 config add <key>=<value> [<key>=<value> ...]","aic2 config del <key>","aic2 config list"]},commands:[oe({name:"set",parameters:["<key>=<value>","[<key>=<value> ...]"],help:{description:"Set configuration values. Multiple key-value pairs can be set at once.",examples:["aic2 config set OPENAI.key=<your key>","aic2 config set ANTHROPIC.topP=0.8 ANTHROPIC.generate=2"]}}),oe({name:"get",parameters:["[<key>","[<key> ...]]"],help:{description:"Retrieve configuration values for specified AI provider.",examples:["aic2 config get OPENAI","aic2 config get ANTHROPIC"]}}),oe({name:"add",parameters:["<key>=<value>","[<key>=<value> ...]"],help:{description:"Add new model to existing configuration. Only Ollama.model can be added.",examples:['aic2 config add OLLAMA.model="gemma2"']}}),oe({name:"list",parameters:[],help:{description:"Display all configuration keys and their values.",examples:["aic2 config list"]}}),oe({name:"del",parameters:["<config-name>"],help:{description:"Delete a configuration setting or section.",examples:["aic2 config del <config-name>","aic2 config del OPENAI.key","aic2 config del OPENAI"]}}),oe({name:"path",parameters:[],help:{description:"Display the path of the loaded configuration file.",examples:["aic2 config path"]}})]},t=>{(async()=>{const{mode:e,keyValue:r}=t._,o=t._[1];if(e==="get"){const s=await le({},[]);if(r.length===0){console.log(s);return}for(const n of r){const i=n.split(".");let c=s,a=!0;for(const m of i)if(Nt(c,m))c=c[m];else{a=!1;break}a?console.log(n,c):console.log(`${n} not found`)}return}if(e==="set"){await jt(r.map(s=>{const n=s.indexOf("=");if(n===-1)throw new b("Invalid format. Use: key=value");const i=s.slice(0,n),c=s.slice(n+1);return[i,c]}));return}if(e==="add"){await ca(r.map(s=>{const n=s.indexOf("=");if(n===-1)throw new b("Invalid format. Use: key=value");const i=s.slice(0,n),c=s.slice(n+1);return[i,c]}));return}if(e==="list"){await la();return}if(e==="del"){if(!o)throw new b("Please provide the config name to delete.");const s=await Ie(),n=o.split(".");if(n.length===2){const[i,c]=n;if(s[i]&&typeof s[i]=="object"&&Nt(s[i],c)){delete s[i][c],Object.keys(s[i]).length===0&&delete s[i];const a=await ve();await O.writeFile(a,ye.stringify(s),"utf8"),console.log(`Successfully deleted config: ${o}`);const m=await O.readFile(a,"utf8");console.log("--- Updated Config Content ---"),console.log(m),console.log("----------------------------")}else throw new b(`Config not found: ${o}`)}else if(n.length===1){const i=n[0];if(Nt(s,i)){delete s[i];const c=await ve();await O.writeFile(c,ye.stringify(s),"utf8"),console.log(`Successfully deleted config: ${o}`);const a=await O.readFile(c,"utf8");console.log("--- Updated Config Content ---"),console.log(a),console.log("----------------------------")}else throw new b(`Config not found: ${o}`)}else throw new b(`Invalid config name format: ${o}`);return}if(e==="path"){await ua();return}throw new b(`Invalid mode: ${e}`)})().catch(e=>{new re().printError(e.message),ne(e),process.exit(1)})}),Pc=oe({name:"github-login",parameters:[],flags:{token:{type:String,description:"Manually provide a GitHub token for authentication",alias:"t"}},help:{description:"Login to GitHub and setup access to GitHub Models",examples:["aic2 github-login","aic2 github-login --token ghp_xxxxxxxxxxxxxxxxxxxx"]}},t=>{(async()=>{const e=new re;if(t.flags.token){try{await $c(t.flags.token,e)}catch(r){throw new b(`Token authentication failed: ${r.message}`)}return}try{await Ec(e)}catch(r){throw new b(`Browser authentication failed: ${r.message}`)}})().catch(e=>{new re().printError(e.message),ne(e),process.exit(1)})});async function $c(t,e){if(e.printWarning("Authenticating with provided token..."),!t.startsWith("ghp_")&&!t.startsWith("gho_")&&!t.startsWith("ghu_"))throw new Error("Invalid token format. GitHub tokens should start with ghp_, gho_, or ghu_");try{const r=await fetch("https://api.github.com/user",{headers:{Authorization:`Bearer ${t}`,Accept:"application/vnd.github.v3+json","User-Agent":"aicommit2-github-models"}});if(!r.ok)throw new Error(`GitHub API request failed: ${r.status} ${r.statusText}`);const o=await r.json();try{(await fetch("https://models.github.ai/inference/chat/completions",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/vnd.github+json",Authorization:`Bearer ${t}`,"User-Agent":"aicommit2-github-models"},body:JSON.stringify({messages:[{role:"user",content:"test"}],model:"gpt-4o-mini",max_tokens:1})})).ok?e.printSuccess("GitHub Models access verified!"):e.printWarning("Could not verify GitHub Models access, but proceeding with authentication...")}catch{e.printWarning("Could not verify GitHub Models access, but proceeding with authentication...")}await jt([["GITHUB_MODELS.key",t]]),e.printSuccess(`Successfully authenticated as ${o.login}`)}catch(r){throw new Error(`Token validation failed: ${r.message}`)}}async function Ec(t){t.printInfo("Starting GitHub browser authentication for GitHub Models...");try{try{_e("gh --version",{stdio:"ignore"})}catch{throw new Error("GitHub CLI (gh) is not installed. Please install it first: https://cli.github.com/")}try{_e("gh auth status",{encoding:"utf8",stdio:"pipe"}).includes("Logged in to github.com")&&t.printInfo("Already authenticated with GitHub CLI")}catch{t.printInfo("Authenticating with GitHub CLI..."),t.printInfo("Please follow the instructions in your browser to complete authentication.");try{_e("gh auth login --web -h github.com",{stdio:"inherit"})}catch{throw new Error("GitHub CLI authentication failed")}}t.printInfo("Verifying GitHub Models access...");try{const e=_e("gh auth token",{encoding:"utf8"}).trim();e&&(await jt([["GITHUB_MODELS.key",e]]),t.printSuccess("GitHub token stored for GitHub Models access"))}catch{t.printWarning("Could not extract token from GitHub CLI, but authentication completed")}t.printSuccess("GitHub authentication completed and GitHub Models access verified!"),t.printInfo("See usage guide: https://github.com/tak-bro/aicommit2/blob/main/docs/providers/github-models.md"),t.printInfo("Available models: gpt-4o-mini, gpt-4o, meta-llama-3.1-405b-instruct, etc."),t.printInfo("Using GitHub Models API: https://models.github.ai")}catch(e){throw e}}const To="prepare-commit-msg",Fo=`.git/hooks/${To}`,at=ws(new URL("cli.mjs",import.meta.url)),xc=process.argv[1].replace(/\\/g,"/").endsWith(`/${Fo}`),No=process.platform==="win32",jo=`
|
|
190
187
|
#!/usr/bin/env node
|
|
191
|
-
import(${JSON.stringify(
|
|
192
|
-
`.trim();var
|
|
193
|
-
`);const r=await Promise.all(e.map(async o=>{const s=ae.join(ee,o),n=await
|
|
194
|
-
${P.green("Total:")} ${e.length} file${e.length!==1?"s":""}`)}catch(e){if(e.code==="ENOENT")console.log(`${P.yellow("Logs directory does not exist yet.")}`);else throw e}},
|
|
188
|
+
import(${JSON.stringify(vs(at))})
|
|
189
|
+
`.trim();var kc=oe({name:"hook",parameters:["<install/uninstall>"],help:{description:"Install or uninstall the Git prepare-commit-msg hook",examples:["aic2 hook install","aic2 hook uninstall"]}},t=>{(async()=>{const e=await tr(),{installUninstall:r}=t._,o=x.join(e,Fo),s=await co(o);if(r==="install"){if(s){if(await O.realpath(o).catch(()=>{})===at){console.warn("The hook is already installed");return}throw new b(`A different ${To} hook seems to be installed. Please remove it before installing aicommit2.`)}await O.mkdir(x.dirname(o),{recursive:!0}),No?await O.writeFile(o,jo):(await O.symlink(at,o,"file"),await O.chmod(o,493)),console.log(`${P.green("\u2714")} Hook installed`);return}if(r==="uninstall"){if(!s){console.warn("Hook is not installed");return}if(No){if(await O.readFile(o,"utf8")!==jo){console.warn("Hook is not installed");return}}else if(await O.realpath(o)!==at){console.warn("Hook is not installed");return}await O.rm(o),console.log(`${P.green("\u2714")} Hook uninstalled`);return}throw new b(`Invalid mode: ${r}`)})().catch(e=>{console.error(`${P.red("\u2716")} ${e.message}`),ne(e),process.exit(1)})});const Ac=as(Qo),Sc=t=>{const e=["B","KB","MB","GB"];if(t===0)return"0 B";const r=Math.floor(Math.log(t)/Math.log(1024));return Math.round(t/Math.pow(1024,r)*100)/100+" "+e[r]},Mc=t=>t.toLocaleDateString()+" "+t.toLocaleTimeString(),Ic=async t=>{try{const e=await xr(ee);if(e.length===0){console.log(`${P.yellow("No log files found.")}`);return}console.log(`${P.blue("Log files in")} ${ee}:
|
|
190
|
+
`);const r=await Promise.all(e.map(async o=>{const s=ae.join(ee,o),n=await ks(s);return{name:o,size:Sc(n.size),modified:Mc(n.mtime)}}));r.sort((o,s)=>new Date(s.modified).getTime()-new Date(o.modified).getTime()),r.forEach((o,s)=>{console.log(`${s===0?"\u{1F4C4}":" "} ${P.cyan(o.name)} ${P.gray(`(${o.size}, ${o.modified})`)}`)}),console.log(`
|
|
191
|
+
${P.green("Total:")} ${e.length} file${e.length!==1?"s":""}`)}catch(e){if(e.code==="ENOENT")console.log(`${P.yellow("Logs directory does not exist yet.")}`);else throw e}},Rc=async t=>{try{await xr(ee);const e=process.platform;let r;switch(e){case"darwin":r=`open "${ee}"`;break;case"win32":r=`start "" "${ee}"`;break;default:r=`xdg-open "${ee}"`;break}await Ac(r),console.log(`${P.green("\u2714")} Opened logs directory in file manager`)}catch(e){e.code==="ENOENT"?console.log(`${P.yellow("Logs directory does not exist yet.")}`):t.printError(`Failed to open logs directory: ${e.message}`)}},Oc=async t=>{try{await As(ee,{recursive:!0,force:!0}),console.log(`${P.green("\u2714")} All log files removed!`)}catch(e){t.printError(`Failed to remove log files: ${e.message}`)}};var Lc=oe({name:"log",parameters:["<action>"],help:{description:"Manage log files generated by the application",examples:["aic2 log list # List all log files","aic2 log path # Show logs directory path","aic2 log open # Open logs directory","aic2 log removeAll # Remove all log files"]}},t=>{(async()=>{const{action:e}=t._,r=new re;switch(e){case"list":await Ic();break;case"path":console.log(`${P.blue("Logs directory:")} ${ee}`);break;case"open":await Rc(r);break;case"removeAll":await Oc(r);break;default:throw new b(`Invalid action: ${e}. Use 'list', 'path', 'open', or 'removeAll'`)}})().catch(e=>{new re().printError(e.message),ne(e),process.exit(1)})});const Dc=process.argv.slice(2).filter(t=>!t.startsWith("--pre-commit")),[ct,_o]=Dc;var Tc=()=>(async()=>{if(!ct)throw new b('Commit message file path is missing. This file should be called from the "pre-commit framework"');if(_o){console.log(`Skipping aicommit2 message generation for ${_o} commit`);return}const t=await rr();if(!t)return;const e=new re;e.printTitle();const r=await le({});if(r.systemPromptPath)try{await O.readFile(x.resolve(r.systemPromptPath),"utf-8")}catch{throw new b(`Error reading system prompt file: ${r.systemPromptPath}`)}const o=Object.entries(r).filter(([u])=>we.includes(u)).map(([u,h])=>[u,h]).filter(([u,h])=>!h.disabled).filter(([u,h])=>u==="OLLAMA"?!!h&&!!h.model&&h.model.length>0:u==="HUGGINGFACE"?!!h&&!!h.cookie:!!h.key&&h.key.length>0).map(([u])=>u);if(o.length===0)throw new b("Please set at least one API key via the `aicommit2 config set` command");const n=new it(r,t);let i;try{i=await wr(n.createCommitMsgRequests$(o).pipe(vr(u=>!u.isError),I(u=>u.value),br()))}finally{e.printAnalyzed()}const a=await O.readFile(ct,"utf8")!=="",m=i.length>1;let d="";a&&(d=`# \u{1F916} Generated by aicommit2 (https://github.com/tak-bro/aicommit2)
|
|
195
192
|
`,d+=`# ----------------------------------------
|
|
196
193
|
`,d+=`# How to use:
|
|
197
194
|
`,m?(d+=`# 1. Remove the "#" from your chosen message
|
|
@@ -210,7 +207,7 @@ ${i.map(u=>`# ${u}`).join(`
|
|
|
210
207
|
`),d+=`
|
|
211
208
|
${i[0]}
|
|
212
209
|
`);const l=await O.readFile(ct,"utf8"),p=d+`
|
|
213
|
-
`+l;await O.writeFile(ct,p),e.printSavedCommitMessage()})().catch(t=>{new re().printError(t.message),ne(t),process.exit(1)});const
|
|
210
|
+
`+l;await O.writeFile(ct,p),e.printSavedCommitMessage()})().catch(t=>{new re().printError(t.message),ne(t),process.exit(1)});const ir=process.argv.slice(2),Go=[];let ar=!1;for(let t=0;t<ir.length;t++){const e=ir[t];if(ar){ar=!1;continue}if(e!=="--hook-mode"){if(e.startsWith("-")){const r=ir[t+1];r&&!r.startsWith("-")&&(ar=!0);continue}Go.push(e)}}const[lt,Ho]=Go;var Fc=(t,e,r,o,s,n)=>(async()=>{if(!lt)throw new b('Commit message file path is missing. This file should be called from the "prepare-commit-msg" git hook or with --hook-mode flag');if(Ho){console.log(`Skipping aicommit2 message generation for ${Ho} commit`);return}const i=await rr();if(!i)return;const c=new re;c.printTitle();const a=await le({locale:t?.toString(),generate:e?.toString(),type:o?.toString(),systemPrompt:s?.toString(),includeBody:n?.toString()},r);if(a.systemPromptPath)try{await O.readFile(x.resolve(a.systemPromptPath),"utf-8")}catch{throw new b(`Error reading system prompt file: ${a.systemPromptPath}`)}const m=Object.entries(a).filter(([$])=>we.includes($)).map(([$,C])=>[$,C]).filter(([$,C])=>!C.disabled).filter(([$,C])=>$==="OLLAMA"?!!C&&!!C.model&&C.model.length>0:$==="HUGGINGFACE"?!!C&&!!C.cookie:!!C.key&&C.key.length>0).map(([$])=>$);if(m.length===0)throw new b("Please set at least one API key via the `aicommit2 config set` command");const l=new it(a,i),p=c.displaySpinner("The AI is analyzing your changes");let u;try{u=await wr(l.createCommitMsgRequests$(m).pipe(vr($=>!$.isError),I($=>$.value),br()))}finally{p.stop(),p.clear(),c.printAnalyzed()}const g=await O.readFile(lt,"utf8")!=="",y=u.length>1,w=await mc();let v="";g&&(v=`${w} \u{1F916} Generated by aicommit2 (https://github.com/tak-bro/aicommit2)
|
|
214
211
|
`,v+=`${w} ----------------------------------------
|
|
215
212
|
`,v+=`${w} How to use:
|
|
216
213
|
`,y?(v+=`${w} 1. Remove the "${w}" from your chosen message
|
|
@@ -228,14 +225,11 @@ ${u.map($=>`${w} ${$}`).join(`
|
|
|
228
225
|
${w} \u{1F4DD} Generated commit message:
|
|
229
226
|
`),v+=`
|
|
230
227
|
${u[0]}
|
|
231
|
-
`);const E=await O.readFile(lt,"utf8"),
|
|
232
|
-
`+E;await O.writeFile(lt,
|
|
233
|
-
commit_hash=$(git rev-parse HEAD)
|
|
234
|
-
commit_message=$(git log -1 --pretty=%B)
|
|
235
|
-
echo "$commit_hash: $commit_message" >> ${this.LOG_PATH}
|
|
236
|
-
`,this.setupProcessHandlers()}setupProcessHandlers(){const e=()=>{this.destroy(),process.exit(0)};process.on("SIGINT",e),process.on("SIGTERM",e),process.on("SIGQUIT",e)}async watch(e,r,o,s,n){this.consoleManager.printTitle(),await rr();const i=await this.initializeConfig(e,r,s,n);this.setupGitHook(),this.initLogFile();try{await this.watchCommitLog(i)}catch(c){return await this.handleWatchGitError(c),this.watch(e,r,o,s,n)}}async initializeConfig(e,r,o,s){const n=await le({locale:e?.toString(),generate:r?.toString(),systemPrompt:o?.toString()},s);return await wo(n),this.getAvailableAIs(n).length===0&&(this.consoleManager.printError(`Please set at least one API key and watchMode via the config command:
|
|
228
|
+
`);const E=await O.readFile(lt,"utf8"),A=v+`
|
|
229
|
+
`+E;await O.writeFile(lt,A),c.printSavedCommitMessage()})().catch(i=>{new re().printError(i.message),ne(i),process.exit(1)});class Bo{constructor(e="SubscriptionManager"){this.destroyed$=new ft,this.subscriptions=new mt,this.isDestroyed=!1,this.name=e}add(e,r){if(this.isDestroyed){console.warn(`${this.name}: Cannot add subscription - manager is destroyed`);const s=new mt;return s.unsubscribe(),s}const o=e.pipe(kr(this.destroyed$),Ar(()=>{process.env.NODE_ENV==="development"&&console.log(`${this.name}: Observable finalized`)})).subscribe({next:r?.next,error:s=>{console.error(`${this.name}: Observable error:`,s),r?.error?.(s)},complete:r?.complete});return this.subscriptions.add(o),o}pipe(e){return this.isDestroyed?(console.warn(`${this.name}: Cannot pipe - manager is destroyed`),e):e.pipe(kr(this.destroyed$),Ar(()=>{process.env.NODE_ENV==="development"&&console.log(`${this.name}: Piped observable finalized`)}))}addSubscription(e){if(this.isDestroyed){console.warn(`${this.name}: Cannot add subscription - manager is destroyed`),e.unsubscribe();return}this.subscriptions.add(e)}get destroySignal$(){return this.destroyed$.asObservable()}get isActive(){return!this.isDestroyed}destroy(){this.isDestroyed||(this.isDestroyed=!0,this.subscriptions.unsubscribe(),this.destroyed$.next(),this.destroyed$.complete(),process.env.NODE_ENV==="development"&&console.log(`${this.name}: Destroyed successfully`))}}const Nc=new Bo("Global"),je=()=>{Nc.destroy()};process.on("exit",je),process.on("SIGINT",je),process.on("SIGTERM",je),process.on("uncaughtException",t=>{console.error("Uncaught exception:",t),je(),process.exit(1)}),process.on("unhandledRejection",(t,e)=>{console.error("Unhandled rejection at:",e,"reason:",t),je(),process.exit(1)});class jc{constructor(){this.destroyed$=new ft,this.consoleManager=new re,this.subscriptionManager=new Bo,this.currentCodeReviewSubscription=null,this.currentCodeReviewPromptManager=null,this.watcher=null,this.lastCommitHash=null,this.isProcessingCommit=!1,this.REPO_PATH=process.cwd(),this.GIT_PATH=x.join(this.REPO_PATH,".git"),this.HEAD_PATH=x.join(this.GIT_PATH,"HEAD"),this.REFS_PATH=x.join(this.GIT_PATH,"refs","heads"),this.COMMIT_MSG_PATH=x.join(this.GIT_PATH,"COMMIT_EDITMSG"),this.setupProcessHandlers()}setupProcessHandlers(){const e=()=>{this.destroy(),process.exit(0)};process.on("SIGINT",e),process.on("SIGTERM",e),process.on("SIGQUIT",e)}async watch(e,r,o,s,n){this.consoleManager.printTitle(),await tr();const i=await this.initializeConfig(e,r,s,n);await this.initializeCurrentCommit();try{await this.watchGitEvents(i)}catch(c){return await this.handleWatchGitError(c),this.watch(e,r,o,s,n)}}async initializeConfig(e,r,o,s){const n=await le({locale:e?.toString(),generate:r?.toString(),systemPrompt:o?.toString()},s);return await wo(n),this.getAvailableAIs(n).length===0&&(this.consoleManager.printError(`Please set at least one API key and watchMode via the config command:
|
|
237
230
|
aicommit2 config set [MODEL].key="YOUR_API_KEY"
|
|
238
|
-
aicommit2 config set [MODEL].watchMode="true"`),process.exit()),n}async handleWatchGitError(e){this.consoleManager.printError(`An error occurred: ${e.message}`),ne(e),await new Promise(r=>setTimeout(r,3e3)),this.consoleManager.printWarning("Restarting the commit monitoring process...")}
|
|
231
|
+
aicommit2 config set [MODEL].watchMode="true"`),process.exit()),n}async handleWatchGitError(e){this.consoleManager.printError(`An error occurred: ${e.message}`),ne(e),await new Promise(r=>setTimeout(r,3e3)),this.consoleManager.printWarning("Restarting the commit monitoring process...")}async initializeCurrentCommit(){try{const e=await this.executeGitCommand("git rev-parse HEAD");this.lastCommitHash=e.trim(),this.consoleManager.printInfo(`Starting watch from commit: ${this.lastCommitHash.substring(0,8)}`)}catch{this.consoleManager.printWarning("No commits found in repository"),this.lastCommitHash=null}}async executeGitCommand(e){const r=ns(es),{stdout:o}=await r(e,{cwd:this.REPO_PATH});return o}getAvailableAIs(e){return Object.entries(e).filter(([r,o])=>we.includes(r)||o.compatible===!0).map(([r,o])=>[r,o]).filter(([r,o])=>!o.disabled).filter(([r,o])=>this.isAIAvailable(r,o,e)).map(([r])=>r)}isAIAvailable(e,r,o){const s=o.watchMode||r.watchMode;return e==="OLLAMA"?!!r&&!!r.model&&r.model.length>0&&s:e==="HUGGINGFACE"?!!r&&!!r.cookie&&s:r.compatible?!!r.url&&!!r.key&&s:!!r.key&&r.key.length>0&&s}clearTerminal(){process.stdout.write("\x1Bc")}async handleCommitEvent(e,r){try{const o=await dc(r);if(!o){this.consoleManager.printWarning("No changes found in this commit");return}this.consoleManager.stopLoader(),this.consoleManager.printStagedFiles(o);const s=this.getAvailableAIs(e);if(s.length===0){this.consoleManager.printError(`Please set at least one API key and watchMode via the config command:
|
|
239
232
|
aicommit2 config set [MODEL].key="YOUR_API_KEY"
|
|
240
|
-
aicommit2 config set [MODEL].watchMode="true"`),process.exit();return}await this.performCodeReview(e,o,s)}catch(o){this.consoleManager.printError(`Error processing commit ${r}: ${o.message}`)}}async performCodeReview(e,r,o){this.cleanupPreviousCodeReview();const s=new it(e,r);this.currentCodeReviewPromptManager=new
|
|
241
|
-
|
|
233
|
+
aicommit2 config set [MODEL].watchMode="true"`),process.exit();return}await this.performCodeReview(e,o,s)}catch(o){this.consoleManager.printError(`Error processing commit ${r}: ${o.message}`)}}async performCodeReview(e,r,o){this.cleanupPreviousCodeReview();const s=new it(e,r);this.currentCodeReviewPromptManager=new nr(Ro);try{const n=this.initializeCodeReviewInquirer();this.currentCodeReviewPromptManager.startLoader(),this.currentCodeReviewSubscription=this.subscribeToCodeReviewRequests(s,o),await n}finally{this.cleanupCodeReview()}}cleanupPreviousCodeReview(){this.cleanupCurrentReviewResources(),this.destroyed$.closed||(this.destroyed$.next(),this.destroyed$.complete()),this.destroyed$=new ft}initializeCodeReviewInquirer(){return this.currentCodeReviewPromptManager.initPrompt({...sr,name:"codeReviewPrompt",message:"Please check code reviews: ",emptyMessage:`\u26A0 ${Oo}`,isDescriptionDim:!1,stopMessage:"Code review completed",descPageSize:20})}subscribeToCodeReviewRequests(e,r){return this.subscriptionManager.add(e.createCodeReviewRequests$(r),{next:o=>{this.currentCodeReviewPromptManager?.refreshChoices(o)},error:o=>{console.error("Code review request error:",o),this.currentCodeReviewPromptManager?.checkErrorOnChoices(!1)},complete:()=>{this.currentCodeReviewPromptManager?.checkErrorOnChoices(!1)}})}cleanupCurrentReviewResources(){this.currentCodeReviewSubscription&&(this.currentCodeReviewSubscription.unsubscribe(),this.currentCodeReviewSubscription=null),this.currentCodeReviewPromptManager&&(this.currentCodeReviewPromptManager.destroy(),this.currentCodeReviewPromptManager=null)}cleanupCodeReview(){this.cleanupCurrentReviewResources(),this.clearTerminal(),this.consoleManager.showLoader("Watching for new Git commits...")}async isGitReset(e){if(!this.lastCommitHash)return!1;try{const r=await this.executeGitCommand(`git merge-base --is-ancestor ${e} ${this.lastCommitHash}`);return!0}catch{return!1}}cancelCurrentReview(){this.currentCodeReviewPromptManager&&this.currentCodeReviewPromptManager.cancel(),this.cleanupCurrentReviewResources(),this.destroyed$.next()}async watchGitEvents(e){this.consoleManager.showLoader("Watching for new Git commits...");const o=[this.HEAD_PATH,this.REFS_PATH,this.COMMIT_MSG_PATH,x.join(this.GIT_PATH,"logs","HEAD")].filter(s=>{try{return U.accessSync(s),!0}catch{return!1}});this.watcher=Ss.watch(o,{persistent:!0,ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:500,pollInterval:100}}),this.watcher.on("change",async s=>{await this.handleGitChange(e,s)}),this.watcher.on("add",async s=>{await this.handleGitChange(e,s)}),this.watcher.on("error",s=>{this.consoleManager.printError(`Watcher error: ${s.message}`),setTimeout(()=>this.watchGitEvents(e),1e3)})}async handleGitChange(e,r){try{const s=(await this.executeGitCommand("git rev-parse HEAD")).trim();if(s!==this.lastCommitHash){if(await this.isGitReset(s)){this.clearTerminal(),this.consoleManager.printInfo(`\u21A9\uFE0F Git reset detected: ${s.substring(0,8)}`),this.lastCommitHash=s,this.isProcessingCommit&&(this.cancelCurrentReview(),this.isProcessingCommit=!1);return}if(this.isProcessingCommit){this.consoleManager.printInfo(`
|
|
234
|
+
\u{1F504} New commit detected, cancelling current review...`);try{this.cancelCurrentReview(),await new Promise(i=>setTimeout(i,200))}catch(i){console.warn("Error during review cancellation:",i)}}this.isProcessingCommit=!0;try{this.consoleManager.stopLoader(),this.consoleManager.printInfo(`
|
|
235
|
+
\u{1F50D} New commit detected: ${s.substring(0,8)}`);const i=this.lastCommitHash;this.lastCommitHash=s,this.clearTerminal(),await this.handleCommitEvent(e,s)}catch(i){this.consoleManager.printError(`Error processing commit ${s.substring(0,8)}: ${i.message}`)}finally{this.isProcessingCommit=!1}}}catch(o){this.isProcessingCommit=!1,o.message?.includes("fatal: not a git repository")||this.consoleManager.printError(`Error checking for new commits: ${o.message}`)}}destroy(){this.isProcessingCommit=!1,this.lastCommitHash=null;try{this.subscriptionManager.destroy(),this.cleanupCurrentReviewResources(),this.watcher&&(this.watcher.close(),this.watcher=null),this.consoleManager.stopLoader(),this.destroyed$.next(),this.destroyed$.complete()}catch(e){console.warn("Error during WatchGitManager destruction:",e)}}}const _c=new jc,Gc=async(t,e,r,o,s)=>_c.watch(t,e,r,o,s),cr=process.argv.slice(2),{version:Uo,description:Hc}=Us;Yo({name:"aicommit2",version:Uo,flags:{locale:{type:String,description:"Locale to use for the generated commit messages (default: en)",alias:"l"},generate:{type:Number,description:"Number of messages to generate (Warning: generating multiple costs more) (default: 1)",alias:"g"},exclude:{type:[String],description:"Files to exclude from AI analysis",alias:"x"},all:{type:Boolean,description:"Automatically stage changes in tracked files for the commit",alias:"a",default:!1},type:{type:String,description:"Type of commit message to generate (default: conventional)",alias:"t"},confirm:{type:Boolean,description:"Skip confirmation when committing after message generation (default: false)",alias:"y",default:!1},clipboard:{type:Boolean,description:"Copy the selected message to the clipboard",alias:"c",default:!1},prompt:{type:String,description:"Custom prompt to let users fine-tune provided prompt",alias:"p"},"watch-commit":{type:Boolean,default:!1},"hook-mode":{type:Boolean,description:"Run in git hook mode, allowing chaining with other hooks",default:!1},"pre-commit":{type:Boolean,description:"Run in pre-commit Framework, allowing chaining with other hooks",default:!1},"include-body":{type:Boolean,description:"Force include commit body in all generated messages",alias:"i",default:!1},"auto-select":{type:Boolean,description:"Automatically select the message when only one is generated",alias:"s",default:!1},edit:{type:Boolean,description:"Open the AI-generated commit message in your default editor",alias:"e",default:!1},"disable-lowercase":{type:Boolean,description:"Disable automatic lowercase conversion of commit messages",default:!1}},commands:[Cc,Pc,kc,Lc],help:{description:Hc},ignoreArgv:t=>t==="unknown-flag"||t==="argument"},async t=>{const e=await le({});if(await ha(e),be.info(`aicommit2 version: ${Uo}`),t.flags["pre-commit"]){Tc();return}if(t.flags["hook-mode"]||xc){Fc(t.flags.locale,t.flags.generate,t.flags.exclude,t.flags.type,t.flags.prompt,t.flags["include-body"]);return}if(t.flags["watch-commit"]){Gc(t.flags.locale,t.flags.generate,t.flags.exclude,t.flags.prompt,cr);return}yc(t.flags.locale,t.flags.generate,t.flags.exclude,t.flags.all,t.flags.type,t.flags.confirm,t.flags.clipboard,t.flags.prompt,t.flags["include-body"],t.flags["auto-select"],t.flags.edit,t.flags["disable-lowercase"],cr)},cr);
|