aicommit2 2.4.12 → 2.4.13

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 (2) hide show
  1. package/dist/cli.mjs +110 -110
  2. package/package.json +1 -1
package/dist/cli.mjs CHANGED
@@ -1,21 +1,21 @@
1
1
  #!/usr/bin/env node
2
- import{command as oe,cli as qo}from"cleye";import{createRequire as Xo}from"module";import U from"fs";import xe from"os";import x from"path";import{Buffer as Qo}from"node:buffer";import ce from"node:path";import dr,{ChildProcess as Zo,exec as es}from"node:child_process";import se from"node:process";import ts,{execSync as je,exec as rs}from"child_process";import{fileURLToPath as mr}from"node:url";import os,{constants as fr}from"node:os";import pr from"assert";import hr from"events";import{createWriteStream as ss,createReadStream as ns}from"node:fs";import is from"buffer";import dt from"stream";import gr,{promisify as as}from"util";import{debuglog as cs,promisify as ls}from"node:util";import He from"inquirer";import P from"chalk";import{of as mt,concatMap as O,from as A,map as M,catchError as I,mergeMap as yr,BehaviorSubject as wr,ReplaySubject as us,Subscription as ft,lastValueFrom as vr,filter as br,toArray as Cr,Subject as pt}from"rxjs";import ds from"@anthropic-ai/sdk";import{fromPromise as L}from"rxjs/internal/observable/innerFrom";import{xxh64 as Pr}from"@pacote/xxhash";import B from"winston";import R from"fs/promises";import"winston-daily-rotate-file";import ms from"axios";import{CohereClient as fs}from"cohere-ai";import $r from"openai";import{GoogleGenerativeAI as ps,HarmCategory as Be,HarmBlockThreshold as Ue}from"@google/generative-ai";import hs from"http";import gs from"https";import ys from"net";import ws from"tls";import vs,{fileURLToPath as bs,pathToFileURL as Cs}from"url";import Er from"tty";import Ps from"groq-sdk";import{Ollama as $s}from"ollama";import{fetch as Es,Agent as xs}from"undici";import ze from"readline";import xr from"figlet";import ks from"gradient-string";import kr from"ora";import Ss from"inquirer-reactive-list-prompt";import{readdir as Sr,stat as As,rm as Ms}from"node:fs/promises";import Is from"chokidar";import{takeUntil as Ar,finalize as Mr}from"rxjs/operators";var Rs="aicommit2",Ir="2.4.12",Os="A Reactive CLI that generates commit messages for Git and Jujutsu with various AI",Ls=["cli","ai","git","jujutsu","jj","vcs","version-control","commit","git-commit","jujutsu-commit","command-line","commandline","aipick","aicommit","aicommits","aicommit2","openai","huggingface","anthropic","claude","claude3","gemini","gemini-pro","generative-ai","mistral","ollama","llama3","llama3.2","llama3.3","gemma","llm","chatgpt","cohere","groq","codestral","perplexity","deepseek","deepseek-r1","pre-commit"],Ds="MIT",Ts="tak-bro/aicommit2",Fs="Hyungtak Jin(@tak-bro)",Ns="module",Gs=["dist"],_s={aicommit2:"./dist/cli.mjs",aic2:"./dist/cli.mjs"},js={prepare:"simple-git-hooks",build:"pkgroll --minify",lint:"eslint --cache .","type-check":"tsc",test:"tsx tests",prepack:"pnpm build && clean-pkg-json",prettier:"prettier"},Hs={"@anthropic-ai/sdk":"^0.39.0","@dqbd/tiktoken":"^1.0.21","@google/generative-ai":"^0.24.1","@inquirer/prompts":"^3.3.2","@pacote/xxhash":"^0.3.2","@types/winston":"^2.4.4",axios:"^1.9.0",chalk:"^5.4.1",chokidar:"^4.0.3",cleye:"^1.3.4","cohere-ai":"^7.17.1","copy-paste":"^1.5.3",figlet:"^1.8.1","formdata-node":"^6.0.3","gradient-string":"^3.0.0","groq-sdk":"^0.7.0",inquirer:"9.2.8","inquirer-reactive-list-prompt":"^1.0.16",ollama:"^0.5.15",openai:"^6.3.0",ora:"^8.2.0",readline:"^1.3.0",rxjs:"^7.8.2",undici:"^7.10.0",uuid:"^9.0.1",winston:"^3.17.0","winston-daily-rotate-file":"^5.0.0"},Bs={"@pvtnbr/eslint-config":"^0.33.0","@semantic-release/changelog":"^6.0.3","@semantic-release/commit-analyzer":"^12.0.0","@semantic-release/git":"^10.0.1","@semantic-release/github":"^10.3.5","@semantic-release/npm":"^12.0.1","@semantic-release/release-notes-generator":"^13.0.0","@types/figlet":"^1.7.0","@types/ini":"^1.3.34","@types/inquirer":"^9.0.8","@types/node":"^18.19.103","@types/uuid":"^9.0.8","@typescript-eslint/eslint-plugin":"^6.21.0","@typescript-eslint/parser":"^6.21.0","clean-pkg-json":"^1.3.0","conventional-changelog-conventionalcommits":"^7.0.2","conventional-commits-parser":"^5.0.0",eslint:"^8.57.1","eslint-config-prettier":"^8.10.0","eslint-plugin-eslint-comments":"^3.2.0","eslint-plugin-import":"^2.31.0","eslint-plugin-jsonc":"^2.20.1","eslint-plugin-no-use-extend-native":"^0.5.0","eslint-plugin-promise":"^6.6.0","eslint-plugin-unicorn":"^49.0.0","eslint-plugin-unused-imports":"^3.2.0",execa:"^7.2.0","fs-fixture":"^1.2.0","https-proxy-agent":"^5.0.1",ini:"^3.0.1","lint-staged":"^13.3.0",manten:"^0.7.0",pkgroll:"^1.11.1",prettier:"^3.5.3","semantic-release":"^23.1.1","simple-git-hooks":"^2.13.0",tsx:"^3.14.0",typescript:"^4.9.5","undici-types":"^7.10.0"},Us={extends:["@pvtnbr","prettier"],rules:{"unicorn/no-process-exit":"off"},overrides:[{files:"./src/commands/prepare-commit-msg-hook.ts",rules:{"unicorn/prevent-abbreviations":"off"}}]},zs={branches:["main"],plugins:[["@semantic-release/commit-analyzer",{preset:"conventionalcommits",releaseRules:[{type:"refactor",release:"patch"},{type:"chore",release:"patch"},{type:"feat",release:"patch"},{scope:"major",release:"major"},{scope:"minor",release:"minor"},{scope:"patch",release:"patch"}]}],"@semantic-release/release-notes-generator",["@semantic-release/changelog",{changelogFile:"CHANGELOG.md"}],"@semantic-release/github",["@semantic-release/git",{assets:["CHANGELOG.md"],message:"chore(release): ${nextRelease.version} [skip ci]\n\n${nextRelease.notes}"}],"@semantic-release/npm"]},Ws={name:Rs,version:Ir,description:Os,keywords:Ls,license:Ds,repository:Ts,author:Fs,type:Ns,files:Gs,bin:_s,scripts:js,"simple-git-hooks":{"pre-commit":"pnpm lint-staged"},"lint-staged":{"*.ts":["prettier --config ./.prettierrc --write","eslint --fix"]},dependencies:Hs,devDependencies:Bs,eslintConfig:Us,release:zs},Ks=Xo(import.meta.url),j=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function me(r){return r&&r.__esModule&&Object.prototype.hasOwnProperty.call(r,"default")?r.default:r}var fe={exports:{}},ht,Rr;function Js(){if(Rr)return ht;Rr=1,ht=o,o.sync=s;var r=U;function e(n,i){var c=i.pathExt!==void 0?i.pathExt:process.env.PATHEXT;if(!c||(c=c.split(";"),c.indexOf("")!==-1))return!0;for(var a=0;a<c.length;a++){var m=c[a].toLowerCase();if(m&&n.substr(-m.length).toLowerCase()===m)return!0}return!1}function t(n,i,c){return!n.isSymbolicLink()&&!n.isFile()?!1:e(i,c)}function o(n,i,c){r.stat(n,function(a,m){c(a,a?!1:t(m,n,i))})}function s(n,i){return t(r.statSync(n),n,i)}return ht}var gt,Or;function Ys(){if(Or)return gt;Or=1,gt=e,e.sync=t;var r=U;function e(n,i,c){r.stat(n,function(a,m){c(a,a?!1:o(m,i))})}function t(n,i){return o(r.statSync(n),i)}function o(n,i){return n.isFile()&&s(n,i)}function s(n,i){var c=n.mode,a=n.uid,m=n.gid,d=i.uid!==void 0?i.uid:process.getuid&&process.getuid(),l=i.gid!==void 0?i.gid:process.getgid&&process.getgid(),p=parseInt("100",8),u=parseInt("010",8),h=parseInt("001",8),g=p|u,y=c&h||c&u&&m===l||c&p&&a===d||c&g&&d===0;return y}return gt}var We;process.platform==="win32"||j.TESTING_WINDOWS?We=Js():We=Ys();var Vs=yt;yt.sync=qs;function yt(r,e,t){if(typeof e=="function"&&(t=e,e={}),!t){if(typeof Promise!="function")throw new TypeError("callback not provided");return new Promise(function(o,s){yt(r,e||{},function(n,i){n?s(n):o(i)})})}We(r,e||{},function(o,s){o&&(o.code==="EACCES"||e&&e.ignoreErrors)&&(o=null,s=!1),t(o,s)})}function qs(r,e){try{return We.sync(r,e||{})}catch(t){if(e&&e.ignoreErrors||t.code==="EACCES")return!1;throw t}}const pe=process.platform==="win32"||process.env.OSTYPE==="cygwin"||process.env.OSTYPE==="msys",Lr=x,Xs=pe?";":":",Dr=Vs,Tr=r=>Object.assign(new Error(`not found: ${r}`),{code:"ENOENT"}),Fr=(r,e)=>{const t=e.colon||Xs,o=r.match(/\//)||pe&&r.match(/\\/)?[""]:[...pe?[process.cwd()]:[],...(e.path||process.env.PATH||"").split(t)],s=pe?e.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",n=pe?s.split(t):[""];return pe&&r.indexOf(".")!==-1&&n[0]!==""&&n.unshift(""),{pathEnv:o,pathExt:n,pathExtExe:s}},Nr=(r,e,t)=>{typeof e=="function"&&(t=e,e={}),e||(e={});const{pathEnv:o,pathExt:s,pathExtExe:n}=Fr(r,e),i=[],c=m=>new Promise((d,l)=>{if(m===o.length)return e.all&&i.length?d(i):l(Tr(r));const p=o[m],u=/^".*"$/.test(p)?p.slice(1,-1):p,h=Lr.join(u,r),g=!u&&/^\.[\\\/]/.test(r)?r.slice(0,2)+h:h;d(a(g,m,0))}),a=(m,d,l)=>new Promise((p,u)=>{if(l===s.length)return p(c(d+1));const h=s[l];Dr(m+h,{pathExt:n},(g,y)=>{if(!g&&y)if(e.all)i.push(m+h);else return p(m+h);return p(a(m,d,l+1))})});return t?c(0).then(m=>t(null,m),t):c(0)},Qs=(r,e)=>{e=e||{};const{pathEnv:t,pathExt:o,pathExtExe:s}=Fr(r,e),n=[];for(let i=0;i<t.length;i++){const c=t[i],a=/^".*"$/.test(c)?c.slice(1,-1):c,m=Lr.join(a,r),d=!a&&/^\.[\\\/]/.test(r)?r.slice(0,2)+m:m;for(let l=0;l<o.length;l++){const p=d+o[l];try{if(Dr.sync(p,{pathExt:s}))if(e.all)n.push(p);else return p}catch{}}}if(e.all&&n.length)return n;if(e.nothrow)return null;throw Tr(r)};var Zs=Nr;Nr.sync=Qs;var wt={exports:{}};const Gr=(r={})=>{const e=r.env||process.env;return(r.platform||process.platform)!=="win32"?"PATH":Object.keys(e).reverse().find(o=>o.toUpperCase()==="PATH")||"Path"};wt.exports=Gr,wt.exports.default=Gr;var en=wt.exports;const _r=x,tn=Zs,rn=en;function jr(r,e){const t=r.options.env||process.env,o=process.cwd(),s=r.options.cwd!=null,n=s&&process.chdir!==void 0&&!process.chdir.disabled;if(n)try{process.chdir(r.options.cwd)}catch{}let i;try{i=tn.sync(r.command,{path:t[rn({env:t})],pathExt:e?_r.delimiter:void 0})}catch{}finally{n&&process.chdir(o)}return i&&(i=_r.resolve(s?r.options.cwd:"",i)),i}function on(r){return jr(r)||jr(r,!0)}var sn=on,vt={};const bt=/([()\][%!^"`<>&|;, *?])/g;function nn(r){return r=r.replace(bt,"^$1"),r}function an(r,e){return r=`${r}`,r=r.replace(/(?=(\\+?)?)\1"/g,'$1$1\\"'),r=r.replace(/(?=(\\+?)?)\1$/,"$1$1"),r=`"${r}"`,r=r.replace(bt,"^$1"),e&&(r=r.replace(bt,"^$1")),r}vt.command=nn,vt.argument=an;var cn=/^#!(.*)/;const ln=cn;var un=(r="")=>{const e=r.match(ln);if(!e)return null;const[t,o]=e[0].replace(/#! ?/,"").split(" "),s=t.split("/").pop();return s==="env"?o:o?`${s} ${o}`:s};const Ct=U,dn=un;function mn(r){const t=Buffer.alloc(150);let o;try{o=Ct.openSync(r,"r"),Ct.readSync(o,t,0,150,0),Ct.closeSync(o)}catch{}return dn(t.toString())}var fn=mn;const pn=x,Hr=sn,Br=vt,hn=fn,gn=process.platform==="win32",yn=/\.(?:com|exe)$/i,wn=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function vn(r){r.file=Hr(r);const e=r.file&&hn(r.file);return e?(r.args.unshift(r.file),r.command=e,Hr(r)):r.file}function bn(r){if(!gn)return r;const e=vn(r),t=!yn.test(e);if(r.options.forceShell||t){const o=wn.test(e);r.command=pn.normalize(r.command),r.command=Br.command(r.command),r.args=r.args.map(n=>Br.argument(n,o));const s=[r.command].concat(r.args).join(" ");r.args=["/d","/s","/c",`"${s}"`],r.command=process.env.comspec||"cmd.exe",r.options.windowsVerbatimArguments=!0}return r}function Cn(r,e,t){e&&!Array.isArray(e)&&(t=e,e=null),e=e?e.slice(0):[],t=Object.assign({},t);const o={command:r,args:e,options:t,file:void 0,original:{command:r,args:e}};return t.shell?o:bn(o)}var Pn=Cn;const Pt=process.platform==="win32";function $t(r,e){return Object.assign(new Error(`${e} ${r.command} ENOENT`),{code:"ENOENT",errno:"ENOENT",syscall:`${e} ${r.command}`,path:r.command,spawnargs:r.args})}function $n(r,e){if(!Pt)return;const t=r.emit;r.emit=function(o,s){if(o==="exit"){const n=Ur(s,e);if(n)return t.call(r,"error",n)}return t.apply(r,arguments)}}function Ur(r,e){return Pt&&r===1&&!e.file?$t(e.original,"spawn"):null}function En(r,e){return Pt&&r===1&&!e.file?$t(e.original,"spawnSync"):null}var xn={hookChildProcess:$n,verifyENOENT:Ur,verifyENOENTSync:En,notFoundError:$t};const zr=ts,Et=Pn,xt=xn;function Wr(r,e,t){const o=Et(r,e,t),s=zr.spawn(o.command,o.args,o.options);return xt.hookChildProcess(s,o),s}function kn(r,e,t){const o=Et(r,e,t),s=zr.spawnSync(o.command,o.args,o.options);return s.error=s.error||xt.verifyENOENTSync(s.status,o),s}fe.exports=Wr,fe.exports.spawn=Wr,fe.exports.sync=kn,fe.exports._parse=Et,fe.exports._enoent=xt;var Sn=fe.exports,An=me(Sn);function Mn(r){const e=typeof r=="string"?`
2
+ import{command as oe,cli as Xo}from"cleye";import{createRequire as Qo}from"module";import U from"fs";import xe from"os";import A from"path";import{Buffer as Zo}from"node:buffer";import ce from"node:path";import dr,{ChildProcess as es,exec as ts}from"node:child_process";import se from"node:process";import rs,{execSync as je,exec as os}from"child_process";import{fileURLToPath as mr}from"node:url";import ss,{constants as fr}from"node:os";import pr from"assert";import hr from"events";import{createWriteStream as ns,createReadStream as is}from"node:fs";import as from"buffer";import mt from"stream";import gr,{promisify as cs}from"util";import{debuglog as ls,promisify as us}from"node:util";import He from"inquirer";import C from"chalk";import{of as ft,concatMap as L,from as M,map as I,catchError as R,mergeMap as yr,BehaviorSubject as wr,ReplaySubject as ds,Subscription as pt,lastValueFrom as vr,filter as br,toArray as Cr,Subject as ht}from"rxjs";import ms from"@anthropic-ai/sdk";import{fromPromise as D}from"rxjs/internal/observable/innerFrom";import{xxh64 as Pr}from"@pacote/xxhash";import H from"winston";import O from"fs/promises";import"winston-daily-rotate-file";import fs from"axios";import{CohereClient as ps}from"cohere-ai";import $r from"openai";import{GoogleGenerativeAI as hs,HarmCategory as Be,HarmBlockThreshold as Ue}from"@google/generative-ai";import gs from"http";import ys from"https";import ws from"net";import vs from"tls";import bs,{fileURLToPath as Cs,pathToFileURL as Ps}from"url";import Er from"tty";import $s from"groq-sdk";import{Ollama as Es}from"ollama";import{fetch as xs,Agent as ks}from"undici";import ze from"readline";import xr from"figlet";import Ss from"gradient-string";import kr from"ora";import As from"inquirer-reactive-list-prompt";import{readdir as Sr,stat as Ms,rm as Is}from"node:fs/promises";import Rs from"chokidar";import{takeUntil as Ar,finalize as Mr}from"rxjs/operators";var Os="aicommit2",Ir="2.4.13",Ls="A Reactive CLI that generates commit messages for Git and Jujutsu with various AI",Ds=["cli","ai","git","jujutsu","jj","vcs","version-control","commit","git-commit","jujutsu-commit","command-line","commandline","aipick","aicommit","aicommits","aicommit2","openai","huggingface","anthropic","claude","claude3","gemini","gemini-pro","generative-ai","mistral","ollama","llama3","llama3.2","llama3.3","gemma","llm","chatgpt","cohere","groq","codestral","perplexity","deepseek","deepseek-r1","pre-commit"],Ts="MIT",Fs="tak-bro/aicommit2",Ns="Hyungtak Jin(@tak-bro)",Gs="module",_s=["dist"],js={aicommit2:"./dist/cli.mjs",aic2:"./dist/cli.mjs"},Hs={prepare:"simple-git-hooks",build:"pkgroll --minify",lint:"eslint --cache .","type-check":"tsc",test:"tsx tests",prepack:"pnpm build && clean-pkg-json",prettier:"prettier"},Bs={"@anthropic-ai/sdk":"^0.39.0","@dqbd/tiktoken":"^1.0.21","@google/generative-ai":"^0.24.1","@inquirer/prompts":"^3.3.2","@pacote/xxhash":"^0.3.2","@types/winston":"^2.4.4",axios:"^1.9.0",chalk:"^5.4.1",chokidar:"^4.0.3",cleye:"^1.3.4","cohere-ai":"^7.17.1","copy-paste":"^1.5.3",figlet:"^1.8.1","formdata-node":"^6.0.3","gradient-string":"^3.0.0","groq-sdk":"^0.7.0",inquirer:"9.2.8","inquirer-reactive-list-prompt":"^1.0.16",ollama:"^0.5.15",openai:"^6.3.0",ora:"^8.2.0",readline:"^1.3.0",rxjs:"^7.8.2",undici:"^7.10.0",uuid:"^9.0.1",winston:"^3.17.0","winston-daily-rotate-file":"^5.0.0"},Us={"@pvtnbr/eslint-config":"^0.33.0","@semantic-release/changelog":"^6.0.3","@semantic-release/commit-analyzer":"^12.0.0","@semantic-release/git":"^10.0.1","@semantic-release/github":"^10.3.5","@semantic-release/npm":"^12.0.1","@semantic-release/release-notes-generator":"^13.0.0","@types/figlet":"^1.7.0","@types/ini":"^1.3.34","@types/inquirer":"^9.0.8","@types/node":"^18.19.103","@types/uuid":"^9.0.8","@typescript-eslint/eslint-plugin":"^6.21.0","@typescript-eslint/parser":"^6.21.0","clean-pkg-json":"^1.3.0","conventional-changelog-conventionalcommits":"^7.0.2","conventional-commits-parser":"^5.0.0",eslint:"^8.57.1","eslint-config-prettier":"^8.10.0","eslint-plugin-eslint-comments":"^3.2.0","eslint-plugin-import":"^2.31.0","eslint-plugin-jsonc":"^2.20.1","eslint-plugin-no-use-extend-native":"^0.5.0","eslint-plugin-promise":"^6.6.0","eslint-plugin-unicorn":"^49.0.0","eslint-plugin-unused-imports":"^3.2.0",execa:"^7.2.0","fs-fixture":"^1.2.0","https-proxy-agent":"^5.0.1",ini:"^3.0.1","lint-staged":"^13.3.0",manten:"^0.7.0",pkgroll:"^1.11.1",prettier:"^3.5.3","semantic-release":"^23.1.1","simple-git-hooks":"^2.13.0",tsx:"^3.14.0",typescript:"^4.9.5","undici-types":"^7.10.0"},zs={extends:["@pvtnbr","prettier"],rules:{"unicorn/no-process-exit":"off"},overrides:[{files:"./src/commands/prepare-commit-msg-hook.ts",rules:{"unicorn/prevent-abbreviations":"off"}}]},Ws={branches:["main"],plugins:[["@semantic-release/commit-analyzer",{preset:"conventionalcommits",releaseRules:[{type:"refactor",release:"patch"},{type:"chore",release:"patch"},{type:"feat",release:"patch"},{scope:"major",release:"major"},{scope:"minor",release:"minor"},{scope:"patch",release:"patch"}]}],"@semantic-release/release-notes-generator",["@semantic-release/changelog",{changelogFile:"CHANGELOG.md"}],"@semantic-release/github",["@semantic-release/git",{assets:["CHANGELOG.md"],message:"chore(release): ${nextRelease.version} [skip ci]\n\n${nextRelease.notes}"}],"@semantic-release/npm"]},Ks={name:Os,version:Ir,description:Ls,keywords:Ds,license:Ts,repository:Fs,author:Ns,type:Gs,files:_s,bin:js,scripts:Hs,"simple-git-hooks":{"pre-commit":"pnpm lint-staged"},"lint-staged":{"*.ts":["prettier --config ./.prettierrc --write","eslint --fix"]},dependencies:Bs,devDependencies:Us,eslintConfig:zs,release:Ws},Js=Qo(import.meta.url),j=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function me(r){return r&&r.__esModule&&Object.prototype.hasOwnProperty.call(r,"default")?r.default:r}var fe={exports:{}},gt,Rr;function Ys(){if(Rr)return gt;Rr=1,gt=o,o.sync=s;var r=U;function e(n,i){var c=i.pathExt!==void 0?i.pathExt:process.env.PATHEXT;if(!c||(c=c.split(";"),c.indexOf("")!==-1))return!0;for(var a=0;a<c.length;a++){var m=c[a].toLowerCase();if(m&&n.substr(-m.length).toLowerCase()===m)return!0}return!1}function t(n,i,c){return!n.isSymbolicLink()&&!n.isFile()?!1:e(i,c)}function o(n,i,c){r.stat(n,function(a,m){c(a,a?!1:t(m,n,i))})}function s(n,i){return t(r.statSync(n),n,i)}return gt}var yt,Or;function Vs(){if(Or)return yt;Or=1,yt=e,e.sync=t;var r=U;function e(n,i,c){r.stat(n,function(a,m){c(a,a?!1:o(m,i))})}function t(n,i){return o(r.statSync(n),i)}function o(n,i){return n.isFile()&&s(n,i)}function s(n,i){var c=n.mode,a=n.uid,m=n.gid,u=i.uid!==void 0?i.uid:process.getuid&&process.getuid(),l=i.gid!==void 0?i.gid:process.getgid&&process.getgid(),d=parseInt("100",8),p=parseInt("010",8),g=parseInt("001",8),h=d|p,y=c&g||c&p&&m===l||c&d&&a===u||c&h&&u===0;return y}return yt}var We;process.platform==="win32"||j.TESTING_WINDOWS?We=Ys():We=Vs();var qs=wt;wt.sync=Xs;function wt(r,e,t){if(typeof e=="function"&&(t=e,e={}),!t){if(typeof Promise!="function")throw new TypeError("callback not provided");return new Promise(function(o,s){wt(r,e||{},function(n,i){n?s(n):o(i)})})}We(r,e||{},function(o,s){o&&(o.code==="EACCES"||e&&e.ignoreErrors)&&(o=null,s=!1),t(o,s)})}function Xs(r,e){try{return We.sync(r,e||{})}catch(t){if(e&&e.ignoreErrors||t.code==="EACCES")return!1;throw t}}const pe=process.platform==="win32"||process.env.OSTYPE==="cygwin"||process.env.OSTYPE==="msys",Lr=A,Qs=pe?";":":",Dr=qs,Tr=r=>Object.assign(new Error(`not found: ${r}`),{code:"ENOENT"}),Fr=(r,e)=>{const t=e.colon||Qs,o=r.match(/\//)||pe&&r.match(/\\/)?[""]:[...pe?[process.cwd()]:[],...(e.path||process.env.PATH||"").split(t)],s=pe?e.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",n=pe?s.split(t):[""];return pe&&r.indexOf(".")!==-1&&n[0]!==""&&n.unshift(""),{pathEnv:o,pathExt:n,pathExtExe:s}},Nr=(r,e,t)=>{typeof e=="function"&&(t=e,e={}),e||(e={});const{pathEnv:o,pathExt:s,pathExtExe:n}=Fr(r,e),i=[],c=m=>new Promise((u,l)=>{if(m===o.length)return e.all&&i.length?u(i):l(Tr(r));const d=o[m],p=/^".*"$/.test(d)?d.slice(1,-1):d,g=Lr.join(p,r),h=!p&&/^\.[\\\/]/.test(r)?r.slice(0,2)+g:g;u(a(h,m,0))}),a=(m,u,l)=>new Promise((d,p)=>{if(l===s.length)return d(c(u+1));const g=s[l];Dr(m+g,{pathExt:n},(h,y)=>{if(!h&&y)if(e.all)i.push(m+g);else return d(m+g);return d(a(m,u,l+1))})});return t?c(0).then(m=>t(null,m),t):c(0)},Zs=(r,e)=>{e=e||{};const{pathEnv:t,pathExt:o,pathExtExe:s}=Fr(r,e),n=[];for(let i=0;i<t.length;i++){const c=t[i],a=/^".*"$/.test(c)?c.slice(1,-1):c,m=Lr.join(a,r),u=!a&&/^\.[\\\/]/.test(r)?r.slice(0,2)+m:m;for(let l=0;l<o.length;l++){const d=u+o[l];try{if(Dr.sync(d,{pathExt:s}))if(e.all)n.push(d);else return d}catch{}}}if(e.all&&n.length)return n;if(e.nothrow)return null;throw Tr(r)};var en=Nr;Nr.sync=Zs;var vt={exports:{}};const Gr=(r={})=>{const e=r.env||process.env;return(r.platform||process.platform)!=="win32"?"PATH":Object.keys(e).reverse().find(o=>o.toUpperCase()==="PATH")||"Path"};vt.exports=Gr,vt.exports.default=Gr;var tn=vt.exports;const _r=A,rn=en,on=tn;function jr(r,e){const t=r.options.env||process.env,o=process.cwd(),s=r.options.cwd!=null,n=s&&process.chdir!==void 0&&!process.chdir.disabled;if(n)try{process.chdir(r.options.cwd)}catch{}let i;try{i=rn.sync(r.command,{path:t[on({env:t})],pathExt:e?_r.delimiter:void 0})}catch{}finally{n&&process.chdir(o)}return i&&(i=_r.resolve(s?r.options.cwd:"",i)),i}function sn(r){return jr(r)||jr(r,!0)}var nn=sn,bt={};const Ct=/([()\][%!^"`<>&|;, *?])/g;function an(r){return r=r.replace(Ct,"^$1"),r}function cn(r,e){return r=`${r}`,r=r.replace(/(?=(\\+?)?)\1"/g,'$1$1\\"'),r=r.replace(/(?=(\\+?)?)\1$/,"$1$1"),r=`"${r}"`,r=r.replace(Ct,"^$1"),e&&(r=r.replace(Ct,"^$1")),r}bt.command=an,bt.argument=cn;var ln=/^#!(.*)/;const un=ln;var dn=(r="")=>{const e=r.match(un);if(!e)return null;const[t,o]=e[0].replace(/#! ?/,"").split(" "),s=t.split("/").pop();return s==="env"?o:o?`${s} ${o}`:s};const Pt=U,mn=dn;function fn(r){const t=Buffer.alloc(150);let o;try{o=Pt.openSync(r,"r"),Pt.readSync(o,t,0,150,0),Pt.closeSync(o)}catch{}return mn(t.toString())}var pn=fn;const hn=A,Hr=nn,Br=bt,gn=pn,yn=process.platform==="win32",wn=/\.(?:com|exe)$/i,vn=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function bn(r){r.file=Hr(r);const e=r.file&&gn(r.file);return e?(r.args.unshift(r.file),r.command=e,Hr(r)):r.file}function Cn(r){if(!yn)return r;const e=bn(r),t=!wn.test(e);if(r.options.forceShell||t){const o=vn.test(e);r.command=hn.normalize(r.command),r.command=Br.command(r.command),r.args=r.args.map(n=>Br.argument(n,o));const s=[r.command].concat(r.args).join(" ");r.args=["/d","/s","/c",`"${s}"`],r.command=process.env.comspec||"cmd.exe",r.options.windowsVerbatimArguments=!0}return r}function Pn(r,e,t){e&&!Array.isArray(e)&&(t=e,e=null),e=e?e.slice(0):[],t=Object.assign({},t);const o={command:r,args:e,options:t,file:void 0,original:{command:r,args:e}};return t.shell?o:Cn(o)}var $n=Pn;const $t=process.platform==="win32";function Et(r,e){return Object.assign(new Error(`${e} ${r.command} ENOENT`),{code:"ENOENT",errno:"ENOENT",syscall:`${e} ${r.command}`,path:r.command,spawnargs:r.args})}function En(r,e){if(!$t)return;const t=r.emit;r.emit=function(o,s){if(o==="exit"){const n=Ur(s,e);if(n)return t.call(r,"error",n)}return t.apply(r,arguments)}}function Ur(r,e){return $t&&r===1&&!e.file?Et(e.original,"spawn"):null}function xn(r,e){return $t&&r===1&&!e.file?Et(e.original,"spawnSync"):null}var kn={hookChildProcess:En,verifyENOENT:Ur,verifyENOENTSync:xn,notFoundError:Et};const zr=rs,xt=$n,kt=kn;function Wr(r,e,t){const o=xt(r,e,t),s=zr.spawn(o.command,o.args,o.options);return kt.hookChildProcess(s,o),s}function Sn(r,e,t){const o=xt(r,e,t),s=zr.spawnSync(o.command,o.args,o.options);return s.error=s.error||kt.verifyENOENTSync(s.status,o),s}fe.exports=Wr,fe.exports.spawn=Wr,fe.exports.sync=Sn,fe.exports._parse=xt,fe.exports._enoent=kt;var An=fe.exports,Mn=me(An);function In(r){const e=typeof r=="string"?`
3
3
  `:`
4
- `.charCodeAt(),t=typeof r=="string"?"\r":"\r".charCodeAt();return r[r.length-1]===e&&(r=r.slice(0,-1)),r[r.length-1]===t&&(r=r.slice(0,-1)),r}function Kr(r={}){const{env:e=process.env,platform:t=process.platform}=r;return t!=="win32"?"PATH":Object.keys(e).reverse().find(o=>o.toUpperCase()==="PATH")||"Path"}const In=({cwd:r=se.cwd(),path:e=se.env[Kr()],preferLocal:t=!0,execPath:o=se.execPath,addExecPath:s=!0}={})=>{const n=r instanceof URL?mr(r):r,i=ce.resolve(n),c=[];return t&&Rn(c,i),s&&On(c,o,i),[...c,e].join(ce.delimiter)},Rn=(r,e)=>{let t;for(;t!==e;)r.push(ce.join(e,"node_modules/.bin")),t=e,e=ce.resolve(e,"..")},On=(r,e,t)=>{const o=e instanceof URL?mr(e):e;r.push(ce.resolve(t,o,".."))},Ln=({env:r=se.env,...e}={})=>{r={...r};const t=Kr({env:r});return e.path=r[t],r[t]=In(e),r},Dn=(r,e,t,o)=>{if(t==="length"||t==="prototype"||t==="arguments"||t==="caller")return;const s=Object.getOwnPropertyDescriptor(r,t),n=Object.getOwnPropertyDescriptor(e,t);!Tn(s,n)&&o||Object.defineProperty(r,t,n)},Tn=function(r,e){return r===void 0||r.configurable||r.writable===e.writable&&r.enumerable===e.enumerable&&r.configurable===e.configurable&&(r.writable||r.value===e.value)},Fn=(r,e)=>{const t=Object.getPrototypeOf(e);t!==Object.getPrototypeOf(r)&&Object.setPrototypeOf(r,t)},Nn=(r,e)=>`/* Wrapped ${r}*/
5
- ${e}`,Gn=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),_n=Object.getOwnPropertyDescriptor(Function.prototype.toString,"name"),jn=(r,e,t)=>{const o=t===""?"":`with ${t.trim()}() `,s=Nn.bind(null,o,e.toString());Object.defineProperty(s,"name",_n),Object.defineProperty(r,"toString",{...Gn,value:s})};function Hn(r,e,{ignoreNonConfigurable:t=!1}={}){const{name:o}=r;for(const s of Reflect.ownKeys(e))Dn(r,e,s,t);return Fn(r,e),jn(r,e,o),r}const Ke=new WeakMap,Jr=(r,e={})=>{if(typeof r!="function")throw new TypeError("Expected a function");let t,o=0;const s=r.displayName||r.name||"<anonymous>",n=function(...i){if(Ke.set(n,++o),o===1)t=r.apply(this,i),r=null;else if(e.throw===!0)throw new Error(`Function \`${s}\` can only be called once`);return t};return Hn(n,r),Ke.set(n,o),n};Jr.callCount=r=>{if(!Ke.has(r))throw new Error(`The given function \`${r.name}\` is not wrapped by the \`onetime\` package`);return Ke.get(r)};const Bn=()=>{const r=Vr-Yr+1;return Array.from({length:r},Un)},Un=(r,e)=>({name:`SIGRT${e+1}`,number:Yr+e,action:"terminate",description:"Application-specific signal (realtime)",standard:"posix"}),Yr=34,Vr=64,zn=[{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"}],qr=()=>{const r=Bn();return[...zn,...r].map(Wn)},Wn=({name:r,number:e,description:t,action:o,forced:s=!1,standard:n})=>{const{signals:{[r]:i}}=fr,c=i!==void 0;return{name:r,number:c?i:e,description:t,supported:c,action:o,forced:s,standard:n}},Kn=()=>{const r=qr();return Object.fromEntries(r.map(Jn))},Jn=({name:r,number:e,description:t,supported:o,action:s,forced:n,standard:i})=>[r,{name:r,number:e,description:t,supported:o,action:s,forced:n,standard:i}],Yn=Kn(),Vn=()=>{const r=qr(),e=Vr+1,t=Array.from({length:e},(o,s)=>qn(s,r));return Object.assign({},...t)},qn=(r,e)=>{const t=Xn(r,e);if(t===void 0)return{};const{name:o,description:s,supported:n,action:i,forced:c,standard:a}=t;return{[r]:{name:o,number:r,description:s,supported:n,action:i,forced:c,standard:a}}},Xn=(r,e)=>{const t=e.find(({name:o})=>fr.signals[o]===r);return t!==void 0?t:e.find(o=>o.number===r)};Vn();const Qn=({timedOut:r,timeout:e,errorCode:t,signal:o,signalDescription:s,exitCode:n,isCanceled:i})=>r?`timed out after ${e} milliseconds`:i?"was canceled":t!==void 0?`failed with ${t}`:o!==void 0?`was killed with ${o} (${s})`:n!==void 0?`failed with exit code ${n}`:"failed",Xr=({stdout:r,stderr:e,all:t,error:o,signal:s,exitCode:n,command:i,escapedCommand:c,timedOut:a,isCanceled:m,killed:d,parsed:{options:{timeout:l,cwd:p=se.cwd()}}})=>{n=n===null?void 0:n,s=s===null?void 0:s;const u=s===void 0?void 0:Yn[s].description,h=o&&o.code,y=`Command ${Qn({timedOut:a,timeout:l,errorCode:h,signal:s,signalDescription:u,exitCode:n,isCanceled:m})}: ${i}`,w=Object.prototype.toString.call(o)==="[object Error]",v=w?`${y}
6
- ${o.message}`:y,E=[v,e,r].filter(Boolean).join(`
7
- `);return w?(o.originalMessage=o.message,o.message=E):o=new Error(E),o.shortMessage=v,o.command=i,o.escapedCommand=c,o.exitCode=n,o.signal=s,o.signalDescription=u,o.stdout=r,o.stderr=e,o.cwd=p,t!==void 0&&(o.all=t),"bufferedData"in o&&delete o.bufferedData,o.failed=!0,o.timedOut=!!a,o.isCanceled=m,o.killed=d&&!a,o},Je=["stdin","stdout","stderr"],Zn=r=>Je.some(e=>r[e]!==void 0),ei=r=>{if(!r)return;const{stdio:e}=r;if(e===void 0)return Je.map(o=>r[o]);if(Zn(r))throw new Error(`It's not possible to provide \`stdio\` in combination with one of ${Je.map(o=>`\`${o}\``).join(", ")}`);if(typeof e=="string")return e;if(!Array.isArray(e))throw new TypeError(`Expected \`stdio\` to be of type \`string\` or \`Array\`, got \`${typeof e}\``);const t=Math.max(e.length,Je.length);return Array.from({length:t},(o,s)=>e[s])};var he={exports:{}},Ye={exports:{}};Ye.exports;var Qr;function ti(){return Qr||(Qr=1,function(r){r.exports=["SIGABRT","SIGALRM","SIGHUP","SIGINT","SIGTERM"],process.platform!=="win32"&&r.exports.push("SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT"),process.platform==="linux"&&r.exports.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT","SIGUNUSED")}(Ye)),Ye.exports}var F=j.process;const le=function(r){return r&&typeof r=="object"&&typeof r.removeListener=="function"&&typeof r.emit=="function"&&typeof r.reallyExit=="function"&&typeof r.listeners=="function"&&typeof r.kill=="function"&&typeof r.pid=="number"&&typeof r.on=="function"};if(!le(F))he.exports=function(){return function(){}};else{var ri=pr,ke=ti(),oi=/^win/i.test(F.platform),Ve=hr;typeof Ve!="function"&&(Ve=Ve.EventEmitter);var H;F.__signal_exit_emitter__?H=F.__signal_exit_emitter__:(H=F.__signal_exit_emitter__=new Ve,H.count=0,H.emitted={}),H.infinite||(H.setMaxListeners(1/0),H.infinite=!0),he.exports=function(r,e){if(!le(j.process))return function(){};ri.equal(typeof r,"function","a callback must be provided for exit handler"),Se===!1&&Zr();var t="exit";e&&e.alwaysLast&&(t="afterexit");var o=function(){H.removeListener(t,r),H.listeners("exit").length===0&&H.listeners("afterexit").length===0&&kt()};return H.on(t,r),o};var kt=function(){!Se||!le(j.process)||(Se=!1,ke.forEach(function(e){try{F.removeListener(e,St[e])}catch{}}),F.emit=At,F.reallyExit=eo,H.count-=1)};he.exports.unload=kt;var ge=function(e,t,o){H.emitted[e]||(H.emitted[e]=!0,H.emit(e,t,o))},St={};ke.forEach(function(r){St[r]=function(){if(le(j.process)){var t=F.listeners(r);t.length===H.count&&(kt(),ge("exit",null,r),ge("afterexit",null,r),oi&&r==="SIGHUP"&&(r="SIGINT"),F.kill(F.pid,r))}}}),he.exports.signals=function(){return ke};var Se=!1,Zr=function(){Se||!le(j.process)||(Se=!0,H.count+=1,ke=ke.filter(function(e){try{return F.on(e,St[e]),!0}catch{return!1}}),F.emit=ni,F.reallyExit=si)};he.exports.load=Zr;var eo=F.reallyExit,si=function(e){le(j.process)&&(F.exitCode=e||0,ge("exit",F.exitCode,null),ge("afterexit",F.exitCode,null),eo.call(F,F.exitCode))},At=F.emit,ni=function(e,t){if(e==="exit"&&le(j.process)){t!==void 0&&(F.exitCode=t);var o=At.apply(this,arguments);return ge("exit",F.exitCode,null),ge("afterexit",F.exitCode,null),o}else return At.apply(this,arguments)}}var ii=he.exports,ai=me(ii);const ci=1e3*5,li=(r,e="SIGTERM",t={})=>{const o=r(e);return ui(r,e,t,o),o},ui=(r,e,t,o)=>{if(!di(e,t,o))return;const s=fi(t),n=setTimeout(()=>{r("SIGKILL")},s);n.unref&&n.unref()},di=(r,{forceKillAfterTimeout:e},t)=>mi(r)&&e!==!1&&t,mi=r=>r===os.constants.signals.SIGTERM||typeof r=="string"&&r.toUpperCase()==="SIGTERM",fi=({forceKillAfterTimeout:r=!0})=>{if(r===!0)return ci;if(!Number.isFinite(r)||r<0)throw new TypeError(`Expected the \`forceKillAfterTimeout\` option to be a non-negative integer, got \`${r}\` (${typeof r})`);return r},pi=(r,e)=>{r.kill()&&(e.isCanceled=!0)},hi=(r,e,t)=>{r.kill(e),t(Object.assign(new Error("Timed out"),{timedOut:!0,signal:e}))},gi=(r,{timeout:e,killSignal:t="SIGTERM"},o)=>{if(e===0||e===void 0)return o;let s;const n=new Promise((c,a)=>{s=setTimeout(()=>{hi(r,t,a)},e)}),i=o.finally(()=>{clearTimeout(s)});return Promise.race([n,i])},yi=({timeout:r})=>{if(r!==void 0&&(!Number.isFinite(r)||r<0))throw new TypeError(`Expected the \`timeout\` option to be a non-negative integer, got \`${r}\` (${typeof r})`)},wi=async(r,{cleanup:e,detached:t},o)=>{if(!e||t)return o;const s=ai(()=>{r.kill()});return o.finally(()=>{s()})};function to(r){return r!==null&&typeof r=="object"&&typeof r.pipe=="function"}function ro(r){return to(r)&&r.writable!==!1&&typeof r._write=="function"&&typeof r._writableState=="object"}const vi=r=>r instanceof Zo&&typeof r.then=="function",Mt=(r,e,t)=>{if(typeof t=="string")return r[e].pipe(ss(t)),r;if(ro(t))return r[e].pipe(t),r;if(!vi(t))throw new TypeError("The second argument must be a string, a stream or an Execa child process.");if(!ro(t.stdin))throw new TypeError("The target child process's stdin must be available.");return r[e].pipe(t.stdin),t},bi=r=>{r.stdout!==null&&(r.pipeStdout=Mt.bind(void 0,r,"stdout")),r.stderr!==null&&(r.pipeStderr=Mt.bind(void 0,r,"stderr")),r.all!==void 0&&(r.pipeAll=Mt.bind(void 0,r,"all"))};var Ae={exports:{}};const{PassThrough:Ci}=dt;var Pi=r=>{r={...r};const{array:e}=r;let{encoding:t}=r;const o=t==="buffer";let s=!1;e?s=!(t||o):t=t||"utf8",o&&(t=null);const n=new Ci({objectMode:s});t&&n.setEncoding(t);let i=0;const c=[];return n.on("data",a=>{c.push(a),s?i=c.length:i+=a.length}),n.getBufferedValue=()=>e?c:o?Buffer.concat(c,i):c.join(""),n.getBufferedLength=()=>i,n};const{constants:$i}=is,Ei=dt,{promisify:xi}=gr,ki=Pi,Si=xi(Ei.pipeline);class oo extends Error{constructor(){super("maxBuffer exceeded"),this.name="MaxBufferError"}}async function It(r,e){if(!r)throw new Error("Expected a stream");e={maxBuffer:1/0,...e};const{maxBuffer:t}=e,o=ki(e);return await new Promise((s,n)=>{const i=c=>{c&&o.getBufferedLength()<=$i.MAX_LENGTH&&(c.bufferedData=o.getBufferedValue()),n(c)};(async()=>{try{await Si(r,o),s()}catch(c){i(c)}})(),o.on("data",()=>{o.getBufferedLength()>t&&i(new oo)})}),o.getBufferedValue()}Ae.exports=It,Ae.exports.buffer=(r,e)=>It(r,{...e,encoding:"buffer"}),Ae.exports.array=(r,e)=>It(r,{...e,array:!0}),Ae.exports.MaxBufferError=oo;var Ai=Ae.exports,so=me(Ai);const{PassThrough:Mi}=dt;var Ii=function(){var r=[],e=new Mi({objectMode:!0});return e.setMaxListeners(0),e.add=t,e.isEmpty=o,e.on("unpipe",s),Array.prototype.slice.call(arguments).forEach(t),e;function t(n){return Array.isArray(n)?(n.forEach(t),this):(r.push(n),n.once("end",s.bind(null,n)),n.once("error",e.emit.bind(e,"error")),n.pipe(e,{end:!1}),this)}function o(){return r.length==0}function s(n){r=r.filter(function(i){return i!==n}),!r.length&&e.readable&&e.end()}},Ri=me(Ii);const Oi=r=>{if(r!==void 0)throw new TypeError("The `input` and `inputFile` options cannot be both set.")},Li=({input:r,inputFile:e})=>typeof e!="string"?r:(Oi(r),ns(e)),Di=(r,e)=>{const t=Li(e);t!==void 0&&(to(t)?t.pipe(r.stdin):r.stdin.end(t))},Ti=(r,{all:e})=>{if(!e||!r.stdout&&!r.stderr)return;const t=Ri();return r.stdout&&t.add(r.stdout),r.stderr&&t.add(r.stderr),t},Rt=async(r,e)=>{if(!(!r||e===void 0)){r.destroy();try{return await e}catch(t){return t.bufferedData}}},Ot=(r,{encoding:e,buffer:t,maxBuffer:o})=>{if(!(!r||!t))return e?so(r,{encoding:e,maxBuffer:o}):so.buffer(r,{maxBuffer:o})},Fi=async({stdout:r,stderr:e,all:t},{encoding:o,buffer:s,maxBuffer:n},i)=>{const c=Ot(r,{encoding:o,buffer:s,maxBuffer:n}),a=Ot(e,{encoding:o,buffer:s,maxBuffer:n}),m=Ot(t,{encoding:o,buffer:s,maxBuffer:n*2});try{return await Promise.all([i,c,a,m])}catch(d){return Promise.all([{error:d,signal:d.signal,timedOut:d.timedOut},Rt(r,c),Rt(e,a),Rt(t,m)])}},Ni=(async()=>{})().constructor.prototype,Gi=["then","catch","finally"].map(r=>[r,Reflect.getOwnPropertyDescriptor(Ni,r)]),no=(r,e)=>{for(const[t,o]of Gi){const s=typeof e=="function"?(...n)=>Reflect.apply(o.value,e(),n):o.value.bind(e);Reflect.defineProperty(r,t,{...o,value:s})}},_i=r=>new Promise((e,t)=>{r.on("exit",(o,s)=>{e({exitCode:o,signal:s})}),r.on("error",o=>{t(o)}),r.stdin&&r.stdin.on("error",o=>{t(o)})}),io=(r,e=[])=>Array.isArray(e)?[r,...e]:[r],ji=/^[\w.-]+$/,Hi=/"/g,Bi=r=>typeof r!="string"||ji.test(r)?r:`"${r.replace(Hi,'\\"')}"`,Ui=(r,e)=>io(r,e).join(" "),zi=(r,e)=>io(r,e).map(t=>Bi(t)).join(" "),Wi=cs("execa").enabled,qe=(r,e)=>String(r).padStart(e,"0"),Ki=()=>{const r=new Date;return`${qe(r.getHours(),2)}:${qe(r.getMinutes(),2)}:${qe(r.getSeconds(),2)}.${qe(r.getMilliseconds(),3)}`},Ji=(r,{verbose:e})=>{e&&se.stderr.write(`[${Ki()}] ${r}
8
- `)},Yi=1e3*1e3*100,Vi=({env:r,extendEnv:e,preferLocal:t,localDir:o,execPath:s})=>{const n=e?{...se.env,...r}:r;return t?Ln({env:n,cwd:o,execPath:s}):n},qi=(r,e,t={})=>{const o=An._parse(r,e,t);return r=o.command,e=o.args,t=o.options,t={maxBuffer:Yi,buffer:!0,stripFinalNewline:!0,extendEnv:!0,preferLocal:!1,localDir:t.cwd||se.cwd(),execPath:se.execPath,encoding:"utf8",reject:!0,cleanup:!0,all:!1,windowsHide:!0,verbose:Wi,...t},t.env=Vi(t),t.stdio=ei(t),se.platform==="win32"&&ce.basename(r,".exe")==="cmd"&&e.unshift("/q"),{file:r,args:e,options:t,parsed:o}},Lt=(r,e,t)=>typeof e!="string"&&!Qo.isBuffer(e)?t===void 0?void 0:"":r.stripFinalNewline?Mn(e):e;function N(r,e,t){const o=qi(r,e,t),s=Ui(r,e),n=zi(r,e);Ji(n,o.options),yi(o.options);let i;try{i=dr.spawn(o.file,o.args,o.options)}catch(u){const h=new dr.ChildProcess,g=Promise.reject(Xr({error:u,stdout:"",stderr:"",all:"",command:s,escapedCommand:n,parsed:o,timedOut:!1,isCanceled:!1,killed:!1}));return no(h,g),h}const c=_i(i),a=gi(i,o.options,c),m=wi(i,o.options,a),d={isCanceled:!1};i.kill=li.bind(null,i.kill.bind(i)),i.cancel=pi.bind(null,i,d);const p=Jr(async()=>{const[{error:u,exitCode:h,signal:g,timedOut:y},w,v,E]=await Fi(i,o.options,m),k=Lt(o.options,w),$=Lt(o.options,v),C=Lt(o.options,E);if(u||h!==0||g!==null){const S=Xr({error:u,exitCode:h,signal:g,stdout:k,stderr:$,all:C,command:s,escapedCommand:n,parsed:o,timedOut:y,isCanceled:d.isCanceled||(o.options.signal?o.options.signal.aborted:!1),killed:i.killed});if(!o.options.reject)return S;throw S}return{command:s,escapedCommand:n,exitCode:0,stdout:k,stderr:$,all:C,failed:!1,timedOut:!1,isCanceled:!1,killed:!1}});return Di(i,o.options),i.all=Ti(i,o.options),bi(i),no(i,p),i}class J{static create(e,t){return new e(t)}}const{hasOwnProperty:Dt}=Object.prototype,Xe=typeof process<"u"&&process.platform==="win32"?`\r
4
+ `.charCodeAt(),t=typeof r=="string"?"\r":"\r".charCodeAt();return r[r.length-1]===e&&(r=r.slice(0,-1)),r[r.length-1]===t&&(r=r.slice(0,-1)),r}function Kr(r={}){const{env:e=process.env,platform:t=process.platform}=r;return t!=="win32"?"PATH":Object.keys(e).reverse().find(o=>o.toUpperCase()==="PATH")||"Path"}const Rn=({cwd:r=se.cwd(),path:e=se.env[Kr()],preferLocal:t=!0,execPath:o=se.execPath,addExecPath:s=!0}={})=>{const n=r instanceof URL?mr(r):r,i=ce.resolve(n),c=[];return t&&On(c,i),s&&Ln(c,o,i),[...c,e].join(ce.delimiter)},On=(r,e)=>{let t;for(;t!==e;)r.push(ce.join(e,"node_modules/.bin")),t=e,e=ce.resolve(e,"..")},Ln=(r,e,t)=>{const o=e instanceof URL?mr(e):e;r.push(ce.resolve(t,o,".."))},Dn=({env:r=se.env,...e}={})=>{r={...r};const t=Kr({env:r});return e.path=r[t],r[t]=Rn(e),r},Tn=(r,e,t,o)=>{if(t==="length"||t==="prototype"||t==="arguments"||t==="caller")return;const s=Object.getOwnPropertyDescriptor(r,t),n=Object.getOwnPropertyDescriptor(e,t);!Fn(s,n)&&o||Object.defineProperty(r,t,n)},Fn=function(r,e){return r===void 0||r.configurable||r.writable===e.writable&&r.enumerable===e.enumerable&&r.configurable===e.configurable&&(r.writable||r.value===e.value)},Nn=(r,e)=>{const t=Object.getPrototypeOf(e);t!==Object.getPrototypeOf(r)&&Object.setPrototypeOf(r,t)},Gn=(r,e)=>`/* Wrapped ${r}*/
5
+ ${e}`,_n=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),jn=Object.getOwnPropertyDescriptor(Function.prototype.toString,"name"),Hn=(r,e,t)=>{const o=t===""?"":`with ${t.trim()}() `,s=Gn.bind(null,o,e.toString());Object.defineProperty(s,"name",jn),Object.defineProperty(r,"toString",{..._n,value:s})};function Bn(r,e,{ignoreNonConfigurable:t=!1}={}){const{name:o}=r;for(const s of Reflect.ownKeys(e))Tn(r,e,s,t);return Nn(r,e),Hn(r,e,o),r}const Ke=new WeakMap,Jr=(r,e={})=>{if(typeof r!="function")throw new TypeError("Expected a function");let t,o=0;const s=r.displayName||r.name||"<anonymous>",n=function(...i){if(Ke.set(n,++o),o===1)t=r.apply(this,i),r=null;else if(e.throw===!0)throw new Error(`Function \`${s}\` can only be called once`);return t};return Bn(n,r),Ke.set(n,o),n};Jr.callCount=r=>{if(!Ke.has(r))throw new Error(`The given function \`${r.name}\` is not wrapped by the \`onetime\` package`);return Ke.get(r)};const Un=()=>{const r=Vr-Yr+1;return Array.from({length:r},zn)},zn=(r,e)=>({name:`SIGRT${e+1}`,number:Yr+e,action:"terminate",description:"Application-specific signal (realtime)",standard:"posix"}),Yr=34,Vr=64,Wn=[{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"}],qr=()=>{const r=Un();return[...Wn,...r].map(Kn)},Kn=({name:r,number:e,description:t,action:o,forced:s=!1,standard:n})=>{const{signals:{[r]:i}}=fr,c=i!==void 0;return{name:r,number:c?i:e,description:t,supported:c,action:o,forced:s,standard:n}},Jn=()=>{const r=qr();return Object.fromEntries(r.map(Yn))},Yn=({name:r,number:e,description:t,supported:o,action:s,forced:n,standard:i})=>[r,{name:r,number:e,description:t,supported:o,action:s,forced:n,standard:i}],Vn=Jn(),qn=()=>{const r=qr(),e=Vr+1,t=Array.from({length:e},(o,s)=>Xn(s,r));return Object.assign({},...t)},Xn=(r,e)=>{const t=Qn(r,e);if(t===void 0)return{};const{name:o,description:s,supported:n,action:i,forced:c,standard:a}=t;return{[r]:{name:o,number:r,description:s,supported:n,action:i,forced:c,standard:a}}},Qn=(r,e)=>{const t=e.find(({name:o})=>fr.signals[o]===r);return t!==void 0?t:e.find(o=>o.number===r)};qn();const Zn=({timedOut:r,timeout:e,errorCode:t,signal:o,signalDescription:s,exitCode:n,isCanceled:i})=>r?`timed out after ${e} milliseconds`:i?"was canceled":t!==void 0?`failed with ${t}`:o!==void 0?`was killed with ${o} (${s})`:n!==void 0?`failed with exit code ${n}`:"failed",Xr=({stdout:r,stderr:e,all:t,error:o,signal:s,exitCode:n,command:i,escapedCommand:c,timedOut:a,isCanceled:m,killed:u,parsed:{options:{timeout:l,cwd:d=se.cwd()}}})=>{n=n===null?void 0:n,s=s===null?void 0:s;const p=s===void 0?void 0:Vn[s].description,g=o&&o.code,y=`Command ${Zn({timedOut:a,timeout:l,errorCode:g,signal:s,signalDescription:p,exitCode:n,isCanceled:m})}: ${i}`,w=Object.prototype.toString.call(o)==="[object Error]",b=w?`${y}
6
+ ${o.message}`:y,P=[b,e,r].filter(Boolean).join(`
7
+ `);return w?(o.originalMessage=o.message,o.message=P):o=new Error(P),o.shortMessage=b,o.command=i,o.escapedCommand=c,o.exitCode=n,o.signal=s,o.signalDescription=p,o.stdout=r,o.stderr=e,o.cwd=d,t!==void 0&&(o.all=t),"bufferedData"in o&&delete o.bufferedData,o.failed=!0,o.timedOut=!!a,o.isCanceled=m,o.killed=u&&!a,o},Je=["stdin","stdout","stderr"],ei=r=>Je.some(e=>r[e]!==void 0),ti=r=>{if(!r)return;const{stdio:e}=r;if(e===void 0)return Je.map(o=>r[o]);if(ei(r))throw new Error(`It's not possible to provide \`stdio\` in combination with one of ${Je.map(o=>`\`${o}\``).join(", ")}`);if(typeof e=="string")return e;if(!Array.isArray(e))throw new TypeError(`Expected \`stdio\` to be of type \`string\` or \`Array\`, got \`${typeof e}\``);const t=Math.max(e.length,Je.length);return Array.from({length:t},(o,s)=>e[s])};var he={exports:{}},Ye={exports:{}};Ye.exports;var Qr;function ri(){return Qr||(Qr=1,function(r){r.exports=["SIGABRT","SIGALRM","SIGHUP","SIGINT","SIGTERM"],process.platform!=="win32"&&r.exports.push("SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT"),process.platform==="linux"&&r.exports.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT","SIGUNUSED")}(Ye)),Ye.exports}var F=j.process;const le=function(r){return r&&typeof r=="object"&&typeof r.removeListener=="function"&&typeof r.emit=="function"&&typeof r.reallyExit=="function"&&typeof r.listeners=="function"&&typeof r.kill=="function"&&typeof r.pid=="number"&&typeof r.on=="function"};if(!le(F))he.exports=function(){return function(){}};else{var oi=pr,ke=ri(),si=/^win/i.test(F.platform),Ve=hr;typeof Ve!="function"&&(Ve=Ve.EventEmitter);var B;F.__signal_exit_emitter__?B=F.__signal_exit_emitter__:(B=F.__signal_exit_emitter__=new Ve,B.count=0,B.emitted={}),B.infinite||(B.setMaxListeners(1/0),B.infinite=!0),he.exports=function(r,e){if(!le(j.process))return function(){};oi.equal(typeof r,"function","a callback must be provided for exit handler"),Se===!1&&Zr();var t="exit";e&&e.alwaysLast&&(t="afterexit");var o=function(){B.removeListener(t,r),B.listeners("exit").length===0&&B.listeners("afterexit").length===0&&St()};return B.on(t,r),o};var St=function(){!Se||!le(j.process)||(Se=!1,ke.forEach(function(e){try{F.removeListener(e,At[e])}catch{}}),F.emit=Mt,F.reallyExit=eo,B.count-=1)};he.exports.unload=St;var ge=function(e,t,o){B.emitted[e]||(B.emitted[e]=!0,B.emit(e,t,o))},At={};ke.forEach(function(r){At[r]=function(){if(le(j.process)){var t=F.listeners(r);t.length===B.count&&(St(),ge("exit",null,r),ge("afterexit",null,r),si&&r==="SIGHUP"&&(r="SIGINT"),F.kill(F.pid,r))}}}),he.exports.signals=function(){return ke};var Se=!1,Zr=function(){Se||!le(j.process)||(Se=!0,B.count+=1,ke=ke.filter(function(e){try{return F.on(e,At[e]),!0}catch{return!1}}),F.emit=ii,F.reallyExit=ni)};he.exports.load=Zr;var eo=F.reallyExit,ni=function(e){le(j.process)&&(F.exitCode=e||0,ge("exit",F.exitCode,null),ge("afterexit",F.exitCode,null),eo.call(F,F.exitCode))},Mt=F.emit,ii=function(e,t){if(e==="exit"&&le(j.process)){t!==void 0&&(F.exitCode=t);var o=Mt.apply(this,arguments);return ge("exit",F.exitCode,null),ge("afterexit",F.exitCode,null),o}else return Mt.apply(this,arguments)}}var ai=he.exports,ci=me(ai);const li=1e3*5,ui=(r,e="SIGTERM",t={})=>{const o=r(e);return di(r,e,t,o),o},di=(r,e,t,o)=>{if(!mi(e,t,o))return;const s=pi(t),n=setTimeout(()=>{r("SIGKILL")},s);n.unref&&n.unref()},mi=(r,{forceKillAfterTimeout:e},t)=>fi(r)&&e!==!1&&t,fi=r=>r===ss.constants.signals.SIGTERM||typeof r=="string"&&r.toUpperCase()==="SIGTERM",pi=({forceKillAfterTimeout:r=!0})=>{if(r===!0)return li;if(!Number.isFinite(r)||r<0)throw new TypeError(`Expected the \`forceKillAfterTimeout\` option to be a non-negative integer, got \`${r}\` (${typeof r})`);return r},hi=(r,e)=>{r.kill()&&(e.isCanceled=!0)},gi=(r,e,t)=>{r.kill(e),t(Object.assign(new Error("Timed out"),{timedOut:!0,signal:e}))},yi=(r,{timeout:e,killSignal:t="SIGTERM"},o)=>{if(e===0||e===void 0)return o;let s;const n=new Promise((c,a)=>{s=setTimeout(()=>{gi(r,t,a)},e)}),i=o.finally(()=>{clearTimeout(s)});return Promise.race([n,i])},wi=({timeout:r})=>{if(r!==void 0&&(!Number.isFinite(r)||r<0))throw new TypeError(`Expected the \`timeout\` option to be a non-negative integer, got \`${r}\` (${typeof r})`)},vi=async(r,{cleanup:e,detached:t},o)=>{if(!e||t)return o;const s=ci(()=>{r.kill()});return o.finally(()=>{s()})};function to(r){return r!==null&&typeof r=="object"&&typeof r.pipe=="function"}function ro(r){return to(r)&&r.writable!==!1&&typeof r._write=="function"&&typeof r._writableState=="object"}const bi=r=>r instanceof es&&typeof r.then=="function",It=(r,e,t)=>{if(typeof t=="string")return r[e].pipe(ns(t)),r;if(ro(t))return r[e].pipe(t),r;if(!bi(t))throw new TypeError("The second argument must be a string, a stream or an Execa child process.");if(!ro(t.stdin))throw new TypeError("The target child process's stdin must be available.");return r[e].pipe(t.stdin),t},Ci=r=>{r.stdout!==null&&(r.pipeStdout=It.bind(void 0,r,"stdout")),r.stderr!==null&&(r.pipeStderr=It.bind(void 0,r,"stderr")),r.all!==void 0&&(r.pipeAll=It.bind(void 0,r,"all"))};var Ae={exports:{}};const{PassThrough:Pi}=mt;var $i=r=>{r={...r};const{array:e}=r;let{encoding:t}=r;const o=t==="buffer";let s=!1;e?s=!(t||o):t=t||"utf8",o&&(t=null);const n=new Pi({objectMode:s});t&&n.setEncoding(t);let i=0;const c=[];return n.on("data",a=>{c.push(a),s?i=c.length:i+=a.length}),n.getBufferedValue=()=>e?c:o?Buffer.concat(c,i):c.join(""),n.getBufferedLength=()=>i,n};const{constants:Ei}=as,xi=mt,{promisify:ki}=gr,Si=$i,Ai=ki(xi.pipeline);class oo extends Error{constructor(){super("maxBuffer exceeded"),this.name="MaxBufferError"}}async function Rt(r,e){if(!r)throw new Error("Expected a stream");e={maxBuffer:1/0,...e};const{maxBuffer:t}=e,o=Si(e);return await new Promise((s,n)=>{const i=c=>{c&&o.getBufferedLength()<=Ei.MAX_LENGTH&&(c.bufferedData=o.getBufferedValue()),n(c)};(async()=>{try{await Ai(r,o),s()}catch(c){i(c)}})(),o.on("data",()=>{o.getBufferedLength()>t&&i(new oo)})}),o.getBufferedValue()}Ae.exports=Rt,Ae.exports.buffer=(r,e)=>Rt(r,{...e,encoding:"buffer"}),Ae.exports.array=(r,e)=>Rt(r,{...e,array:!0}),Ae.exports.MaxBufferError=oo;var Mi=Ae.exports,so=me(Mi);const{PassThrough:Ii}=mt;var Ri=function(){var r=[],e=new Ii({objectMode:!0});return e.setMaxListeners(0),e.add=t,e.isEmpty=o,e.on("unpipe",s),Array.prototype.slice.call(arguments).forEach(t),e;function t(n){return Array.isArray(n)?(n.forEach(t),this):(r.push(n),n.once("end",s.bind(null,n)),n.once("error",e.emit.bind(e,"error")),n.pipe(e,{end:!1}),this)}function o(){return r.length==0}function s(n){r=r.filter(function(i){return i!==n}),!r.length&&e.readable&&e.end()}},Oi=me(Ri);const Li=r=>{if(r!==void 0)throw new TypeError("The `input` and `inputFile` options cannot be both set.")},Di=({input:r,inputFile:e})=>typeof e!="string"?r:(Li(r),is(e)),Ti=(r,e)=>{const t=Di(e);t!==void 0&&(to(t)?t.pipe(r.stdin):r.stdin.end(t))},Fi=(r,{all:e})=>{if(!e||!r.stdout&&!r.stderr)return;const t=Oi();return r.stdout&&t.add(r.stdout),r.stderr&&t.add(r.stderr),t},Ot=async(r,e)=>{if(!(!r||e===void 0)){r.destroy();try{return await e}catch(t){return t.bufferedData}}},Lt=(r,{encoding:e,buffer:t,maxBuffer:o})=>{if(!(!r||!t))return e?so(r,{encoding:e,maxBuffer:o}):so.buffer(r,{maxBuffer:o})},Ni=async({stdout:r,stderr:e,all:t},{encoding:o,buffer:s,maxBuffer:n},i)=>{const c=Lt(r,{encoding:o,buffer:s,maxBuffer:n}),a=Lt(e,{encoding:o,buffer:s,maxBuffer:n}),m=Lt(t,{encoding:o,buffer:s,maxBuffer:n*2});try{return await Promise.all([i,c,a,m])}catch(u){return Promise.all([{error:u,signal:u.signal,timedOut:u.timedOut},Ot(r,c),Ot(e,a),Ot(t,m)])}},Gi=(async()=>{})().constructor.prototype,_i=["then","catch","finally"].map(r=>[r,Reflect.getOwnPropertyDescriptor(Gi,r)]),no=(r,e)=>{for(const[t,o]of _i){const s=typeof e=="function"?(...n)=>Reflect.apply(o.value,e(),n):o.value.bind(e);Reflect.defineProperty(r,t,{...o,value:s})}},ji=r=>new Promise((e,t)=>{r.on("exit",(o,s)=>{e({exitCode:o,signal:s})}),r.on("error",o=>{t(o)}),r.stdin&&r.stdin.on("error",o=>{t(o)})}),io=(r,e=[])=>Array.isArray(e)?[r,...e]:[r],Hi=/^[\w.-]+$/,Bi=/"/g,Ui=r=>typeof r!="string"||Hi.test(r)?r:`"${r.replace(Bi,'\\"')}"`,zi=(r,e)=>io(r,e).join(" "),Wi=(r,e)=>io(r,e).map(t=>Ui(t)).join(" "),Ki=ls("execa").enabled,qe=(r,e)=>String(r).padStart(e,"0"),Ji=()=>{const r=new Date;return`${qe(r.getHours(),2)}:${qe(r.getMinutes(),2)}:${qe(r.getSeconds(),2)}.${qe(r.getMilliseconds(),3)}`},Yi=(r,{verbose:e})=>{e&&se.stderr.write(`[${Ji()}] ${r}
8
+ `)},Vi=1e3*1e3*100,qi=({env:r,extendEnv:e,preferLocal:t,localDir:o,execPath:s})=>{const n=e?{...se.env,...r}:r;return t?Dn({env:n,cwd:o,execPath:s}):n},Xi=(r,e,t={})=>{const o=Mn._parse(r,e,t);return r=o.command,e=o.args,t=o.options,t={maxBuffer:Vi,buffer:!0,stripFinalNewline:!0,extendEnv:!0,preferLocal:!1,localDir:t.cwd||se.cwd(),execPath:se.execPath,encoding:"utf8",reject:!0,cleanup:!0,all:!1,windowsHide:!0,verbose:Ki,...t},t.env=qi(t),t.stdio=ti(t),se.platform==="win32"&&ce.basename(r,".exe")==="cmd"&&e.unshift("/q"),{file:r,args:e,options:t,parsed:o}},Dt=(r,e,t)=>typeof e!="string"&&!Zo.isBuffer(e)?t===void 0?void 0:"":r.stripFinalNewline?In(e):e;function N(r,e,t){const o=Xi(r,e,t),s=zi(r,e),n=Wi(r,e);Yi(n,o.options),wi(o.options);let i;try{i=dr.spawn(o.file,o.args,o.options)}catch(p){const g=new dr.ChildProcess,h=Promise.reject(Xr({error:p,stdout:"",stderr:"",all:"",command:s,escapedCommand:n,parsed:o,timedOut:!1,isCanceled:!1,killed:!1}));return no(g,h),g}const c=ji(i),a=yi(i,o.options,c),m=vi(i,o.options,a),u={isCanceled:!1};i.kill=ui.bind(null,i.kill.bind(i)),i.cancel=hi.bind(null,i,u);const d=Jr(async()=>{const[{error:p,exitCode:g,signal:h,timedOut:y},w,b,P]=await Ni(i,o.options,m),S=Dt(o.options,w),k=Dt(o.options,b),$=Dt(o.options,P);if(p||g!==0||h!==null){const x=Xr({error:p,exitCode:g,signal:h,stdout:S,stderr:k,all:$,command:s,escapedCommand:n,parsed:o,timedOut:y,isCanceled:u.isCanceled||(o.options.signal?o.options.signal.aborted:!1),killed:i.killed});if(!o.options.reject)return x;throw x}return{command:s,escapedCommand:n,exitCode:0,stdout:S,stderr:k,all:$,failed:!1,timedOut:!1,isCanceled:!1,killed:!1}});return Ti(i,o.options),i.all=Fi(i,o.options),Ci(i),no(i,d),i}class J{static create(e,t){return new e(t)}}const{hasOwnProperty:Tt}=Object.prototype,Xe=typeof process<"u"&&process.platform==="win32"?`\r
9
9
  `:`
10
- `,Tt=(r,e)=>{const t=[];let o="";typeof e=="string"?e={section:e,whitespace:!1}:(e=e||Object.create(null),e.whitespace=e.whitespace===!0);const s=e.whitespace?" = ":"=";for(const n of Object.keys(r)){const i=r[n];if(i&&Array.isArray(i))for(const c of i)o+=ye(n+"[]")+s+ye(c)+Xe;else i&&typeof i=="object"?t.push(n):o+=ye(n)+s+ye(i)+Xe}e.section&&o.length&&(o="["+ye(e.section)+"]"+Xe+o);for(const n of t){const i=ao(n).join("\\."),c=(e.section?e.section+".":"")+i,{whitespace:a}=e,m=Tt(r[n],{section:c,whitespace:a});o.length&&m.length&&(o+=Xe),o+=m}return o},ao=r=>r.replace(/\1/g,"LITERAL\\1LITERAL").replace(/\\\./g,"").split(/\./).map(e=>e.replace(/\1/g,"\\.").replace(/\2LITERAL\\1LITERAL\2/g,"")),co=r=>{const e=Object.create(null);let t=e,o=null;const s=/^\[([^\]]*)\]$|^([^=]+)(=(.*))?$/i,n=r.split(/[\r\n]+/g);for(const c of n){if(!c||c.match(/^\s*[;#]/))continue;const a=c.match(s);if(!a)continue;if(a[1]!==void 0){if(o=Qe(a[1]),o==="__proto__"){t=Object.create(null);continue}t=e[o]=e[o]||Object.create(null);continue}const m=Qe(a[2]),d=m.length>2&&m.slice(-2)==="[]",l=d?m.slice(0,-2):m;if(l==="__proto__")continue;const p=a[3]?Qe(a[4]):!0,u=p==="true"||p==="false"||p==="null"?JSON.parse(p):p;d&&(Dt.call(t,l)?Array.isArray(t[l])||(t[l]=[t[l]]):t[l]=[]),Array.isArray(t[l])?t[l].push(u):t[l]=u}const i=[];for(const c of Object.keys(e)){if(!Dt.call(e,c)||typeof e[c]!="object"||Array.isArray(e[c]))continue;const a=ao(c);t=e;const m=a.pop(),d=m.replace(/\\\./g,".");for(const l of a)l!=="__proto__"&&((!Dt.call(t,l)||typeof t[l]!="object")&&(t[l]=Object.create(null)),t=t[l]);t===e&&d===m||(t[d]=e[c],i.push(c))}for(const c of i)delete e[c];return e},lo=r=>r.startsWith('"')&&r.endsWith('"')||r.startsWith("'")&&r.endsWith("'"),ye=r=>typeof r!="string"||r.match(/[=\r\n]/)||r.match(/^\[/)||r.length>1&&lo(r)||r!==r.trim()?JSON.stringify(r):r.split(";").join("\\;").split("#").join("\\#"),Qe=(r,e)=>{if(r=(r||"").trim(),lo(r)){r.charAt(0)==="'"&&(r=r.slice(1,-1));try{r=JSON.parse(r)}catch{}}else{let t=!1,o="";for(let s=0,n=r.length;s<n;s++){const i=r.charAt(s);if(t)"\\;#".indexOf(i)!==-1?o+=i:o+="\\"+i,t=!1;else{if(";#".indexOf(i)!==-1)break;i==="\\"?t=!0:o+=i}}return t&&(o+="\\"),o.trim()}return r};var Xi={parse:co,decode:co,stringify:Tt,encode:Tt,safe:ye,unsafe:Qe},we=me(Xi);class b extends Error{}const Ft=" ",ie=r=>{r instanceof Error&&(r instanceof b||(r.stack&&console.error(P.dim(r.stack.split(`
10
+ `,Ft=(r,e)=>{const t=[];let o="";typeof e=="string"?e={section:e,whitespace:!1}:(e=e||Object.create(null),e.whitespace=e.whitespace===!0);const s=e.whitespace?" = ":"=";for(const n of Object.keys(r)){const i=r[n];if(i&&Array.isArray(i))for(const c of i)o+=ye(n+"[]")+s+ye(c)+Xe;else i&&typeof i=="object"?t.push(n):o+=ye(n)+s+ye(i)+Xe}e.section&&o.length&&(o="["+ye(e.section)+"]"+Xe+o);for(const n of t){const i=ao(n).join("\\."),c=(e.section?e.section+".":"")+i,{whitespace:a}=e,m=Ft(r[n],{section:c,whitespace:a});o.length&&m.length&&(o+=Xe),o+=m}return o},ao=r=>r.replace(/\1/g,"LITERAL\\1LITERAL").replace(/\\\./g,"").split(/\./).map(e=>e.replace(/\1/g,"\\.").replace(/\2LITERAL\\1LITERAL\2/g,"")),co=r=>{const e=Object.create(null);let t=e,o=null;const s=/^\[([^\]]*)\]$|^([^=]+)(=(.*))?$/i,n=r.split(/[\r\n]+/g);for(const c of n){if(!c||c.match(/^\s*[;#]/))continue;const a=c.match(s);if(!a)continue;if(a[1]!==void 0){if(o=Qe(a[1]),o==="__proto__"){t=Object.create(null);continue}t=e[o]=e[o]||Object.create(null);continue}const m=Qe(a[2]),u=m.length>2&&m.slice(-2)==="[]",l=u?m.slice(0,-2):m;if(l==="__proto__")continue;const d=a[3]?Qe(a[4]):!0,p=d==="true"||d==="false"||d==="null"?JSON.parse(d):d;u&&(Tt.call(t,l)?Array.isArray(t[l])||(t[l]=[t[l]]):t[l]=[]),Array.isArray(t[l])?t[l].push(p):t[l]=p}const i=[];for(const c of Object.keys(e)){if(!Tt.call(e,c)||typeof e[c]!="object"||Array.isArray(e[c]))continue;const a=ao(c);t=e;const m=a.pop(),u=m.replace(/\\\./g,".");for(const l of a)l!=="__proto__"&&((!Tt.call(t,l)||typeof t[l]!="object")&&(t[l]=Object.create(null)),t=t[l]);t===e&&u===m||(t[u]=e[c],i.push(c))}for(const c of i)delete e[c];return e},lo=r=>r.startsWith('"')&&r.endsWith('"')||r.startsWith("'")&&r.endsWith("'"),ye=r=>typeof r!="string"||r.match(/[=\r\n]/)||r.match(/^\[/)||r.length>1&&lo(r)||r!==r.trim()?JSON.stringify(r):r.split(";").join("\\;").split("#").join("\\#"),Qe=(r,e)=>{if(r=(r||"").trim(),lo(r)){r.charAt(0)==="'"&&(r=r.slice(1,-1));try{r=JSON.parse(r)}catch{}}else{let t=!1,o="";for(let s=0,n=r.length;s<n;s++){const i=r.charAt(s);if(t)"\\;#".indexOf(i)!==-1?o+=i:o+="\\"+i,t=!1;else{if(";#".indexOf(i)!==-1)break;i==="\\"?t=!0:o+=i}}return t&&(o+="\\"),o.trim()}return r};var Qi={parse:co,decode:co,stringify:Ft,encode:Ft,safe:ye,unsafe:Qe},we=me(Qi);class v extends Error{}const Nt=" ",ie=r=>{r instanceof Error&&(r instanceof v||(r.stack&&console.error(C.dim(r.stack.split(`
11
11
  `).slice(1).join(`
12
12
  `))),console.error(`
13
- ${Ft}${P.dim(`aicommit2 v${Ir}`)}`),console.error(`
14
- ${Ft}Please open a Bug report with the information above:`),console.error(`${Ft}https://github.com/tak-bro/aicommit2/issues/new/choose`)))},uo=r=>R.lstat(r).then(()=>!0,()=>!1),mo=async r=>{try{await R.mkdir(r,{recursive:!0})}catch(e){if(e.code!=="EEXIST")throw e}},Ze=r=>r&&`${r[0].toUpperCase()}${r.slice(1)}`,et=(r,e)=>{const t=Math.ceil(r),o=Math.floor(e);return Math.floor(Math.random()*(o-t+1))+t},Qi=(r,e)=>r.disabled&&!e.disabled?1:!r.disabled&&e.disabled?-1:0,tt=r=>r.reduce((e,t)=>Array.isArray(t)?e.concat(tt(t)):e.concat(t),[]),fo=(r,e=5)=>r.replace(/[\n\r]/g,"").split(" ").slice(0,e).join(" "),Zi=r=>{let e=0;for(let t=0;t<r.length;t++){const o=r.charCodeAt(t);e=(e<<5)-e+o,e=e&e}return Math.abs(e)},ea=r=>{const e=r%360,t=65+r%15,o=45+r%10;return`hsl(${e}, ${t}%, ${o}%)`},ta=r=>{const[e,t,o]=r.match(/\d+/g).map((l,p)=>p===0?Number(l):Number(l)/100),s=(1-Math.abs(2*o-1))*t,n=s*(1-Math.abs(e/60%2-1)),i=o-s/2;let c,a,m;e<60?[c,a,m]=[s,n,0]:e<120?[c,a,m]=[n,s,0]:e<180?[c,a,m]=[0,s,n]:e<240?[c,a,m]=[0,n,s]:e<300?[c,a,m]=[n,0,s]:[c,a,m]=[s,0,n];const d=l=>{const p=Math.round((l+i)*255).toString(16);return p.length===1?"0"+p:p};return`#${d(c)}${d(a)}${d(m)}`},ra=r=>{const e=Zi(r),t=ea(e);return{primary:ta(t),secondary:"#FFFFFF"}},oa=r=>{try{return{ok:!0,data:JSON.parse(r)}}catch(e){return{ok:!1,error:e}}},rt=r=>{if(!r||typeof r!="string")return"";if(x.isAbsolute(r))return x.resolve(r);if(Ie){const e=x.dirname(Ie),t=x.join(e,r);return x.resolve(t)}else return""},sa=["","conventional","gitmoji"],Nt="http://localhost:11434",{hasOwnProperty:na}=Object.prototype,Gt=(r,e)=>na.call(r,e),ve=["OPENAI","OLLAMA","HUGGINGFACE","GEMINI","ANTHROPIC","MISTRAL","CODESTRAL","COHERE","GROQ","PERPLEXITY","DEEPSEEK","GITHUB_MODELS"],po=r=>{const e=xe.platform(),t=xe.homedir();let o,s;switch(r){case"config":o=process.env.XDG_CONFIG_HOME;break;case"data":o=process.env.XDG_DATA_HOME;break;case"cache":o=process.env.XDG_CACHE_HOME;break;case"state":o=process.env.XDG_STATE_HOME;break;default:o=void 0}if(e==="darwin")r==="cache"?s=x.join(t,"Library","Caches"):s=x.join(t,"Library","Application Support");else if(e==="win32")s=process.env.LOCALAPPDATA||t;else switch(r){case"config":s=x.join(t,".config");break;case"data":s=x.join(t,".local","share");break;case"cache":s=x.join(t,".cache");break;case"state":s=x.join(t,".local","state");break;default:s=t}return o||s},ia=x.join(po("config"),"aicommit2"),ee=x.join(po("state"),"aicommit2","logs"),ho=x.join(ia,"config.ini"),go=x.join(ee,"aicommit2-%DATE%.log"),yo=x.join(ee,"exceptions-%DATE%.log"),aa=r=>{const e=Object.keys(r),t=new Set([...ve,...e.filter(o=>/^[A-Z][A-Z0-9_]*$/.test(o))]);return Array.from(t)},D=(r,e,t)=>{if(!e)throw new b(`Invalid config property ${r}: ${t}`)},ne=(r,e=!1)=>t=>typeof t=="boolean"?t:t==null?e:(D(r,/^(?:true|false)$/.test(t),"Must be a boolean(true or false)"),t==="true"),f={systemPrompt(r){return r||""},systemPromptPath(r){return r||""},codeReviewPromptPath(r){return r||""},timeout(r){if(!r)return 1e4;D("timeout",/^\d+$/.test(r),"Must be an integer");const e=Number(r);return D("timeout",e>=500,"Must be greater than 500ms"),e},temperature(r){if(!r)return .7;D("temperature",/^(2|\d)(\.\d{1,2})?$/.test(r),"Must be decimal between 0 and 2");const e=Number(r);return D("temperature",e>0,"Must be greater than 0"),D("temperature",e<=2,"Must be less than or equal to 2"),e},maxTokens(r){return r?(D("maxTokens",/^\d+$/.test(r),"Must be an integer"),Number(r)):1024},logLevel(r){return r?(D("logLevel",/^(?:error|warn|info|http|verbose|debug|silly)$/.test(r),"Must be a valid log level (error, warn, info, http, verbose, debug, silly)"),r):"info"},logFilePath(r){return r||go},exceptionLogFilePath(r){return r||yo},locale(r){return r?(D("locale",r,"Cannot be empty"),D("locale",/^[a-z-]+$/i.test(r),"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"),r):"en"},generate(r){if(!r)return 1;D("generate",/^\d+$/.test(r),"Must be an integer");const e=Number(r);return D("generate",e>0,"Must be greater than 0"),D("generate",e<=5,"Must be less or equal to 5"),e},type(r){return r?(D("type",sa.includes(r),"Invalid commit type"),r):"conventional"},maxLength(r){if(!r)return 50;D("maxLength",/^\d+$/.test(r),"Must be an integer");const e=Number(r);return D("maxLength",e>=20,"Must be greater than 20 characters"),e},exclude:r=>r?(typeof r=="string"?r?.split(","):r).map(t=>t.trim()).filter(t=>!!t&&t.length>0):[],topP:r=>{if(!r)return .9;D("topP",/^(1|\d)(\.\d{1,2})?$/.test(r),"Must be decimal between 0 and 1");const e=Number(r);return D("topP",e>0,"Must be greater than 0"),D("topP",e<=1,"Must be less than or equal to 1"),e},logging:ne("logging",!0),includeBody:ne("includeBody"),codeReview:ne("codeReview"),disabled:ne("disabled"),watchMode:ne("watchMode"),forceGit:ne("forceGit"),disableLowerCase:ne("disableLowerCase")},Me={OPENAI:{key:r=>r||"",envKey:r=>r||"",model:r=>r?(typeof r=="string"?r?.split(","):r).map(t=>t.trim()).filter(t=>!!t&&t.length>0):["gpt-4o-mini"],url:r=>r?(D("OPENAI.url",/^https?:\/\//.test(r),"Must be a valid URL"),r):"https://api.openai.com",path:r=>r||"/v1/chat/completions",proxy:r=>r||"",topP:f.topP,systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,timeout:f.timeout,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode,disableLowerCase:f.disableLowerCase},HUGGINGFACE:{cookie:r=>r||"",model:r=>r?(typeof r=="string"?r?.split(","):r).map(t=>t.trim()).filter(t=>!!t&&t.length>0):["CohereForAI/c4ai-command-r-plus"],systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,timeout:f.timeout,temperature:f.temperature,maxTokens:f.maxTokens,topP:f.topP,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode,disableLowerCase:f.disableLowerCase},GEMINI:{key:r=>r||"",envKey:r=>r||"",model:r=>r?(typeof r=="string"?r?.split(","):r).map(t=>t.trim()).filter(t=>!!t&&t.length>0):["gemini-2.0-flash"],systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,topP:f.topP,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode,disableLowerCase:f.disableLowerCase},ANTHROPIC:{key:r=>r||"",envKey:r=>r||"",model:r=>r?(typeof r=="string"?r?.split(","):r).map(t=>t.trim()).filter(t=>!!t&&t.length>0):["claude-3-5-haiku-20241022"],systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,topP:f.topP,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode,disableLowerCase:f.disableLowerCase},MISTRAL:{key:r=>r||"",envKey:r=>r||"",model:r=>r?(typeof r=="string"?r?.split(","):r).map(t=>t.trim()).filter(t=>!!t&&t.length>0):["mistral-small-latest"],systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,timeout:f.timeout,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,topP:f.topP,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode,disableLowerCase:f.disableLowerCase},CODESTRAL:{key:r=>r||"",envKey:r=>r||"",model:r=>r?(typeof r=="string"?r?.split(","):r).map(t=>t.trim()).filter(t=>!!t&&t.length>0):["codestral-latest"],topP:f.topP,systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,timeout:f.timeout,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode,disableLowerCase:f.disableLowerCase},OLLAMA:{model:r=>r?(typeof r=="string"?r?.split(","):r).map(t=>t.trim()).filter(t=>!!t&&t.length>0):[],host:r=>r?(D("OLLAMA.host",/^https?:\/\//.test(r),"Must be a valid URL"),r):Nt,timeout:r=>{if(!r)return 1e5;D("OLLAMA.timeout",/^\d+$/.test(r),"Must be an integer");const e=Number(r);return D("OLLAMA.timeout",e>=500,"Must be greater than 500ms"),e},auth:r=>r||"",key:r=>r||"",envKey:r=>r||"",numCtx:r=>{if(!r)return 2048;D("OLLAMA.numCtx",/^\d+$/.test(r),"Must be an integer");const e=Number(r);return D("OLLAMA.numCtx",e>=2048,"Must be greater than 2048"),e},systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,topP:f.topP,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode,disableLowerCase:f.disableLowerCase},COHERE:{key:r=>r||"",envKey:r=>r||"",model:r=>r?(typeof r=="string"?r?.split(","):r).map(t=>t.trim()).filter(t=>!!t&&t.length>0):["command-r"],systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,topP:f.topP,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode,disableLowerCase:f.disableLowerCase},GROQ:{key:r=>r||"",envKey:r=>r||"",model:r=>r?(typeof r=="string"?r?.split(","):r).map(t=>t.trim()).filter(t=>!!t&&t.length>0):["llama-3.3-70b-versatile"],systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,timeout:f.timeout,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,topP:f.topP,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode,disableLowerCase:f.disableLowerCase},PERPLEXITY:{key:r=>r||"",envKey:r=>r||"",model:r=>r?(typeof r=="string"?r?.split(","):r).map(t=>t.trim()).filter(t=>!!t&&t.length>0):["sonar"],topP:f.topP,systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,timeout:f.timeout,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode,disableLowerCase:f.disableLowerCase},DEEPSEEK:{key:r=>r||"",envKey:r=>r||"",model:r=>r?(typeof r=="string"?r?.split(","):r).map(t=>t.trim()).filter(t=>!!t&&t.length>0):["deepseek-coder"],topP:f.topP,systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,timeout:f.timeout,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode,disableLowerCase:f.disableLowerCase},GITHUB_MODELS:{key:r=>r||"",envKey:r=>r||"",model:r=>r?(typeof r=="string"?r?.split(","):r).map(t=>t.trim()).filter(t=>!!t&&t.length>0):["gpt-4o-mini"],systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,timeout:f.timeout,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,topP:f.topP,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode,disableLowerCase:f.disableLowerCase}};let Ie;const ca=(r=[])=>{const e={};for(const t of r)if(t.startsWith("--")){const[o,s]=t.slice(2).split("="),[n,i]=o.split(".");n&&i&&n in Me?(e[n]||(e[n]={}),e[n][i]=s):e[o]=s}return e},la=()=>{const r=xe.homedir(),e=process.env.AICOMMIT_CONFIG_PATH,t=ho,o=x.join(r,".aicommit2");return[e,t,o].filter(s=>!!s)},be=async()=>{const r=la();for(const e of r)if(await uo(e))return e;return ho},Re=async()=>{const r=await be();Ie=r;try{const e=await R.readFile(r,"utf8");return we.parse(e)}catch(e){return e.code==="ENOENT"?(Ie=void 0,{}):(console.error(`Error reading config file ${r}:`,e),Ie=void 0,{})}},ue=async(r,e=[])=>{const t=await Re(),o=ca(e),s={...r,...o},n={},i=aa(t),c={};for(const m of i){const l=t[m]?.envKey||`${m}_API_KEY`,p=process.env[l];p&&(c[m]={key:p})}const a=(m,d)=>{const l=s[`${m}.${d}`]??s[m]?.[d],p=c[m]?.[d],u=t[m]?.[d],h=s[d]??t[d];return l!==void 0?l:p!==void 0?p:u!==void 0?u:h};for(const[m,d]of Object.entries(f)){const l=s[m]??t[m];n[m]=d(l)}for(const m of i){n[m]={};const d=Me[m]||ot(m);for(const[l,p]of Object.entries(d)){const u=a(m,l);n[m][l]=p(u)}}return n},_t=async r=>{const e=await Re();for(const[s,n]of r){const[i,c]=s.split(".");if(!c){const d=f[s];if(!d)throw new b(`Invalid config property: ${s}`);e[s]=d(n);continue}if(e[i]||(e[i]={}),ve.includes(i)){const d=Me[i][c];if(!d)throw new b(`Invalid config property: ${s}`);e[i][c]=d(n);continue}if(!/^[A-Z][A-Z0-9_]*$/.test(i))throw new b(`Invalid service name: ${i}. Service names must be uppercase letters, numbers, and underscores.`);const m=ot(i);if(!m[c])throw new b(`Invalid config property for custom service: ${s}`);try{e[i][c]=m[c](n)}catch(d){throw d instanceof b?d:new b(`Invalid value for ${s}: ${d.message}`)}}const t=await be(),o=x.dirname(t);await R.mkdir(o,{recursive:!0}),await R.writeFile(t,we.stringify(e),"utf8")},ua=async r=>{const e=await Re();for(const[s,n]of r){const[i,c]=s.split("."),a=e[i];if(c==="model"){a||(e[i]={});const d=e[i][c]||[],l=typeof n=="string"?n.split(",").map(p=>p.trim()).filter(p=>!!p):n;e[i][c]=tt([...d,...l]);continue}if(a&&a.compatible===!0){a||(e[i]={});const d=ot(i);if(!d[c])throw new b(`Invalid config property: ${s}`);try{e[i][c]=d[c](n)}catch(l){throw l instanceof b?l:new b(`Invalid value for ${s}: ${l.message}`)}continue}if(i in Me){a||(e[i]={});const d=Me[i][c];if(!d)throw new b(`Invalid config property: ${s}`);e[i][c]=d(n)}else{const d=ot(i);if(!d[c])throw new b(`Invalid config property: ${s}`);e[i]||(e[i]={}),e[i][c]=d[c](n)}}const t=await be(),o=x.dirname(t);await R.mkdir(o,{recursive:!0}),await R.writeFile(t,we.stringify(e),"utf8")},da=async()=>{const r=await Re();console.log(we.stringify(r))},ma=async()=>{console.log(await be())},ot=r=>({compatible:ne("compatible"),stream:ne("stream"),url:e=>e?(D(`${r}.url`,/^https?:\/\//.test(e),"Must be a valid URL"),e):"",path:e=>e||"",key:e=>e||"",envKey:e=>e||"",model:e=>e?(typeof e=="string"?e?.split(","):e).map(o=>o.trim()).filter(o=>!!o&&o.length>0):[],systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,timeout:f.timeout,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,topP:f.topP,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode,disableLowerCase:f.disableLowerCase}),Oe=new Map,de=(r,e,t)=>{const o=Pr(0).update(e).digest("hex").substring(0,8),s=`${r}_${o}_${t}`;if(Oe.has(s))return Oe.get(s);const n=new Date,i=ha(n,r,e,t),c=`${ee}/${i}`,a=B.createLogger({level:"info",format:B.format.combine(B.format.timestamp({format:"YYYY-MM-DDTHH:mm:ss.SSSZ"}),B.format.printf(({timestamp:m,level:d,message:l,...p})=>p&&Object.keys(p).length>0?`[${m}] ${d}: ${l} ${JSON.stringify(p,null,2)}`:`[${m}] ${d}: ${l}`)),transports:[new B.transports.File({filename:c})]});return a.info(`=== ${r.toUpperCase()} AI SERVICE LOG ===`),a.info(`Diff Hash: ${o}`),a.info(`Request Type: ${t.toUpperCase()}`),a.info(`Start Time: ${n.toISOString()}`),a.info("=".repeat(50)),a.info(""),Oe.set(s,a),a},fa=r=>{const e={...r},t=["authorization","x-api-key","x-goog-api-key","api-key"];for(const o of t){const s=o.toLowerCase(),n=Object.keys(e).find(i=>i.toLowerCase()===s);n&&e[n]&&typeof e[n]=="string"&&(e[n].startsWith("Bearer ")?e[n]="Bearer [MASKED]":e[n]="[MASKED]")}return e},Y=(r,e,t,o,s,n,i=!0)=>{if(!i)return;const c=de(t,r,e);c.info(`Making request to ${t} API with model: ${o}`),c.info(`Request URL: ${s}`),c.info("Request headers:",fa(n))},te=(r,e,t,o,s=!0)=>{if(!s)return;de(t,r,e).info("Request payload:",o)},V=(r,e,t,o,s,n=!0)=>{if(!n)return;const i=de(t,r,e);i.info("System prompt:",{prompt:o}),i.info("User prompt:",{prompt:s})},q=(r,e,t,o,s=!0)=>{if(!s)return;de(t,r,e).info("Response received:",o)},_=(r,e,t,o,s=!0)=>{if(!s)return;de(t,r,e).error("API request failed:",o)},z=(r,e,t,o,s,n=!0)=>{if(!n)return;const i=de(t,r,e);o?i.info(`Request completed successfully in ${o}ms`):i.info("Request completed successfully"),s&&i.info("Final processed response:",{response:s}),i.info(""),i.info("=".repeat(50)),i.info(`End Time: ${new Date().toISOString()}`),i.info("=== REQUEST COMPLETED ===")},pa=(r,e,t,o,s,n,i,c=!0)=>{if(!c)return;const a=de(t,r,e);i?a.error(`Request failed after ${n}ms:`,{error:i}):(a.info(`Request completed in ${n}ms`),a.info("Response:",{response:s})),z(r,e,t,n,s,c)},ha=(r,e,t,o)=>{const{year:s,month:n,day:i,hours:c,minutes:a,seconds:m}=ga(r),l=Pr(0).update(t).digest("hex").substring(0,8),p=e.toLowerCase().replace(/[^a-z0-9]/g,"").substring(0,20);return o==="review"?`${s}-${n}-${i}_${c}-${a}-${m}_${l}_${p}_review.log`:`${s}-${n}-${i}_${c}-${a}-${m}_${l}_${p}_commit.log`},ga=r=>{const e=r.getFullYear().toString(),t=(r.getMonth()+1).toString().padStart(2,"0"),o=r.getDate().toString().padStart(2,"0"),s=r.getHours().toString().padStart(2,"0"),n=r.getMinutes().toString().padStart(2,"0"),i=r.getSeconds().toString().padStart(2,"0");return{year:e,month:t,day:o,hours:s,minutes:n,seconds:i}},jt=()=>{for(const[r,e]of Oe.entries())try{e.close()}catch(t){console.error(`Failed to close logger ${r}:`,t)}Oe.clear()};process.on("exit",jt),process.on("SIGINT",()=>{jt(),process.exit(0)}),process.on("SIGTERM",()=>{jt(),process.exit(0)});let st;async function ya(r){if(st){console.warn("Logger already initialized. Skipping re-initialization.");return}const e=r?.logLevel||"info",t=r?.logFilePath||go,o=r?.exceptionLogFilePath||yo,s=r?.logging??!0;await mo(x.dirname(t)),await mo(x.dirname(o));const n=[];s?n.push(new B.transports.DailyRotateFile({filename:t,datePattern:"YYYY-MM-DD",zippedArchive:!0,maxSize:"20m",maxFiles:"14d",level:e,format:B.format.combine(B.format.timestamp(),B.format.printf(({level:i,message:c,timestamp:a})=>`[${a}] ${i}: ${c}`))})):n.push(new B.transports.Console({silent:!0})),st=B.createLogger({level:e,format:B.format.json(),transports:n,exceptionHandlers:s?[new B.transports.DailyRotateFile({filename:o,datePattern:"YYYY-MM-DD",zippedArchive:!0,maxSize:"20m",maxFiles:"14d",format:B.format.combine(B.format.timestamp(),B.format.json())})]:[],exitOnError:!1,silent:!s})}const Ce=new Proxy({},{get:(r,e,t)=>{if(!st)throw new Error("Logger not initialized. Call initializeLogger() first.");return Reflect.get(st,e,t)}});class X{constructor(e){this.handleError$=t=>{const o=this.getDetailedErrorMessage(t),s=t.status?`HTTP ${t.status}: ${o}`:o;if(this.params.config.logging){const n=this.params.stagedDiff.diff,i=this.serviceName.replace(/\[|\]/g,"").trim();pa(n,"commit",i,"Error occurred","",void 0,s)}return Ce.error(`${this.errorPrefix} ${s}`),t.stack&&Ce.error(` ${t.stack}`),t.content&&Ce.error(` Problematic content: ${t.content}`),t.originalError&&Ce.error(` Original error: ${t.originalError}`),mt({name:`${this.errorPrefix} ${s}`,value:s,isError:!0,disabled:!0})},this.serviceName="AI",this.errorPrefix="ERROR",this.colors={primary:""},this.params=e,this.logSessionId=e.logSessionId}getDetailedErrorMessage(e){const t=e.message||"";return t.includes("API key")||t.includes("api_key")?"Invalid API key. Check your API key configuration":t.includes("rate_limit")||t.includes("Rate limit")||t.includes("429")||t.includes("Too Many Requests")?"Rate limit exceeded. Wait a moment and try again, or upgrade your plan":t.includes("model")||t.includes("Model")?"Model not found or not accessible. Check if the model name is correct":t.includes("timeout")||t.includes("Timeout")?"Request timed out. Try again or increase the timeout setting":t.includes("network")||t.includes("connection")||t.includes("ECONNREFUSED")?"Network error. Check your internet connection and try again":t.includes("quota")||t.includes("usage")||t.includes("QUOTA_EXCEEDED")?"API quota exceeded. Check your usage limits":t.includes("401")||t.includes("Unauthorized")?"Authentication failed. Your API key may be invalid or expired":t.includes("403")||t.includes("Forbidden")?"Access denied. Your API key may not have permission for this model":t.includes("404")||t.includes("Not Found")?"Model or endpoint not found. Check your model configuration":t.includes("500")||t.includes("Internal Server Error")?"Server error. Try again later":t.includes("overloaded")||t.includes("capacity")||t.includes("SERVICE_UNAVAILABLE")||t.includes("unavailable")?"Service is temporarily unavailable. Try again in a few minutes":this.getServiceSpecificErrorMessage(e)||t||"Unknown error occurred"}getServiceSpecificErrorMessage(e){return null}cleanJsonCodeBlock(e){const t=/```(?:json|JSON)?\s*([\s\S]*?)\s*```/,o=e.match(t);return o?o[1].trim():e}parseMessage(e,t,o){const s=this.cleanJsonCodeBlock(e),n=/(\[\s*\{[\s\S]*?\}\s*\]|\{[\s\S]*?\})/,i=s.match(n);if(!i){const u=new Error("AI response did not contain a valid JSON object or array.");throw u.name="InvalidJsonResponse",u.content=e,u}const c=i[0],a=oa(c);if(!a.ok){const u=new Error("Failed to parse AI response as JSON");throw u.name="JsonParseError",u.content=c,u.originalError=a.error,u}const m=a.data,d=Array.isArray(m)?m:[m];if(!d.length||!d.every(u=>typeof u.subject=="string")){const u=new Error("AI response contained malformed commit message data.");throw u.name="MalformedCommitMessage",u.content=e,u}const p=d.map(u=>this.extractMessageAsType(u,t)).map(u=>({title:`${u.subject}`,value:`${u.subject}${u.body?`
13
+ ${Nt}${C.dim(`aicommit2 v${Ir}`)}`),console.error(`
14
+ ${Nt}Please open a Bug report with the information above:`),console.error(`${Nt}https://github.com/tak-bro/aicommit2/issues/new/choose`)))},uo=r=>O.lstat(r).then(()=>!0,()=>!1),mo=async r=>{try{await O.mkdir(r,{recursive:!0})}catch(e){if(e.code!=="EEXIST")throw e}},Ze=r=>r&&`${r[0].toUpperCase()}${r.slice(1)}`,et=(r,e)=>{const t=Math.ceil(r),o=Math.floor(e);return Math.floor(Math.random()*(o-t+1))+t},Zi=(r,e)=>r.disabled&&!e.disabled?1:!r.disabled&&e.disabled?-1:0,tt=r=>r.reduce((e,t)=>Array.isArray(t)?e.concat(tt(t)):e.concat(t),[]),fo=(r,e=5)=>r.replace(/[\n\r]/g,"").split(" ").slice(0,e).join(" "),ea=r=>{let e=0;for(let t=0;t<r.length;t++){const o=r.charCodeAt(t);e=(e<<5)-e+o,e=e&e}return Math.abs(e)},ta=r=>{const e=r%360,t=65+r%15,o=45+r%10;return`hsl(${e}, ${t}%, ${o}%)`},ra=r=>{const[e,t,o]=r.match(/\d+/g).map((l,d)=>d===0?Number(l):Number(l)/100),s=(1-Math.abs(2*o-1))*t,n=s*(1-Math.abs(e/60%2-1)),i=o-s/2;let c,a,m;e<60?[c,a,m]=[s,n,0]:e<120?[c,a,m]=[n,s,0]:e<180?[c,a,m]=[0,s,n]:e<240?[c,a,m]=[0,n,s]:e<300?[c,a,m]=[n,0,s]:[c,a,m]=[s,0,n];const u=l=>{const d=Math.round((l+i)*255).toString(16);return d.length===1?"0"+d:d};return`#${u(c)}${u(a)}${u(m)}`},oa=r=>{const e=ea(r),t=ta(e);return{primary:ra(t),secondary:"#FFFFFF"}},sa=r=>{try{return{ok:!0,data:JSON.parse(r)}}catch(e){return{ok:!1,error:e}}},rt=r=>{if(!r||typeof r!="string")return"";if(A.isAbsolute(r))return A.resolve(r);if(Ie){const e=A.dirname(Ie),t=A.join(e,r);return A.resolve(t)}else return""},na=["","conventional","gitmoji"],Gt="http://localhost:11434",{hasOwnProperty:ia}=Object.prototype,_t=(r,e)=>ia.call(r,e),ve=["OPENAI","OLLAMA","HUGGINGFACE","GEMINI","ANTHROPIC","MISTRAL","CODESTRAL","COHERE","GROQ","PERPLEXITY","DEEPSEEK","GITHUB_MODELS"],po=r=>{const e=xe.platform(),t=xe.homedir();let o,s;switch(r){case"config":o=process.env.XDG_CONFIG_HOME;break;case"data":o=process.env.XDG_DATA_HOME;break;case"cache":o=process.env.XDG_CACHE_HOME;break;case"state":o=process.env.XDG_STATE_HOME;break;default:o=void 0}if(e==="darwin")r==="cache"?s=A.join(t,"Library","Caches"):s=A.join(t,"Library","Application Support");else if(e==="win32")s=process.env.LOCALAPPDATA||t;else switch(r){case"config":s=A.join(t,".config");break;case"data":s=A.join(t,".local","share");break;case"cache":s=A.join(t,".cache");break;case"state":s=A.join(t,".local","state");break;default:s=t}return o||s},aa=A.join(po("config"),"aicommit2"),ee=A.join(po("state"),"aicommit2","logs"),ho=A.join(aa,"config.ini"),go=A.join(ee,"aicommit2-%DATE%.log"),yo=A.join(ee,"exceptions-%DATE%.log"),ca=r=>{const e=Object.keys(r),t=new Set([...ve,...e.filter(o=>/^[A-Z][A-Z0-9_]*$/.test(o))]);return Array.from(t)},T=(r,e,t)=>{if(!e)throw new v(`Invalid config property ${r}: ${t}`)},ne=(r,e=!1)=>t=>typeof t=="boolean"?t:t==null?e:(T(r,/^(?:true|false)$/.test(t),"Must be a boolean(true or false)"),t==="true"),f={systemPrompt(r){return r||""},systemPromptPath(r){return r||""},codeReviewPromptPath(r){return r||""},timeout(r){if(!r)return 1e4;T("timeout",/^\d+$/.test(r),"Must be an integer");const e=Number(r);return T("timeout",e>=500,"Must be greater than 500ms"),e},temperature(r){if(!r)return .7;T("temperature",/^(2|\d)(\.\d{1,2})?$/.test(r),"Must be decimal between 0 and 2");const e=Number(r);return T("temperature",e>0,"Must be greater than 0"),T("temperature",e<=2,"Must be less than or equal to 2"),e},maxTokens(r){return r?(T("maxTokens",/^\d+$/.test(r),"Must be an integer"),Number(r)):1024},logLevel(r){return r?(T("logLevel",/^(?:error|warn|info|http|verbose|debug|silly)$/.test(r),"Must be a valid log level (error, warn, info, http, verbose, debug, silly)"),r):"info"},logFilePath(r){return r||go},exceptionLogFilePath(r){return r||yo},locale(r){return r?(T("locale",r,"Cannot be empty"),T("locale",/^[a-z-]+$/i.test(r),"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"),r):"en"},generate(r){if(!r)return 1;T("generate",/^\d+$/.test(r),"Must be an integer");const e=Number(r);return T("generate",e>0,"Must be greater than 0"),T("generate",e<=5,"Must be less or equal to 5"),e},type(r){return r?(T("type",na.includes(r),"Invalid commit type"),r):"conventional"},maxLength(r){if(!r)return 50;T("maxLength",/^\d+$/.test(r),"Must be an integer");const e=Number(r);return T("maxLength",e>=20,"Must be greater than 20 characters"),e},exclude:r=>r?(typeof r=="string"?r?.split(","):r).map(t=>t.trim()).filter(t=>!!t&&t.length>0):[],topP:r=>{if(!r)return .9;T("topP",/^(1|\d)(\.\d{1,2})?$/.test(r),"Must be decimal between 0 and 1");const e=Number(r);return T("topP",e>0,"Must be greater than 0"),T("topP",e<=1,"Must be less than or equal to 1"),e},logging:ne("logging",!0),includeBody:ne("includeBody"),codeReview:ne("codeReview"),disabled:ne("disabled"),watchMode:ne("watchMode"),forceGit:ne("forceGit"),disableLowerCase:ne("disableLowerCase")},Me={OPENAI:{key:r=>r||"",envKey:r=>r||"",model:r=>r?(typeof r=="string"?r?.split(","):r).map(t=>t.trim()).filter(t=>!!t&&t.length>0):["gpt-4o-mini"],url:r=>r?(T("OPENAI.url",/^https?:\/\//.test(r),"Must be a valid URL"),r):"https://api.openai.com",path:r=>r||"/v1/chat/completions",proxy:r=>r||"",topP:f.topP,systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,timeout:f.timeout,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode,disableLowerCase:f.disableLowerCase},HUGGINGFACE:{cookie:r=>r||"",model:r=>r?(typeof r=="string"?r?.split(","):r).map(t=>t.trim()).filter(t=>!!t&&t.length>0):["CohereForAI/c4ai-command-r-plus"],systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,timeout:f.timeout,temperature:f.temperature,maxTokens:f.maxTokens,topP:f.topP,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode,disableLowerCase:f.disableLowerCase},GEMINI:{key:r=>r||"",envKey:r=>r||"",model:r=>r?(typeof r=="string"?r?.split(","):r).map(t=>t.trim()).filter(t=>!!t&&t.length>0):["gemini-2.0-flash"],systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,topP:f.topP,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode,disableLowerCase:f.disableLowerCase},ANTHROPIC:{key:r=>r||"",envKey:r=>r||"",model:r=>r?(typeof r=="string"?r?.split(","):r).map(t=>t.trim()).filter(t=>!!t&&t.length>0):["claude-3-5-haiku-20241022"],systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,topP:f.topP,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode,disableLowerCase:f.disableLowerCase},MISTRAL:{key:r=>r||"",envKey:r=>r||"",model:r=>r?(typeof r=="string"?r?.split(","):r).map(t=>t.trim()).filter(t=>!!t&&t.length>0):["mistral-small-latest"],systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,timeout:f.timeout,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,topP:f.topP,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode,disableLowerCase:f.disableLowerCase},CODESTRAL:{key:r=>r||"",envKey:r=>r||"",model:r=>r?(typeof r=="string"?r?.split(","):r).map(t=>t.trim()).filter(t=>!!t&&t.length>0):["codestral-latest"],topP:f.topP,systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,timeout:f.timeout,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode,disableLowerCase:f.disableLowerCase},OLLAMA:{model:r=>r?(typeof r=="string"?r?.split(","):r).map(t=>t.trim()).filter(t=>!!t&&t.length>0):[],host:r=>r?(T("OLLAMA.host",/^https?:\/\//.test(r),"Must be a valid URL"),r):Gt,timeout:r=>{if(!r)return 1e5;T("OLLAMA.timeout",/^\d+$/.test(r),"Must be an integer");const e=Number(r);return T("OLLAMA.timeout",e>=500,"Must be greater than 500ms"),e},auth:r=>r||"",key:r=>r||"",envKey:r=>r||"",numCtx:r=>{if(!r)return 2048;T("OLLAMA.numCtx",/^\d+$/.test(r),"Must be an integer");const e=Number(r);return T("OLLAMA.numCtx",e>=2048,"Must be greater than 2048"),e},systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,topP:f.topP,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode,disableLowerCase:f.disableLowerCase},COHERE:{key:r=>r||"",envKey:r=>r||"",model:r=>r?(typeof r=="string"?r?.split(","):r).map(t=>t.trim()).filter(t=>!!t&&t.length>0):["command-r"],systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,topP:f.topP,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode,disableLowerCase:f.disableLowerCase},GROQ:{key:r=>r||"",envKey:r=>r||"",model:r=>r?(typeof r=="string"?r?.split(","):r).map(t=>t.trim()).filter(t=>!!t&&t.length>0):["llama-3.3-70b-versatile"],systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,timeout:f.timeout,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,topP:f.topP,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode,disableLowerCase:f.disableLowerCase},PERPLEXITY:{key:r=>r||"",envKey:r=>r||"",model:r=>r?(typeof r=="string"?r?.split(","):r).map(t=>t.trim()).filter(t=>!!t&&t.length>0):["sonar"],topP:f.topP,systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,timeout:f.timeout,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode,disableLowerCase:f.disableLowerCase},DEEPSEEK:{key:r=>r||"",envKey:r=>r||"",model:r=>r?(typeof r=="string"?r?.split(","):r).map(t=>t.trim()).filter(t=>!!t&&t.length>0):["deepseek-coder"],topP:f.topP,systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,timeout:f.timeout,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode,disableLowerCase:f.disableLowerCase},GITHUB_MODELS:{key:r=>r||"",envKey:r=>r||"",model:r=>r?(typeof r=="string"?r?.split(","):r).map(t=>t.trim()).filter(t=>!!t&&t.length>0):["gpt-4o-mini"],systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,timeout:f.timeout,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,topP:f.topP,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode,disableLowerCase:f.disableLowerCase}};let Ie;const la=(r=[])=>{const e={};for(const t of r)if(t.startsWith("--")){const[o,s]=t.slice(2).split("="),[n,i]=o.split(".");n&&i&&n in Me?(e[n]||(e[n]={}),e[n][i]=s):e[o]=s}return e},ua=()=>{const r=xe.homedir(),e=process.env.AICOMMIT_CONFIG_PATH,t=ho,o=A.join(r,".aicommit2");return[e,t,o].filter(s=>!!s)},be=async()=>{const r=ua();for(const e of r)if(await uo(e))return e;return ho},Re=async()=>{const r=await be();Ie=r;try{const e=await O.readFile(r,"utf8");return we.parse(e)}catch(e){return e.code==="ENOENT"?(Ie=void 0,{}):(console.error(`Error reading config file ${r}:`,e),Ie=void 0,{})}},ue=async(r,e=[])=>{const t=await Re(),o=la(e),s={...r,...o},n={},i=ca(t),c={};for(const m of i){const l=t[m]?.envKey||`${m}_API_KEY`,d=process.env[l];d&&(c[m]={key:d})}const a=(m,u)=>{const l=s[`${m}.${u}`]??s[m]?.[u],d=c[m]?.[u],p=t[m]?.[u],g=s[u]??t[u];return l!==void 0?l:d!==void 0?d:p!==void 0?p:g};for(const[m,u]of Object.entries(f)){const l=s[m]??t[m];n[m]=u(l)}for(const m of i){n[m]={};const u=Me[m]||ot(m);for(const[l,d]of Object.entries(u)){const p=a(m,l);n[m][l]=d(p)}}return n},jt=async r=>{const e=await Re();for(const[s,n]of r){const[i,c]=s.split(".");if(!c){const u=f[s];if(!u)throw new v(`Invalid config property: ${s}`);e[s]=u(n);continue}if(e[i]||(e[i]={}),ve.includes(i)){const u=Me[i][c];if(!u)throw new v(`Invalid config property: ${s}`);e[i][c]=u(n);continue}if(!/^[A-Z][A-Z0-9_]*$/.test(i))throw new v(`Invalid service name: ${i}. Service names must be uppercase letters, numbers, and underscores.`);const m=ot(i);if(!m[c])throw new v(`Invalid config property for custom service: ${s}`);try{e[i][c]=m[c](n)}catch(u){throw u instanceof v?u:new v(`Invalid value for ${s}: ${u.message}`)}}const t=await be(),o=A.dirname(t);await O.mkdir(o,{recursive:!0}),await O.writeFile(t,we.stringify(e),"utf8")},da=async r=>{const e=await Re();for(const[s,n]of r){const[i,c]=s.split("."),a=e[i];if(c==="model"){a||(e[i]={});const u=e[i][c]||[],l=typeof n=="string"?n.split(",").map(d=>d.trim()).filter(d=>!!d):n;e[i][c]=tt([...u,...l]);continue}if(a&&a.compatible===!0){a||(e[i]={});const u=ot(i);if(!u[c])throw new v(`Invalid config property: ${s}`);try{e[i][c]=u[c](n)}catch(l){throw l instanceof v?l:new v(`Invalid value for ${s}: ${l.message}`)}continue}if(i in Me){a||(e[i]={});const u=Me[i][c];if(!u)throw new v(`Invalid config property: ${s}`);e[i][c]=u(n)}else{const u=ot(i);if(!u[c])throw new v(`Invalid config property: ${s}`);e[i]||(e[i]={}),e[i][c]=u[c](n)}}const t=await be(),o=A.dirname(t);await O.mkdir(o,{recursive:!0}),await O.writeFile(t,we.stringify(e),"utf8")},ma=async()=>{const r=await Re();console.log(we.stringify(r))},fa=async()=>{console.log(await be())},ot=r=>({compatible:ne("compatible"),stream:ne("stream"),url:e=>e?(T(`${r}.url`,/^https?:\/\//.test(e),"Must be a valid URL"),e):"",path:e=>e||"",key:e=>e||"",envKey:e=>e||"",model:e=>e?(typeof e=="string"?e?.split(","):e).map(o=>o.trim()).filter(o=>!!o&&o.length>0):[],systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,timeout:f.timeout,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,topP:f.topP,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode,disableLowerCase:f.disableLowerCase}),Oe=new Map,de=(r,e,t)=>{const o=Pr(0).update(e).digest("hex").substring(0,8),s=`${r}_${o}_${t}`;if(Oe.has(s))return Oe.get(s);const n=new Date,i=ga(n,r,e,t),c=`${ee}/${i}`,a=H.createLogger({level:"info",format:H.format.combine(H.format.timestamp({format:"YYYY-MM-DDTHH:mm:ss.SSSZ"}),H.format.printf(({timestamp:m,level:u,message:l,...d})=>d&&Object.keys(d).length>0?`[${m}] ${u}: ${l} ${JSON.stringify(d,null,2)}`:`[${m}] ${u}: ${l}`)),transports:[new H.transports.File({filename:c})]});return a.info(`=== ${r.toUpperCase()} AI SERVICE LOG ===`),a.info(`Diff Hash: ${o}`),a.info(`Request Type: ${t.toUpperCase()}`),a.info(`Start Time: ${n.toISOString()}`),a.info("=".repeat(50)),a.info(""),Oe.set(s,a),a},pa=r=>{const e={...r},t=["authorization","x-api-key","x-goog-api-key","api-key"];for(const o of t){const s=o.toLowerCase(),n=Object.keys(e).find(i=>i.toLowerCase()===s);n&&e[n]&&typeof e[n]=="string"&&(e[n].startsWith("Bearer ")?e[n]="Bearer [MASKED]":e[n]="[MASKED]")}return e},Y=(r,e,t,o,s,n,i=!0)=>{if(!i)return;const c=de(t,r,e);c.info(`Making request to ${t} API with model: ${o}`),c.info(`Request URL: ${s}`),c.info("Request headers:",pa(n))},te=(r,e,t,o,s=!0)=>{if(!s)return;de(t,r,e).info("Request payload:",o)},V=(r,e,t,o,s,n=!0)=>{if(!n)return;const i=de(t,r,e);i.info("System prompt:",{prompt:o}),i.info("User prompt:",{prompt:s})},q=(r,e,t,o,s=!0)=>{if(!s)return;de(t,r,e).info("Response received:",o)},_=(r,e,t,o,s=!0)=>{if(!s)return;de(t,r,e).error("API request failed:",o)},z=(r,e,t,o,s,n=!0)=>{if(!n)return;const i=de(t,r,e);o?i.info(`Request completed successfully in ${o}ms`):i.info("Request completed successfully"),s&&i.info("Final processed response:",{response:s}),i.info(""),i.info("=".repeat(50)),i.info(`End Time: ${new Date().toISOString()}`),i.info("=== REQUEST COMPLETED ===")},ha=(r,e,t,o,s,n,i,c=!0)=>{if(!c)return;const a=de(t,r,e);i?a.error(`Request failed after ${n}ms:`,{error:i}):(a.info(`Request completed in ${n}ms`),a.info("Response:",{response:s})),z(r,e,t,n,s,c)},ga=(r,e,t,o)=>{const{year:s,month:n,day:i,hours:c,minutes:a,seconds:m}=ya(r),l=Pr(0).update(t).digest("hex").substring(0,8),d=e.toLowerCase().replace(/[^a-z0-9]/g,"").substring(0,20);return o==="review"?`${s}-${n}-${i}_${c}-${a}-${m}_${l}_${d}_review.log`:`${s}-${n}-${i}_${c}-${a}-${m}_${l}_${d}_commit.log`},ya=r=>{const e=r.getFullYear().toString(),t=(r.getMonth()+1).toString().padStart(2,"0"),o=r.getDate().toString().padStart(2,"0"),s=r.getHours().toString().padStart(2,"0"),n=r.getMinutes().toString().padStart(2,"0"),i=r.getSeconds().toString().padStart(2,"0");return{year:e,month:t,day:o,hours:s,minutes:n,seconds:i}},Ht=()=>{for(const[r,e]of Oe.entries())try{e.close()}catch(t){console.error(`Failed to close logger ${r}:`,t)}Oe.clear()};process.on("exit",Ht),process.on("SIGINT",()=>{Ht(),process.exit(0)}),process.on("SIGTERM",()=>{Ht(),process.exit(0)});let st,wo="info";async function wa(r){if(st){console.warn("Logger already initialized. Skipping re-initialization.");return}const e=r?.logLevel||"info";wo=e;const t=r?.logFilePath||go,o=r?.exceptionLogFilePath||yo,s=r?.logging??!0;await mo(A.dirname(t)),await mo(A.dirname(o));const n=[];s?n.push(new H.transports.DailyRotateFile({filename:t,datePattern:"YYYY-MM-DD",zippedArchive:!0,maxSize:"20m",maxFiles:"14d",level:e,format:H.format.combine(H.format.timestamp(),H.format.printf(({level:i,message:c,timestamp:a})=>`[${a}] ${i}: ${c}`))})):n.push(new H.transports.Console({silent:!0})),st=H.createLogger({level:e,format:H.format.json(),transports:n,exceptionHandlers:s?[new H.transports.DailyRotateFile({filename:o,datePattern:"YYYY-MM-DD",zippedArchive:!0,maxSize:"20m",maxFiles:"14d",format:H.format.combine(H.format.timestamp(),H.format.json())})]:[],exitOnError:!1,silent:!s})}const Ce=new Proxy({},{get:(r,e,t)=>{if(!st)throw new Error("Logger not initialized. Call initializeLogger() first.");return Reflect.get(st,e,t)}});function va(){const r=H.config.npm.levels;return(r[wo]??r.info)>=r.verbose}class X{constructor(e){this.handleError$=t=>{const o=this.getDetailedErrorMessage(t),s=t.status?`HTTP ${t.status}: ${o}`:o;if(this.params.config.logging){const n=this.params.stagedDiff.diff,i=this.serviceName.replace(/\[|\]/g,"").trim();ha(n,"commit",i,"Error occurred","",void 0,s)}return Ce.error(`${this.errorPrefix} ${s}`),t.stack&&Ce.error(` ${t.stack}`),t.content&&Ce.error(` Problematic content: ${t.content}`),t.originalError&&Ce.error(` Original error: ${t.originalError}`),ft({name:`${this.errorPrefix} ${s}`,value:s,isError:!0,disabled:!0})},this.serviceName="AI",this.errorPrefix="ERROR",this.colors={primary:""},this.params=e,this.logSessionId=e.logSessionId}getDetailedErrorMessage(e){const t=e.message||"";return t.includes("API key")||t.includes("api_key")?"Invalid API key. Check your API key configuration":t.includes("rate_limit")||t.includes("Rate limit")||t.includes("429")||t.includes("Too Many Requests")?"Rate limit exceeded. Wait a moment and try again, or upgrade your plan":t.includes("model")||t.includes("Model")?"Model not found or not accessible. Check if the model name is correct":t.includes("timeout")||t.includes("Timeout")?"Request timed out. Try again or increase the timeout setting":t.includes("network")||t.includes("connection")||t.includes("ECONNREFUSED")?"Network error. Check your internet connection and try again":t.includes("quota")||t.includes("usage")||t.includes("QUOTA_EXCEEDED")?"API quota exceeded. Check your usage limits":t.includes("401")||t.includes("Unauthorized")?"Authentication failed. Your API key may be invalid or expired":t.includes("403")||t.includes("Forbidden")?"Access denied. Your API key may not have permission for this model":t.includes("404")||t.includes("Not Found")?"Model or endpoint not found. Check your model configuration":t.includes("500")||t.includes("Internal Server Error")?"Server error. Try again later":t.includes("overloaded")||t.includes("capacity")||t.includes("SERVICE_UNAVAILABLE")||t.includes("unavailable")?"Service is temporarily unavailable. Try again in a few minutes":this.getServiceSpecificErrorMessage(e)||t||"Unknown error occurred"}getServiceSpecificErrorMessage(e){return null}cleanJsonCodeBlock(e){const t=/```(?:json|JSON)?\s*([\s\S]*?)\s*```/,o=e.match(t);return o?o[1].trim():e}parseMessage(e,t,o){const s=this.cleanJsonCodeBlock(e),n=/(\[\s*\{[\s\S]*?\}\s*\]|\{[\s\S]*?\})/,i=s.match(n);if(!i){const p=new Error("AI response did not contain a valid JSON object or array.");throw p.name="InvalidJsonResponse",p.content=e,p}const c=i[0],a=sa(c);if(!a.ok){const p=new Error("Failed to parse AI response as JSON");throw p.name="JsonParseError",p.content=c,p.originalError=a.error,p}const m=a.data,u=Array.isArray(m)?m:[m];if(!u.length||!u.every(p=>typeof p.subject=="string")){const p=new Error("AI response contained malformed commit message data.");throw p.name="MalformedCommitMessage",p.content=e,p}const d=u.map(p=>this.extractMessageAsType(p,t)).map(p=>({title:`${p.subject}`,value:`${p.subject}${p.body?`
15
15
 
16
- ${u.body}`:""}${u.footer?`
16
+ ${p.body}`:""}${p.footer?`
17
17
 
18
- ${u.footer}`:""}`})).slice(0,o);if(this.isLoggingEnabled()){const u=p.map(h=>h.title).join(", ");Ce.info(`${this.serviceName} Parsed ${p.length} commit messages: ${u}`)}return p}extractMessageAsType(e,t){switch(t){case"conventional":const o=/(\w+)(?:\(.*?\))?:\s*(.*)/,s=e.subject.match(o),n=s?s[0]:e.subject;return{...e,subject:this.normalizeCommitMessage(n)};case"gitmoji":const i=/:\w*:\s*(.*)/,c=e.subject.match(i),a=this.params.config.disableLowerCase??!1;return{...e,subject:c&&!a?c[0].toLowerCase():e.subject};default:return e}}normalizeCommitMessage(e){const t=/^(\w+)(\(.*?\))?:\s(.*)$/,o=e.match(t);if(o){const[,s,n,i]=o,c=this.params.config.disableLowerCase??!1,a=s.toLowerCase(),m=c?i:i.charAt(0).toLowerCase()+i.slice(1);e=`${a}${n||""}: ${m}`}return e}sanitizeResponse(e){if(typeof e=="string")try{return[{title:`${fo(e)}...`,value:e}]}catch{return[]}return e.map(t=>{try{return{title:`${fo(t)}...`,value:t}}catch{return{title:"",value:""}}})}isLoggingEnabled(){return this.params.config.logging&&!!this.logSessionId}}const W={locale:"en",maxLength:50,type:"conventional",generate:1,systemPrompt:"",systemPromptPath:"",codeReviewPromptPath:""},wa={"":"<commit message>",conventional:`<type>(<optional scope>): <description>
18
+ ${p.footer}`:""}`})).slice(0,o);if(this.isLoggingEnabled()){const p=d.map(g=>g.title).join(", ");Ce.info(`${this.serviceName} Parsed ${d.length} commit messages: ${p}`)}return d}extractMessageAsType(e,t){switch(t){case"conventional":const o=/(\w+)(?:\(.*?\))?:\s*(.*)/,s=e.subject.match(o),n=s?s[0]:e.subject;return{...e,subject:this.normalizeCommitMessage(n)};case"gitmoji":const i=/:\w*:\s*(.*)/,c=e.subject.match(i),a=this.params.config.disableLowerCase??!1;return{...e,subject:c&&!a?c[0].toLowerCase():e.subject};default:return e}}normalizeCommitMessage(e){const t=/^(\w+)(\(.*?\))?:\s(.*)$/,o=e.match(t);if(o){const[,s,n,i]=o,c=this.params.config.disableLowerCase??!1,a=s.toLowerCase(),m=c?i:i.charAt(0).toLowerCase()+i.slice(1);e=`${a}${n||""}: ${m}`}return e}sanitizeResponse(e){if(typeof e=="string")try{return[{title:`${fo(e)}...`,value:e}]}catch{return[]}return e.map(t=>{try{return{title:`${fo(t)}...`,value:t}}catch{return{title:"",value:""}}})}isLoggingEnabled(){return this.params.config.logging&&!!this.logSessionId}}const W={locale:"en",maxLength:50,type:"conventional",generate:1,systemPrompt:"",systemPromptPath:"",codeReviewPromptPath:""},ba={"":"<commit message>",conventional:`<type>(<optional scope>): <description>
19
19
 
20
20
  [optional body]
21
21
 
@@ -23,11 +23,11 @@ ${u.footer}`:""}`})).slice(0,o);if(this.isLoggingEnabled()){const u=p.map(h=>h.t
23
23
 
24
24
  [optional body]
25
25
 
26
- [optional footer(s)]`},va={"":"",gitmoji:`
26
+ [optional footer(s)]`},Ca={"":"",gitmoji:`
27
27
  ${Object.entries({":sparkles:":"Introduce new features.",":bug:":"Fix a bug.",":memo:":"Add or update documentation.",":art:":"Improve structure / format of the code.",":zap:":"Improve performance.",":fire:":"Remove code or files.",":ambulance:":"Critical hotfix.",":white_check_mark:":"Add, update, or pass tests.",":lock:":"Fix security or privacy issues.",":rocket:":"Deploy stuff.",":lipstick:":"Add or update the UI and style files.",":tada:":"Begin a project.",":recycle:":"Refactor code.",":wrench:":"Add or update configuration files.",":bulb:":"Add or update comments in source code.",":twisted_rightwards_arrows:":"Merge branches."}).map(([r,e])=>` - ${r}: ${e}`).join(`
28
28
  `)}`,conventional:`
29
29
  ${Object.entries({docs:"Documentation only changes",style:"Changes that do not affect the meaning of the code (white-space, formatting, missing semi-colons, etc)",refactor:"A code change that neither fixes a bug nor adds a feature",perf:"A code change that improves performance",test:"Adding missing tests or correcting existing tests",build:"Changes that affect the build system or external dependencies",ci:"Changes to CI configuration files, scripts",chore:"Other changes that don't modify src or test files",revert:"Reverts a previous commit",feat:"A new feature",fix:"A bug fix"}).map(([r,e])=>` - ${r}: ${e}`).join(`
30
- `)}`},wo=(r,e)=>r.replace(/{(\w+)}/g,(t,o)=>e[o]?.toString()||W[o]?.toString()),vo=r=>{const{type:e,maxLength:t,generate:o,locale:s}=r,n="You are an expert Git commit message writer specializing in analyzing code changes and creating precise, meaningful commit messages.",i=`Your task is to generate exactly ${o} ${e} style commit message${o!==1?"s":""} based on the provided git diff.`;return[n,i,"",["## Requirements:",`1. Language: Write all messages in ${s}`,`2. Format: Strictly follow the ${e} commit format:`,`${wa[e]}`,`3. Allowed Types:${va[e]}`,"","## Guidelines:",`- Subject line: Max ${t} characters, imperative mood, no period`,"- Analyze the diff to understand:"," * What files were changed"," * What functionality was added, modified, or removed"," * The scope and impact of changes","- For the commit type, choose based on:"," * feat: New functionality or feature"," * fix: Bug fixes or error corrections"," * refactor: Code restructuring without changing functionality"," * docs: Documentation changes only"," * style: Formatting, missing semi-colons, etc"," * test: Adding or modifying tests"," * chore: Maintenance tasks, dependency updates"," * perf: Performance improvements"," * build: Build system or external dependency changes"," * ci: CI configuration changes","- Scope: Extract from file paths or logical grouping (e.g., auth, api, ui)","- Body (when needed):"," * Explain the motivation for the change"," * Compare previous behavior with new behavior"," * Note any breaking changes or important details","- Footer: Include references to issues, breaking changes if applicable","","## Analysis Approach:","1. Identify the primary purpose of the changes","2. Group related changes together","3. Determine the most appropriate type and scope","4. Write a clear, concise subject line","5. Add body details for complex changes","","Remember: The commit message should help future developers understand WHY this change was made, not just WHAT was changed."].join(`
30
+ `)}`},vo=(r,e)=>r.replace(/{(\w+)}/g,(t,o)=>e[o]?.toString()||W[o]?.toString()),bo=r=>{const{type:e,maxLength:t,generate:o,locale:s}=r,n="You are an expert Git commit message writer specializing in analyzing code changes and creating precise, meaningful commit messages.",i=`Your task is to generate exactly ${o} ${e} style commit message${o!==1?"s":""} based on the provided git diff.`;return[n,i,"",["## Requirements:",`1. Language: Write all messages in ${s}`,`2. Format: Strictly follow the ${e} commit format:`,`${ba[e]}`,`3. Allowed Types:${Ca[e]}`,"","## Guidelines:",`- Subject line: Max ${t} characters, imperative mood, no period`,"- Analyze the diff to understand:"," * What files were changed"," * What functionality was added, modified, or removed"," * The scope and impact of changes","- For the commit type, choose based on:"," * feat: New functionality or feature"," * fix: Bug fixes or error corrections"," * refactor: Code restructuring without changing functionality"," * docs: Documentation changes only"," * style: Formatting, missing semi-colons, etc"," * test: Adding or modifying tests"," * chore: Maintenance tasks, dependency updates"," * perf: Performance improvements"," * build: Build system or external dependency changes"," * ci: CI configuration changes","- Scope: Extract from file paths or logical grouping (e.g., auth, api, ui)","- Body (when needed):"," * Explain the motivation for the change"," * Compare previous behavior with new behavior"," * Note any breaking changes or important details","- Footer: Include references to issues, breaking changes if applicable","","## Analysis Approach:","1. Identify the primary purpose of the changes","2. Group related changes together","3. Determine the most appropriate type and scope","4. Write a clear, concise subject line","5. Add body details for complex changes","","Remember: The commit message should help future developers understand WHY this change was made, not just WHAT was changed."].join(`
31
31
  `)].filter(Boolean).join(`
32
32
  `)},nt=(r,e)=>{const t=o=>o==="conventional"?`${Array(e).fill(null).map((s,n)=>`
33
33
  {
@@ -44,9 +44,9 @@ Lastly, Provide your response as a JSON array containing exactly ${e} object${e!
44
44
  [${t(r)}
45
45
  ]`,`Ensure you generate exactly ${e} commit message${e!==1?"s":""}, even if it requires creating slightly varied versions for similar changes.`,"The response should be valid JSON that can be parsed without errors."].filter(Boolean).join(`
46
46
  `)},Q=r=>{const{systemPrompt:e,systemPromptPath:t,type:o,generate:s}=r;if(e)return`${e}
47
- ${nt(o,s)}`;if(!t)return`${vo(r)}
48
- ${nt(o,s)}`;try{const n=U.readFileSync(rt(t),"utf-8");return`${wo(n,r)}
49
- ${nt(o,s)}`}catch{return`${vo(r)}
47
+ ${nt(o,s)}`;if(!t)return`${bo(r)}
48
+ ${nt(o,s)}`;try{const n=U.readFileSync(rt(t),"utf-8");return`${vo(n,r)}
49
+ ${nt(o,s)}`}catch{return`${bo(r)}
50
50
  ${nt(o,s)}`}},Z=r=>{const{codeReviewPromptPath:e,locale:t}=r,o=`I'll give you the output of the "git diff" command as an input. Please review the following code and provide your feedback in Markdown format. Focus on:
51
51
 
52
52
  1. Language: ${t}
@@ -55,7 +55,7 @@ ${nt(o,s)}`}},Z=r=>{const{codeReviewPromptPath:e,locale:t}=r,o=`I'll give you th
55
55
  4. Performance improvements
56
56
  5. Readability and maintainability
57
57
 
58
- Please structure your response with appropriate Markdown headings, code blocks, and bullet points.`;if(!e)return o;try{const s=U.readFileSync(rt(e),"utf-8");return`${wo(s,r)}`}catch{return o}},bo=async r=>{if(r.systemPromptPath)try{U.readFileSync(rt(r.systemPromptPath),"utf-8")}catch(e){throw new b(`Error reading system prompt file: ${r.systemPromptPath}, ${e}`)}if(r.codeReview&&r.codeReviewPromptPath)try{U.readFileSync(rt(r.codeReviewPromptPath),"utf-8")}catch(e){throw new b(`Error reading code review prompt file: ${r.codeReviewPromptPath}, ${e}`)}},Pe=(r,e="commit")=>e==="review"?`Please analyze the following diff and provide a comprehensive code review:
58
+ Please structure your response with appropriate Markdown headings, code blocks, and bullet points.`;if(!e)return o;try{const s=U.readFileSync(rt(e),"utf-8");return`${vo(s,r)}`}catch{return o}},Co=async r=>{if(r.systemPromptPath)try{U.readFileSync(rt(r.systemPromptPath),"utf-8")}catch(e){throw new v(`Error reading system prompt file: ${r.systemPromptPath}, ${e}`)}if(r.codeReview&&r.codeReviewPromptPath)try{U.readFileSync(rt(r.codeReviewPromptPath),"utf-8")}catch(e){throw new v(`Error reading code review prompt file: ${r.codeReviewPromptPath}, ${e}`)}},Pe=(r,e="commit")=>e==="review"?`Please analyze the following diff and provide a comprehensive code review:
59
59
 
60
60
  \`\`\`diff
61
61
  ${r}
@@ -67,93 +67,93 @@ Focus on code quality, potential issues, and improvement suggestions.`:`Please a
67
67
  ${r}
68
68
  \`\`\`
69
69
 
70
- Focus on understanding the purpose and impact of these changes to create meaningful commit message(s).`,ba=10*60*1e3;class Ca extends X{constructor(e){super(e),this.params=e,this.colors={primary:"#AE5630",secondary:"#fff"},this.serviceName=P.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[Anthropic]"),this.errorPrefix=P.red.bold("[Anthropic]"),this.anthropic=new ds({apiKey:this.params.config.key,...this.params.config.timeout>ba&&{timeout:this.params.config.timeout}})}getServiceSpecificErrorMessage(e){const t=e.message||"";return t.includes("API key")||t.includes("api_key")?"Invalid API key. Check your Anthropic API key in configuration":t.includes("quota")||t.includes("usage")?"API quota exceeded. Check your Anthropic usage limits":t.includes("model")||t.includes("Model")?"Model not found or not accessible. Check if the Claude model name is correct":t.includes("403")||t.includes("Forbidden")?"Access denied. Your API key may not have permission for this Claude model":t.includes("404")||t.includes("Not Found")?"Model or endpoint not found. Check your Claude model configuration":t.includes("500")||t.includes("Internal Server Error")?"Anthropic server error. Try again later":null}generateCommitMessage$(){return L(this.generateMessage("commit")).pipe(O(e=>A(e)),M(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})),I(this.handleError$))}generateCodeReview$(){return L(this.generateMessage("review")).pipe(O(e=>A(e)),M(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),I(this.handleError$))}async generateMessage(e){const t=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n,logging:i,temperature:c,locale:a,generate:m,type:d,maxLength:l,maxTokens:p,topP:u,model:h}=this.params.config,g={...W,locale:a,maxLength:l,type:d,generate:m,systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n},y=e==="review"?Z(g):Q(g),w=Pe(t,e),E=`${this.params.config.url||"https://api.anthropic.com"}/v1/messages`,k={"Content-Type":"application/json","x-api-key":this.params.config.key,"anthropic-version":"2023-06-01"};Y(t,e,"Anthropic",h,E,k,i),V(t,e,"Anthropic",y,w,i);const $={max_tokens:p,temperature:c,system:y,messages:[{role:"user",content:w}],top_p:u,model:h};te(t,e,"Anthropic",$,i);const C=Date.now();try{const S=await this.anthropic.messages.create($),T=Date.now()-C;q(t,e,"Anthropic",S,i);const G=S.content.map(({text:ae})=>ae).join("");return z(t,e,"Anthropic",T,G,i),e==="review"?this.sanitizeResponse(G):this.parseMessage(G,d,m)}catch(S){throw _(t,e,"Anthropic",S,i),S}}}class Le{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=ms.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 Pa extends X{constructor(e){super(e),this.params=e,this.apiKey="",this.colors={primary:"#e28c58",secondary:"#fff"},this.serviceName=P.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[Codestral]"),this.errorPrefix=P.red.bold("[Codestral]"),this.apiKey=this.params.config.key}getServiceSpecificErrorMessage(e){const t=e.message||"";return t.includes("API key")||t.includes("api_key")?"Invalid API key. Check your Codestral API key in configuration":t.includes("rate_limit")||t.includes("Rate limit")?"Rate limit exceeded. Wait a moment and try again, or upgrade your Codestral plan":t.includes("model")||t.includes("Model")?"Model not found or not accessible. Check if the Codestral model name is correct":t.includes("Invalid model type")?"Invalid model type. Use supported models: codestral-latest, codestral-2501":t.includes("overloaded")||t.includes("capacity")?"Codestral service is overloaded. Try again in a few minutes":t.includes("403")||t.includes("Forbidden")?"Access denied. Your API key may not have permission for this Codestral model":t.includes("404")||t.includes("Not Found")?"Model or endpoint not found. Check your Codestral model configuration":t.includes("500")||t.includes("Internal Server Error")?"Codestral server error. Try again later":null}generateCommitMessage$(){return L(this.generateMessage("commit")).pipe(O(e=>A(e)),M(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})),I(this.handleError$))}generateCodeReview$(){return L(this.generateMessage("review")).pipe(O(e=>A(e)),M(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),I(this.handleError$))}async generateMessage(e){const t=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n,logging:i,locale:c,generate:a,type:m,maxLength:d}=this.params.config,l={...W,locale:c,maxLength:d,type:m,generate:a,systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n},p=e==="review"?Z(l):Q(l);this.checkAvailableModels();const u=Pe(t,e),g=`${this.params.config.url||"https://codestral.mistral.ai"}/v1/chat/completions`,y={Authorization:`Bearer ${this.apiKey}`,"content-type":"application/json"};Y(t,e,"Codestral",this.params.config.model,g,y,i),V(t,e,"Codestral",p,u,i);const w=await this.createChatCompletions(p,e);return e==="review"?this.sanitizeResponse(w):this.parseMessage(w,m,a)}checkAvailableModels(){if(["codestral-latest","codestral-2501"].includes(this.params.config.model))return!0;throw new Error("Invalid model type of Codestral AI")}async createChatCompletions(e,t){const o=this.params.stagedDiff.diff,{logging:s}=this.params.config,n=this.params.config.url||"https://codestral.mistral.ai",i={model:this.params.config.model,messages:[{role:"system",content:e},{role:"user",content:Pe(this.params.stagedDiff.diff,t)}],temperature:this.params.config.temperature,top_p:this.params.config.topP,max_tokens:this.params.config.maxTokens,stream:!1,safe_prompt:!1,random_seed:et(10,1e3)};t==="commit"&&(i.response_format={type:"json_object"}),te(o,t,"Codestral",i,s);const c=Date.now();try{const m=await new Le({method:"POST",baseURL:`${n}/v1/chat/completions`,timeout:this.params.config.timeout}).setHeaders({Authorization:`Bearer ${this.apiKey}`,"content-type":"application/json"}).setBody(i).execute(),d=Date.now()-c,l=m.data;if(q(o,t,"Codestral",l,s),!l.choices||l.choices.length===0||!l.choices[0].message?.content)throw _(o,t,"Codestral",{message:"No Content on response",result:l},s),new Error("No Content on response. Please open a Bug report");const u=l.choices[0].message.content;return z(o,t,"Codestral",d,u,s),u}catch(a){throw _(o,t,"Codestral",a,s),a}}}class $a extends X{constructor(e){super(e),this.params=e,this.colors={primary:"#D18EE2",secondary:"#fff"},this.serviceName=P.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[Cohere]"),this.errorPrefix=P.red.bold("[Cohere]"),this.cohere=new fs({token:this.params.config.key})}getServiceSpecificErrorMessage(e){const t=e.message||"";return t.includes("API key")||t.includes("api_key")?"Invalid API key. Check your Cohere API key in configuration":t.includes("rate_limit")||t.includes("Rate limit")?"Rate limit exceeded. Wait a moment and try again, or upgrade your Cohere plan":t.includes("model")||t.includes("Model")?"Model not found or not accessible. Check if the Cohere model name is correct":t.includes("overloaded")||t.includes("capacity")?"Cohere service is overloaded. Try again in a few minutes":t.includes("403")||t.includes("Forbidden")?"Access denied. Your API key may not have permission for this Cohere model":t.includes("404")||t.includes("Not Found")?"Model or endpoint not found. Check your Cohere model configuration":t.includes("500")||t.includes("Internal Server Error")?"Cohere server error. Try again later":null}generateCommitMessage$(){return L(this.generateMessage("commit")).pipe(O(e=>A(e)),M(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})),I(this.handleError$))}generateCodeReview$(){return L(this.generateMessage("review")).pipe(O(e=>A(e)),M(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),I(this.handleError$))}async generateMessage(e){const t=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n,logging:i,temperature:c,locale:a,generate:m,type:d,maxLength:l,maxTokens:p}=this.params.config,u={...W,locale:a,maxLength:l,type:d,generate:m,systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n},h=e==="review"?Z(u):Q(u),g=`Here is the diff: ${t}`,w=`${this.params.config.url||"https://api.cohere.ai"}/v1/chat`,v={Authorization:`Bearer ${this.params.config.key}`,"Content-Type":"application/json"};Y(t,e,"Cohere",this.params.config.model,w,v,i),V(t,e,"Cohere",h,g,i);const E={chatHistory:h?[{role:"SYSTEM",message:h}]:[],message:g,connectors:[{id:"web-search"}],maxTokens:p,temperature:c,model:this.params.config.model,seed:et(10,1e3),p:this.params.config.topP};te(t,e,"Cohere",E,i);const k=Date.now();try{const $=await this.cohere.chat(E,{timeoutInSeconds:Math.floor(this.params.config.timeout/1e3)}),C=Date.now()-k,S=$.text;return q(t,e,"Cohere",$,i),z(t,e,"Cohere",C,S,i),e==="review"?this.sanitizeResponse(S):this.parseMessage(S,d,m)}catch($){throw _(t,e,"Cohere",$,i),$}}}class Ea extends X{constructor(e){super(e),this.params=e,this.colors={primary:"#53a3f9",secondary:"#fff"},this.serviceName=P.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[DeepSeek]"),this.errorPrefix=P.red.bold("[DeepSeek]");const t=this.params.config.url||"https://api.deepseek.com";this.deepSeek=new $r({baseURL:t,apiKey:this.params.config.key})}getServiceSpecificErrorMessage(e){const t=e.message||"";return t.includes("API key")||t.includes("api_key")?"Invalid API key. Check your DeepSeek API key in configuration":t.includes("rate_limit")||t.includes("Rate limit")?"Rate limit exceeded. Wait a moment and try again, or upgrade your DeepSeek plan":t.includes("model")||t.includes("Model")?"Model not found or not accessible. Check if the DeepSeek model name is correct":t.includes("Invalid model type")?"Invalid model type. Use supported models: deepseek-reasoner, deepseek-chat":t.includes("overloaded")||t.includes("capacity")?"DeepSeek service is overloaded. Try again in a few minutes":t.includes("403")||t.includes("Forbidden")?"Access denied. Your API key may not have permission for this DeepSeek model":t.includes("404")||t.includes("Not Found")?"Model or endpoint not found. Check your DeepSeek model configuration":t.includes("500")||t.includes("Internal Server Error")?"DeepSeek server error. Try again later":null}generateCommitMessage$(){return L(this.generateMessage("commit")).pipe(O(e=>A(e)),M(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})),I(this.handleError$))}generateCodeReview$(){return L(this.generateMessage("review")).pipe(O(e=>A(e)),M(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),I(this.handleError$))}async generateMessage(e){const t=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n,logging:i,locale:c,generate:a,type:m,maxLength:d}=this.params.config,l={...W,locale:c,maxLength:d,type:m,generate:a,systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n},p=e==="review"?Z(l):Q(l);this.checkAvailableModels();const u=Pe(t,e),g=`${this.params.config.url||"https://api.deepseek.com"}/chat/completions`,y={Authorization:`Bearer ${this.params.config.key}`,"Content-Type":"application/json"};Y(t,e,"DeepSeek",this.params.config.model,g,y,i),V(t,e,"DeepSeek",p,u,i);const w=await this.createChatCompletions(p,u,e);return e==="review"?this.sanitizeResponse(w):this.parseMessage(w,m,a)}checkAvailableModels(){if(["deepseek-reasoner","deepseek-chat"].includes(this.params.config.model))return!0;throw new Error("Invalid model type of DeepSeek")}async createChatCompletions(e,t,o){const s=this.params.stagedDiff.diff,{logging:n}=this.params.config,i={messages:[{role:"system",content:e},{role:"user",content:t}],model:this.params.config.model,max_tokens:this.params.config.maxTokens,top_p:this.params.config.topP,temperature:this.params.config.temperature};te(s,o,"DeepSeek",i,n);const c=Date.now();try{const a=await this.deepSeek.chat.completions.create(i,{timeout:this.params.config.timeout}),m=Date.now()-c,d=a.choices[0].message.content||"";return q(s,o,"DeepSeek",a,n),z(s,o,"DeepSeek",m,d,n),d}catch(a){throw _(s,o,"DeepSeek",a,n),a}}}class xa extends X{constructor(e){super(e),this.params=e,this.colors={primary:"#0077FF",secondary:"#fff"},this.serviceName=P.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[Gemini]"),this.errorPrefix=P.red.bold("[Gemini]"),this.genAI=new ps(this.params.config.key)}getServiceSpecificErrorMessage(e){const t=e.message||"";return t.includes("API key")||t.includes("api_key")?"Invalid API key. Check your Google AI Studio API key in configuration":t.includes("quota")||t.includes("QUOTA_EXCEEDED")?"API quota exceeded. Check your Google AI Studio usage limits":t.includes("model")||t.includes("Model")?"Model not found or not accessible. Check if the Gemini model name is correct":t.includes("SAFETY")||t.includes("safety")?"Content blocked by safety filters. Try rephrasing your request":t.includes("RECITATION")||t.includes("recitation")?"Content blocked due to recitation concerns. Try a different approach":t.includes("403")||t.includes("Forbidden")?"Access denied. Your API key may not have permission for this Gemini model":t.includes("404")||t.includes("Not Found")?"Model or endpoint not found. Check your Gemini model configuration":t.includes("500")||t.includes("Internal Server Error")?"Google AI service error. Try again later":null}generateCommitMessage$(){return L(this.generateMessage("commit")).pipe(O(e=>A(e)),M(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})),I(this.handleError$))}generateCodeReview$(){return L(this.generateMessage("review")).pipe(O(e=>A(e)),M(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),I(this.handleError$))}async generateMessage(e){const t=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:s,logging:n,locale:i,codeReviewPromptPath:c,generate:a,type:m,maxLength:d}=this.params.config,l=this.params.config.maxTokens,p={...W,locale:i,maxLength:d,type:m,generate:a,systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:c},u=e==="review"?Z(p):Q(p),h={maxOutputTokens:l,temperature:this.params.config.temperature,topP:this.params.config.topP},g=this.genAI.getGenerativeModel({model:this.params.config.model,systemInstruction:u,generationConfig:h,safetySettings:[{category:Be.HARM_CATEGORY_HATE_SPEECH,threshold:Ue.BLOCK_LOW_AND_ABOVE},{category:Be.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:Ue.BLOCK_LOW_AND_ABOVE},{category:Be.HARM_CATEGORY_HARASSMENT,threshold:Ue.BLOCK_LOW_AND_ABOVE},{category:Be.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:Ue.BLOCK_LOW_AND_ABOVE}]}),y=Pe(t,e),v=`${this.params.config.url||"https://generativelanguage.googleapis.com"}/v1beta/models/${this.params.config.model}:generateContent`,E={"Content-Type":"application/json","x-goog-api-key":this.params.config.key};Y(t,e,"Gemini",this.params.config.model,v,E,n),V(t,e,"Gemini",u,y,n),te(t,e,"Gemini",{systemInstruction:{parts:[{text:u}]},contents:[{parts:[{text:y}]}],generationConfig:h},n);const $=Date.now();try{const C=this.params.config.timeout>1e4?{request:{timeout:this.params.config.timeout}}:void 0,S=await g.generateContent(y,C),G=S.response.text(),ae=Date.now()-$;return q(t,e,"Gemini",{response:G,candidates:S.response.candidates,usageMetadata:S.response.usageMetadata},n),z(t,e,"Gemini",ae,G,n),e==="review"?this.sanitizeResponse(G):this.parseMessage(G,m,a)}catch(C){throw _(t,e,"Gemini",C,n),C}}}var Ht={},Bt={exports:{}},De={exports:{}},Ut,Co;function ka(){if(Co)return Ut;Co=1;var r=1e3,e=r*60,t=e*60,o=t*24,s=o*7,n=o*365.25;Ut=function(d,l){l=l||{};var p=typeof d;if(p==="string"&&d.length>0)return i(d);if(p==="number"&&isFinite(d))return l.long?a(d):c(d);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(d))};function i(d){if(d=String(d),!(d.length>100)){var l=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(d);if(l){var p=parseFloat(l[1]),u=(l[2]||"ms").toLowerCase();switch(u){case"years":case"year":case"yrs":case"yr":case"y":return p*n;case"weeks":case"week":case"w":return p*s;case"days":case"day":case"d":return p*o;case"hours":case"hour":case"hrs":case"hr":case"h":return p*t;case"minutes":case"minute":case"mins":case"min":case"m":return p*e;case"seconds":case"second":case"secs":case"sec":case"s":return p*r;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return p;default:return}}}}function c(d){var l=Math.abs(d);return l>=o?Math.round(d/o)+"d":l>=t?Math.round(d/t)+"h":l>=e?Math.round(d/e)+"m":l>=r?Math.round(d/r)+"s":d+"ms"}function a(d){var l=Math.abs(d);return l>=o?m(d,l,o,"day"):l>=t?m(d,l,t,"hour"):l>=e?m(d,l,e,"minute"):l>=r?m(d,l,r,"second"):d+" ms"}function m(d,l,p,u){var h=l>=p*1.5;return Math.round(d/p)+" "+u+(h?"s":"")}return Ut}var zt,Po;function $o(){if(Po)return zt;Po=1;function r(e){o.debug=o,o.default=o,o.coerce=m,o.disable=c,o.enable=n,o.enabled=a,o.humanize=ka(),o.destroy=d,Object.keys(e).forEach(l=>{o[l]=e[l]}),o.names=[],o.skips=[],o.formatters={};function t(l){let p=0;for(let u=0;u<l.length;u++)p=(p<<5)-p+l.charCodeAt(u),p|=0;return o.colors[Math.abs(p)%o.colors.length]}o.selectColor=t;function o(l){let p,u=null,h,g;function y(...w){if(!y.enabled)return;const v=y,E=Number(new Date),k=E-(p||E);v.diff=k,v.prev=p,v.curr=E,p=E,w[0]=o.coerce(w[0]),typeof w[0]!="string"&&w.unshift("%O");let $=0;w[0]=w[0].replace(/%([a-zA-Z%])/g,(S,T)=>{if(S==="%%")return"%";$++;const G=o.formatters[T];if(typeof G=="function"){const ae=w[$];S=G.call(v,ae),w.splice($,1),$--}return S}),o.formatArgs.call(v,w),(v.log||o.log).apply(v,w)}return y.namespace=l,y.useColors=o.useColors(),y.color=o.selectColor(l),y.extend=s,y.destroy=o.destroy,Object.defineProperty(y,"enabled",{enumerable:!0,configurable:!1,get:()=>u!==null?u:(h!==o.namespaces&&(h=o.namespaces,g=o.enabled(l)),g),set:w=>{u=w}}),typeof o.init=="function"&&o.init(y),y}function s(l,p){const u=o(this.namespace+(typeof p>"u"?":":p)+l);return u.log=this.log,u}function n(l){o.save(l),o.namespaces=l,o.names=[],o.skips=[];const p=(typeof l=="string"?l:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(const u of p)u[0]==="-"?o.skips.push(u.slice(1)):o.names.push(u)}function i(l,p){let u=0,h=0,g=-1,y=0;for(;u<l.length;)if(h<p.length&&(p[h]===l[u]||p[h]==="*"))p[h]==="*"?(g=h,y=u,h++):(u++,h++);else if(g!==-1)h=g+1,y++,u=y;else return!1;for(;h<p.length&&p[h]==="*";)h++;return h===p.length}function c(){const l=[...o.names,...o.skips.map(p=>"-"+p)].join(",");return o.enable(""),l}function a(l){for(const p of o.skips)if(i(l,p))return!1;for(const p of o.names)if(i(l,p))return!0;return!1}function m(l){return l instanceof Error?l.stack||l.message:l}function d(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return o.enable(o.load()),o}return zt=r,zt}De.exports;var Eo;function Sa(){return Eo||(Eo=1,function(r,e){e.formatArgs=o,e.save=s,e.load=n,e.useColors=t,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 t(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let a;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&(a=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(a[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function o(a){if(a[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+a[0]+(this.useColors?"%c ":" ")+"+"+r.exports.humanize(this.diff),!this.useColors)return;const m="color: "+this.color;a.splice(1,0,m,"color: inherit");let d=0,l=0;a[0].replace(/%[a-zA-Z%]/g,p=>{p!=="%%"&&(d++,p==="%c"&&(l=d))}),a.splice(l,0,m)}e.log=console.debug||console.log||(()=>{});function s(a){try{a?e.storage.setItem("debug",a):e.storage.removeItem("debug")}catch{}}function n(){let a;try{a=e.storage.getItem("debug")||e.storage.getItem("DEBUG")}catch{}return!a&&typeof process<"u"&&"env"in process&&(a=process.env.DEBUG),a}function i(){try{return localStorage}catch{}}r.exports=$o()(e);const{formatters:c}=r.exports;c.j=function(a){try{return JSON.stringify(a)}catch(m){return"[UnexpectedJSONParseError]: "+m.message}}}(De,De.exports)),De.exports}var Te={exports:{}},Wt,xo;function Aa(){return xo||(xo=1,Wt=(r,e=process.argv)=>{const t=r.startsWith("-")?"":r.length===1?"-":"--",o=e.indexOf(t+r),s=e.indexOf("--");return o!==-1&&(s===-1||o<s)}),Wt}var Kt,ko;function Ma(){if(ko)return Kt;ko=1;const r=xe,e=Er,t=Aa(),{env:o}=process;let s;t("no-color")||t("no-colors")||t("color=false")||t("color=never")?s=0:(t("color")||t("colors")||t("color=true")||t("color=always"))&&(s=1),"FORCE_COLOR"in o&&(o.FORCE_COLOR==="true"?s=1:o.FORCE_COLOR==="false"?s=0:s=o.FORCE_COLOR.length===0?1:Math.min(parseInt(o.FORCE_COLOR,10),3));function n(a){return a===0?!1:{level:a,hasBasic:!0,has256:a>=2,has16m:a>=3}}function i(a,m){if(s===0)return 0;if(t("color=16m")||t("color=full")||t("color=truecolor"))return 3;if(t("color=256"))return 2;if(a&&!m&&s===void 0)return 0;const d=s||0;if(o.TERM==="dumb")return d;if(process.platform==="win32"){const l=r.release().split(".");return Number(l[0])>=10&&Number(l[2])>=10586?Number(l[2])>=14931?3:2:1}if("CI"in o)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE"].some(l=>l in o)||o.CI_NAME==="codeship"?1:d;if("TEAMCITY_VERSION"in o)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(o.TEAMCITY_VERSION)?1:0;if(o.COLORTERM==="truecolor")return 3;if("TERM_PROGRAM"in o){const l=parseInt((o.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(o.TERM_PROGRAM){case"iTerm.app":return l>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(o.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(o.TERM)||"COLORTERM"in o?1:d}function c(a){const m=i(a,a&&a.isTTY);return n(m)}return Kt={supportsColor:c,stdout:n(i(!0,e.isatty(1))),stderr:n(i(!0,e.isatty(2)))},Kt}Te.exports;var So;function Ia(){return So||(So=1,function(r,e){const t=Er,o=gr;e.init=d,e.log=c,e.formatArgs=n,e.save=a,e.load=m,e.useColors=s,e.destroy=o.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."),e.colors=[6,2,3,4,5,1];try{const p=Ma();p&&(p.stderr||p).level>=2&&(e.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221])}catch{}e.inspectOpts=Object.keys(process.env).filter(p=>/^debug_/i.test(p)).reduce((p,u)=>{const h=u.substring(6).toLowerCase().replace(/_([a-z])/g,(y,w)=>w.toUpperCase());let g=process.env[u];return/^(yes|on|true|enabled)$/i.test(g)?g=!0:/^(no|off|false|disabled)$/i.test(g)?g=!1:g==="null"?g=null:g=Number(g),p[h]=g,p},{});function s(){return"colors"in e.inspectOpts?!!e.inspectOpts.colors:t.isatty(process.stderr.fd)}function n(p){const{namespace:u,useColors:h}=this;if(h){const g=this.color,y="\x1B[3"+(g<8?g:"8;5;"+g),w=` ${y};1m${u} \x1B[0m`;p[0]=w+p[0].split(`
70
+ Focus on understanding the purpose and impact of these changes to create meaningful commit message(s).`,Pa=10*60*1e3;class $a extends X{constructor(e){super(e),this.params=e,this.colors={primary:"#AE5630",secondary:"#fff"},this.serviceName=C.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[Anthropic]"),this.errorPrefix=C.red.bold("[Anthropic]"),this.anthropic=new ms({apiKey:this.params.config.key,...this.params.config.timeout>Pa&&{timeout:this.params.config.timeout}})}getServiceSpecificErrorMessage(e){const t=e.message||"";return t.includes("API key")||t.includes("api_key")?"Invalid API key. Check your Anthropic API key in configuration":t.includes("quota")||t.includes("usage")?"API quota exceeded. Check your Anthropic usage limits":t.includes("model")||t.includes("Model")?"Model not found or not accessible. Check if the Claude model name is correct":t.includes("403")||t.includes("Forbidden")?"Access denied. Your API key may not have permission for this Claude model":t.includes("404")||t.includes("Not Found")?"Model or endpoint not found. Check your Claude model configuration":t.includes("500")||t.includes("Internal Server Error")?"Anthropic server error. Try again later":null}generateCommitMessage$(){return D(this.generateMessage("commit")).pipe(L(e=>M(e)),I(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:this.params.config.includeBody?e.value:e.title,description:this.params.config.includeBody?e.value:"",isError:!1})),R(this.handleError$))}generateCodeReview$(){return D(this.generateMessage("review")).pipe(L(e=>M(e)),I(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),R(this.handleError$))}async generateMessage(e){const t=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n,logging:i,temperature:c,locale:a,generate:m,type:u,maxLength:l,maxTokens:d,topP:p,model:g}=this.params.config,h={...W,locale:a,maxLength:l,type:u,generate:m,systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n},y=e==="review"?Z(h):Q(h),w=Pe(t,e),P=`${this.params.config.url||"https://api.anthropic.com"}/v1/messages`,S={"Content-Type":"application/json","x-api-key":this.params.config.key,"anthropic-version":"2023-06-01"};Y(t,e,"Anthropic",g,P,S,i),V(t,e,"Anthropic",y,w,i);const k={max_tokens:d,temperature:c,system:y,messages:[{role:"user",content:w}],top_p:p,model:g};te(t,e,"Anthropic",k,i);const $=Date.now();try{const x=await this.anthropic.messages.create(k),E=Date.now()-$;q(t,e,"Anthropic",x,i);const G=x.content.map(({text:ae})=>ae).join("");return z(t,e,"Anthropic",E,G,i),e==="review"?this.sanitizeResponse(G):this.parseMessage(G,u,m)}catch(x){throw _(t,e,"Anthropic",x,i),x}}}class Le{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=fs.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 Ea extends X{constructor(e){super(e),this.params=e,this.apiKey="",this.colors={primary:"#e28c58",secondary:"#fff"},this.serviceName=C.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[Codestral]"),this.errorPrefix=C.red.bold("[Codestral]"),this.apiKey=this.params.config.key}getServiceSpecificErrorMessage(e){const t=e.message||"";return t.includes("API key")||t.includes("api_key")?"Invalid API key. Check your Codestral API key in configuration":t.includes("rate_limit")||t.includes("Rate limit")?"Rate limit exceeded. Wait a moment and try again, or upgrade your Codestral plan":t.includes("model")||t.includes("Model")?"Model not found or not accessible. Check if the Codestral model name is correct":t.includes("Invalid model type")?"Invalid model type. Use supported models: codestral-latest, codestral-2501":t.includes("overloaded")||t.includes("capacity")?"Codestral service is overloaded. Try again in a few minutes":t.includes("403")||t.includes("Forbidden")?"Access denied. Your API key may not have permission for this Codestral model":t.includes("404")||t.includes("Not Found")?"Model or endpoint not found. Check your Codestral model configuration":t.includes("500")||t.includes("Internal Server Error")?"Codestral server error. Try again later":null}generateCommitMessage$(){return D(this.generateMessage("commit")).pipe(L(e=>M(e)),I(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:this.params.config.includeBody?e.value:e.title,description:this.params.config.includeBody?e.value:"",isError:!1})),R(this.handleError$))}generateCodeReview$(){return D(this.generateMessage("review")).pipe(L(e=>M(e)),I(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),R(this.handleError$))}async generateMessage(e){const t=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n,logging:i,locale:c,generate:a,type:m,maxLength:u}=this.params.config,l={...W,locale:c,maxLength:u,type:m,generate:a,systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n},d=e==="review"?Z(l):Q(l);this.checkAvailableModels();const p=Pe(t,e),h=`${this.params.config.url||"https://codestral.mistral.ai"}/v1/chat/completions`,y={Authorization:`Bearer ${this.apiKey}`,"content-type":"application/json"};Y(t,e,"Codestral",this.params.config.model,h,y,i),V(t,e,"Codestral",d,p,i);const w=await this.createChatCompletions(d,e);return e==="review"?this.sanitizeResponse(w):this.parseMessage(w,m,a)}checkAvailableModels(){if(["codestral-latest","codestral-2501"].includes(this.params.config.model))return!0;throw new Error("Invalid model type of Codestral AI")}async createChatCompletions(e,t){const o=this.params.stagedDiff.diff,{logging:s}=this.params.config,n=this.params.config.url||"https://codestral.mistral.ai",i={model:this.params.config.model,messages:[{role:"system",content:e},{role:"user",content:Pe(this.params.stagedDiff.diff,t)}],temperature:this.params.config.temperature,top_p:this.params.config.topP,max_tokens:this.params.config.maxTokens,stream:!1,safe_prompt:!1,random_seed:et(10,1e3)};t==="commit"&&(i.response_format={type:"json_object"}),te(o,t,"Codestral",i,s);const c=Date.now();try{const m=await new Le({method:"POST",baseURL:`${n}/v1/chat/completions`,timeout:this.params.config.timeout}).setHeaders({Authorization:`Bearer ${this.apiKey}`,"content-type":"application/json"}).setBody(i).execute(),u=Date.now()-c,l=m.data;if(q(o,t,"Codestral",l,s),!l.choices||l.choices.length===0||!l.choices[0].message?.content)throw _(o,t,"Codestral",{message:"No Content on response",result:l},s),new Error("No Content on response. Please open a Bug report");const p=l.choices[0].message.content;return z(o,t,"Codestral",u,p,s),p}catch(a){throw _(o,t,"Codestral",a,s),a}}}class xa extends X{constructor(e){super(e),this.params=e,this.colors={primary:"#D18EE2",secondary:"#fff"},this.serviceName=C.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[Cohere]"),this.errorPrefix=C.red.bold("[Cohere]"),this.cohere=new ps({token:this.params.config.key})}getServiceSpecificErrorMessage(e){const t=e.message||"";return t.includes("API key")||t.includes("api_key")?"Invalid API key. Check your Cohere API key in configuration":t.includes("rate_limit")||t.includes("Rate limit")?"Rate limit exceeded. Wait a moment and try again, or upgrade your Cohere plan":t.includes("model")||t.includes("Model")?"Model not found or not accessible. Check if the Cohere model name is correct":t.includes("overloaded")||t.includes("capacity")?"Cohere service is overloaded. Try again in a few minutes":t.includes("403")||t.includes("Forbidden")?"Access denied. Your API key may not have permission for this Cohere model":t.includes("404")||t.includes("Not Found")?"Model or endpoint not found. Check your Cohere model configuration":t.includes("500")||t.includes("Internal Server Error")?"Cohere server error. Try again later":null}generateCommitMessage$(){return D(this.generateMessage("commit")).pipe(L(e=>M(e)),I(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:this.params.config.includeBody?e.value:e.title,description:this.params.config.includeBody?e.value:"",isError:!1})),R(this.handleError$))}generateCodeReview$(){return D(this.generateMessage("review")).pipe(L(e=>M(e)),I(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),R(this.handleError$))}async generateMessage(e){const t=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n,logging:i,temperature:c,locale:a,generate:m,type:u,maxLength:l,maxTokens:d}=this.params.config,p={...W,locale:a,maxLength:l,type:u,generate:m,systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n},g=e==="review"?Z(p):Q(p),h=`Here is the diff: ${t}`,w=`${this.params.config.url||"https://api.cohere.ai"}/v1/chat`,b={Authorization:`Bearer ${this.params.config.key}`,"Content-Type":"application/json"};Y(t,e,"Cohere",this.params.config.model,w,b,i),V(t,e,"Cohere",g,h,i);const P={chatHistory:g?[{role:"SYSTEM",message:g}]:[],message:h,connectors:[{id:"web-search"}],maxTokens:d,temperature:c,model:this.params.config.model,seed:et(10,1e3),p:this.params.config.topP};te(t,e,"Cohere",P,i);const S=Date.now();try{const k=await this.cohere.chat(P,{timeoutInSeconds:Math.floor(this.params.config.timeout/1e3)}),$=Date.now()-S,x=k.text;return q(t,e,"Cohere",k,i),z(t,e,"Cohere",$,x,i),e==="review"?this.sanitizeResponse(x):this.parseMessage(x,u,m)}catch(k){throw _(t,e,"Cohere",k,i),k}}}class ka extends X{constructor(e){super(e),this.params=e,this.colors={primary:"#53a3f9",secondary:"#fff"},this.serviceName=C.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[DeepSeek]"),this.errorPrefix=C.red.bold("[DeepSeek]");const t=this.params.config.url||"https://api.deepseek.com";this.deepSeek=new $r({baseURL:t,apiKey:this.params.config.key})}getServiceSpecificErrorMessage(e){const t=e.message||"";return t.includes("API key")||t.includes("api_key")?"Invalid API key. Check your DeepSeek API key in configuration":t.includes("rate_limit")||t.includes("Rate limit")?"Rate limit exceeded. Wait a moment and try again, or upgrade your DeepSeek plan":t.includes("model")||t.includes("Model")?"Model not found or not accessible. Check if the DeepSeek model name is correct":t.includes("Invalid model type")?"Invalid model type. Use supported models: deepseek-reasoner, deepseek-chat":t.includes("overloaded")||t.includes("capacity")?"DeepSeek service is overloaded. Try again in a few minutes":t.includes("403")||t.includes("Forbidden")?"Access denied. Your API key may not have permission for this DeepSeek model":t.includes("404")||t.includes("Not Found")?"Model or endpoint not found. Check your DeepSeek model configuration":t.includes("500")||t.includes("Internal Server Error")?"DeepSeek server error. Try again later":null}generateCommitMessage$(){return D(this.generateMessage("commit")).pipe(L(e=>M(e)),I(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:this.params.config.includeBody?e.value:e.title,description:this.params.config.includeBody?e.value:"",isError:!1})),R(this.handleError$))}generateCodeReview$(){return D(this.generateMessage("review")).pipe(L(e=>M(e)),I(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),R(this.handleError$))}async generateMessage(e){const t=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n,logging:i,locale:c,generate:a,type:m,maxLength:u}=this.params.config,l={...W,locale:c,maxLength:u,type:m,generate:a,systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n},d=e==="review"?Z(l):Q(l);this.checkAvailableModels();const p=Pe(t,e),h=`${this.params.config.url||"https://api.deepseek.com"}/chat/completions`,y={Authorization:`Bearer ${this.params.config.key}`,"Content-Type":"application/json"};Y(t,e,"DeepSeek",this.params.config.model,h,y,i),V(t,e,"DeepSeek",d,p,i);const w=await this.createChatCompletions(d,p,e);return e==="review"?this.sanitizeResponse(w):this.parseMessage(w,m,a)}checkAvailableModels(){if(["deepseek-reasoner","deepseek-chat"].includes(this.params.config.model))return!0;throw new Error("Invalid model type of DeepSeek")}async createChatCompletions(e,t,o){const s=this.params.stagedDiff.diff,{logging:n}=this.params.config,i={messages:[{role:"system",content:e},{role:"user",content:t}],model:this.params.config.model,max_tokens:this.params.config.maxTokens,top_p:this.params.config.topP,temperature:this.params.config.temperature};te(s,o,"DeepSeek",i,n);const c=Date.now();try{const a=await this.deepSeek.chat.completions.create(i,{timeout:this.params.config.timeout}),m=Date.now()-c,u=a.choices[0].message.content||"";return q(s,o,"DeepSeek",a,n),z(s,o,"DeepSeek",m,u,n),u}catch(a){throw _(s,o,"DeepSeek",a,n),a}}}class Sa extends X{constructor(e){super(e),this.params=e,this.colors={primary:"#0077FF",secondary:"#fff"},this.serviceName=C.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[Gemini]"),this.errorPrefix=C.red.bold("[Gemini]"),this.genAI=new hs(this.params.config.key)}getServiceSpecificErrorMessage(e){const t=e.message||"";return t.includes("API key")||t.includes("api_key")?"Invalid API key. Check your Google AI Studio API key in configuration":t.includes("quota")||t.includes("QUOTA_EXCEEDED")?"API quota exceeded. Check your Google AI Studio usage limits":t.includes("model")||t.includes("Model")?"Model not found or not accessible. Check if the Gemini model name is correct":t.includes("SAFETY")||t.includes("safety")?"Content blocked by safety filters. Try rephrasing your request":t.includes("RECITATION")||t.includes("recitation")?"Content blocked due to recitation concerns. Try a different approach":t.includes("403")||t.includes("Forbidden")?"Access denied. Your API key may not have permission for this Gemini model":t.includes("404")||t.includes("Not Found")?"Model or endpoint not found. Check your Gemini model configuration":t.includes("500")||t.includes("Internal Server Error")?"Google AI service error. Try again later":null}generateCommitMessage$(){return D(this.generateMessage("commit")).pipe(L(e=>M(e)),I(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:this.params.config.includeBody?e.value:e.title,description:this.params.config.includeBody?e.value:"",isError:!1})),R(this.handleError$))}generateCodeReview$(){return D(this.generateMessage("review")).pipe(L(e=>M(e)),I(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),R(this.handleError$))}async generateMessage(e){const t=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:s,logging:n,locale:i,codeReviewPromptPath:c,generate:a,type:m,maxLength:u}=this.params.config,l=this.params.config.maxTokens,d={...W,locale:i,maxLength:u,type:m,generate:a,systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:c},p=e==="review"?Z(d):Q(d),g={maxOutputTokens:l,temperature:this.params.config.temperature,topP:this.params.config.topP},h=this.genAI.getGenerativeModel({model:this.params.config.model,systemInstruction:p,generationConfig:g,safetySettings:[{category:Be.HARM_CATEGORY_HATE_SPEECH,threshold:Ue.BLOCK_LOW_AND_ABOVE},{category:Be.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:Ue.BLOCK_LOW_AND_ABOVE},{category:Be.HARM_CATEGORY_HARASSMENT,threshold:Ue.BLOCK_LOW_AND_ABOVE},{category:Be.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:Ue.BLOCK_LOW_AND_ABOVE}]}),y=Pe(t,e),b=`${this.params.config.url||"https://generativelanguage.googleapis.com"}/v1beta/models/${this.params.config.model}:generateContent`,P={"Content-Type":"application/json","x-goog-api-key":this.params.config.key};Y(t,e,"Gemini",this.params.config.model,b,P,n),V(t,e,"Gemini",p,y,n),te(t,e,"Gemini",{systemInstruction:{parts:[{text:p}]},contents:[{parts:[{text:y}]}],generationConfig:g},n);const k=Date.now();try{const $=this.params.config.timeout>1e4?{request:{timeout:this.params.config.timeout}}:void 0,x=await h.generateContent(y,$),G=x.response.text(),ae=Date.now()-k;return q(t,e,"Gemini",{response:G,candidates:x.response.candidates,usageMetadata:x.response.usageMetadata},n),z(t,e,"Gemini",ae,G,n),e==="review"?this.sanitizeResponse(G):this.parseMessage(G,m,a)}catch($){throw _(t,e,"Gemini",$,n),$}}}var Bt={},Ut={exports:{}},De={exports:{}},zt,Po;function Aa(){if(Po)return zt;Po=1;var r=1e3,e=r*60,t=e*60,o=t*24,s=o*7,n=o*365.25;zt=function(u,l){l=l||{};var d=typeof u;if(d==="string"&&u.length>0)return i(u);if(d==="number"&&isFinite(u))return l.long?a(u):c(u);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(u))};function i(u){if(u=String(u),!(u.length>100)){var l=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(u);if(l){var d=parseFloat(l[1]),p=(l[2]||"ms").toLowerCase();switch(p){case"years":case"year":case"yrs":case"yr":case"y":return d*n;case"weeks":case"week":case"w":return d*s;case"days":case"day":case"d":return d*o;case"hours":case"hour":case"hrs":case"hr":case"h":return d*t;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*r;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return d;default:return}}}}function c(u){var l=Math.abs(u);return l>=o?Math.round(u/o)+"d":l>=t?Math.round(u/t)+"h":l>=e?Math.round(u/e)+"m":l>=r?Math.round(u/r)+"s":u+"ms"}function a(u){var l=Math.abs(u);return l>=o?m(u,l,o,"day"):l>=t?m(u,l,t,"hour"):l>=e?m(u,l,e,"minute"):l>=r?m(u,l,r,"second"):u+" ms"}function m(u,l,d,p){var g=l>=d*1.5;return Math.round(u/d)+" "+p+(g?"s":"")}return zt}var Wt,$o;function Eo(){if($o)return Wt;$o=1;function r(e){o.debug=o,o.default=o,o.coerce=m,o.disable=c,o.enable=n,o.enabled=a,o.humanize=Aa(),o.destroy=u,Object.keys(e).forEach(l=>{o[l]=e[l]}),o.names=[],o.skips=[],o.formatters={};function t(l){let d=0;for(let p=0;p<l.length;p++)d=(d<<5)-d+l.charCodeAt(p),d|=0;return o.colors[Math.abs(d)%o.colors.length]}o.selectColor=t;function o(l){let d,p=null,g,h;function y(...w){if(!y.enabled)return;const b=y,P=Number(new Date),S=P-(d||P);b.diff=S,b.prev=d,b.curr=P,d=P,w[0]=o.coerce(w[0]),typeof w[0]!="string"&&w.unshift("%O");let k=0;w[0]=w[0].replace(/%([a-zA-Z%])/g,(x,E)=>{if(x==="%%")return"%";k++;const G=o.formatters[E];if(typeof G=="function"){const ae=w[k];x=G.call(b,ae),w.splice(k,1),k--}return x}),o.formatArgs.call(b,w),(b.log||o.log).apply(b,w)}return y.namespace=l,y.useColors=o.useColors(),y.color=o.selectColor(l),y.extend=s,y.destroy=o.destroy,Object.defineProperty(y,"enabled",{enumerable:!0,configurable:!1,get:()=>p!==null?p:(g!==o.namespaces&&(g=o.namespaces,h=o.enabled(l)),h),set:w=>{p=w}}),typeof o.init=="function"&&o.init(y),y}function s(l,d){const p=o(this.namespace+(typeof d>"u"?":":d)+l);return p.log=this.log,p}function n(l){o.save(l),o.namespaces=l,o.names=[],o.skips=[];const d=(typeof l=="string"?l:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(const p of d)p[0]==="-"?o.skips.push(p.slice(1)):o.names.push(p)}function i(l,d){let p=0,g=0,h=-1,y=0;for(;p<l.length;)if(g<d.length&&(d[g]===l[p]||d[g]==="*"))d[g]==="*"?(h=g,y=p,g++):(p++,g++);else if(h!==-1)g=h+1,y++,p=y;else return!1;for(;g<d.length&&d[g]==="*";)g++;return g===d.length}function c(){const l=[...o.names,...o.skips.map(d=>"-"+d)].join(",");return o.enable(""),l}function a(l){for(const d of o.skips)if(i(l,d))return!1;for(const d of o.names)if(i(l,d))return!0;return!1}function m(l){return l instanceof Error?l.stack||l.message:l}function u(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return o.enable(o.load()),o}return Wt=r,Wt}De.exports;var xo;function Ma(){return xo||(xo=1,function(r,e){e.formatArgs=o,e.save=s,e.load=n,e.useColors=t,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 t(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let a;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&(a=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(a[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function o(a){if(a[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+a[0]+(this.useColors?"%c ":" ")+"+"+r.exports.humanize(this.diff),!this.useColors)return;const m="color: "+this.color;a.splice(1,0,m,"color: inherit");let u=0,l=0;a[0].replace(/%[a-zA-Z%]/g,d=>{d!=="%%"&&(u++,d==="%c"&&(l=u))}),a.splice(l,0,m)}e.log=console.debug||console.log||(()=>{});function s(a){try{a?e.storage.setItem("debug",a):e.storage.removeItem("debug")}catch{}}function n(){let a;try{a=e.storage.getItem("debug")||e.storage.getItem("DEBUG")}catch{}return!a&&typeof process<"u"&&"env"in process&&(a=process.env.DEBUG),a}function i(){try{return localStorage}catch{}}r.exports=Eo()(e);const{formatters:c}=r.exports;c.j=function(a){try{return JSON.stringify(a)}catch(m){return"[UnexpectedJSONParseError]: "+m.message}}}(De,De.exports)),De.exports}var Te={exports:{}},Kt,ko;function Ia(){return ko||(ko=1,Kt=(r,e=process.argv)=>{const t=r.startsWith("-")?"":r.length===1?"-":"--",o=e.indexOf(t+r),s=e.indexOf("--");return o!==-1&&(s===-1||o<s)}),Kt}var Jt,So;function Ra(){if(So)return Jt;So=1;const r=xe,e=Er,t=Ia(),{env:o}=process;let s;t("no-color")||t("no-colors")||t("color=false")||t("color=never")?s=0:(t("color")||t("colors")||t("color=true")||t("color=always"))&&(s=1),"FORCE_COLOR"in o&&(o.FORCE_COLOR==="true"?s=1:o.FORCE_COLOR==="false"?s=0:s=o.FORCE_COLOR.length===0?1:Math.min(parseInt(o.FORCE_COLOR,10),3));function n(a){return a===0?!1:{level:a,hasBasic:!0,has256:a>=2,has16m:a>=3}}function i(a,m){if(s===0)return 0;if(t("color=16m")||t("color=full")||t("color=truecolor"))return 3;if(t("color=256"))return 2;if(a&&!m&&s===void 0)return 0;const u=s||0;if(o.TERM==="dumb")return u;if(process.platform==="win32"){const l=r.release().split(".");return Number(l[0])>=10&&Number(l[2])>=10586?Number(l[2])>=14931?3:2:1}if("CI"in o)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE"].some(l=>l in o)||o.CI_NAME==="codeship"?1:u;if("TEAMCITY_VERSION"in o)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(o.TEAMCITY_VERSION)?1:0;if(o.COLORTERM==="truecolor")return 3;if("TERM_PROGRAM"in o){const l=parseInt((o.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(o.TERM_PROGRAM){case"iTerm.app":return l>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(o.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(o.TERM)||"COLORTERM"in o?1:u}function c(a){const m=i(a,a&&a.isTTY);return n(m)}return Jt={supportsColor:c,stdout:n(i(!0,e.isatty(1))),stderr:n(i(!0,e.isatty(2)))},Jt}Te.exports;var Ao;function Oa(){return Ao||(Ao=1,function(r,e){const t=Er,o=gr;e.init=u,e.log=c,e.formatArgs=n,e.save=a,e.load=m,e.useColors=s,e.destroy=o.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."),e.colors=[6,2,3,4,5,1];try{const d=Ra();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,p)=>{const g=p.substring(6).toLowerCase().replace(/_([a-z])/g,(y,w)=>w.toUpperCase());let h=process.env[p];return/^(yes|on|true|enabled)$/i.test(h)?h=!0:/^(no|off|false|disabled)$/i.test(h)?h=!1:h==="null"?h=null:h=Number(h),d[g]=h,d},{});function s(){return"colors"in e.inspectOpts?!!e.inspectOpts.colors:t.isatty(process.stderr.fd)}function n(d){const{namespace:p,useColors:g}=this;if(g){const h=this.color,y="\x1B[3"+(h<8?h:"8;5;"+h),w=` ${y};1m${p} \x1B[0m`;d[0]=w+d[0].split(`
71
71
  `).join(`
72
- `+w),p.push(y+"m+"+r.exports.humanize(this.diff)+"\x1B[0m")}else p[0]=i()+u+" "+p[0]}function i(){return e.inspectOpts.hideDate?"":new Date().toISOString()+" "}function c(...p){return process.stderr.write(o.formatWithOptions(e.inspectOpts,...p)+`
73
- `)}function a(p){p?process.env.DEBUG=p:delete process.env.DEBUG}function m(){return process.env.DEBUG}function d(p){p.inspectOpts={};const u=Object.keys(e.inspectOpts);for(let h=0;h<u.length;h++)p.inspectOpts[u[h]]=e.inspectOpts[u[h]]}r.exports=$o()(e);const{formatters:l}=r.exports;l.o=function(p){return this.inspectOpts.colors=this.useColors,o.inspect(p,this.inspectOpts).split(`
74
- `).map(u=>u.trim()).join(" ")},l.O=function(p){return this.inspectOpts.colors=this.useColors,o.inspect(p,this.inspectOpts)}}(Te,Te.exports)),Te.exports}typeof process>"u"||process.type==="renderer"||process.browser===!0||process.__nwjs?Bt.exports=Sa():Bt.exports=Ia();var Jt=Bt.exports,Yt={};Object.defineProperty(Yt,"__esModule",{value:!0});function Ra(r){return function(e,t){return new Promise((o,s)=>{r.call(this,e,t,(n,i)=>{n?s(n):o(i)})})}}Yt.default=Ra;var Ao=j&&j.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};const Oa=hr,La=Ao(Jt),Da=Ao(Yt),Fe=La.default("agent-base");function Ta(r){return!!r&&typeof r.addRequest=="function"}function Vt(){const{stack:r}=new Error;return typeof r!="string"?!1:r.split(`
75
- `).some(e=>e.indexOf("(https.js:")!==-1||e.indexOf("node:https:")!==-1)}function it(r,e){return new it.Agent(r,e)}(function(r){class e extends Oa.EventEmitter{constructor(o,s){super();let n=s;typeof o=="function"?this.callback=o:o&&(n=o),this.timeout=null,n&&typeof n.timeout=="number"&&(this.timeout=n.timeout),this.maxFreeSockets=1,this.maxSockets=1,this.maxTotalSockets=1/0,this.sockets={},this.freeSockets={},this.requests={},this.options={}}get defaultPort(){return typeof this.explicitDefaultPort=="number"?this.explicitDefaultPort:Vt()?443:80}set defaultPort(o){this.explicitDefaultPort=o}get protocol(){return typeof this.explicitProtocol=="string"?this.explicitProtocol:Vt()?"https:":"http:"}set protocol(o){this.explicitProtocol=o}callback(o,s,n){throw new Error('"agent-base" has no default implementation, you must subclass and override `callback()`')}addRequest(o,s){const n=Object.assign({},s);typeof n.secureEndpoint!="boolean"&&(n.secureEndpoint=Vt()),n.host==null&&(n.host="localhost"),n.port==null&&(n.port=n.secureEndpoint?443:80),n.protocol==null&&(n.protocol=n.secureEndpoint?"https:":"http:"),n.host&&n.path&&delete n.path,delete n.agent,delete n.hostname,delete n._defaultAgent,delete n.defaultPort,delete n.createConnection,o._last=!0,o.shouldKeepAlive=!1;let i=!1,c=null;const a=n.timeout||this.timeout,m=u=>{o._hadError||(o.emit("error",u),o._hadError=!0)},d=()=>{c=null,i=!0;const u=new Error(`A "socket" was not created for HTTP request before ${a}ms`);u.code="ETIMEOUT",m(u)},l=u=>{i||(c!==null&&(clearTimeout(c),c=null),m(u))},p=u=>{if(i)return;if(c!=null&&(clearTimeout(c),c=null),Ta(u)){Fe("Callback returned another Agent instance %o",u.constructor.name),u.addRequest(o,n);return}if(u){u.once("free",()=>{this.freeSocket(u,n)}),o.onSocket(u);return}const h=new Error(`no Duplex stream was returned to agent-base for \`${o.method} ${o.path}\``);m(h)};if(typeof this.callback!="function"){m(new Error("`callback` is not defined"));return}this.promisifiedCallback||(this.callback.length>=3?(Fe("Converting legacy callback function to promise"),this.promisifiedCallback=Da.default(this.callback)):this.promisifiedCallback=this.callback),typeof a=="number"&&a>0&&(c=setTimeout(d,a)),"port"in n&&typeof n.port!="number"&&(n.port=Number(n.port));try{Fe("Resolving socket for %o request: %o",n.protocol,`${o.method} ${o.path}`),Promise.resolve(this.promisifiedCallback(o,n)).then(p,l)}catch(u){Promise.reject(u).catch(l)}}freeSocket(o,s){Fe("Freeing socket %o %o",o.constructor.name,s),o.destroy()}destroy(){Fe("Destroying agent %o",this.constructor.name)}}r.Agent=e,r.prototype=r.Agent.prototype})(it||(it={}));var Fa=it,qt={},Na=j&&j.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(qt,"__esModule",{value:!0});const Ga=Na(Jt),Ne=Ga.default("https-proxy-agent:parse-proxy-response");function _a(r){return new Promise((e,t)=>{let o=0;const s=[];function n(){const l=r.read();l?d(l):r.once("readable",n)}function i(){r.removeListener("end",a),r.removeListener("error",m),r.removeListener("close",c),r.removeListener("readable",n)}function c(l){Ne("onclose had error %o",l)}function a(){Ne("onend")}function m(l){i(),Ne("onerror %o",l),t(l)}function d(l){s.push(l),o+=l.length;const p=Buffer.concat(s,o);if(p.indexOf(`\r
72
+ `+w),d.push(y+"m+"+r.exports.humanize(this.diff)+"\x1B[0m")}else d[0]=i()+p+" "+d[0]}function i(){return e.inspectOpts.hideDate?"":new Date().toISOString()+" "}function c(...d){return process.stderr.write(o.formatWithOptions(e.inspectOpts,...d)+`
73
+ `)}function a(d){d?process.env.DEBUG=d:delete process.env.DEBUG}function m(){return process.env.DEBUG}function u(d){d.inspectOpts={};const p=Object.keys(e.inspectOpts);for(let g=0;g<p.length;g++)d.inspectOpts[p[g]]=e.inspectOpts[p[g]]}r.exports=Eo()(e);const{formatters:l}=r.exports;l.o=function(d){return this.inspectOpts.colors=this.useColors,o.inspect(d,this.inspectOpts).split(`
74
+ `).map(p=>p.trim()).join(" ")},l.O=function(d){return this.inspectOpts.colors=this.useColors,o.inspect(d,this.inspectOpts)}}(Te,Te.exports)),Te.exports}typeof process>"u"||process.type==="renderer"||process.browser===!0||process.__nwjs?Ut.exports=Ma():Ut.exports=Oa();var Yt=Ut.exports,Vt={};Object.defineProperty(Vt,"__esModule",{value:!0});function La(r){return function(e,t){return new Promise((o,s)=>{r.call(this,e,t,(n,i)=>{n?s(n):o(i)})})}}Vt.default=La;var Mo=j&&j.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};const Da=hr,Ta=Mo(Yt),Fa=Mo(Vt),Fe=Ta.default("agent-base");function Na(r){return!!r&&typeof r.addRequest=="function"}function qt(){const{stack:r}=new Error;return typeof r!="string"?!1:r.split(`
75
+ `).some(e=>e.indexOf("(https.js:")!==-1||e.indexOf("node:https:")!==-1)}function it(r,e){return new it.Agent(r,e)}(function(r){class e extends Da.EventEmitter{constructor(o,s){super();let n=s;typeof o=="function"?this.callback=o:o&&(n=o),this.timeout=null,n&&typeof n.timeout=="number"&&(this.timeout=n.timeout),this.maxFreeSockets=1,this.maxSockets=1,this.maxTotalSockets=1/0,this.sockets={},this.freeSockets={},this.requests={},this.options={}}get defaultPort(){return typeof this.explicitDefaultPort=="number"?this.explicitDefaultPort:qt()?443:80}set defaultPort(o){this.explicitDefaultPort=o}get protocol(){return typeof this.explicitProtocol=="string"?this.explicitProtocol:qt()?"https:":"http:"}set protocol(o){this.explicitProtocol=o}callback(o,s,n){throw new Error('"agent-base" has no default implementation, you must subclass and override `callback()`')}addRequest(o,s){const n=Object.assign({},s);typeof n.secureEndpoint!="boolean"&&(n.secureEndpoint=qt()),n.host==null&&(n.host="localhost"),n.port==null&&(n.port=n.secureEndpoint?443:80),n.protocol==null&&(n.protocol=n.secureEndpoint?"https:":"http:"),n.host&&n.path&&delete n.path,delete n.agent,delete n.hostname,delete n._defaultAgent,delete n.defaultPort,delete n.createConnection,o._last=!0,o.shouldKeepAlive=!1;let i=!1,c=null;const a=n.timeout||this.timeout,m=p=>{o._hadError||(o.emit("error",p),o._hadError=!0)},u=()=>{c=null,i=!0;const p=new Error(`A "socket" was not created for HTTP request before ${a}ms`);p.code="ETIMEOUT",m(p)},l=p=>{i||(c!==null&&(clearTimeout(c),c=null),m(p))},d=p=>{if(i)return;if(c!=null&&(clearTimeout(c),c=null),Na(p)){Fe("Callback returned another Agent instance %o",p.constructor.name),p.addRequest(o,n);return}if(p){p.once("free",()=>{this.freeSocket(p,n)}),o.onSocket(p);return}const g=new Error(`no Duplex stream was returned to agent-base for \`${o.method} ${o.path}\``);m(g)};if(typeof this.callback!="function"){m(new Error("`callback` is not defined"));return}this.promisifiedCallback||(this.callback.length>=3?(Fe("Converting legacy callback function to promise"),this.promisifiedCallback=Fa.default(this.callback)):this.promisifiedCallback=this.callback),typeof a=="number"&&a>0&&(c=setTimeout(u,a)),"port"in n&&typeof n.port!="number"&&(n.port=Number(n.port));try{Fe("Resolving socket for %o request: %o",n.protocol,`${o.method} ${o.path}`),Promise.resolve(this.promisifiedCallback(o,n)).then(d,l)}catch(p){Promise.reject(p).catch(l)}}freeSocket(o,s){Fe("Freeing socket %o %o",o.constructor.name,s),o.destroy()}destroy(){Fe("Destroying agent %o",this.constructor.name)}}r.Agent=e,r.prototype=r.Agent.prototype})(it||(it={}));var Ga=it,Xt={},_a=j&&j.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Xt,"__esModule",{value:!0});const ja=_a(Yt),Ne=ja.default("https-proxy-agent:parse-proxy-response");function Ha(r){return new Promise((e,t)=>{let o=0;const s=[];function n(){const l=r.read();l?u(l):r.once("readable",n)}function i(){r.removeListener("end",a),r.removeListener("error",m),r.removeListener("close",c),r.removeListener("readable",n)}function c(l){Ne("onclose had error %o",l)}function a(){Ne("onend")}function m(l){i(),Ne("onerror %o",l),t(l)}function u(l){s.push(l),o+=l.length;const d=Buffer.concat(s,o);if(d.indexOf(`\r
76
76
  \r
77
- `)===-1){Ne("have not received end of HTTP headers yet..."),n();return}const h=p.toString("ascii",0,p.indexOf(`\r
78
- `)),g=+h.split(" ")[1];Ne("got proxy server response: %o",h),e({statusCode:g,buffered:p})}r.on("error",m),r.on("close",c),r.on("end",a),n()})}qt.default=_a;var ja=j&&j.__awaiter||function(r,e,t,o){function s(n){return n instanceof t?n:new t(function(i){i(n)})}return new(t||(t=Promise))(function(n,i){function c(d){try{m(o.next(d))}catch(l){i(l)}}function a(d){try{m(o.throw(d))}catch(l){i(l)}}function m(d){d.done?n(d.value):s(d.value).then(c,a)}m((o=o.apply(r,e||[])).next())})},$e=j&&j.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Ht,"__esModule",{value:!0});const Mo=$e(ys),Io=$e(ws),Ha=$e(vs),Ba=$e(pr),Ua=$e(Jt),za=Fa,Wa=$e(qt),Ge=Ua.default("https-proxy-agent:agent");class Ka extends za.Agent{constructor(e){let t;if(typeof e=="string"?t=Ha.default.parse(e):t=e,!t)throw new Error("an HTTP(S) proxy server `host` and `port` must be specified!");Ge("creating new HttpsProxyAgent instance: %o",t),super(t);const o=Object.assign({},t);this.secureProxy=t.secureProxy||Va(o.protocol),o.host=o.hostname||o.host,typeof o.port=="string"&&(o.port=parseInt(o.port,10)),!o.port&&o.host&&(o.port=this.secureProxy?443:80),this.secureProxy&&!("ALPNProtocols"in o)&&(o.ALPNProtocols=["http 1.1"]),o.host&&o.path&&(delete o.path,delete o.pathname),this.proxy=o}callback(e,t){return ja(this,void 0,void 0,function*(){const{proxy:o,secureProxy:s}=this;let n;s?(Ge("Creating `tls.Socket`: %o",o),n=Io.default.connect(o)):(Ge("Creating `net.Socket`: %o",o),n=Mo.default.connect(o));const i=Object.assign({},o.headers);let a=`CONNECT ${`${t.host}:${t.port}`} HTTP/1.1\r
79
- `;o.auth&&(i["Proxy-Authorization"]=`Basic ${Buffer.from(o.auth).toString("base64")}`);let{host:m,port:d,secureEndpoint:l}=t;Ya(d,l)||(m+=`:${d}`),i.Host=m,i.Connection="close";for(const y of Object.keys(i))a+=`${y}: ${i[y]}\r
80
- `;const p=Wa.default(n);n.write(`${a}\r
81
- `);const{statusCode:u,buffered:h}=yield p;if(u===200){if(e.once("socket",Ja),t.secureEndpoint){Ge("Upgrading socket connection to TLS");const y=t.servername||t.host;return Io.default.connect(Object.assign(Object.assign({},qa(t,"host","hostname","path","port")),{socket:n,servername:y}))}return n}n.destroy();const g=new Mo.default.Socket({writable:!1});return g.readable=!0,e.once("socket",y=>{Ge("replaying proxy buffer for failed request"),Ba.default(y.listenerCount("data")>0),y.push(h),y.push(null)}),g})}}Ht.default=Ka;function Ja(r){r.resume()}function Ya(r,e){return!!(!e&&r===80||e&&r===443)}function Va(r){return typeof r=="string"?/^https:?$/i.test(r):!1}function qa(r,...e){const t={};let o;for(o in r)e.includes(o)||(t[o]=r[o]);return t}var Xa=j&&j.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};const Xt=Xa(Ht);function Qt(r){return new Xt.default(r)}(function(r){r.HttpsProxyAgent=Xt.default,r.prototype=Xt.default.prototype})(Qt||(Qt={}));var Qa=Qt,Za=me(Qa);const ec=async(r,e,t,o,s,n,i)=>new Promise((c,a)=>{const m=JSON.stringify(o),l=(r.protocol.includes("https")?gs:hs).request({port:i||void 0,hostname:r.hostname,path:e,method:"POST",headers:{"Content-Type":"application/json","Content-Length":Buffer.byteLength(m),...t},timeout:s,agent:n?Za(n):void 0},p=>{const u=[];p.on("data",h=>u.push(h)),p.on("end",()=>{c({request:l,response:p,data:Buffer.concat(u).toString()})})});l.on("error",a),l.on("timeout",()=>{l.destroy(),a(new b(`Time out error: request took over ${s}ms. Try increasing the \`timeout\` config`))}),l.write(m),l.end()}),tc=async(r,e,t,o,s,n)=>{const i=new URL(r),{response:c,data:a}=await ec(i,e,{Authorization:`Bearer ${t}`},o,s,n);if(!c.statusCode||c.statusCode<200||c.statusCode>299){let m=`API Error: ${c.statusCode} - ${c.statusMessage}`;throw a&&(m+=`
77
+ `)===-1){Ne("have not received end of HTTP headers yet..."),n();return}const g=d.toString("ascii",0,d.indexOf(`\r
78
+ `)),h=+g.split(" ")[1];Ne("got proxy server response: %o",g),e({statusCode:h,buffered:d})}r.on("error",m),r.on("close",c),r.on("end",a),n()})}Xt.default=Ha;var Ba=j&&j.__awaiter||function(r,e,t,o){function s(n){return n instanceof t?n:new t(function(i){i(n)})}return new(t||(t=Promise))(function(n,i){function c(u){try{m(o.next(u))}catch(l){i(l)}}function a(u){try{m(o.throw(u))}catch(l){i(l)}}function m(u){u.done?n(u.value):s(u.value).then(c,a)}m((o=o.apply(r,e||[])).next())})},$e=j&&j.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Bt,"__esModule",{value:!0});const Io=$e(ws),Ro=$e(vs),Ua=$e(bs),za=$e(pr),Wa=$e(Yt),Ka=Ga,Ja=$e(Xt),Ge=Wa.default("https-proxy-agent:agent");class Ya extends Ka.Agent{constructor(e){let t;if(typeof e=="string"?t=Ua.default.parse(e):t=e,!t)throw new Error("an HTTP(S) proxy server `host` and `port` must be specified!");Ge("creating new HttpsProxyAgent instance: %o",t),super(t);const o=Object.assign({},t);this.secureProxy=t.secureProxy||Xa(o.protocol),o.host=o.hostname||o.host,typeof o.port=="string"&&(o.port=parseInt(o.port,10)),!o.port&&o.host&&(o.port=this.secureProxy?443:80),this.secureProxy&&!("ALPNProtocols"in o)&&(o.ALPNProtocols=["http 1.1"]),o.host&&o.path&&(delete o.path,delete o.pathname),this.proxy=o}callback(e,t){return Ba(this,void 0,void 0,function*(){const{proxy:o,secureProxy:s}=this;let n;s?(Ge("Creating `tls.Socket`: %o",o),n=Ro.default.connect(o)):(Ge("Creating `net.Socket`: %o",o),n=Io.default.connect(o));const i=Object.assign({},o.headers);let a=`CONNECT ${`${t.host}:${t.port}`} HTTP/1.1\r
79
+ `;o.auth&&(i["Proxy-Authorization"]=`Basic ${Buffer.from(o.auth).toString("base64")}`);let{host:m,port:u,secureEndpoint:l}=t;qa(u,l)||(m+=`:${u}`),i.Host=m,i.Connection="close";for(const y of Object.keys(i))a+=`${y}: ${i[y]}\r
80
+ `;const d=Ja.default(n);n.write(`${a}\r
81
+ `);const{statusCode:p,buffered:g}=yield d;if(p===200){if(e.once("socket",Va),t.secureEndpoint){Ge("Upgrading socket connection to TLS");const y=t.servername||t.host;return Ro.default.connect(Object.assign(Object.assign({},Qa(t,"host","hostname","path","port")),{socket:n,servername:y}))}return n}n.destroy();const h=new Io.default.Socket({writable:!1});return h.readable=!0,e.once("socket",y=>{Ge("replaying proxy buffer for failed request"),za.default(y.listenerCount("data")>0),y.push(g),y.push(null)}),h})}}Bt.default=Ya;function Va(r){r.resume()}function qa(r,e){return!!(!e&&r===80||e&&r===443)}function Xa(r){return typeof r=="string"?/^https:?$/i.test(r):!1}function Qa(r,...e){const t={};let o;for(o in r)e.includes(o)||(t[o]=r[o]);return t}var Za=j&&j.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};const Qt=Za(Bt);function Zt(r){return new Qt.default(r)}(function(r){r.HttpsProxyAgent=Qt.default,r.prototype=Qt.default.prototype})(Zt||(Zt={}));var ec=Zt,tc=me(ec);const rc=async(r,e,t,o,s,n,i)=>new Promise((c,a)=>{const m=JSON.stringify(o),l=(r.protocol.includes("https")?ys:gs).request({port:i||void 0,hostname:r.hostname,path:e,method:"POST",headers:{"Content-Type":"application/json","Content-Length":Buffer.byteLength(m),...t},timeout:s,agent:n?tc(n):void 0},d=>{const p=[];d.on("data",g=>p.push(g)),d.on("end",()=>{c({request:l,response:d,data:Buffer.concat(p).toString()})})});l.on("error",a),l.on("timeout",()=>{l.destroy(),a(new v(`Time out error: request took over ${s}ms. Try increasing the \`timeout\` config`))}),l.write(m),l.end()}),oc=async(r,e,t,o,s,n)=>{const i=new URL(r),{response:c,data:a}=await rc(i,e,{Authorization:`Bearer ${t}`},o,s,n);if(!c.statusCode||c.statusCode<200||c.statusCode>299){let m=`API Error: ${c.statusCode} - ${c.statusMessage}`;throw a&&(m+=`
82
82
 
83
83
  ${a}`),c.statusCode===500&&(m+=`
84
84
 
85
- Check the API status: ${r}`),new b(m)}return JSON.parse(a)},Ro=r=>r.trim(),rc=["gpt-5","gpt-5-mini","gpt-5-nano","gpt-5-codex"],Zt=r=>rc.some(e=>r===e||r.startsWith(`${e}-`)),oc=async(r,e,t,o,s,n,i,c,a,m,d,l,p,u)=>{try{const h=Pe(n,p),g=Zt(s),y={model:s,messages:[{role:"system",content:d},{role:"user",content:h}],stream:!1,n:1,frequency_penalty:0,presence_penalty:0,...g?{max_completion_tokens:c,temperature:1}:{max_tokens:c,top_p:m,temperature:a}},w=new URL(e),v=`${w.protocol}//${w.host}${t}`,E={Authorization:`Bearer ${o}`,"Content-Type":"application/json"};Y(n,p,r,s,v,E,l),V(n,p,r,d,h,l),te(n,p,r,y,l);const k=Date.now(),$=await tc(e,t,o,y,i,u),C=Date.now()-k;q(n,p,r,$,l);const S=$.choices.filter(T=>T.message?.content).map(T=>Ro(T.message.content)).join();return z(n,p,r,C,S,l),$.choices.filter(T=>T.message?.content).map(T=>Ro(T.message.content))}catch(h){_(n,p,r,h,l);const g=h;throw g.code==="ENOTFOUND"?new b(`Error connecting to ${g.hostname} (${g.syscall})`):g}};class sc extends X{constructor(e){super(e),this.params=e,this.baseURL="https://models.github.ai",this.colors={primary:"#24292e",secondary:"#FFF"},this.serviceName=P.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[GitHub Models]"),this.errorPrefix=P.red.bold("[GitHub Models]")}getServiceSpecificErrorMessage(e){switch(e.code){case"MISSING_TOKEN":return"GitHub token is required. Run: aicommit2 github-login";case"AUTHENTICATION_FAILED":return"Authentication failed. Your GitHub token may be expired or invalid. Run: aicommit2 github-login";case"ACCESS_DENIED":return'Access denied. Make sure your GitHub token has "Models" permission in GitHub settings';case"NO_CONTENT":return"No content received from GitHub Models. The model may have failed to generate a response";default:return null}}generateCommitMessage$(){return L(this.generateMessage("commit")).pipe(O(e=>A(e)),M(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})),I(this.handleError$))}generateCodeReview$(){return L(this.generateMessage("review")).pipe(O(e=>A(e)),M(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),I(this.handleError$))}async generateMessage(e){if(!this.params.config.key){const u=new Error("GitHub token is required for GitHub Models. Use: aicommit2 github-login");throw u.code="MISSING_TOKEN",u}const t=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n,locale:i,generate:c,type:a,maxLength:m}=this.params.config,d={...W,locale:i,maxLength:m,type:a,generate:c,systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n},l=e==="review"?Z(d):Q(d),p=await this.makeRequest(l,t,e);return e==="review"?this.sanitizeResponse(p):this.parseMessage(p,a,c)}async makeRequest(e,t,o){const s=Array.isArray(this.params.config.model)?this.params.config.model[0]:this.params.config.model||"gpt-4o-mini",n=[{role:"system",content:e},{role:"user",content:o==="review"?t:`Here's the diff:
85
+ Check the API status: ${r}`),new v(m)}return JSON.parse(a)},Oo=r=>r.trim(),sc=["gpt-5","gpt-5-mini","gpt-5-nano","gpt-5-codex"],er=r=>sc.some(e=>r===e||r.startsWith(`${e}-`)),nc=async(r,e,t,o,s,n,i,c,a,m,u,l,d,p)=>{try{const g=Pe(n,d),h=er(s),y={model:s,messages:[{role:"system",content:u},{role:"user",content:g}],stream:!1,n:1,frequency_penalty:0,presence_penalty:0,...h?{max_completion_tokens:c,temperature:1}:{max_tokens:c,top_p:m,temperature:a}},w=new URL(e),b=`${w.protocol}//${w.host}${t}`,P={Authorization:`Bearer ${o}`,"Content-Type":"application/json"};Y(n,d,r,s,b,P,l),V(n,d,r,u,g,l),te(n,d,r,y,l);const S=Date.now(),k=await oc(e,t,o,y,i,p),$=Date.now()-S;q(n,d,r,k,l);const x=k.choices.filter(E=>E.message?.content).map(E=>Oo(E.message.content)).join();return z(n,d,r,$,x,l),k.choices.filter(E=>E.message?.content).map(E=>Oo(E.message.content))}catch(g){_(n,d,r,g,l);const h=g;throw h.code==="ENOTFOUND"?new v(`Error connecting to ${h.hostname} (${h.syscall})`):h}};class ic extends X{constructor(e){super(e),this.params=e,this.baseURL="https://models.github.ai",this.colors={primary:"#24292e",secondary:"#FFF"},this.serviceName=C.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[GitHub Models]"),this.errorPrefix=C.red.bold("[GitHub Models]")}getServiceSpecificErrorMessage(e){switch(e.code){case"MISSING_TOKEN":return"GitHub token is required. Run: aicommit2 github-login";case"AUTHENTICATION_FAILED":return"Authentication failed. Your GitHub token may be expired or invalid. Run: aicommit2 github-login";case"ACCESS_DENIED":return'Access denied. Make sure your GitHub token has "Models" permission in GitHub settings';case"NO_CONTENT":return"No content received from GitHub Models. The model may have failed to generate a response";default:return null}}generateCommitMessage$(){return D(this.generateMessage("commit")).pipe(L(e=>M(e)),I(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:this.params.config.includeBody?e.value:e.title,description:this.params.config.includeBody?e.value:"",isError:!1})),R(this.handleError$))}generateCodeReview$(){return D(this.generateMessage("review")).pipe(L(e=>M(e)),I(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),R(this.handleError$))}async generateMessage(e){if(!this.params.config.key){const p=new Error("GitHub token is required for GitHub Models. Use: aicommit2 github-login");throw p.code="MISSING_TOKEN",p}const t=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n,locale:i,generate:c,type:a,maxLength:m}=this.params.config,u={...W,locale:i,maxLength:m,type:a,generate:c,systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n},l=e==="review"?Z(u):Q(u),d=await this.makeRequest(l,t,e);return e==="review"?this.sanitizeResponse(d):this.parseMessage(d,a,c)}async makeRequest(e,t,o){const s=Array.isArray(this.params.config.model)?this.params.config.model[0]:this.params.config.model||"gpt-4o-mini",n=[{role:"system",content:e},{role:"user",content:o==="review"?t:`Here's the diff:
86
86
 
87
- ${t}`}],i=Zt(s),c={messages:n,model:s,stream:!1,...i?{max_completion_tokens:this.params.config.maxTokens||1024,temperature:1}:{max_tokens:this.params.config.maxTokens||1024,top_p:this.params.config.topP||.95,temperature:this.params.config.temperature||.7}},a=`${this.baseURL}/inference/chat/completions`,m={"Content-Type":"application/json",Accept:"application/vnd.github+json",Authorization:`Bearer ${this.params.config.key}`},{logging:d}=this.params.config;Y(t,o,"GitHub Models",s,a,m,d),V(t,o,"GitHub Models",e,o==="review"?t:`Here's the diff:
87
+ ${t}`}],i=er(s),c={messages:n,model:s,stream:!1,...i?{max_completion_tokens:this.params.config.maxTokens||1024,temperature:1}:{max_tokens:this.params.config.maxTokens||1024,top_p:this.params.config.topP||.95,temperature:this.params.config.temperature||.7}},a=`${this.baseURL}/inference/chat/completions`,m={"Content-Type":"application/json",Accept:"application/vnd.github+json",Authorization:`Bearer ${this.params.config.key}`},{logging:u}=this.params.config;Y(t,o,"GitHub Models",s,a,m,u),V(t,o,"GitHub Models",e,o==="review"?t:`Here's the diff:
88
88
 
89
- ${t}`,d),te(t,o,"GitHub Models",c,d);const l=new AbortController,p=setTimeout(()=>l.abort(),this.params.config.timeout);try{const u=Date.now(),h=await fetch(a,{method:"POST",headers:m,body:JSON.stringify(c),signal:l.signal});if(clearTimeout(p),!h.ok){const v=await h.text(),E={status:h.status,statusText:h.statusText,url:a,headers:Object.fromEntries(h.headers),body:v};_(t,o,"GitHub Models",E,d);let k=`GitHub API request failed: ${h.status} ${h.statusText}`;try{const C=JSON.parse(v);C.error?.message?k+=` - ${C.error.message}`:C.message&&(k+=` - ${C.message}`)}catch{v&&(k+=` - ${v}`)}if(h.status===401){const C=new Error("GitHub authentication failed. Please run: aicommit2 github-login");throw C.status=h.status,C.code="AUTHENTICATION_FAILED",C.content=v,C}else if(h.status===403){const C=new Error('GitHub Models access denied. Make sure your token has "Models" permission.');throw C.status=h.status,C.code="ACCESS_DENIED",C.content=v,C}else if(h.status===404){const C=new Error(`Model "${s}" not found. Please check the model name.`);throw C.status=h.status,C.code="MODEL_NOT_FOUND",C.content=v,C}else if(h.status===429){const C=new Error("Rate limit exceeded. Please try again later.");throw C.status=h.status,C.code="RATE_LIMIT_EXCEEDED",C.content=v,C}const $=new Error(k);throw $.status=h.status,$.code="API_ERROR",$.content=v,$}const g=await h.json(),y=Date.now()-u;q(t,o,"GitHub Models",g,d);const w=g.choices?.[0]?.message?.content?.trim();if(!w){_(t,o,"GitHub Models",{message:"No content found in GitHub Models response",result:g},d);const E=new Error("No response content received from GitHub Models");throw E.code="NO_CONTENT",E.content=JSON.stringify(g,null,2),E}return z(t,o,"GitHub Models",y,w,d),w}catch(u){if(clearTimeout(p),u instanceof Error&&u.name==="AbortError"){const y={message:`GitHub Models request timeout after ${this.params.config.timeout}ms`,error:u};_(t,o,"GitHub Models",y,d);const w=new Error(`GitHub Models request timed out after ${this.params.config.timeout}ms`);throw w.code="REQUEST_TIMEOUT",w.originalError=u,w}if(u.code)throw u;_(t,o,"GitHub Models",{message:"GitHub Models request failed",error:u},d);const g=new Error(`GitHub Models request failed: ${u instanceof Error?u.message:String(u)}`);throw g.code="REQUEST_FAILED",g.originalError=u,g}}}class nc extends X{constructor(e){super(e),this.params=e,this.colors={primary:"#f55036",secondary:"#fff"},this.serviceName=P.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[Groq]"),this.errorPrefix=P.red.bold("[Groq]"),this.groq=new Ps({apiKey:this.params.config.key})}getServiceSpecificErrorMessage(e){const t=e.message||"";return t.includes("API key")||t.includes("api_key")?"Invalid API key. Check your Groq API key in configuration":t.includes("rate_limit")||t.includes("Rate limit")?"Rate limit exceeded. Wait a moment and try again, or upgrade your Groq plan":t.includes("model")||t.includes("Model")?"Model not found or not accessible. Check if the Groq model name is correct":t.includes("overloaded")||t.includes("capacity")?"Groq service is overloaded. Try again in a few minutes":t.includes("403")||t.includes("Forbidden")?"Access denied. Your API key may not have permission for this Groq model":t.includes("404")||t.includes("Not Found")?"Model or endpoint not found. Check your Groq model configuration":t.includes("500")||t.includes("Internal Server Error")?"Groq server error. Try again later":null}generateCommitMessage$(){return L(this.generateMessage("commit")).pipe(O(e=>A(e)),M(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})),I(this.handleError$))}generateCodeReview$(){return L(this.generateMessage("review")).pipe(O(e=>A(e)),M(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),I(this.handleError$))}async generateMessage(e){const t=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n,logging:i,locale:c,temperature:a,generate:m,type:d,maxLength:l}=this.params.config,p=this.params.config.maxTokens,u={...W,locale:c,maxLength:l,type:d,generate:m,systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n},h=e==="review"?Z(u):Q(u),g=`Here is the diff: ${t}`,w=`${this.params.config.url||"https://api.groq.com"}/openai/v1/chat/completions`,v={Authorization:`Bearer ${this.params.config.key}`,"Content-Type":"application/json"};Y(t,e,"Groq",this.params.config.model,w,v,i),V(t,e,"Groq",h,g,i);const E={messages:[{role:"system",content:h},{role:"user",content:g}],model:this.params.config.model,max_tokens:p,top_p:this.params.config.topP,temperature:a};te(t,e,"Groq",E,i);const k=Date.now();try{const $=await this.groq.chat.completions.create(E,{timeout:this.params.config.timeout}),C=Date.now()-k,S=$.choices[0].message.content||"";return q(t,e,"Groq",$,i),z(t,e,"Groq",C,S,i),e==="review"?this.sanitizeResponse(S):this.parseMessage(S,d,m)}catch($){throw _(t,e,"Groq",$,i),$}}}class ic extends X{constructor(e){super(e),this.params=e,this.headers={},this.models=[],this.currentModelId=null,this.currentConversation=void 0,this.currentConversionID=void 0,this.cookie="",this.colors={primary:"#FED21F",secondary:"#000"},this.serviceName=P.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[HuggingFace]"),this.errorPrefix=P.red.bold("[HuggingFace]"),this.cookie=this.params.config.cookie;const t=this.params.config.url||"https://huggingface.co";this.headers={accept:"*/*","accept-language":"en-US,en;q=0.9","sec-ch-ua":'"Chromium";v="116", "Not)A;Brand";v="24", "Google Chrome";v="116"',"sec-ch-ua-mobile":"?0","sec-ch-ua-platform":'"Windows"',"sec-fetch-dest":"empty","sec-fetch-mode":"cors","sec-fetch-site":"same-origin",origin:t,"Referrer-Policy":"strict-origin-when-cross-origin"}}getServiceSpecificErrorMessage(e){const t=e.message||"";return t.includes("cookie")||t.includes("Cookie")?"Invalid cookie. Check your Hugging Face session cookie in configuration":t.includes("model")||t.includes("Model")?"Model not found or not accessible. Check if the Hugging Face model name is correct":t.includes("conversation")||t.includes("conversion")?"Failed to create conversation. Try again or check your session":t.includes("401")||t.includes("Unauthorized")?"Authentication failed. Your Hugging Face session may have expired":t.includes("403")||t.includes("Forbidden")?"Access denied. You may not have permission to access this model":t.includes("404")||t.includes("Not Found")?"Model not found. Check your Hugging Face model configuration":t.includes("500")||t.includes("Internal Server Error")?"Hugging Face server error. Try again later":t.includes("overloaded")||t.includes("capacity")?"Hugging Face service is overloaded. Try again in a few minutes":null}generateCommitMessage$(){return L(this.generateMessage("commit")).pipe(O(e=>A(e)),M(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})),I(this.handleError$))}generateCodeReview$(){return L(this.generateMessage("review")).pipe(O(e=>A(e)),M(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),I(this.handleError$))}async generateMessage(e){await this.initialize();const t=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n,logging:i,locale:c,generate:a,type:m,maxLength:d,temperature:l,maxTokens:p,topP:u,timeout:h}=this.params.config,g={...W,locale:c,maxLength:d,type:m,generate:a,systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n},y=e==="review"?Z(g):Q(g),w=`Here is the diff: ${t}`,E=`${this.params.config.url||"https://huggingface.co"}/chat/conversation`,k={...this.headers,cookie:this.cookie};Y(t,e,"HuggingFace",this.params.config.model,E,k,i),V(t,e,"HuggingFace",y,w,i);const $=Date.now();try{const C=await this.getNewChat(y),T=await(await this.sendMessage(w,C.id)).completeResponsePromise();await this.deleteConversation(C.id);const G=Date.now()-$;return q(t,e,"HuggingFace",{response:T},i),z(t,e,"HuggingFace",G,T,i),e==="review"?this.sanitizeResponse(T):this.parseMessage(T,m,a)}catch(C){throw _(t,e,"HuggingFace",C,i),C}}async initialize(){const e=await this.getRemoteLlms(),t=e.find(o=>o.name?.toLowerCase()===this.params.config.model.toLowerCase());if(t){this.currentModel=t,this.currentModelId=t.id;return}this.currentModel=e[0],this.currentModelId=e[0].id}async getRemoteLlms(){const e=this.params.config.url||"https://huggingface.co",t=await fetch(`${e}/chat/__data.json`,{headers:{...this.headers,cookie:this.cookie},body:null,method:"GET"});if(t.status!==200)throw new Error(`Failed to get remote LLMs with status code: ${t.status}`);const s=(await t.json()).nodes[0].data,n=s[s[0].models],i=[],c=a=>a===-1?null:s[a];for(const a of n){const m=s[a];if(s[m.unlisted])continue;const d={id:c(m.id),name:c(m.name),displayName:c(m.displayName),preprompt:c(m.preprompt),promptExamples:[],websiteUrl:c(m.websiteUrl),description:c(m.description),datasetName:c(m.datasetName),datasetUrl:c(m.datasetUrl),modelUrl:c(m.modelUrl),parameters:{}},l=c(m.promptExamples);if(l!==null){const h=l.map(g=>c(g));d.promptExamples=h.map(g=>({title:s[g.title],prompt:s[g.prompt]}))}const p=c(m.parameters),u={};for(const[h,g]of Object.entries(p)){if(g===-1){u[h]=null;continue}if(Array.isArray(s[g])){u[h]=s[g].map(y=>s[y]);continue}u[h]=s[g]}d.parameters=u,i.push(d)}return this.models=i,i}async getNewChat(e){const t={model:this.currentModelId,preprompt:e};let o=0;const s=this.params.config.url||"https://huggingface.co";for(;o<5;){const n=await fetch(`${s}/chat/conversation`,{headers:{...this.headers,"content-type":"application/json",cookie:this.cookie,Referer:`${s}/chat/`},body:JSON.stringify(t),method:"POST"}),{conversationId:i}=await n.json();if(i){this.currentConversionID=i;break}else o++}if(!this.currentConversionID)throw new Error("Failed to create new conversion");return await this.getConversationHistory(this.currentConversionID)}async getConversationHistory(e){if(!e)throw new Error("conversationId is required for getConversationHistory");const t=this.params.config.url||"https://huggingface.co",o=await fetch(`${t}/chat/conversation/${e}/__data.json`,{headers:{...this.headers,cookie:this.cookie,Referer:`${t}/chat/`},body:null,method:"GET"});if(o.status!=200)throw new Error("Unable get conversation details "+o);{const s=await o.json();return this.metadataParser(s,e)}}metadataParser(e,t){const o={id:"",model:"",systemPrompt:"",title:"",history:[]},s=e.nodes[1].data,n=s[s[0].model],i=s[s[0].preprompt],c=s[s[0].title],a=s[s[0].messages],m=[];for(const d of a){const l=s[d],p=new Date(s[l.createdAt][1]).getTime()/1e3,u=new Date(s[l.updatedAt][1]).getTime()/1e3;m.push({id:s[l.id],role:s[l.from],content:s[l.content],createdAt:p,updatedAt:u})}return o.id=t,o.model=n,o.systemPrompt=i,o.title=c,o.history=m,this.currentConversation=o,o}async sendMessage(e,t){if(e==="")throw new Error("the prompt can not be empty.");if(!t&&!this.currentConversionID?await this.getNewChat():t?(this.currentConversionID=t,await this.getConversationHistory(t)):this.currentConversionID&&await this.getConversationHistory(this.currentConversionID),!this.currentConversation)throw new Error("Failed to create new conversion");const o={inputs:e,id:this.currentConversation.history[this.currentConversation.history.length-1].id,is_retry:!1,is_continue:!1,web_search:!1,tools:[]},s=new FormData;s.append("data",JSON.stringify(o));const n=this.params.config.url||"https://huggingface.co",i=new AbortController,c=setTimeout(()=>i.abort(),this.params.config.timeout),a=await fetch(`${n}/chat/conversation/${this.currentConversionID}`,{headers:{...this.headers,cookie:this.cookie,Referer:`${n}/chat/conversation/${this.currentConversionID}`},body:s,method:"POST",signal:i.signal});clearTimeout(c);function m(g){try{const y=g.split(`
90
- `),w=[];for(const v of y)v.trim()&&w.push(JSON.parse(v));return w}catch{return[{}]}}const d=new TextDecoder;let l="";const p=new TransformStream({async transform(g,y){const w=d.decode(g);try{const v=m(w);for(const E of v)E.type==="finalAnswer"?(l=E?.text||"",y.terminate()):E.type==="stream"&&y.enqueue(E?.token||"")}catch{throw new Error("Error during parsing response")}}}),u=a.body?.pipeThrough(p);async function h(){return new Promise(async(g,y)=>{try{if(!u)y("ModifiedStream undefined");else{const w=u.getReader();for(;;){const{done:v,value:E}=await w.read();if(v){g(l);break}}}}catch(w){y(w)}})}return{id:this.currentConversionID,stream:u,completeResponsePromise:h}}async deleteConversation(e){const t=this.params.config.url||"https://huggingface.co";return(await fetch(`${t}/chat/conversation/${e}`,{headers:{...this.headers,cookie:this.cookie,Referer:`${t}/chat/`},body:null,method:"DELETE"})).json()}}class ac extends X{constructor(e){super(e),this.params=e,this.apiKey="",this.colors={primary:"#ff7000",secondary:"#fff"},this.serviceName=P.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[MistralAI]"),this.errorPrefix=P.red.bold("[MistralAI]"),this.apiKey=this.params.config.key}getServiceSpecificErrorMessage(e){const t=e.message||"";return t.includes("API key")||t.includes("api_key")?"Invalid API key. Check your Mistral AI API key in configuration":t.includes("quota")||t.includes("usage")?"API quota exceeded. Check your Mistral AI usage limits":t.includes("model")||t.includes("Model")?"Model not found or not accessible. Check if the Mistral model name is correct":t.includes("403")||t.includes("Forbidden")?"Access denied. Your API key may not have permission for this Mistral model":t.includes("404")||t.includes("Not Found")?"Model or endpoint not found. Check your Mistral model configuration":t.includes("500")||t.includes("Internal Server Error")?"Mistral AI server error. Try again later":null}generateCommitMessage$(){return L(this.generateMessage("commit")).pipe(O(e=>A(e)),M(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})),I(this.handleError$))}generateCodeReview$(){return L(this.generateMessage("review")).pipe(O(e=>A(e)),M(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),I(this.handleError$))}async generateMessage(e){const t=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n,logging:i,locale:c,generate:a,type:m,maxLength:d}=this.params.config,l={...W,locale:c,maxLength:d,type:m,generate:a,systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n},p=e==="review"?Z(l):Q(l);await this.checkAvailableModels();const u=`Here is the diff: ${t}`,g=`${this.params.config.url||"https://api.mistral.ai"}/v1/chat/completions`,y={Authorization:`Bearer ${this.apiKey}`,"content-type":"application/json"};Y(t,e,"MistralAI",this.params.config.model,g,y,i),V(t,e,"MistralAI",p,u,i);const w=await this.createChatCompletions(p,u,e);return e==="review"?this.sanitizeResponse(w):this.parseMessage(w,m,a)}async checkAvailableModels(){if((await this.getAvailableModels()).includes(this.params.config.model))return!0;throw new Error(`Invalid model type of Mistral AI: ${this.params.config.model}`)}async getAvailableModels(){const e=this.params.config.url||"https://api.mistral.ai";return(await new Le({method:"GET",baseURL:`${e}/v1/models`,timeout:this.params.config.timeout}).setHeaders({Authorization:`Bearer ${this.apiKey}`,"content-type":"application/json"}).execute()).data.data.filter(o=>o.object==="model").map(o=>o.id)}async createChatCompletions(e,t,o){const s=this.params.stagedDiff.diff,{logging:n}=this.params.config,i={model:this.params.config.model,messages:[{role:"system",content:e},{role:"user",content:t}],temperature:this.params.config.temperature,top_p:this.params.config.topP,max_tokens:this.params.config.maxTokens,stream:!1,safe_prompt:!1,random_seed:et(10,1e3)};te(s,o,"MistralAI",i,n);const c=Date.now();try{const a=this.params.config.url||"https://api.mistral.ai",m=await new Le({method:"POST",baseURL:`${a}/v1/chat/completions`,timeout:this.params.config.timeout}).setHeaders({Authorization:`Bearer ${this.apiKey}`,"content-type":"application/json"}).setBody(i).execute(),d=Date.now()-c,l=m.data;if(q(s,o,"MistralAI",l,n),!l.choices||l.choices.length===0||!l.choices[0].message?.content)throw _(s,o,"MistralAI",{message:"No Content on response",result:l},n),new Error("No Content on response. Please open a Bug report");const u=l.choices[0].message.content;return z(s,o,"MistralAI",d,u,n),u}catch(a){throw _(s,o,"MistralAI",a,n),a}}}class cc extends X{constructor(e){super(e),this.params=e,this.host=Nt,this.model="",this.key="",this.auth="",this.setupFetch=(t,o={})=>Es(t,{...o,dispatcher:new xs({headersTimeout:this.params.config.timeout})}),this.colors={primary:"#FFF",secondary:"#000"},this.model=this.params.keyName,this.serviceName=P.bgHex(this.colors.primary).hex(this.colors.secondary).bold(`[${Ze(this.model)}]`),this.errorPrefix=P.red.bold(`[${Ze(this.model)}]`),this.host=this.params.config.host||Nt,this.auth=this.params.config.auth||"Bearer",this.key=this.params.config.key||"",this.ollama=new $s({host:this.host,fetch:this.setupFetch,...this.key&&{headers:{Authorization:`${this.auth} ${this.key}`}}})}getServiceSpecificErrorMessage(e){const t=e.message||"";return t.includes("ECONNREFUSED")||t.includes("connection")?`Cannot connect to Ollama server at ${this.host}. Make sure Ollama is running`:t.includes("model")||t.includes("Model")?`Model '${this.model}' not found. Pull the model with: ollama pull ${this.model}`:t.includes("401")||t.includes("Unauthorized")?"Authentication failed. Check your Ollama API key if authentication is enabled":t.includes("403")||t.includes("Forbidden")?"Access denied. Check your Ollama server permissions":t.includes("404")||t.includes("Not Found")?`Model '${this.model}' not found on Ollama server. Pull it first with: ollama pull ${this.model}`:t.includes("500")||t.includes("Internal Server Error")?"Ollama server error. Check server logs and try again":t.includes("overloaded")||t.includes("capacity")?"Ollama server is overloaded. Try again in a few minutes":null}generateCommitMessage$(){return L(this.generateMessage("commit")).pipe(O(e=>A(e)),M(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})),I(this.handleError$))}generateCodeReview$(){return L(this.generateMessage("review")).pipe(O(e=>A(e)),M(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),I(this.handleError$))}async generateMessage(e){const t=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n,logging:i,locale:c,generate:a,type:m,maxLength:d}=this.params.config,l={...W,locale:c,maxLength:d,type:m,generate:a,systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n},p=e==="review"?Z(l):Q(l);await this.checkIsAvailableOllama();const u=`Here is the diff: ${t}`,h=`Ollama_${this.model}`,g=`${this.host}/api/chat`,y=this.key?{Authorization:`${this.auth} ${this.key}`}:{};Y(t,e,h,this.model,g,y,i),V(t,e,h,p,u,i);const w=await this.createChatCompletions(p,u,e);return e==="review"?this.sanitizeResponse(w):this.parseMessage(w,m,a)}async checkIsAvailableOllama(){const e=new Le({method:"GET",baseURL:`${this.host}`,timeout:this.params.config.timeout});return this.key&&e.setHeaders({Authorization:`${this.auth} ${this.key}`}),(await e.execute()).data}async createChatCompletions(e,t,o){const{stream:s,numCtx:n,temperature:i,topP:c,timeout:a,maxTokens:m,logging:d}=this.params.config,l=s||!1,p=this.params.stagedDiff.diff,u=`Ollama_${this.model}`,h={model:this.model,messages:[{role:"system",content:e},{role:"user",content:t}],stream:l,keep_alive:a,options:{num_ctx:n,temperature:i,top_p:c,seed:et(10,1e3),num_predict:m??-1}};te(p,o,u,h,d);const g=Date.now();try{const y=await this.ollama.chat(h),w=Date.now()-g;let v="";if(l){if(y)for await(const E of y)v+=E.message.content}else v=y.message.content;return q(p,o,u,{response:v,fullResponse:y},d),z(p,o,u,w,v,d),v}catch(y){throw _(p,o,u,y,d),y}}}class lc extends X{constructor(e){super(e),this.params=e;const t=this.params.keyName||"OPENAI_COMPATIBLE";this.colors=ra(t),this.serviceName=P.bgHex(this.colors.primary).hex(this.colors.secondary).bold(`[${Ze(t)}]`),this.errorPrefix=P.red.bold(`[${Ze(t)}]`),this.openAI=new $r({apiKey:this.params.config.key,baseURL:`${this.params.config.url}${this.params.config.path}`})}getServiceSpecificErrorMessage(e){const t=e.message||"";return t.includes("API key")||t.includes("api_key")?"Invalid API key. Check your OpenAI-compatible API key in configuration":t.includes("rate_limit")||t.includes("Rate limit")?"Rate limit exceeded. Wait a moment and try again, or check your service limits":t.includes("model")||t.includes("Model")?"Model not found or not accessible. Check if the model name is correct":t.includes("network")||t.includes("connection")?"Network error. Check your internet connection and API endpoint":t.includes("quota")||t.includes("usage")?"API quota exceeded. Check your usage limits":t.includes("403")||t.includes("Forbidden")?"Access denied. Your API key may not have permission for this model":t.includes("404")||t.includes("Not Found")?"Model or endpoint not found. Check your API configuration":t.includes("500")||t.includes("Internal Server Error")?"Server error. Try again later":t.includes("overloaded")||t.includes("capacity")?"Service is overloaded. Try again in a few minutes":null}generateCommitMessage$(){return L(this.generateMessage("commit")).pipe(O(e=>A(e)),M(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})),I(this.handleError$))}generateCodeReview$(){return L(this.generateMessage("review")).pipe(O(e=>A(e)),M(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),I(this.handleError$))}async generateMessage(e){const t=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n,logging:i,locale:c,temperature:a,generate:m,type:d,maxLength:l,timeout:p,stream:u=!1}=this.params.config,h=this.params.config.maxTokens,g={...W,locale:c,maxLength:l,type:d,generate:m,systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n},y=e==="review"?Z(g):Q(g),w=`Here is the diff: ${t}`,v=this.params.keyName||"OpenAI-Compatible",E=`${this.params.config.url}${this.params.config.path}`,k={Authorization:`Bearer ${this.params.config.key}`,"Content-Type":"application/json"};Y(t,e,v,this.params.config.model,E,k,i),V(t,e,v,y,w,i);const $=Zt(this.params.config.model),C={messages:[{role:"system",content:y},{role:"user",content:w}],model:this.params.config.model,stream:u,...$?{max_completion_tokens:h,temperature:1}:{max_tokens:h,top_p:this.params.config.topP,temperature:a}};te(t,e,v,C,i);const S=Date.now();try{const T=await this.openAI.chat.completions.create(C,{timeout:p});let G="";if(u&&T){const Ko=T;for await(const ur of Ko){const Jo=ur.choices?.[0]?.delta?.content||"",Yo=ur.choices?.[0]?.delta?.reasoning_content||"",Vo=`${Jo}${Yo}`;G+=Vo}}else G=T.choices?.[0]?.message.content||"";const ae=Date.now()-S;return q(t,e,v,T,i),z(t,e,v,ae,G,i),e==="review"?this.sanitizeResponse(G):this.parseMessage(G,d,m)}catch(T){throw _(t,e,v,T,i),T}}}class uc extends X{constructor(e){super(e),this.params=e,this.colors={primary:"#74AA9C",secondary:"#FFF"},this.serviceName=P.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[ChatGPT]"),this.errorPrefix=P.red.bold("[ChatGPT]")}getServiceSpecificErrorMessage(e){const t=e.message||"";return t.includes("API key")?"Invalid API key. Check your OpenAI API key in configuration":t.includes("quota")?"API quota exceeded. Check your OpenAI usage limits":t.includes("500")?"OpenAI server error. Try again later":null}generateCommitMessage$(){return L(this.generateMessage("commit")).pipe(O(e=>A(e)),M(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})),I(this.handleError$))}generateCodeReview$(){return L(this.generateMessage("review")).pipe(O(e=>A(e)),M(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),I(this.handleError$))}extractJSONFromError(e){const t=/[{[]{1}([,:{}[\]0-9.\-+Eaeflnr-u \n\r\t]|".*?")+[}\]]{1}/gis,o=e.match(t);return o?Object.assign({},...o.map(s=>JSON.parse(s))):{error:{message:"Unknown error"}}}async generateMessage(e){const t=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n,temperature:i,logging:c,locale:a,generate:m,type:d,maxLength:l,proxy:p,maxTokens:u,timeout:h}=this.params.config,g={...W,locale:a,maxLength:l,type:d,generate:m,systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n},y=e==="review"?Z(g):Q(g),w=await oc("ChatGPT",this.params.config.url,this.params.config.path,this.params.config.key,this.params.config.model,t,h,u,i,this.params.config.topP,y,c,e,p);return tt(e==="review"?w.map(v=>this.sanitizeResponse(v)):w.map(v=>this.parseMessage(v,d,m)))}}class dc extends X{constructor(e){super(e),this.params=e,this.apiKey="",this.colors={primary:"#20808D",secondary:"#FFF"},this.serviceName=P.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[Perplexity]"),this.errorPrefix=P.red.bold("[Perplexity]"),this.apiKey=this.params.config.key}getServiceSpecificErrorMessage(e){const t=e.message||"";return t.includes("API key")||t.includes("api_key")?"Invalid API key. Check your Perplexity API key in configuration":t.includes("rate_limit")||t.includes("Rate limit")?"Rate limit exceeded. Wait a moment and try again, or upgrade your Perplexity plan":t.includes("model")||t.includes("Model")?"Model not found or not accessible. Check if the Perplexity model name is correct":t.includes("overloaded")||t.includes("capacity")?"Perplexity service is overloaded. Try again in a few minutes":t.includes("403")||t.includes("Forbidden")?"Access denied. Your API key may not have permission for this Perplexity model":t.includes("404")||t.includes("Not Found")?"Model or endpoint not found. Check your Perplexity model configuration":t.includes("500")||t.includes("Internal Server Error")?"Perplexity server error. Try again later":null}generateCommitMessage$(){return L(this.generateMessage("commit")).pipe(O(e=>A(e)),M(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})),I(this.handleError$))}generateCodeReview$(){return L(this.generateMessage("review")).pipe(O(e=>A(e)),M(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),I(this.handleError$))}extractJSONFromError(e){const t=/[{[]{1}([,:{}[\]0-9.\-+Eaeflnr-u \n\r\t]|".*?")+[}\]]{1}/gis,o=e.match(t);return o?Object.assign({},...o.map(s=>JSON.parse(s))):{error:{message:"Unknown error"}}}async generateMessage(e){const t=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n,logging:i,locale:c,generate:a,type:m,maxLength:d}=this.params.config,l={...W,locale:c,maxLength:d,type:m,generate:a,systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n},p=e==="review"?Z(l):Q(l),u=`Here is the diff: ${t}`,g=`${this.params.config.url||"https://api.perplexity.ai"}/chat/completions`,y={Authorization:`Bearer ${this.apiKey}`,"content-type":"application/json"};Y(t,e,"Perplexity",this.params.config.model,g,y,i),V(t,e,"Perplexity",p,u,i);const w=await this.createChatCompletions(p,u,e);return this.parseMessage(w,m,a)}async createChatCompletions(e,t,o){const s=this.params.stagedDiff.diff,{logging:n}=this.params.config,i={model:this.params.config.model,messages:[{role:"system",content:e},{role:"user",content:t}],temperature:this.params.config.temperature,top_p:this.params.config.topP,max_tokens:this.params.config.maxTokens,stream:!1};te(s,o,"Perplexity",i,n);const c=Date.now();try{const a=this.params.config.url||"https://api.perplexity.ai",m=await new Le({method:"POST",baseURL:`${a}/chat/completions`,timeout:this.params.config.timeout}).setHeaders({Authorization:`Bearer ${this.apiKey}`,"content-type":"application/json"}).setBody(i).execute(),d=Date.now()-c,l=m.data;if(q(s,o,"Perplexity",l,n),!l.choices||l.choices.length===0||!l.choices[0].message?.content)throw _(s,o,"Perplexity",{message:"No Content on response",result:l},n),new Error("No Content on response. Please open a Bug report");const u=l.choices[0].message.content;return z(s,o,"Perplexity",d,u,n),u}catch(a){throw _(s,o,"Perplexity",a,n),a}}}class at{constructor(e,t){this.config=e,this.stagedDiff=t}createCommitMsgRequests$(e){return this.createServiceRequests$(e,"commit")}createCodeReviewRequests$(e){return this.createServiceRequests$(e,"review")}createServiceRequests$(e,t){return A(e).pipe(yr(o=>{const s=this.config[o],n=Array.isArray(s.model)?s.model:[s.model];return A(n).pipe(yr(i=>{if(s.compatible){const c=J.create(lc,{config:{...s,url:s.url||"",path:s.path||"",model:i},stagedDiff:this.stagedDiff,keyName:i});return t==="commit"?c.generateCommitMessage$():c.generateCodeReview$()}switch(o){case"OPENAI":{const a=J.create(uc,{config:{...this.config.OPENAI,model:i},stagedDiff:this.stagedDiff,keyName:i});return t==="commit"?a.generateCommitMessage$():a.generateCodeReview$()}case"GEMINI":{const a=J.create(xa,{config:{...this.config.GEMINI,model:i},stagedDiff:this.stagedDiff,keyName:i});return t==="commit"?a.generateCommitMessage$():a.generateCodeReview$()}case"ANTHROPIC":{const a=J.create(Ca,{config:{...this.config.ANTHROPIC,model:i},stagedDiff:this.stagedDiff,keyName:i});return t==="commit"?a.generateCommitMessage$():a.generateCodeReview$()}case"HUGGINGFACE":{const a=J.create(ic,{config:{...this.config.HUGGINGFACE,model:i},stagedDiff:this.stagedDiff,keyName:i});return t==="commit"?a.generateCommitMessage$():a.generateCodeReview$()}case"MISTRAL":{const a=J.create(ac,{config:{...this.config.MISTRAL,model:i},stagedDiff:this.stagedDiff,keyName:i});return t==="commit"?a.generateCommitMessage$():a.generateCodeReview$()}case"CODESTRAL":{const a=J.create(Pa,{config:{...this.config.CODESTRAL,model:i},stagedDiff:this.stagedDiff,keyName:i});return t==="commit"?a.generateCommitMessage$():a.generateCodeReview$()}case"OLLAMA":{const a=J.create(cc,{config:{...this.config.OLLAMA,model:i},keyName:i,stagedDiff:this.stagedDiff});return t==="commit"?a.generateCommitMessage$():a.generateCodeReview$()}case"COHERE":{const a=J.create($a,{config:{...this.config.COHERE,model:i},stagedDiff:this.stagedDiff,keyName:i});return t==="commit"?a.generateCommitMessage$():a.generateCodeReview$()}case"GROQ":{const a=J.create(nc,{config:{...this.config.GROQ,model:i},stagedDiff:this.stagedDiff,keyName:i});return t==="commit"?a.generateCommitMessage$():a.generateCodeReview$()}case"PERPLEXITY":{const a=J.create(dc,{config:{...this.config.PERPLEXITY,model:i},stagedDiff:this.stagedDiff,keyName:i});return t==="commit"?a.generateCommitMessage$():a.generateCodeReview$()}case"GITHUB_MODELS":{const a=J.create(sc,{config:{...this.config.GITHUB_MODELS,model:i},stagedDiff:this.stagedDiff,keyName:i});return t==="commit"?a.generateCommitMessage$():a.generateCodeReview$()}case"DEEPSEEK":{const a=J.create(Ea,{config:{...this.config.DEEPSEEK,model:i},stagedDiff:this.stagedDiff,keyName:i});return t==="commit"?a.generateCommitMessage$():a.generateCodeReview$()}default:const c=P.red.bold(`[${o}]`);return mt({name:c+" Invalid AI type",value:"Invalid AI type",isError:!0,disabled:!0})}}))}),I(o=>{const s=P.red.bold("[UNKNOWN]");return mt({name:s+` ${o.message||""}`,value:"Unknown error",isError:!0,disabled:!0})}))}}class Oo{getDetectedMessage(e){return`Detected ${e.files.length.toLocaleString()} changed file${e.files.length>1?"s":""} (${e.diff.length.toLocaleString()} characters)`}getDetectedFiles(e){return`Detected ${e.length.toLocaleString()} changed file${e.length>1?"s":""}`}}class er extends Oo{constructor(){super(...arguments),this.name="git",this.excludeFromDiff=e=>`:(exclude)${e}`,this.filesToExclude=["package-lock.json","pnpm-lock.yaml","*.lock","*.lockb"].map(this.excludeFromDiff)}async assertRepo(){try{const{stdout:e}=await N("git",["rev-parse","--show-toplevel"],{reject:!0});return e.trim()}catch(e){const t=e;if(t.code==="ENOENT")throw new b(`Git command not found!
89
+ ${t}`,u),te(t,o,"GitHub Models",c,u);const l=new AbortController,d=setTimeout(()=>l.abort(),this.params.config.timeout);try{const p=Date.now(),g=await fetch(a,{method:"POST",headers:m,body:JSON.stringify(c),signal:l.signal});if(clearTimeout(d),!g.ok){const b=await g.text(),P={status:g.status,statusText:g.statusText,url:a,headers:Object.fromEntries(g.headers),body:b};_(t,o,"GitHub Models",P,u);let S=`GitHub API request failed: ${g.status} ${g.statusText}`;try{const $=JSON.parse(b);$.error?.message?S+=` - ${$.error.message}`:$.message&&(S+=` - ${$.message}`)}catch{b&&(S+=` - ${b}`)}if(g.status===401){const $=new Error("GitHub authentication failed. Please run: aicommit2 github-login");throw $.status=g.status,$.code="AUTHENTICATION_FAILED",$.content=b,$}else if(g.status===403){const $=new Error('GitHub Models access denied. Make sure your token has "Models" permission.');throw $.status=g.status,$.code="ACCESS_DENIED",$.content=b,$}else if(g.status===404){const $=new Error(`Model "${s}" not found. Please check the model name.`);throw $.status=g.status,$.code="MODEL_NOT_FOUND",$.content=b,$}else if(g.status===429){const $=new Error("Rate limit exceeded. Please try again later.");throw $.status=g.status,$.code="RATE_LIMIT_EXCEEDED",$.content=b,$}const k=new Error(S);throw k.status=g.status,k.code="API_ERROR",k.content=b,k}const h=await g.json(),y=Date.now()-p;q(t,o,"GitHub Models",h,u);const w=h.choices?.[0]?.message?.content?.trim();if(!w){_(t,o,"GitHub Models",{message:"No content found in GitHub Models response",result:h},u);const P=new Error("No response content received from GitHub Models");throw P.code="NO_CONTENT",P.content=JSON.stringify(h,null,2),P}return z(t,o,"GitHub Models",y,w,u),w}catch(p){if(clearTimeout(d),p instanceof Error&&p.name==="AbortError"){const y={message:`GitHub Models request timeout after ${this.params.config.timeout}ms`,error:p};_(t,o,"GitHub Models",y,u);const w=new Error(`GitHub Models request timed out after ${this.params.config.timeout}ms`);throw w.code="REQUEST_TIMEOUT",w.originalError=p,w}if(p.code)throw p;_(t,o,"GitHub Models",{message:"GitHub Models request failed",error:p},u);const h=new Error(`GitHub Models request failed: ${p instanceof Error?p.message:String(p)}`);throw h.code="REQUEST_FAILED",h.originalError=p,h}}}class ac extends X{constructor(e){super(e),this.params=e,this.colors={primary:"#f55036",secondary:"#fff"},this.serviceName=C.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[Groq]"),this.errorPrefix=C.red.bold("[Groq]"),this.groq=new $s({apiKey:this.params.config.key})}getServiceSpecificErrorMessage(e){const t=e.message||"";return t.includes("API key")||t.includes("api_key")?"Invalid API key. Check your Groq API key in configuration":t.includes("rate_limit")||t.includes("Rate limit")?"Rate limit exceeded. Wait a moment and try again, or upgrade your Groq plan":t.includes("model")||t.includes("Model")?"Model not found or not accessible. Check if the Groq model name is correct":t.includes("overloaded")||t.includes("capacity")?"Groq service is overloaded. Try again in a few minutes":t.includes("403")||t.includes("Forbidden")?"Access denied. Your API key may not have permission for this Groq model":t.includes("404")||t.includes("Not Found")?"Model or endpoint not found. Check your Groq model configuration":t.includes("500")||t.includes("Internal Server Error")?"Groq server error. Try again later":null}generateCommitMessage$(){return D(this.generateMessage("commit")).pipe(L(e=>M(e)),I(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:this.params.config.includeBody?e.value:e.title,description:this.params.config.includeBody?e.value:"",isError:!1})),R(this.handleError$))}generateCodeReview$(){return D(this.generateMessage("review")).pipe(L(e=>M(e)),I(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),R(this.handleError$))}async generateMessage(e){const t=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n,logging:i,locale:c,temperature:a,generate:m,type:u,maxLength:l}=this.params.config,d=this.params.config.maxTokens,p={...W,locale:c,maxLength:l,type:u,generate:m,systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n},g=e==="review"?Z(p):Q(p),h=`Here is the diff: ${t}`,w=`${this.params.config.url||"https://api.groq.com"}/openai/v1/chat/completions`,b={Authorization:`Bearer ${this.params.config.key}`,"Content-Type":"application/json"};Y(t,e,"Groq",this.params.config.model,w,b,i),V(t,e,"Groq",g,h,i);const P={messages:[{role:"system",content:g},{role:"user",content:h}],model:this.params.config.model,max_tokens:d,top_p:this.params.config.topP,temperature:a};te(t,e,"Groq",P,i);const S=Date.now();try{const k=await this.groq.chat.completions.create(P,{timeout:this.params.config.timeout}),$=Date.now()-S,x=k.choices[0].message.content||"";return q(t,e,"Groq",k,i),z(t,e,"Groq",$,x,i),e==="review"?this.sanitizeResponse(x):this.parseMessage(x,u,m)}catch(k){throw _(t,e,"Groq",k,i),k}}}class cc extends X{constructor(e){super(e),this.params=e,this.headers={},this.models=[],this.currentModelId=null,this.currentConversation=void 0,this.currentConversionID=void 0,this.cookie="",this.colors={primary:"#FED21F",secondary:"#000"},this.serviceName=C.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[HuggingFace]"),this.errorPrefix=C.red.bold("[HuggingFace]"),this.cookie=this.params.config.cookie;const t=this.params.config.url||"https://huggingface.co";this.headers={accept:"*/*","accept-language":"en-US,en;q=0.9","sec-ch-ua":'"Chromium";v="116", "Not)A;Brand";v="24", "Google Chrome";v="116"',"sec-ch-ua-mobile":"?0","sec-ch-ua-platform":'"Windows"',"sec-fetch-dest":"empty","sec-fetch-mode":"cors","sec-fetch-site":"same-origin",origin:t,"Referrer-Policy":"strict-origin-when-cross-origin"}}getServiceSpecificErrorMessage(e){const t=e.message||"";return t.includes("cookie")||t.includes("Cookie")?"Invalid cookie. Check your Hugging Face session cookie in configuration":t.includes("model")||t.includes("Model")?"Model not found or not accessible. Check if the Hugging Face model name is correct":t.includes("conversation")||t.includes("conversion")?"Failed to create conversation. Try again or check your session":t.includes("401")||t.includes("Unauthorized")?"Authentication failed. Your Hugging Face session may have expired":t.includes("403")||t.includes("Forbidden")?"Access denied. You may not have permission to access this model":t.includes("404")||t.includes("Not Found")?"Model not found. Check your Hugging Face model configuration":t.includes("500")||t.includes("Internal Server Error")?"Hugging Face server error. Try again later":t.includes("overloaded")||t.includes("capacity")?"Hugging Face service is overloaded. Try again in a few minutes":null}generateCommitMessage$(){return D(this.generateMessage("commit")).pipe(L(e=>M(e)),I(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:this.params.config.includeBody?e.value:e.title,description:this.params.config.includeBody?e.value:"",isError:!1})),R(this.handleError$))}generateCodeReview$(){return D(this.generateMessage("review")).pipe(L(e=>M(e)),I(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),R(this.handleError$))}async generateMessage(e){await this.initialize();const t=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n,logging:i,locale:c,generate:a,type:m,maxLength:u,temperature:l,maxTokens:d,topP:p,timeout:g}=this.params.config,h={...W,locale:c,maxLength:u,type:m,generate:a,systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n},y=e==="review"?Z(h):Q(h),w=`Here is the diff: ${t}`,P=`${this.params.config.url||"https://huggingface.co"}/chat/conversation`,S={...this.headers,cookie:this.cookie};Y(t,e,"HuggingFace",this.params.config.model,P,S,i),V(t,e,"HuggingFace",y,w,i);const k=Date.now();try{const $=await this.getNewChat(y),E=await(await this.sendMessage(w,$.id)).completeResponsePromise();await this.deleteConversation($.id);const G=Date.now()-k;return q(t,e,"HuggingFace",{response:E},i),z(t,e,"HuggingFace",G,E,i),e==="review"?this.sanitizeResponse(E):this.parseMessage(E,m,a)}catch($){throw _(t,e,"HuggingFace",$,i),$}}async initialize(){const e=await this.getRemoteLlms(),t=e.find(o=>o.name?.toLowerCase()===this.params.config.model.toLowerCase());if(t){this.currentModel=t,this.currentModelId=t.id;return}this.currentModel=e[0],this.currentModelId=e[0].id}async getRemoteLlms(){const e=this.params.config.url||"https://huggingface.co",t=await fetch(`${e}/chat/__data.json`,{headers:{...this.headers,cookie:this.cookie},body:null,method:"GET"});if(t.status!==200)throw new Error(`Failed to get remote LLMs with status code: ${t.status}`);const s=(await t.json()).nodes[0].data,n=s[s[0].models],i=[],c=a=>a===-1?null:s[a];for(const a of n){const m=s[a];if(s[m.unlisted])continue;const u={id:c(m.id),name:c(m.name),displayName:c(m.displayName),preprompt:c(m.preprompt),promptExamples:[],websiteUrl:c(m.websiteUrl),description:c(m.description),datasetName:c(m.datasetName),datasetUrl:c(m.datasetUrl),modelUrl:c(m.modelUrl),parameters:{}},l=c(m.promptExamples);if(l!==null){const g=l.map(h=>c(h));u.promptExamples=g.map(h=>({title:s[h.title],prompt:s[h.prompt]}))}const d=c(m.parameters),p={};for(const[g,h]of Object.entries(d)){if(h===-1){p[g]=null;continue}if(Array.isArray(s[h])){p[g]=s[h].map(y=>s[y]);continue}p[g]=s[h]}u.parameters=p,i.push(u)}return this.models=i,i}async getNewChat(e){const t={model:this.currentModelId,preprompt:e};let o=0;const s=this.params.config.url||"https://huggingface.co";for(;o<5;){const n=await fetch(`${s}/chat/conversation`,{headers:{...this.headers,"content-type":"application/json",cookie:this.cookie,Referer:`${s}/chat/`},body:JSON.stringify(t),method:"POST"}),{conversationId:i}=await n.json();if(i){this.currentConversionID=i;break}else o++}if(!this.currentConversionID)throw new Error("Failed to create new conversion");return await this.getConversationHistory(this.currentConversionID)}async getConversationHistory(e){if(!e)throw new Error("conversationId is required for getConversationHistory");const t=this.params.config.url||"https://huggingface.co",o=await fetch(`${t}/chat/conversation/${e}/__data.json`,{headers:{...this.headers,cookie:this.cookie,Referer:`${t}/chat/`},body:null,method:"GET"});if(o.status!=200)throw new Error("Unable get conversation details "+o);{const s=await o.json();return this.metadataParser(s,e)}}metadataParser(e,t){const o={id:"",model:"",systemPrompt:"",title:"",history:[]},s=e.nodes[1].data,n=s[s[0].model],i=s[s[0].preprompt],c=s[s[0].title],a=s[s[0].messages],m=[];for(const u of a){const l=s[u],d=new Date(s[l.createdAt][1]).getTime()/1e3,p=new Date(s[l.updatedAt][1]).getTime()/1e3;m.push({id:s[l.id],role:s[l.from],content:s[l.content],createdAt:d,updatedAt:p})}return o.id=t,o.model=n,o.systemPrompt=i,o.title=c,o.history=m,this.currentConversation=o,o}async sendMessage(e,t){if(e==="")throw new Error("the prompt can not be empty.");if(!t&&!this.currentConversionID?await this.getNewChat():t?(this.currentConversionID=t,await this.getConversationHistory(t)):this.currentConversionID&&await this.getConversationHistory(this.currentConversionID),!this.currentConversation)throw new Error("Failed to create new conversion");const o={inputs:e,id:this.currentConversation.history[this.currentConversation.history.length-1].id,is_retry:!1,is_continue:!1,web_search:!1,tools:[]},s=new FormData;s.append("data",JSON.stringify(o));const n=this.params.config.url||"https://huggingface.co",i=new AbortController,c=setTimeout(()=>i.abort(),this.params.config.timeout),a=await fetch(`${n}/chat/conversation/${this.currentConversionID}`,{headers:{...this.headers,cookie:this.cookie,Referer:`${n}/chat/conversation/${this.currentConversionID}`},body:s,method:"POST",signal:i.signal});clearTimeout(c);function m(h){try{const y=h.split(`
90
+ `),w=[];for(const b of y)b.trim()&&w.push(JSON.parse(b));return w}catch{return[{}]}}const u=new TextDecoder;let l="";const d=new TransformStream({async transform(h,y){const w=u.decode(h);try{const b=m(w);for(const P of b)P.type==="finalAnswer"?(l=P?.text||"",y.terminate()):P.type==="stream"&&y.enqueue(P?.token||"")}catch{throw new Error("Error during parsing response")}}}),p=a.body?.pipeThrough(d);async function g(){return new Promise(async(h,y)=>{try{if(!p)y("ModifiedStream undefined");else{const w=p.getReader();for(;;){const{done:b,value:P}=await w.read();if(b){h(l);break}}}}catch(w){y(w)}})}return{id:this.currentConversionID,stream:p,completeResponsePromise:g}}async deleteConversation(e){const t=this.params.config.url||"https://huggingface.co";return(await fetch(`${t}/chat/conversation/${e}`,{headers:{...this.headers,cookie:this.cookie,Referer:`${t}/chat/`},body:null,method:"DELETE"})).json()}}class lc extends X{constructor(e){super(e),this.params=e,this.apiKey="",this.colors={primary:"#ff7000",secondary:"#fff"},this.serviceName=C.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[MistralAI]"),this.errorPrefix=C.red.bold("[MistralAI]"),this.apiKey=this.params.config.key}getServiceSpecificErrorMessage(e){const t=e.message||"";return t.includes("API key")||t.includes("api_key")?"Invalid API key. Check your Mistral AI API key in configuration":t.includes("quota")||t.includes("usage")?"API quota exceeded. Check your Mistral AI usage limits":t.includes("model")||t.includes("Model")?"Model not found or not accessible. Check if the Mistral model name is correct":t.includes("403")||t.includes("Forbidden")?"Access denied. Your API key may not have permission for this Mistral model":t.includes("404")||t.includes("Not Found")?"Model or endpoint not found. Check your Mistral model configuration":t.includes("500")||t.includes("Internal Server Error")?"Mistral AI server error. Try again later":null}generateCommitMessage$(){return D(this.generateMessage("commit")).pipe(L(e=>M(e)),I(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:this.params.config.includeBody?e.value:e.title,description:this.params.config.includeBody?e.value:"",isError:!1})),R(this.handleError$))}generateCodeReview$(){return D(this.generateMessage("review")).pipe(L(e=>M(e)),I(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),R(this.handleError$))}async generateMessage(e){const t=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n,logging:i,locale:c,generate:a,type:m,maxLength:u}=this.params.config,l={...W,locale:c,maxLength:u,type:m,generate:a,systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n},d=e==="review"?Z(l):Q(l);await this.checkAvailableModels();const p=`Here is the diff: ${t}`,h=`${this.params.config.url||"https://api.mistral.ai"}/v1/chat/completions`,y={Authorization:`Bearer ${this.apiKey}`,"content-type":"application/json"};Y(t,e,"MistralAI",this.params.config.model,h,y,i),V(t,e,"MistralAI",d,p,i);const w=await this.createChatCompletions(d,p,e);return e==="review"?this.sanitizeResponse(w):this.parseMessage(w,m,a)}async checkAvailableModels(){if((await this.getAvailableModels()).includes(this.params.config.model))return!0;throw new Error(`Invalid model type of Mistral AI: ${this.params.config.model}`)}async getAvailableModels(){const e=this.params.config.url||"https://api.mistral.ai";return(await new Le({method:"GET",baseURL:`${e}/v1/models`,timeout:this.params.config.timeout}).setHeaders({Authorization:`Bearer ${this.apiKey}`,"content-type":"application/json"}).execute()).data.data.filter(o=>o.object==="model").map(o=>o.id)}async createChatCompletions(e,t,o){const s=this.params.stagedDiff.diff,{logging:n}=this.params.config,i={model:this.params.config.model,messages:[{role:"system",content:e},{role:"user",content:t}],temperature:this.params.config.temperature,top_p:this.params.config.topP,max_tokens:this.params.config.maxTokens,stream:!1,safe_prompt:!1,random_seed:et(10,1e3)};te(s,o,"MistralAI",i,n);const c=Date.now();try{const a=this.params.config.url||"https://api.mistral.ai",m=await new Le({method:"POST",baseURL:`${a}/v1/chat/completions`,timeout:this.params.config.timeout}).setHeaders({Authorization:`Bearer ${this.apiKey}`,"content-type":"application/json"}).setBody(i).execute(),u=Date.now()-c,l=m.data;if(q(s,o,"MistralAI",l,n),!l.choices||l.choices.length===0||!l.choices[0].message?.content)throw _(s,o,"MistralAI",{message:"No Content on response",result:l},n),new Error("No Content on response. Please open a Bug report");const p=l.choices[0].message.content;return z(s,o,"MistralAI",u,p,n),p}catch(a){throw _(s,o,"MistralAI",a,n),a}}}class uc extends X{constructor(e){super(e),this.params=e,this.host=Gt,this.model="",this.key="",this.auth="",this.setupFetch=(t,o={})=>xs(t,{...o,dispatcher:new ks({headersTimeout:this.params.config.timeout})}),this.colors={primary:"#FFF",secondary:"#000"},this.model=this.params.keyName,this.serviceName=C.bgHex(this.colors.primary).hex(this.colors.secondary).bold(`[${Ze(this.model)}]`),this.errorPrefix=C.red.bold(`[${Ze(this.model)}]`),this.host=this.params.config.host||Gt,this.auth=this.params.config.auth||"Bearer",this.key=this.params.config.key||"",this.ollama=new Es({host:this.host,fetch:this.setupFetch,...this.key&&{headers:{Authorization:`${this.auth} ${this.key}`}}})}getServiceSpecificErrorMessage(e){const t=e.message||"";return t.includes("ECONNREFUSED")||t.includes("connection")?`Cannot connect to Ollama server at ${this.host}. Make sure Ollama is running`:t.includes("model")||t.includes("Model")?`Model '${this.model}' not found. Pull the model with: ollama pull ${this.model}`:t.includes("401")||t.includes("Unauthorized")?"Authentication failed. Check your Ollama API key if authentication is enabled":t.includes("403")||t.includes("Forbidden")?"Access denied. Check your Ollama server permissions":t.includes("404")||t.includes("Not Found")?`Model '${this.model}' not found on Ollama server. Pull it first with: ollama pull ${this.model}`:t.includes("500")||t.includes("Internal Server Error")?"Ollama server error. Check server logs and try again":t.includes("overloaded")||t.includes("capacity")?"Ollama server is overloaded. Try again in a few minutes":null}generateCommitMessage$(){return D(this.generateMessage("commit")).pipe(L(e=>M(e)),I(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:this.params.config.includeBody?e.value:e.title,description:this.params.config.includeBody?e.value:"",isError:!1})),R(this.handleError$))}generateCodeReview$(){return D(this.generateMessage("review")).pipe(L(e=>M(e)),I(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),R(this.handleError$))}async generateMessage(e){const t=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n,logging:i,locale:c,generate:a,type:m,maxLength:u}=this.params.config,l={...W,locale:c,maxLength:u,type:m,generate:a,systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n},d=e==="review"?Z(l):Q(l);await this.checkIsAvailableOllama();const p=`Here is the diff: ${t}`,g=`Ollama_${this.model}`,h=`${this.host}/api/chat`,y=this.key?{Authorization:`${this.auth} ${this.key}`}:{};Y(t,e,g,this.model,h,y,i),V(t,e,g,d,p,i);const w=await this.createChatCompletions(d,p,e);return e==="review"?this.sanitizeResponse(w):this.parseMessage(w,m,a)}async checkIsAvailableOllama(){const e=new Le({method:"GET",baseURL:`${this.host}`,timeout:this.params.config.timeout});return this.key&&e.setHeaders({Authorization:`${this.auth} ${this.key}`}),(await e.execute()).data}async createChatCompletions(e,t,o){const{stream:s,numCtx:n,temperature:i,topP:c,timeout:a,maxTokens:m,logging:u}=this.params.config,l=s||!1,d=this.params.stagedDiff.diff,p=`Ollama_${this.model}`,g={model:this.model,messages:[{role:"system",content:e},{role:"user",content:t}],stream:l,keep_alive:a,options:{num_ctx:n,temperature:i,top_p:c,seed:et(10,1e3),num_predict:m??-1}};te(d,o,p,g,u);const h=Date.now();try{const y=await this.ollama.chat(g),w=Date.now()-h;let b="";if(l){if(y)for await(const P of y)b+=P.message.content}else b=y.message.content;return q(d,o,p,{response:b,fullResponse:y},u),z(d,o,p,w,b,u),b}catch(y){throw _(d,o,p,y,u),y}}}class dc extends X{constructor(e){super(e),this.params=e;const t=this.params.keyName||"OPENAI_COMPATIBLE";this.colors=oa(t),this.serviceName=C.bgHex(this.colors.primary).hex(this.colors.secondary).bold(`[${Ze(t)}]`),this.errorPrefix=C.red.bold(`[${Ze(t)}]`),this.openAI=new $r({apiKey:this.params.config.key,baseURL:`${this.params.config.url}${this.params.config.path}`})}getServiceSpecificErrorMessage(e){const t=e.message||"";return t.includes("API key")||t.includes("api_key")?"Invalid API key. Check your OpenAI-compatible API key in configuration":t.includes("rate_limit")||t.includes("Rate limit")?"Rate limit exceeded. Wait a moment and try again, or check your service limits":t.includes("model")||t.includes("Model")?"Model not found or not accessible. Check if the model name is correct":t.includes("network")||t.includes("connection")?"Network error. Check your internet connection and API endpoint":t.includes("quota")||t.includes("usage")?"API quota exceeded. Check your usage limits":t.includes("403")||t.includes("Forbidden")?"Access denied. Your API key may not have permission for this model":t.includes("404")||t.includes("Not Found")?"Model or endpoint not found. Check your API configuration":t.includes("500")||t.includes("Internal Server Error")?"Server error. Try again later":t.includes("overloaded")||t.includes("capacity")?"Service is overloaded. Try again in a few minutes":null}generateCommitMessage$(){return D(this.generateMessage("commit")).pipe(L(e=>M(e)),I(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:this.params.config.includeBody?e.value:e.title,description:this.params.config.includeBody?e.value:"",isError:!1})),R(this.handleError$))}generateCodeReview$(){return D(this.generateMessage("review")).pipe(L(e=>M(e)),I(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),R(this.handleError$))}async generateMessage(e){const t=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n,logging:i,locale:c,temperature:a,generate:m,type:u,maxLength:l,timeout:d,stream:p=!1}=this.params.config,g=this.params.config.maxTokens,h={...W,locale:c,maxLength:l,type:u,generate:m,systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n},y=e==="review"?Z(h):Q(h),w=`Here is the diff: ${t}`,b=this.params.keyName||"OpenAI-Compatible",P=`${this.params.config.url}${this.params.config.path}`,S={Authorization:`Bearer ${this.params.config.key}`,"Content-Type":"application/json"};Y(t,e,b,this.params.config.model,P,S,i),V(t,e,b,y,w,i);const k=er(this.params.config.model),$={messages:[{role:"system",content:y},{role:"user",content:w}],model:this.params.config.model,stream:p,...k?{max_completion_tokens:g,temperature:1}:{max_tokens:g,top_p:this.params.config.topP,temperature:a}};te(t,e,b,$,i);const x=Date.now();try{const E=await this.openAI.chat.completions.create($,{timeout:d});let G="";if(p&&E){const Jo=E;for await(const ur of Jo){const Yo=ur.choices?.[0]?.delta?.content||"",Vo=ur.choices?.[0]?.delta?.reasoning_content||"",qo=`${Yo}${Vo}`;G+=qo}}else G=E.choices?.[0]?.message.content||"";const ae=Date.now()-x;return q(t,e,b,E,i),z(t,e,b,ae,G,i),e==="review"?this.sanitizeResponse(G):this.parseMessage(G,u,m)}catch(E){throw _(t,e,b,E,i),E}}}class mc extends X{constructor(e){super(e),this.params=e,this.colors={primary:"#74AA9C",secondary:"#FFF"},this.serviceName=C.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[ChatGPT]"),this.errorPrefix=C.red.bold("[ChatGPT]")}getServiceSpecificErrorMessage(e){const t=e.message||"";return t.includes("API key")?"Invalid API key. Check your OpenAI API key in configuration":t.includes("quota")?"API quota exceeded. Check your OpenAI usage limits":t.includes("500")?"OpenAI server error. Try again later":null}generateCommitMessage$(){return D(this.generateMessage("commit")).pipe(L(e=>M(e)),I(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:this.params.config.includeBody?e.value:e.title,description:this.params.config.includeBody?e.value:"",isError:!1})),R(this.handleError$))}generateCodeReview$(){return D(this.generateMessage("review")).pipe(L(e=>M(e)),I(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),R(this.handleError$))}extractJSONFromError(e){const t=/[{[]{1}([,:{}[\]0-9.\-+Eaeflnr-u \n\r\t]|".*?")+[}\]]{1}/gis,o=e.match(t);return o?Object.assign({},...o.map(s=>JSON.parse(s))):{error:{message:"Unknown error"}}}async generateMessage(e){const t=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n,temperature:i,logging:c,locale:a,generate:m,type:u,maxLength:l,proxy:d,maxTokens:p,timeout:g}=this.params.config,h={...W,locale:a,maxLength:l,type:u,generate:m,systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n},y=e==="review"?Z(h):Q(h),w=await nc("ChatGPT",this.params.config.url,this.params.config.path,this.params.config.key,this.params.config.model,t,g,p,i,this.params.config.topP,y,c,e,d);return tt(e==="review"?w.map(b=>this.sanitizeResponse(b)):w.map(b=>this.parseMessage(b,u,m)))}}class fc extends X{constructor(e){super(e),this.params=e,this.apiKey="",this.colors={primary:"#20808D",secondary:"#FFF"},this.serviceName=C.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[Perplexity]"),this.errorPrefix=C.red.bold("[Perplexity]"),this.apiKey=this.params.config.key}getServiceSpecificErrorMessage(e){const t=e.message||"";return t.includes("API key")||t.includes("api_key")?"Invalid API key. Check your Perplexity API key in configuration":t.includes("rate_limit")||t.includes("Rate limit")?"Rate limit exceeded. Wait a moment and try again, or upgrade your Perplexity plan":t.includes("model")||t.includes("Model")?"Model not found or not accessible. Check if the Perplexity model name is correct":t.includes("overloaded")||t.includes("capacity")?"Perplexity service is overloaded. Try again in a few minutes":t.includes("403")||t.includes("Forbidden")?"Access denied. Your API key may not have permission for this Perplexity model":t.includes("404")||t.includes("Not Found")?"Model or endpoint not found. Check your Perplexity model configuration":t.includes("500")||t.includes("Internal Server Error")?"Perplexity server error. Try again later":null}generateCommitMessage$(){return D(this.generateMessage("commit")).pipe(L(e=>M(e)),I(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:this.params.config.includeBody?e.value:e.title,description:this.params.config.includeBody?e.value:"",isError:!1})),R(this.handleError$))}generateCodeReview$(){return D(this.generateMessage("review")).pipe(L(e=>M(e)),I(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),R(this.handleError$))}extractJSONFromError(e){const t=/[{[]{1}([,:{}[\]0-9.\-+Eaeflnr-u \n\r\t]|".*?")+[}\]]{1}/gis,o=e.match(t);return o?Object.assign({},...o.map(s=>JSON.parse(s))):{error:{message:"Unknown error"}}}async generateMessage(e){const t=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n,logging:i,locale:c,generate:a,type:m,maxLength:u}=this.params.config,l={...W,locale:c,maxLength:u,type:m,generate:a,systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n},d=e==="review"?Z(l):Q(l),p=`Here is the diff: ${t}`,h=`${this.params.config.url||"https://api.perplexity.ai"}/chat/completions`,y={Authorization:`Bearer ${this.apiKey}`,"content-type":"application/json"};Y(t,e,"Perplexity",this.params.config.model,h,y,i),V(t,e,"Perplexity",d,p,i);const w=await this.createChatCompletions(d,p,e);return this.parseMessage(w,m,a)}async createChatCompletions(e,t,o){const s=this.params.stagedDiff.diff,{logging:n}=this.params.config,i={model:this.params.config.model,messages:[{role:"system",content:e},{role:"user",content:t}],temperature:this.params.config.temperature,top_p:this.params.config.topP,max_tokens:this.params.config.maxTokens,stream:!1};te(s,o,"Perplexity",i,n);const c=Date.now();try{const a=this.params.config.url||"https://api.perplexity.ai",m=await new Le({method:"POST",baseURL:`${a}/chat/completions`,timeout:this.params.config.timeout}).setHeaders({Authorization:`Bearer ${this.apiKey}`,"content-type":"application/json"}).setBody(i).execute(),u=Date.now()-c,l=m.data;if(q(s,o,"Perplexity",l,n),!l.choices||l.choices.length===0||!l.choices[0].message?.content)throw _(s,o,"Perplexity",{message:"No Content on response",result:l},n),new Error("No Content on response. Please open a Bug report");const p=l.choices[0].message.content;return z(s,o,"Perplexity",u,p,n),p}catch(a){throw _(s,o,"Perplexity",a,n),a}}}class at{constructor(e,t){this.config=e,this.stagedDiff=t}createCommitMsgRequests$(e){return this.createServiceRequests$(e,"commit")}createCodeReviewRequests$(e){return this.createServiceRequests$(e,"review")}createServiceRequests$(e,t){return M(e).pipe(yr(o=>{const s=this.config[o],n=Array.isArray(s.model)?s.model:[s.model];return M(n).pipe(yr(i=>{if(s.compatible){const c=J.create(dc,{config:{...s,url:s.url||"",path:s.path||"",model:i},stagedDiff:this.stagedDiff,keyName:i});return t==="commit"?c.generateCommitMessage$():c.generateCodeReview$()}switch(o){case"OPENAI":{const a=J.create(mc,{config:{...this.config.OPENAI,model:i},stagedDiff:this.stagedDiff,keyName:i});return t==="commit"?a.generateCommitMessage$():a.generateCodeReview$()}case"GEMINI":{const a=J.create(Sa,{config:{...this.config.GEMINI,model:i},stagedDiff:this.stagedDiff,keyName:i});return t==="commit"?a.generateCommitMessage$():a.generateCodeReview$()}case"ANTHROPIC":{const a=J.create($a,{config:{...this.config.ANTHROPIC,model:i},stagedDiff:this.stagedDiff,keyName:i});return t==="commit"?a.generateCommitMessage$():a.generateCodeReview$()}case"HUGGINGFACE":{const a=J.create(cc,{config:{...this.config.HUGGINGFACE,model:i},stagedDiff:this.stagedDiff,keyName:i});return t==="commit"?a.generateCommitMessage$():a.generateCodeReview$()}case"MISTRAL":{const a=J.create(lc,{config:{...this.config.MISTRAL,model:i},stagedDiff:this.stagedDiff,keyName:i});return t==="commit"?a.generateCommitMessage$():a.generateCodeReview$()}case"CODESTRAL":{const a=J.create(Ea,{config:{...this.config.CODESTRAL,model:i},stagedDiff:this.stagedDiff,keyName:i});return t==="commit"?a.generateCommitMessage$():a.generateCodeReview$()}case"OLLAMA":{const a=J.create(uc,{config:{...this.config.OLLAMA,model:i},keyName:i,stagedDiff:this.stagedDiff});return t==="commit"?a.generateCommitMessage$():a.generateCodeReview$()}case"COHERE":{const a=J.create(xa,{config:{...this.config.COHERE,model:i},stagedDiff:this.stagedDiff,keyName:i});return t==="commit"?a.generateCommitMessage$():a.generateCodeReview$()}case"GROQ":{const a=J.create(ac,{config:{...this.config.GROQ,model:i},stagedDiff:this.stagedDiff,keyName:i});return t==="commit"?a.generateCommitMessage$():a.generateCodeReview$()}case"PERPLEXITY":{const a=J.create(fc,{config:{...this.config.PERPLEXITY,model:i},stagedDiff:this.stagedDiff,keyName:i});return t==="commit"?a.generateCommitMessage$():a.generateCodeReview$()}case"GITHUB_MODELS":{const a=J.create(ic,{config:{...this.config.GITHUB_MODELS,model:i},stagedDiff:this.stagedDiff,keyName:i});return t==="commit"?a.generateCommitMessage$():a.generateCodeReview$()}case"DEEPSEEK":{const a=J.create(ka,{config:{...this.config.DEEPSEEK,model:i},stagedDiff:this.stagedDiff,keyName:i});return t==="commit"?a.generateCommitMessage$():a.generateCodeReview$()}default:const c=C.red.bold(`[${o}]`);return ft({name:c+" Invalid AI type",value:"Invalid AI type",isError:!0,disabled:!0})}}))}),R(o=>{const s=C.red.bold("[UNKNOWN]");return ft({name:s+` ${o.message||""}`,value:"Unknown error",isError:!0,disabled:!0})}))}}class Lo{getDetectedMessage(e){return`Detected ${e.files.length.toLocaleString()} changed file${e.files.length>1?"s":""} (${e.diff.length.toLocaleString()} characters)`}getDetectedFiles(e){return`Detected ${e.length.toLocaleString()} changed file${e.length>1?"s":""}`}}class tr extends Lo{constructor(){super(...arguments),this.name="git",this.excludeFromDiff=e=>`:(exclude)${e}`,this.filesToExclude=["package-lock.json","pnpm-lock.yaml","*.lock","*.lockb"].map(this.excludeFromDiff)}async assertRepo(){try{const{stdout:e}=await N("git",["rev-parse","--show-toplevel"],{reject:!0});return e.trim()}catch(e){const t=e;if(t.code==="ENOENT")throw new v(`Git command not found!
91
91
 
92
- Please install Git first: https://git-scm.com/downloads`);if(t.stderr){if(t.stderr.includes("not a git repository"))throw new b(`Not in a Git repository!
92
+ Please install Git first: https://git-scm.com/downloads`);if(t.stderr){if(t.stderr.includes("not a git repository"))throw new v(`Not in a Git repository!
93
93
 
94
94
  Initialize with: git init
95
- Or navigate to an existing Git repository.`);if(t.stderr.includes("permission denied"))throw new b(`Git permission denied: ${t.stderr.trim()}
95
+ Or navigate to an existing Git repository.`);if(t.stderr.includes("permission denied"))throw new v(`Git permission denied: ${t.stderr.trim()}
96
96
 
97
- Check file permissions and repository access.`)}throw new b(`Failed to verify Git repository: ${t.message||"Unknown error"}`)}}async getStagedDiff(e,t){const o=["diff","--cached","--diff-algorithm=minimal"],{stdout:s}=await N("git",[...o,"--name-only",...this.filesToExclude,...e?e.map(this.excludeFromDiff):[],...t?t.map(this.excludeFromDiff):[]]);if(!s)return null;const{stdout:n}=await N("git",[...o,...this.filesToExclude,...e?e.map(this.excludeFromDiff):[],...t?t.map(this.excludeFromDiff):[]]),i=s.split(`
97
+ Check file permissions and repository access.`)}throw new v(`Failed to verify Git repository: ${t.message||"Unknown error"}`)}}async getStagedDiff(e,t){const o=["diff","--cached","--diff-algorithm=minimal"],{stdout:s}=await N("git",[...o,"--name-only",...this.filesToExclude,...e?e.map(this.excludeFromDiff):[],...t?t.map(this.excludeFromDiff):[]]);if(!s)return null;const{stdout:n}=await N("git",[...o,...this.filesToExclude,...e?e.map(this.excludeFromDiff):[],...t?t.map(this.excludeFromDiff):[]]),i=s.split(`
98
98
  `).filter(Boolean),{stdout:c}=await N("git",[...o,"--numstat",...e?e.map(this.excludeFromDiff):[],...t?t.map(this.excludeFromDiff):[]]),a=[],m=c.split(`
99
- `).filter(Boolean);for(const p of m){const u=p.split(" ");u[0]==="-"&&u[1]==="-"&&u[2]&&a.push(u[2])}let d=n;if(a.length>0){n.trim()||(d=""),d+=`
99
+ `).filter(Boolean);for(const d of m){const p=d.split(" ");p[0]==="-"&&p[1]==="-"&&p[2]&&a.push(p[2])}let u=n;if(a.length>0){n.trim()||(u=""),u+=`
100
100
 
101
101
  --- Binary Files Changed ---
102
- `;for(const p of a){const{stdout:u}=await N("git",["status","--porcelain",p]),h=u.substring(0,2).trim();d+=`Binary file ${p} ${h==="A"?"added":h==="M"?"modified":h==="D"?"deleted":"changed"}
103
- `}}const l=[...new Set([...i,...a])];return{files:l,diff:d||`Files changed: ${l.join(", ")}`}}async getCommitDiff(e,t,o){const s=["diff-tree","-r","--no-commit-id","--name-only",e],{stdout:n}=await N("git",[...s,...this.filesToExclude,...t?t.map(this.excludeFromDiff):[],...o?o.map(this.excludeFromDiff):[]]);if(!n)return null;const{stdout:i}=await N("git",["show",e,"--",...this.filesToExclude,...t?t.map(this.excludeFromDiff):[],...o?o.map(this.excludeFromDiff):[]]),{stdout:c}=await N("git",["diff-tree","-r","--numstat",e,...t?t.map(this.excludeFromDiff):[],...o?o.map(this.excludeFromDiff):[]]),a=[],m=c.split(`
104
- `).filter(Boolean);for(const p of m){const u=p.split(" ");u[0]==="-"&&u[1]==="-"&&u[2]&&a.push(u[2])}let d=i;if(a.length>0){i.trim()||(d=""),d+=`
102
+ `;for(const d of a){const{stdout:p}=await N("git",["status","--porcelain",d]),g=p.substring(0,2).trim();u+=`Binary file ${d} ${g==="A"?"added":g==="M"?"modified":g==="D"?"deleted":"changed"}
103
+ `}}const l=[...new Set([...i,...a])];return{files:l,diff:u||`Files changed: ${l.join(", ")}`}}async getCommitDiff(e,t,o){const s=["diff-tree","-r","--no-commit-id","--name-only",e],{stdout:n}=await N("git",[...s,...this.filesToExclude,...t?t.map(this.excludeFromDiff):[],...o?o.map(this.excludeFromDiff):[]]);if(!n)return null;const{stdout:i}=await N("git",["show",e,"--",...this.filesToExclude,...t?t.map(this.excludeFromDiff):[],...o?o.map(this.excludeFromDiff):[]]),{stdout:c}=await N("git",["diff-tree","-r","--numstat",e,...t?t.map(this.excludeFromDiff):[],...o?o.map(this.excludeFromDiff):[]]),a=[],m=c.split(`
104
+ `).filter(Boolean);for(const d of m){const p=d.split(" ");p[0]==="-"&&p[1]==="-"&&p[2]&&a.push(p[2])}let u=i;if(a.length>0){i.trim()||(u=""),u+=`
105
105
 
106
106
  --- Binary Files Changed ---
107
- `;for(const p of a)d+=`Binary file ${p} changed
107
+ `;for(const d of a)u+=`Binary file ${d} changed
108
108
  `}const l=[...new Set([...n.split(`
109
- `).filter(Boolean),...a])];return{files:l,diff:d||`Files changed: ${l.join(", ")}`}}async commit(e,t=[]){try{await N("git",["commit","-m",e,...t],{stdio:"inherit"})}catch(o){const s=o;throw s.stderr?s.stderr.includes("nothing to commit")?new b(`Nothing to commit.
109
+ `).filter(Boolean),...a])];return{files:l,diff:u||`Files changed: ${l.join(", ")}`}}async commit(e,t=[]){try{await N("git",["commit","-m",e,...t],{stdio:"inherit"})}catch(o){const s=o;throw s.stderr?s.stderr.includes("nothing to commit")?new v(`Nothing to commit.
110
110
 
111
111
  Stage your changes with: git add <files>
112
- Or use the --all flag to stage all changes.`):s.stderr.includes("Please enter the commit message")?new b(`Commit message cannot be empty.
112
+ Or use the --all flag to stage all changes.`):s.stderr.includes("Please enter the commit message")?new v(`Commit message cannot be empty.
113
113
 
114
- Provide a meaningful commit message.`):s.stderr.includes("Author identity unknown")?new b(`Git author identity not configured.
114
+ Provide a meaningful commit message.`):s.stderr.includes("Author identity unknown")?new v(`Git author identity not configured.
115
115
 
116
116
  Configure with:
117
117
  git config --global user.name "Your Name"
118
- git config --global user.email "your.email@example.com"`):s.stderr.includes("Permission denied")?new b(`Git permission error: ${s.stderr.trim()}
118
+ git config --global user.email "your.email@example.com"`):s.stderr.includes("Permission denied")?new v(`Git permission error: ${s.stderr.trim()}
119
119
 
120
- Check repository permissions and file access.`):new b(`Git commit failed: ${s.stderr.trim()}`):s.exitCode===1?new b("Git commit failed. Check your staged changes and try again."):new b(`Failed to commit with Git: ${s.message||"Unknown error"}`)}}async getCommentChar(){try{const{stdout:e}=await N("git",["config","--get","core.commentChar"]);return e}catch{return"#"}}}class mc extends Oo{constructor(){super(...arguments),this.name="jujutsu",this.excludeFromDiff=e=>e.includes("*")||e.includes("?")||e.includes("[")?`~glob:"${e}"`:`~"${e}"`,this.filesToExclude=["package-lock.json","pnpm-lock.yaml","*.lock","*.lockb"]}async assertRepo(){try{const{stdout:e}=await N("jj",["--version"],{reject:!0});process.env.DEBUG&&console.log(`Jujutsu version: ${e}`)}catch(e){const t=e;throw t.code==="ENOENT"?new b(`Jujutsu (jj) command not found!
120
+ Check repository permissions and file access.`):new v(`Git commit failed: ${s.stderr.trim()}`):s.exitCode===1?new v("Git commit failed. Check your staged changes and try again."):new v(`Failed to commit with Git: ${s.message||"Unknown error"}`)}}async getCommentChar(){try{const{stdout:e}=await N("git",["config","--get","core.commentChar"]);return e}catch{return"#"}}}class pc extends Lo{constructor(){super(...arguments),this.name="jujutsu",this.excludeFromDiff=e=>e.includes("*")||e.includes("?")||e.includes("[")?`~glob:"${e}"`:`~"${e}"`,this.filesToExclude=["package-lock.json","pnpm-lock.yaml","*.lock","*.lockb"]}async assertRepo(){try{const{stdout:e}=await N("jj",["--version"],{reject:!0});process.env.DEBUG&&console.log(`Jujutsu version: ${e}`)}catch(e){const t=e;throw t.code==="ENOENT"?new v(`Jujutsu (jj) command not found!
121
121
 
122
122
  Please install Jujutsu:
123
123
  - macOS: brew install jj
124
124
  - Linux: cargo install jj-cli
125
125
  - Windows: cargo install jj-cli
126
- - See: https://github.com/martinvonz/jj#installation`):new b(`Failed to execute jj command: ${t.message}`)}try{const{stdout:e,stderr:t}=await N("jj",["workspace","root"],{reject:!0}),o=e.trim();if(!o)throw new b("jj workspace root returned empty path");const s=x.join(o,".jj");if(!U.existsSync(s))throw new b(`Jujutsu repository directory not found at ${s}
126
+ - See: https://github.com/martinvonz/jj#installation`):new v(`Failed to execute jj command: ${t.message}`)}try{const{stdout:e,stderr:t}=await N("jj",["workspace","root"],{reject:!0}),o=e.trim();if(!o)throw new v("jj workspace root returned empty path");const s=A.join(o,".jj");if(!U.existsSync(s))throw new v(`Jujutsu repository directory not found at ${s}
127
127
 
128
- Initialize a jj repository with: jj init`);return o}catch(e){if(e instanceof b)throw e;const t=e;throw t.stderr?t.stderr.includes("not in a jj repo")?new b(`Not in a Jujutsu repository!
128
+ Initialize a jj repository with: jj init`);return o}catch(e){if(e instanceof v)throw e;const t=e;throw t.stderr?t.stderr.includes("not in a jj repo")?new v(`Not in a Jujutsu repository!
129
129
 
130
130
  Initialize with: jj init
131
- Or navigate to an existing jj repository.`):t.stderr.includes("No workspace found")?new b(`No Jujutsu workspace found!
131
+ Or navigate to an existing jj repository.`):t.stderr.includes("No workspace found")?new v(`No Jujutsu workspace found!
132
132
 
133
- This may be a bare repository. Navigate to a workspace directory.`):new b(`Jujutsu error: ${t.stderr.trim()}`):new b(`Failed to verify Jujutsu repository: ${t.message||"Unknown error"}`)}}async getStagedDiff(e,t){try{const{stdout:o}=await N("jj",["status","--no-pager"]);if(process.env.DEBUG&&(console.log("jj status output:",JSON.stringify(o)),console.log("excludeFiles:",e),console.log("exclude:",t)),o.includes("No changes.")||o.includes("The working copy is clean"))return null;const s=this.filesToExclude.map(this.excludeFromDiff),n=[...e?e.map(this.excludeFromDiff):[],...t?t.map(this.excludeFromDiff):[]],i=[...s,...n];let c="all()";i.length>0&&(c=`all() & ${i.join(" & ")}`);const a=["diff","--name-only"],m=["diff","--git"];i.length>0&&(a.push(c),m.push(c)),process.env.DEBUG&&(console.log("jj diff command with fileset:",a),console.log("fileset expression:",c));const{stdout:d}=await N("jj",a);if(process.env.DEBUG&&console.log("jj diff --name-only output:",JSON.stringify(d)),!d.trim())return null;const{stdout:l}=await N("jj",m),{stdout:p}=await N("jj",["status","--no-pager"]),u=d.split(`
134
- `).filter(Boolean),h=[],g=p.split(`
135
- `);for(const v of g)if(v.includes("(binary)")||v.includes("Binary file")){const E=v.match(/([^\s]+)\s*\(binary\)/);E&&E[1]&&h.push(E[1])}let y=l;if(h.length>0){y+=`
133
+ This may be a bare repository. Navigate to a workspace directory.`):new v(`Jujutsu error: ${t.stderr.trim()}`):new v(`Failed to verify Jujutsu repository: ${t.message||"Unknown error"}`)}}async getStagedDiff(e,t){try{const{stdout:o}=await N("jj",["status","--no-pager"]);if(process.env.DEBUG&&(console.log("jj status output:",JSON.stringify(o)),console.log("excludeFiles:",e),console.log("exclude:",t)),o.includes("No changes.")||o.includes("The working copy is clean"))return null;const s=this.filesToExclude.map(this.excludeFromDiff),n=[...e?e.map(this.excludeFromDiff):[],...t?t.map(this.excludeFromDiff):[]],i=[...s,...n];let c="all()";i.length>0&&(c=`all() & ${i.join(" & ")}`);const a=["diff","--name-only"],m=["diff","--git"];i.length>0&&(a.push(c),m.push(c)),process.env.DEBUG&&(console.log("jj diff command with fileset:",a),console.log("fileset expression:",c));const{stdout:u}=await N("jj",a);if(process.env.DEBUG&&console.log("jj diff --name-only output:",JSON.stringify(u)),!u.trim())return null;const{stdout:l}=await N("jj",m),{stdout:d}=await N("jj",["status","--no-pager"]),p=u.split(`
134
+ `).filter(Boolean),g=[],h=d.split(`
135
+ `);for(const b of h)if(b.includes("(binary)")||b.includes("Binary file")){const P=b.match(/([^\s]+)\s*\(binary\)/);P&&P[1]&&g.push(P[1])}let y=l;if(g.length>0){y+=`
136
136
 
137
137
  --- Binary Files Changed ---
138
- `;for(const v of h)y+=`Binary file ${v} changed
139
- `}const w=[...new Set([...u,...h])];return{files:w,diff:y||`Files changed: ${w.join(", ")}`}}catch(o){const s=o;if(s.stderr){if(s.stderr.includes("No changes to show"))return null;if(s.stderr.includes("Operation not allowed"))throw new b(`Jujutsu diff failed: ${s.stderr.trim()}
138
+ `;for(const b of g)y+=`Binary file ${b} changed
139
+ `}const w=[...new Set([...p,...g])];return{files:w,diff:y||`Files changed: ${w.join(", ")}`}}catch(o){const s=o;if(s.stderr){if(s.stderr.includes("No changes to show"))return null;if(s.stderr.includes("Operation not allowed"))throw new v(`Jujutsu diff failed: ${s.stderr.trim()}
140
140
 
141
- Try: jj status --no-pager`);if(s.stderr.includes("Invalid revision"))throw new b(`Jujutsu revision error: ${s.stderr.trim()}
141
+ Try: jj status --no-pager`);if(s.stderr.includes("Invalid revision"))throw new v(`Jujutsu revision error: ${s.stderr.trim()}
142
142
 
143
- Check if you're in a valid workspace.`)}if(s.exitCode===1&&!s.stderr)return null;if(process.env.DEBUG)throw new b(`Jujutsu diff failed: ${s.message}
143
+ Check if you're in a valid workspace.`)}if(s.exitCode===1&&!s.stderr)return null;if(process.env.DEBUG)throw new v(`Jujutsu diff failed: ${s.message}
144
144
  stderr: ${s.stderr}
145
- exitCode: ${s.exitCode}`);return null}}async getCommitDiff(e,t,o){const s=[...t?t.map(this.excludeFromDiff):[],...o?o.map(this.excludeFromDiff):[]];try{const n=["diff","--name-only","--revision",e],i=["diff","--git","--revision",e];if(s.length>0){const d=`all() & ${s.join(" & ")}`;n.push(d),i.push(d),process.env.DEBUG&&console.log("jj getCommitDiff fileset expression:",d)}const{stdout:c}=await N("jj",n);if(!c.trim())return null;const{stdout:a}=await N("jj",i),m=c.split(`
146
- `).filter(Boolean);return{files:m,diff:a||`Files changed: ${m.join(", ")}`}}catch(n){if(process.env.DEBUG){const i=n;console.log("jj getCommitDiff error:",i.message,i.stderr)}return null}}async commit(e,t=[]){try{await N("jj",["describe","-m",e,...t],{stdio:"inherit"}),await N("jj",["new"],{stdio:"inherit"})}catch(o){const s=o;throw s.stderr?s.stderr.includes("Empty commit message")?new b(`Commit message cannot be empty.
145
+ exitCode: ${s.exitCode}`);return null}}async getCommitDiff(e,t,o){const s=[...t?t.map(this.excludeFromDiff):[],...o?o.map(this.excludeFromDiff):[]];try{const n=["diff","--name-only","--revision",e],i=["diff","--git","--revision",e];if(s.length>0){const u=`all() & ${s.join(" & ")}`;n.push(u),i.push(u),process.env.DEBUG&&console.log("jj getCommitDiff fileset expression:",u)}const{stdout:c}=await N("jj",n);if(!c.trim())return null;const{stdout:a}=await N("jj",i),m=c.split(`
146
+ `).filter(Boolean);return{files:m,diff:a||`Files changed: ${m.join(", ")}`}}catch(n){if(process.env.DEBUG){const i=n;console.log("jj getCommitDiff error:",i.message,i.stderr)}return null}}async commit(e,t=[]){try{await N("jj",["describe","-m",e,...t],{stdio:"inherit"}),await N("jj",["new"],{stdio:"inherit"})}catch(o){const s=o;throw s.stderr?s.stderr.includes("Empty commit message")?new v(`Commit message cannot be empty.
147
147
 
148
- Provide a meaningful commit message.`):s.stderr.includes("No changes to commit")?new b(`No changes to commit.
148
+ Provide a meaningful commit message.`):s.stderr.includes("No changes to commit")?new v(`No changes to commit.
149
149
 
150
- Make some changes first, then try again.`):s.stderr.includes("Invalid revision")?new b(`Jujutsu commit error: ${s.stderr.trim()}
150
+ Make some changes first, then try again.`):s.stderr.includes("Invalid revision")?new v(`Jujutsu commit error: ${s.stderr.trim()}
151
151
 
152
- Ensure you're in a valid workspace with changes.`):s.stderr.includes("Operation not allowed")?new b(`Jujutsu operation not allowed: ${s.stderr.trim()}
152
+ Ensure you're in a valid workspace with changes.`):s.stderr.includes("Operation not allowed")?new v(`Jujutsu operation not allowed: ${s.stderr.trim()}
153
153
 
154
- Check repository state with: jj status`):new b(`Jujutsu describe failed: ${s.stderr.trim()}`):s.exitCode===1?new b("Jujutsu commit failed. Check your changes and repository state."):new b(`Failed to commit with Jujutsu: ${s.message||"Unknown error"}`)}}async getCommentChar(){try{const{stdout:e}=await N("jj",["config","get","ui.comment-char"]);return e.trim()||"#"}catch{return"#"}}}let tr=null;async function fc(){if(process.env.FORCE_GIT==="true")try{const s=new er;return await s.assertRepo(),s}catch(s){throw new b(`FORCE_GIT="true" environment variable is set, but Git is not available or not in a git repository.
155
- ${s instanceof Error?s.message:String(s)}`)}let e=!1;try{e=(await ue({})).forceGit===!0}catch{e=!1}if(e)try{const s=new er;return await s.assertRepo(),s}catch(s){throw new b(`forceGit=true is set in config, but Git is not available or not in a git repository.
156
- ${s instanceof Error?s.message:String(s)}`)}let t=null,o=null;try{const s=new mc;return await s.assertRepo(),s}catch(s){t=s instanceof Error?s:new Error(String(s))}try{const s=new er;return await s.assertRepo(),s}catch(s){o=s instanceof Error?s:new Error(String(s))}if(t&&o){const s=t.message.replace("KnownError: ","").trim(),n=o.message.replace("KnownError: ","").trim();throw new b(`No supported VCS repository found.
154
+ Check repository state with: jj status`):new v(`Jujutsu describe failed: ${s.stderr.trim()}`):s.exitCode===1?new v("Jujutsu commit failed. Check your changes and repository state."):new v(`Failed to commit with Jujutsu: ${s.message||"Unknown error"}`)}}async getCommentChar(){try{const{stdout:e}=await N("jj",["config","get","ui.comment-char"]);return e.trim()||"#"}catch{return"#"}}}let rr=null;async function hc(){if(process.env.FORCE_GIT==="true")try{const s=new tr;return await s.assertRepo(),s}catch(s){throw new v(`FORCE_GIT="true" environment variable is set, but Git is not available or not in a git repository.
155
+ ${s instanceof Error?s.message:String(s)}`)}let e=!1;try{e=(await ue({})).forceGit===!0}catch{e=!1}if(e)try{const s=new tr;return await s.assertRepo(),s}catch(s){throw new v(`forceGit=true is set in config, but Git is not available or not in a git repository.
156
+ ${s instanceof Error?s.message:String(s)}`)}let t=null,o=null;try{const s=new pc;return await s.assertRepo(),s}catch(s){t=s instanceof Error?s:new Error(String(s))}try{const s=new tr;return await s.assertRepo(),s}catch(s){o=s instanceof Error?s:new Error(String(s))}if(t&&o){const s=t.message.replace("KnownError: ","").trim(),n=o.message.replace("KnownError: ","").trim();throw new v(`No supported VCS repository found.
157
157
 
158
158
  Jujutsu Error:
159
159
  ${s}
@@ -166,70 +166,70 @@ Solutions:
166
166
  \u2022 Initialize a Git repository: git init
167
167
  \u2022 Navigate to an existing Jujutsu or Git repository
168
168
  \u2022 Set FORCE_GIT="true" environment variable to force Git detection in a jj repository
169
- \u2022 Set forceGit=true in config file to prefer Git detection`)}throw new b("Unexpected error during VCS detection")}async function Ee(){return tr||(tr=await fc()),tr}const rr=async()=>(await Ee()).assertRepo(),or=async(r,e)=>(await Ee()).getStagedDiff(r,e),pc=async(r,e,t)=>{const o=await Ee();if(!o.getCommitDiff)throw new b(`Commit diff not supported for ${o.name}`);return o.getCommitDiff(r,e,t)},hc=async()=>(await Ee()).getCommentChar(),gc=r=>`Detected ${r.files.length.toLocaleString()} changed file${r.files.length>1?"s":""} (${r.diff.length.toLocaleString()} characters)`,yc=async()=>(await Ee()).name,wc=async(r,e)=>{await(await Ee()).commit(r,e||[])};class re{constructor(){this.title="aicommit2"}printTitle(){try{const e=xr.textSync(this.title,{font:"Small Slant"}),t=ks(["#8B5CF6","#A020F0","#D946EF"]);console.log(P.bold(t.multiline(e)))}catch{console.log(P.bold(xr.textSync(this.title,{font:"Small Slant"})))}}showLoader(e){if(this.loader){this.loader.text=e;return}this.loader=kr(e).start()}stopLoader(){this.loader?.stop(),this.loader=void 0}displaySpinner(e){return kr(e).start()}stopSpinner(e){e.stop(),e.clear()}printStagedFiles(e){console.log(P.bold.green("\u2714 ")+P.bold(`${gc(e)}:`)),console.log(`${e.files.map(t=>` ${t}`).join(`
169
+ \u2022 Set forceGit=true in config file to prefer Git detection`)}throw new v("Unexpected error during VCS detection")}async function Ee(){return rr||(rr=await hc()),rr}const or=async()=>(await Ee()).assertRepo(),sr=async(r,e)=>(await Ee()).getStagedDiff(r,e),gc=async(r,e,t)=>{const o=await Ee();if(!o.getCommitDiff)throw new v(`Commit diff not supported for ${o.name}`);return o.getCommitDiff(r,e,t)},yc=async()=>(await Ee()).getCommentChar(),wc=r=>`Detected ${r.files.length.toLocaleString()} changed file${r.files.length>1?"s":""} (${r.diff.length.toLocaleString()} characters)`,vc=async()=>(await Ee()).name,bc=async(r,e)=>{await(await Ee()).commit(r,e||[])};class re{constructor(){this.title="aicommit2"}printTitle(){try{const e=xr.textSync(this.title,{font:"Small Slant"}),t=Ss(["#8B5CF6","#A020F0","#D946EF"]);console.log(C.bold(t.multiline(e)))}catch{console.log(C.bold(xr.textSync(this.title,{font:"Small Slant"})))}}showLoader(e){if(this.loader){this.loader.text=e;return}this.loader=kr(e).start()}stopLoader(){this.loader?.stop(),this.loader=void 0}displaySpinner(e){return kr(e).start()}stopSpinner(e){e.stop(),e.clear()}printStagedFiles(e){console.log(C.bold.green("\u2714 ")+C.bold(`${wc(e)}:`)),console.log(`${e.files.map(t=>` ${t}`).join(`
170
170
  `)}
171
171
  `)}printAnalyzed(){console.log(`
172
- ${P.bold.green("\u2714")} ${P.bold("Changes analyzed")}`)}printCommitted(){console.log(`
173
- ${P.bold.green("\u2714")} ${P.bold("Successfully committed!")}`)}printCopied(){console.log(`
174
- ${P.bold.green("\u2714")} ${P.bold("Successfully copied! Press 'Ctrl + V' to paste")}`)}printSavedCommitMessage(){console.log(`
175
- ${P.bold.green("\u2714")} ${P.bold("Saved commit message")}`)}printCancelledCommit(){console.log(`
176
- ${P.bold.yellow("\u26A0")} ${P.yellow("Commit cancelled")}`)}printError(e){console.log(`
177
- ${P.bold.red("\u2716")} ${P.red(`${e}`)}`)}printWarning(e){console.log(`
178
- ${P.bold.yellow("\u26A0")} ${P.red(`${e}`)}`)}printSuccess(e){console.log(`
179
- ${P.bold.green("\u2714")} ${P.green(`${e}`)}`)}printInfo(e){console.log(`
180
- ${P.bold.blue("\u2139")} ${P.blue(`${e}`)}`)}printSetupGitEvent(e){console.log(`
181
- ${P.bold.green("\u2714")} ${P.bold(`Git ${e} hook has been set up`)}`)}moveCursorUp(){const e=ze.createInterface({input:process.stdin,output:process.stdout});ze.moveCursor(process.stdout,0,-1),e.close()}moveCursorDown(){const e=ze.createInterface({input:process.stdin,output:process.stdout});ze.moveCursor(process.stdout,0,2),e.close()}print(e){console.log(e)}}const vc={isLoading:!1,startOption:{text:"AI is analyzing your changes"}},Lo={isLoading:!1,startOption:{text:"AI is performing a code review"}},sr="No commit messages were generated",Do="No code reviews were generated",nr={type:"reactiveListPrompt",name:"aicommit2Prompt",message:"Pick a commit message to use: ",emptyMessage:`\u26A0 ${sr}`,loop:!1,descPageSize:15,showDescription:!0,pickKey:"short",isDescriptionDim:!0,stopMessage:"Changes analyzed"};class ir{constructor(e){this.choices$=new wr([]),this.destroyed$=new us(1),this.stopMessage="Changes analyzed",this.isDestroyed=!1,this.subscriptions=new ft,this.inquirerInstance=null,this.loader$=new wr(e)}addSubscription(e){if(this.isDestroyed){e.unsubscribe();return}this.subscriptions.add(e)}initPrompt(e=nr){return this.stopMessage=e.stopMessage,He.registerPrompt("reactiveListPrompt",Ss),this.inquirerInstance=He.prompt({choices$:this.choices$,loader$:this.loader$,...e}),this.inquirerInstance}startLoader(){this.loader$.next({isLoading:!0})}clearLoader(){this.inquirerInstance&&this.loader$.next({isLoading:!1,clear:!0})}refreshChoices(e){this.isDestroyed||!e||!e.value||this.choices$.next([...this.currentChoices,e].sort(Qi))}checkErrorOnChoices(e=!0){if(this.choices$.getValue().map(o=>o).every(o=>o?.isError||o?.disabled)){this.alertNoGeneratedMessage(),this.logEmptyCommitMessage(),e&&process.exit(1);return}this.stopLoaderOnSuccess()}completeSubject(){try{this.destroyed$.next(!0),this.destroyed$.complete(),this.choices$.closed||this.choices$.complete(),this.loader$.closed||this.loader$.complete()}catch(e){console.warn("Error completing subjects:",e)}}closeInquirerInstance(){if(!this.inquirerInstance)return;const e=this.inquirerInstance.ui;e?.rl&&!e.rl.closed&&e.close()}cancel(){this.inquirerInstance?.ui?.activePrompt&&this.inquirerInstance.ui.activePrompt.abortPrompt()}destroy(){if(!this.isDestroyed){this.isDestroyed=!0;try{this.cancel(),this.closeInquirerInstance(),this.subscriptions.unsubscribe(),this.completeSubject()}catch(e){console.warn("Error during ReactivePromptManager destruction:",e)}finally{this.inquirerInstance=null}}}alertNoGeneratedMessage(){this.loader$.next({isLoading:!1,message:sr,stopOption:{doneFrame:"\u26A0",color:"yellow"}})}stopLoaderOnSuccess(){this.loader$.next({isLoading:!1,message:this.stopMessage})}logEmptyCommitMessage(){console.log(`
182
- ${P.bold.yellow("\u26A0")} ${P.yellow(`${sr}`)}`)}get currentChoices(){return this.choices$.getValue().map(e=>e)}}const K=new re;var bc=async(r,e,t,o,s,n,i,c,a,m,d,l,p)=>(async()=>{K.printTitle(),await rr(),o&&await yc()==="git"&&await N("git",["add","--update"]);const u=await ue({locale:r?.toString(),generate:e?.toString(),type:s?.toString(),systemPrompt:c?.toString(),includeBody:a?.toString(),disableLowerCase:l?.toString()},p);(a===!0||u.includeBody===!0)&&Object.keys(u).forEach(C=>{typeof u[C]=="object"&&u[C]!==null&&"includeBody"in u[C]&&(u[C].includeBody=!0)}),l&&Object.keys(u).forEach(C=>{typeof u[C]=="object"&&u[C]!==null&&"disableLowerCase"in u[C]&&(u[C].disableLowerCase=!0)}),await bo(u);const g=K.displaySpinner("Detecting staged files"),y=await or(t,u.exclude);if(g.stop(),!y)throw new b("No staged changes found. Stage your changes manually, or automatically stage all changes with the `--all` flag.");K.printStagedFiles(y);const w=To(u,"commit");if(w.length===0)throw new b("Please set at least one API key via the `aicommit2 config set` command");const v=new at(u,y),E=To(u,"review");E.length>0&&await Cc(v,E);let k=await Pc(v,w,m);if(d){if(K.printInfo("Opening editor to modify commit message..."),k=await $c(k),!k.trim())throw new b("Commit message cannot be empty");K.printSuccess("Commit message edited successfully!"),console.log(`
183
- ${k}
184
- `)}i&&(Ks("copy-paste").copy(k),K.printCopied(),process.exit()),(n||m&&w.length===1)&&(await Fo(k,p),process.exit());const{confirmationPrompt:$}=await He.prompt([{type:"confirm",name:"confirmationPrompt",message:"Use selected message?",default:!0}]);$?await Fo(k,p):K.printCancelledCommit(),process.exit()})().catch(u=>{K.printError(u.message),ie(u),process.exit(1)});function To(r,e){return Object.entries(r).map(([t,o])=>[t,o]).filter(([t,o])=>!o.disabled).filter(([t,o])=>ve.includes(t)||o.compatible===!0).filter(([t,o])=>{switch(e){case"commit":return t==="OLLAMA"?!!o&&!!o.model&&o.model.length>0:t==="HUGGINGFACE"?!!o&&!!o.cookie:!!o.key&&o.key.length>0;case"review":const s=r.codeReview||o.codeReview;return t==="OLLAMA"?!!o&&!!o.model&&o.model.length>0&&s:t==="HUGGINGFACE"?!!o&&!!o.cookie&&s:!!o.key&&o.key.length>0&&s}}).map(([t])=>t)}async function Cc(r,e){const t=new ir(Lo);let o=null;try{const s=t.initPrompt({...nr,name:"codeReviewPrompt",message:"Please check code reviews: ",emptyMessage:`\u26A0 ${Do}`,isDescriptionDim:!1,stopMessage:"Code review completed",descPageSize:20});if(t.startLoader(),o=r.createCodeReviewRequests$(e).subscribe({next:a=>t.refreshChoices(a),error:a=>{console.error("Code review request error:",a),t.checkErrorOnChoices()},complete:()=>t.checkErrorOnChoices()}),!(await s).codeReviewPrompt?.value)throw new b("An error occurred! No selected code review");K.moveCursorUp();const{continuePrompt:c}=await He.prompt([{type:"confirm",name:"continuePrompt",message:"Will you continue without changing the code?",default:!0}]);c||(K.printCancelledCommit(),process.exit())}finally{o&&o.unsubscribe(),t.destroy()}}async function Pc(r,e,t){const o=new ir(vc);let s=null;try{if(t&&e.length===1){const a=[];o.startLoader(),s=r.createCommitMsgRequests$(e).subscribe({next:d=>{a.push(d),o.refreshChoices(d)},error:d=>{console.error("Commit message generation error:",d),o.checkErrorOnChoices(!1)},complete:()=>o.checkErrorOnChoices(!1)}),await new Promise(d=>{s?.add(()=>d())}),o.clearLoader(),K.moveCursorUp();const m=a.find(d=>d.value&&!d.isError&&!d.disabled);if(!m||!m.value)throw new b("No valid commit message was generated");return K.print(`
172
+ ${C.bold.green("\u2714")} ${C.bold("Changes analyzed")}`)}printCommitted(){console.log(`
173
+ ${C.bold.green("\u2714")} ${C.bold("Successfully committed!")}`)}printCopied(){console.log(`
174
+ ${C.bold.green("\u2714")} ${C.bold("Successfully copied! Press 'Ctrl + V' to paste")}`)}printSavedCommitMessage(){console.log(`
175
+ ${C.bold.green("\u2714")} ${C.bold("Saved commit message")}`)}printCancelledCommit(){console.log(`
176
+ ${C.bold.yellow("\u26A0")} ${C.yellow("Commit cancelled")}`)}printError(e){console.log(`
177
+ ${C.bold.red("\u2716")} ${C.red(`${e}`)}`)}printWarning(e){console.log(`
178
+ ${C.bold.yellow("\u26A0")} ${C.red(`${e}`)}`)}printSuccess(e){console.log(`
179
+ ${C.bold.green("\u2714")} ${C.green(`${e}`)}`)}printInfo(e){console.log(`
180
+ ${C.bold.blue("\u2139")} ${C.blue(`${e}`)}`)}printSetupGitEvent(e){console.log(`
181
+ ${C.bold.green("\u2714")} ${C.bold(`Git ${e} hook has been set up`)}`)}moveCursorUp(){const e=ze.createInterface({input:process.stdin,output:process.stdout});ze.moveCursor(process.stdout,0,-1),e.close()}moveCursorDown(){const e=ze.createInterface({input:process.stdin,output:process.stdout});ze.moveCursor(process.stdout,0,2),e.close()}print(e){console.log(e)}}const Cc={isLoading:!1,startOption:{text:"AI is analyzing your changes"}},Do={isLoading:!1,startOption:{text:"AI is performing a code review"}},nr="No commit messages were generated",To="No code reviews were generated",ir={type:"reactiveListPrompt",name:"aicommit2Prompt",message:"Pick a commit message to use: ",emptyMessage:`\u26A0 ${nr}`,loop:!1,descPageSize:15,showDescription:!0,pickKey:"short",isDescriptionDim:!0,stopMessage:"Changes analyzed"};class ar{constructor(e){this.choices$=new wr([]),this.destroyed$=new ds(1),this.stopMessage="Changes analyzed",this.isDestroyed=!1,this.subscriptions=new pt,this.inquirerInstance=null,this.loader$=new wr(e)}addSubscription(e){if(this.isDestroyed){e.unsubscribe();return}this.subscriptions.add(e)}initPrompt(e=ir){return this.stopMessage=e.stopMessage,He.registerPrompt("reactiveListPrompt",As),this.inquirerInstance=He.prompt({choices$:this.choices$,loader$:this.loader$,...e}),this.inquirerInstance}startLoader(){this.loader$.next({isLoading:!0})}clearLoader(){this.inquirerInstance&&this.loader$.next({isLoading:!1,clear:!0})}refreshChoices(e){this.isDestroyed||!e||!e.value||this.choices$.next([...this.currentChoices,e].sort(Zi))}checkErrorOnChoices(e=!0){if(this.choices$.getValue().map(o=>o).every(o=>o?.isError||o?.disabled)){this.alertNoGeneratedMessage(),this.logEmptyCommitMessage(),e&&process.exit(1);return}this.stopLoaderOnSuccess()}completeSubject(){try{this.destroyed$.next(!0),this.destroyed$.complete(),this.choices$.closed||this.choices$.complete(),this.loader$.closed||this.loader$.complete()}catch(e){console.warn("Error completing subjects:",e)}}closeInquirerInstance(){if(!this.inquirerInstance)return;const e=this.inquirerInstance.ui;e?.rl&&!e.rl.closed&&e.close()}cancel(){this.inquirerInstance?.ui?.activePrompt&&this.inquirerInstance.ui.activePrompt.abortPrompt()}destroy(){if(!this.isDestroyed){this.isDestroyed=!0;try{this.cancel(),this.closeInquirerInstance(),this.subscriptions.unsubscribe(),this.completeSubject()}catch(e){va()&&console.warn("Error during ReactivePromptManager destruction:",e)}finally{this.inquirerInstance=null}}}alertNoGeneratedMessage(){this.loader$.next({isLoading:!1,message:nr,stopOption:{doneFrame:"\u26A0",color:"yellow"}})}stopLoaderOnSuccess(){this.loader$.next({isLoading:!1,message:this.stopMessage})}logEmptyCommitMessage(){console.log(`
182
+ ${C.bold.yellow("\u26A0")} ${C.yellow(`${nr}`)}`)}get currentChoices(){return this.choices$.getValue().map(e=>e)}}const K=new re;var Pc=async(r,e,t,o,s,n,i,c,a,m,u,l,d,p)=>(async()=>{K.printTitle(),await or(),o&&await vc()==="git"&&await N("git",["add","--update"]);const g={locale:r?.toString(),generate:e?.toString(),type:s?.toString(),systemPrompt:c?.toString(),includeBody:a?.toString(),disableLowerCase:l?.toString()};d&&(g.logLevel="verbose");const h=await ue(g,p);(a===!0||h.includeBody===!0)&&Object.keys(h).forEach(E=>{typeof h[E]=="object"&&h[E]!==null&&"includeBody"in h[E]&&(h[E].includeBody=!0)}),l&&Object.keys(h).forEach(E=>{typeof h[E]=="object"&&h[E]!==null&&"disableLowerCase"in h[E]&&(h[E].disableLowerCase=!0)}),await Co(h);const w=K.displaySpinner("Detecting staged files"),b=await sr(t,h.exclude);if(w.stop(),!b)throw new v("No staged changes found. Stage your changes manually, or automatically stage all changes with the `--all` flag.");K.printStagedFiles(b);const P=Fo(h,"commit");if(P.length===0)throw new v("Please set at least one API key via the `aicommit2 config set` command");const S=new at(h,b),k=Fo(h,"review");k.length>0&&await $c(S,k);let $=await Ec(S,P,m);if(u){if(K.printInfo("Opening editor to modify commit message..."),$=await xc($),!$.trim())throw new v("Commit message cannot be empty");K.printSuccess("Commit message edited successfully!"),console.log(`
183
+ ${$}
184
+ `)}i&&(Js("copy-paste").copy($),K.printCopied(),process.exit()),(n||m&&P.length===1)&&(await No($,p),process.exit());const{confirmationPrompt:x}=await He.prompt([{type:"confirm",name:"confirmationPrompt",message:"Use selected message?",default:!0}]);x?await No($,p):K.printCancelledCommit(),process.exit()})().catch(g=>{K.printError(g.message),ie(g),process.exit(1)});function Fo(r,e){return Object.entries(r).map(([t,o])=>[t,o]).filter(([t,o])=>!o.disabled).filter(([t,o])=>ve.includes(t)||o.compatible===!0).filter(([t,o])=>{switch(e){case"commit":return t==="OLLAMA"?!!o&&!!o.model&&o.model.length>0:t==="HUGGINGFACE"?!!o&&!!o.cookie:!!o.key&&o.key.length>0;case"review":const s=r.codeReview||o.codeReview;return t==="OLLAMA"?!!o&&!!o.model&&o.model.length>0&&s:t==="HUGGINGFACE"?!!o&&!!o.cookie&&s:!!o.key&&o.key.length>0&&s}}).map(([t])=>t)}async function $c(r,e){const t=new ar(Do);let o=null;try{const s=t.initPrompt({...ir,name:"codeReviewPrompt",message:"Please check code reviews: ",emptyMessage:`\u26A0 ${To}`,isDescriptionDim:!1,stopMessage:"Code review completed",descPageSize:20});if(t.startLoader(),o=r.createCodeReviewRequests$(e).subscribe({next:a=>t.refreshChoices(a),error:a=>{console.error("Code review request error:",a),t.checkErrorOnChoices()},complete:()=>t.checkErrorOnChoices()}),!(await s).codeReviewPrompt?.value)throw new v("An error occurred! No selected code review");K.moveCursorUp();const{continuePrompt:c}=await He.prompt([{type:"confirm",name:"continuePrompt",message:"Will you continue without changing the code?",default:!0}]);c||(K.printCancelledCommit(),process.exit())}finally{o&&o.unsubscribe(),t.destroy()}}async function Ec(r,e,t){const o=new ar(Cc);let s=null;try{if(t&&e.length===1){const a=[];o.startLoader(),s=r.createCommitMsgRequests$(e).subscribe({next:u=>{a.push(u),o.refreshChoices(u)},error:u=>{console.error("Commit message generation error:",u),o.checkErrorOnChoices(!1)},complete:()=>o.checkErrorOnChoices(!1)}),await new Promise(u=>{s?.add(()=>u())}),o.clearLoader(),K.moveCursorUp();const m=a.find(u=>u.value&&!u.isError&&!u.disabled);if(!m||!m.value)throw new v("No valid commit message was generated");return K.print(`
185
185
  ${m.name}
186
- `),m.value}const n=o.initPrompt();o.startLoader(),s=r.createCommitMsgRequests$(e).subscribe({next:a=>o.refreshChoices(a),error:a=>{console.error("Commit message generation error:",a),o.checkErrorOnChoices()},complete:()=>o.checkErrorOnChoices()});const i=await n;K.moveCursorUp();const c=i.aicommit2Prompt?.value;if(!c)throw new b("An error occurred! No selected message");return c}finally{s&&s.unsubscribe(),o.destroy()}}async function $c(r){const e=process.env.VISUAL||process.env.EDITOR||(process.platform==="win32"?"notepad":"vi"),t=x.join(xe.tmpdir(),`aicommit2-${Date.now()}.txt`);try{U.writeFileSync(t,r,"utf8"),await N(e,[t],{stdio:"inherit"});const o=U.readFileSync(t,"utf8").trim();if(U.unlinkSync(t),!o)throw new b("Commit cancelled - empty message");return o}catch(o){throw U.existsSync(t)&&U.unlinkSync(t),o instanceof b?o:o&&typeof o=="object"&&"exitCode"in o&&o.exitCode!==0?new b("Commit cancelled"):process.env.VISUAL||process.env.EDITOR?new b(`Failed to open editor "${e}". Please check that the editor command is valid and available.`):new b(`Failed to open editor "${e}". Please set your EDITOR or VISUAL environment variable to a valid editor command.`)}}async function Fo(r,e){await wc(r,e),K.printCommitted()}var Ec=oe({name:"config",parameters:["<mode>","[key=value...]"],help:{description:"Manage configuration settings",examples:["aic2 config set <key>=<value> [<key>=<value> ...]","aic2 config get [<key> [<key> ...]]","aic2 config add <key>=<value> [<key>=<value> ...]","aic2 config del <key>","aic2 config list"]},commands:[oe({name:"set",parameters:["<key>=<value>","[<key>=<value> ...]"],help:{description:"Set configuration values. Multiple key-value pairs can be set at once.",examples:["aic2 config set OPENAI.key=<your key>","aic2 config set ANTHROPIC.topP=0.8 ANTHROPIC.generate=2"]}}),oe({name:"get",parameters:["[<key>","[<key> ...]]"],help:{description:"Retrieve configuration values for specified AI provider.",examples:["aic2 config get OPENAI","aic2 config get ANTHROPIC"]}}),oe({name:"add",parameters:["<key>=<value>","[<key>=<value> ...]"],help:{description:"Add new model to existing configuration. Only Ollama.model can be added.",examples:['aic2 config add OLLAMA.model="gemma2"']}}),oe({name:"list",parameters:[],help:{description:"Display all configuration keys and their values.",examples:["aic2 config list"]}}),oe({name:"del",parameters:["<config-name>"],help:{description:"Delete a configuration setting or section.",examples:["aic2 config del <config-name>","aic2 config del OPENAI.key","aic2 config del OPENAI"]}}),oe({name:"path",parameters:[],help:{description:"Display the path of the loaded configuration file.",examples:["aic2 config path"]}})]},r=>{(async()=>{const{mode:e,keyValue:t}=r._,o=r._[1];if(e==="get"){const s=await ue({},[]);if(t.length===0){console.log(s);return}for(const n of t){const i=n.split(".");let c=s,a=!0;for(const m of i)if(Gt(c,m))c=c[m];else{a=!1;break}a?console.log(n,c):console.log(`${n} not found`)}return}if(e==="set"){await _t(t.map(s=>{const n=s.indexOf("=");if(n===-1)throw new b("Invalid format. Use: key=value");const i=s.slice(0,n),c=s.slice(n+1);return[i,c]}));return}if(e==="add"){await ua(t.map(s=>{const n=s.indexOf("=");if(n===-1)throw new b("Invalid format. Use: key=value");const i=s.slice(0,n),c=s.slice(n+1);return[i,c]}));return}if(e==="list"){await da();return}if(e==="del"){if(!o)throw new b("Please provide the config name to delete.");const s=await Re(),n=o.split(".");if(n.length===2){const[i,c]=n;if(s[i]&&typeof s[i]=="object"&&Gt(s[i],c)){delete s[i][c],Object.keys(s[i]).length===0&&delete s[i];const a=await be();await R.writeFile(a,we.stringify(s),"utf8"),console.log(`Successfully deleted config: ${o}`);const m=await R.readFile(a,"utf8");console.log("--- Updated Config Content ---"),console.log(m),console.log("----------------------------")}else throw new b(`Config not found: ${o}`)}else if(n.length===1){const i=n[0];if(Gt(s,i)){delete s[i];const c=await be();await R.writeFile(c,we.stringify(s),"utf8"),console.log(`Successfully deleted config: ${o}`);const a=await R.readFile(c,"utf8");console.log("--- Updated Config Content ---"),console.log(a),console.log("----------------------------")}else throw new b(`Config not found: ${o}`)}else throw new b(`Invalid config name format: ${o}`);return}if(e==="path"){await ma();return}throw new b(`Invalid mode: ${e}`)})().catch(e=>{new re().printError(e.message),ie(e),process.exit(1)})}),xc=oe({name:"github-login",parameters:[],flags:{token:{type:String,description:"Manually provide a GitHub token for authentication",alias:"t"}},help:{description:"Login to GitHub and setup access to GitHub Models",examples:["aic2 github-login","aic2 github-login --token ghp_xxxxxxxxxxxxxxxxxxxx"]}},r=>{(async()=>{const e=new re;if(r.flags.token){try{await kc(r.flags.token,e)}catch(t){throw new b(`Token authentication failed: ${t.message}`)}return}try{await Sc(e)}catch(t){throw new b(`Browser authentication failed: ${t.message}`)}})().catch(e=>{new re().printError(e.message),ie(e),process.exit(1)})});async function kc(r,e){if(e.printWarning("Authenticating with provided token..."),!r.startsWith("ghp_")&&!r.startsWith("gho_")&&!r.startsWith("ghu_"))throw new Error("Invalid token format. GitHub tokens should start with ghp_, gho_, or ghu_");try{const t=await fetch("https://api.github.com/user",{headers:{Authorization:`Bearer ${r}`,Accept:"application/vnd.github.v3+json","User-Agent":"aicommit2-github-models"}});if(!t.ok)throw new Error(`GitHub API request failed: ${t.status} ${t.statusText}`);const o=await t.json();try{(await fetch("https://models.github.ai/inference/chat/completions",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/vnd.github+json",Authorization:`Bearer ${r}`,"User-Agent":"aicommit2-github-models"},body:JSON.stringify({messages:[{role:"user",content:"test"}],model:"gpt-4o-mini",max_tokens:1})})).ok?e.printSuccess("GitHub Models access verified!"):e.printWarning("Could not verify GitHub Models access, but proceeding with authentication...")}catch{e.printWarning("Could not verify GitHub Models access, but proceeding with authentication...")}await _t([["GITHUB_MODELS.key",r]]),e.printSuccess(`Successfully authenticated as ${o.login}`)}catch(t){throw new Error(`Token validation failed: ${t.message}`)}}async function Sc(r){r.printInfo("Starting GitHub browser authentication for GitHub Models...");try{try{je("gh --version",{stdio:"ignore"})}catch{throw new Error("GitHub CLI (gh) is not installed. Please install it first: https://cli.github.com/")}try{je("gh auth status",{encoding:"utf8",stdio:"pipe"}).includes("Logged in to github.com")&&r.printInfo("Already authenticated with GitHub CLI")}catch{r.printInfo("Authenticating with GitHub CLI..."),r.printInfo("Please follow the instructions in your browser to complete authentication.");try{je("gh auth login --web -h github.com",{stdio:"inherit"})}catch{throw new Error("GitHub CLI authentication failed")}}r.printInfo("Verifying GitHub Models access...");try{const e=je("gh auth token",{encoding:"utf8"}).trim();e&&(await _t([["GITHUB_MODELS.key",e]]),r.printSuccess("GitHub token stored for GitHub Models access"))}catch{r.printWarning("Could not extract token from GitHub CLI, but authentication completed")}r.printSuccess("GitHub authentication completed and GitHub Models access verified!"),r.printInfo("See usage guide: https://github.com/tak-bro/aicommit2/blob/main/docs/providers/github-models.md"),r.printInfo("Available models: gpt-4o-mini, gpt-4o, meta-llama-3.1-405b-instruct, etc."),r.printInfo("Using GitHub Models API: https://models.github.ai")}catch(e){throw e}}const No="prepare-commit-msg",Go=`.git/hooks/${No}`,ct=bs(new URL("cli.mjs",import.meta.url)),Ac=process.argv[1].replace(/\\/g,"/").endsWith(`/${Go}`),_o=process.platform==="win32",jo=`
186
+ `),m.value}const n=o.initPrompt();o.startLoader(),s=r.createCommitMsgRequests$(e).subscribe({next:a=>o.refreshChoices(a),error:a=>{console.error("Commit message generation error:",a),o.checkErrorOnChoices()},complete:()=>o.checkErrorOnChoices()});const i=await n;K.moveCursorUp();const c=i.aicommit2Prompt?.value;if(!c)throw new v("An error occurred! No selected message");return c}finally{s&&s.unsubscribe(),o.destroy()}}async function xc(r){const e=process.env.VISUAL||process.env.EDITOR||(process.platform==="win32"?"notepad":"vi"),t=A.join(xe.tmpdir(),`aicommit2-${Date.now()}.txt`);try{U.writeFileSync(t,r,"utf8"),await N(e,[t],{stdio:"inherit"});const o=U.readFileSync(t,"utf8").trim();if(U.unlinkSync(t),!o)throw new v("Commit cancelled - empty message");return o}catch(o){throw U.existsSync(t)&&U.unlinkSync(t),o instanceof v?o:o&&typeof o=="object"&&"exitCode"in o&&o.exitCode!==0?new v("Commit cancelled"):process.env.VISUAL||process.env.EDITOR?new v(`Failed to open editor "${e}". Please check that the editor command is valid and available.`):new v(`Failed to open editor "${e}". Please set your EDITOR or VISUAL environment variable to a valid editor command.`)}}async function No(r,e){await bc(r,e),K.printCommitted()}var kc=oe({name:"config",parameters:["<mode>","[key=value...]"],help:{description:"Manage configuration settings",examples:["aic2 config set <key>=<value> [<key>=<value> ...]","aic2 config get [<key> [<key> ...]]","aic2 config add <key>=<value> [<key>=<value> ...]","aic2 config del <key>","aic2 config list"]},commands:[oe({name:"set",parameters:["<key>=<value>","[<key>=<value> ...]"],help:{description:"Set configuration values. Multiple key-value pairs can be set at once.",examples:["aic2 config set OPENAI.key=<your key>","aic2 config set ANTHROPIC.topP=0.8 ANTHROPIC.generate=2"]}}),oe({name:"get",parameters:["[<key>","[<key> ...]]"],help:{description:"Retrieve configuration values for specified AI provider.",examples:["aic2 config get OPENAI","aic2 config get ANTHROPIC"]}}),oe({name:"add",parameters:["<key>=<value>","[<key>=<value> ...]"],help:{description:"Add new model to existing configuration. Only Ollama.model can be added.",examples:['aic2 config add OLLAMA.model="gemma2"']}}),oe({name:"list",parameters:[],help:{description:"Display all configuration keys and their values.",examples:["aic2 config list"]}}),oe({name:"del",parameters:["<config-name>"],help:{description:"Delete a configuration setting or section.",examples:["aic2 config del <config-name>","aic2 config del OPENAI.key","aic2 config del OPENAI"]}}),oe({name:"path",parameters:[],help:{description:"Display the path of the loaded configuration file.",examples:["aic2 config path"]}})]},r=>{(async()=>{const{mode:e,keyValue:t}=r._,o=r._[1];if(e==="get"){const s=await ue({},[]);if(t.length===0){console.log(s);return}for(const n of t){const i=n.split(".");let c=s,a=!0;for(const m of i)if(_t(c,m))c=c[m];else{a=!1;break}a?console.log(n,c):console.log(`${n} not found`)}return}if(e==="set"){await jt(t.map(s=>{const n=s.indexOf("=");if(n===-1)throw new v("Invalid format. Use: key=value");const i=s.slice(0,n),c=s.slice(n+1);return[i,c]}));return}if(e==="add"){await da(t.map(s=>{const n=s.indexOf("=");if(n===-1)throw new v("Invalid format. Use: key=value");const i=s.slice(0,n),c=s.slice(n+1);return[i,c]}));return}if(e==="list"){await ma();return}if(e==="del"){if(!o)throw new v("Please provide the config name to delete.");const s=await Re(),n=o.split(".");if(n.length===2){const[i,c]=n;if(s[i]&&typeof s[i]=="object"&&_t(s[i],c)){delete s[i][c],Object.keys(s[i]).length===0&&delete s[i];const a=await be();await O.writeFile(a,we.stringify(s),"utf8"),console.log(`Successfully deleted config: ${o}`);const m=await O.readFile(a,"utf8");console.log("--- Updated Config Content ---"),console.log(m),console.log("----------------------------")}else throw new v(`Config not found: ${o}`)}else if(n.length===1){const i=n[0];if(_t(s,i)){delete s[i];const c=await be();await O.writeFile(c,we.stringify(s),"utf8"),console.log(`Successfully deleted config: ${o}`);const a=await O.readFile(c,"utf8");console.log("--- Updated Config Content ---"),console.log(a),console.log("----------------------------")}else throw new v(`Config not found: ${o}`)}else throw new v(`Invalid config name format: ${o}`);return}if(e==="path"){await fa();return}throw new v(`Invalid mode: ${e}`)})().catch(e=>{new re().printError(e.message),ie(e),process.exit(1)})}),Sc=oe({name:"github-login",parameters:[],flags:{token:{type:String,description:"Manually provide a GitHub token for authentication",alias:"t"}},help:{description:"Login to GitHub and setup access to GitHub Models",examples:["aic2 github-login","aic2 github-login --token ghp_xxxxxxxxxxxxxxxxxxxx"]}},r=>{(async()=>{const e=new re;if(r.flags.token){try{await Ac(r.flags.token,e)}catch(t){throw new v(`Token authentication failed: ${t.message}`)}return}try{await Mc(e)}catch(t){throw new v(`Browser authentication failed: ${t.message}`)}})().catch(e=>{new re().printError(e.message),ie(e),process.exit(1)})});async function Ac(r,e){if(e.printWarning("Authenticating with provided token..."),!r.startsWith("ghp_")&&!r.startsWith("gho_")&&!r.startsWith("ghu_"))throw new Error("Invalid token format. GitHub tokens should start with ghp_, gho_, or ghu_");try{const t=await fetch("https://api.github.com/user",{headers:{Authorization:`Bearer ${r}`,Accept:"application/vnd.github.v3+json","User-Agent":"aicommit2-github-models"}});if(!t.ok)throw new Error(`GitHub API request failed: ${t.status} ${t.statusText}`);const o=await t.json();try{(await fetch("https://models.github.ai/inference/chat/completions",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/vnd.github+json",Authorization:`Bearer ${r}`,"User-Agent":"aicommit2-github-models"},body:JSON.stringify({messages:[{role:"user",content:"test"}],model:"gpt-4o-mini",max_tokens:1})})).ok?e.printSuccess("GitHub Models access verified!"):e.printWarning("Could not verify GitHub Models access, but proceeding with authentication...")}catch{e.printWarning("Could not verify GitHub Models access, but proceeding with authentication...")}await jt([["GITHUB_MODELS.key",r]]),e.printSuccess(`Successfully authenticated as ${o.login}`)}catch(t){throw new Error(`Token validation failed: ${t.message}`)}}async function Mc(r){r.printInfo("Starting GitHub browser authentication for GitHub Models...");try{try{je("gh --version",{stdio:"ignore"})}catch{throw new Error("GitHub CLI (gh) is not installed. Please install it first: https://cli.github.com/")}try{je("gh auth status",{encoding:"utf8",stdio:"pipe"}).includes("Logged in to github.com")&&r.printInfo("Already authenticated with GitHub CLI")}catch{r.printInfo("Authenticating with GitHub CLI..."),r.printInfo("Please follow the instructions in your browser to complete authentication.");try{je("gh auth login --web -h github.com",{stdio:"inherit"})}catch{throw new Error("GitHub CLI authentication failed")}}r.printInfo("Verifying GitHub Models access...");try{const e=je("gh auth token",{encoding:"utf8"}).trim();e&&(await jt([["GITHUB_MODELS.key",e]]),r.printSuccess("GitHub token stored for GitHub Models access"))}catch{r.printWarning("Could not extract token from GitHub CLI, but authentication completed")}r.printSuccess("GitHub authentication completed and GitHub Models access verified!"),r.printInfo("See usage guide: https://github.com/tak-bro/aicommit2/blob/main/docs/providers/github-models.md"),r.printInfo("Available models: gpt-4o-mini, gpt-4o, meta-llama-3.1-405b-instruct, etc."),r.printInfo("Using GitHub Models API: https://models.github.ai")}catch(e){throw e}}const Go="prepare-commit-msg",_o=`.git/hooks/${Go}`,ct=Cs(new URL("cli.mjs",import.meta.url)),Ic=process.argv[1].replace(/\\/g,"/").endsWith(`/${_o}`),jo=process.platform==="win32",Ho=`
187
187
  #!/usr/bin/env node
188
- import(${JSON.stringify(Cs(ct))})
189
- `.trim();var Mc=oe({name:"hook",parameters:["<install/uninstall>"],help:{description:"Install or uninstall the Git prepare-commit-msg hook",examples:["aic2 hook install","aic2 hook uninstall"]}},r=>{(async()=>{const e=await rr(),{installUninstall:t}=r._,o=x.join(e,Go),s=await uo(o);if(t==="install"){if(s){if(await R.realpath(o).catch(()=>{})===ct){console.warn("The hook is already installed");return}throw new b(`A different ${No} hook seems to be installed. Please remove it before installing aicommit2.`)}await R.mkdir(x.dirname(o),{recursive:!0}),_o?await R.writeFile(o,jo):(await R.symlink(ct,o,"file"),await R.chmod(o,493)),console.log(`${P.green("\u2714")} Hook installed`);return}if(t==="uninstall"){if(!s){console.warn("Hook is not installed");return}if(_o){if(await R.readFile(o,"utf8")!==jo){console.warn("Hook is not installed");return}}else if(await R.realpath(o)!==ct){console.warn("Hook is not installed");return}await R.rm(o),console.log(`${P.green("\u2714")} Hook uninstalled`);return}throw new b(`Invalid mode: ${t}`)})().catch(e=>{console.error(`${P.red("\u2716")} ${e.message}`),ie(e),process.exit(1)})});const Ic=ls(es),Rc=r=>{const e=["B","KB","MB","GB"];if(r===0)return"0 B";const t=Math.floor(Math.log(r)/Math.log(1024));return Math.round(r/Math.pow(1024,t)*100)/100+" "+e[t]},Oc=r=>r.toLocaleDateString()+" "+r.toLocaleTimeString(),Lc=async r=>{try{const e=await Sr(ee);if(e.length===0){console.log(`${P.yellow("No log files found.")}`);return}console.log(`${P.blue("Log files in")} ${ee}:
190
- `);const t=await Promise.all(e.map(async o=>{const s=ce.join(ee,o),n=await As(s);return{name:o,size:Rc(n.size),modified:Oc(n.mtime)}}));t.sort((o,s)=>new Date(s.modified).getTime()-new Date(o.modified).getTime()),t.forEach((o,s)=>{console.log(`${s===0?"\u{1F4C4}":" "} ${P.cyan(o.name)} ${P.gray(`(${o.size}, ${o.modified})`)}`)}),console.log(`
191
- ${P.green("Total:")} ${e.length} file${e.length!==1?"s":""}`)}catch(e){if(e.code==="ENOENT")console.log(`${P.yellow("Logs directory does not exist yet.")}`);else throw e}},Dc=async r=>{try{await Sr(ee);const e=process.platform;let t;switch(e){case"darwin":t=`open "${ee}"`;break;case"win32":t=`start "" "${ee}"`;break;default:t=`xdg-open "${ee}"`;break}await Ic(t),console.log(`${P.green("\u2714")} Opened logs directory in file manager`)}catch(e){e.code==="ENOENT"?console.log(`${P.yellow("Logs directory does not exist yet.")}`):r.printError(`Failed to open logs directory: ${e.message}`)}},Tc=async r=>{try{await Ms(ee,{recursive:!0,force:!0}),console.log(`${P.green("\u2714")} All log files removed!`)}catch(e){r.printError(`Failed to remove log files: ${e.message}`)}};var Fc=oe({name:"log",parameters:["<action>"],help:{description:"Manage log files generated by the application",examples:["aic2 log list # List all log files","aic2 log path # Show logs directory path","aic2 log open # Open logs directory","aic2 log removeAll # Remove all log files"]}},r=>{(async()=>{const{action:e}=r._,t=new re;switch(e){case"list":await Lc();break;case"path":console.log(`${P.blue("Logs directory:")} ${ee}`);break;case"open":await Dc(t);break;case"removeAll":await Tc(t);break;default:throw new b(`Invalid action: ${e}. Use 'list', 'path', 'open', or 'removeAll'`)}})().catch(e=>{new re().printError(e.message),ie(e),process.exit(1)})});const Nc=process.argv.slice(2).filter(r=>!r.startsWith("--pre-commit")),[lt,Ho]=Nc;var Gc=()=>(async()=>{if(!lt)throw new b('Commit message file path is missing. This file should be called from the "pre-commit framework"');if(Ho){console.log(`Skipping aicommit2 message generation for ${Ho} commit`);return}const r=await or();if(!r)return;const e=new re;e.printTitle();const t=await ue({});if(t.systemPromptPath)try{await R.readFile(x.resolve(t.systemPromptPath),"utf-8")}catch{throw new b(`Error reading system prompt file: ${t.systemPromptPath}`)}const o=Object.entries(t).filter(([u])=>ve.includes(u)).map(([u,h])=>[u,h]).filter(([u,h])=>!h.disabled).filter(([u,h])=>u==="OLLAMA"?!!h&&!!h.model&&h.model.length>0:u==="HUGGINGFACE"?!!h&&!!h.cookie:!!h.key&&h.key.length>0).map(([u])=>u);if(o.length===0)throw new b("Please set at least one API key via the `aicommit2 config set` command");const n=new at(t,r);let i;try{i=await vr(n.createCommitMsgRequests$(o).pipe(br(u=>!u.isError),M(u=>u.value),Cr()))}finally{e.printAnalyzed()}const a=await R.readFile(lt,"utf8")!=="",m=i.length>1;let d="";a&&(d=`# \u{1F916} Generated by aicommit2 (https://github.com/tak-bro/aicommit2)
188
+ import(${JSON.stringify(Ps(ct))})
189
+ `.trim();var Rc=oe({name:"hook",parameters:["<install/uninstall>"],help:{description:"Install or uninstall the Git prepare-commit-msg hook",examples:["aic2 hook install","aic2 hook uninstall"]}},r=>{(async()=>{const e=await or(),{installUninstall:t}=r._,o=A.join(e,_o),s=await uo(o);if(t==="install"){if(s){if(await O.realpath(o).catch(()=>{})===ct){console.warn("The hook is already installed");return}throw new v(`A different ${Go} hook seems to be installed. Please remove it before installing aicommit2.`)}await O.mkdir(A.dirname(o),{recursive:!0}),jo?await O.writeFile(o,Ho):(await O.symlink(ct,o,"file"),await O.chmod(o,493)),console.log(`${C.green("\u2714")} Hook installed`);return}if(t==="uninstall"){if(!s){console.warn("Hook is not installed");return}if(jo){if(await O.readFile(o,"utf8")!==Ho){console.warn("Hook is not installed");return}}else if(await O.realpath(o)!==ct){console.warn("Hook is not installed");return}await O.rm(o),console.log(`${C.green("\u2714")} Hook uninstalled`);return}throw new v(`Invalid mode: ${t}`)})().catch(e=>{console.error(`${C.red("\u2716")} ${e.message}`),ie(e),process.exit(1)})});const Oc=us(ts),Lc=r=>{const e=["B","KB","MB","GB"];if(r===0)return"0 B";const t=Math.floor(Math.log(r)/Math.log(1024));return Math.round(r/Math.pow(1024,t)*100)/100+" "+e[t]},Dc=r=>r.toLocaleDateString()+" "+r.toLocaleTimeString(),Tc=async r=>{try{const e=await Sr(ee);if(e.length===0){console.log(`${C.yellow("No log files found.")}`);return}console.log(`${C.blue("Log files in")} ${ee}:
190
+ `);const t=await Promise.all(e.map(async o=>{const s=ce.join(ee,o),n=await Ms(s);return{name:o,size:Lc(n.size),modified:Dc(n.mtime)}}));t.sort((o,s)=>new Date(s.modified).getTime()-new Date(o.modified).getTime()),t.forEach((o,s)=>{console.log(`${s===0?"\u{1F4C4}":" "} ${C.cyan(o.name)} ${C.gray(`(${o.size}, ${o.modified})`)}`)}),console.log(`
191
+ ${C.green("Total:")} ${e.length} file${e.length!==1?"s":""}`)}catch(e){if(e.code==="ENOENT")console.log(`${C.yellow("Logs directory does not exist yet.")}`);else throw e}},Fc=async r=>{try{await Sr(ee);const e=process.platform;let t;switch(e){case"darwin":t=`open "${ee}"`;break;case"win32":t=`start "" "${ee}"`;break;default:t=`xdg-open "${ee}"`;break}await Oc(t),console.log(`${C.green("\u2714")} Opened logs directory in file manager`)}catch(e){e.code==="ENOENT"?console.log(`${C.yellow("Logs directory does not exist yet.")}`):r.printError(`Failed to open logs directory: ${e.message}`)}},Nc=async r=>{try{await Is(ee,{recursive:!0,force:!0}),console.log(`${C.green("\u2714")} All log files removed!`)}catch(e){r.printError(`Failed to remove log files: ${e.message}`)}};var Gc=oe({name:"log",parameters:["<action>"],help:{description:"Manage log files generated by the application",examples:["aic2 log list # List all log files","aic2 log path # Show logs directory path","aic2 log open # Open logs directory","aic2 log removeAll # Remove all log files"]}},r=>{(async()=>{const{action:e}=r._,t=new re;switch(e){case"list":await Tc();break;case"path":console.log(`${C.blue("Logs directory:")} ${ee}`);break;case"open":await Fc(t);break;case"removeAll":await Nc(t);break;default:throw new v(`Invalid action: ${e}. Use 'list', 'path', 'open', or 'removeAll'`)}})().catch(e=>{new re().printError(e.message),ie(e),process.exit(1)})});const _c=process.argv.slice(2).filter(r=>!r.startsWith("--pre-commit")),[lt,Bo]=_c;var jc=(r=!1)=>(async()=>{if(!lt)throw new v('Commit message file path is missing. This file should be called from the "pre-commit framework"');if(Bo){console.log(`Skipping aicommit2 message generation for ${Bo} commit`);return}const e=await sr();if(!e)return;const t=new re;t.printTitle();const o={};r&&(o.logLevel="verbose");const s=await ue(o);if(s.systemPromptPath)try{await O.readFile(A.resolve(s.systemPromptPath),"utf-8")}catch{throw new v(`Error reading system prompt file: ${s.systemPromptPath}`)}const n=Object.entries(s).filter(([h])=>ve.includes(h)).map(([h,y])=>[h,y]).filter(([h,y])=>!y.disabled).filter(([h,y])=>h==="OLLAMA"?!!y&&!!y.model&&y.model.length>0:h==="HUGGINGFACE"?!!y&&!!y.cookie:!!y.key&&y.key.length>0).map(([h])=>h);if(n.length===0)throw new v("Please set at least one API key via the `aicommit2 config set` command");const c=new at(s,e);let a;try{a=await vr(c.createCommitMsgRequests$(n).pipe(br(h=>!h.isError),I(h=>h.value),Cr()))}finally{t.printAnalyzed()}const u=await O.readFile(lt,"utf8")!=="",l=a.length>1;let d="";u&&(d=`# \u{1F916} Generated by aicommit2 (https://github.com/tak-bro/aicommit2)
192
192
  `,d+=`# ----------------------------------------
193
193
  `,d+=`# How to use:
194
- `,m?(d+=`# 1. Remove the "#" from your chosen message
194
+ `,l?(d+=`# 1. Remove the "#" from your chosen message
195
195
  `,d+=`# 2. Edit the message if needed
196
196
  `,d+=`# 3. Save and close the editor
197
197
  `):(d+=`# 1. The message below will be used
198
198
  `,d+=`# 2. Edit the message if needed
199
199
  `,d+=`# 3. Save and close the editor
200
200
  `),d+=`# ----------------------------------------
201
- `),m?(a&&(d+=`
201
+ `),l?(u&&(d+=`
202
202
  # \u{1F4DD} Choose one of these messages:
203
203
  `),d+=`
204
- ${i.map(u=>`# ${u}`).join(`
205
- `)}`):(a&&(d+=`
204
+ ${a.map(h=>`# ${h}`).join(`
205
+ `)}`):(u&&(d+=`
206
206
  # \u{1F4DD} Generated commit message:
207
207
  `),d+=`
208
- ${i[0]}
209
- `);const l=await R.readFile(lt,"utf8"),p=d+`
210
- `+l;await R.writeFile(lt,p),e.printSavedCommitMessage()})().catch(r=>{new re().printError(r.message),ie(r),process.exit(1)});const ar=process.argv.slice(2),Bo=[];let cr=!1;for(let r=0;r<ar.length;r++){const e=ar[r];if(cr){cr=!1;continue}if(e!=="--hook-mode"){if(e.startsWith("-")){const t=ar[r+1];t&&!t.startsWith("-")&&(cr=!0);continue}Bo.push(e)}}const[ut,Uo]=Bo;var _c=(r,e,t,o,s,n)=>(async()=>{if(!ut)throw new b('Commit message file path is missing. This file should be called from the "prepare-commit-msg" git hook or with --hook-mode flag');if(Uo){console.log(`Skipping aicommit2 message generation for ${Uo} commit`);return}const i=await or();if(!i)return;const c=new re;c.printTitle();const a=await ue({locale:r?.toString(),generate:e?.toString(),type:o?.toString(),systemPrompt:s?.toString(),includeBody:n?.toString()},t);if(a.systemPromptPath)try{await R.readFile(x.resolve(a.systemPromptPath),"utf-8")}catch{throw new b(`Error reading system prompt file: ${a.systemPromptPath}`)}const m=Object.entries(a).filter(([$])=>ve.includes($)).map(([$,C])=>[$,C]).filter(([$,C])=>!C.disabled).filter(([$,C])=>$==="OLLAMA"?!!C&&!!C.model&&C.model.length>0:$==="HUGGINGFACE"?!!C&&!!C.cookie:!!C.key&&C.key.length>0).map(([$])=>$);if(m.length===0)throw new b("Please set at least one API key via the `aicommit2 config set` command");const l=new at(a,i),p=c.displaySpinner("The AI is analyzing your changes");let u;try{u=await vr(l.createCommitMsgRequests$(m).pipe(br($=>!$.isError),M($=>$.value),Cr()))}finally{p.stop(),p.clear(),c.printAnalyzed()}const g=await R.readFile(ut,"utf8")!=="",y=u.length>1,w=await hc();let v="";g&&(v=`${w} \u{1F916} Generated by aicommit2 (https://github.com/tak-bro/aicommit2)
211
- `,v+=`${w} ----------------------------------------
212
- `,v+=`${w} How to use:
213
- `,y?(v+=`${w} 1. Remove the "${w}" from your chosen message
214
- `,v+=`${w} 2. Edit the message if needed
215
- `,v+=`${w} 3. Save and close the editor
216
- `):(v+=`${w} 1. The message below will be used
217
- `,v+=`${w} 2. Edit the message if needed
218
- `,v+=`${w} 3. Save and close the editor
219
- `),v+=`${w} ----------------------------------------
220
- `),y?(g&&(v+=`
221
- ${w} \u{1F4DD} Choose one of these messages:
222
- `),v+=`
223
- ${u.map($=>`${w} ${$}`).join(`
224
- `)}`):(g&&(v+=`
225
- ${w} \u{1F4DD} Generated commit message:
226
- `),v+=`
227
- ${u[0]}
228
- `);const E=await R.readFile(ut,"utf8"),k=v+`
229
- `+E;await R.writeFile(ut,k),c.printSavedCommitMessage()})().catch(i=>{new re().printError(i.message),ie(i),process.exit(1)});class zo{constructor(e="SubscriptionManager"){this.destroyed$=new pt,this.subscriptions=new ft,this.isDestroyed=!1,this.name=e}add(e,t){if(this.isDestroyed){console.warn(`${this.name}: Cannot add subscription - manager is destroyed`);const s=new ft;return s.unsubscribe(),s}const o=e.pipe(Ar(this.destroyed$),Mr(()=>{process.env.NODE_ENV==="development"&&console.log(`${this.name}: Observable finalized`)})).subscribe({next:t?.next,error:s=>{console.error(`${this.name}: Observable error:`,s),t?.error?.(s)},complete:t?.complete});return this.subscriptions.add(o),o}pipe(e){return this.isDestroyed?(console.warn(`${this.name}: Cannot pipe - manager is destroyed`),e):e.pipe(Ar(this.destroyed$),Mr(()=>{process.env.NODE_ENV==="development"&&console.log(`${this.name}: Piped observable finalized`)}))}addSubscription(e){if(this.isDestroyed){console.warn(`${this.name}: Cannot add subscription - manager is destroyed`),e.unsubscribe();return}this.subscriptions.add(e)}get destroySignal$(){return this.destroyed$.asObservable()}get isActive(){return!this.isDestroyed}destroy(){this.isDestroyed||(this.isDestroyed=!0,this.subscriptions.unsubscribe(),this.destroyed$.next(),this.destroyed$.complete(),process.env.NODE_ENV==="development"&&console.log(`${this.name}: Destroyed successfully`))}}const jc=new zo("Global"),_e=()=>{jc.destroy()};process.on("exit",_e),process.on("SIGINT",_e),process.on("SIGTERM",_e),process.on("uncaughtException",r=>{console.error("Uncaught exception:",r),_e(),process.exit(1)}),process.on("unhandledRejection",(r,e)=>{console.error("Unhandled rejection at:",e,"reason:",r),_e(),process.exit(1)});class Hc{constructor(){this.destroyed$=new pt,this.consoleManager=new re,this.subscriptionManager=new zo,this.currentCodeReviewSubscription=null,this.currentCodeReviewPromptManager=null,this.watcher=null,this.lastCommitHash=null,this.isProcessingCommit=!1,this.REPO_PATH=process.cwd(),this.GIT_PATH=x.join(this.REPO_PATH,".git"),this.HEAD_PATH=x.join(this.GIT_PATH,"HEAD"),this.REFS_PATH=x.join(this.GIT_PATH,"refs","heads"),this.COMMIT_MSG_PATH=x.join(this.GIT_PATH,"COMMIT_EDITMSG"),this.setupProcessHandlers()}setupProcessHandlers(){const e=()=>{this.destroy(),process.exit(0)};process.on("SIGINT",e),process.on("SIGTERM",e),process.on("SIGQUIT",e)}async watch(e,t,o,s,n){this.consoleManager.printTitle(),await rr();const i=await this.initializeConfig(e,t,s,n);await this.initializeCurrentCommit();try{await this.watchGitEvents(i)}catch(c){return await this.handleWatchGitError(c),this.watch(e,t,o,s,n)}}async initializeConfig(e,t,o,s){const n=await ue({locale:e?.toString(),generate:t?.toString(),systemPrompt:o?.toString()},s);return await bo(n),this.getAvailableAIs(n).length===0&&(this.consoleManager.printError(`Please set at least one API key and watchMode via the config command:
208
+ ${a[0]}
209
+ `);const p=await O.readFile(lt,"utf8"),g=d+`
210
+ `+p;await O.writeFile(lt,g),t.printSavedCommitMessage()})().catch(e=>{new re().printError(e.message),ie(e),process.exit(1)});const cr=process.argv.slice(2),Uo=[];let lr=!1;for(let r=0;r<cr.length;r++){const e=cr[r];if(lr){lr=!1;continue}if(e!=="--hook-mode"){if(e.startsWith("-")){const t=cr[r+1];t&&!t.startsWith("-")&&(lr=!0);continue}Uo.push(e)}}const[ut,zo]=Uo;var Hc=(r,e,t,o,s,n,i)=>(async()=>{if(!ut)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(zo){console.log(`Skipping aicommit2 message generation for ${zo} commit`);return}const c=await sr();if(!c)return;const a=new re;a.printTitle();const m={locale:r?.toString(),generate:e?.toString(),type:o?.toString(),systemPrompt:s?.toString(),includeBody:n?.toString()};i&&(m.logLevel="verbose");const u=await ue(m,t);if(u.systemPromptPath)try{await O.readFile(A.resolve(u.systemPromptPath),"utf-8")}catch{throw new v(`Error reading system prompt file: ${u.systemPromptPath}`)}const l=Object.entries(u).filter(([x])=>ve.includes(x)).map(([x,E])=>[x,E]).filter(([x,E])=>!E.disabled).filter(([x,E])=>x==="OLLAMA"?!!E&&!!E.model&&E.model.length>0:x==="HUGGINGFACE"?!!E&&!!E.cookie:!!E.key&&E.key.length>0).map(([x])=>x);if(l.length===0)throw new v("Please set at least one API key via the `aicommit2 config set` command");const p=new at(u,c),g=a.displaySpinner("The AI is analyzing your changes");let h;try{h=await vr(p.createCommitMsgRequests$(l).pipe(br(x=>!x.isError),I(x=>x.value),Cr()))}finally{g.stop(),g.clear(),a.printAnalyzed()}const w=await O.readFile(ut,"utf8")!=="",b=h.length>1,P=await yc();let S="";w&&(S=`${P} \u{1F916} Generated by aicommit2 (https://github.com/tak-bro/aicommit2)
211
+ `,S+=`${P} ----------------------------------------
212
+ `,S+=`${P} How to use:
213
+ `,b?(S+=`${P} 1. Remove the "${P}" from your chosen message
214
+ `,S+=`${P} 2. Edit the message if needed
215
+ `,S+=`${P} 3. Save and close the editor
216
+ `):(S+=`${P} 1. The message below will be used
217
+ `,S+=`${P} 2. Edit the message if needed
218
+ `,S+=`${P} 3. Save and close the editor
219
+ `),S+=`${P} ----------------------------------------
220
+ `),b?(w&&(S+=`
221
+ ${P} \u{1F4DD} Choose one of these messages:
222
+ `),S+=`
223
+ ${h.map(x=>`${P} ${x}`).join(`
224
+ `)}`):(w&&(S+=`
225
+ ${P} \u{1F4DD} Generated commit message:
226
+ `),S+=`
227
+ ${h[0]}
228
+ `);const k=await O.readFile(ut,"utf8"),$=S+`
229
+ `+k;await O.writeFile(ut,$),a.printSavedCommitMessage()})().catch(c=>{new re().printError(c.message),ie(c),process.exit(1)});class Wo{constructor(e="SubscriptionManager"){this.destroyed$=new ht,this.subscriptions=new pt,this.isDestroyed=!1,this.name=e}add(e,t){if(this.isDestroyed){console.warn(`${this.name}: Cannot add subscription - manager is destroyed`);const s=new pt;return s.unsubscribe(),s}const o=e.pipe(Ar(this.destroyed$),Mr(()=>{process.env.NODE_ENV==="development"&&console.log(`${this.name}: Observable finalized`)})).subscribe({next:t?.next,error:s=>{console.error(`${this.name}: Observable error:`,s),t?.error?.(s)},complete:t?.complete});return this.subscriptions.add(o),o}pipe(e){return this.isDestroyed?(console.warn(`${this.name}: Cannot pipe - manager is destroyed`),e):e.pipe(Ar(this.destroyed$),Mr(()=>{process.env.NODE_ENV==="development"&&console.log(`${this.name}: Piped observable finalized`)}))}addSubscription(e){if(this.isDestroyed){console.warn(`${this.name}: Cannot add subscription - manager is destroyed`),e.unsubscribe();return}this.subscriptions.add(e)}get destroySignal$(){return this.destroyed$.asObservable()}get isActive(){return!this.isDestroyed}destroy(){this.isDestroyed||(this.isDestroyed=!0,this.subscriptions.unsubscribe(),this.destroyed$.next(),this.destroyed$.complete(),process.env.NODE_ENV==="development"&&console.log(`${this.name}: Destroyed successfully`))}}const Bc=new Wo("Global"),_e=()=>{Bc.destroy()};process.on("exit",_e),process.on("SIGINT",_e),process.on("SIGTERM",_e),process.on("uncaughtException",r=>{console.error("Uncaught exception:",r),_e(),process.exit(1)}),process.on("unhandledRejection",(r,e)=>{console.error("Unhandled rejection at:",e,"reason:",r),_e(),process.exit(1)});class Uc{constructor(){this.destroyed$=new ht,this.consoleManager=new re,this.subscriptionManager=new Wo,this.currentCodeReviewSubscription=null,this.currentCodeReviewPromptManager=null,this.watcher=null,this.lastCommitHash=null,this.isProcessingCommit=!1,this.REPO_PATH=process.cwd(),this.GIT_PATH=A.join(this.REPO_PATH,".git"),this.HEAD_PATH=A.join(this.GIT_PATH,"HEAD"),this.REFS_PATH=A.join(this.GIT_PATH,"refs","heads"),this.COMMIT_MSG_PATH=A.join(this.GIT_PATH,"COMMIT_EDITMSG"),this.setupProcessHandlers()}setupProcessHandlers(){const e=()=>{this.destroy(),process.exit(0)};process.on("SIGINT",e),process.on("SIGTERM",e),process.on("SIGQUIT",e)}async watch(e,t,o,s,n,i){this.consoleManager.printTitle(),await or();const c=await this.initializeConfig(e,t,s,n,i);await this.initializeCurrentCommit();try{await this.watchGitEvents(c)}catch(a){return await this.handleWatchGitError(a),this.watch(e,t,o,s,n,i)}}async initializeConfig(e,t,o,s,n){const i={locale:e?.toString(),generate:t?.toString(),systemPrompt:o?.toString()};s&&(i.logLevel="verbose");const c=await ue(i,n);return await Co(c),this.getAvailableAIs(c).length===0&&(this.consoleManager.printError(`Please set at least one API key and watchMode via the config command:
230
230
  aicommit2 config set [MODEL].key="YOUR_API_KEY"
231
- aicommit2 config set [MODEL].watchMode="true"`),process.exit()),n}async handleWatchGitError(e){this.consoleManager.printError(`An error occurred: ${e.message}`),ie(e),await new Promise(t=>setTimeout(t,3e3)),this.consoleManager.printWarning("Restarting the commit monitoring process...")}async initializeCurrentCommit(){try{const e=await this.executeGitCommand("git rev-parse HEAD");this.lastCommitHash=e.trim(),this.consoleManager.printInfo(`Starting watch from commit: ${this.lastCommitHash.substring(0,8)}`)}catch{this.consoleManager.printWarning("No commits found in repository"),this.lastCommitHash=null}}async executeGitCommand(e){const t=as(rs),{stdout:o}=await t(e,{cwd:this.REPO_PATH});return o}getAvailableAIs(e){return Object.entries(e).filter(([t,o])=>ve.includes(t)||o.compatible===!0).map(([t,o])=>[t,o]).filter(([t,o])=>!o.disabled).filter(([t,o])=>this.isAIAvailable(t,o,e)).map(([t])=>t)}isAIAvailable(e,t,o){const s=o.watchMode||t.watchMode;return e==="OLLAMA"?!!t&&!!t.model&&t.model.length>0&&s:e==="HUGGINGFACE"?!!t&&!!t.cookie&&s:t.compatible?!!t.url&&!!t.key&&s:!!t.key&&t.key.length>0&&s}clearTerminal(){process.stdout.write("\x1Bc")}async handleCommitEvent(e,t){try{const o=await pc(t);if(!o){this.consoleManager.printWarning("No changes found in this commit");return}this.consoleManager.stopLoader(),this.consoleManager.printStagedFiles(o);const s=this.getAvailableAIs(e);if(s.length===0){this.consoleManager.printError(`Please set at least one API key and watchMode via the config command:
231
+ aicommit2 config set [MODEL].watchMode="true"`),process.exit()),c}async handleWatchGitError(e){this.consoleManager.printError(`An error occurred: ${e.message}`),ie(e),await new Promise(t=>setTimeout(t,3e3)),this.consoleManager.printWarning("Restarting the commit monitoring process...")}async initializeCurrentCommit(){try{const e=await this.executeGitCommand("git rev-parse HEAD");this.lastCommitHash=e.trim(),this.consoleManager.printInfo(`Starting watch from commit: ${this.lastCommitHash.substring(0,8)}`)}catch{this.consoleManager.printWarning("No commits found in repository"),this.lastCommitHash=null}}async executeGitCommand(e){const t=cs(os),{stdout:o}=await t(e,{cwd:this.REPO_PATH});return o}getAvailableAIs(e){return Object.entries(e).filter(([t,o])=>ve.includes(t)||o.compatible===!0).map(([t,o])=>[t,o]).filter(([t,o])=>!o.disabled).filter(([t,o])=>this.isAIAvailable(t,o,e)).map(([t])=>t)}isAIAvailable(e,t,o){const s=o.watchMode||t.watchMode;return e==="OLLAMA"?!!t&&!!t.model&&t.model.length>0&&s:e==="HUGGINGFACE"?!!t&&!!t.cookie&&s:t.compatible?!!t.url&&!!t.key&&s:!!t.key&&t.key.length>0&&s}clearTerminal(){process.stdout.write("\x1Bc")}async handleCommitEvent(e,t){try{const o=await gc(t);if(!o){this.consoleManager.printWarning("No changes found in this commit");return}this.consoleManager.stopLoader(),this.consoleManager.printStagedFiles(o);const s=this.getAvailableAIs(e);if(s.length===0){this.consoleManager.printError(`Please set at least one API key and watchMode via the config command:
232
232
  aicommit2 config set [MODEL].key="YOUR_API_KEY"
233
- aicommit2 config set [MODEL].watchMode="true"`),process.exit();return}await this.performCodeReview(e,o,s)}catch(o){this.consoleManager.printError(`Error processing commit ${t}: ${o.message}`)}}async performCodeReview(e,t,o){this.cleanupPreviousCodeReview();const s=new at(e,t);this.currentCodeReviewPromptManager=new ir(Lo);try{const n=this.initializeCodeReviewInquirer();this.currentCodeReviewPromptManager.startLoader(),this.currentCodeReviewSubscription=this.subscribeToCodeReviewRequests(s,o),await n}finally{this.cleanupCodeReview()}}cleanupPreviousCodeReview(){this.cleanupCurrentReviewResources(),this.destroyed$.closed||(this.destroyed$.next(),this.destroyed$.complete()),this.destroyed$=new pt}initializeCodeReviewInquirer(){return this.currentCodeReviewPromptManager.initPrompt({...nr,name:"codeReviewPrompt",message:"Please check code reviews: ",emptyMessage:`\u26A0 ${Do}`,isDescriptionDim:!1,stopMessage:"Code review completed",descPageSize:20})}subscribeToCodeReviewRequests(e,t){return this.subscriptionManager.add(e.createCodeReviewRequests$(t),{next:o=>{this.currentCodeReviewPromptManager?.refreshChoices(o)},error:o=>{console.error("Code review request error:",o),this.currentCodeReviewPromptManager?.checkErrorOnChoices(!1)},complete:()=>{this.currentCodeReviewPromptManager?.checkErrorOnChoices(!1)}})}cleanupCurrentReviewResources(){this.currentCodeReviewSubscription&&(this.currentCodeReviewSubscription.unsubscribe(),this.currentCodeReviewSubscription=null),this.currentCodeReviewPromptManager&&(this.currentCodeReviewPromptManager.destroy(),this.currentCodeReviewPromptManager=null)}cleanupCodeReview(){this.cleanupCurrentReviewResources(),this.clearTerminal(),this.consoleManager.showLoader("Watching for new Git commits...")}async isGitReset(e){if(!this.lastCommitHash)return!1;try{const t=await this.executeGitCommand(`git merge-base --is-ancestor ${e} ${this.lastCommitHash}`);return!0}catch{return!1}}cancelCurrentReview(){this.currentCodeReviewPromptManager&&this.currentCodeReviewPromptManager.cancel(),this.cleanupCurrentReviewResources(),this.destroyed$.next()}async watchGitEvents(e){this.consoleManager.showLoader("Watching for new Git commits...");const o=[this.HEAD_PATH,this.REFS_PATH,this.COMMIT_MSG_PATH,x.join(this.GIT_PATH,"logs","HEAD")].filter(s=>{try{return U.accessSync(s),!0}catch{return!1}});this.watcher=Is.watch(o,{persistent:!0,ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:500,pollInterval:100}}),this.watcher.on("change",async s=>{await this.handleGitChange(e,s)}),this.watcher.on("add",async s=>{await this.handleGitChange(e,s)}),this.watcher.on("error",s=>{this.consoleManager.printError(`Watcher error: ${s.message}`),setTimeout(()=>this.watchGitEvents(e),1e3)})}async handleGitChange(e,t){try{const s=(await this.executeGitCommand("git rev-parse HEAD")).trim();if(s!==this.lastCommitHash){if(await this.isGitReset(s)){this.clearTerminal(),this.consoleManager.printInfo(`\u21A9\uFE0F Git reset detected: ${s.substring(0,8)}`),this.lastCommitHash=s,this.isProcessingCommit&&(this.cancelCurrentReview(),this.isProcessingCommit=!1);return}if(this.isProcessingCommit){this.consoleManager.printInfo(`
233
+ aicommit2 config set [MODEL].watchMode="true"`),process.exit();return}await this.performCodeReview(e,o,s)}catch(o){this.consoleManager.printError(`Error processing commit ${t}: ${o.message}`)}}async performCodeReview(e,t,o){this.cleanupPreviousCodeReview();const s=new at(e,t);this.currentCodeReviewPromptManager=new ar(Do);try{const n=this.initializeCodeReviewInquirer();this.currentCodeReviewPromptManager.startLoader(),this.currentCodeReviewSubscription=this.subscribeToCodeReviewRequests(s,o),await n}finally{this.cleanupCodeReview()}}cleanupPreviousCodeReview(){this.cleanupCurrentReviewResources(),this.destroyed$.closed||(this.destroyed$.next(),this.destroyed$.complete()),this.destroyed$=new ht}initializeCodeReviewInquirer(){return this.currentCodeReviewPromptManager.initPrompt({...ir,name:"codeReviewPrompt",message:"Please check code reviews: ",emptyMessage:`\u26A0 ${To}`,isDescriptionDim:!1,stopMessage:"Code review completed",descPageSize:20})}subscribeToCodeReviewRequests(e,t){return this.subscriptionManager.add(e.createCodeReviewRequests$(t),{next:o=>{this.currentCodeReviewPromptManager?.refreshChoices(o)},error:o=>{console.error("Code review request error:",o),this.currentCodeReviewPromptManager?.checkErrorOnChoices(!1)},complete:()=>{this.currentCodeReviewPromptManager?.checkErrorOnChoices(!1)}})}cleanupCurrentReviewResources(){this.currentCodeReviewSubscription&&(this.currentCodeReviewSubscription.unsubscribe(),this.currentCodeReviewSubscription=null),this.currentCodeReviewPromptManager&&(this.currentCodeReviewPromptManager.destroy(),this.currentCodeReviewPromptManager=null)}cleanupCodeReview(){this.cleanupCurrentReviewResources(),this.clearTerminal(),this.consoleManager.showLoader("Watching for new Git commits...")}async isGitReset(e){if(!this.lastCommitHash)return!1;try{const t=await this.executeGitCommand(`git merge-base --is-ancestor ${e} ${this.lastCommitHash}`);return!0}catch{return!1}}cancelCurrentReview(){this.currentCodeReviewPromptManager&&this.currentCodeReviewPromptManager.cancel(),this.cleanupCurrentReviewResources(),this.destroyed$.next()}async watchGitEvents(e){this.consoleManager.showLoader("Watching for new Git commits...");const o=[this.HEAD_PATH,this.REFS_PATH,this.COMMIT_MSG_PATH,A.join(this.GIT_PATH,"logs","HEAD")].filter(s=>{try{return U.accessSync(s),!0}catch{return!1}});this.watcher=Rs.watch(o,{persistent:!0,ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:500,pollInterval:100}}),this.watcher.on("change",async s=>{await this.handleGitChange(e,s)}),this.watcher.on("add",async s=>{await this.handleGitChange(e,s)}),this.watcher.on("error",s=>{this.consoleManager.printError(`Watcher error: ${s.message}`),setTimeout(()=>this.watchGitEvents(e),1e3)})}async handleGitChange(e,t){try{const s=(await this.executeGitCommand("git rev-parse HEAD")).trim();if(s!==this.lastCommitHash){if(await this.isGitReset(s)){this.clearTerminal(),this.consoleManager.printInfo(`\u21A9\uFE0F Git reset detected: ${s.substring(0,8)}`),this.lastCommitHash=s,this.isProcessingCommit&&(this.cancelCurrentReview(),this.isProcessingCommit=!1);return}if(this.isProcessingCommit){this.consoleManager.printInfo(`
234
234
  \u{1F504} New commit detected, cancelling current review...`);try{this.cancelCurrentReview(),await new Promise(i=>setTimeout(i,200))}catch(i){console.warn("Error during review cancellation:",i)}}this.isProcessingCommit=!0;try{this.consoleManager.stopLoader(),this.consoleManager.printInfo(`
235
- \u{1F50D} New commit detected: ${s.substring(0,8)}`);const i=this.lastCommitHash;this.lastCommitHash=s,this.clearTerminal(),await this.handleCommitEvent(e,s)}catch(i){this.consoleManager.printError(`Error processing commit ${s.substring(0,8)}: ${i.message}`)}finally{this.isProcessingCommit=!1}}}catch(o){this.isProcessingCommit=!1,o.message?.includes("fatal: not a git repository")||this.consoleManager.printError(`Error checking for new commits: ${o.message}`)}}destroy(){this.isProcessingCommit=!1,this.lastCommitHash=null;try{this.subscriptionManager.destroy(),this.cleanupCurrentReviewResources(),this.watcher&&(this.watcher.close(),this.watcher=null),this.consoleManager.stopLoader(),this.destroyed$.next(),this.destroyed$.complete()}catch(e){console.warn("Error during WatchGitManager destruction:",e)}}}const Bc=new Hc,Uc=async(r,e,t,o,s)=>Bc.watch(r,e,t,o,s),lr=process.argv.slice(2),{version:Wo,description:zc}=Ws;qo({name:"aicommit2",version:Wo,flags:{locale:{type:String,description:"Locale to use for the generated commit messages (default: en)",alias:"l"},generate:{type:Number,description:"Number of messages to generate (Warning: generating multiple costs more) (default: 1)",alias:"g"},exclude:{type:[String],description:"Files to exclude from AI analysis",alias:"x"},all:{type:Boolean,description:"Automatically stage changes in tracked files for the commit",alias:"a",default:!1},type:{type:String,description:"Type of commit message to generate (default: conventional)",alias:"t"},confirm:{type:Boolean,description:"Skip confirmation when committing after message generation (default: false)",alias:"y",default:!1},clipboard:{type:Boolean,description:"Copy the selected message to the clipboard",alias:"c",default:!1},prompt:{type:String,description:"Custom prompt to let users fine-tune provided prompt",alias:"p"},"watch-commit":{type:Boolean,default:!1},"hook-mode":{type:Boolean,description:"Run in git hook mode, allowing chaining with other hooks",default:!1},"pre-commit":{type:Boolean,description:"Run in pre-commit Framework, allowing chaining with other hooks",default:!1},"include-body":{type:Boolean,description:"Force include commit body in all generated messages",alias:"i",default:!1},"auto-select":{type:Boolean,description:"Automatically select the message when only one is generated",alias:"s",default:!1},edit:{type:Boolean,description:"Open the AI-generated commit message in your default editor",alias:"e",default:!1},"disable-lowercase":{type:Boolean,description:"Disable automatic lowercase conversion of commit messages",default:!1}},commands:[Ec,xc,Mc,Fc],help:{description:zc},ignoreArgv:r=>r==="unknown-flag"||r==="argument"},async r=>{const e=await ue({});if(await ya(e),Ce.info(`aicommit2 version: ${Wo}`),r.flags["pre-commit"]){Gc();return}if(r.flags["hook-mode"]||Ac){_c(r.flags.locale,r.flags.generate,r.flags.exclude,r.flags.type,r.flags.prompt,r.flags["include-body"]);return}if(r.flags["watch-commit"]){Uc(r.flags.locale,r.flags.generate,r.flags.exclude,r.flags.prompt,lr);return}bc(r.flags.locale,r.flags.generate,r.flags.exclude,r.flags.all,r.flags.type,r.flags.confirm,r.flags.clipboard,r.flags.prompt,r.flags["include-body"],r.flags["auto-select"],r.flags.edit,r.flags["disable-lowercase"],lr)},lr);
235
+ \u{1F50D} New commit detected: ${s.substring(0,8)}`);const i=this.lastCommitHash;this.lastCommitHash=s,this.clearTerminal(),await this.handleCommitEvent(e,s)}catch(i){this.consoleManager.printError(`Error processing commit ${s.substring(0,8)}: ${i.message}`)}finally{this.isProcessingCommit=!1}}}catch(o){this.isProcessingCommit=!1,o.message?.includes("fatal: not a git repository")||this.consoleManager.printError(`Error checking for new commits: ${o.message}`)}}destroy(){this.isProcessingCommit=!1,this.lastCommitHash=null;try{this.subscriptionManager.destroy(),this.cleanupCurrentReviewResources(),this.watcher&&(this.watcher.close(),this.watcher=null),this.consoleManager.stopLoader(),this.destroyed$.next(),this.destroyed$.complete()}catch(e){console.warn("Error during WatchGitManager destruction:",e)}}}const zc=new Uc,Wc=async(r,e,t,o,s,n)=>zc.watch(r,e,t,o,s,n),dt=process.argv.slice(2),{version:Ko,description:Kc}=Ks;Xo({name:"aicommit2",version:Ko,flags:{locale:{type:String,description:"Locale to use for the generated commit messages (default: en)",alias:"l"},generate:{type:Number,description:"Number of messages to generate (Warning: generating multiple costs more) (default: 1)",alias:"g"},exclude:{type:[String],description:"Files to exclude from AI analysis",alias:"x"},all:{type:Boolean,description:"Automatically stage changes in tracked files for the commit",alias:"a",default:!1},type:{type:String,description:"Type of commit message to generate (default: conventional)",alias:"t"},confirm:{type:Boolean,description:"Skip confirmation when committing after message generation (default: false)",alias:"y",default:!1},clipboard:{type:Boolean,description:"Copy the selected message to the clipboard",alias:"c",default:!1},prompt:{type:String,description:"Custom prompt to let users fine-tune provided prompt",alias:"p"},"watch-commit":{type:Boolean,default:!1},"hook-mode":{type:Boolean,description:"Run in git hook mode, allowing chaining with other hooks",default:!1},"pre-commit":{type:Boolean,description:"Run in pre-commit Framework, allowing chaining with other hooks",default:!1},"include-body":{type:Boolean,description:"Force include commit body in all generated messages",alias:"i",default:!1},"auto-select":{type:Boolean,description:"Automatically select the message when only one is generated",alias:"s",default:!1},edit:{type:Boolean,description:"Open the AI-generated commit message in your default editor",alias:"e",default:!1},"disable-lowercase":{type:Boolean,description:"Disable automatic lowercase conversion of commit messages",default:!1},verbose:{type:Boolean,description:"Enable verbose logging for this run",alias:"v",default:!1}},commands:[kc,Sc,Rc,Gc],help:{description:Kc},ignoreArgv:r=>r==="unknown-flag"||r==="argument"},async r=>{const e={};r.flags.verbose&&(e.logLevel="verbose");const t=await ue(e,dt);if(await wa(t),Ce.info(`aicommit2 version: ${Ko}`),r.flags["pre-commit"]){jc(r.flags.verbose);return}if(r.flags["hook-mode"]||Ic){Hc(r.flags.locale,r.flags.generate,r.flags.exclude,r.flags.type,r.flags.prompt,r.flags["include-body"],r.flags.verbose);return}if(r.flags["watch-commit"]){Wc(r.flags.locale,r.flags.generate,r.flags.exclude,r.flags.prompt,r.flags.verbose,dt);return}Pc(r.flags.locale,r.flags.generate,r.flags.exclude,r.flags.all,r.flags.type,r.flags.confirm,r.flags.clipboard,r.flags.prompt,r.flags["include-body"],r.flags["auto-select"],r.flags.edit,r.flags["disable-lowercase"],r.flags.verbose,dt)},dt);