aicommit2 2.2.14 → 2.2.16

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.
Files changed (3) hide show
  1. package/README.md +205 -565
  2. package/dist/cli.mjs +85 -85
  3. package/package.json +1 -1
package/dist/cli.mjs CHANGED
@@ -1,32 +1,32 @@
1
1
  #!/usr/bin/env node
2
- 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"?`
2
+ import{command as Y,cli as Ls}from"cleye";import{createRequire as Ts}from"module";import{Buffer as Ns}from"node:buffer";import re from"node:path";import zt,{ChildProcess as Fs}from"node:child_process";import q from"node:process";import _s from"child_process";import O from"path";import _ from"fs";import{fileURLToPath as Kt}from"node:url";import Ds,{constants as Wt}from"node:os";import Vt from"assert";import Yt from"events";import{createWriteStream as Gs,createReadStream as js}from"node:fs";import Bs from"buffer";import et from"stream";import Jt from"util";import{debuglog as Hs}from"node:util";import xe from"inquirer";import tt from"ora";import w from"chalk";import{of as L,concatMap as A,from as P,map as E,catchError as x,mergeMap as Ae,BehaviorSubject as Xt,ReplaySubject as Us,lastValueFrom as Qt,filter as Zt,toArray as er,Subject as tr}from"rxjs";import qs from"@anthropic-ai/sdk";import{fromPromise as M}from"rxjs/internal/observable/innerFrom";import Me from"os";import{xxh64 as zs}from"@pacote/xxhash";import Ks from"axios";import{CohereClient as Ws,CohereTimeoutError as Vs}from"cohere-ai";import Se from"openai";import{GoogleGenerativeAI as Ys,HarmCategory as Re,HarmBlockThreshold as Ie}from"@google/generative-ai";import rr from"groq-sdk";import{Ollama as Js}from"ollama";import{fetch as Xs,Agent as Qs}from"undici";import I from"fs/promises";import Zs from"http";import eo from"https";import to from"net";import ro from"tls";import so,{fileURLToPath as oo,pathToFileURL as no}from"url";import sr from"tty";import ke from"readline";import io from"figlet";import ao from"inquirer-reactive-list-prompt";import{rm as co}from"node:fs/promises";import lo from"chokidar";import{takeUntil as mo}from"rxjs/operators";var uo=Ts(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:{}},rt,or;function fo(){if(or)return rt;or=1,rt=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 a=0;a<l.length;a++){var u=l[a].toLowerCase();if(u&&n.substr(-u.length).toLowerCase()===u)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(a,u){l(a,a?!1:s(u,n,i))})}function o(n,i){return s(t.statSync(n),n,i)}return rt}var st,nr;function po(){if(nr)return st;nr=1,st=e,e.sync=s;var t=_;function e(n,i,l){t.stat(n,function(a,u){l(a,a?!1:r(u,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,a=n.uid,u=n.gid,f=i.uid!==void 0?i.uid:process.getuid&&process.getuid(),c=i.gid!==void 0?i.gid:process.getgid&&process.getgid(),m=parseInt("100",8),p=parseInt("010",8),h=parseInt("001",8),g=m|p,y=l&h||l&p&&u===c||l&m&&a===f||l&g&&f===0;return y}return st}var Oe;process.platform==="win32"||k.TESTING_WINDOWS?Oe=fo():Oe=po();var ho=ot;ot.sync=go;function ot(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){ot(t,e||{},function(n,i){n?o(n):r(i)})})}Oe(t,e||{},function(r,o){r&&(r.code==="EACCES"||e&&e.ignoreErrors)&&(r=null,o=!1),s(r,o)})}function go(t,e){try{return Oe.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=O,yo=ne?";":":",ar=ho,cr=t=>Object.assign(new Error(`not found: ${t}`),{code:"ENOENT"}),lr=(t,e)=>{const s=e.colon||yo,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=u=>new Promise((f,c)=>{if(u===r.length)return e.all&&i.length?f(i):c(cr(t));const m=r[u],p=/^".*"$/.test(m)?m.slice(1,-1):m,h=ir.join(p,t),g=!p&&/^\.[\\\/]/.test(t)?t.slice(0,2)+h:h;f(a(g,u,0))}),a=(u,f,c)=>new Promise((m,p)=>{if(c===o.length)return m(l(f+1));const h=o[c];ar(u+h,{pathExt:n},(g,y)=>{if(!g&&y)if(e.all)i.push(u+h);else return m(u+h);return m(a(u,f,c+1))})});return s?l(0).then(u=>s(null,u),s):l(0)},wo=(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],a=/^".*"$/.test(l)?l.slice(1,-1):l,u=ir.join(a,t),f=!a&&/^\.[\\\/]/.test(t)?t.slice(0,2)+u:u;for(let c=0;c<r.length;c++){const m=f+r[c];try{if(ar.sync(m,{pathExt:o}))if(e.all)n.push(m);else return m}catch{}}}if(e.all&&n.length)return n;if(e.nothrow)return null;throw cr(t)};var vo=mr;mr.sync=wo;var nt={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"};nt.exports=ur,nt.exports.default=ur;var bo=nt.exports;const dr=O,$o=vo,Po=bo;function fr(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=$o.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 Co(t){return fr(t)||fr(t,!0)}var Eo=Co,it={};const at=/([()\][%!^"`<>&|;, *?])/g;function xo(t){return t=t.replace(at,"^$1"),t}function Ao(t,e){return t=`${t}`,t=t.replace(/(?=(\\+?)?)\1"/g,'$1$1\\"'),t=t.replace(/(?=(\\+?)?)\1$/,"$1$1"),t=`"${t}"`,t=t.replace(at,"^$1"),e&&(t=t.replace(at,"^$1")),t}it.command=xo,it.argument=Ao;var Mo=/^#!(.*)/;const So=Mo;var Ro=(t="")=>{const e=t.match(So);if(!e)return null;const[s,r]=e[0].replace(/#! ?/,"").split(" "),o=s.split("/").pop();return o==="env"?r:r?`${o} ${r}`:o};const ct=_,Io=Ro;function ko(t){const s=Buffer.alloc(150);let r;try{r=ct.openSync(t,"r"),ct.readSync(r,s,0,150,0),ct.closeSync(r)}catch{}return Io(s.toString())}var Oo=ko;const Lo=O,pr=Eo,hr=it,To=Oo,No=process.platform==="win32",Fo=/\.(?:com|exe)$/i,_o=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function Do(t){t.file=pr(t);const e=t.file&&To(t.file);return e?(t.args.unshift(t.file),t.command=e,pr(t)):t.file}function Go(t){if(!No)return t;const e=Do(t),s=!Fo.test(e);if(t.options.forceShell||s){const r=_o.test(e);t.command=Lo.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 jo(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:Go(r)}var Bo=jo;const lt=process.platform==="win32";function mt(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 Ho(t,e){if(!lt)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 lt&&t===1&&!e.file?mt(e.original,"spawn"):null}function Uo(t,e){return lt&&t===1&&!e.file?mt(e.original,"spawnSync"):null}var qo={hookChildProcess:Ho,verifyENOENT:gr,verifyENOENTSync:Uo,notFoundError:mt};const yr=_s,ut=Bo,dt=qo;function wr(t,e,s){const r=ut(t,e,s),o=yr.spawn(r.command,r.args,r.options);return dt.hookChildProcess(o,r),o}function zo(t,e,s){const r=ut(t,e,s),o=yr.spawnSync(r.command,r.args,r.options);return o.error=o.error||dt.verifyENOENTSync(o.status,r),o}oe.exports=wr,oe.exports.spawn=wr,oe.exports.sync=zo,oe.exports._parse=ut,oe.exports._enoent=dt;var Ko=oe.exports,Wo=se(Ko);function Vo(t){const e=typeof t=="string"?`
3
3
  `:`
4
- `.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}*/
5
- ${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}
4
+ `.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&&Jo(l,i),o&&Xo(l,r,i),[...l,e].join(re.delimiter)},Jo=(t,e)=>{let s;for(;s!==e;)t.push(re.join(e,"node_modules/.bin")),s=e,e=re.resolve(e,"..")},Xo=(t,e,s)=>{const r=e instanceof URL?Kt(e):e;t.push(re.resolve(s,r,".."))},Qo=({env:t=q.env,...e}={})=>{t={...t};const s=vr({env:t});return e.path=t[s],t[s]=Yo(e),t},Zo=(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);!en(o,n)&&r||Object.defineProperty(t,s,n)},en=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)},tn=(t,e)=>{const s=Object.getPrototypeOf(e);s!==Object.getPrototypeOf(t)&&Object.setPrototypeOf(t,s)},rn=(t,e)=>`/* Wrapped ${t}*/
5
+ ${e}`,sn=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),on=Object.getOwnPropertyDescriptor(Function.prototype.toString,"name"),nn=(t,e,s)=>{const r=s===""?"":`with ${s.trim()}() `,o=rn.bind(null,r,e.toString());Object.defineProperty(o,"name",on),Object.defineProperty(t,"toString",{...sn,value:o})};function an(t,e,{ignoreNonConfigurable:s=!1}={}){const{name:r}=t;for(const o of Reflect.ownKeys(e))Zo(t,e,o,s);return tn(t,e),nn(t,e,r),t}const Le=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(Le.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 an(n,t),Le.set(n,r),n};br.callCount=t=>{if(!Le.has(t))throw new Error(`The given function \`${t.name}\` is not wrapped by the \`onetime\` package`);return Le.get(t)};const cn=()=>{const t=Pr-$r+1;return Array.from({length:t},ln)},ln=(t,e)=>({name:`SIGRT${e+1}`,number:$r+e,action:"terminate",description:"Application-specific signal (realtime)",standard:"posix"}),$r=34,Pr=64,mn=[{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=cn();return[...mn,...t].map(un)},un=({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}},dn=()=>{const t=Cr();return Object.fromEntries(t.map(fn))},fn=({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=dn(),hn=()=>{const t=Cr(),e=Pr+1,s=Array.from({length:e},(r,o)=>gn(o,t));return Object.assign({},...s)},gn=(t,e)=>{const s=yn(t,e);if(s===void 0)return{};const{name:r,description:o,supported:n,action:i,forced:l,standard:a}=s;return{[t]:{name:r,number:t,description:o,supported:n,action:i,forced:l,standard:a}}},yn=(t,e)=>{const s=e.find(({name:r})=>Wt.signals[r]===t);return s!==void 0?s:e.find(r=>r.number===t)};hn();const wn=({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:a,isCanceled:u,killed:f,parsed:{options:{timeout:c,cwd:m=q.cwd()}}})=>{n=n===null?void 0:n,o=o===null?void 0:o;const p=o===void 0?void 0:pn[o].description,h=r&&r.code,y=`Command ${wn({timedOut:a,timeout:c,errorCode:h,signal:o,signalDescription:p,exitCode:n,isCanceled:u})}: ${i}`,b=Object.prototype.toString.call(r)==="[object Error]",C=b?`${y}
6
6
  ${r.message}`:y,F=[C,e,t].filter(Boolean).join(`
7
- `);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}
8
- `)},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?`
7
+ `);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=p,r.stdout=t,r.stderr=e,r.cwd=m,s!==void 0&&(r.all=s),"bufferedData"in r&&delete r.bufferedData,r.failed=!0,r.timedOut=!!a,r.isCanceled=u,r.killed=f&&!a,r},Te=["stdin","stdout","stderr"],vn=t=>Te.some(e=>t[e]!==void 0),bn=t=>{if(!t)return;const{stdio:e}=t;if(e===void 0)return Te.map(r=>t[r]);if(vn(t))throw new Error(`It's not possible to provide \`stdio\` in combination with one of ${Te.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,Te.length);return Array.from({length:s},(r,o)=>e[o])};var ie={exports:{}},Ne={exports:{}};Ne.exports;var xr;function $n(){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")}(Ne)),Ne.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=Vt,de=$n(),Cn=/^win/i.test(S.platform),Fe=Yt;typeof Fe!="function"&&(Fe=Fe.EventEmitter);var T;S.__signal_exit_emitter__?T=S.__signal_exit_emitter__:(T=S.__signal_exit_emitter__=new Fe,T.count=0,T.emitted={}),T.infinite||(T.setMaxListeners(1/0),T.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"),fe===!1&&Ar();var s="exit";e&&e.alwaysLast&&(s="afterexit");var r=function(){T.removeListener(s,t),T.listeners("exit").length===0&&T.listeners("afterexit").length===0&&ft()};return T.on(s,t),r};var ft=function(){!fe||!Z(k.process)||(fe=!1,de.forEach(function(e){try{S.removeListener(e,pt[e])}catch{}}),S.emit=ht,S.reallyExit=Mr,T.count-=1)};ie.exports.unload=ft;var ae=function(e,s,r){T.emitted[e]||(T.emitted[e]=!0,T.emit(e,s,r))},pt={};de.forEach(function(t){pt[t]=function(){if(Z(k.process)){var s=S.listeners(t);s.length===T.count&&(ft(),ae("exit",null,t),ae("afterexit",null,t),Cn&&t==="SIGHUP"&&(t="SIGINT"),S.kill(S.pid,t))}}}),ie.exports.signals=function(){return de};var fe=!1,Ar=function(){fe||!Z(k.process)||(fe=!0,T.count+=1,de=de.filter(function(e){try{return S.on(e,pt[e]),!0}catch{return!1}}),S.emit=xn,S.reallyExit=En)};ie.exports.load=Ar;var Mr=S.reallyExit,En=function(e){Z(k.process)&&(S.exitCode=e||0,ae("exit",S.exitCode,null),ae("afterexit",S.exitCode,null),Mr.call(S,S.exitCode))},ht=S.emit,xn=function(e,s){if(e==="exit"&&Z(k.process)){s!==void 0&&(S.exitCode=s);var r=ht.apply(this,arguments);return ae("exit",S.exitCode,null),ae("afterexit",S.exitCode,null),r}else return ht.apply(this,arguments)}}var An=ie.exports,Mn=se(An);const Sn=1e3*5,Rn=(t,e="SIGTERM",s={})=>{const r=t(e);return In(t,e,s,r),r},In=(t,e,s,r)=>{if(!kn(e,s,r))return;const o=Ln(s),n=setTimeout(()=>{t("SIGKILL")},o);n.unref&&n.unref()},kn=(t,{forceKillAfterTimeout:e},s)=>On(t)&&e!==!1&&s,On=t=>t===Ds.constants.signals.SIGTERM||typeof t=="string"&&t.toUpperCase()==="SIGTERM",Ln=({forceKillAfterTimeout:t=!0})=>{if(t===!0)return Sn;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},Tn=(t,e)=>{t.kill()&&(e.isCanceled=!0)},Nn=(t,e,s)=>{t.kill(e),s(Object.assign(new Error("Timed out"),{timedOut:!0,signal:e}))},Fn=(t,{timeout:e,killSignal:s="SIGTERM"},r)=>{if(e===0||e===void 0)return r;let o;const n=new Promise((l,a)=>{o=setTimeout(()=>{Nn(t,s,a)},e)}),i=r.finally(()=>{clearTimeout(o)});return Promise.race([n,i])},_n=({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})`)},Dn=async(t,{cleanup:e,detached:s},r)=>{if(!e||s)return r;const o=Mn(()=>{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 Gn=t=>t instanceof Fs&&typeof t.then=="function",gt=(t,e,s)=>{if(typeof s=="string")return t[e].pipe(Gs(s)),t;if(Rr(s))return t[e].pipe(s),t;if(!Gn(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},jn=t=>{t.stdout!==null&&(t.pipeStdout=gt.bind(void 0,t,"stdout")),t.stderr!==null&&(t.pipeStderr=gt.bind(void 0,t,"stderr")),t.all!==void 0&&(t.pipeAll=gt.bind(void 0,t,"all"))};var pe={exports:{}};const{PassThrough:Bn}=et;var Hn=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 Bn({objectMode:o});s&&n.setEncoding(s);let i=0;const l=[];return n.on("data",a=>{l.push(a),o?i=l.length:i+=a.length}),n.getBufferedValue=()=>e?l:r?Buffer.concat(l,i):l.join(""),n.getBufferedLength=()=>i,n};const{constants:Un}=Bs,qn=et,{promisify:zn}=Jt,Kn=Hn,Wn=zn(qn.pipeline);class Ir extends Error{constructor(){super("maxBuffer exceeded"),this.name="MaxBufferError"}}async function yt(t,e){if(!t)throw new Error("Expected a stream");e={maxBuffer:1/0,...e};const{maxBuffer:s}=e,r=Kn(e);return await new Promise((o,n)=>{const i=l=>{l&&r.getBufferedLength()<=Un.MAX_LENGTH&&(l.bufferedData=r.getBufferedValue()),n(l)};(async()=>{try{await Wn(t,r),o()}catch(l){i(l)}})(),r.on("data",()=>{r.getBufferedLength()>s&&i(new Ir)})}),r.getBufferedValue()}pe.exports=yt,pe.exports.buffer=(t,e)=>yt(t,{...e,encoding:"buffer"}),pe.exports.array=(t,e)=>yt(t,{...e,array:!0}),pe.exports.MaxBufferError=Ir;var Vn=pe.exports,kr=se(Vn);const{PassThrough:Yn}=et;var Jn=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()}},Xn=se(Jn);const Qn=t=>{if(t!==void 0)throw new TypeError("The `input` and `inputFile` options cannot be both set.")},Zn=({input:t,inputFile:e})=>typeof e!="string"?t:(Qn(t),js(e)),ei=(t,e)=>{const s=Zn(e);s!==void 0&&(Sr(s)?s.pipe(t.stdin):t.stdin.end(s))},ti=(t,{all:e})=>{if(!e||!t.stdout&&!t.stderr)return;const s=Xn();return t.stdout&&s.add(t.stdout),t.stderr&&s.add(t.stderr),s},wt=async(t,e)=>{if(!(!t||e===void 0)){t.destroy();try{return await e}catch(s){return s.bufferedData}}},vt=(t,{encoding:e,buffer:s,maxBuffer:r})=>{if(!(!t||!s))return e?kr(t,{encoding:e,maxBuffer:r}):kr.buffer(t,{maxBuffer:r})},ri=async({stdout:t,stderr:e,all:s},{encoding:r,buffer:o,maxBuffer:n},i)=>{const l=vt(t,{encoding:r,buffer:o,maxBuffer:n}),a=vt(e,{encoding:r,buffer:o,maxBuffer:n}),u=vt(s,{encoding:r,buffer:o,maxBuffer:n*2});try{return await Promise.all([i,l,a,u])}catch(f){return Promise.all([{error:f,signal:f.signal,timedOut:f.timedOut},wt(t,l),wt(e,a),wt(s,u)])}},si=(async()=>{})().constructor.prototype,oi=["then","catch","finally"].map(t=>[t,Reflect.getOwnPropertyDescriptor(si,t)]),Or=(t,e)=>{for(const[s,r]of oi){const o=typeof e=="function"?(...n)=>Reflect.apply(r.value,e(),n):r.value.bind(e);Reflect.defineProperty(t,s,{...r,value:o})}},ni=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],ii=/^[\w.-]+$/,ai=/"/g,ci=t=>typeof t!="string"||ii.test(t)?t:`"${t.replace(ai,'\\"')}"`,li=(t,e)=>Lr(t,e).join(" "),mi=(t,e)=>Lr(t,e).map(s=>ci(s)).join(" "),ui=Hs("execa").enabled,_e=(t,e)=>String(t).padStart(e,"0"),di=()=>{const t=new Date;return`${_e(t.getHours(),2)}:${_e(t.getMinutes(),2)}:${_e(t.getSeconds(),2)}.${_e(t.getMilliseconds(),3)}`},fi=(t,{verbose:e})=>{e&&q.stderr.write(`[${di()}] ${t}
8
+ `)},pi=1e3*1e3*100,hi=({env:t,extendEnv:e,preferLocal:s,localDir:r,execPath:o})=>{const n=e?{...q.env,...t}:t;return s?Qo({env:n,cwd:r,execPath:o}):n},gi=(t,e,s={})=>{const r=Wo._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:ui,...s},s.env=hi(s),s.stdio=bn(s),q.platform==="win32"&&re.basename(t,".exe")==="cmd"&&e.unshift("/q"),{file:t,args:e,options:s,parsed:r}},bt=(t,e,s)=>typeof e!="string"&&!Ns.isBuffer(e)?s===void 0?void 0:"":t.stripFinalNewline?Vo(e):e;function J(t,e,s){const r=gi(t,e,s),o=li(t,e),n=mi(t,e);fi(n,r.options),_n(r.options);let i;try{i=zt.spawn(r.file,r.args,r.options)}catch(p){const h=new zt.ChildProcess,g=Promise.reject(Er({error:p,stdout:"",stderr:"",all:"",command:o,escapedCommand:n,parsed:r,timedOut:!1,isCanceled:!1,killed:!1}));return Or(h,g),h}const l=ni(i),a=Fn(i,r.options,l),u=Dn(i,r.options,a),f={isCanceled:!1};i.kill=Rn.bind(null,i.kill.bind(i)),i.cancel=Tn.bind(null,i,f);const m=br(async()=>{const[{error:p,exitCode:h,signal:g,timedOut:y},b,C,F]=await ri(i,r.options,u),K=bt(r.options,b),W=bt(r.options,C),ue=bt(r.options,F);if(p||h!==0||g!==null){const V=Er({error:p,exitCode:h,signal:g,stdout:K,stderr:W,all:ue,command:o,escapedCommand:n,parsed:r,timedOut:y,isCanceled:f.isCanceled||(r.options.signal?r.options.signal.aborted:!1),killed:i.killed});if(!r.options.reject)return V;throw V}return{command:o,escapedCommand:n,exitCode:0,stdout:K,stderr:W,all:ue,failed:!1,timedOut:!1,isCanceled:!1,killed:!1}});return ei(i,r.options),i.all=ti(i,r.options),jn(i),Or(i,m),i}class R{static create(e,s){return new e(s)}}const De=t=>t&&`${t[0].toUpperCase()}${t.slice(1)}`,Ge=(t,e)=>{const s=Math.ceil(t),r=Math.floor(e);return Math.floor(Math.random()*(r-s+1))+s},yi=(t,e)=>t.disabled&&!e.disabled?1:!t.disabled&&e.disabled?-1:0,je=t=>t.reduce((e,s)=>Array.isArray(s)?e.concat(je(s)):e.concat(s),[]),Tr=(t,e=5)=>t.replace(/[\n\r]/g,"").split(" ").slice(0,e).join(" "),wi=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)},vi=t=>{const e=t%360,s=65+t%15,r=45+t%10;return`hsl(${e}, ${s}%, ${r}%)`},bi=t=>{const[e,s,r]=t.match(/\d+/g).map((c,m)=>m===0?Number(c):Number(c)/100),o=(1-Math.abs(2*r-1))*s,n=o*(1-Math.abs(e/60%2-1)),i=r-o/2;let l,a,u;e<60?[l,a,u]=[o,n,0]:e<120?[l,a,u]=[n,o,0]:e<180?[l,a,u]=[0,o,n]:e<240?[l,a,u]=[0,n,o]:e<300?[l,a,u]=[n,0,o]:[l,a,u]=[o,0,n];const f=c=>{const m=Math.round((c+i)*255).toString(16);return m.length===1?"0"+m:m};return`#${f(l)}${f(a)}${f(u)}`},$i=t=>{const e=wi(t),s=vi(e);return{primary:bi(s),secondary:"#FFFFFF"}};class j{constructor(e){this.handleError$=s=>{let r="An error occurred";return s.message&&(r=s.message),L({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=u=>u.replace(/[\u0000-\u001F\u007F-\u009F]/g,"").replace(/\\(?!["\\/bfnrtu])/g,"\\\\"),i=/\[\s*\{[\s\S]*?\}\s*\]/,l=e.match(i);if(l)try{const u=JSON.parse(n(l[0]));o=Array.isArray(u)?u:[u]}catch{return[]}else{const u=/\{[\s\S]*?\}/,f=e.match(u);if(!f)return[];try{o=[JSON.parse(n(f[0]))]}catch{return[]}}return!o.length||!o.every(u=>typeof u.subject=="string")?[]:o.map(u=>this.extractMessageAsType(u,s)).map(u=>({title:`${u.subject}`,value:`${u.subject}${u.body?`
9
9
 
10
- ${m.body}`:""}${m.footer?`
10
+ ${u.body}`:""}${u.footer?`
11
11
 
12
- ${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(`
12
+ ${u.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(),a=i.charAt(0).toLowerCase()+i.slice(1);e=`${l}${n||""}: ${a}`}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.16",Pi="A Reactive CLI that generates git commit messages with various AI";class v extends Error{}const $t=" ",ee=t=>{t instanceof Error&&(t instanceof v||(t.stack&&console.error(w.dim(t.stack.split(`
13
13
  `).slice(1).join(`
14
14
  `))),console.error(`
15
- ${vt}${w.dim(`aicommit2 v${Nr}`)}`),console.error(`
16
- ${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
17
- ${s}`,m=`- Response
18
- ${r}`,p=`[Git Diff]
19
- ${e}`;if(_.existsSync(l)){const a=_.readFileSync(l,"utf-8");_r(l,`${n}
20
- ${m}
15
+ ${$t}${w.dim(`aicommit2 v${Nr}`)}`),console.error(`
16
+ ${$t}Please open a Bug report with the information above:`),console.error(`${$t}https://github.com/tak-bro/aicommit2/issues/new/choose`)))},Fr=O.join(Me.homedir(),".aicommit2_log"),Ci=new Date,B=(t,e,s,r,o)=>{const n=`[${t}]`,i=Ei(Ci,e,o),l=`${Fr}/${i}`,a=`- System Prompt
17
+ ${s}`,u=`- Response
18
+ ${r}`,f=`[Git Diff]
19
+ ${e}`;if(_.existsSync(l)){const c=_.readFileSync(l,"utf-8");_r(l,`${n}
20
+ ${u}
21
21
 
22
- ${c}
22
+ ${a}
23
23
 
24
- ${a}`);return}_r(l,`${n}
25
- ${m}
24
+ ${c}`);return}_r(l,`${n}
25
+ ${u}
26
26
 
27
- ${c}
27
+ ${a}
28
28
 
29
- ${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>
29
+ ${f}`)},Ei=(t,e,s)=>{const{year:r,month:o,day:n,hours:i,minutes:l,seconds:a}=xi(t),f=zs(0).update(e).digest("hex");return s==="review"?`aic2_review_${r}-${o}-${n}_${i}-${l}-${a}_${f}.log`:`aic2_${r}-${o}-${n}_${i}-${l}-${a}_${f}.log`},_r=(t,e="")=>{_.mkdirSync(O.dirname(t),{recursive:!0}),_.writeFileSync(t,e,"utf-8")},xi=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:""},Ai={"":"<commit message>",conventional:`<type>(<optional scope>): <description>
30
30
 
31
31
  [optional body]
32
32
 
@@ -34,12 +34,12 @@ ${p}`)},Ci=(t,e,s)=>{const{year:r,month:o,day:n,hours:i,minutes:l,seconds:c}=Ei(
34
34
 
35
35
  [optional body]
36
36
 
37
- [optional footer(s)]`},Ai={"":"",gitmoji:`
37
+ [optional footer(s)]`},Mi={"":"",gitmoji:`
38
38
  ${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(`
39
39
  `)}`,conventional:`
40
40
  ${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(`
41
- `)}`},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(`
42
- `)},De=(t,e)=>{const s=r=>r==="conventional"?`${Array(e).fill(null).map((o,n)=>`
41
+ `)}`},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:`,`${Ai[e]}`,`3. Types: use one of the following types:${Mi[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(`
42
+ `)},Be=(t,e)=>{const s=r=>r==="conventional"?`${Array(e).fill(null).map((o,n)=>`
43
43
  {
44
44
  "subject": "fix(auth): fix bug in user authentication process",
45
45
  "body": "- Update login function to handle edge cases\\n- Add additional error logging for debugging",
@@ -54,10 +54,10 @@ Lastly, Provide your response as a JSON array containing exactly ${e} object${e!
54
54
  [${s(t)}
55
55
  ]`,`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(`
56
56
  `)},H=t=>{const{systemPrompt:e,systemPromptPath:s,type:r,generate:o}=t;if(e)return`${e}
57
- ${De(r,o)}`;if(!s)return`${Gr(t)}
58
- ${De(r,o)}`;try{const n=_.readFileSync(T.resolve(s),"utf-8");return`${Dr(n,t)}
59
- ${De(r,o)}`}catch{return`${Gr(t)}
60
- ${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:
57
+ ${Be(r,o)}`;if(!s)return`${Gr(t)}
58
+ ${Be(r,o)}`;try{const n=_.readFileSync(O.resolve(s),"utf-8");return`${Dr(n,t)}
59
+ ${Be(r,o)}`}catch{return`${Gr(t)}
60
+ ${Be(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:
61
61
 
62
62
  1. Language: ${s}
63
63
  2. Code quality and best practices
@@ -65,29 +65,29 @@ ${De(r,o)}`}},U=t=>{const{codeReviewPromptPath:e,locale:s}=t,r=`I'll give you th
65
65
  4. Performance improvements
66
66
  5. Readability and maintainability
67
67
 
68
- 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 await this.deleteConversation(f.id),i&&B("HuggingFace",s,d,g,e),e==="review"?this.sanitizeResponse(g):this.parseMessage(g,m,c)}catch(s){const r=s;throw r.code==="ENOTFOUND"?new v(`Error connecting to ${r.hostname} (${r.syscall})`):r}}async intialize(){const e=await this.getRemoteLlms(),s=e.find(r=>r.name?.toLowerCase()===this.params.config.model.toLowerCase());if(s){this.currentModel=s,this.currentModelId=s.id;return}this.currentModel=e[0],this.currentModelId=e[0].id}async getRemoteLlms(){const e=await fetch("https://huggingface.co/chat/__data.json",{headers:{...this.headers,cookie:this.cookie},body:null,method:"GET"});if(e.status!==200)throw new Error(`Failed to get remote LLMs with status code: ${e.status}`);const r=(await e.json()).nodes[0].data,o=r[r[0].models],n=[],i=l=>l===-1?null:r[l];for(const l of o){const c=r[l];if(r[c.unlisted])continue;const m={id:i(c.id),name:i(c.name),displayName:i(c.displayName),preprompt:i(c.preprompt),promptExamples:[],websiteUrl:i(c.websiteUrl),description:i(c.description),datasetName:i(c.datasetName),datasetUrl:i(c.datasetUrl),modelUrl:i(c.modelUrl),parameters:{}},p=i(c.promptExamples);if(p!==null){const f=p.map(h=>i(h));m.promptExamples=f.map(h=>({title:r[h.title],prompt:r[h.prompt]}))}const a=i(c.parameters),d={};for(const[f,h]of Object.entries(a)){if(h===-1){d[f]=null;continue}if(Array.isArray(r[h])){d[f]=r[h].map(g=>r[g]);continue}d[f]=r[h]}m.parameters=d,n.push(m)}return this.models=n,n}async getNewChat(e){const s={model:this.currentModelId,preprompt:e};let r=0;for(;r<5;){const o=await fetch("https://huggingface.co/chat/conversation",{headers:{...this.headers,"content-type":"application/json",cookie:this.cookie,Referer:"https://huggingface.co/chat/"},body:JSON.stringify(s),method:"POST"}),{conversationId:n}=await o.json();if(n){this.currentConversionID=n;break}else r++}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 s=await fetch("https://huggingface.co/chat/conversation/"+e+"/__data.json",{headers:{...this.headers,cookie:this.cookie,Referer:"https://huggingface.co/chat/"},body:null,method:"GET"});if(s.status!=200)throw new Error("Unable get conversation details "+s);{const r=await s.json();return this.metadataParser(r,e)}}metadataParser(e,s){const r={id:"",model:"",systemPrompt:"",title:"",history:[]},o=e.nodes[1].data,n=o[o[0].model],i=o[o[0].preprompt],l=o[o[0].title],c=o[o[0].messages],m=[];for(const p of c){const a=o[p],d=new Date(o[a.createdAt][1]).getTime()/1e3,f=new Date(o[a.updatedAt][1]).getTime()/1e3;m.push({id:o[a.id],role:o[a.from],content:o[a.content],createdAt:d,updatedAt:f})}return r.id=s,r.model=n,r.systemPrompt=i,r.title=l,r.history=m,this.currentConversation=r,r}async sendMessage(e,s){if(e==="")throw new Error("the prompt can not be empty.");if(!s&&!this.currentConversionID?await this.getNewChat():s?(this.currentConversionID=s,await this.getConversationHistory(s)):this.currentConversionID&&await this.getConversationHistory(this.currentConversionID),!this.currentConversation)throw new Error("Failed to create new conversion");const r={inputs:e,id:this.currentConversation.history[this.currentConversation.history.length-1].id,is_retry:!1,is_continue:!1,web_search:!1,tools:[]},o=new FormData;o.append("data",JSON.stringify(r));const n=await fetch("https://huggingface.co/chat/conversation/"+this.currentConversionID,{headers:{...this.headers,cookie:this.cookie,Referer:"https://huggingface.co/chat/conversation/"+this.currentConversionID},body:o,method:"POST"});function i(d){try{const f=d.split(`
69
- `),h=[];for(const g of f)g.trim()&&h.push(JSON.parse(g));return h}catch{return[{}]}}const l=new TextDecoder;let c="";const m=new TransformStream({async transform(d,f){const h=l.decode(d);try{const g=i(h);for(const y of g)y.type==="finalAnswer"?(c=y?.text||"",f.terminate()):y.type==="stream"&&f.enqueue(y?.token||"")}catch{throw new Error("Error during parsing response")}}}),p=n.body?.pipeThrough(m);async function a(){return new Promise(async(d,f)=>{try{if(!p)f("ModifiedStream undefined");else{const h=p.getReader();for(;;){const{done:g,value:y}=await h.read();if(g){d(c);break}}}}catch(h){f(h)}})}return{id:this.currentConversionID,stream:p,completeResponsePromise:a}}async deleteConversation(e){return(await fetch(`https://huggingface.co/chat/conversation/${e}`,{headers:{...this.headers,cookie:this.cookie,Referer:"https://huggingface.co/chat/"},body:null,method:"DELETE"})).json()}}class Yr extends j{constructor(e){super(e),this.params=e,this.host="https://api.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:"#ff7000",secondary:"#fff"},this.serviceName=w.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[MistralAI]"),this.errorPrefix=w.red.bold("[MistralAI]"),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);await this.checkAvailableModels();const f=await this.createChatCompletions(d,`Here is the diff: ${s}`);return i&&B("MistralAI",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}}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(){return(await new fe({method:"GET",baseURL:`${this.host}/v1/models`,timeout:this.params.config.timeout}).setHeaders({Authorization:`Bearer ${this.apiKey}`,"content-type":"application/json"}).execute()).data.data.filter(s=>s.object==="model").map(s=>s.id)}async createChatCompletions(e,s){const o=(await 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:s}],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)}).execute()).data;if(!o.choices||o.choices.length===0||!o.choices[0].message?.content)throw new Error("No Content on response. Please open a Bug report");return o.choices[0].message.content}}const{hasOwnProperty:bt}=Object.prototype,Ge=typeof process<"u"&&process.platform==="win32"?`\r
68
+ Please structure your response with appropriate Markdown headings, code blocks, and bullet points.`;if(!e)return r;try{const o=_.readFileSync(O.resolve(e),"utf-8");return`${Dr(o,t)}`}catch{return r}},jr=async t=>{if(t.systemPromptPath)try{_.readFileSync(O.resolve(t.systemPromptPath),"utf-8")}catch{throw new v(`Error reading system prompt file: ${t.systemPromptPath}`)}if(t.codeReview&&t.codeReviewPromptPath)try{_.readFileSync(O.resolve(t.codeReviewPromptPath),"utf-8")}catch{throw new v(`Error reading code review prompt file: ${t.codeReviewPromptPath}`)}},Si=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 L({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 qs({apiKey:this.params.config.key,...this.params.config.timeout>Si&&{timeout:this.params.config.timeout}})}generateCommitMessage$(){return M(this.generateMessage("commit")).pipe(A(e=>P(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=>P(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:a,generate:u,type:f,maxLength:c,maxTokens:m,topP:p,model:h}=this.params.config,g={...G,locale:a,maxLength:c,type:f,generate:u,systemPrompt:r,systemPromptPath:o,codeReviewPromptPath:n},y=e==="review"?U(g):H(g),b={max_tokens:m,temperature:l,system:y,messages:[{role:"user",content:`Here is the diff: ${s}`}],top_p:p,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,f,u)}catch(s){const r=s;throw r.code==="ENOTFOUND"?new v(`Error connecting to ${r.hostname} (${r.syscall})`):r}}}class he{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=Ks.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 L({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=>P(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=>P(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:a,type:u,maxLength:f}=this.params.config,c={...G,locale:l,maxLength:f,type:u,generate:a,systemPrompt:r,systemPromptPath:o,codeReviewPromptPath:n},m=e==="review"?U(c):H(c);this.checkAvailableModels();const p=await this.createChatCompletions(m,e);return i&&B("Codestral",s,m,p,e),e==="review"?this.sanitizeResponse(p):this.parseMessage(p,u,a)}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 he({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:Ge(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 Ri=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 L({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 Ws({token:this.params.config.key})}generateCommitMessage$(){return M(this.generateMessage("commit")).pipe(A(e=>P(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=>P(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:a,generate:u,type:f,maxLength:c,maxTokens:m}=this.params.config,p={...G,locale:a,maxLength:c,type:f,generate:u,systemPrompt:r,systemPromptPath:o,codeReviewPromptPath:n},h=e==="review"?U(p):H(p),g=await this.cohere.chat({chatHistory:h?[{role:"SYSTEM",message:h}]:[],message:`Here is the diff: ${s}`,connectors:[{id:"web-search"}],maxTokens:m,temperature:l,model:this.params.config.model,seed:Ge(10,1e3),p:this.params.config.topP},{...this.params.config.timeout>Ri&&{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,f,u)}catch(s){const r=s;throw r instanceof Vs?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 L({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 Se({baseURL:this.host,apiKey:this.params.config.key})}generateCommitMessage$(){return M(this.generateMessage("commit")).pipe(A(e=>P(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=>P(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:a,type:u,maxLength:f}=this.params.config,c={...G,locale:l,maxLength:f,type:u,generate:a,systemPrompt:r,systemPromptPath:o,codeReviewPromptPath:n},m=e==="review"?U(c):H(c);this.checkAvailableModels();const p=await this.createChatCompletions(m);return i&&B("DeepSeek",s,m,p,e),e==="review"?this.sanitizeResponse(p):this.parseMessage(p,u,a)}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(a=>i.push(a[1]));const l=i[1]||"An error occurred";return L({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=>P(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=>P(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:a,type:u,maxLength:f}=this.params.config,c=this.params.config.maxTokens,m={...G,locale:i,maxLength:f,type:u,generate:a,systemPrompt:r,systemPromptPath:o,codeReviewPromptPath:l},p=e==="review"?U(m):H(m),h={maxOutputTokens:c,temperature:this.params.config.temperature,topP:this.params.config.topP},C=(await this.genAI.getGenerativeModel({model:this.params.config.model,systemInstruction:p,generationConfig:h,safetySettings:[{category:Re.HARM_CATEGORY_HATE_SPEECH,threshold:Ie.BLOCK_LOW_AND_ABOVE},{category:Re.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:Ie.BLOCK_LOW_AND_ABOVE},{category:Re.HARM_CATEGORY_HARASSMENT,threshold:Ie.BLOCK_LOW_AND_ABOVE},{category:Re.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:Ie.BLOCK_LOW_AND_ABOVE}]}).generateContent(`Here is the diff: ${s}`)).response.text();return n&&B("Gemini",s,p,C,e),e==="review"?this.sanitizeResponse(C):this.parseMessage(C,u,a)}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 L({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=>P(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=>P(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:a,generate:u,type:f,maxLength:c}=this.params.config,m=this.params.config.maxTokens,p={...G,locale:l,maxLength:c,type:f,generate:u,systemPrompt:r,systemPromptPath:o,codeReviewPromptPath:n},h=e==="review"?U(p):H(p),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:m,top_p:this.params.config.topP,temperature:a},{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,f,u)}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=>P(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=>P(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.initialize();const s=this.params.stagedDiff.diff,{systemPrompt:r,systemPromptPath:o,codeReviewPromptPath:n,logging:i,locale:l,generate:a,type:u,maxLength:f}=this.params.config,c={...G,locale:l,maxLength:f,type:u,generate:a,systemPrompt:r,systemPromptPath:o,codeReviewPromptPath:n},m=e==="review"?U(c):H(c),p=await this.getNewChat(m),g=await(await this.sendMessage(`Here is the diff: ${s}`,p.id)).completeResponsePromise();return await this.deleteConversation(p.id),i&&B("HuggingFace",s,m,g,e),e==="review"?this.sanitizeResponse(g):this.parseMessage(g,u,a)}catch(s){const r=s;throw r.code==="ENOTFOUND"?new v(`Error connecting to ${r.hostname} (${r.syscall})`):r}}async initialize(){const e=await this.getRemoteLlms(),s=e.find(r=>r.name?.toLowerCase()===this.params.config.model.toLowerCase());if(s){this.currentModel=s,this.currentModelId=s.id;return}this.currentModel=e[0],this.currentModelId=e[0].id}async getRemoteLlms(){const e=await fetch("https://huggingface.co/chat/__data.json",{headers:{...this.headers,cookie:this.cookie},body:null,method:"GET"});if(e.status!==200)throw new Error(`Failed to get remote LLMs with status code: ${e.status}`);const r=(await e.json()).nodes[0].data,o=r[r[0].models],n=[],i=l=>l===-1?null:r[l];for(const l of o){const a=r[l];if(r[a.unlisted])continue;const u={id:i(a.id),name:i(a.name),displayName:i(a.displayName),preprompt:i(a.preprompt),promptExamples:[],websiteUrl:i(a.websiteUrl),description:i(a.description),datasetName:i(a.datasetName),datasetUrl:i(a.datasetUrl),modelUrl:i(a.modelUrl),parameters:{}},f=i(a.promptExamples);if(f!==null){const p=f.map(h=>i(h));u.promptExamples=p.map(h=>({title:r[h.title],prompt:r[h.prompt]}))}const c=i(a.parameters),m={};for(const[p,h]of Object.entries(c)){if(h===-1){m[p]=null;continue}if(Array.isArray(r[h])){m[p]=r[h].map(g=>r[g]);continue}m[p]=r[h]}u.parameters=m,n.push(u)}return this.models=n,n}async getNewChat(e){const s={model:this.currentModelId,preprompt:e};let r=0;for(;r<5;){const o=await fetch("https://huggingface.co/chat/conversation",{headers:{...this.headers,"content-type":"application/json",cookie:this.cookie,Referer:"https://huggingface.co/chat/"},body:JSON.stringify(s),method:"POST"}),{conversationId:n}=await o.json();if(n){this.currentConversionID=n;break}else r++}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 s=await fetch("https://huggingface.co/chat/conversation/"+e+"/__data.json",{headers:{...this.headers,cookie:this.cookie,Referer:"https://huggingface.co/chat/"},body:null,method:"GET"});if(s.status!=200)throw new Error("Unable get conversation details "+s);{const r=await s.json();return this.metadataParser(r,e)}}metadataParser(e,s){const r={id:"",model:"",systemPrompt:"",title:"",history:[]},o=e.nodes[1].data,n=o[o[0].model],i=o[o[0].preprompt],l=o[o[0].title],a=o[o[0].messages],u=[];for(const f of a){const c=o[f],m=new Date(o[c.createdAt][1]).getTime()/1e3,p=new Date(o[c.updatedAt][1]).getTime()/1e3;u.push({id:o[c.id],role:o[c.from],content:o[c.content],createdAt:m,updatedAt:p})}return r.id=s,r.model=n,r.systemPrompt=i,r.title=l,r.history=u,this.currentConversation=r,r}async sendMessage(e,s){if(e==="")throw new Error("the prompt can not be empty.");if(!s&&!this.currentConversionID?await this.getNewChat():s?(this.currentConversionID=s,await this.getConversationHistory(s)):this.currentConversionID&&await this.getConversationHistory(this.currentConversionID),!this.currentConversation)throw new Error("Failed to create new conversion");const r={inputs:e,id:this.currentConversation.history[this.currentConversation.history.length-1].id,is_retry:!1,is_continue:!1,web_search:!1,tools:[]},o=new FormData;o.append("data",JSON.stringify(r));const n=await fetch("https://huggingface.co/chat/conversation/"+this.currentConversionID,{headers:{...this.headers,cookie:this.cookie,Referer:"https://huggingface.co/chat/conversation/"+this.currentConversionID},body:o,method:"POST"});function i(m){try{const p=m.split(`
69
+ `),h=[];for(const g of p)g.trim()&&h.push(JSON.parse(g));return h}catch{return[{}]}}const l=new TextDecoder;let a="";const u=new TransformStream({async transform(m,p){const h=l.decode(m);try{const g=i(h);for(const y of g)y.type==="finalAnswer"?(a=y?.text||"",p.terminate()):y.type==="stream"&&p.enqueue(y?.token||"")}catch{throw new Error("Error during parsing response")}}}),f=n.body?.pipeThrough(u);async function c(){return new Promise(async(m,p)=>{try{if(!f)p("ModifiedStream undefined");else{const h=f.getReader();for(;;){const{done:g,value:y}=await h.read();if(g){m(a);break}}}}catch(h){p(h)}})}return{id:this.currentConversionID,stream:f,completeResponsePromise:c}}async deleteConversation(e){return(await fetch(`https://huggingface.co/chat/conversation/${e}`,{headers:{...this.headers,cookie:this.cookie,Referer:"https://huggingface.co/chat/"},body:null,method:"DELETE"})).json()}}class Vr extends j{constructor(e){super(e),this.params=e,this.host="https://api.mistral.ai",this.apiKey="",this.handleError$=s=>{const r=s.message?.replace(/(\r\n|\n|\r)/gm,"")||"An error occurred";return L({name:`${this.errorPrefix} ${r}`,value:r,isError:!0,disabled:!0})},this.colors={primary:"#ff7000",secondary:"#fff"},this.serviceName=w.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[MistralAI]"),this.errorPrefix=w.red.bold("[MistralAI]"),this.apiKey=this.params.config.key}generateCommitMessage$(){return M(this.generateMessage("commit")).pipe(A(e=>P(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=>P(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:a,type:u,maxLength:f}=this.params.config,c={...G,locale:l,maxLength:f,type:u,generate:a,systemPrompt:r,systemPromptPath:o,codeReviewPromptPath:n},m=e==="review"?U(c):H(c);await this.checkAvailableModels();const p=await this.createChatCompletions(m,`Here is the diff: ${s}`);return i&&B("MistralAI",s,m,p,e),e==="review"?this.sanitizeResponse(p):this.parseMessage(p,u,a)}catch(s){const r=s;throw r.code==="ENOTFOUND"?new v(`Error connecting to ${r.hostname} (${r.syscall})`):r}}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(){return(await new he({method:"GET",baseURL:`${this.host}/v1/models`,timeout:this.params.config.timeout}).setHeaders({Authorization:`Bearer ${this.apiKey}`,"content-type":"application/json"}).execute()).data.data.filter(s=>s.object==="model").map(s=>s.id)}async createChatCompletions(e,s){const o=(await new he({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:s}],temperature:this.params.config.temperature,top_p:this.params.config.topP,max_tokens:this.params.config.maxTokens,stream:!1,safe_prompt:!1,random_seed:Ge(10,1e3)}).execute()).data;if(!o.choices||o.choices.length===0||!o.choices[0].message?.content)throw new Error("No Content on response. Please open a Bug report");return o.choices[0].message.content}}const{hasOwnProperty:Pt}=Object.prototype,He=typeof process<"u"&&process.platform==="win32"?`\r
70
70
  `:`
71
- `,Pt=(t,e)=>{const s=[];let r="";typeof e=="string"?e={section:e,whitespace:!1}:(e=e||Object.create(null),e.whitespace=e.whitespace===!0);const o=e.whitespace?" = ":"=";for(const n of Object.keys(t)){const i=t[n];if(i&&Array.isArray(i))for(const l of i)r+=ce(n+"[]")+o+ce(l)+Ge;else i&&typeof i=="object"?s.push(n):r+=ce(n)+o+ce(i)+Ge}e.section&&r.length&&(r="["+ce(e.section)+"]"+Ge+r);for(const n of s){const i=Vr(n).join("\\."),l=(e.section?e.section+".":"")+i,{whitespace:c}=e,m=Pt(t[n],{section:l,whitespace:c});r.length&&m.length&&(r+=Ge),r+=m}return r},Vr=t=>t.replace(/\1/g,"LITERAL\\1LITERAL").replace(/\\\./g,"").split(/\./).map(e=>e.replace(/\1/g,"\\.").replace(/\2LITERAL\\1LITERAL\2/g,"")),Jr=t=>{const e=Object.create(null);let s=e,r=null;const o=/^\[([^\]]*)\]$|^([^=]+)(=(.*))?$/i,n=t.split(/[\r\n]+/g);for(const l of n){if(!l||l.match(/^\s*[;#]/))continue;const c=l.match(o);if(!c)continue;if(c[1]!==void 0){if(r=je(c[1]),r==="__proto__"){s=Object.create(null);continue}s=e[r]=e[r]||Object.create(null);continue}const m=je(c[2]),p=m.length>2&&m.slice(-2)==="[]",a=p?m.slice(0,-2):m;if(a==="__proto__")continue;const d=c[3]?je(c[4]):!0,f=d==="true"||d==="false"||d==="null"?JSON.parse(d):d;p&&(bt.call(s,a)?Array.isArray(s[a])||(s[a]=[s[a]]):s[a]=[]),Array.isArray(s[a])?s[a].push(f):s[a]=f}const i=[];for(const l of Object.keys(e)){if(!bt.call(e,l)||typeof e[l]!="object"||Array.isArray(e[l]))continue;const c=Vr(l);s=e;const m=c.pop(),p=m.replace(/\\\./g,".");for(const a of c)a!=="__proto__"&&((!bt.call(s,a)||typeof s[a]!="object")&&(s[a]=Object.create(null)),s=s[a]);s===e&&p===m||(s[p]=e[l],i.push(l))}for(const l of i)delete e[l];return e},Xr=t=>t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'"),ce=t=>typeof t!="string"||t.match(/[=\r\n]/)||t.match(/^\[/)||t.length>1&&Xr(t)||t!==t.trim()?JSON.stringify(t):t.split(";").join("\\;").split("#").join("\\#"),je=(t,e)=>{if(t=(t||"").trim(),Xr(t)){t.charAt(0)==="'"&&(t=t.slice(1,-1));try{t=JSON.parse(t)}catch{}}else{let s=!1,r="";for(let o=0,n=t.length;o<n;o++){const i=t.charAt(o);if(s)"\\;#".indexOf(i)!==-1?r+=i:r+="\\"+i,s=!1;else{if(";#".indexOf(i)!==-1)break;i==="\\"?s=!0:r+=i}}return s&&(r+="\\"),r.trim()}return t};var Ri={parse:Jr,decode:Jr,stringify:Pt,encode:Pt,safe:ce,unsafe:je},$t=se(Ri);const Qr=t=>I.lstat(t).then(()=>!0,()=>!1),Ii=["","conventional","gitmoji"],Ct="http://localhost:11434",{hasOwnProperty:ki}=Object.prototype,Be=(t,e)=>ki.call(t,e),V=["OPENAI","OLLAMA","HUGGINGFACE","GEMINI","ANTHROPIC","MISTRAL","CODESTRAL","COHERE","GROQ","PERPLEXITY","DEEPSEEK"],Oi=t=>{const e=Object.keys(t),s=new Set([...V,...e.filter(r=>/^[A-Z][A-Z0-9_]*$/.test(r))]);return Array.from(s)},P=(t,e,s)=>{if(!e)throw new v(`Invalid config property ${t}: ${s}`)},u={systemPrompt(t){return t||""},systemPromptPath(t){return t||""},codeReviewPromptPath(t){return t||""},timeout(t){if(!t)return 1e4;P("timeout",/^\d+$/.test(t),"Must be an integer");const e=Number(t);return P("timeout",e>=500,"Must be greater than 500ms"),e},temperature(t){if(!t)return .7;P("temperature",/^(2|\d)(\.\d{1,2})?$/.test(t),"Must be decimal between 0 and 2");const e=Number(t);return P("temperature",e>0,"Must be greater than 0"),P("temperature",e<=2,"Must be less than or equal to 2"),e},maxTokens(t){return t?(P("maxTokens",/^\d+$/.test(t),"Must be an integer"),Number(t)):1024},logging(t){return typeof t=="boolean"?t:t==null?!0:(P("logging",/^(?:true|false)$/.test(t),"Must be a boolean(true or false)"),t==="true")},locale(t){return t?(P("locale",t,"Cannot be empty"),P("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;P("generate",/^\d+$/.test(t),"Must be an integer");const e=Number(t);return P("generate",e>0,"Must be greater than 0"),P("generate",e<=5,"Must be less or equal to 5"),e},type(t){return t?(P("type",Ii.includes(t),"Invalid commit type"),t):"conventional"},maxLength(t){if(!t)return 50;P("maxLength",/^\d+$/.test(t),"Must be an integer");const e=Number(t);return P("maxLength",e>=20,"Must be greater than 20 characters"),e},includeBody(t){return typeof t=="boolean"?t:t==null?!1:(P("includeBody",/^(?:true|false)$/.test(t),"Must be a boolean(true or false)"),t==="true")},exclude:t=>t?(typeof t=="string"?t?.split(","):t).map(s=>s.trim()).filter(s=>!!s&&s.length>0):[],topP:t=>{if(!t)return .9;P("topP",/^(1|\d)(\.\d{1,2})?$/.test(t),"Must be decimal between 0 and 1");const e=Number(t);return P("topP",e>0,"Must be greater than 0"),P("topP",e<=1,"Must be less than or equal to 1"),e},codeReview(t){return typeof t=="boolean"?t:t==null?!1:(P("codeReview",/^(?:true|false)$/.test(t),"Must be a boolean(true or false)"),t==="true")},disabled(t){return typeof t=="boolean"?t:t==null?!1:(P("disabled",/^(?:true|false)$/.test(t),"Must be a boolean(true or false)"),t==="true")},watchMode(t){return typeof t=="boolean"?t:t==null?!1:(P("watchMode",/^(?:true|false)$/.test(t),"Must be a boolean(true or false)"),t==="true")}},he={OPENAI:{key:t=>t||"",model:t=>t||"gpt-4o-mini",url:t=>t?(P("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:u.topP,systemPrompt:u.systemPrompt,systemPromptPath:u.systemPromptPath,codeReviewPromptPath:u.codeReviewPromptPath,timeout:u.timeout,temperature:u.temperature,maxTokens:u.maxTokens,logging:u.logging,locale:u.locale,generate:u.generate,type:u.type,maxLength:u.maxLength,includeBody:u.includeBody,codeReview:u.codeReview,disabled:u.disabled,watchMode:u.watchMode},HUGGINGFACE:{cookie:t=>t||"",model:t=>t?(P("HUGGINGFACE.model",["CohereForAI/c4ai-command-r-plus","meta-llama/Meta-Llama-3-70B-Instruct","HuggingFaceH4/zephyr-orpo-141b-A35b-v0.1","mistralai/Mixtral-8x7B-Instruct-v0.1","NousResearch/Nous-Hermes-2-Mixtral-8x7B-DPO","01-ai/Yi-1.5-34B-Chat","mistralai/Mistral-7B-Instruct-v0.2","microsoft/Phi-3-mini-4k-instruct"].includes(t),"Invalid model type of HuggingFace chat"),t):"CohereForAI/c4ai-command-r-plus",systemPrompt:u.systemPrompt,systemPromptPath:u.systemPromptPath,codeReviewPromptPath:u.codeReviewPromptPath,logging:u.logging,locale:u.locale,generate:u.generate,type:u.type,maxLength:u.maxLength,includeBody:u.includeBody,codeReview:u.codeReview,disabled:u.disabled,watchMode:u.watchMode},GEMINI:{key:t=>t||"",model:t=>!t||t.length===0?"gemini-2.0-flash":(P("GEMINI.model",["gemini-2.0-flash","gemini-2.0-flash-lite","gemini-2.0-pro-exp-02-05","gemini-2.0-flash-thinking-exp-01-21","gemini-2.0-flash-exp","gemini-1.5-flash","gemini-1.5-flash-8b","gemini-1.5-pro"].includes(t),"Invalid model type of Gemini"),t),systemPrompt:u.systemPrompt,systemPromptPath:u.systemPromptPath,codeReviewPromptPath:u.codeReviewPromptPath,temperature:u.temperature,maxTokens:u.maxTokens,logging:u.logging,locale:u.locale,generate:u.generate,type:u.type,maxLength:u.maxLength,includeBody:u.includeBody,topP:u.topP,codeReview:u.codeReview,disabled:u.disabled,watchMode:u.watchMode},ANTHROPIC:{key:t=>t||"",model:t=>!t||t.length===0?"claude-3-5-haiku-20241022":(P("ANTHROPIC.model",["claude-3-7-sonnet-20250219","claude-3-5-sonnet-20241022","claude-3-5-haiku-20241022","claude-3-opus-20240229","claude-3-sonnet-20240229","claude-3-haiku-20240307"].includes(t),"Invalid model type of Anthropic"),t),systemPrompt:u.systemPrompt,systemPromptPath:u.systemPromptPath,codeReviewPromptPath:u.codeReviewPromptPath,temperature:u.temperature,maxTokens:u.maxTokens,logging:u.logging,locale:u.locale,generate:u.generate,type:u.type,maxLength:u.maxLength,includeBody:u.includeBody,topP:u.topP,codeReview:u.codeReview,disabled:u.disabled,watchMode:u.watchMode},MISTRAL:{key:t=>t||"",model:t=>!t||t.length===0?"pixtral-12b-2409":(P("MISTRAL.model",["codestral-latest","mistral-large-latest","pixtral-large-latest","ministral-8b-latest","mistral-small-latest","mistral-embed","mistral-moderation-latest"].includes(t),"Invalid model type of Mistral AI"),t),systemPrompt:u.systemPrompt,systemPromptPath:u.systemPromptPath,codeReviewPromptPath:u.codeReviewPromptPath,timeout:u.timeout,temperature:u.temperature,maxTokens:u.maxTokens,logging:u.logging,locale:u.locale,generate:u.generate,type:u.type,maxLength:u.maxLength,includeBody:u.includeBody,topP:u.topP,codeReview:u.codeReview,disabled:u.disabled,watchMode:u.watchMode},CODESTRAL:{key:t=>t||"",model:t=>!t||t.length===0?"codestral-latest":(P("CODESTRAL.model",["codestral-latest","codestral-2501"].includes(t),"Invalid model type of Codestral"),t),topP:u.topP,systemPrompt:u.systemPrompt,systemPromptPath:u.systemPromptPath,codeReviewPromptPath:u.codeReviewPromptPath,timeout:u.timeout,temperature:u.temperature,maxTokens:u.maxTokens,logging:u.logging,locale:u.locale,generate:u.generate,type:u.type,maxLength:u.maxLength,includeBody:u.includeBody,codeReview:u.codeReview,disabled:u.disabled,watchMode:u.watchMode},OLLAMA:{model:t=>t?(typeof t=="string"?t?.split(","):t).map(s=>s.trim()).filter(s=>!!s&&s.length>0):[],host:t=>t?(P("OLLAMA.host",/^https?:\/\//.test(t),"Must be a valid URL"),t):Ct,timeout:t=>{if(!t)return 1e5;P("OLLAMA.timeout",/^\d+$/.test(t),"Must be an integer");const e=Number(t);return P("OLLAMA.timeout",e>=500,"Must be greater than 500ms"),e},auth:t=>t||"",key:t=>t||"",numCtx:t=>{if(!t)return 2048;P("OLLAMA.numCtx",/^\d+$/.test(t),"Must be an integer");const e=Number(t);return P("OLLAMA.numCtx",e>=2048,"Must be greater than 2048"),e},systemPrompt:u.systemPrompt,systemPromptPath:u.systemPromptPath,codeReviewPromptPath:u.codeReviewPromptPath,temperature:u.temperature,logging:u.logging,locale:u.locale,generate:u.generate,type:u.type,maxLength:u.maxLength,includeBody:u.includeBody,topP:u.topP,codeReview:u.codeReview,disabled:u.disabled,watchMode:u.watchMode},COHERE:{key:t=>t||"",model:t=>!t||t.length===0?"command":(P("COHERE.model",["command-r7b-12-2024","command-r-plus-08-2024","command-r-plus-04-2024","command-r-plus","command-r-08-2024","command-r-03-2024","command-r","command","command-nightly","command-light","command-light-nightly","c4ai-aya-expanse-8b","c4ai-aya-expanse-32b"].includes(t),"Invalid model type of Cohere"),t),systemPrompt:u.systemPrompt,systemPromptPath:u.systemPromptPath,codeReviewPromptPath:u.codeReviewPromptPath,temperature:u.temperature,maxTokens:u.maxTokens,logging:u.logging,locale:u.locale,generate:u.generate,type:u.type,maxLength:u.maxLength,includeBody:u.includeBody,topP:u.topP,codeReview:u.codeReview,disabled:u.disabled,watchMode:u.watchMode},GROQ:{key:t=>t||"",model:t=>!t||t.length===0?"deepseek-r1-distill-llama-70b":(P("GROQ.model",["qwen-2.5-32b","qwen-2.5-coder-32b","deepseek-r1-distill-qwen-32b","deepseek-r1-distill-llama-70b","gemma2-9b-it","llama-3.3-70b-versatile","llama-3.1-8b-instant","llama-guard-3-8b","llama3-70b-8192","llama3-8b-8192","mixtral-8x7b-32768","distil-whisper-large-v3-en","whisper-large-v3","whisper-large-v3-turbo","llama-3.3-70b-specdec","llama-3.2-1b-preview","llama-3.2-3b-preview","llama-3.2-11b-vision-preview","llama-3.2-90b-vision-preview"].includes(t),"Invalid model type of Groq"),t),systemPrompt:u.systemPrompt,systemPromptPath:u.systemPromptPath,codeReviewPromptPath:u.codeReviewPromptPath,timeout:u.timeout,temperature:u.temperature,maxTokens:u.maxTokens,logging:u.logging,locale:u.locale,generate:u.generate,type:u.type,maxLength:u.maxLength,includeBody:u.includeBody,topP:u.topP,codeReview:u.codeReview,disabled:u.disabled,watchMode:u.watchMode},PERPLEXITY:{key:t=>t||"",model:t=>!t||t.length===0?"sonar":(P("PERPLEXITY.model",["sonar-pro","sonar","llama-3.1-sonar-small-128k-online","llama-3.1-sonar-large-128k-online","llama-3.1-sonar-huge-128k-online"].includes(t),"Invalid model type of Perplexity"),t),topP:u.topP,systemPrompt:u.systemPrompt,systemPromptPath:u.systemPromptPath,codeReviewPromptPath:u.codeReviewPromptPath,timeout:u.timeout,temperature:u.temperature,maxTokens:u.maxTokens,logging:u.logging,locale:u.locale,generate:u.generate,type:u.type,maxLength:u.maxLength,includeBody:u.includeBody,codeReview:u.codeReview,disabled:u.disabled,watchMode:u.watchMode},DEEPSEEK:{key:t=>t||"",model:t=>!t||t.length===0?"deepseek-chat":(console.log(t),P("DEEPSEEK.model",["deepseek-reasoner","deepseek-chat"].includes(t),"Invalid model type of DeepSeek"),t),topP:u.topP,systemPrompt:u.systemPrompt,systemPromptPath:u.systemPromptPath,codeReviewPromptPath:u.codeReviewPromptPath,timeout:u.timeout,temperature:u.temperature,maxTokens:u.maxTokens,logging:u.logging,locale:u.locale,generate:u.generate,type:u.type,maxLength:u.maxLength,includeBody:u.includeBody,codeReview:u.codeReview,disabled:u.disabled,watchMode:u.watchMode}},He=T.join(Ze.homedir(),".aicommit2"),Li=(t=[])=>{const e={};for(const s of t)if(s.startsWith("--")){const[r,o]=s.slice(2).split("="),[n,i]=r.split(".");n&&i&&n in he?(e[n]||(e[n]={}),e[n][i]=o):e[r]=o}return e},Zr=async()=>await Qr(He)?await I.readFile(He,"utf8"):"",Et=async()=>{const t=await Zr();if(!t)return Object.create(null);let e=$t.parse(t);return Be(e,"OLLAMA")&&Be(e.OLLAMA,"model")&&(e={...e,OLLAMA:{...e.OLLAMA,model:typeof e.OLLAMA.model=="string"?[e.OLLAMA.model]:e.OLLAMA.model}}),Be(e,"exclude")&&(e={...e,exclude:typeof e.exclude=="string"?[e.exclude]:e.exclude}),e},ge=async(t,e=[])=>{const s=await Et(),r=Li(e),o={...t,...r},n={},i=Oi(s),l={},c=V.map(p=>({service:p,envKey:`${p}_API_KEY`}));for(const{service:p,envKey:a}of c){const d=process.env[a];d&&(l[p]={key:d})}const m=(p,a)=>{const d=o[`${p}.${a}`]??o[p]?.[a],f=l[p]?.[a],h=s[p]?.[a],g=o[a]??s[a];return d!==void 0?d:f!==void 0?f:h!==void 0?h:g};for(const[p,a]of Object.entries(u)){const d=o[p]??s[p];n[p]=a(d)}for(const p of i){n[p]={};const a=he[p]||Ue(p);for(const[d,f]of Object.entries(a)){const h=m(p,d);n[p][d]=f(h)}}return n},Ti=async t=>{const e=await Et();for(const[s,r]of t){const[o,n]=s.split(".");if(!n){const c=u[s];if(!c)throw new v(`Invalid config property: ${s}`);e[s]=c(r);continue}if(e[o]||(e[o]={}),V.includes(o)){const c=he[o][n];if(!c)throw new v(`Invalid config property: ${s}`);e[o][n]=c(r);continue}if(!/^[A-Z][A-Z0-9_]*$/.test(o))throw new v(`Invalid service name: ${o}. Service names must be uppercase letters, numbers, and underscores.`);const l=Ue(o);if(!l[n])throw new v(`Invalid config property for custom service: ${s}`);try{e[o][n]=l[n](r)}catch(c){throw c instanceof v?c:new v(`Invalid value for ${s}: ${c.message}`)}}await I.writeFile(He,$t.stringify(e),"utf8")},Ni=async t=>{const e=await Et();for(const[s,r]of t){const[o,n]=s.split("."),i=e[o];if(o==="OLLAMA"&&n==="model"){i||(e[o]={});const c=e[o][n]||[];e[o][n]=_e([...c,r]);continue}if(i&&i.compatible===!0){i||(e[o]={});const c=Ue(o);if(!c[n])throw new v(`Invalid config property: ${s}`);try{e[o][n]=c[n](r)}catch(m){throw m instanceof v?m:new v(`Invalid value for ${s}: ${m.message}`)}continue}if(o in he){i||(e[o]={});const c=he[o][n];if(!c)throw new v(`Invalid config property: ${s}`);e[o][n]=c(r)}else{const c=Ue(o);if(!c[n])throw new v(`Invalid config property: ${s}`);e[o]||(e[o]={}),e[o][n]=c[n](r)}}await I.writeFile(He,$t.stringify(e),"utf8")},Fi=async()=>{const t=await Zr();console.log(t)},Ue=t=>({compatible:e=>typeof e=="boolean"?e:e==null?!1:(P("compatible",/^(?:true|false)$/.test(e),"Must be a boolean(true or false)"),e==="true"),stream:e=>typeof e=="boolean"?e:e==null?!1:(P("stream",/^(?:true|false)$/.test(e),"Must be a boolean(true or false)"),e==="true"),url:e=>e?(P(`${t}.url`,/^https?:\/\//.test(e),"Must be a valid URL"),e):"",path:e=>e||"",key:e=>e||"",model:e=>e||"",systemPrompt:u.systemPrompt,systemPromptPath:u.systemPromptPath,codeReviewPromptPath:u.codeReviewPromptPath,timeout:u.timeout,temperature:u.temperature,maxTokens:u.maxTokens,logging:u.logging,locale:u.locale,generate:u.generate,type:u.type,maxLength:u.maxLength,includeBody:u.includeBody,topP:u.topP,codeReview:u.codeReview,disabled:u.disabled,watchMode:u.watchMode});class es extends j{constructor(e){super(e),this.params=e,this.host=Ct,this.model="",this.key="",this.auth="",this.handleError$=s=>{if(s.response&&s.response.data?.error)return O({name:`${this.errorPrefix} ${s.response.data?.error}`,value:s.response.data?.error,isError:!0,disabled:!0});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.setupFetch=(s,r={})=>Js(s,{...r,dispatcher:new Xs({headersTimeout:this.params.config.timeout})}),this.colors={primary:"#FFF",secondary:"#000"},this.model=this.params.keyName,this.serviceName=w.bgHex(this.colors.primary).hex(this.colors.secondary).bold(`[${Ne(this.model)}]`),this.errorPrefix=w.red.bold(`[${Ne(this.model)}]`),this.host=this.params.config.host||Ct,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}`}}})}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);await this.checkIsAvailableOllama();const f=await this.createChatCompletions(d,`Here is the diff: ${s}`);return i&&B(`Ollama_${this.model}`,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}}async checkIsAvailableOllama(){try{const e=new fe({method:"GET",baseURL:`${this.host}`,timeout:this.params.config.timeout});return this.key&&e.setHeaders({Authorization:`${this.auth} ${this.key}`}),(await e.execute()).data}catch(e){throw e.code==="ECONNREFUSED"?new v(`Error connecting to ${this.host}. Please run Ollama or check host`):e}}async createChatCompletions(e,s){const r=this.params.config.stream||!1,o=await this.ollama.chat({model:this.model,messages:[{role:"system",content:e},{role:"user",content:s}],stream:r,keep_alive:this.params.config.timeout,options:{num_ctx:this.params.config.numCtx,temperature:this.params.config.temperature,top_p:this.params.config.topP,seed:Fe(10,1e3)}});if(r){let n="";if(o)for await(const i of o)n+=i.message.content;return n}return o.message.content}}class ts extends j{constructor(e){super(e),this.params=e,this.handleError$=r=>{let o="N/A",n=r.message;r instanceof xe.APIConnectionTimeoutError?n=`Connection timeout: ${r.message}`:r instanceof xe.APIError&&(o=`${r.status}`,n=r.name);const i=`${o} ${n}`;return O({name:`${this.errorPrefix} ${i}`,value:n,isError:!0,disabled:!0})};const s=this.params.keyName||"OPENAI_COMPATIBLE";this.colors=bi(s),this.serviceName=w.bgHex(this.colors.primary).hex(this.colors.secondary).bold(`[${Ne(s)}]`),this.errorPrefix=w.red.bold(`[${Ne(s)}]`),this.openAI=new xe({apiKey:this.params.config.key,baseURL:`${this.params.config.url}${this.params.config.path}`})}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,timeout:d,stream:f=!1}=this.params.config,h=this.params.config.maxTokens,g={...G,locale:l,maxLength:a,type:p,generate:m,systemPrompt:r,systemPromptPath:o,codeReviewPromptPath:n},y=e==="review"?U(g):H(g),b=await this.openAI.chat.completions.create({messages:[{role:"system",content:y},{role:"user",content:`Here is the diff: ${s}`}],model:this.params.config.model,stream:f,max_tokens:h,top_p:this.params.config.topP,temperature:c},{timeout:d});let C="";if(f&&b){const F=b;for await(const K of F){const W=K.choices[0]?.delta?.content||"",me=K.choices[0]?.delta?.reasoning_content||"",Y=`${W}${me}`;C+=Y}}else C=b.choices[0].message.content||"";return i&&B(this.params.keyName,s,y,C,e),e==="review"?this.sanitizeResponse(C):this.parseMessage(C,p,m)}catch(s){throw console.error("generateMessage error >>>",s),s}}}var xt={},At={exports:{}},ye={exports:{}},Mt,rs;function _i(){if(rs)return Mt;rs=1;var t=1e3,e=t*60,s=e*60,r=s*24,o=r*7,n=r*365.25;Mt=function(p,a){a=a||{};var d=typeof p;if(d==="string"&&p.length>0)return i(p);if(d==="number"&&isFinite(p))return a.long?c(p):l(p);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(p))};function i(p){if(p=String(p),!(p.length>100)){var a=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(p);if(a){var d=parseFloat(a[1]),f=(a[2]||"ms").toLowerCase();switch(f){case"years":case"year":case"yrs":case"yr":case"y":return d*n;case"weeks":case"week":case"w":return d*o;case"days":case"day":case"d":return d*r;case"hours":case"hour":case"hrs":case"hr":case"h":return d*s;case"minutes":case"minute":case"mins":case"min":case"m":return d*e;case"seconds":case"second":case"secs":case"sec":case"s":return d*t;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return d;default:return}}}}function l(p){var a=Math.abs(p);return a>=r?Math.round(p/r)+"d":a>=s?Math.round(p/s)+"h":a>=e?Math.round(p/e)+"m":a>=t?Math.round(p/t)+"s":p+"ms"}function c(p){var a=Math.abs(p);return a>=r?m(p,a,r,"day"):a>=s?m(p,a,s,"hour"):a>=e?m(p,a,e,"minute"):a>=t?m(p,a,t,"second"):p+" ms"}function m(p,a,d,f){var h=a>=d*1.5;return Math.round(p/d)+" "+f+(h?"s":"")}return Mt}var St,ss;function os(){if(ss)return St;ss=1;function t(e){r.debug=r,r.default=r,r.coerce=m,r.disable=l,r.enable=n,r.enabled=c,r.humanize=_i(),r.destroy=p,Object.keys(e).forEach(a=>{r[a]=e[a]}),r.names=[],r.skips=[],r.formatters={};function s(a){let d=0;for(let f=0;f<a.length;f++)d=(d<<5)-d+a.charCodeAt(f),d|=0;return r.colors[Math.abs(d)%r.colors.length]}r.selectColor=s;function r(a){let d,f=null,h,g;function y(...b){if(!y.enabled)return;const C=y,F=Number(new Date),K=F-(d||F);C.diff=K,C.prev=d,C.curr=F,d=F,b[0]=r.coerce(b[0]),typeof b[0]!="string"&&b.unshift("%O");let W=0;b[0]=b[0].replace(/%([a-zA-Z%])/g,(Y,Is)=>{if(Y==="%%")return"%";W++;const qt=r.formatters[Is];if(typeof qt=="function"){const ks=b[W];Y=qt.call(C,ks),b.splice(W,1),W--}return Y}),r.formatArgs.call(C,b),(C.log||r.log).apply(C,b)}return y.namespace=a,y.useColors=r.useColors(),y.color=r.selectColor(a),y.extend=o,y.destroy=r.destroy,Object.defineProperty(y,"enabled",{enumerable:!0,configurable:!1,get:()=>f!==null?f:(h!==r.namespaces&&(h=r.namespaces,g=r.enabled(a)),g),set:b=>{f=b}}),typeof r.init=="function"&&r.init(y),y}function o(a,d){const f=r(this.namespace+(typeof d>"u"?":":d)+a);return f.log=this.log,f}function n(a){r.save(a),r.namespaces=a,r.names=[],r.skips=[];const d=(typeof a=="string"?a:"").trim().replace(" ",",").split(",").filter(Boolean);for(const f of d)f[0]==="-"?r.skips.push(f.slice(1)):r.names.push(f)}function i(a,d){let f=0,h=0,g=-1,y=0;for(;f<a.length;)if(h<d.length&&(d[h]===a[f]||d[h]==="*"))d[h]==="*"?(g=h,y=f,h++):(f++,h++);else if(g!==-1)h=g+1,y++,f=y;else return!1;for(;h<d.length&&d[h]==="*";)h++;return h===d.length}function l(){const a=[...r.names,...r.skips.map(d=>"-"+d)].join(",");return r.enable(""),a}function c(a){for(const d of r.skips)if(i(a,d))return!1;for(const d of r.names)if(i(a,d))return!0;return!1}function m(a){return a instanceof Error?a.stack||a.message:a}function p(){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 r.enable(r.load()),r}return St=t,St}ye.exports;var ns;function Di(){return ns||(ns=1,function(t,e){e.formatArgs=r,e.save=o,e.load=n,e.useColors=s,e.storage=i(),e.destroy=(()=>{let c=!1;return()=>{c||(c=!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 s(){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 c;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&&(c=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(c[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function r(c){if(c[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+c[0]+(this.useColors?"%c ":" ")+"+"+t.exports.humanize(this.diff),!this.useColors)return;const m="color: "+this.color;c.splice(1,0,m,"color: inherit");let p=0,a=0;c[0].replace(/%[a-zA-Z%]/g,d=>{d!=="%%"&&(p++,d==="%c"&&(a=p))}),c.splice(a,0,m)}e.log=console.debug||console.log||(()=>{});function o(c){try{c?e.storage.setItem("debug",c):e.storage.removeItem("debug")}catch{}}function n(){let c;try{c=e.storage.getItem("debug")}catch{}return!c&&typeof process<"u"&&"env"in process&&(c=process.env.DEBUG),c}function i(){try{return localStorage}catch{}}t.exports=os()(e);const{formatters:l}=t.exports;l.j=function(c){try{return JSON.stringify(c)}catch(m){return"[UnexpectedJSONParseError]: "+m.message}}}(ye,ye.exports)),ye.exports}var we={exports:{}},Rt,is;function Gi(){return is||(is=1,Rt=(t,e=process.argv)=>{const s=t.startsWith("-")?"":t.length===1?"-":"--",r=e.indexOf(s+t),o=e.indexOf("--");return r!==-1&&(o===-1||r<o)}),Rt}var It,as;function ji(){if(as)return It;as=1;const t=Ze,e=sr,s=Gi(),{env:r}=process;let o;s("no-color")||s("no-colors")||s("color=false")||s("color=never")?o=0:(s("color")||s("colors")||s("color=true")||s("color=always"))&&(o=1),"FORCE_COLOR"in r&&(r.FORCE_COLOR==="true"?o=1:r.FORCE_COLOR==="false"?o=0:o=r.FORCE_COLOR.length===0?1:Math.min(parseInt(r.FORCE_COLOR,10),3));function n(c){return c===0?!1:{level:c,hasBasic:!0,has256:c>=2,has16m:c>=3}}function i(c,m){if(o===0)return 0;if(s("color=16m")||s("color=full")||s("color=truecolor"))return 3;if(s("color=256"))return 2;if(c&&!m&&o===void 0)return 0;const p=o||0;if(r.TERM==="dumb")return p;if(process.platform==="win32"){const a=t.release().split(".");return Number(a[0])>=10&&Number(a[2])>=10586?Number(a[2])>=14931?3:2:1}if("CI"in r)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE"].some(a=>a in r)||r.CI_NAME==="codeship"?1:p;if("TEAMCITY_VERSION"in r)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(r.TEAMCITY_VERSION)?1:0;if(r.COLORTERM==="truecolor")return 3;if("TERM_PROGRAM"in r){const a=parseInt((r.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(r.TERM_PROGRAM){case"iTerm.app":return a>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(r.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(r.TERM)||"COLORTERM"in r?1:p}function l(c){const m=i(c,c&&c.isTTY);return n(m)}return It={supportsColor:l,stdout:n(i(!0,e.isatty(1))),stderr:n(i(!0,e.isatty(2)))},It}we.exports;var cs;function Bi(){return cs||(cs=1,function(t,e){const s=sr,r=Jt;e.init=p,e.log=l,e.formatArgs=n,e.save=c,e.load=m,e.useColors=o,e.destroy=r.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 d=ji();d&&(d.stderr||d).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(d=>/^debug_/i.test(d)).reduce((d,f)=>{const h=f.substring(6).toLowerCase().replace(/_([a-z])/g,(y,b)=>b.toUpperCase());let g=process.env[f];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),d[h]=g,d},{});function o(){return"colors"in e.inspectOpts?!!e.inspectOpts.colors:s.isatty(process.stderr.fd)}function n(d){const{namespace:f,useColors:h}=this;if(h){const g=this.color,y="\x1B[3"+(g<8?g:"8;5;"+g),b=` ${y};1m${f} \x1B[0m`;d[0]=b+d[0].split(`
71
+ `,Ct=(t,e)=>{const s=[];let r="";typeof e=="string"?e={section:e,whitespace:!1}:(e=e||Object.create(null),e.whitespace=e.whitespace===!0);const o=e.whitespace?" = ":"=";for(const n of Object.keys(t)){const i=t[n];if(i&&Array.isArray(i))for(const l of i)r+=ce(n+"[]")+o+ce(l)+He;else i&&typeof i=="object"?s.push(n):r+=ce(n)+o+ce(i)+He}e.section&&r.length&&(r="["+ce(e.section)+"]"+He+r);for(const n of s){const i=Yr(n).join("\\."),l=(e.section?e.section+".":"")+i,{whitespace:a}=e,u=Ct(t[n],{section:l,whitespace:a});r.length&&u.length&&(r+=He),r+=u}return r},Yr=t=>t.replace(/\1/g,"LITERAL\\1LITERAL").replace(/\\\./g,"").split(/\./).map(e=>e.replace(/\1/g,"\\.").replace(/\2LITERAL\\1LITERAL\2/g,"")),Jr=t=>{const e=Object.create(null);let s=e,r=null;const o=/^\[([^\]]*)\]$|^([^=]+)(=(.*))?$/i,n=t.split(/[\r\n]+/g);for(const l of n){if(!l||l.match(/^\s*[;#]/))continue;const a=l.match(o);if(!a)continue;if(a[1]!==void 0){if(r=Ue(a[1]),r==="__proto__"){s=Object.create(null);continue}s=e[r]=e[r]||Object.create(null);continue}const u=Ue(a[2]),f=u.length>2&&u.slice(-2)==="[]",c=f?u.slice(0,-2):u;if(c==="__proto__")continue;const m=a[3]?Ue(a[4]):!0,p=m==="true"||m==="false"||m==="null"?JSON.parse(m):m;f&&(Pt.call(s,c)?Array.isArray(s[c])||(s[c]=[s[c]]):s[c]=[]),Array.isArray(s[c])?s[c].push(p):s[c]=p}const i=[];for(const l of Object.keys(e)){if(!Pt.call(e,l)||typeof e[l]!="object"||Array.isArray(e[l]))continue;const a=Yr(l);s=e;const u=a.pop(),f=u.replace(/\\\./g,".");for(const c of a)c!=="__proto__"&&((!Pt.call(s,c)||typeof s[c]!="object")&&(s[c]=Object.create(null)),s=s[c]);s===e&&f===u||(s[f]=e[l],i.push(l))}for(const l of i)delete e[l];return e},Xr=t=>t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'"),ce=t=>typeof t!="string"||t.match(/[=\r\n]/)||t.match(/^\[/)||t.length>1&&Xr(t)||t!==t.trim()?JSON.stringify(t):t.split(";").join("\\;").split("#").join("\\#"),Ue=(t,e)=>{if(t=(t||"").trim(),Xr(t)){t.charAt(0)==="'"&&(t=t.slice(1,-1));try{t=JSON.parse(t)}catch{}}else{let s=!1,r="";for(let o=0,n=t.length;o<n;o++){const i=t.charAt(o);if(s)"\\;#".indexOf(i)!==-1?r+=i:r+="\\"+i,s=!1;else{if(";#".indexOf(i)!==-1)break;i==="\\"?s=!0:r+=i}}return s&&(r+="\\"),r.trim()}return t};var Ii={parse:Jr,decode:Jr,stringify:Ct,encode:Ct,safe:ce,unsafe:Ue},ge=se(Ii);const Qr=t=>I.lstat(t).then(()=>!0,()=>!1),ki=["","conventional","gitmoji"],Et="http://localhost:11434",{hasOwnProperty:Oi}=Object.prototype,le=(t,e)=>Oi.call(t,e),te=["OPENAI","OLLAMA","HUGGINGFACE","GEMINI","ANTHROPIC","MISTRAL","CODESTRAL","COHERE","GROQ","PERPLEXITY","DEEPSEEK"],Li=t=>{const e=Object.keys(t),s=new Set([...te,...e.filter(r=>/^[A-Z][A-Z0-9_]*$/.test(r))]);return Array.from(s)},$=(t,e,s)=>{if(!e)throw new v(`Invalid config property ${t}: ${s}`)},d={systemPrompt(t){return t||""},systemPromptPath(t){return t||""},codeReviewPromptPath(t){return t||""},timeout(t){if(!t)return 1e4;$("timeout",/^\d+$/.test(t),"Must be an integer");const e=Number(t);return $("timeout",e>=500,"Must be greater than 500ms"),e},temperature(t){if(!t)return .7;$("temperature",/^(2|\d)(\.\d{1,2})?$/.test(t),"Must be decimal between 0 and 2");const e=Number(t);return $("temperature",e>0,"Must be greater than 0"),$("temperature",e<=2,"Must be less than or equal to 2"),e},maxTokens(t){return t?($("maxTokens",/^\d+$/.test(t),"Must be an integer"),Number(t)):1024},logging(t){return typeof t=="boolean"?t:t==null?!0:($("logging",/^(?:true|false)$/.test(t),"Must be a boolean(true or false)"),t==="true")},locale(t){return t?($("locale",t,"Cannot be empty"),$("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;$("generate",/^\d+$/.test(t),"Must be an integer");const e=Number(t);return $("generate",e>0,"Must be greater than 0"),$("generate",e<=5,"Must be less or equal to 5"),e},type(t){return t?($("type",ki.includes(t),"Invalid commit type"),t):"conventional"},maxLength(t){if(!t)return 50;$("maxLength",/^\d+$/.test(t),"Must be an integer");const e=Number(t);return $("maxLength",e>=20,"Must be greater than 20 characters"),e},includeBody(t){return typeof t=="boolean"?t:t==null?!1:($("includeBody",/^(?:true|false)$/.test(t),"Must be a boolean(true or false)"),t==="true")},exclude:t=>t?(typeof t=="string"?t?.split(","):t).map(s=>s.trim()).filter(s=>!!s&&s.length>0):[],topP:t=>{if(!t)return .9;$("topP",/^(1|\d)(\.\d{1,2})?$/.test(t),"Must be decimal between 0 and 1");const e=Number(t);return $("topP",e>0,"Must be greater than 0"),$("topP",e<=1,"Must be less than or equal to 1"),e},codeReview(t){return typeof t=="boolean"?t:t==null?!1:($("codeReview",/^(?:true|false)$/.test(t),"Must be a boolean(true or false)"),t==="true")},disabled(t){return typeof t=="boolean"?t:t==null?!1:($("disabled",/^(?:true|false)$/.test(t),"Must be a boolean(true or false)"),t==="true")},watchMode(t){return typeof t=="boolean"?t:t==null?!1:($("watchMode",/^(?:true|false)$/.test(t),"Must be a boolean(true or false)"),t==="true")}},ye={OPENAI:{key:t=>t||"",model:t=>t||"gpt-4o-mini",url:t=>t?($("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:d.topP,systemPrompt:d.systemPrompt,systemPromptPath:d.systemPromptPath,codeReviewPromptPath:d.codeReviewPromptPath,timeout:d.timeout,temperature:d.temperature,maxTokens:d.maxTokens,logging:d.logging,locale:d.locale,generate:d.generate,type:d.type,maxLength:d.maxLength,includeBody:d.includeBody,codeReview:d.codeReview,disabled:d.disabled,watchMode:d.watchMode},HUGGINGFACE:{cookie:t=>t||"",model:t=>t?($("HUGGINGFACE.model",["CohereForAI/c4ai-command-r-plus","meta-llama/Meta-Llama-3-70B-Instruct","HuggingFaceH4/zephyr-orpo-141b-A35b-v0.1","mistralai/Mixtral-8x7B-Instruct-v0.1","NousResearch/Nous-Hermes-2-Mixtral-8x7B-DPO","01-ai/Yi-1.5-34B-Chat","mistralai/Mistral-7B-Instruct-v0.2","microsoft/Phi-3-mini-4k-instruct"].includes(t),"Invalid model type of HuggingFace chat"),t):"CohereForAI/c4ai-command-r-plus",systemPrompt:d.systemPrompt,systemPromptPath:d.systemPromptPath,codeReviewPromptPath:d.codeReviewPromptPath,logging:d.logging,locale:d.locale,generate:d.generate,type:d.type,maxLength:d.maxLength,includeBody:d.includeBody,codeReview:d.codeReview,disabled:d.disabled,watchMode:d.watchMode},GEMINI:{key:t=>t||"",model:t=>!t||t.length===0?"gemini-2.0-flash":($("GEMINI.model",["gemini-2.5-flash-preview-04-17","gemini-2.5-pro-preview-05-06","gemini-2.0-flash","gemini-2.0-flash-lite","gemini-2.0-flash-preview-image-generation","gemini-1.5-pro","gemini-1.5-flash","gemini-1.5-flash-8b"].includes(t),"Invalid model type of Gemini"),t),systemPrompt:d.systemPrompt,systemPromptPath:d.systemPromptPath,codeReviewPromptPath:d.codeReviewPromptPath,temperature:d.temperature,maxTokens:d.maxTokens,logging:d.logging,locale:d.locale,generate:d.generate,type:d.type,maxLength:d.maxLength,includeBody:d.includeBody,topP:d.topP,codeReview:d.codeReview,disabled:d.disabled,watchMode:d.watchMode},ANTHROPIC:{key:t=>t||"",model:t=>!t||t.length===0?"claude-3-5-haiku-20241022":($("ANTHROPIC.model",["claude-3-7-sonnet-20250219","claude-3-5-sonnet-20241022","claude-3-5-haiku-20241022","claude-3-opus-20240229","claude-3-sonnet-20240229","claude-3-haiku-20240307"].includes(t),"Invalid model type of Anthropic"),t),systemPrompt:d.systemPrompt,systemPromptPath:d.systemPromptPath,codeReviewPromptPath:d.codeReviewPromptPath,temperature:d.temperature,maxTokens:d.maxTokens,logging:d.logging,locale:d.locale,generate:d.generate,type:d.type,maxLength:d.maxLength,includeBody:d.includeBody,topP:d.topP,codeReview:d.codeReview,disabled:d.disabled,watchMode:d.watchMode},MISTRAL:{key:t=>t||"",model:t=>!t||t.length===0?"pixtral-12b-2409":($("MISTRAL.model",["codestral-latest","mistral-large-latest","pixtral-large-latest","ministral-8b-latest","mistral-small-latest","mistral-embed","mistral-moderation-latest"].includes(t),"Invalid model type of Mistral AI"),t),systemPrompt:d.systemPrompt,systemPromptPath:d.systemPromptPath,codeReviewPromptPath:d.codeReviewPromptPath,timeout:d.timeout,temperature:d.temperature,maxTokens:d.maxTokens,logging:d.logging,locale:d.locale,generate:d.generate,type:d.type,maxLength:d.maxLength,includeBody:d.includeBody,topP:d.topP,codeReview:d.codeReview,disabled:d.disabled,watchMode:d.watchMode},CODESTRAL:{key:t=>t||"",model:t=>!t||t.length===0?"codestral-latest":($("CODESTRAL.model",["codestral-latest","codestral-2501"].includes(t),"Invalid model type of Codestral"),t),topP:d.topP,systemPrompt:d.systemPrompt,systemPromptPath:d.systemPromptPath,codeReviewPromptPath:d.codeReviewPromptPath,timeout:d.timeout,temperature:d.temperature,maxTokens:d.maxTokens,logging:d.logging,locale:d.locale,generate:d.generate,type:d.type,maxLength:d.maxLength,includeBody:d.includeBody,codeReview:d.codeReview,disabled:d.disabled,watchMode:d.watchMode},OLLAMA:{model:t=>t?(typeof t=="string"?t?.split(","):t).map(s=>s.trim()).filter(s=>!!s&&s.length>0):[],host:t=>t?($("OLLAMA.host",/^https?:\/\//.test(t),"Must be a valid URL"),t):Et,timeout:t=>{if(!t)return 1e5;$("OLLAMA.timeout",/^\d+$/.test(t),"Must be an integer");const e=Number(t);return $("OLLAMA.timeout",e>=500,"Must be greater than 500ms"),e},auth:t=>t||"",key:t=>t||"",numCtx:t=>{if(!t)return 2048;$("OLLAMA.numCtx",/^\d+$/.test(t),"Must be an integer");const e=Number(t);return $("OLLAMA.numCtx",e>=2048,"Must be greater than 2048"),e},systemPrompt:d.systemPrompt,systemPromptPath:d.systemPromptPath,codeReviewPromptPath:d.codeReviewPromptPath,temperature:d.temperature,logging:d.logging,locale:d.locale,generate:d.generate,type:d.type,maxLength:d.maxLength,includeBody:d.includeBody,topP:d.topP,codeReview:d.codeReview,disabled:d.disabled,watchMode:d.watchMode},COHERE:{key:t=>t||"",model:t=>!t||t.length===0?"command":($("COHERE.model",["command-r7b-12-2024","command-r-plus-08-2024","command-r-plus-04-2024","command-r-plus","command-r-08-2024","command-r-03-2024","command-r","command","command-nightly","command-light","command-light-nightly","c4ai-aya-expanse-8b","c4ai-aya-expanse-32b"].includes(t),"Invalid model type of Cohere"),t),systemPrompt:d.systemPrompt,systemPromptPath:d.systemPromptPath,codeReviewPromptPath:d.codeReviewPromptPath,temperature:d.temperature,maxTokens:d.maxTokens,logging:d.logging,locale:d.locale,generate:d.generate,type:d.type,maxLength:d.maxLength,includeBody:d.includeBody,topP:d.topP,codeReview:d.codeReview,disabled:d.disabled,watchMode:d.watchMode},GROQ:{key:t=>t||"",model:t=>!t||t.length===0?"llama-3.3-70b-versatile":($("GROQ.model",["allam-2-7b","compound-beta","compound-beta-mini","deepseek-r1-distill-llama-70b","distil-whisper-large-v3-en","gemma2-9b-it","llama-3.1-8b-instant","llama-3.3-70b-versatile","llama-guard-3-8b","llama3-70b-8192","llama3-8b-8192","meta-llama/llama-4-maverick-17b-128e-instruct","meta-llama/llama-4-scout-17b-16e-instruct","mistral-saba-24b","playai-tts","playai-tts-arabic","qwen-qwq-32b","whisper-large-v3","whisper-large-v3-turbo"].includes(t),"Invalid model type of Groq"),t),systemPrompt:d.systemPrompt,systemPromptPath:d.systemPromptPath,codeReviewPromptPath:d.codeReviewPromptPath,timeout:d.timeout,temperature:d.temperature,maxTokens:d.maxTokens,logging:d.logging,locale:d.locale,generate:d.generate,type:d.type,maxLength:d.maxLength,includeBody:d.includeBody,topP:d.topP,codeReview:d.codeReview,disabled:d.disabled,watchMode:d.watchMode},PERPLEXITY:{key:t=>t||"",model:t=>!t||t.length===0?"sonar":($("PERPLEXITY.model",["sonar-pro","sonar","llama-3.1-sonar-small-128k-online","llama-3.1-sonar-large-128k-online","llama-3.1-sonar-huge-128k-online"].includes(t),"Invalid model type of Perplexity"),t),topP:d.topP,systemPrompt:d.systemPrompt,systemPromptPath:d.systemPromptPath,codeReviewPromptPath:d.codeReviewPromptPath,timeout:d.timeout,temperature:d.temperature,maxTokens:d.maxTokens,logging:d.logging,locale:d.locale,generate:d.generate,type:d.type,maxLength:d.maxLength,includeBody:d.includeBody,codeReview:d.codeReview,disabled:d.disabled,watchMode:d.watchMode},DEEPSEEK:{key:t=>t||"",model:t=>!t||t.length===0?"deepseek-chat":(console.log(t),$("DEEPSEEK.model",["deepseek-reasoner","deepseek-chat"].includes(t),"Invalid model type of DeepSeek"),t),topP:d.topP,systemPrompt:d.systemPrompt,systemPromptPath:d.systemPromptPath,codeReviewPromptPath:d.codeReviewPromptPath,timeout:d.timeout,temperature:d.temperature,maxTokens:d.maxTokens,logging:d.logging,locale:d.locale,generate:d.generate,type:d.type,maxLength:d.maxLength,includeBody:d.includeBody,codeReview:d.codeReview,disabled:d.disabled,watchMode:d.watchMode}},qe=O.join(Me.homedir(),".aicommit2"),Ti=(t=[])=>{const e={};for(const s of t)if(s.startsWith("--")){const[r,o]=s.slice(2).split("="),[n,i]=r.split(".");n&&i&&n in ye?(e[n]||(e[n]={}),e[n][i]=o):e[r]=o}return e},Zr=async()=>await Qr(qe)?await I.readFile(qe,"utf8"):"",ze=async()=>{const t=await Zr();if(!t)return Object.create(null);let e=ge.parse(t);return le(e,"OLLAMA")&&le(e.OLLAMA,"model")&&(e={...e,OLLAMA:{...e.OLLAMA,model:typeof e.OLLAMA.model=="string"?[e.OLLAMA.model]:e.OLLAMA.model}}),le(e,"exclude")&&(e={...e,exclude:typeof e.exclude=="string"?[e.exclude]:e.exclude}),e},we=async(t,e=[])=>{const s=await ze(),r=Ti(e),o={...t,...r},n={},i=Li(s),l={},a=te.map(f=>({service:f,envKey:`${f}_API_KEY`}));for(const{service:f,envKey:c}of a){const m=process.env[c];m&&(l[f]={key:m})}const u=(f,c)=>{const m=o[`${f}.${c}`]??o[f]?.[c],p=l[f]?.[c],h=s[f]?.[c],g=o[c]??s[c];return m!==void 0?m:p!==void 0?p:h!==void 0?h:g};for(const[f,c]of Object.entries(d)){const m=o[f]??s[f];n[f]=c(m)}for(const f of i){n[f]={};const c=ye[f]||Ke(f);for(const[m,p]of Object.entries(c)){const h=u(f,m);n[f][m]=p(h)}}return n},Ni=async t=>{const e=await ze();for(const[s,r]of t){const[o,n]=s.split(".");if(!n){const a=d[s];if(!a)throw new v(`Invalid config property: ${s}`);e[s]=a(r);continue}if(e[o]||(e[o]={}),te.includes(o)){const a=ye[o][n];if(!a)throw new v(`Invalid config property: ${s}`);e[o][n]=a(r);continue}if(!/^[A-Z][A-Z0-9_]*$/.test(o))throw new v(`Invalid service name: ${o}. Service names must be uppercase letters, numbers, and underscores.`);const l=Ke(o);if(!l[n])throw new v(`Invalid config property for custom service: ${s}`);try{e[o][n]=l[n](r)}catch(a){throw a instanceof v?a:new v(`Invalid value for ${s}: ${a.message}`)}}await I.writeFile(qe,ge.stringify(e),"utf8")},Fi=async t=>{const e=await ze();for(const[s,r]of t){const[o,n]=s.split("."),i=e[o];if(o==="OLLAMA"&&n==="model"){i||(e[o]={});const a=e[o][n]||[];e[o][n]=je([...a,r]);continue}if(i&&i.compatible===!0){i||(e[o]={});const a=Ke(o);if(!a[n])throw new v(`Invalid config property: ${s}`);try{e[o][n]=a[n](r)}catch(u){throw u instanceof v?u:new v(`Invalid value for ${s}: ${u.message}`)}continue}if(o in ye){i||(e[o]={});const a=ye[o][n];if(!a)throw new v(`Invalid config property: ${s}`);e[o][n]=a(r)}else{const a=Ke(o);if(!a[n])throw new v(`Invalid config property: ${s}`);e[o]||(e[o]={}),e[o][n]=a[n](r)}}await I.writeFile(qe,ge.stringify(e),"utf8")},_i=async()=>{const t=await Zr();console.log(t)},Ke=t=>({compatible:e=>typeof e=="boolean"?e:e==null?!1:($("compatible",/^(?:true|false)$/.test(e),"Must be a boolean(true or false)"),e==="true"),stream:e=>typeof e=="boolean"?e:e==null?!1:($("stream",/^(?:true|false)$/.test(e),"Must be a boolean(true or false)"),e==="true"),url:e=>e?($(`${t}.url`,/^https?:\/\//.test(e),"Must be a valid URL"),e):"",path:e=>e||"",key:e=>e||"",model:e=>e||"",systemPrompt:d.systemPrompt,systemPromptPath:d.systemPromptPath,codeReviewPromptPath:d.codeReviewPromptPath,timeout:d.timeout,temperature:d.temperature,maxTokens:d.maxTokens,logging:d.logging,locale:d.locale,generate:d.generate,type:d.type,maxLength:d.maxLength,includeBody:d.includeBody,topP:d.topP,codeReview:d.codeReview,disabled:d.disabled,watchMode:d.watchMode});class es extends j{constructor(e){super(e),this.params=e,this.host=Et,this.model="",this.key="",this.auth="",this.handleError$=s=>{if(s.response&&s.response.data?.error)return L({name:`${this.errorPrefix} ${s.response.data?.error}`,value:s.response.data?.error,isError:!0,disabled:!0});const r=s.message?.replace(/(\r\n|\n|\r)/gm,"")||"An error occurred";return L({name:`${this.errorPrefix} ${r}`,value:r,isError:!0,disabled:!0})},this.setupFetch=(s,r={})=>Xs(s,{...r,dispatcher:new Qs({headersTimeout:this.params.config.timeout})}),this.colors={primary:"#FFF",secondary:"#000"},this.model=this.params.keyName,this.serviceName=w.bgHex(this.colors.primary).hex(this.colors.secondary).bold(`[${De(this.model)}]`),this.errorPrefix=w.red.bold(`[${De(this.model)}]`),this.host=this.params.config.host||Et,this.auth=this.params.config.auth||"Bearer",this.key=this.params.config.key||"",this.ollama=new Js({host:this.host,fetch:this.setupFetch,...this.key&&{headers:{Authorization:`${this.auth} ${this.key}`}}})}generateCommitMessage$(){return M(this.generateMessage("commit")).pipe(A(e=>P(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=>P(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:a,type:u,maxLength:f}=this.params.config,c={...G,locale:l,maxLength:f,type:u,generate:a,systemPrompt:r,systemPromptPath:o,codeReviewPromptPath:n},m=e==="review"?U(c):H(c);await this.checkIsAvailableOllama();const p=await this.createChatCompletions(m,`Here is the diff: ${s}`);return i&&B(`Ollama_${this.model}`,s,m,p,e),e==="review"?this.sanitizeResponse(p):this.parseMessage(p,u,a)}catch(s){const r=s;throw r.code==="ENOTFOUND"?new v(`Error connecting to ${r.hostname} (${r.syscall})`):r}}async checkIsAvailableOllama(){try{const e=new he({method:"GET",baseURL:`${this.host}`,timeout:this.params.config.timeout});return this.key&&e.setHeaders({Authorization:`${this.auth} ${this.key}`}),(await e.execute()).data}catch(e){throw e.code==="ECONNREFUSED"?new v(`Error connecting to ${this.host}. Please run Ollama or check host`):e}}async createChatCompletions(e,s){const r=this.params.config.stream||!1,o=await this.ollama.chat({model:this.model,messages:[{role:"system",content:e},{role:"user",content:s}],stream:r,keep_alive:this.params.config.timeout,options:{num_ctx:this.params.config.numCtx,temperature:this.params.config.temperature,top_p:this.params.config.topP,seed:Ge(10,1e3)}});if(r){let n="";if(o)for await(const i of o)n+=i.message.content;return n}return o.message.content}}class ts extends j{constructor(e){super(e),this.params=e,this.handleError$=r=>{let o="N/A",n=r.message;r instanceof Se.APIConnectionTimeoutError?n=`Connection timeout: ${r.message}`:r instanceof Se.APIError&&(o=`${r.status}`,n=r.name);const i=`${o} ${n}`;return L({name:`${this.errorPrefix} ${i}`,value:n,isError:!0,disabled:!0})};const s=this.params.keyName||"OPENAI_COMPATIBLE";this.colors=$i(s),this.serviceName=w.bgHex(this.colors.primary).hex(this.colors.secondary).bold(`[${De(s)}]`),this.errorPrefix=w.red.bold(`[${De(s)}]`),this.openAI=new Se({apiKey:this.params.config.key,baseURL:`${this.params.config.url}${this.params.config.path}`})}generateCommitMessage$(){return M(this.generateMessage("commit")).pipe(A(e=>P(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=>P(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:a,generate:u,type:f,maxLength:c,timeout:m,stream:p=!1}=this.params.config,h=this.params.config.maxTokens,g={...G,locale:l,maxLength:c,type:f,generate:u,systemPrompt:r,systemPromptPath:o,codeReviewPromptPath:n},y=e==="review"?U(g):H(g),b=await this.openAI.chat.completions.create({messages:[{role:"system",content:y},{role:"user",content:`Here is the diff: ${s}`}],model:this.params.config.model,stream:p,max_tokens:h,top_p:this.params.config.topP,temperature:a},{timeout:m});let C="";if(p&&b){const F=b;for await(const K of F){const W=K.choices[0]?.delta?.content||"",ue=K.choices[0]?.delta?.reasoning_content||"",V=`${W}${ue}`;C+=V}}else C=b.choices[0].message.content||"";return i&&B(this.params.keyName,s,y,C,e),e==="review"?this.sanitizeResponse(C):this.parseMessage(C,f,u)}catch(s){throw console.error("generateMessage error >>>",s),s}}}var xt={},At={exports:{}},ve={exports:{}},Mt,rs;function Di(){if(rs)return Mt;rs=1;var t=1e3,e=t*60,s=e*60,r=s*24,o=r*7,n=r*365.25;Mt=function(f,c){c=c||{};var m=typeof f;if(m==="string"&&f.length>0)return i(f);if(m==="number"&&isFinite(f))return c.long?a(f):l(f);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(f))};function i(f){if(f=String(f),!(f.length>100)){var c=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(f);if(c){var m=parseFloat(c[1]),p=(c[2]||"ms").toLowerCase();switch(p){case"years":case"year":case"yrs":case"yr":case"y":return m*n;case"weeks":case"week":case"w":return m*o;case"days":case"day":case"d":return m*r;case"hours":case"hour":case"hrs":case"hr":case"h":return m*s;case"minutes":case"minute":case"mins":case"min":case"m":return m*e;case"seconds":case"second":case"secs":case"sec":case"s":return m*t;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return m;default:return}}}}function l(f){var c=Math.abs(f);return c>=r?Math.round(f/r)+"d":c>=s?Math.round(f/s)+"h":c>=e?Math.round(f/e)+"m":c>=t?Math.round(f/t)+"s":f+"ms"}function a(f){var c=Math.abs(f);return c>=r?u(f,c,r,"day"):c>=s?u(f,c,s,"hour"):c>=e?u(f,c,e,"minute"):c>=t?u(f,c,t,"second"):f+" ms"}function u(f,c,m,p){var h=c>=m*1.5;return Math.round(f/m)+" "+p+(h?"s":"")}return Mt}var St,ss;function os(){if(ss)return St;ss=1;function t(e){r.debug=r,r.default=r,r.coerce=u,r.disable=l,r.enable=n,r.enabled=a,r.humanize=Di(),r.destroy=f,Object.keys(e).forEach(c=>{r[c]=e[c]}),r.names=[],r.skips=[],r.formatters={};function s(c){let m=0;for(let p=0;p<c.length;p++)m=(m<<5)-m+c.charCodeAt(p),m|=0;return r.colors[Math.abs(m)%r.colors.length]}r.selectColor=s;function r(c){let m,p=null,h,g;function y(...b){if(!y.enabled)return;const C=y,F=Number(new Date),K=F-(m||F);C.diff=K,C.prev=m,C.curr=F,m=F,b[0]=r.coerce(b[0]),typeof b[0]!="string"&&b.unshift("%O");let W=0;b[0]=b[0].replace(/%([a-zA-Z%])/g,(V,ks)=>{if(V==="%%")return"%";W++;const qt=r.formatters[ks];if(typeof qt=="function"){const Os=b[W];V=qt.call(C,Os),b.splice(W,1),W--}return V}),r.formatArgs.call(C,b),(C.log||r.log).apply(C,b)}return y.namespace=c,y.useColors=r.useColors(),y.color=r.selectColor(c),y.extend=o,y.destroy=r.destroy,Object.defineProperty(y,"enabled",{enumerable:!0,configurable:!1,get:()=>p!==null?p:(h!==r.namespaces&&(h=r.namespaces,g=r.enabled(c)),g),set:b=>{p=b}}),typeof r.init=="function"&&r.init(y),y}function o(c,m){const p=r(this.namespace+(typeof m>"u"?":":m)+c);return p.log=this.log,p}function n(c){r.save(c),r.namespaces=c,r.names=[],r.skips=[];const m=(typeof c=="string"?c:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(const p of m)p[0]==="-"?r.skips.push(p.slice(1)):r.names.push(p)}function i(c,m){let p=0,h=0,g=-1,y=0;for(;p<c.length;)if(h<m.length&&(m[h]===c[p]||m[h]==="*"))m[h]==="*"?(g=h,y=p,h++):(p++,h++);else if(g!==-1)h=g+1,y++,p=y;else return!1;for(;h<m.length&&m[h]==="*";)h++;return h===m.length}function l(){const c=[...r.names,...r.skips.map(m=>"-"+m)].join(",");return r.enable(""),c}function a(c){for(const m of r.skips)if(i(c,m))return!1;for(const m of r.names)if(i(c,m))return!0;return!1}function u(c){return c instanceof Error?c.stack||c.message:c}function f(){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 r.enable(r.load()),r}return St=t,St}ve.exports;var ns;function Gi(){return ns||(ns=1,function(t,e){e.formatArgs=r,e.save=o,e.load=n,e.useColors=s,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 s(){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 r(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 u="color: "+this.color;a.splice(1,0,u,"color: inherit");let f=0,c=0;a[0].replace(/%[a-zA-Z%]/g,m=>{m!=="%%"&&(f++,m==="%c"&&(c=f))}),a.splice(c,0,u)}e.log=console.debug||console.log||(()=>{});function o(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=os()(e);const{formatters:l}=t.exports;l.j=function(a){try{return JSON.stringify(a)}catch(u){return"[UnexpectedJSONParseError]: "+u.message}}}(ve,ve.exports)),ve.exports}var be={exports:{}},Rt,is;function ji(){return is||(is=1,Rt=(t,e=process.argv)=>{const s=t.startsWith("-")?"":t.length===1?"-":"--",r=e.indexOf(s+t),o=e.indexOf("--");return r!==-1&&(o===-1||r<o)}),Rt}var It,as;function Bi(){if(as)return It;as=1;const t=Me,e=sr,s=ji(),{env:r}=process;let o;s("no-color")||s("no-colors")||s("color=false")||s("color=never")?o=0:(s("color")||s("colors")||s("color=true")||s("color=always"))&&(o=1),"FORCE_COLOR"in r&&(r.FORCE_COLOR==="true"?o=1:r.FORCE_COLOR==="false"?o=0:o=r.FORCE_COLOR.length===0?1:Math.min(parseInt(r.FORCE_COLOR,10),3));function n(a){return a===0?!1:{level:a,hasBasic:!0,has256:a>=2,has16m:a>=3}}function i(a,u){if(o===0)return 0;if(s("color=16m")||s("color=full")||s("color=truecolor"))return 3;if(s("color=256"))return 2;if(a&&!u&&o===void 0)return 0;const f=o||0;if(r.TERM==="dumb")return f;if(process.platform==="win32"){const c=t.release().split(".");return Number(c[0])>=10&&Number(c[2])>=10586?Number(c[2])>=14931?3:2:1}if("CI"in r)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE"].some(c=>c in r)||r.CI_NAME==="codeship"?1:f;if("TEAMCITY_VERSION"in r)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(r.TEAMCITY_VERSION)?1:0;if(r.COLORTERM==="truecolor")return 3;if("TERM_PROGRAM"in r){const c=parseInt((r.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(r.TERM_PROGRAM){case"iTerm.app":return c>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(r.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(r.TERM)||"COLORTERM"in r?1:f}function l(a){const u=i(a,a&&a.isTTY);return n(u)}return It={supportsColor:l,stdout:n(i(!0,e.isatty(1))),stderr:n(i(!0,e.isatty(2)))},It}be.exports;var cs;function Hi(){return cs||(cs=1,function(t,e){const s=sr,r=Jt;e.init=f,e.log=l,e.formatArgs=n,e.save=a,e.load=u,e.useColors=o,e.destroy=r.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 m=Bi();m&&(m.stderr||m).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(m=>/^debug_/i.test(m)).reduce((m,p)=>{const h=p.substring(6).toLowerCase().replace(/_([a-z])/g,(y,b)=>b.toUpperCase());let g=process.env[p];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),m[h]=g,m},{});function o(){return"colors"in e.inspectOpts?!!e.inspectOpts.colors:s.isatty(process.stderr.fd)}function n(m){const{namespace:p,useColors:h}=this;if(h){const g=this.color,y="\x1B[3"+(g<8?g:"8;5;"+g),b=` ${y};1m${p} \x1B[0m`;m[0]=b+m[0].split(`
72
72
  `).join(`
73
- `+b),d.push(y+"m+"+t.exports.humanize(this.diff)+"\x1B[0m")}else d[0]=i()+f+" "+d[0]}function i(){return e.inspectOpts.hideDate?"":new Date().toISOString()+" "}function l(...d){return process.stderr.write(r.formatWithOptions(e.inspectOpts,...d)+`
74
- `)}function c(d){d?process.env.DEBUG=d:delete process.env.DEBUG}function m(){return process.env.DEBUG}function p(d){d.inspectOpts={};const f=Object.keys(e.inspectOpts);for(let h=0;h<f.length;h++)d.inspectOpts[f[h]]=e.inspectOpts[f[h]]}t.exports=os()(e);const{formatters:a}=t.exports;a.o=function(d){return this.inspectOpts.colors=this.useColors,r.inspect(d,this.inspectOpts).split(`
75
- `).map(f=>f.trim()).join(" ")},a.O=function(d){return this.inspectOpts.colors=this.useColors,r.inspect(d,this.inspectOpts)}}(we,we.exports)),we.exports}typeof process>"u"||process.type==="renderer"||process.browser===!0||process.__nwjs?At.exports=Di():At.exports=Bi();var kt=At.exports,Ot={};Object.defineProperty(Ot,"__esModule",{value:!0});function Hi(t){return function(e,s){return new Promise((r,o)=>{t.call(this,e,s,(n,i)=>{n?o(n):r(i)})})}}Ot.default=Hi;var ls=k&&k.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};const Ui=Vt,qi=ls(kt),zi=ls(Ot),ve=qi.default("agent-base");function Ki(t){return!!t&&typeof t.addRequest=="function"}function Lt(){const{stack:t}=new Error;return typeof t!="string"?!1:t.split(`
76
- `).some(e=>e.indexOf("(https.js:")!==-1||e.indexOf("node:https:")!==-1)}function qe(t,e){return new qe.Agent(t,e)}(function(t){class e extends Ui.EventEmitter{constructor(r,o){super();let n=o;typeof r=="function"?this.callback=r:r&&(n=r),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:Lt()?443:80}set defaultPort(r){this.explicitDefaultPort=r}get protocol(){return typeof this.explicitProtocol=="string"?this.explicitProtocol:Lt()?"https:":"http:"}set protocol(r){this.explicitProtocol=r}callback(r,o,n){throw new Error('"agent-base" has no default implementation, you must subclass and override `callback()`')}addRequest(r,o){const n=Object.assign({},o);typeof n.secureEndpoint!="boolean"&&(n.secureEndpoint=Lt()),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,r._last=!0,r.shouldKeepAlive=!1;let i=!1,l=null;const c=n.timeout||this.timeout,m=f=>{r._hadError||(r.emit("error",f),r._hadError=!0)},p=()=>{l=null,i=!0;const f=new Error(`A "socket" was not created for HTTP request before ${c}ms`);f.code="ETIMEOUT",m(f)},a=f=>{i||(l!==null&&(clearTimeout(l),l=null),m(f))},d=f=>{if(i)return;if(l!=null&&(clearTimeout(l),l=null),Ki(f)){ve("Callback returned another Agent instance %o",f.constructor.name),f.addRequest(r,n);return}if(f){f.once("free",()=>{this.freeSocket(f,n)}),r.onSocket(f);return}const h=new Error(`no Duplex stream was returned to agent-base for \`${r.method} ${r.path}\``);m(h)};if(typeof this.callback!="function"){m(new Error("`callback` is not defined"));return}this.promisifiedCallback||(this.callback.length>=3?(ve("Converting legacy callback function to promise"),this.promisifiedCallback=zi.default(this.callback)):this.promisifiedCallback=this.callback),typeof c=="number"&&c>0&&(l=setTimeout(p,c)),"port"in n&&typeof n.port!="number"&&(n.port=Number(n.port));try{ve("Resolving socket for %o request: %o",n.protocol,`${r.method} ${r.path}`),Promise.resolve(this.promisifiedCallback(r,n)).then(d,a)}catch(f){Promise.reject(f).catch(a)}}freeSocket(r,o){ve("Freeing socket %o %o",r.constructor.name,o),r.destroy()}destroy(){ve("Destroying agent %o",this.constructor.name)}}t.Agent=e,t.prototype=t.Agent.prototype})(qe||(qe={}));var Wi=qe,Tt={},Yi=k&&k.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Tt,"__esModule",{value:!0});const Vi=Yi(kt),be=Vi.default("https-proxy-agent:parse-proxy-response");function Ji(t){return new Promise((e,s)=>{let r=0;const o=[];function n(){const a=t.read();a?p(a):t.once("readable",n)}function i(){t.removeListener("end",c),t.removeListener("error",m),t.removeListener("close",l),t.removeListener("readable",n)}function l(a){be("onclose had error %o",a)}function c(){be("onend")}function m(a){i(),be("onerror %o",a),s(a)}function p(a){o.push(a),r+=a.length;const d=Buffer.concat(o,r);if(d.indexOf(`\r
73
+ `+b),m.push(y+"m+"+t.exports.humanize(this.diff)+"\x1B[0m")}else m[0]=i()+p+" "+m[0]}function i(){return e.inspectOpts.hideDate?"":new Date().toISOString()+" "}function l(...m){return process.stderr.write(r.formatWithOptions(e.inspectOpts,...m)+`
74
+ `)}function a(m){m?process.env.DEBUG=m:delete process.env.DEBUG}function u(){return process.env.DEBUG}function f(m){m.inspectOpts={};const p=Object.keys(e.inspectOpts);for(let h=0;h<p.length;h++)m.inspectOpts[p[h]]=e.inspectOpts[p[h]]}t.exports=os()(e);const{formatters:c}=t.exports;c.o=function(m){return this.inspectOpts.colors=this.useColors,r.inspect(m,this.inspectOpts).split(`
75
+ `).map(p=>p.trim()).join(" ")},c.O=function(m){return this.inspectOpts.colors=this.useColors,r.inspect(m,this.inspectOpts)}}(be,be.exports)),be.exports}typeof process>"u"||process.type==="renderer"||process.browser===!0||process.__nwjs?At.exports=Gi():At.exports=Hi();var kt=At.exports,Ot={};Object.defineProperty(Ot,"__esModule",{value:!0});function Ui(t){return function(e,s){return new Promise((r,o)=>{t.call(this,e,s,(n,i)=>{n?o(n):r(i)})})}}Ot.default=Ui;var ls=k&&k.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};const qi=Yt,zi=ls(kt),Ki=ls(Ot),$e=zi.default("agent-base");function Wi(t){return!!t&&typeof t.addRequest=="function"}function Lt(){const{stack:t}=new Error;return typeof t!="string"?!1:t.split(`
76
+ `).some(e=>e.indexOf("(https.js:")!==-1||e.indexOf("node:https:")!==-1)}function We(t,e){return new We.Agent(t,e)}(function(t){class e extends qi.EventEmitter{constructor(r,o){super();let n=o;typeof r=="function"?this.callback=r:r&&(n=r),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:Lt()?443:80}set defaultPort(r){this.explicitDefaultPort=r}get protocol(){return typeof this.explicitProtocol=="string"?this.explicitProtocol:Lt()?"https:":"http:"}set protocol(r){this.explicitProtocol=r}callback(r,o,n){throw new Error('"agent-base" has no default implementation, you must subclass and override `callback()`')}addRequest(r,o){const n=Object.assign({},o);typeof n.secureEndpoint!="boolean"&&(n.secureEndpoint=Lt()),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,r._last=!0,r.shouldKeepAlive=!1;let i=!1,l=null;const a=n.timeout||this.timeout,u=p=>{r._hadError||(r.emit("error",p),r._hadError=!0)},f=()=>{l=null,i=!0;const p=new Error(`A "socket" was not created for HTTP request before ${a}ms`);p.code="ETIMEOUT",u(p)},c=p=>{i||(l!==null&&(clearTimeout(l),l=null),u(p))},m=p=>{if(i)return;if(l!=null&&(clearTimeout(l),l=null),Wi(p)){$e("Callback returned another Agent instance %o",p.constructor.name),p.addRequest(r,n);return}if(p){p.once("free",()=>{this.freeSocket(p,n)}),r.onSocket(p);return}const h=new Error(`no Duplex stream was returned to agent-base for \`${r.method} ${r.path}\``);u(h)};if(typeof this.callback!="function"){u(new Error("`callback` is not defined"));return}this.promisifiedCallback||(this.callback.length>=3?($e("Converting legacy callback function to promise"),this.promisifiedCallback=Ki.default(this.callback)):this.promisifiedCallback=this.callback),typeof a=="number"&&a>0&&(l=setTimeout(f,a)),"port"in n&&typeof n.port!="number"&&(n.port=Number(n.port));try{$e("Resolving socket for %o request: %o",n.protocol,`${r.method} ${r.path}`),Promise.resolve(this.promisifiedCallback(r,n)).then(m,c)}catch(p){Promise.reject(p).catch(c)}}freeSocket(r,o){$e("Freeing socket %o %o",r.constructor.name,o),r.destroy()}destroy(){$e("Destroying agent %o",this.constructor.name)}}t.Agent=e,t.prototype=t.Agent.prototype})(We||(We={}));var Vi=We,Tt={},Yi=k&&k.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Tt,"__esModule",{value:!0});const Ji=Yi(kt),Pe=Ji.default("https-proxy-agent:parse-proxy-response");function Xi(t){return new Promise((e,s)=>{let r=0;const o=[];function n(){const c=t.read();c?f(c):t.once("readable",n)}function i(){t.removeListener("end",a),t.removeListener("error",u),t.removeListener("close",l),t.removeListener("readable",n)}function l(c){Pe("onclose had error %o",c)}function a(){Pe("onend")}function u(c){i(),Pe("onerror %o",c),s(c)}function f(c){o.push(c),r+=c.length;const m=Buffer.concat(o,r);if(m.indexOf(`\r
77
77
  \r
78
- `)===-1){be("have not received end of HTTP headers yet..."),n();return}const h=d.toString("ascii",0,d.indexOf(`\r
79
- `)),g=+h.split(" ")[1];be("got proxy server response: %o",h),e({statusCode:g,buffered:d})}t.on("error",m),t.on("close",l),t.on("end",c),n()})}Tt.default=Ji;var Xi=k&&k.__awaiter||function(t,e,s,r){function o(n){return n instanceof s?n:new s(function(i){i(n)})}return new(s||(s=Promise))(function(n,i){function l(p){try{m(r.next(p))}catch(a){i(a)}}function c(p){try{m(r.throw(p))}catch(a){i(a)}}function m(p){p.done?n(p.value):o(p.value).then(l,c)}m((r=r.apply(t,e||[])).next())})},le=k&&k.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(xt,"__esModule",{value:!0});const ms=le(eo),us=le(to),Qi=le(ro),Zi=le(Yt),ea=le(kt),ta=Wi,ra=le(Tt),Pe=ea.default("https-proxy-agent:agent");class sa extends ta.Agent{constructor(e){let s;if(typeof e=="string"?s=Qi.default.parse(e):s=e,!s)throw new Error("an HTTP(S) proxy server `host` and `port` must be specified!");Pe("creating new HttpsProxyAgent instance: %o",s),super(s);const r=Object.assign({},s);this.secureProxy=s.secureProxy||ia(r.protocol),r.host=r.hostname||r.host,typeof r.port=="string"&&(r.port=parseInt(r.port,10)),!r.port&&r.host&&(r.port=this.secureProxy?443:80),this.secureProxy&&!("ALPNProtocols"in r)&&(r.ALPNProtocols=["http 1.1"]),r.host&&r.path&&(delete r.path,delete r.pathname),this.proxy=r}callback(e,s){return Xi(this,void 0,void 0,function*(){const{proxy:r,secureProxy:o}=this;let n;o?(Pe("Creating `tls.Socket`: %o",r),n=us.default.connect(r)):(Pe("Creating `net.Socket`: %o",r),n=ms.default.connect(r));const i=Object.assign({},r.headers);let c=`CONNECT ${`${s.host}:${s.port}`} HTTP/1.1\r
80
- `;r.auth&&(i["Proxy-Authorization"]=`Basic ${Buffer.from(r.auth).toString("base64")}`);let{host:m,port:p,secureEndpoint:a}=s;na(p,a)||(m+=`:${p}`),i.Host=m,i.Connection="close";for(const y of Object.keys(i))c+=`${y}: ${i[y]}\r
81
- `;const d=ra.default(n);n.write(`${c}\r
82
- `);const{statusCode:f,buffered:h}=yield d;if(f===200){if(e.once("socket",oa),s.secureEndpoint){Pe("Upgrading socket connection to TLS");const y=s.servername||s.host;return us.default.connect(Object.assign(Object.assign({},aa(s,"host","hostname","path","port")),{socket:n,servername:y}))}return n}n.destroy();const g=new ms.default.Socket({writable:!1});return g.readable=!0,e.once("socket",y=>{Pe("replaying proxy buffer for failed request"),Zi.default(y.listenerCount("data")>0),y.push(h),y.push(null)}),g})}}xt.default=sa;function oa(t){t.resume()}function na(t,e){return!!(!e&&t===80||e&&t===443)}function ia(t){return typeof t=="string"?/^https:?$/i.test(t):!1}function aa(t,...e){const s={};let r;for(r in t)e.includes(r)||(s[r]=t[r]);return s}var ca=k&&k.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};const Nt=ca(xt);function Ft(t){return new Nt.default(t)}(function(t){t.HttpsProxyAgent=Nt.default,t.prototype=Nt.default.prototype})(Ft||(Ft={}));var la=Ft,ma=se(la);const ua=async(t,e,s,r,o,n,i)=>new Promise((l,c)=>{const m=JSON.stringify(r),a=(t.protocol.includes("https")?Zs:Qs).request({port:i||void 0,hostname:t.hostname,path:e,method:"POST",headers:{"Content-Type":"application/json","Content-Length":Buffer.byteLength(m),...s},timeout:o,agent:n?ma(n):void 0},d=>{const f=[];d.on("data",h=>f.push(h)),d.on("end",()=>{l({request:a,response:d,data:Buffer.concat(f).toString()})})});a.on("error",c),a.on("timeout",()=>{a.destroy(),c(new v(`Time out error: request took over ${o}ms. Try increasing the \`timeout\` config`))}),a.write(m),a.end()}),da=async(t,e,s,r,o,n)=>{const i=new URL(t),{response:l,data:c}=await ua(i,e,{Authorization:`Bearer ${s}`},r,o,n);if(!l.statusCode||l.statusCode<200||l.statusCode>299){let m=`API Error: ${l.statusCode} - ${l.statusMessage}`;throw c&&(m+=`
78
+ `)===-1){Pe("have not received end of HTTP headers yet..."),n();return}const h=m.toString("ascii",0,m.indexOf(`\r
79
+ `)),g=+h.split(" ")[1];Pe("got proxy server response: %o",h),e({statusCode:g,buffered:m})}t.on("error",u),t.on("close",l),t.on("end",a),n()})}Tt.default=Xi;var Qi=k&&k.__awaiter||function(t,e,s,r){function o(n){return n instanceof s?n:new s(function(i){i(n)})}return new(s||(s=Promise))(function(n,i){function l(f){try{u(r.next(f))}catch(c){i(c)}}function a(f){try{u(r.throw(f))}catch(c){i(c)}}function u(f){f.done?n(f.value):o(f.value).then(l,a)}u((r=r.apply(t,e||[])).next())})},me=k&&k.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(xt,"__esModule",{value:!0});const ms=me(to),us=me(ro),Zi=me(so),ea=me(Vt),ta=me(kt),ra=Vi,sa=me(Tt),Ce=ta.default("https-proxy-agent:agent");class oa extends ra.Agent{constructor(e){let s;if(typeof e=="string"?s=Zi.default.parse(e):s=e,!s)throw new Error("an HTTP(S) proxy server `host` and `port` must be specified!");Ce("creating new HttpsProxyAgent instance: %o",s),super(s);const r=Object.assign({},s);this.secureProxy=s.secureProxy||aa(r.protocol),r.host=r.hostname||r.host,typeof r.port=="string"&&(r.port=parseInt(r.port,10)),!r.port&&r.host&&(r.port=this.secureProxy?443:80),this.secureProxy&&!("ALPNProtocols"in r)&&(r.ALPNProtocols=["http 1.1"]),r.host&&r.path&&(delete r.path,delete r.pathname),this.proxy=r}callback(e,s){return Qi(this,void 0,void 0,function*(){const{proxy:r,secureProxy:o}=this;let n;o?(Ce("Creating `tls.Socket`: %o",r),n=us.default.connect(r)):(Ce("Creating `net.Socket`: %o",r),n=ms.default.connect(r));const i=Object.assign({},r.headers);let a=`CONNECT ${`${s.host}:${s.port}`} HTTP/1.1\r
80
+ `;r.auth&&(i["Proxy-Authorization"]=`Basic ${Buffer.from(r.auth).toString("base64")}`);let{host:u,port:f,secureEndpoint:c}=s;ia(f,c)||(u+=`:${f}`),i.Host=u,i.Connection="close";for(const y of Object.keys(i))a+=`${y}: ${i[y]}\r
81
+ `;const m=sa.default(n);n.write(`${a}\r
82
+ `);const{statusCode:p,buffered:h}=yield m;if(p===200){if(e.once("socket",na),s.secureEndpoint){Ce("Upgrading socket connection to TLS");const y=s.servername||s.host;return us.default.connect(Object.assign(Object.assign({},ca(s,"host","hostname","path","port")),{socket:n,servername:y}))}return n}n.destroy();const g=new ms.default.Socket({writable:!1});return g.readable=!0,e.once("socket",y=>{Ce("replaying proxy buffer for failed request"),ea.default(y.listenerCount("data")>0),y.push(h),y.push(null)}),g})}}xt.default=oa;function na(t){t.resume()}function ia(t,e){return!!(!e&&t===80||e&&t===443)}function aa(t){return typeof t=="string"?/^https:?$/i.test(t):!1}function ca(t,...e){const s={};let r;for(r in t)e.includes(r)||(s[r]=t[r]);return s}var la=k&&k.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};const Nt=la(xt);function Ft(t){return new Nt.default(t)}(function(t){t.HttpsProxyAgent=Nt.default,t.prototype=Nt.default.prototype})(Ft||(Ft={}));var ma=Ft,ua=se(ma);const da=async(t,e,s,r,o,n,i)=>new Promise((l,a)=>{const u=JSON.stringify(r),c=(t.protocol.includes("https")?eo:Zs).request({port:i||void 0,hostname:t.hostname,path:e,method:"POST",headers:{"Content-Type":"application/json","Content-Length":Buffer.byteLength(u),...s},timeout:o,agent:n?ua(n):void 0},m=>{const p=[];m.on("data",h=>p.push(h)),m.on("end",()=>{l({request:c,response:m,data:Buffer.concat(p).toString()})})});c.on("error",a),c.on("timeout",()=>{c.destroy(),a(new v(`Time out error: request took over ${o}ms. Try increasing the \`timeout\` config`))}),c.write(u),c.end()}),fa=async(t,e,s,r,o,n)=>{const i=new URL(t),{response:l,data:a}=await da(i,e,{Authorization:`Bearer ${s}`},r,o,n);if(!l.statusCode||l.statusCode<200||l.statusCode>299){let u=`API Error: ${l.statusCode} - ${l.statusMessage}`;throw a&&(u+=`
83
83
 
84
- ${c}`),l.statusCode===500&&(m+=`
84
+ ${a}`),l.statusCode===500&&(u+=`
85
85
 
86
- Check the API status: ${t}`),new v(m)}return JSON.parse(c)},ds=t=>t.trim(),pa=async(t,e,s,r,o,n,i,l,c,m,p,a,d,f)=>{try{const h={model:o,messages:[{role:"system",content:p},{role:"user",content:`Here is the diff: ${n}`}],temperature:c,max_tokens:l,stream:!1,n:1,top_p:m,frequency_penalty:0,presence_penalty:0},g=await da(e,s,r,h,i,f),y=g.choices.filter(b=>b.message?.content).map(b=>ds(b.message.content)).join();return a&&B(t,n,p,y,d),g.choices.filter(b=>b.message?.content).map(b=>ds(b.message.content))}catch(h){const g=h;throw g.code==="ENOTFOUND"?new v(`Error connecting to ${g.hostname} (${g.syscall})`):g}};class ps extends j{constructor(e){super(e),this.params=e,this.handleError$=s=>{let r="An error occurred";if(s.message){r=s.message.split(`
87
- `)[0];const o=this.extractJSONFromError(s.message);r+=`: ${o.error.message}`}return O({name:`${this.errorPrefix} ${r}`,value:r,isError:!0,disabled:!0})},this.colors={primary:"#74AA9C",secondary:"#FFF"},this.serviceName=w.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[ChatGPT]"),this.errorPrefix=w.red.bold("[ChatGPT]")}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$))}extractJSONFromError(e){const s=/[{[]{1}([,:{}[\]0-9.\-+Eaeflnr-u \n\r\t]|".*?")+[}\]]{1}/gis,r=e.match(s);return r?Object.assign({},...r.map(o=>JSON.parse(o))):{error:{message:"Unknown error"}}}async generateMessage(e){const s=this.params.stagedDiff.diff,{systemPrompt:r,systemPromptPath:o,codeReviewPromptPath:n,temperature:i,logging:l,locale:c,generate:m,type:p,maxLength:a,proxy:d,maxTokens:f,timeout: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=await pa("ChatGPT",this.params.config.url,this.params.config.path,this.params.config.key,this.params.config.model,s,h,f,i,this.params.config.topP,y,l,e,d);return _e(e==="review"?b.map(C=>this.sanitizeResponse(C)):b.map(C=>this.parseMessage(C,p,m)))}}class fs extends j{constructor(e){super(e),this.params=e,this.host="https://api.perplexity.ai",this.apiKey="",this.handleError$=s=>{let r="An error occurred";if(s.message){r=s.message.split(`
88
- `)[0];const o=this.extractJSONFromError(s.message);r+=`: ${o.error.message}`}return O({name:`${this.errorPrefix} ${r}`,value:r,isError:!0,disabled:!0})},this.colors={primary:"#20808D",secondary:"#FFF"},this.serviceName=w.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[Perplexity]"),this.errorPrefix=w.red.bold("[Perplexity]"),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$))}extractJSONFromError(e){const s=/[{[]{1}([,:{}[\]0-9.\-+Eaeflnr-u \n\r\t]|".*?")+[}\]]{1}/gis,r=e.match(s);return r?Object.assign({},...r.map(o=>JSON.parse(o))):{error:{message:"Unknown error"}}}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),f=await this.createChatCompletions(d,s);return i&&B("Perplexity",s,d,f,e),this.parseMessage(f,m,c)}catch(s){const r=s;throw r.code==="ENOTFOUND"?new v(`Error connecting to ${r.hostname} (${r.syscall})`):r}}async createChatCompletions(e,s){const o=(await new fe({method:"POST",baseURL:`${this.host}/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: ${s}`}],temperature:this.params.config.temperature,top_p:this.params.config.topP,max_tokens:this.params.config.maxTokens,stream:!1}).execute()).data;if(!o.choices||o.choices.length===0||!o.choices[0].message?.content)throw new Error("No Content on response. Please open a Bug report");return o.choices[0].message.content}}class ze{constructor(e,s){this.config=e,this.stagedDiff=s}createCommitMsgRequests$(e){return $(e).pipe(Ee(s=>{const r=this.config[s];if(r.compatible)return R.create(ts,{config:{...r,url:r.url||"",path:r.path||""},stagedDiff:this.stagedDiff,keyName:s}).generateCommitMessage$();switch(s){case"OPENAI":return R.create(ps,{config:this.config.OPENAI,stagedDiff:this.stagedDiff,keyName:s}).generateCommitMessage$();case"GEMINI":return R.create(zr,{config:this.config.GEMINI,stagedDiff:this.stagedDiff,keyName:s}).generateCommitMessage$();case"ANTHROPIC":return R.create(Br,{config:this.config.ANTHROPIC,stagedDiff:this.stagedDiff,keyName:s}).generateCommitMessage$();case"HUGGINGFACE":return R.create(Wr,{config:this.config.HUGGINGFACE,stagedDiff:this.stagedDiff,keyName:s}).generateCommitMessage$();case"MISTRAL":return R.create(Yr,{config:this.config.MISTRAL,stagedDiff:this.stagedDiff,keyName:s}).generateCommitMessage$();case"CODESTRAL":return R.create(Hr,{config:this.config.CODESTRAL,stagedDiff:this.stagedDiff,keyName:s}).generateCommitMessage$();case"OLLAMA":return $(this.config.OLLAMA.model).pipe(Ee(n=>R.create(es,{config:this.config.OLLAMA,keyName:n,stagedDiff:this.stagedDiff}).generateCommitMessage$()));case"COHERE":return R.create(Ur,{config:this.config.COHERE,stagedDiff:this.stagedDiff,keyName:s}).generateCommitMessage$();case"GROQ":return R.create(Kr,{config:this.config.GROQ,stagedDiff:this.stagedDiff,keyName:s}).generateCommitMessage$();case"PERPLEXITY":return R.create(fs,{config:this.config.PERPLEXITY,stagedDiff:this.stagedDiff,keyName:s}).generateCommitMessage$();case"DEEPSEEK":return R.create(qr,{config:this.config.DEEPSEEK,stagedDiff:this.stagedDiff,keyName:s}).generateCommitMessage$();default:const o=w.red.bold(`[${s}]`);return O({name:o+" Invalid AI type",value:"Invalid AI type",isError:!0,disabled:!0})}}),x(s=>{const r=w.red.bold("[UNKNOWN]");return O({name:r+` ${s.message||""}`,value:"Unknown error",isError:!0,disabled:!0})}))}createCodeReviewRequests$(e){return $(e).pipe(Ee(s=>{const r=this.config[s];if(r.compatible)return R.create(ts,{config:{...r,url:r.url||"",path:r.path||""},stagedDiff:this.stagedDiff,keyName:s}).generateCodeReview$();switch(s){case"OPENAI":return R.create(ps,{config:this.config.OPENAI,stagedDiff:this.stagedDiff,keyName:s}).generateCodeReview$();case"GEMINI":return R.create(zr,{config:this.config.GEMINI,stagedDiff:this.stagedDiff,keyName:s}).generateCodeReview$();case"ANTHROPIC":return R.create(Br,{config:this.config.ANTHROPIC,stagedDiff:this.stagedDiff,keyName:s}).generateCodeReview$();case"HUGGINGFACE":return R.create(Wr,{config:this.config.HUGGINGFACE,stagedDiff:this.stagedDiff,keyName:s}).generateCodeReview$();case"MISTRAL":return R.create(Yr,{config:this.config.MISTRAL,stagedDiff:this.stagedDiff,keyName:s}).generateCodeReview$();case"CODESTRAL":return R.create(Hr,{config:this.config.CODESTRAL,stagedDiff:this.stagedDiff,keyName:s}).generateCodeReview$();case"OLLAMA":return $(this.config.OLLAMA.model).pipe(Ee(n=>R.create(es,{config:this.config.OLLAMA,keyName:n,stagedDiff:this.stagedDiff}).generateCodeReview$()));case"COHERE":return R.create(Ur,{config:this.config.COHERE,stagedDiff:this.stagedDiff,keyName:s}).generateCodeReview$();case"GROQ":return R.create(Kr,{config:this.config.GROQ,stagedDiff:this.stagedDiff,keyName:s}).generateCodeReview$();case"PERPLEXITY":return R.create(fs,{config:this.config.PERPLEXITY,stagedDiff:this.stagedDiff,keyName:s}).generateCodeReview$();case"DEEPSEEK":return R.create(qr,{config:this.config.DEEPSEEK,stagedDiff:this.stagedDiff,keyName:s}).generateCodeReview$();default:const o=w.red.bold(`[${s}]`);return O({name:o+" Invalid AI type",value:"Invalid AI type",isError:!0,disabled:!0})}}),x(s=>{const r=w.red.bold("[UNKNOWN]");return O({name:r+` ${s.message||""}`,value:"Unknown error",isError:!0,disabled:!0})}))}}const _t=async()=>{const{stdout:t,failed:e}=await ee("git",["rev-parse","--show-toplevel"],{reject:!1});if(e)throw new v("The current directory must be a Git repository!");return t},J=t=>`:(exclude)${t}`,Ke=["package-lock.json","pnpm-lock.yaml","*.lock","*.lockb","*.gif","*.png"].map(J),Dt=async(t,e)=>{const s=["diff","--cached","--diff-algorithm=minimal"],{stdout:r}=await ee("git",[...s,"--name-only",...Ke,...t?t.map(J):[],...e?e.map(J):[]]);if(!r)return null;const{stdout:o}=await ee("git",[...s,...Ke,...t?t.map(J):[]]);return{files:r.split(`
89
- `),diff:o}},fa=t=>`Detected ${t.length.toLocaleString()} staged file${t.length>1?"s":""}`,ha=async(t,e,s)=>{const r=["diff-tree","-r","--no-commit-id","--name-only",t],{stdout:o}=await ee("git",[...r,...Ke,...e?e.map(J):[],...s?s.map(J):[]]);if(!o)return null;const{stdout:n}=await ee("git",["show",t,"--",...Ke,...e?e.map(J):[],...s?s.map(J):[]]);return{files:o.split(`
90
- `).filter(Boolean),diff:n}};class X{constructor(){this.title="aicommit2"}printTitle(){console.log(no.textSync(this.title,{font:"Small"}))}showLoader(e){if(this.loader){this.loader.text=e;return}this.loader=Qe(e).start()}stopLoader(){this.loader?.stop(),this.loader=void 0}displaySpinner(e){return Qe(e).start()}stopSpinner(e){e.stop(),e.clear()}printStagedFiles(e){console.log(w.bold.green("\u2714 ")+w.bold(`${fa(e.files)}:`)),console.log(`${e.files.map(s=>` ${s}`).join(`
86
+ Check the API status: ${t}`),new v(u)}return JSON.parse(a)},ds=t=>t.trim(),pa=async(t,e,s,r,o,n,i,l,a,u,f,c,m,p)=>{try{const h={model:o,messages:[{role:"system",content:f},{role:"user",content:`Here is the diff: ${n}`}],temperature:a,max_tokens:l,stream:!1,n:1,top_p:u,frequency_penalty:0,presence_penalty:0},g=await fa(e,s,r,h,i,p),y=g.choices.filter(b=>b.message?.content).map(b=>ds(b.message.content)).join();return c&&B(t,n,f,y,m),g.choices.filter(b=>b.message?.content).map(b=>ds(b.message.content))}catch(h){const g=h;throw g.code==="ENOTFOUND"?new v(`Error connecting to ${g.hostname} (${g.syscall})`):g}};class fs extends j{constructor(e){super(e),this.params=e,this.handleError$=s=>{let r="An error occurred";if(s.message){r=s.message.split(`
87
+ `)[0];const o=this.extractJSONFromError(s.message);r+=`: ${o.error.message}`}return L({name:`${this.errorPrefix} ${r}`,value:r,isError:!0,disabled:!0})},this.colors={primary:"#74AA9C",secondary:"#FFF"},this.serviceName=w.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[ChatGPT]"),this.errorPrefix=w.red.bold("[ChatGPT]")}generateCommitMessage$(){return M(this.generateMessage("commit")).pipe(A(e=>P(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=>P(e)),E(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),x(this.handleError$))}extractJSONFromError(e){const s=/[{[]{1}([,:{}[\]0-9.\-+Eaeflnr-u \n\r\t]|".*?")+[}\]]{1}/gis,r=e.match(s);return r?Object.assign({},...r.map(o=>JSON.parse(o))):{error:{message:"Unknown error"}}}async generateMessage(e){const s=this.params.stagedDiff.diff,{systemPrompt:r,systemPromptPath:o,codeReviewPromptPath:n,temperature:i,logging:l,locale:a,generate:u,type:f,maxLength:c,proxy:m,maxTokens:p,timeout:h}=this.params.config,g={...G,locale:a,maxLength:c,type:f,generate:u,systemPrompt:r,systemPromptPath:o,codeReviewPromptPath:n},y=e==="review"?U(g):H(g),b=await pa("ChatGPT",this.params.config.url,this.params.config.path,this.params.config.key,this.params.config.model,s,h,p,i,this.params.config.topP,y,l,e,m);return je(e==="review"?b.map(C=>this.sanitizeResponse(C)):b.map(C=>this.parseMessage(C,f,u)))}}class ps extends j{constructor(e){super(e),this.params=e,this.host="https://api.perplexity.ai",this.apiKey="",this.handleError$=s=>{let r="An error occurred";if(s.message){r=s.message.split(`
88
+ `)[0];const o=this.extractJSONFromError(s.message);r+=`: ${o.error.message}`}return L({name:`${this.errorPrefix} ${r}`,value:r,isError:!0,disabled:!0})},this.colors={primary:"#20808D",secondary:"#FFF"},this.serviceName=w.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[Perplexity]"),this.errorPrefix=w.red.bold("[Perplexity]"),this.apiKey=this.params.config.key}generateCommitMessage$(){return M(this.generateMessage("commit")).pipe(A(e=>P(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=>P(e)),E(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),x(this.handleError$))}extractJSONFromError(e){const s=/[{[]{1}([,:{}[\]0-9.\-+Eaeflnr-u \n\r\t]|".*?")+[}\]]{1}/gis,r=e.match(s);return r?Object.assign({},...r.map(o=>JSON.parse(o))):{error:{message:"Unknown error"}}}async generateMessage(e){try{const s=this.params.stagedDiff.diff,{systemPrompt:r,systemPromptPath:o,codeReviewPromptPath:n,logging:i,locale:l,generate:a,type:u,maxLength:f}=this.params.config,c={...G,locale:l,maxLength:f,type:u,generate:a,systemPrompt:r,systemPromptPath:o,codeReviewPromptPath:n},m=e==="review"?U(c):H(c),p=await this.createChatCompletions(m,s);return i&&B("Perplexity",s,m,p,e),this.parseMessage(p,u,a)}catch(s){const r=s;throw r.code==="ENOTFOUND"?new v(`Error connecting to ${r.hostname} (${r.syscall})`):r}}async createChatCompletions(e,s){const o=(await new he({method:"POST",baseURL:`${this.host}/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: ${s}`}],temperature:this.params.config.temperature,top_p:this.params.config.topP,max_tokens:this.params.config.maxTokens,stream:!1}).execute()).data;if(!o.choices||o.choices.length===0||!o.choices[0].message?.content)throw new Error("No Content on response. Please open a Bug report");return o.choices[0].message.content}}class Ve{constructor(e,s){this.config=e,this.stagedDiff=s}createCommitMsgRequests$(e){return P(e).pipe(Ae(s=>{const r=this.config[s];if(r.compatible)return R.create(ts,{config:{...r,url:r.url||"",path:r.path||""},stagedDiff:this.stagedDiff,keyName:s}).generateCommitMessage$();switch(s){case"OPENAI":return R.create(fs,{config:this.config.OPENAI,stagedDiff:this.stagedDiff,keyName:s}).generateCommitMessage$();case"GEMINI":return R.create(zr,{config:this.config.GEMINI,stagedDiff:this.stagedDiff,keyName:s}).generateCommitMessage$();case"ANTHROPIC":return R.create(Br,{config:this.config.ANTHROPIC,stagedDiff:this.stagedDiff,keyName:s}).generateCommitMessage$();case"HUGGINGFACE":return R.create(Wr,{config:this.config.HUGGINGFACE,stagedDiff:this.stagedDiff,keyName:s}).generateCommitMessage$();case"MISTRAL":return R.create(Vr,{config:this.config.MISTRAL,stagedDiff:this.stagedDiff,keyName:s}).generateCommitMessage$();case"CODESTRAL":return R.create(Hr,{config:this.config.CODESTRAL,stagedDiff:this.stagedDiff,keyName:s}).generateCommitMessage$();case"OLLAMA":return P(this.config.OLLAMA.model).pipe(Ae(n=>R.create(es,{config:this.config.OLLAMA,keyName:n,stagedDiff:this.stagedDiff}).generateCommitMessage$()));case"COHERE":return R.create(Ur,{config:this.config.COHERE,stagedDiff:this.stagedDiff,keyName:s}).generateCommitMessage$();case"GROQ":return R.create(Kr,{config:this.config.GROQ,stagedDiff:this.stagedDiff,keyName:s}).generateCommitMessage$();case"PERPLEXITY":return R.create(ps,{config:this.config.PERPLEXITY,stagedDiff:this.stagedDiff,keyName:s}).generateCommitMessage$();case"DEEPSEEK":return R.create(qr,{config:this.config.DEEPSEEK,stagedDiff:this.stagedDiff,keyName:s}).generateCommitMessage$();default:const o=w.red.bold(`[${s}]`);return L({name:o+" Invalid AI type",value:"Invalid AI type",isError:!0,disabled:!0})}}),x(s=>{const r=w.red.bold("[UNKNOWN]");return L({name:r+` ${s.message||""}`,value:"Unknown error",isError:!0,disabled:!0})}))}createCodeReviewRequests$(e){return P(e).pipe(Ae(s=>{const r=this.config[s];if(r.compatible)return R.create(ts,{config:{...r,url:r.url||"",path:r.path||""},stagedDiff:this.stagedDiff,keyName:s}).generateCodeReview$();switch(s){case"OPENAI":return R.create(fs,{config:this.config.OPENAI,stagedDiff:this.stagedDiff,keyName:s}).generateCodeReview$();case"GEMINI":return R.create(zr,{config:this.config.GEMINI,stagedDiff:this.stagedDiff,keyName:s}).generateCodeReview$();case"ANTHROPIC":return R.create(Br,{config:this.config.ANTHROPIC,stagedDiff:this.stagedDiff,keyName:s}).generateCodeReview$();case"HUGGINGFACE":return R.create(Wr,{config:this.config.HUGGINGFACE,stagedDiff:this.stagedDiff,keyName:s}).generateCodeReview$();case"MISTRAL":return R.create(Vr,{config:this.config.MISTRAL,stagedDiff:this.stagedDiff,keyName:s}).generateCodeReview$();case"CODESTRAL":return R.create(Hr,{config:this.config.CODESTRAL,stagedDiff:this.stagedDiff,keyName:s}).generateCodeReview$();case"OLLAMA":return P(this.config.OLLAMA.model).pipe(Ae(n=>R.create(es,{config:this.config.OLLAMA,keyName:n,stagedDiff:this.stagedDiff}).generateCodeReview$()));case"COHERE":return R.create(Ur,{config:this.config.COHERE,stagedDiff:this.stagedDiff,keyName:s}).generateCodeReview$();case"GROQ":return R.create(Kr,{config:this.config.GROQ,stagedDiff:this.stagedDiff,keyName:s}).generateCodeReview$();case"PERPLEXITY":return R.create(ps,{config:this.config.PERPLEXITY,stagedDiff:this.stagedDiff,keyName:s}).generateCodeReview$();case"DEEPSEEK":return R.create(qr,{config:this.config.DEEPSEEK,stagedDiff:this.stagedDiff,keyName:s}).generateCodeReview$();default:const o=w.red.bold(`[${s}]`);return L({name:o+" Invalid AI type",value:"Invalid AI type",isError:!0,disabled:!0})}}),x(s=>{const r=w.red.bold("[UNKNOWN]");return L({name:r+` ${s.message||""}`,value:"Unknown error",isError:!0,disabled:!0})}))}}const _t=async()=>{const{stdout:t,failed:e}=await J("git",["rev-parse","--show-toplevel"],{reject:!1});if(e)throw new v("The current directory must be a Git repository!");return t},X=t=>`:(exclude)${t}`,Ye=["package-lock.json","pnpm-lock.yaml","*.lock","*.lockb","*.gif","*.png"].map(X),Dt=async(t,e)=>{const s=["diff","--cached","--diff-algorithm=minimal"],{stdout:r}=await J("git",[...s,"--name-only",...Ye,...t?t.map(X):[],...e?e.map(X):[]]);if(!r)return null;const{stdout:o}=await J("git",[...s,...Ye,...t?t.map(X):[]]);return{files:r.split(`
89
+ `),diff:o}},ha=t=>`Detected ${t.length.toLocaleString()} staged file${t.length>1?"s":""}`,ga=async(t,e,s)=>{const r=["diff-tree","-r","--no-commit-id","--name-only",t],{stdout:o}=await J("git",[...r,...Ye,...e?e.map(X):[],...s?s.map(X):[]]);if(!o)return null;const{stdout:n}=await J("git",["show",t,"--",...Ye,...e?e.map(X):[],...s?s.map(X):[]]);return{files:o.split(`
90
+ `).filter(Boolean),diff:n}},ya=async()=>{try{const{stdout:t}=await J("git",["config","--get","core.commentChar"]);return t}catch{return"#"}};class Q{constructor(){this.title="aicommit2"}printTitle(){console.log(io.textSync(this.title,{font:"Small"}))}showLoader(e){if(this.loader){this.loader.text=e;return}this.loader=tt(e).start()}stopLoader(){this.loader?.stop(),this.loader=void 0}displaySpinner(e){return tt(e).start()}stopSpinner(e){e.stop(),e.clear()}printStagedFiles(e){console.log(w.bold.green("\u2714 ")+w.bold(`${ha(e.files)}:`)),console.log(`${e.files.map(s=>` ${s}`).join(`
91
91
  `)}
92
92
  `)}printAnalyzed(){console.log(`
93
93
  ${w.bold.green("\u2714")} ${w.bold("Changes analyzed")}`)}printCommitted(){console.log(`
@@ -97,54 +97,54 @@ ${w.bold.green("\u2714")} ${w.bold("Saved commit message")}`)}printCancelledComm
97
97
  ${w.bold.yellow("\u26A0")} ${w.yellow("Commit cancelled")}`)}printError(e){console.log(`
98
98
  ${w.bold.red("\u2716")} ${w.red(`${e}`)}`)}printWarning(e){console.log(`
99
99
  ${w.bold.yellow("\u26A0")} ${w.red(`${e}`)}`)}printSetupGitEvent(e){console.log(`
100
- ${w.bold.green("\u2714")} ${w.bold(`Git ${e} hook has been set up`)}`)}moveCursorUp(){const e=Se.createInterface({input:process.stdin,output:process.stdout});Se.moveCursor(process.stdout,0,-1),e.close()}moveCursorDown(){const e=Se.createInterface({input:process.stdin,output:process.stdout});Se.moveCursor(process.stdout,0,2),e.close()}}const ga={isLoading:!1,startOption:{text:"AI is analyzing your changes"}},hs={isLoading:!1,startOption:{text:"AI is performing a code review"}},Gt="No commit messages were generated",gs="No code reviews were generated",jt={type:"reactiveListPrompt",name:"aicommit2Prompt",message:"Pick a commit message to use: ",emptyMessage:`\u26A0 ${Gt}`,loop:!1,descPageSize:15,showDescription:!0,pickKey:"short",isDescriptionDim:!0,stopMessage:"Changes analyzed"};class Bt{constructor(e){this.choices$=new Xt([]),this.destroyed$=new Hs(1),this.stopMessage="Changes analyzed",this.inquirerInstance=null,this.loader$=new Xt(e)}initPrompt(e=jt){return this.stopMessage=e.stopMessage,Ce.registerPrompt("reactiveListPrompt",io),this.inquirerInstance=Ce.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){const{value:s,isError:r}=e;!e||!s||this.choices$.next([...this.currentChoices,e].sort(gi))}checkErrorOnChoices(e=!0){if(this.choices$.getValue().map(r=>r).every(r=>r?.isError||r?.disabled)){this.alertNoGeneratedMessage(),this.logEmptyCommitMessage(),e&&process.exit(1);return}this.stopLoaderOnSuccess()}completeSubject(){this.choices$.complete(),this.loader$.complete(),this.destroyed$.next(!0),this.destroyed$.complete()}closeInquirerInstance(){this.inquirerInstance&&this.inquirerInstance.ui.close()}cancel(){this.inquirerInstance?.ui?.activePrompt&&this.inquirerInstance.ui.activePrompt.abortPrompt()}alertNoGeneratedMessage(){this.loader$.next({isLoading:!1,message:Gt,stopOption:{doneFrame:"\u26A0",color:"yellow"}})}stopLoaderOnSuccess(){this.loader$.next({isLoading:!1,message:this.stopMessage})}logEmptyCommitMessage(){console.log(`${w.bold.yellow("\u26A0")} ${w.yellow(`${Gt}`)}`)}get currentChoices(){return this.choices$.getValue().map(e=>e)}}const z=new X;var ya=async(t,e,s,r,o,n,i,l,c)=>(async()=>{z.printTitle(),await _t(),r&&await ee("git",["add","--update"]);const m=await ge({locale:t?.toString(),generate:e?.toString(),commitType:o?.toString(),systemPrompt:l?.toString()},c);await jr(m);const p=z.displaySpinner("Detecting staged files"),a=await Dt(s,m.exclude);if(p.stop(),!a)throw new v("No staged changes found. Stage your changes manually, or automatically stage all changes with the `--all` flag.");z.printStagedFiles(a);const d=ys(m,"commit");if(d.length===0)throw new v("Please set at least one API key via the `aicommit2 config set` command");const f=new ze(m,a),h=ys(m,"review");h.length>0&&await wa(f,h);const g=await va(f,d);i&&(mo("copy-paste").copy(g),z.printCopied(),process.exit()),n&&(await ws(g,c),process.exit());const{confirmationPrompt:y}=await Ce.prompt([{type:"confirm",name:"confirmationPrompt",message:"Use selected message?",default:!0}]);y?await ws(g,c):z.printCancelledCommit(),process.exit()})().catch(m=>{z.printError(m.message),te(m),process.exit(1)});function ys(t,e){return Object.entries(t).map(([s,r])=>[s,r]).filter(([s,r])=>!r.disabled).filter(([s,r])=>V.includes(s)||r.compatible===!0).filter(([s,r])=>{switch(e){case"commit":return s==="OLLAMA"?!!r&&!!r.model&&r.model.length>0:s==="HUGGINGFACE"?!!r&&!!r.cookie:!!r.key&&r.key.length>0;case"review":const o=t.codeReview||r.codeReview;return s==="OLLAMA"?!!r&&!!r.model&&r.model.length>0&&o:s==="HUGGINGFACE"?!!r&&!!r.cookie&&o:!!r.key&&r.key.length>0&&o}}).map(([s])=>s)}async function wa(t,e){const s=new Bt(hs),r=s.initPrompt({...jt,name:"codeReviewPrompt",message:"Please check code reviews: ",emptyMessage:`\u26A0 ${gs}`,isDescriptionDim:!1,stopMessage:"Code review completed",descPageSize:20});s.startLoader();const o=t.createCodeReviewRequests$(e).subscribe(c=>s.refreshChoices(c),()=>{},()=>s.checkErrorOnChoices());if(!(await r).codeReviewPrompt?.value)throw new v("An error occurred! No selected code review");o.unsubscribe(),s.completeSubject(),z.moveCursorUp();const{continuePrompt:l}=await Ce.prompt([{type:"confirm",name:"continuePrompt",message:"Will you continue without changing the code?",default:!0}]);l||(z.printCancelledCommit(),process.exit())}async function va(t,e){const s=new Bt(ga),r=s.initPrompt();s.startLoader();const o=t.createCommitMsgRequests$(e).subscribe(l=>s.refreshChoices(l),()=>{},()=>s.checkErrorOnChoices()),n=await r;o.unsubscribe(),s.completeSubject(),z.moveCursorUp();const i=n.aicommit2Prompt?.value;if(!i)throw new v("An error occurred! No selected message");return i}async function ws(t,e){const s=Qe("Committing with the generated message").start();await ee("git",["commit","-m",t,...e]),s.stop(),s.clear(),z.printCommitted()}var ba=Q({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 list"]},commands:[Q({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"]}}),Q({name:"get",parameters:["[<key>","[<key> ...]]"],help:{description:"Retrieve configuration values for specified AI provider.",examples:["aic2 config get OPENAI","aic2 config get ANTHROPIC"]}}),Q({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"']}}),Q({name:"list",parameters:[],help:{description:"Display all configuration keys and their values.",examples:["aic2 config list"]}})]},t=>{(async()=>{const{mode:e,keyValue:s}=t._;if(e==="get"){const r=await ge({},[]);for(const o of s)if(Be(r,o)){if(V.includes(o)){console.log(o,r[o]);return}console.log(`${o}=${r[o]}`)}return}if(e==="set"){await Ti(s.map(r=>{const o=r.indexOf("=");if(o===-1)throw new v("Invalid format. Use: key=value");const n=r.slice(0,o),i=r.slice(o+1);return[n,i]}));return}if(e==="add"){await Ni(s.map(r=>{const o=r.indexOf("=");if(o===-1)throw new v("Invalid format. Use: key=value");const n=r.slice(0,o),i=r.slice(o+1);return[n,i]}));return}if(e==="list"){await Fi();return}throw new v(`Invalid mode: ${e}`)})().catch(e=>{new X().printError(e.message),te(e),process.exit(1)})});const vs="prepare-commit-msg",bs=`.git/hooks/${vs}`,We=so(new URL("cli.mjs",import.meta.url)),Pa=process.argv[1].replace(/\\/g,"/").endsWith(`/${bs}`),Ps=process.platform==="win32",$s=`
100
+ ${w.bold.green("\u2714")} ${w.bold(`Git ${e} hook has been set up`)}`)}moveCursorUp(){const e=ke.createInterface({input:process.stdin,output:process.stdout});ke.moveCursor(process.stdout,0,-1),e.close()}moveCursorDown(){const e=ke.createInterface({input:process.stdin,output:process.stdout});ke.moveCursor(process.stdout,0,2),e.close()}}const wa={isLoading:!1,startOption:{text:"AI is analyzing your changes"}},hs={isLoading:!1,startOption:{text:"AI is performing a code review"}},Gt="No commit messages were generated",gs="No code reviews were generated",jt={type:"reactiveListPrompt",name:"aicommit2Prompt",message:"Pick a commit message to use: ",emptyMessage:`\u26A0 ${Gt}`,loop:!1,descPageSize:15,showDescription:!0,pickKey:"short",isDescriptionDim:!0,stopMessage:"Changes analyzed"};class Bt{constructor(e){this.choices$=new Xt([]),this.destroyed$=new Us(1),this.stopMessage="Changes analyzed",this.inquirerInstance=null,this.loader$=new Xt(e)}initPrompt(e=jt){return this.stopMessage=e.stopMessage,xe.registerPrompt("reactiveListPrompt",ao),this.inquirerInstance=xe.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){const{value:s,isError:r}=e;!e||!s||this.choices$.next([...this.currentChoices,e].sort(yi))}checkErrorOnChoices(e=!0){if(this.choices$.getValue().map(r=>r).every(r=>r?.isError||r?.disabled)){this.alertNoGeneratedMessage(),this.logEmptyCommitMessage(),e&&process.exit(1);return}this.stopLoaderOnSuccess()}completeSubject(){this.choices$.complete(),this.loader$.complete(),this.destroyed$.next(!0),this.destroyed$.complete()}closeInquirerInstance(){this.inquirerInstance&&this.inquirerInstance.ui.close()}cancel(){this.inquirerInstance?.ui?.activePrompt&&this.inquirerInstance.ui.activePrompt.abortPrompt()}alertNoGeneratedMessage(){this.loader$.next({isLoading:!1,message:Gt,stopOption:{doneFrame:"\u26A0",color:"yellow"}})}stopLoaderOnSuccess(){this.loader$.next({isLoading:!1,message:this.stopMessage})}logEmptyCommitMessage(){console.log(`${w.bold.yellow("\u26A0")} ${w.yellow(`${Gt}`)}`)}get currentChoices(){return this.choices$.getValue().map(e=>e)}}const z=new Q;var va=async(t,e,s,r,o,n,i,l,a)=>(async()=>{z.printTitle(),await _t(),r&&await J("git",["add","--update"]);const u=await we({locale:t?.toString(),generate:e?.toString(),commitType:o?.toString(),systemPrompt:l?.toString()},a);await jr(u);const f=z.displaySpinner("Detecting staged files"),c=await Dt(s,u.exclude);if(f.stop(),!c)throw new v("No staged changes found. Stage your changes manually, or automatically stage all changes with the `--all` flag.");z.printStagedFiles(c);const m=ys(u,"commit");if(m.length===0)throw new v("Please set at least one API key via the `aicommit2 config set` command");const p=new Ve(u,c),h=ys(u,"review");h.length>0&&await ba(p,h);const g=await $a(p,m);i&&(uo("copy-paste").copy(g),z.printCopied(),process.exit()),n&&(await ws(g,a),process.exit());const{confirmationPrompt:y}=await xe.prompt([{type:"confirm",name:"confirmationPrompt",message:"Use selected message?",default:!0}]);y?await ws(g,a):z.printCancelledCommit(),process.exit()})().catch(u=>{z.printError(u.message),ee(u),process.exit(1)});function ys(t,e){return Object.entries(t).map(([s,r])=>[s,r]).filter(([s,r])=>!r.disabled).filter(([s,r])=>te.includes(s)||r.compatible===!0).filter(([s,r])=>{switch(e){case"commit":return s==="OLLAMA"?!!r&&!!r.model&&r.model.length>0:s==="HUGGINGFACE"?!!r&&!!r.cookie:!!r.key&&r.key.length>0;case"review":const o=t.codeReview||r.codeReview;return s==="OLLAMA"?!!r&&!!r.model&&r.model.length>0&&o:s==="HUGGINGFACE"?!!r&&!!r.cookie&&o:!!r.key&&r.key.length>0&&o}}).map(([s])=>s)}async function ba(t,e){const s=new Bt(hs),r=s.initPrompt({...jt,name:"codeReviewPrompt",message:"Please check code reviews: ",emptyMessage:`\u26A0 ${gs}`,isDescriptionDim:!1,stopMessage:"Code review completed",descPageSize:20});s.startLoader();const o=t.createCodeReviewRequests$(e).subscribe(a=>s.refreshChoices(a),()=>{},()=>s.checkErrorOnChoices());if(!(await r).codeReviewPrompt?.value)throw new v("An error occurred! No selected code review");o.unsubscribe(),s.completeSubject(),z.moveCursorUp();const{continuePrompt:l}=await xe.prompt([{type:"confirm",name:"continuePrompt",message:"Will you continue without changing the code?",default:!0}]);l||(z.printCancelledCommit(),process.exit())}async function $a(t,e){const s=new Bt(wa),r=s.initPrompt();s.startLoader();const o=t.createCommitMsgRequests$(e).subscribe(l=>s.refreshChoices(l),()=>{},()=>s.checkErrorOnChoices()),n=await r;o.unsubscribe(),s.completeSubject(),z.moveCursorUp();const i=n.aicommit2Prompt?.value;if(!i)throw new v("An error occurred! No selected message");return i}async function ws(t,e){const s=tt("Committing with the generated message").start();await J("git",["commit","-m",t,...e]),s.stop(),s.clear(),z.printCommitted()}var Pa=Y({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:[Y({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"]}}),Y({name:"get",parameters:["[<key>","[<key> ...]]"],help:{description:"Retrieve configuration values for specified AI provider.",examples:["aic2 config get OPENAI","aic2 config get ANTHROPIC"]}}),Y({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"']}}),Y({name:"list",parameters:[],help:{description:"Display all configuration keys and their values.",examples:["aic2 config list"]}}),Y({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"]}})]},t=>{(async()=>{const{mode:e,keyValue:s}=t._,r=t._[1];if(e==="get"){const o=await we({},[]);if(s.length===0){console.log(o);return}for(const n of s){const i=n.split(".");let l=o,a=!0;for(const u of i)if(le(l,u))l=l[u];else{a=!1;break}a?console.log(n,l):console.log(`${n} not found`)}return}if(e==="set"){await Ni(s.map(o=>{const n=o.indexOf("=");if(n===-1)throw new v("Invalid format. Use: key=value");const i=o.slice(0,n),l=o.slice(n+1);return[i,l]}));return}if(e==="add"){await Fi(s.map(o=>{const n=o.indexOf("=");if(n===-1)throw new v("Invalid format. Use: key=value");const i=o.slice(0,n),l=o.slice(n+1);return[i,l]}));return}if(e==="list"){await _i();return}if(e==="del"){if(!r)throw new v("Please provide the config name to delete.");const o=await ze(),n=r.split(".");if(n.length===2){const[i,l]=n;if(o[i]&&typeof o[i]=="object"&&le(o[i],l))delete o[i][l],Object.keys(o[i]).length===0&&delete o[i],await I.writeFile(vs,ge.stringify(o),"utf8"),console.log(`Successfully deleted config: ${r}`);else throw new v(`Config not found: ${r}`)}else if(n.length===1){const i=n[0];if(le(o,i))delete o[i],await I.writeFile(vs,ge.stringify(o),"utf8"),console.log(`Successfully deleted config: ${r}`);else throw new v(`Config not found: ${r}`)}else throw new v(`Invalid config name format: ${r}`);return}throw new v(`Invalid mode: ${e}`)})().catch(e=>{new Q().printError(e.message),ee(e),process.exit(1)})});const vs=O.join(Me.homedir(),".aicommit2"),bs="prepare-commit-msg",$s=`.git/hooks/${bs}`,Je=oo(new URL("cli.mjs",import.meta.url)),Ca=process.argv[1].replace(/\\/g,"/").endsWith(`/${$s}`),Ps=process.platform==="win32",Cs=`
101
101
  #!/usr/bin/env node
102
- import(${JSON.stringify(oo(We))})
103
- `.trim();var $a=Q({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 _t(),{installUninstall:s}=t._,r=T.join(e,bs),o=await Qr(r);if(s==="install"){if(o){if(await I.realpath(r).catch(()=>{})===We){console.warn("The hook is already installed");return}throw new v(`A different ${vs} hook seems to be installed. Please remove it before installing aicommit2.`)}await I.mkdir(T.dirname(r),{recursive:!0}),Ps?await I.writeFile(r,$s):(await I.symlink(We,r,"file"),await I.chmod(r,493)),console.log(`${w.green("\u2714")} Hook installed`);return}if(s==="uninstall"){if(!o){console.warn("Hook is not installed");return}if(Ps){if(await I.readFile(r,"utf8")!==$s){console.warn("Hook is not installed");return}}else if(await I.realpath(r)!==We){console.warn("Hook is not installed");return}await I.rm(r),console.log(`${w.green("\u2714")} Hook uninstalled`);return}throw new v(`Invalid mode: ${s}`)})().catch(e=>{console.error(`${w.red("\u2716")} ${e.message}`),te(e),process.exit(1)})}),Ca=Q({name:"log",parameters:["<removeAll>"],help:{description:"Manage log files generated by the application",examples:["aic2 log removeAll"]}},t=>{(async()=>{const{removeAll:e}=t._;if(e==="removeAll"){await ao(Fr,{recursive:!0,force:!0}),console.log(`${w.green("\u2714")} All Log files are removed!`);return}throw new v(`Invalid mode: ${e}`)})().catch(e=>{new X().printError(e.message),te(e),process.exit(1)})});const Ea=process.argv.slice(2).filter(t=>!t.startsWith("--pre-commit")),[Ye,Cs]=Ea;var xa=()=>(async()=>{if(!Ye)throw new v('Commit message file path is missing. This file should be called from the "pre-commit framework"');if(Cs){console.log(`Skipping aicommit2 message generation for ${Cs} commit`);return}const t=await Dt();if(!t)return;const e=new X;e.printTitle();const s=await ge({});if(s.systemPromptPath)try{await I.readFile(T.resolve(s.systemPromptPath),"utf-8")}catch{throw new v(`Error reading system prompt file: ${s.systemPromptPath}`)}const r=Object.entries(s).filter(([f])=>V.includes(f)).map(([f,h])=>[f,h]).filter(([f,h])=>!h.disabled).filter(([f,h])=>f==="OLLAMA"?!!h&&!!h.model&&h.model.length>0:f==="HUGGINGFACE"?!!h&&!!h.cookie:!!h.key&&h.key.length>0).map(([f])=>f);if(r.length===0)throw new v("Please set at least one API key via the `aicommit2 config set` command");const n=new ze(s,t);let i;try{i=await Qt(n.createCommitMsgRequests$(r).pipe(Zt(f=>!f.isError),E(f=>f.value),er()))}finally{e.printAnalyzed()}const c=await I.readFile(Ye,"utf8")!=="",m=i.length>1;let p="";c&&(p=`# \u{1F916} Generated by aicommit2 (https://github.com/tak-bro/aicommit2)
104
- `,p+=`# ----------------------------------------
105
- `,p+=`# How to use:
106
- `,m?(p+=`# 1. Remove the "#" from your chosen message
107
- `,p+=`# 2. Edit the message if needed
108
- `,p+=`# 3. Save and close the editor
109
- `):(p+=`# 1. The message below will be used
110
- `,p+=`# 2. Edit the message if needed
111
- `,p+=`# 3. Save and close the editor
112
- `),p+=`# ----------------------------------------
113
- `),m?(c&&(p+=`
102
+ import(${JSON.stringify(no(Je))})
103
+ `.trim();var Ea=Y({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 _t(),{installUninstall:s}=t._,r=O.join(e,$s),o=await Qr(r);if(s==="install"){if(o){if(await I.realpath(r).catch(()=>{})===Je){console.warn("The hook is already installed");return}throw new v(`A different ${bs} hook seems to be installed. Please remove it before installing aicommit2.`)}await I.mkdir(O.dirname(r),{recursive:!0}),Ps?await I.writeFile(r,Cs):(await I.symlink(Je,r,"file"),await I.chmod(r,493)),console.log(`${w.green("\u2714")} Hook installed`);return}if(s==="uninstall"){if(!o){console.warn("Hook is not installed");return}if(Ps){if(await I.readFile(r,"utf8")!==Cs){console.warn("Hook is not installed");return}}else if(await I.realpath(r)!==Je){console.warn("Hook is not installed");return}await I.rm(r),console.log(`${w.green("\u2714")} Hook uninstalled`);return}throw new v(`Invalid mode: ${s}`)})().catch(e=>{console.error(`${w.red("\u2716")} ${e.message}`),ee(e),process.exit(1)})}),xa=Y({name:"log",parameters:["<removeAll>"],help:{description:"Manage log files generated by the application",examples:["aic2 log removeAll"]}},t=>{(async()=>{const{removeAll:e}=t._;if(e==="removeAll"){await co(Fr,{recursive:!0,force:!0}),console.log(`${w.green("\u2714")} All Log files are removed!`);return}throw new v(`Invalid mode: ${e}`)})().catch(e=>{new Q().printError(e.message),ee(e),process.exit(1)})});const Aa=process.argv.slice(2).filter(t=>!t.startsWith("--pre-commit")),[Xe,Es]=Aa;var Ma=()=>(async()=>{if(!Xe)throw new v('Commit message file path is missing. This file should be called from the "pre-commit framework"');if(Es){console.log(`Skipping aicommit2 message generation for ${Es} commit`);return}const t=await Dt();if(!t)return;const e=new Q;e.printTitle();const s=await we({});if(s.systemPromptPath)try{await I.readFile(O.resolve(s.systemPromptPath),"utf-8")}catch{throw new v(`Error reading system prompt file: ${s.systemPromptPath}`)}const r=Object.entries(s).filter(([p])=>te.includes(p)).map(([p,h])=>[p,h]).filter(([p,h])=>!h.disabled).filter(([p,h])=>p==="OLLAMA"?!!h&&!!h.model&&h.model.length>0:p==="HUGGINGFACE"?!!h&&!!h.cookie:!!h.key&&h.key.length>0).map(([p])=>p);if(r.length===0)throw new v("Please set at least one API key via the `aicommit2 config set` command");const n=new Ve(s,t);let i;try{i=await Qt(n.createCommitMsgRequests$(r).pipe(Zt(p=>!p.isError),E(p=>p.value),er()))}finally{e.printAnalyzed()}const a=await I.readFile(Xe,"utf8")!=="",u=i.length>1;let f="";a&&(f=`# \u{1F916} Generated by aicommit2 (https://github.com/tak-bro/aicommit2)
104
+ `,f+=`# ----------------------------------------
105
+ `,f+=`# How to use:
106
+ `,u?(f+=`# 1. Remove the "#" from your chosen message
107
+ `,f+=`# 2. Edit the message if needed
108
+ `,f+=`# 3. Save and close the editor
109
+ `):(f+=`# 1. The message below will be used
110
+ `,f+=`# 2. Edit the message if needed
111
+ `,f+=`# 3. Save and close the editor
112
+ `),f+=`# ----------------------------------------
113
+ `),u?(a&&(f+=`
114
114
  # \u{1F4DD} Choose one of these messages:
115
- `),p+=`
116
- ${i.map(f=>`# ${f}`).join(`
117
- `)}`):(c&&(p+=`
115
+ `),f+=`
116
+ ${i.map(p=>`# ${p}`).join(`
117
+ `)}`):(a&&(f+=`
118
118
  # \u{1F4DD} Generated commit message:
119
- `),p+=`
119
+ `),f+=`
120
120
  ${i[0]}
121
- `);const a=await I.readFile(Ye,"utf8"),d=p+`
122
- `+a;await I.writeFile(Ye,d),e.printSavedCommitMessage()})().catch(t=>{new X().printError(t.message),te(t),process.exit(1)});const Aa=process.argv.slice(2).filter(t=>!t.startsWith("--hook-mode")),[Ve,Es]=Aa;var Ma=()=>(async()=>{if(!Ve)throw new v('Commit message file path is missing. This file should be called from the "prepare-commit-msg" git hook or with --hook-mode flag');if(Es){console.log(`Skipping aicommit2 message generation for ${Es} commit`);return}const t=await Dt();if(!t)return;const e=new X;e.printTitle();const s=await ge({});if(s.systemPromptPath)try{await I.readFile(T.resolve(s.systemPromptPath),"utf-8")}catch{throw new v(`Error reading system prompt file: ${s.systemPromptPath}`)}const r=Object.entries(s).filter(([h])=>V.includes(h)).map(([h,g])=>[h,g]).filter(([h,g])=>!g.disabled).filter(([h,g])=>h==="OLLAMA"?!!g&&!!g.model&&g.model.length>0:h==="HUGGINGFACE"?!!g&&!!g.cookie:!!g.key&&g.key.length>0).map(([h])=>h);if(r.length===0)throw new v("Please set at least one API key via the `aicommit2 config set` command");const n=new ze(s,t),i=e.displaySpinner("The AI is analyzing your changes");let l;try{l=await Qt(n.createCommitMsgRequests$(r).pipe(Zt(h=>!h.isError),E(h=>h.value),er()))}finally{i.stop(),i.clear(),e.printAnalyzed()}const m=await I.readFile(Ve,"utf8")!=="",p=l.length>1;let a="";m&&(a=`# \u{1F916} Generated by aicommit2 (https://github.com/tak-bro/aicommit2)
123
- `,a+=`# ----------------------------------------
124
- `,a+=`# How to use:
125
- `,p?(a+=`# 1. Remove the "#" from your chosen message
126
- `,a+=`# 2. Edit the message if needed
127
- `,a+=`# 3. Save and close the editor
128
- `):(a+=`# 1. The message below will be used
129
- `,a+=`# 2. Edit the message if needed
130
- `,a+=`# 3. Save and close the editor
131
- `),a+=`# ----------------------------------------
132
- `),p?(m&&(a+=`
133
- # \u{1F4DD} Choose one of these messages:
134
- `),a+=`
135
- ${l.map(h=>`# ${h}`).join(`
136
- `)}`):(m&&(a+=`
137
- # \u{1F4DD} Generated commit message:
138
- `),a+=`
121
+ `);const c=await I.readFile(Xe,"utf8"),m=f+`
122
+ `+c;await I.writeFile(Xe,m),e.printSavedCommitMessage()})().catch(t=>{new Q().printError(t.message),ee(t),process.exit(1)});const Sa=process.argv.slice(2).filter(t=>!t.startsWith("--hook-mode")),[Qe,xs]=Sa;var Ra=()=>(async()=>{if(!Qe)throw new v('Commit message file path is missing. This file should be called from the "prepare-commit-msg" git hook or with --hook-mode flag');if(xs){console.log(`Skipping aicommit2 message generation for ${xs} commit`);return}const t=await Dt();if(!t)return;const e=new Q;e.printTitle();const s=await we({});if(s.systemPromptPath)try{await I.readFile(O.resolve(s.systemPromptPath),"utf-8")}catch{throw new v(`Error reading system prompt file: ${s.systemPromptPath}`)}const r=Object.entries(s).filter(([g])=>te.includes(g)).map(([g,y])=>[g,y]).filter(([g,y])=>!y.disabled).filter(([g,y])=>g==="OLLAMA"?!!y&&!!y.model&&y.model.length>0:g==="HUGGINGFACE"?!!y&&!!y.cookie:!!y.key&&y.key.length>0).map(([g])=>g);if(r.length===0)throw new v("Please set at least one API key via the `aicommit2 config set` command");const n=new Ve(s,t),i=e.displaySpinner("The AI is analyzing your changes");let l;try{l=await Qt(n.createCommitMsgRequests$(r).pipe(Zt(g=>!g.isError),E(g=>g.value),er()))}finally{i.stop(),i.clear(),e.printAnalyzed()}const u=await I.readFile(Qe,"utf8")!=="",f=l.length>1,c=await ya();let m="";u&&(m=`${c} \u{1F916} Generated by aicommit2 (https://github.com/tak-bro/aicommit2)
123
+ `,m+=`${c} ----------------------------------------
124
+ `,m+=`${c} How to use:
125
+ `,f?(m+=`${c} 1. Remove the "${c}" from your chosen message
126
+ `,m+=`${c} 2. Edit the message if needed
127
+ `,m+=`${c} 3. Save and close the editor
128
+ `):(m+=`${c} 1. The message below will be used
129
+ `,m+=`${c} 2. Edit the message if needed
130
+ `,m+=`${c} 3. Save and close the editor
131
+ `),m+=`${c} ----------------------------------------
132
+ `),f?(u&&(m+=`
133
+ ${c} \u{1F4DD} Choose one of these messages:
134
+ `),m+=`
135
+ ${l.map(g=>`${c} ${g}`).join(`
136
+ `)}`):(u&&(m+=`
137
+ ${c} \u{1F4DD} Generated commit message:
138
+ `),m+=`
139
139
  ${l[0]}
140
- `);const d=await I.readFile(Ve,"utf8"),f=a+`
141
- `+d;await I.writeFile(Ve,f),e.printSavedCommitMessage()})().catch(t=>{new X().printError(t.message),te(t),process.exit(1)});let Je=new tr;const D=new X,xs=process.cwd(),Sa=T.join(xs,".git","hooks","post-commit"),$e=T.join(xs,".git","commit-log.txt"),Ra=`#!/bin/sh
140
+ `);const p=await I.readFile(Qe,"utf8"),h=m+`
141
+ `+p;await I.writeFile(Qe,h),e.printSavedCommitMessage()})().catch(t=>{new Q().printError(t.message),ee(t),process.exit(1)});let Ze=new tr;const D=new Q,As=process.cwd(),Ia=O.join(As,".git","hooks","post-commit"),Ee=O.join(As,".git","commit-log.txt"),ka=`#!/bin/sh
142
142
  commit_hash=$(git rev-parse HEAD)
143
143
  commit_message=$(git log -1 --pretty=%B)
144
- echo "$commit_hash: $commit_message" >> ${$e}
145
- `;let Ht=null,N=null;const As=async(t,e,s,r,o)=>{D.printTitle(),await _t();const n=await Ia(t,e,r,o);Ta(),Oa();try{await Rs(n)}catch(i){return ka(i),As(t,e,s,r,o)}},Ia=async(t,e,s,r)=>{const o=await ge({locale:t?.toString(),generate:e?.toString(),systemPrompt:s?.toString()},r);return await jr(o),Ms(o).length===0&&(D.printError(`Please set at least one API key and watchMode via the config command:
144
+ echo "$commit_hash: $commit_message" >> ${Ee}
145
+ `;let Ht=null,N=null;const Ms=async(t,e,s,r,o)=>{D.printTitle(),await _t();const n=await Oa(t,e,r,o);Fa(),Ta();try{await Is(n)}catch(i){return La(i),Ms(t,e,s,r,o)}},Oa=async(t,e,s,r)=>{const o=await we({locale:t?.toString(),generate:e?.toString(),systemPrompt:s?.toString()},r);return await jr(o),Ss(o).length===0&&(D.printError(`Please set at least one API key and watchMode via the config command:
146
146
  aicommit2 config set [MODEL].key="YOUR_API_KEY"
147
- aicommit2 config set [MODEL].watchMode="true"`),process.exit()),o},ka=async t=>{D.printError(`An error occurred: ${t.message}`),te(t),await new Promise(e=>setTimeout(e,3e3)),D.printWarning("Restarting the commit monitoring process...")},Oa=()=>{_.writeFileSync($e,"",{flag:"w"})},Ms=t=>Object.entries(t).filter(([e,s])=>V.includes(e)||s.compatible===!0).map(([e,s])=>[e,s]).filter(([e,s])=>!s.disabled).filter(([e,s])=>La(e,s,t)).map(([e])=>e),La=(t,e,s)=>{const r=s.watchMode||e.watchMode;return t==="OLLAMA"?!!e&&!!e.model&&e.model.length>0&&r:t==="HUGGINGFACE"?!!e&&!!e.cookie&&r:e.compatible?!!e.url&&!!e.key&&r:!!e.key&&e.key.length>0&&r},Ta=()=>{_.writeFileSync(Sa,Ra,{mode:493}),D.printSetupGitEvent("post-commit")},Ss=()=>{process.stdout.write("\x1Bc")},Na=async(t,e)=>{try{const s=await ha(e);if(!s){D.printWarning("No changes found in this commit");return}D.stopLoader(),D.printStagedFiles(s);const r=Ms(t);if(r.length===0){D.printError(`Please set at least one API key and watchMode via the config command:
147
+ aicommit2 config set [MODEL].watchMode="true"`),process.exit()),o},La=async t=>{D.printError(`An error occurred: ${t.message}`),ee(t),await new Promise(e=>setTimeout(e,3e3)),D.printWarning("Restarting the commit monitoring process...")},Ta=()=>{_.writeFileSync(Ee,"",{flag:"w"})},Ss=t=>Object.entries(t).filter(([e,s])=>te.includes(e)||s.compatible===!0).map(([e,s])=>[e,s]).filter(([e,s])=>!s.disabled).filter(([e,s])=>Na(e,s,t)).map(([e])=>e),Na=(t,e,s)=>{const r=s.watchMode||e.watchMode;return t==="OLLAMA"?!!e&&!!e.model&&e.model.length>0&&r:t==="HUGGINGFACE"?!!e&&!!e.cookie&&r:e.compatible?!!e.url&&!!e.key&&r:!!e.key&&e.key.length>0&&r},Fa=()=>{_.writeFileSync(Ia,ka,{mode:493}),D.printSetupGitEvent("post-commit")},Rs=()=>{process.stdout.write("\x1Bc")},_a=async(t,e)=>{try{const s=await ga(e);if(!s){D.printWarning("No changes found in this commit");return}D.stopLoader(),D.printStagedFiles(s);const r=Ss(t);if(r.length===0){D.printError(`Please set at least one API key and watchMode via the config command:
148
148
  aicommit2 config set [MODEL].key="YOUR_API_KEY"
149
- aicommit2 config set [MODEL].watchMode="true"`),process.exit();return}await Fa(t,s,r)}catch(s){D.printError(`Error processing commit ${e}: ${s.message}`)}},Fa=async(t,e,s)=>{_a();const r=new ze(t,e);N=new Bt(hs);const o=Da();N.startLoader(),Ht=Ga(r,s),await o,ja()},_a=()=>{N&&(Ht?.unsubscribe(),N.clearLoader(),N.completeSubject(),N.cancel(),N.closeInquirerInstance()),Je.next(),Je.complete(),Je=new tr},Da=()=>N.initPrompt({...jt,name:"codeReviewPrompt",message:"Please check code reviews: ",emptyMessage:`\u26A0 ${gs}`,isDescriptionDim:!1,stopMessage:"Code review completed",descPageSize:20}),Ga=(t,e)=>t.createCodeReviewRequests$(e).pipe(lo(Je)).subscribe(s=>{N?.refreshChoices(s)},()=>{},()=>{N?.checkErrorOnChoices(!1)}),ja=()=>{N&&(Ht?.unsubscribe(),N.clearLoader(),N.completeSubject(),N.cancel(),N.closeInquirerInstance(),N=null),Ss(),D.showLoader("Watching for new Git commits...")},Rs=async t=>{const e=co.watch($e,{persistent:!0});e.on("change",async()=>{try{const s=await Ba();for(const r of s)r&&await Ha(t,r)}catch(s){D.printError(`Error reading or processing commit log: ${s.message}`)}finally{Ua()}}),e.on("error",qa(t))},Ba=async()=>(await _.promises.readFile($e,"utf8")).trim().split(`
150
- `),Ha=async(t,e)=>{const[s]=e.split(":");if(!s){D.printWarning("Empty commit hash detected, skipping...");return}Ss(),await Na(t,s.trim())},Ua=()=>{try{_.truncateSync($e)}catch(t){D.printError(`Error truncating log file: ${t.message}`)}},qa=t=>e=>{D.printError(`Watcher error: ${e.message}`),setTimeout(()=>Rs(t),1e3)},Ut=process.argv.slice(2);process.noDeprecation=!0,Os({name:"aicommit2",version:Nr,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}},commands:[ba,$a,Ca],help:{description:Pi},ignoreArgv:t=>t==="unknown-flag"||t==="argument"},t=>{if(t.flags["pre-commit"]){xa();return}if(t.flags["hook-mode"]||Pa){Ma();return}if(t.flags["watch-commit"]){As(t.flags.locale,t.flags.generate,t.flags.exclude,t.flags.prompt,Ut);return}ya(t.flags.locale,t.flags.generate,t.flags.exclude,t.flags.all,t.flags.type,t.flags.confirm,t.flags.clipboard,t.flags.prompt,Ut)},Ut);
149
+ aicommit2 config set [MODEL].watchMode="true"`),process.exit();return}await Da(t,s,r)}catch(s){D.printError(`Error processing commit ${e}: ${s.message}`)}},Da=async(t,e,s)=>{Ga();const r=new Ve(t,e);N=new Bt(hs);const o=ja();N.startLoader(),Ht=Ba(r,s),await o,Ha()},Ga=()=>{N&&(Ht?.unsubscribe(),N.clearLoader(),N.completeSubject(),N.cancel(),N.closeInquirerInstance()),Ze.next(),Ze.complete(),Ze=new tr},ja=()=>N.initPrompt({...jt,name:"codeReviewPrompt",message:"Please check code reviews: ",emptyMessage:`\u26A0 ${gs}`,isDescriptionDim:!1,stopMessage:"Code review completed",descPageSize:20}),Ba=(t,e)=>t.createCodeReviewRequests$(e).pipe(mo(Ze)).subscribe(s=>{N?.refreshChoices(s)},()=>{},()=>{N?.checkErrorOnChoices(!1)}),Ha=()=>{N&&(Ht?.unsubscribe(),N.clearLoader(),N.completeSubject(),N.cancel(),N.closeInquirerInstance(),N=null),Rs(),D.showLoader("Watching for new Git commits...")},Is=async t=>{const e=lo.watch(Ee,{persistent:!0});e.on("change",async()=>{try{const s=await Ua();for(const r of s)r&&await qa(t,r)}catch(s){D.printError(`Error reading or processing commit log: ${s.message}`)}finally{za()}}),e.on("error",Ka(t))},Ua=async()=>(await _.promises.readFile(Ee,"utf8")).trim().split(`
150
+ `),qa=async(t,e)=>{const[s]=e.split(":");if(!s){D.printWarning("Empty commit hash detected, skipping...");return}Rs(),await _a(t,s.trim())},za=()=>{try{_.truncateSync(Ee)}catch(t){D.printError(`Error truncating log file: ${t.message}`)}},Ka=t=>e=>{D.printError(`Watcher error: ${e.message}`),setTimeout(()=>Is(t),1e3)},Ut=process.argv.slice(2);process.noDeprecation=!0,Ls({name:"aicommit2",version:Nr,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}},commands:[Pa,Ea,xa],help:{description:Pi},ignoreArgv:t=>t==="unknown-flag"||t==="argument"},t=>{if(t.flags["pre-commit"]){Ma();return}if(t.flags["hook-mode"]||Ca){Ra();return}if(t.flags["watch-commit"]){Ms(t.flags.locale,t.flags.generate,t.flags.exclude,t.flags.prompt,Ut);return}va(t.flags.locale,t.flags.generate,t.flags.exclude,t.flags.all,t.flags.type,t.flags.confirm,t.flags.clipboard,t.flags.prompt,Ut)},Ut);