aicommit2
Version:
A Reactive CLI that generates git commit messages with various AI
68 lines (56 loc) • 124 kB
JavaScript
#!/usr/bin/env node
import{command as Q,cli as Os}from"cleye";import{createRequire as Ls}from"module";import{Buffer as Ts}from"node:buffer";import re from"node:path";import zt,{ChildProcess as Ns}from"node:child_process";import q from"node:process";import Fs from"child_process";import T from"path";import _ from"fs";import{fileURLToPath as Kt}from"node:url";import _s,{constants as Wt}from"node:os";import Yt from"assert";import Vt from"events";import{createWriteStream as Ds,createReadStream as Gs}from"node:fs";import js from"buffer";import Xe from"stream";import Jt from"util";import{debuglog as Bs}from"node:util";import Ce from"inquirer";import Qe from"ora";import w from"chalk";import{of as O,concatMap as A,from as $,map as E,catchError as x,mergeMap as Ee,BehaviorSubject as Xt,ReplaySubject as Hs,lastValueFrom as Qt,filter as Zt,toArray as er,Subject as tr}from"rxjs";import Us from"@anthropic-ai/sdk";import{fromPromise as M}from"rxjs/internal/observable/innerFrom";import Ze from"os";import{xxh64 as qs}from"@pacote/xxhash";import zs from"axios";import{CohereClient as Ks,CohereTimeoutError as Ws}from"cohere-ai";import xe from"openai";import{GoogleGenerativeAI as Ys,HarmCategory as Ae,HarmBlockThreshold as Me}from"@google/generative-ai";import rr from"groq-sdk";import{Ollama as Vs}from"ollama";import{fetch as Js,Agent as Xs}from"undici";import I from"fs/promises";import Qs from"http";import Zs from"https";import eo from"net";import to from"tls";import ro,{fileURLToPath as so,pathToFileURL as oo}from"url";import sr from"tty";import Se from"readline";import no from"figlet";import io from"inquirer-reactive-list-prompt";import{rm as ao}from"node:fs/promises";import co from"chokidar";import{takeUntil as lo}from"rxjs/operators";var mo=Ls(import.meta.url),k=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function se(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var oe={exports:{}},et,or;function uo(){if(or)return et;or=1,et=r,r.sync=o;var t=_;function e(n,i){var l=i.pathExt!==void 0?i.pathExt:process.env.PATHEXT;if(!l||(l=l.split(";"),l.indexOf("")!==-1))return!0;for(var c=0;c<l.length;c++){var m=l[c].toLowerCase();if(m&&n.substr(-m.length).toLowerCase()===m)return!0}return!1}function s(n,i,l){return!n.isSymbolicLink()&&!n.isFile()?!1:e(i,l)}function r(n,i,l){t.stat(n,function(c,m){l(c,c?!1:s(m,n,i))})}function o(n,i){return s(t.statSync(n),n,i)}return et}var tt,nr;function po(){if(nr)return tt;nr=1,tt=e,e.sync=s;var t=_;function e(n,i,l){t.stat(n,function(c,m){l(c,c?!1:r(m,i))})}function s(n,i){return r(t.statSync(n),i)}function r(n,i){return n.isFile()&&o(n,i)}function o(n,i){var l=n.mode,c=n.uid,m=n.gid,p=i.uid!==void 0?i.uid:process.getuid&&process.getuid(),a=i.gid!==void 0?i.gid:process.getgid&&process.getgid(),d=parseInt("100",8),f=parseInt("010",8),h=parseInt("001",8),g=d|f,y=l&h||l&f&&m===a||l&d&&c===p||l&g&&p===0;return y}return tt}var Re;process.platform==="win32"||k.TESTING_WINDOWS?Re=uo():Re=po();var fo=rt;rt.sync=ho;function rt(t,e,s){if(typeof e=="function"&&(s=e,e={}),!s){if(typeof Promise!="function")throw new TypeError("callback not provided");return new Promise(function(r,o){rt(t,e||{},function(n,i){n?o(n):r(i)})})}Re(t,e||{},function(r,o){r&&(r.code==="EACCES"||e&&e.ignoreErrors)&&(r=null,o=!1),s(r,o)})}function ho(t,e){try{return Re.sync(t,e||{})}catch(s){if(e&&e.ignoreErrors||s.code==="EACCES")return!1;throw s}}const ne=process.platform==="win32"||process.env.OSTYPE==="cygwin"||process.env.OSTYPE==="msys",ir=T,go=ne?";":":",ar=fo,cr=t=>Object.assign(new Error(`not found: ${t}`),{code:"ENOENT"}),lr=(t,e)=>{const s=e.colon||go,r=t.match(/\//)||ne&&t.match(/\\/)?[""]:[...ne?[process.cwd()]:[],...(e.path||process.env.PATH||"").split(s)],o=ne?e.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",n=ne?o.split(s):[""];return ne&&t.indexOf(".")!==-1&&n[0]!==""&&n.unshift(""),{pathEnv:r,pathExt:n,pathExtExe:o}},mr=(t,e,s)=>{typeof e=="function"&&(s=e,e={}),e||(e={});const{pathEnv:r,pathExt:o,pathExtExe:n}=lr(t,e),i=[],l=m=>new Promise((p,a)=>{if(m===r.length)return e.all&&i.length?p(i):a(cr(t));const d=r[m],f=/^".*"$/.test(d)?d.slice(1,-1):d,h=ir.join(f,t),g=!f&&/^\.[\\\/]/.test(t)?t.slice(0,2)+h:h;p(c(g,m,0))}),c=(m,p,a)=>new Promise((d,f)=>{if(a===o.length)return d(l(p+1));const h=o[a];ar(m+h,{pathExt:n},(g,y)=>{if(!g&&y)if(e.all)i.push(m+h);else return d(m+h);return d(c(m,p,a+1))})});return s?l(0).then(m=>s(null,m),s):l(0)},yo=(t,e)=>{e=e||{};const{pathEnv:s,pathExt:r,pathExtExe:o}=lr(t,e),n=[];for(let i=0;i<s.length;i++){const l=s[i],c=/^".*"$/.test(l)?l.slice(1,-1):l,m=ir.join(c,t),p=!c&&/^\.[\\\/]/.test(t)?t.slice(0,2)+m:m;for(let a=0;a<r.length;a++){const d=p+r[a];try{if(ar.sync(d,{pathExt:o}))if(e.all)n.push(d);else return d}catch{}}}if(e.all&&n.length)return n;if(e.nothrow)return null;throw cr(t)};var wo=mr;mr.sync=yo;var st={exports:{}};const ur=(t={})=>{const e=t.env||process.env;return(t.platform||process.platform)!=="win32"?"PATH":Object.keys(e).reverse().find(r=>r.toUpperCase()==="PATH")||"Path"};st.exports=ur,st.exports.default=ur;var vo=st.exports;const dr=T,bo=wo,Po=vo;function pr(t,e){const s=t.options.env||process.env,r=process.cwd(),o=t.options.cwd!=null,n=o&&process.chdir!==void 0&&!process.chdir.disabled;if(n)try{process.chdir(t.options.cwd)}catch{}let i;try{i=bo.sync(t.command,{path:s[Po({env:s})],pathExt:e?dr.delimiter:void 0})}catch{}finally{n&&process.chdir(r)}return i&&(i=dr.resolve(o?t.options.cwd:"",i)),i}function $o(t){return pr(t)||pr(t,!0)}var Co=$o,ot={};const nt=/([()\][%!^"`<>&|;, *?])/g;function Eo(t){return t=t.replace(nt,"^$1"),t}function xo(t,e){return t=`${t}`,t=t.replace(/(?=(\\+?)?)\1"/g,'$1$1\\"'),t=t.replace(/(?=(\\+?)?)\1$/,"$1$1"),t=`"${t}"`,t=t.replace(nt,"^$1"),e&&(t=t.replace(nt,"^$1")),t}ot.command=Eo,ot.argument=xo;var Ao=/^#!(.*)/;const Mo=Ao;var So=(t="")=>{const e=t.match(Mo);if(!e)return null;const[s,r]=e[0].replace(/#! ?/,"").split(" "),o=s.split("/").pop();return o==="env"?r:r?`${o} ${r}`:o};const it=_,Ro=So;function Io(t){const s=Buffer.alloc(150);let r;try{r=it.openSync(t,"r"),it.readSync(r,s,0,150,0),it.closeSync(r)}catch{}return Ro(s.toString())}var ko=Io;const Oo=T,fr=Co,hr=ot,Lo=ko,To=process.platform==="win32",No=/\.(?:com|exe)$/i,Fo=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function _o(t){t.file=fr(t);const e=t.file&&Lo(t.file);return e?(t.args.unshift(t.file),t.command=e,fr(t)):t.file}function Do(t){if(!To)return t;const e=_o(t),s=!No.test(e);if(t.options.forceShell||s){const r=Fo.test(e);t.command=Oo.normalize(t.command),t.command=hr.command(t.command),t.args=t.args.map(n=>hr.argument(n,r));const o=[t.command].concat(t.args).join(" ");t.args=["/d","/s","/c",`"${o}"`],t.command=process.env.comspec||"cmd.exe",t.options.windowsVerbatimArguments=!0}return t}function Go(t,e,s){e&&!Array.isArray(e)&&(s=e,e=null),e=e?e.slice(0):[],s=Object.assign({},s);const r={command:t,args:e,options:s,file:void 0,original:{command:t,args:e}};return s.shell?r:Do(r)}var jo=Go;const at=process.platform==="win32";function ct(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 Bo(t,e){if(!at)return;const s=t.emit;t.emit=function(r,o){if(r==="exit"){const n=gr(o,e);if(n)return s.call(t,"error",n)}return s.apply(t,arguments)}}function gr(t,e){return at&&t===1&&!e.file?ct(e.original,"spawn"):null}function Ho(t,e){return at&&t===1&&!e.file?ct(e.original,"spawnSync"):null}var Uo={hookChildProcess:Bo,verifyENOENT:gr,verifyENOENTSync:Ho,notFoundError:ct};const yr=Fs,lt=jo,mt=Uo;function wr(t,e,s){const r=lt(t,e,s),o=yr.spawn(r.command,r.args,r.options);return mt.hookChildProcess(o,r),o}function qo(t,e,s){const r=lt(t,e,s),o=yr.spawnSync(r.command,r.args,r.options);return o.error=o.error||mt.verifyENOENTSync(o.status,r),o}oe.exports=wr,oe.exports.spawn=wr,oe.exports.sync=qo,oe.exports._parse=lt,oe.exports._enoent=mt;var zo=oe.exports,Ko=se(zo);function Wo(t){const e=typeof t=="string"?`
`:`
`.charCodeAt(),s=typeof t=="string"?"\r":"\r".charCodeAt();return t[t.length-1]===e&&(t=t.slice(0,-1)),t[t.length-1]===s&&(t=t.slice(0,-1)),t}function vr(t={}){const{env:e=process.env,platform:s=process.platform}=t;return s!=="win32"?"PATH":Object.keys(e).reverse().find(r=>r.toUpperCase()==="PATH")||"Path"}const Yo=({cwd:t=q.cwd(),path:e=q.env[vr()],preferLocal:s=!0,execPath:r=q.execPath,addExecPath:o=!0}={})=>{const n=t instanceof URL?Kt(t):t,i=re.resolve(n),l=[];return s&&Vo(l,i),o&&Jo(l,r,i),[...l,e].join(re.delimiter)},Vo=(t,e)=>{let s;for(;s!==e;)t.push(re.join(e,"node_modules/.bin")),s=e,e=re.resolve(e,"..")},Jo=(t,e,s)=>{const r=e instanceof URL?Kt(e):e;t.push(re.resolve(s,r,".."))},Xo=({env:t=q.env,...e}={})=>{t={...t};const s=vr({env:t});return e.path=t[s],t[s]=Yo(e),t},Qo=(t,e,s,r)=>{if(s==="length"||s==="prototype"||s==="arguments"||s==="caller")return;const o=Object.getOwnPropertyDescriptor(t,s),n=Object.getOwnPropertyDescriptor(e,s);!Zo(o,n)&&r||Object.defineProperty(t,s,n)},Zo=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)},en=(t,e)=>{const s=Object.getPrototypeOf(e);s!==Object.getPrototypeOf(t)&&Object.setPrototypeOf(t,s)},tn=(t,e)=>`/* Wrapped ${t}*/
${e}`,rn=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),sn=Object.getOwnPropertyDescriptor(Function.prototype.toString,"name"),on=(t,e,s)=>{const r=s===""?"":`with ${s.trim()}() `,o=tn.bind(null,r,e.toString());Object.defineProperty(o,"name",sn),Object.defineProperty(t,"toString",{...rn,value:o})};function nn(t,e,{ignoreNonConfigurable:s=!1}={}){const{name:r}=t;for(const o of Reflect.ownKeys(e))Qo(t,e,o,s);return en(t,e),on(t,e,r),t}const Ie=new WeakMap,br=(t,e={})=>{if(typeof t!="function")throw new TypeError("Expected a function");let s,r=0;const o=t.displayName||t.name||"<anonymous>",n=function(...i){if(Ie.set(n,++r),r===1)s=t.apply(this,i),t=null;else if(e.throw===!0)throw new Error(`Function \`${o}\` can only be called once`);return s};return nn(n,t),Ie.set(n,r),n};br.callCount=t=>{if(!Ie.has(t))throw new Error(`The given function \`${t.name}\` is not wrapped by the \`onetime\` package`);return Ie.get(t)};const an=()=>{const t=$r-Pr+1;return Array.from({length:t},cn)},cn=(t,e)=>({name:`SIGRT${e+1}`,number:Pr+e,action:"terminate",description:"Application-specific signal (realtime)",standard:"posix"}),Pr=34,$r=64,ln=[{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"}],Cr=()=>{const t=an();return[...ln,...t].map(mn)},mn=({name:t,number:e,description:s,action:r,forced:o=!1,standard:n})=>{const{signals:{[t]:i}}=Wt,l=i!==void 0;return{name:t,number:l?i:e,description:s,supported:l,action:r,forced:o,standard:n}},un=()=>{const t=Cr();return Object.fromEntries(t.map(dn))},dn=({name:t,number:e,description:s,supported:r,action:o,forced:n,standard:i})=>[t,{name:t,number:e,description:s,supported:r,action:o,forced:n,standard:i}],pn=un(),fn=()=>{const t=Cr(),e=$r+1,s=Array.from({length:e},(r,o)=>hn(o,t));return Object.assign({},...s)},hn=(t,e)=>{const s=gn(t,e);if(s===void 0)return{};const{name:r,description:o,supported:n,action:i,forced:l,standard:c}=s;return{[t]:{name:r,number:t,description:o,supported:n,action:i,forced:l,standard:c}}},gn=(t,e)=>{const s=e.find(({name:r})=>Wt.signals[r]===t);return s!==void 0?s:e.find(r=>r.number===t)};fn();const yn=({timedOut:t,timeout:e,errorCode:s,signal:r,signalDescription:o,exitCode:n,isCanceled:i})=>t?`timed out after ${e} milliseconds`:i?"was canceled":s!==void 0?`failed with ${s}`:r!==void 0?`was killed with ${r} (${o})`:n!==void 0?`failed with exit code ${n}`:"failed",Er=({stdout:t,stderr:e,all:s,error:r,signal:o,exitCode:n,command:i,escapedCommand:l,timedOut:c,isCanceled:m,killed:p,parsed:{options:{timeout:a,cwd:d=q.cwd()}}})=>{n=n===null?void 0:n,o=o===null?void 0:o;const f=o===void 0?void 0:pn[o].description,h=r&&r.code,y=`Command ${yn({timedOut:c,timeout:a,errorCode:h,signal:o,signalDescription:f,exitCode:n,isCanceled:m})}: ${i}`,b=Object.prototype.toString.call(r)==="[object Error]",C=b?`${y}
${r.message}`:y,F=[C,e,t].filter(Boolean).join(`
`);return b?(r.originalMessage=r.message,r.message=F):r=new Error(F),r.shortMessage=C,r.command=i,r.escapedCommand=l,r.exitCode=n,r.signal=o,r.signalDescription=f,r.stdout=t,r.stderr=e,r.cwd=d,s!==void 0&&(r.all=s),"bufferedData"in r&&delete r.bufferedData,r.failed=!0,r.timedOut=!!c,r.isCanceled=m,r.killed=p&&!c,r},ke=["stdin","stdout","stderr"],wn=t=>ke.some(e=>t[e]!==void 0),vn=t=>{if(!t)return;const{stdio:e}=t;if(e===void 0)return ke.map(r=>t[r]);if(wn(t))throw new Error(`It's not possible to provide \`stdio\` in combination with one of ${ke.map(r=>`\`${r}\``).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 s=Math.max(e.length,ke.length);return Array.from({length:s},(r,o)=>e[o])};var ie={exports:{}},Oe={exports:{}};Oe.exports;var xr;function bn(){return xr||(xr=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")}(Oe)),Oe.exports}var S=k.process;const Z=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(!Z(S))ie.exports=function(){return function(){}};else{var Pn=Yt,ue=bn(),$n=/^win/i.test(S.platform),Le=Vt;typeof Le!="function"&&(Le=Le.EventEmitter);var L;S.__signal_exit_emitter__?L=S.__signal_exit_emitter__:(L=S.__signal_exit_emitter__=new Le,L.count=0,L.emitted={}),L.infinite||(L.setMaxListeners(1/0),L.infinite=!0),ie.exports=function(t,e){if(!Z(k.process))return function(){};Pn.equal(typeof t,"function","a callback must be provided for exit handler"),de===!1&&Ar();var s="exit";e&&e.alwaysLast&&(s="afterexit");var r=function(){L.removeListener(s,t),L.listeners("exit").length===0&&L.listeners("afterexit").length===0&&ut()};return L.on(s,t),r};var ut=function(){!de||!Z(k.process)||(de=!1,ue.forEach(function(e){try{S.removeListener(e,dt[e])}catch{}}),S.emit=pt,S.reallyExit=Mr,L.count-=1)};ie.exports.unload=ut;var ae=function(e,s,r){L.emitted[e]||(L.emitted[e]=!0,L.emit(e,s,r))},dt={};ue.forEach(function(t){dt[t]=function(){if(Z(k.process)){var s=S.listeners(t);s.length===L.count&&(ut(),ae("exit",null,t),ae("afterexit",null,t),$n&&t==="SIGHUP"&&(t="SIGINT"),S.kill(S.pid,t))}}}),ie.exports.signals=function(){return ue};var de=!1,Ar=function(){de||!Z(k.process)||(de=!0,L.count+=1,ue=ue.filter(function(e){try{return S.on(e,dt[e]),!0}catch{return!1}}),S.emit=En,S.reallyExit=Cn)};ie.exports.load=Ar;var Mr=S.reallyExit,Cn=function(e){Z(k.process)&&(S.exitCode=e||0,ae("exit",S.exitCode,null),ae("afterexit",S.exitCode,null),Mr.call(S,S.exitCode))},pt=S.emit,En=function(e,s){if(e==="exit"&&Z(k.process)){s!==void 0&&(S.exitCode=s);var r=pt.apply(this,arguments);return ae("exit",S.exitCode,null),ae("afterexit",S.exitCode,null),r}else return pt.apply(this,arguments)}}var xn=ie.exports,An=se(xn);const Mn=1e3*5,Sn=(t,e="SIGTERM",s={})=>{const r=t(e);return Rn(t,e,s,r),r},Rn=(t,e,s,r)=>{if(!In(e,s,r))return;const o=On(s),n=setTimeout(()=>{t("SIGKILL")},o);n.unref&&n.unref()},In=(t,{forceKillAfterTimeout:e},s)=>kn(t)&&e!==!1&&s,kn=t=>t===_s.constants.signals.SIGTERM||typeof t=="string"&&t.toUpperCase()==="SIGTERM",On=({forceKillAfterTimeout:t=!0})=>{if(t===!0)return Mn;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},Ln=(t,e)=>{t.kill()&&(e.isCanceled=!0)},Tn=(t,e,s)=>{t.kill(e),s(Object.assign(new Error("Timed out"),{timedOut:!0,signal:e}))},Nn=(t,{timeout:e,killSignal:s="SIGTERM"},r)=>{if(e===0||e===void 0)return r;let o;const n=new Promise((l,c)=>{o=setTimeout(()=>{Tn(t,s,c)},e)}),i=r.finally(()=>{clearTimeout(o)});return Promise.race([n,i])},Fn=({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})`)},_n=async(t,{cleanup:e,detached:s},r)=>{if(!e||s)return r;const o=An(()=>{t.kill()});return r.finally(()=>{o()})};function Sr(t){return t!==null&&typeof t=="object"&&typeof t.pipe=="function"}function Rr(t){return Sr(t)&&t.writable!==!1&&typeof t._write=="function"&&typeof t._writableState=="object"}const Dn=t=>t instanceof Ns&&typeof t.then=="function",ft=(t,e,s)=>{if(typeof s=="string")return t[e].pipe(Ds(s)),t;if(Rr(s))return t[e].pipe(s),t;if(!Dn(s))throw new TypeError("The second argument must be a string, a stream or an Execa child process.");if(!Rr(s.stdin))throw new TypeError("The target child process's stdin must be available.");return t[e].pipe(s.stdin),s},Gn=t=>{t.stdout!==null&&(t.pipeStdout=ft.bind(void 0,t,"stdout")),t.stderr!==null&&(t.pipeStderr=ft.bind(void 0,t,"stderr")),t.all!==void 0&&(t.pipeAll=ft.bind(void 0,t,"all"))};var pe={exports:{}};const{PassThrough:jn}=Xe;var Bn=t=>{t={...t};const{array:e}=t;let{encoding:s}=t;const r=s==="buffer";let o=!1;e?o=!(s||r):s=s||"utf8",r&&(s=null);const n=new jn({objectMode:o});s&&n.setEncoding(s);let i=0;const l=[];return n.on("data",c=>{l.push(c),o?i=l.length:i+=c.length}),n.getBufferedValue=()=>e?l:r?Buffer.concat(l,i):l.join(""),n.getBufferedLength=()=>i,n};const{constants:Hn}=js,Un=Xe,{promisify:qn}=Jt,zn=Bn,Kn=qn(Un.pipeline);class Ir extends Error{constructor(){super("maxBuffer exceeded"),this.name="MaxBufferError"}}async function ht(t,e){if(!t)throw new Error("Expected a stream");e={maxBuffer:1/0,...e};const{maxBuffer:s}=e,r=zn(e);return await new Promise((o,n)=>{const i=l=>{l&&r.getBufferedLength()<=Hn.MAX_LENGTH&&(l.bufferedData=r.getBufferedValue()),n(l)};(async()=>{try{await Kn(t,r),o()}catch(l){i(l)}})(),r.on("data",()=>{r.getBufferedLength()>s&&i(new Ir)})}),r.getBufferedValue()}pe.exports=ht,pe.exports.buffer=(t,e)=>ht(t,{...e,encoding:"buffer"}),pe.exports.array=(t,e)=>ht(t,{...e,array:!0}),pe.exports.MaxBufferError=Ir;var Wn=pe.exports,kr=se(Wn);const{PassThrough:Yn}=Xe;var Vn=function(){var t=[],e=new Yn({objectMode:!0});return e.setMaxListeners(0),e.add=s,e.isEmpty=r,e.on("unpipe",o),Array.prototype.slice.call(arguments).forEach(s),e;function s(n){return Array.isArray(n)?(n.forEach(s),this):(t.push(n),n.once("end",o.bind(null,n)),n.once("error",e.emit.bind(e,"error")),n.pipe(e,{end:!1}),this)}function r(){return t.length==0}function o(n){t=t.filter(function(i){return i!==n}),!t.length&&e.readable&&e.end()}},Jn=se(Vn);const Xn=t=>{if(t!==void 0)throw new TypeError("The `input` and `inputFile` options cannot be both set.")},Qn=({input:t,inputFile:e})=>typeof e!="string"?t:(Xn(t),Gs(e)),Zn=(t,e)=>{const s=Qn(e);s!==void 0&&(Sr(s)?s.pipe(t.stdin):t.stdin.end(s))},ei=(t,{all:e})=>{if(!e||!t.stdout&&!t.stderr)return;const s=Jn();return t.stdout&&s.add(t.stdout),t.stderr&&s.add(t.stderr),s},gt=async(t,e)=>{if(!(!t||e===void 0)){t.destroy();try{return await e}catch(s){return s.bufferedData}}},yt=(t,{encoding:e,buffer:s,maxBuffer:r})=>{if(!(!t||!s))return e?kr(t,{encoding:e,maxBuffer:r}):kr.buffer(t,{maxBuffer:r})},ti=async({stdout:t,stderr:e,all:s},{encoding:r,buffer:o,maxBuffer:n},i)=>{const l=yt(t,{encoding:r,buffer:o,maxBuffer:n}),c=yt(e,{encoding:r,buffer:o,maxBuffer:n}),m=yt(s,{encoding:r,buffer:o,maxBuffer:n*2});try{return await Promise.all([i,l,c,m])}catch(p){return Promise.all([{error:p,signal:p.signal,timedOut:p.timedOut},gt(t,l),gt(e,c),gt(s,m)])}},ri=(async()=>{})().constructor.prototype,si=["then","catch","finally"].map(t=>[t,Reflect.getOwnPropertyDescriptor(ri,t)]),Or=(t,e)=>{for(const[s,r]of si){const o=typeof e=="function"?(...n)=>Reflect.apply(r.value,e(),n):r.value.bind(e);Reflect.defineProperty(t,s,{...r,value:o})}},oi=t=>new Promise((e,s)=>{t.on("exit",(r,o)=>{e({exitCode:r,signal:o})}),t.on("error",r=>{s(r)}),t.stdin&&t.stdin.on("error",r=>{s(r)})}),Lr=(t,e=[])=>Array.isArray(e)?[t,...e]:[t],ni=/^[\w.-]+$/,ii=/"/g,ai=t=>typeof t!="string"||ni.test(t)?t:`"${t.replace(ii,'\\"')}"`,ci=(t,e)=>Lr(t,e).join(" "),li=(t,e)=>Lr(t,e).map(s=>ai(s)).join(" "),mi=Bs("execa").enabled,Te=(t,e)=>String(t).padStart(e,"0"),ui=()=>{const t=new Date;return`${Te(t.getHours(),2)}:${Te(t.getMinutes(),2)}:${Te(t.getSeconds(),2)}.${Te(t.getMilliseconds(),3)}`},di=(t,{verbose:e})=>{e&&q.stderr.write(`[${ui()}] ${t}
`)},pi=1e3*1e3*100,fi=({env:t,extendEnv:e,preferLocal:s,localDir:r,execPath:o})=>{const n=e?{...q.env,...t}:t;return s?Xo({env:n,cwd:r,execPath:o}):n},hi=(t,e,s={})=>{const r=Ko._parse(t,e,s);return t=r.command,e=r.args,s=r.options,s={maxBuffer:pi,buffer:!0,stripFinalNewline:!0,extendEnv:!0,preferLocal:!1,localDir:s.cwd||q.cwd(),execPath:q.execPath,encoding:"utf8",reject:!0,cleanup:!0,all:!1,windowsHide:!0,verbose:mi,...s},s.env=fi(s),s.stdio=vn(s),q.platform==="win32"&&re.basename(t,".exe")==="cmd"&&e.unshift("/q"),{file:t,args:e,options:s,parsed:r}},wt=(t,e,s)=>typeof e!="string"&&!Ts.isBuffer(e)?s===void 0?void 0:"":t.stripFinalNewline?Wo(e):e;function ee(t,e,s){const r=hi(t,e,s),o=ci(t,e),n=li(t,e);di(n,r.options),Fn(r.options);let i;try{i=zt.spawn(r.file,r.args,r.options)}catch(f){const h=new zt.ChildProcess,g=Promise.reject(Er({error:f,stdout:"",stderr:"",all:"",command:o,escapedCommand:n,parsed:r,timedOut:!1,isCanceled:!1,killed:!1}));return Or(h,g),h}const l=oi(i),c=Nn(i,r.options,l),m=_n(i,r.options,c),p={isCanceled:!1};i.kill=Sn.bind(null,i.kill.bind(i)),i.cancel=Ln.bind(null,i,p);const d=br(async()=>{const[{error:f,exitCode:h,signal:g,timedOut:y},b,C,F]=await ti(i,r.options,m),K=wt(r.options,b),W=wt(r.options,C),me=wt(r.options,F);if(f||h!==0||g!==null){const Y=Er({error:f,exitCode:h,signal:g,stdout:K,stderr:W,all:me,command:o,escapedCommand:n,parsed:r,timedOut:y,isCanceled:p.isCanceled||(r.options.signal?r.options.signal.aborted:!1),killed:i.killed});if(!r.options.reject)return Y;throw Y}return{command:o,escapedCommand:n,exitCode:0,stdout:K,stderr:W,all:me,failed:!1,timedOut:!1,isCanceled:!1,killed:!1}});return Zn(i,r.options),i.all=ei(i,r.options),Gn(i),Or(i,d),i}class R{static create(e,s){return new e(s)}}const Ne=t=>t&&`${t[0].toUpperCase()}${t.slice(1)}`,Fe=(t,e)=>{const s=Math.ceil(t),r=Math.floor(e);return Math.floor(Math.random()*(r-s+1))+s},gi=(t,e)=>t.disabled&&!e.disabled?1:!t.disabled&&e.disabled?-1:0,_e=t=>t.reduce((e,s)=>Array.isArray(s)?e.concat(_e(s)):e.concat(s),[]),Tr=(t,e=5)=>t.replace(/[\n\r]/g,"").split(" ").slice(0,e).join(" "),yi=t=>{let e=0;for(let s=0;s<t.length;s++){const r=t.charCodeAt(s);e=(e<<5)-e+r,e=e&e}return Math.abs(e)},wi=t=>{const e=t%360,s=65+t%15,r=45+t%10;return`hsl(${e}, ${s}%, ${r}%)`},vi=t=>{const[e,s,r]=t.match(/\d+/g).map((a,d)=>d===0?Number(a):Number(a)/100),o=(1-Math.abs(2*r-1))*s,n=o*(1-Math.abs(e/60%2-1)),i=r-o/2;let l,c,m;e<60?[l,c,m]=[o,n,0]:e<120?[l,c,m]=[n,o,0]:e<180?[l,c,m]=[0,o,n]:e<240?[l,c,m]=[0,n,o]:e<300?[l,c,m]=[n,0,o]:[l,c,m]=[o,0,n];const p=a=>{const d=Math.round((a+i)*255).toString(16);return d.length===1?"0"+d:d};return`#${p(l)}${p(c)}${p(m)}`},bi=t=>{const e=yi(t),s=wi(e);return{primary:vi(s),secondary:"#FFFFFF"}};class j{constructor(e){this.handleError$=s=>{let r="An error occurred";return s.message&&(r=s.message),O({name:`${this.errorPrefix} ${r}`,value:r,isError:!0,disabled:!0})},this.serviceName="AI",this.errorPrefix="ERROR",this.colors={primary:""}}parseMessage(e,s,r){try{let o;const n=m=>m.replace(/[\u0000-\u001F\u007F-\u009F]/g,"").replace(/\\(?!["\\/bfnrtu])/g,"\\\\"),i=/\[\s*\{[\s\S]*?\}\s*\]/,l=e.match(i);if(l)try{const m=JSON.parse(n(l[0]));o=Array.isArray(m)?m:[m]}catch{return[]}else{const m=/\{[\s\S]*?\}/,p=e.match(m);if(!p)return[];try{o=[JSON.parse(n(p[0]))]}catch{return[]}}return!o.length||!o.every(m=>typeof m.subject=="string")?[]:o.map(m=>this.extractMessageAsType(m,s)).map(m=>({title:`${m.subject}`,value:`${m.subject}${m.body?`
${m.body}`:""}${m.footer?`
${m.footer}`:""}`})).slice(0,r)}catch{return[]}}extractMessageAsType(e,s){switch(s){case"conventional":const r=/(\w+)(?:\(.*?\))?:\s*(.*)/,o=e.subject.match(r),n=o?o[0]:e.subject;return{...e,subject:this.normalizeCommitMessage(n)};case"gitmoji":const i=/:\w*:\s*(.*)/,l=e.subject.match(i);return{...e,subject:l?l[0].toLowerCase():e.subject};default:return e}}normalizeCommitMessage(e){const s=/^(\w+)(\(.*?\))?:\s(.*)$/,r=e.match(s);if(r){const[,o,n,i]=r,l=o.toLowerCase(),c=i.charAt(0).toLowerCase()+i.slice(1);e=`${l}${n||""}: ${c}`}return e}sanitizeResponse(e){if(typeof e=="string")try{return[{title:`${Tr(e)}...`,value:e}]}catch{return[]}return e.map(s=>{try{return{title:`${Tr(s)}...`,value:s}}catch{return{title:"",value:""}}})}}var Nr="2.2.14",Pi="A Reactive CLI that generates git commit messages with various AI";class v extends Error{}const vt=" ",te=t=>{t instanceof Error&&(t instanceof v||(t.stack&&console.error(w.dim(t.stack.split(`
`).slice(1).join(`
`))),console.error(`
${vt}${w.dim(`aicommit2 v${Nr}`)}`),console.error(`
${vt}Please open a Bug report with the information above:`),console.error(`${vt}https://github.com/tak-bro/aicommit2/issues/new/choose`)))},Fr=T.join(Ze.homedir(),".aicommit2_log"),$i=new Date,B=(t,e,s,r,o)=>{const n=`[${t}]`,i=Ci($i,e,o),l=`${Fr}/${i}`,c=`- System Prompt
${s}`,m=`- Response
${r}`,p=`[Git Diff]
${e}`;if(_.existsSync(l)){const a=_.readFileSync(l,"utf-8");_r(l,`${n}
${m}
${c}
${a}`);return}_r(l,`${n}
${m}
${c}
${p}`)},Ci=(t,e,s)=>{const{year:r,month:o,day:n,hours:i,minutes:l,seconds:c}=Ei(t),p=qs(0).update(e).digest("hex");return s==="review"?`aic2_review_${r}-${o}-${n}_${i}-${l}-${c}_${p}.log`:`aic2_${r}-${o}-${n}_${i}-${l}-${c}_${p}.log`},_r=(t,e="")=>{_.mkdirSync(T.dirname(t),{recursive:!0}),_.writeFileSync(t,e,"utf-8")},Ei=t=>{const e=t.getFullYear().toString(),s=(t.getMonth()+1).toString().padStart(2,"0"),r=t.getDate().toString().padStart(2,"0"),o=t.getHours().toString().padStart(2,"0"),n=t.getMinutes().toString().padStart(2,"0"),i=t.getSeconds().toString().padStart(2,"0");return{year:e,month:s,day:r,hours:o,minutes:n,seconds:i}},G={locale:"en",maxLength:50,type:"conventional",generate:1,systemPrompt:"",systemPromptPath:"",codeReviewPromptPath:""},xi={"":"<commit message>",conventional:`<type>(<optional scope>): <description>
[optional body]
[optional footer(s)]`,gitmoji:`:<emoji>:(<optional scope>): <description>
[optional body]
[optional footer(s)]`},Ai={"":"",gitmoji:`
${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(`
`)}`,conventional:`
${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(`
`)}`},Dr=(t,e)=>t.replace(/{(\w+)}/g,(s,r)=>e[r]?.toString()||G[r]?.toString()),Gr=t=>{const{type:e,maxLength:s,generate:r,locale:o}=t;return[`You are a helpful assistant specializing in writing clear and informative Git commit messages using the ${e} style`,`Based on the given code changes or context, generate exactly ${r} ${e} Git commit message${r!==1?"s":""} based on the following guidelines.`,`1. Message Language: ${o}`,`2. Format: follow the ${e} Commits format:`,`${xi[e]}`,`3. Types: use one of the following types:${Ai[e]}`,"4. Guidelines for writing commit messages:"," - Be specific about what changes were made",' - Use imperative mood ("add feature" not "added feature")',` - Keep subject line under ${s} characters`," - Do not end the subject line with a period"," - Use the body to explain what and why vs. how","5. Focus on:"," - What problem this commit solves"," - Why this change was necessary"," - Any important technical details","6. Exclude anything unnecessary such as translation or implementation details."].filter(Boolean).join(`
`)},De=(t,e)=>{const s=r=>r==="conventional"?`${Array(e).fill(null).map((o,n)=>`
{
"subject": "fix(auth): fix bug in user authentication process",
"body": "- Update login function to handle edge cases\\n- Add additional error logging for debugging",
"footer": ""
}`).join(",")}`:`${Array(e).fill(null).map((o,n)=>`
{
"subject": ":sparkles: Add real-time chat feature",
"body": "- Implement WebSocket connection\\n- Add message encryption\\n- Include typing indicators",
"footer": ""
}`).join(",")}`;return[`
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:
[${s(t)}
]`,`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(`
`)},H=t=>{const{systemPrompt:e,systemPromptPath:s,type:r,generate:o}=t;if(e)return`${e}
${De(r,o)}`;if(!s)return`${Gr(t)}
${De(r,o)}`;try{const n=_.readFileSync(T.resolve(s),"utf-8");return`${Dr(n,t)}
${De(r,o)}`}catch{return`${Gr(t)}
${De(r,o)}`}},U=t=>{const{codeReviewPromptPath:e,locale:s}=t,r=`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:
1. Language: ${s}
2. Code quality and best practices
3. Potential bugs or errors
4. Performance improvements
5. Readability and maintainability
Please structure your response with appropriate Markdown headings, code blocks, and bullet points.`;if(!e)return r;try{const o=_.readFileSync(T.resolve(e),"utf-8");return`${Dr(o,t)}`}catch{return r}},jr=async t=>{if(t.systemPromptPath)try{_.readFileSync(T.resolve(t.systemPromptPath),"utf-8")}catch{throw new v(`Error reading system prompt file: ${t.systemPromptPath}`)}if(t.codeReview&&t.codeReviewPromptPath)try{_.readFileSync(T.resolve(t.codeReviewPromptPath),"utf-8")}catch{throw new v(`Error reading code review prompt file: ${t.codeReviewPromptPath}`)}},Mi=10*60*1e3;class Br extends j{constructor(e){super(e),this.params=e,this.handleError$=s=>{const r=s.error?.error?.message?.replace(/(\r\n|\n|\r)/gm,"")||"An error occurred";return O({name:`${this.errorPrefix} ${r}`,value:r,isError:!0,disabled:!0})},this.colors={primary:"#AE5630",secondary:"#fff"},this.serviceName=w.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[Anthropic]"),this.errorPrefix=w.red.bold("[Anthropic]"),this.anthropic=new Us({apiKey:this.params.config.key,...this.params.config.timeout>Mi&&{timeout:this.params.config.timeout}})}generateCommitMessage$(){return M(this.generateMessage("commit")).pipe(A(e=>$(e)),E(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})),x(this.handleError$))}generateCodeReview$(){return M(this.generateMessage("review")).pipe(A(e=>$(e)),E(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),x(this.handleError$))}async generateMessage(e){try{const s=this.params.stagedDiff.diff,{systemPrompt:r,systemPromptPath:o,codeReviewPromptPath:n,logging:i,temperature:l,locale:c,generate:m,type:p,maxLength:a,maxTokens:d,topP:f,model:h}=this.params.config,g={...G,locale:c,maxLength:a,type:p,generate:m,systemPrompt:r,systemPromptPath:o,codeReviewPromptPath:n},y=e==="review"?U(g):H(g),b={max_tokens:d,temperature:l,system:y,messages:[{role:"user",content:`Here is the diff: ${s}`}],top_p:f,model:h},F=(await this.anthropic.messages.create(b)).content.map(({text:K})=>K).join("");return i&&B("Anthropic",s,y,F,e),e==="review"?this.sanitizeResponse(F):this.parseMessage(F,p,m)}catch(s){const r=s;throw r.code==="ENOTFOUND"?new v(`Error connecting to ${r.hostname} (${r.syscall})`):r}}}class fe{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=zs.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 Hr extends j{constructor(e){super(e),this.params=e,this.host="https://codestral.mistral.ai",this.apiKey="",this.handleError$=s=>{const r=s.message?.replace(/(\r\n|\n|\r)/gm,"")||"An error occurred";return O({name:`${this.errorPrefix} ${r}`,value:r,isError:!0,disabled:!0})},this.colors={primary:"#e28c58",secondary:"#fff"},this.serviceName=w.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[Codestral]"),this.errorPrefix=w.red.bold("[Codestral]"),this.apiKey=this.params.config.key}generateCommitMessage$(){return M(this.generateMessage("commit")).pipe(A(e=>$(e)),E(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})),x(this.handleError$))}generateCodeReview$(){return M(this.generateMessage("review")).pipe(A(e=>$(e)),E(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),x(this.handleError$))}async generateMessage(e){try{const s=this.params.stagedDiff.diff,{systemPrompt:r,systemPromptPath:o,codeReviewPromptPath:n,logging:i,locale:l,generate:c,type:m,maxLength:p}=this.params.config,a={...G,locale:l,maxLength:p,type:m,generate:c,systemPrompt:r,systemPromptPath:o,codeReviewPromptPath:n},d=e==="review"?U(a):H(a);this.checkAvailableModels();const f=await this.createChatCompletions(d,e);return i&&B("Codestral",s,d,f,e),e==="review"?this.sanitizeResponse(f):this.parseMessage(f,m,c)}catch(s){const r=s;throw r.code==="ENOTFOUND"?new v(`Error connecting to ${r.hostname} (${r.syscall})`):r}}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,s){const r=new fe({method:"POST",baseURL:`${this.host}/v1/chat/completions`,timeout:this.params.config.timeout}).setHeaders({Authorization:`Bearer ${this.apiKey}`,"content-type":"application/json"}).setBody({model:this.params.config.model,messages:[{role:"system",content:e},{role:"user",content:`Here is the diff: ${this.params.stagedDiff.diff}`}],temperature:this.params.config.temperature,top_p:this.params.config.topP,max_tokens:this.params.config.maxTokens,stream:!1,safe_prompt:!1,random_seed:Fe(10,1e3)});s==="commit"&&r.addBody({response_format:{type:"json_object"}});const n=(await r.execute()).data;if(!n.choices||n.choices.length===0||!n.choices[0].message?.content)throw new Error("No Content on response. Please open a Bug report");return n.choices[0].message.content}}const Si=2*60*1e3;class Ur extends j{constructor(e){super(e),this.params=e,this.handleError$=s=>{const r=/"message":\s*"([^"]*)"/,o=s.message.match(r);let n=s?.body?.message;o&&o[1]&&(n=o[1]);const i=`${s.statusCode} ${n}`;return O({name:`${this.errorPrefix} ${i}`,value:n,isError:!0,disabled:!0})},this.colors={primary:"#D18EE2",secondary:"#fff"},this.serviceName=w.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[Cohere]"),this.errorPrefix=w.red.bold("[Cohere]"),this.cohere=new Ks({token:this.params.config.key})}generateCommitMessage$(){return M(this.generateMessage("commit")).pipe(A(e=>$(e)),E(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})),x(this.handleError$))}generateCodeReview$(){return M(this.generateMessage("review")).pipe(A(e=>$(e)),E(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),x(this.handleError$))}async generateMessage(e){try{const s=this.params.stagedDiff.diff,{systemPrompt:r,systemPromptPath:o,codeReviewPromptPath:n,logging:i,temperature:l,locale:c,generate:m,type:p,maxLength:a,maxTokens:d}=this.params.config,f={...G,locale:c,maxLength:a,type:p,generate:m,systemPrompt:r,systemPromptPath:o,codeReviewPromptPath:n},h=e==="review"?U(f):H(f),g=await this.cohere.chat({chatHistory:h?[{role:"SYSTEM",message:h}]:[],message:`Here is the diff: ${s}`,connectors:[{id:"web-search"}],maxTokens:d,temperature:l,model:this.params.config.model,seed:Fe(10,1e3),p:this.params.config.topP},{...this.params.config.timeout>Si&&{timeoutInSeconds:Math.floor(this.params.config.timeout/1e3)}});return i&&B("Cohere",s,h,g.text,e),e==="review"?this.sanitizeResponse(g.text):this.parseMessage(g.text,p,m)}catch(s){const r=s;throw r instanceof Ws?new v("Request timed out error!"):r}}}class qr extends j{constructor(e){super(e),this.params=e,this.host="https://api.deepseek.com",this.handleError$=s=>{const r=s.message?.replace(/(\r\n|\n|\r)/gm,"")||"An error occurred";return O({name:`${this.errorPrefix} ${r}`,value:r,isError:!0,disabled:!0})},this.colors={primary:"#53a3f9",secondary:"#fff"},this.serviceName=w.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[DeepSeek]"),this.errorPrefix=w.red.bold("[DeepSeek]"),this.deepSeek=new xe({baseURL:this.host,apiKey:this.params.config.key})}generateCommitMessage$(){return M(this.generateMessage("commit")).pipe(A(e=>$(e)),E(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})),x(this.handleError$))}generateCodeReview$(){return M(this.generateMessage("review")).pipe(A(e=>$(e)),E(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),x(this.handleError$))}async generateMessage(e){try{const s=this.params.stagedDiff.diff,{systemPrompt:r,systemPromptPath:o,codeReviewPromptPath:n,logging:i,locale:l,generate:c,type:m,maxLength:p}=this.params.config,a={...G,locale:l,maxLength:p,type:m,generate:c,systemPrompt:r,systemPromptPath:o,codeReviewPromptPath:n},d=e==="review"?U(a):H(a);this.checkAvailableModels();const f=await this.createChatCompletions(d);return i&&B("DeepSeek",s,d,f,e),e==="review"?this.sanitizeResponse(f):this.parseMessage(f,m,c)}catch(s){const r=s;throw r.code==="ENOTFOUND"?new v(`Error connecting to ${r.hostname} (${r.syscall})`):r}}checkAvailableModels(){if(["deepseek-reasoner","deepseek-chat"].includes(this.params.config.model))return!0;throw new Error("Invalid model type of DeepSeek")}async createChatCompletions(e){return(await this.deepSeek.chat.completions.create({messages:[{role:"system",content:e},{role:"user",content:`Here is the diff: ${this.params.stagedDiff.diff}`}],model:this.params.config.model,max_tokens:this.params.config.maxTokens,top_p:this.params.config.topP,temperature:this.params.config.temperature},{timeout:this.params.config.timeout})).choices[0].message.content||""}}class zr extends j{constructor(e){super(e),this.params=e,this.handleError$=s=>{const r=s.message||s.toString(),o=/(\[.*?\]\s*[^[]*)/g,n=[...r.matchAll(o)],i=[];n.forEach(c=>i.push(c[1]));const l=i[1]||"An error occurred";return O({name:`${this.errorPrefix} ${l}`,value:l,isError:!0,disabled:!0})},this.colors={primary:"#0077FF",secondary:"#fff"},this.serviceName=w.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[Gemini]"),this.errorPrefix=w.red.bold("[Gemini]"),this.genAI=new Ys(this.params.config.key)}generateCommitMessage$(){return M(this.generateMessage("commit")).pipe(A(e=>$(e)),E(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})),x(this.handleError$))}generateCodeReview$(){return M(this.generateMessage("review")).pipe(A(e=>$(e)),E(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),x(this.handleError$))}async generateMessage(e){try{const s=this.params.stagedDiff.diff,{systemPrompt:r,systemPromptPath:o,logging:n,locale:i,codeReviewPromptPath:l,generate:c,type:m,maxLength:p}=this.params.config,a=this.params.config.maxTokens,d={...G,locale:i,maxLength:p,type:m,generate:c,systemPrompt:r,systemPromptPath:o,codeReviewPromptPath:l},f=e==="review"?U(d):H(d),h={maxOutputTokens:a,temperature:this.params.config.temperature,topP:this.params.config.topP},C=(await this.genAI.getGenerativeModel({model:this.params.config.model,systemInstruction:f,generationConfig:h,safetySettings:[{category:Ae.HARM_CATEGORY_HATE_SPEECH,threshold:Me.BLOCK_LOW_AND_ABOVE},{category:Ae.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:Me.BLOCK_LOW_AND_ABOVE},{category:Ae.HARM_CATEGORY_HARASSMENT,threshold:Me.BLOCK_LOW_AND_ABOVE},{category:Ae.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:Me.BLOCK_LOW_AND_ABOVE}]}).generateContent(`Here is the diff: ${s}`)).response.text();return n&&B("Gemini",s,f,C,e),e==="review"?this.sanitizeResponse(C):this.parseMessage(C,m,c)}catch(s){const r=s;throw r.code==="ENOTFOUND"?new v(`Error connecting to ${r.hostname} (${r.syscall})`):r}}}class Kr extends j{constructor(e){super(e),this.params=e,this.handleError$=s=>{let r="N/A",o="An error occurred";s instanceof rr.APIError&&(r=`${s.status}`,o=s.name);const n=`${r} ${o}`;return O({name:`${this.errorPrefix} ${n}`,value:o,isError:!0,disabled:!0})},this.colors={primary:"#f55036",secondary:"#fff"},this.serviceName=w.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[Groq]"),this.errorPrefix=w.red.bold("[Groq]"),this.groq=new rr({apiKey:this.params.config.key})}generateCommitMessage$(){return M(this.generateMessage("commit")).pipe(A(e=>$(e)),E(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})),x(this.handleError$))}generateCodeReview$(){return M(this.generateMessage("review")).pipe(A(e=>$(e)),E(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),x(this.handleError$))}async generateMessage(e){try{const s=this.params.stagedDiff.diff,{systemPrompt:r,systemPromptPath:o,codeReviewPromptPath:n,logging:i,locale:l,temperature:c,generate:m,type:p,maxLength:a}=this.params.config,d=this.params.config.maxTokens,f={...G,locale:l,maxLength:a,type:p,generate:m,systemPrompt:r,systemPromptPath:o,codeReviewPromptPath:n},h=e==="review"?U(f):H(f),y=(await this.groq.chat.completions.create({messages:[{role:"system",content:h},{role:"user",content:`Here is the diff: ${s}`}],model:this.params.config.model,max_tokens:d,top_p:this.params.config.topP,temperature:c},{timeout:this.params.config.timeout})).choices[0].message.content||"";return i&&B("Groq",s,h,y,e),e==="review"?this.sanitizeResponse(y):this.parseMessage(y,p,m)}catch(s){throw s}}}class Wr extends j{constructor(e){super(e),this.params=e,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:"https://huggingface.co","Referrer-Policy":"strict-origin-when-cross-origin"},this.models=[],this.currentModelId=null,this.currentConversation=void 0,this.currentConversionID=void 0,this.cookie="",this.colors={primary:"#FED21F",secondary:"#000"},this.serviceName=w.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[HuggingFace]"),this.errorPrefix=w.red.bold("[HuggingFace]"),this.cookie=this.params.config.cookie}generateCommitMessage$(){return M(this.generateMessage("commit")).pipe(A(e=>$(e)),E(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})),x(this.handleError$))}generateCodeReview$(){return M(this.generateMessage("review")).pipe(A(e=>$(e)),E(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),x(this.handleError$))}async generateMessage(e){try{await this.intialize();const s=this.params.stagedDiff.diff,{systemPrompt:r,systemPromptPath:o,codeReviewPromptPath:n,logging:i,locale:l,generate:c,type:m,maxLength:p}=this.params.config,a={...G,locale:l,maxLength:p,type:m,generate:c,systemPrompt:r,systemPromptPath:o,codeReviewPromptPath:n},d=e==="review"?U(a):H(a),f=await this.getNewChat(d),g=await(await this.sendMessage(`Here is the diff: ${s}`,f.id)).completeResponsePromise();return awa