aicommit2 2.3.4 → 2.3.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +3 -0
  2. package/dist/cli.mjs +26 -26
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -56,6 +56,7 @@ _aicommit2_ is a reactive CLI tool that automatically generates Git commit messa
56
56
  - [Groq](docs/providers/groq.md)
57
57
  - [Perplexity](docs/providers/perplexity.md)
58
58
  - [DeepSeek](docs/providers/deepseek.md)
59
+ - [GitHub Models](docs/providers/github-models.md)
59
60
  - [OpenAI API Compatibility](docs/providers/compatible.md)
60
61
 
61
62
  ### Local AI Services
@@ -647,6 +648,7 @@ aicommit2 config set codeReviewPromptPath="/path/to/user/prompt.txt"
647
648
  | **Groq** | ✓ | ✓ | ✓ | ✓ |
648
649
  | **Perplexity** | ✓ | ✓ | ✓ | ✓ |
649
650
  | **DeepSeek** | ✓ | ✓ | ✓ | ✓ |
651
+ | **Github Models** | ✓ | ✓ | ✓ | ✓ |
650
652
  | **Ollama** | ✓ | ✓ | | ✓ |
651
653
  | **OpenAI API-Compatible** | ✓ | ✓ | ✓ | ✓ |
652
654
 
@@ -678,6 +680,7 @@ aicommit2 config set \
678
680
  > - [Groq](docs/providers/groq.md)
679
681
  > - [Perplexity](docs/providers/perplexity.md)
680
682
  > - [DeepSeek](docs/providers/deepseek.md)
683
+ > - [GitHub Models](docs/providers/github-models.md)
681
684
  > - [OpenAI API Compatibility](docs/providers/compatible.md)
682
685
  > - [Ollama](docs/providers/ollama.md)
683
686
 
package/dist/cli.mjs CHANGED
@@ -1,17 +1,17 @@
1
1
  #!/usr/bin/env node
2
- import{command as ie,cli as ln}from"cleye";import{createRequire as un}from"module";import{Buffer as dn}from"node:buffer";import ue from"node:path";import mr,{ChildProcess as mn,exec as fn}from"node:child_process";import ae from"node:process";import pn,{execSync as je}from"child_process";import S from"path";import oe from"fs";import{fileURLToPath as fr}from"node:url";import hn,{constants as pr}from"node:os";import hr from"assert";import gr from"events";import{createWriteStream as gn,createReadStream as yn}from"node:fs";import wn from"buffer";import gt from"stream";import yr from"util";import{debuglog as vn,promisify as bn}from"node:util";import Be from"inquirer";import yt from"ora";import C from"chalk";import{of as Ae,concatMap as L,from as I,map as M,catchError as R,mergeMap as Ue,BehaviorSubject as wr,ReplaySubject as Cn,lastValueFrom as vr,filter as br,toArray as Cr,Subject as Pr}from"rxjs";import Pn from"@anthropic-ai/sdk";import{fromPromise as N}from"rxjs/internal/observable/innerFrom";import{xxh64 as $r}from"@pacote/xxhash";import U from"winston";import O from"fs/promises";import ze from"os";import"winston-daily-rotate-file";import $n from"axios";import{CohereClient as En}from"cohere-ai";import Er from"openai";import{GoogleGenerativeAI as kn,HarmCategory as Ke,HarmBlockThreshold as We}from"@google/generative-ai";import An from"groq-sdk";import{Ollama as xn}from"ollama";import{fetch as Sn,Agent as In}from"undici";import Mn from"http";import Rn from"https";import On from"net";import Ln from"tls";import Nn,{fileURLToPath as Tn,pathToFileURL as Dn}from"url";import kr from"tty";import Ye from"readline";import _n from"figlet";import Fn from"inquirer-reactive-list-prompt";import{readdir as Ar,stat as Gn,rm as Hn}from"node:fs/promises";import jn from"chokidar";import{takeUntil as Bn}from"rxjs/operators";var Un="aicommit2",xr="2.3.4",zn="A Reactive CLI that generates git commit messages with various AI",Kn=["cli","ai","git","commit","git-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"],Wn="MIT",Yn="tak-bro/aicommit2",qn="Hyungtak Jin(@tak-bro)",Jn="module",Vn=["dist"],Xn={aicommit2:"./dist/cli.mjs",aic2:"./dist/cli.mjs"},Qn={prepare:"simple-git-hooks",build:"pkgroll --minify",lint:"eslint --cache .","type-check":"tsc",test:"tsx tests",prepack:"pnpm build && clean-pkg-json",prettier:"prettier"},Zn={"@anthropic-ai/sdk":"^0.39.0","@dqbd/tiktoken":"^1.0.21","@google/generative-ai":"^0.24.1","@inquirer/prompts":"^3.3.2","@pacote/xxhash":"^0.3.2","@types/winston":"^2.4.4",axios:"^1.9.0",chalk:"^5.4.1",chokidar:"^4.0.3",cleye:"^1.3.4","cohere-ai":"^7.17.1","copy-paste":"^1.5.3",figlet:"^1.8.1","formdata-node":"^6.0.3","groq-sdk":"^0.7.0",inquirer:"9.2.8","inquirer-reactive-list-prompt":"^1.0.15",ollama:"^0.5.15",openai:"^5.0.1",ora:"^8.2.0",readline:"^1.3.0",rxjs:"^7.8.2",undici:"^7.10.0",uuid:"^9.0.1",winston:"^3.17.0","winston-daily-rotate-file":"^5.0.0"},es={"@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"},ts={extends:["@pvtnbr","prettier"],rules:{"unicorn/no-process-exit":"off"},overrides:[{files:"./src/commands/prepare-commit-msg-hook.ts",rules:{"unicorn/prevent-abbreviations":"off"}}]},rs={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"]},os={name:Un,version:xr,description:zn,keywords:Kn,license:Wn,repository:Yn,author:qn,type:Jn,files:Vn,bin:Xn,scripts:Qn,"simple-git-hooks":{"pre-commit":"pnpm lint-staged"},"lint-staged":{"*.ts":["prettier --config ./.prettierrc --write","eslint --fix"]},dependencies:Zn,devDependencies:es,eslintConfig:ts,release:rs},ns=un(import.meta.url),F=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function fe(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var pe={exports:{}},wt,Sr;function ss(){if(Sr)return wt;Sr=1,wt=o,o.sync=s;var t=oe;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 l=0;l<c.length;l++){var u=c[l].toLowerCase();if(u&&n.substr(-u.length).toLowerCase()===u)return!0}return!1}function r(n,i,c){return!n.isSymbolicLink()&&!n.isFile()?!1:e(i,c)}function o(n,i,c){t.stat(n,function(l,u){c(l,l?!1:r(u,n,i))})}function s(n,i){return r(t.statSync(n),n,i)}return wt}var vt,Ir;function is(){if(Ir)return vt;Ir=1,vt=e,e.sync=r;var t=oe;function e(n,i,c){t.stat(n,function(l,u){c(l,l?!1:o(u,i))})}function r(n,i){return o(t.statSync(n),i)}function o(n,i){return n.isFile()&&s(n,i)}function s(n,i){var c=n.mode,l=n.uid,u=n.gid,m=i.uid!==void 0?i.uid:process.getuid&&process.getuid(),a=i.gid!==void 0?i.gid:process.getgid&&process.getgid(),d=parseInt("100",8),f=parseInt("010",8),h=parseInt("001",8),g=d|f,y=c&h||c&f&&u===a||c&d&&l===m||c&g&&m===0;return y}return vt}var qe;process.platform==="win32"||F.TESTING_WINDOWS?qe=ss():qe=is();var as=bt;bt.sync=cs;function bt(t,e,r){if(typeof e=="function"&&(r=e,e={}),!r){if(typeof Promise!="function")throw new TypeError("callback not provided");return new Promise(function(o,s){bt(t,e||{},function(n,i){n?s(n):o(i)})})}qe(t,e||{},function(o,s){o&&(o.code==="EACCES"||e&&e.ignoreErrors)&&(o=null,s=!1),r(o,s)})}function cs(t,e){try{return qe.sync(t,e||{})}catch(r){if(e&&e.ignoreErrors||r.code==="EACCES")return!1;throw r}}const he=process.platform==="win32"||process.env.OSTYPE==="cygwin"||process.env.OSTYPE==="msys",Mr=S,ls=he?";":":",Rr=as,Or=t=>Object.assign(new Error(`not found: ${t}`),{code:"ENOENT"}),Lr=(t,e)=>{const r=e.colon||ls,o=t.match(/\//)||he&&t.match(/\\/)?[""]:[...he?[process.cwd()]:[],...(e.path||process.env.PATH||"").split(r)],s=he?e.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",n=he?s.split(r):[""];return he&&t.indexOf(".")!==-1&&n[0]!==""&&n.unshift(""),{pathEnv:o,pathExt:n,pathExtExe:s}},Nr=(t,e,r)=>{typeof e=="function"&&(r=e,e={}),e||(e={});const{pathEnv:o,pathExt:s,pathExtExe:n}=Lr(t,e),i=[],c=u=>new Promise((m,a)=>{if(u===o.length)return e.all&&i.length?m(i):a(Or(t));const d=o[u],f=/^".*"$/.test(d)?d.slice(1,-1):d,h=Mr.join(f,t),g=!f&&/^\.[\\\/]/.test(t)?t.slice(0,2)+h:h;m(l(g,u,0))}),l=(u,m,a)=>new Promise((d,f)=>{if(a===s.length)return d(c(m+1));const h=s[a];Rr(u+h,{pathExt:n},(g,y)=>{if(!g&&y)if(e.all)i.push(u+h);else return d(u+h);return d(l(u,m,a+1))})});return r?c(0).then(u=>r(null,u),r):c(0)},us=(t,e)=>{e=e||{};const{pathEnv:r,pathExt:o,pathExtExe:s}=Lr(t,e),n=[];for(let i=0;i<r.length;i++){const c=r[i],l=/^".*"$/.test(c)?c.slice(1,-1):c,u=Mr.join(l,t),m=!l&&/^\.[\\\/]/.test(t)?t.slice(0,2)+u:u;for(let a=0;a<o.length;a++){const d=m+o[a];try{if(Rr.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 Or(t)};var ds=Nr;Nr.sync=us;var Ct={exports:{}};const Tr=(t={})=>{const e=t.env||process.env;return(t.platform||process.platform)!=="win32"?"PATH":Object.keys(e).reverse().find(o=>o.toUpperCase()==="PATH")||"Path"};Ct.exports=Tr,Ct.exports.default=Tr;var ms=Ct.exports;const Dr=S,fs=ds,ps=ms;function _r(t,e){const r=t.options.env||process.env,o=process.cwd(),s=t.options.cwd!=null,n=s&&process.chdir!==void 0&&!process.chdir.disabled;if(n)try{process.chdir(t.options.cwd)}catch{}let i;try{i=fs.sync(t.command,{path:r[ps({env:r})],pathExt:e?Dr.delimiter:void 0})}catch{}finally{n&&process.chdir(o)}return i&&(i=Dr.resolve(s?t.options.cwd:"",i)),i}function hs(t){return _r(t)||_r(t,!0)}var gs=hs,Pt={};const $t=/([()\][%!^"`<>&|;, *?])/g;function ys(t){return t=t.replace($t,"^$1"),t}function ws(t,e){return t=`${t}`,t=t.replace(/(?=(\\+?)?)\1"/g,'$1$1\\"'),t=t.replace(/(?=(\\+?)?)\1$/,"$1$1"),t=`"${t}"`,t=t.replace($t,"^$1"),e&&(t=t.replace($t,"^$1")),t}Pt.command=ys,Pt.argument=ws;var vs=/^#!(.*)/;const bs=vs;var Cs=(t="")=>{const e=t.match(bs);if(!e)return null;const[r,o]=e[0].replace(/#! ?/,"").split(" "),s=r.split("/").pop();return s==="env"?o:o?`${s} ${o}`:s};const Et=oe,Ps=Cs;function $s(t){const r=Buffer.alloc(150);let o;try{o=Et.openSync(t,"r"),Et.readSync(o,r,0,150,0),Et.closeSync(o)}catch{}return Ps(r.toString())}var Es=$s;const ks=S,Fr=gs,Gr=Pt,As=Es,xs=process.platform==="win32",Ss=/\.(?:com|exe)$/i,Is=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function Ms(t){t.file=Fr(t);const e=t.file&&As(t.file);return e?(t.args.unshift(t.file),t.command=e,Fr(t)):t.file}function Rs(t){if(!xs)return t;const e=Ms(t),r=!Ss.test(e);if(t.options.forceShell||r){const o=Is.test(e);t.command=ks.normalize(t.command),t.command=Gr.command(t.command),t.args=t.args.map(n=>Gr.argument(n,o));const s=[t.command].concat(t.args).join(" ");t.args=["/d","/s","/c",`"${s}"`],t.command=process.env.comspec||"cmd.exe",t.options.windowsVerbatimArguments=!0}return t}function Os(t,e,r){e&&!Array.isArray(e)&&(r=e,e=null),e=e?e.slice(0):[],r=Object.assign({},r);const o={command:t,args:e,options:r,file:void 0,original:{command:t,args:e}};return r.shell?o:Rs(o)}var Ls=Os;const kt=process.platform==="win32";function At(t,e){return Object.assign(new Error(`${e} ${t.command} ENOENT`),{code:"ENOENT",errno:"ENOENT",syscall:`${e} ${t.command}`,path:t.command,spawnargs:t.args})}function Ns(t,e){if(!kt)return;const r=t.emit;t.emit=function(o,s){if(o==="exit"){const n=Hr(s,e);if(n)return r.call(t,"error",n)}return r.apply(t,arguments)}}function Hr(t,e){return kt&&t===1&&!e.file?At(e.original,"spawn"):null}function Ts(t,e){return kt&&t===1&&!e.file?At(e.original,"spawnSync"):null}var Ds={hookChildProcess:Ns,verifyENOENT:Hr,verifyENOENTSync:Ts,notFoundError:At};const jr=pn,xt=Ls,St=Ds;function Br(t,e,r){const o=xt(t,e,r),s=jr.spawn(o.command,o.args,o.options);return St.hookChildProcess(s,o),s}function _s(t,e,r){const o=xt(t,e,r),s=jr.spawnSync(o.command,o.args,o.options);return s.error=s.error||St.verifyENOENTSync(s.status,o),s}pe.exports=Br,pe.exports.spawn=Br,pe.exports.sync=_s,pe.exports._parse=xt,pe.exports._enoent=St;var Fs=pe.exports,Gs=fe(Fs);function Hs(t){const e=typeof t=="string"?`
2
+ import{command as ie,cli as ln}from"cleye";import{createRequire as un}from"module";import{Buffer as dn}from"node:buffer";import ue from"node:path";import dr,{ChildProcess as mn,exec as fn}from"node:child_process";import ae from"node:process";import pn,{execSync as je}from"child_process";import S from"path";import oe from"fs";import{fileURLToPath as mr}from"node:url";import hn,{constants as fr}from"node:os";import pr from"assert";import hr from"events";import{createWriteStream as gn,createReadStream as yn}from"node:fs";import wn from"buffer";import gt from"stream";import gr from"util";import{debuglog as vn,promisify as bn}from"node:util";import Be from"inquirer";import C from"chalk";import{of as Ae,concatMap as L,from as I,map as M,catchError as R,mergeMap as Ue,BehaviorSubject as yr,ReplaySubject as Cn,lastValueFrom as wr,filter as vr,toArray as br,Subject as Cr}from"rxjs";import Pn from"@anthropic-ai/sdk";import{fromPromise as N}from"rxjs/internal/observable/innerFrom";import{xxh64 as Pr}from"@pacote/xxhash";import H from"winston";import O from"fs/promises";import ze from"os";import"winston-daily-rotate-file";import $n from"axios";import{CohereClient as En}from"cohere-ai";import $r from"openai";import{GoogleGenerativeAI as kn,HarmCategory as Ke,HarmBlockThreshold as We}from"@google/generative-ai";import An from"groq-sdk";import{Ollama as xn}from"ollama";import{fetch as Sn,Agent as In}from"undici";import Mn from"http";import Rn from"https";import On from"net";import Ln from"tls";import Nn,{fileURLToPath as Tn,pathToFileURL as Dn}from"url";import Er from"tty";import Ye from"readline";import _n from"figlet";import kr from"ora";import Fn from"inquirer-reactive-list-prompt";import{readdir as Ar,stat as Gn,rm as Hn}from"node:fs/promises";import jn from"chokidar";import{takeUntil as Bn}from"rxjs/operators";var Un="aicommit2",xr="2.3.6",zn="A Reactive CLI that generates git commit messages with various AI",Kn=["cli","ai","git","commit","git-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"],Wn="MIT",Yn="tak-bro/aicommit2",qn="Hyungtak Jin(@tak-bro)",Jn="module",Vn=["dist"],Xn={aicommit2:"./dist/cli.mjs",aic2:"./dist/cli.mjs"},Qn={prepare:"simple-git-hooks",build:"pkgroll --minify",lint:"eslint --cache .","type-check":"tsc",test:"tsx tests",prepack:"pnpm build && clean-pkg-json",prettier:"prettier"},Zn={"@anthropic-ai/sdk":"^0.39.0","@dqbd/tiktoken":"^1.0.21","@google/generative-ai":"^0.24.1","@inquirer/prompts":"^3.3.2","@pacote/xxhash":"^0.3.2","@types/winston":"^2.4.4",axios:"^1.9.0",chalk:"^5.4.1",chokidar:"^4.0.3",cleye:"^1.3.4","cohere-ai":"^7.17.1","copy-paste":"^1.5.3",figlet:"^1.8.1","formdata-node":"^6.0.3","groq-sdk":"^0.7.0",inquirer:"9.2.8","inquirer-reactive-list-prompt":"^1.0.15",ollama:"^0.5.15",openai:"^5.0.1",ora:"^8.2.0",readline:"^1.3.0",rxjs:"^7.8.2",undici:"^7.10.0",uuid:"^9.0.1",winston:"^3.17.0","winston-daily-rotate-file":"^5.0.0"},es={"@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"},ts={extends:["@pvtnbr","prettier"],rules:{"unicorn/no-process-exit":"off"},overrides:[{files:"./src/commands/prepare-commit-msg-hook.ts",rules:{"unicorn/prevent-abbreviations":"off"}}]},rs={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"]},os={name:Un,version:xr,description:zn,keywords:Kn,license:Wn,repository:Yn,author:qn,type:Jn,files:Vn,bin:Xn,scripts:Qn,"simple-git-hooks":{"pre-commit":"pnpm lint-staged"},"lint-staged":{"*.ts":["prettier --config ./.prettierrc --write","eslint --fix"]},dependencies:Zn,devDependencies:es,eslintConfig:ts,release:rs},ns=un(import.meta.url),F=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function fe(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var pe={exports:{}},yt,Sr;function ss(){if(Sr)return yt;Sr=1,yt=o,o.sync=s;var t=oe;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 l=0;l<c.length;l++){var u=c[l].toLowerCase();if(u&&n.substr(-u.length).toLowerCase()===u)return!0}return!1}function r(n,i,c){return!n.isSymbolicLink()&&!n.isFile()?!1:e(i,c)}function o(n,i,c){t.stat(n,function(l,u){c(l,l?!1:r(u,n,i))})}function s(n,i){return r(t.statSync(n),n,i)}return yt}var wt,Ir;function is(){if(Ir)return wt;Ir=1,wt=e,e.sync=r;var t=oe;function e(n,i,c){t.stat(n,function(l,u){c(l,l?!1:o(u,i))})}function r(n,i){return o(t.statSync(n),i)}function o(n,i){return n.isFile()&&s(n,i)}function s(n,i){var c=n.mode,l=n.uid,u=n.gid,m=i.uid!==void 0?i.uid:process.getuid&&process.getuid(),a=i.gid!==void 0?i.gid:process.getgid&&process.getgid(),d=parseInt("100",8),f=parseInt("010",8),h=parseInt("001",8),g=d|f,y=c&h||c&f&&u===a||c&d&&l===m||c&g&&m===0;return y}return wt}var qe;process.platform==="win32"||F.TESTING_WINDOWS?qe=ss():qe=is();var as=vt;vt.sync=cs;function vt(t,e,r){if(typeof e=="function"&&(r=e,e={}),!r){if(typeof Promise!="function")throw new TypeError("callback not provided");return new Promise(function(o,s){vt(t,e||{},function(n,i){n?s(n):o(i)})})}qe(t,e||{},function(o,s){o&&(o.code==="EACCES"||e&&e.ignoreErrors)&&(o=null,s=!1),r(o,s)})}function cs(t,e){try{return qe.sync(t,e||{})}catch(r){if(e&&e.ignoreErrors||r.code==="EACCES")return!1;throw r}}const he=process.platform==="win32"||process.env.OSTYPE==="cygwin"||process.env.OSTYPE==="msys",Mr=S,ls=he?";":":",Rr=as,Or=t=>Object.assign(new Error(`not found: ${t}`),{code:"ENOENT"}),Lr=(t,e)=>{const r=e.colon||ls,o=t.match(/\//)||he&&t.match(/\\/)?[""]:[...he?[process.cwd()]:[],...(e.path||process.env.PATH||"").split(r)],s=he?e.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",n=he?s.split(r):[""];return he&&t.indexOf(".")!==-1&&n[0]!==""&&n.unshift(""),{pathEnv:o,pathExt:n,pathExtExe:s}},Nr=(t,e,r)=>{typeof e=="function"&&(r=e,e={}),e||(e={});const{pathEnv:o,pathExt:s,pathExtExe:n}=Lr(t,e),i=[],c=u=>new Promise((m,a)=>{if(u===o.length)return e.all&&i.length?m(i):a(Or(t));const d=o[u],f=/^".*"$/.test(d)?d.slice(1,-1):d,h=Mr.join(f,t),g=!f&&/^\.[\\\/]/.test(t)?t.slice(0,2)+h:h;m(l(g,u,0))}),l=(u,m,a)=>new Promise((d,f)=>{if(a===s.length)return d(c(m+1));const h=s[a];Rr(u+h,{pathExt:n},(g,y)=>{if(!g&&y)if(e.all)i.push(u+h);else return d(u+h);return d(l(u,m,a+1))})});return r?c(0).then(u=>r(null,u),r):c(0)},us=(t,e)=>{e=e||{};const{pathEnv:r,pathExt:o,pathExtExe:s}=Lr(t,e),n=[];for(let i=0;i<r.length;i++){const c=r[i],l=/^".*"$/.test(c)?c.slice(1,-1):c,u=Mr.join(l,t),m=!l&&/^\.[\\\/]/.test(t)?t.slice(0,2)+u:u;for(let a=0;a<o.length;a++){const d=m+o[a];try{if(Rr.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 Or(t)};var ds=Nr;Nr.sync=us;var bt={exports:{}};const Tr=(t={})=>{const e=t.env||process.env;return(t.platform||process.platform)!=="win32"?"PATH":Object.keys(e).reverse().find(o=>o.toUpperCase()==="PATH")||"Path"};bt.exports=Tr,bt.exports.default=Tr;var ms=bt.exports;const Dr=S,fs=ds,ps=ms;function _r(t,e){const r=t.options.env||process.env,o=process.cwd(),s=t.options.cwd!=null,n=s&&process.chdir!==void 0&&!process.chdir.disabled;if(n)try{process.chdir(t.options.cwd)}catch{}let i;try{i=fs.sync(t.command,{path:r[ps({env:r})],pathExt:e?Dr.delimiter:void 0})}catch{}finally{n&&process.chdir(o)}return i&&(i=Dr.resolve(s?t.options.cwd:"",i)),i}function hs(t){return _r(t)||_r(t,!0)}var gs=hs,Ct={};const Pt=/([()\][%!^"`<>&|;, *?])/g;function ys(t){return t=t.replace(Pt,"^$1"),t}function ws(t,e){return t=`${t}`,t=t.replace(/(?=(\\+?)?)\1"/g,'$1$1\\"'),t=t.replace(/(?=(\\+?)?)\1$/,"$1$1"),t=`"${t}"`,t=t.replace(Pt,"^$1"),e&&(t=t.replace(Pt,"^$1")),t}Ct.command=ys,Ct.argument=ws;var vs=/^#!(.*)/;const bs=vs;var Cs=(t="")=>{const e=t.match(bs);if(!e)return null;const[r,o]=e[0].replace(/#! ?/,"").split(" "),s=r.split("/").pop();return s==="env"?o:o?`${s} ${o}`:s};const $t=oe,Ps=Cs;function $s(t){const r=Buffer.alloc(150);let o;try{o=$t.openSync(t,"r"),$t.readSync(o,r,0,150,0),$t.closeSync(o)}catch{}return Ps(r.toString())}var Es=$s;const ks=S,Fr=gs,Gr=Ct,As=Es,xs=process.platform==="win32",Ss=/\.(?:com|exe)$/i,Is=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function Ms(t){t.file=Fr(t);const e=t.file&&As(t.file);return e?(t.args.unshift(t.file),t.command=e,Fr(t)):t.file}function Rs(t){if(!xs)return t;const e=Ms(t),r=!Ss.test(e);if(t.options.forceShell||r){const o=Is.test(e);t.command=ks.normalize(t.command),t.command=Gr.command(t.command),t.args=t.args.map(n=>Gr.argument(n,o));const s=[t.command].concat(t.args).join(" ");t.args=["/d","/s","/c",`"${s}"`],t.command=process.env.comspec||"cmd.exe",t.options.windowsVerbatimArguments=!0}return t}function Os(t,e,r){e&&!Array.isArray(e)&&(r=e,e=null),e=e?e.slice(0):[],r=Object.assign({},r);const o={command:t,args:e,options:r,file:void 0,original:{command:t,args:e}};return r.shell?o:Rs(o)}var Ls=Os;const Et=process.platform==="win32";function kt(t,e){return Object.assign(new Error(`${e} ${t.command} ENOENT`),{code:"ENOENT",errno:"ENOENT",syscall:`${e} ${t.command}`,path:t.command,spawnargs:t.args})}function Ns(t,e){if(!Et)return;const r=t.emit;t.emit=function(o,s){if(o==="exit"){const n=Hr(s,e);if(n)return r.call(t,"error",n)}return r.apply(t,arguments)}}function Hr(t,e){return Et&&t===1&&!e.file?kt(e.original,"spawn"):null}function Ts(t,e){return Et&&t===1&&!e.file?kt(e.original,"spawnSync"):null}var Ds={hookChildProcess:Ns,verifyENOENT:Hr,verifyENOENTSync:Ts,notFoundError:kt};const jr=pn,At=Ls,xt=Ds;function Br(t,e,r){const o=At(t,e,r),s=jr.spawn(o.command,o.args,o.options);return xt.hookChildProcess(s,o),s}function _s(t,e,r){const o=At(t,e,r),s=jr.spawnSync(o.command,o.args,o.options);return s.error=s.error||xt.verifyENOENTSync(s.status,o),s}pe.exports=Br,pe.exports.spawn=Br,pe.exports.sync=_s,pe.exports._parse=At,pe.exports._enoent=xt;var Fs=pe.exports,Gs=fe(Fs);function Hs(t){const e=typeof t=="string"?`
3
3
  `:`
4
- `.charCodeAt(),r=typeof t=="string"?"\r":"\r".charCodeAt();return t[t.length-1]===e&&(t=t.slice(0,-1)),t[t.length-1]===r&&(t=t.slice(0,-1)),t}function Ur(t={}){const{env:e=process.env,platform:r=process.platform}=t;return r!=="win32"?"PATH":Object.keys(e).reverse().find(o=>o.toUpperCase()==="PATH")||"Path"}const js=({cwd:t=ae.cwd(),path:e=ae.env[Ur()],preferLocal:r=!0,execPath:o=ae.execPath,addExecPath:s=!0}={})=>{const n=t instanceof URL?fr(t):t,i=ue.resolve(n),c=[];return r&&Bs(c,i),s&&Us(c,o,i),[...c,e].join(ue.delimiter)},Bs=(t,e)=>{let r;for(;r!==e;)t.push(ue.join(e,"node_modules/.bin")),r=e,e=ue.resolve(e,"..")},Us=(t,e,r)=>{const o=e instanceof URL?fr(e):e;t.push(ue.resolve(r,o,".."))},zs=({env:t=ae.env,...e}={})=>{t={...t};const r=Ur({env:t});return e.path=t[r],t[r]=js(e),t},Ks=(t,e,r,o)=>{if(r==="length"||r==="prototype"||r==="arguments"||r==="caller")return;const s=Object.getOwnPropertyDescriptor(t,r),n=Object.getOwnPropertyDescriptor(e,r);!Ws(s,n)&&o||Object.defineProperty(t,r,n)},Ws=function(t,e){return t===void 0||t.configurable||t.writable===e.writable&&t.enumerable===e.enumerable&&t.configurable===e.configurable&&(t.writable||t.value===e.value)},Ys=(t,e)=>{const r=Object.getPrototypeOf(e);r!==Object.getPrototypeOf(t)&&Object.setPrototypeOf(t,r)},qs=(t,e)=>`/* Wrapped ${t}*/
5
- ${e}`,Js=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),Vs=Object.getOwnPropertyDescriptor(Function.prototype.toString,"name"),Xs=(t,e,r)=>{const o=r===""?"":`with ${r.trim()}() `,s=qs.bind(null,o,e.toString());Object.defineProperty(s,"name",Vs),Object.defineProperty(t,"toString",{...Js,value:s})};function Qs(t,e,{ignoreNonConfigurable:r=!1}={}){const{name:o}=t;for(const s of Reflect.ownKeys(e))Ks(t,e,s,r);return Ys(t,e),Xs(t,e,o),t}const Je=new WeakMap,zr=(t,e={})=>{if(typeof t!="function")throw new TypeError("Expected a function");let r,o=0;const s=t.displayName||t.name||"<anonymous>",n=function(...i){if(Je.set(n,++o),o===1)r=t.apply(this,i),t=null;else if(e.throw===!0)throw new Error(`Function \`${s}\` can only be called once`);return r};return Qs(n,t),Je.set(n,o),n};zr.callCount=t=>{if(!Je.has(t))throw new Error(`The given function \`${t.name}\` is not wrapped by the \`onetime\` package`);return Je.get(t)};const Zs=()=>{const t=Wr-Kr+1;return Array.from({length:t},ei)},ei=(t,e)=>({name:`SIGRT${e+1}`,number:Kr+e,action:"terminate",description:"Application-specific signal (realtime)",standard:"posix"}),Kr=34,Wr=64,ti=[{name:"SIGHUP",number:1,action:"terminate",description:"Terminal closed",standard:"posix"},{name:"SIGINT",number:2,action:"terminate",description:"User interruption with CTRL-C",standard:"ansi"},{name:"SIGQUIT",number:3,action:"core",description:"User interruption with CTRL-\\",standard:"posix"},{name:"SIGILL",number:4,action:"core",description:"Invalid machine instruction",standard:"ansi"},{name:"SIGTRAP",number:5,action:"core",description:"Debugger breakpoint",standard:"posix"},{name:"SIGABRT",number:6,action:"core",description:"Aborted",standard:"ansi"},{name:"SIGIOT",number:6,action:"core",description:"Aborted",standard:"bsd"},{name:"SIGBUS",number:7,action:"core",description:"Bus error due to misaligned, non-existing address or paging error",standard:"bsd"},{name:"SIGEMT",number:7,action:"terminate",description:"Command should be emulated but is not implemented",standard:"other"},{name:"SIGFPE",number:8,action:"core",description:"Floating point arithmetic error",standard:"ansi"},{name:"SIGKILL",number:9,action:"terminate",description:"Forced termination",standard:"posix",forced:!0},{name:"SIGUSR1",number:10,action:"terminate",description:"Application-specific signal",standard:"posix"},{name:"SIGSEGV",number:11,action:"core",description:"Segmentation fault",standard:"ansi"},{name:"SIGUSR2",number:12,action:"terminate",description:"Application-specific signal",standard:"posix"},{name:"SIGPIPE",number:13,action:"terminate",description:"Broken pipe or socket",standard:"posix"},{name:"SIGALRM",number:14,action:"terminate",description:"Timeout or timer",standard:"posix"},{name:"SIGTERM",number:15,action:"terminate",description:"Termination",standard:"ansi"},{name:"SIGSTKFLT",number:16,action:"terminate",description:"Stack is empty or overflowed",standard:"other"},{name:"SIGCHLD",number:17,action:"ignore",description:"Child process terminated, paused or unpaused",standard:"posix"},{name:"SIGCLD",number:17,action:"ignore",description:"Child process terminated, paused or unpaused",standard:"other"},{name:"SIGCONT",number:18,action:"unpause",description:"Unpaused",standard:"posix",forced:!0},{name:"SIGSTOP",number:19,action:"pause",description:"Paused",standard:"posix",forced:!0},{name:"SIGTSTP",number:20,action:"pause",description:'Paused using CTRL-Z or "suspend"',standard:"posix"},{name:"SIGTTIN",number:21,action:"pause",description:"Background process cannot read terminal input",standard:"posix"},{name:"SIGBREAK",number:21,action:"terminate",description:"User interruption with CTRL-BREAK",standard:"other"},{name:"SIGTTOU",number:22,action:"pause",description:"Background process cannot write to terminal output",standard:"posix"},{name:"SIGURG",number:23,action:"ignore",description:"Socket received out-of-band data",standard:"bsd"},{name:"SIGXCPU",number:24,action:"core",description:"Process timed out",standard:"bsd"},{name:"SIGXFSZ",number:25,action:"core",description:"File too big",standard:"bsd"},{name:"SIGVTALRM",number:26,action:"terminate",description:"Timeout or timer",standard:"bsd"},{name:"SIGPROF",number:27,action:"terminate",description:"Timeout or timer",standard:"bsd"},{name:"SIGWINCH",number:28,action:"ignore",description:"Terminal window size changed",standard:"bsd"},{name:"SIGIO",number:29,action:"terminate",description:"I/O is available",standard:"other"},{name:"SIGPOLL",number:29,action:"terminate",description:"Watched event",standard:"other"},{name:"SIGINFO",number:29,action:"ignore",description:"Request for process information",standard:"other"},{name:"SIGPWR",number:30,action:"terminate",description:"Device running out of power",standard:"systemv"},{name:"SIGSYS",number:31,action:"core",description:"Invalid system call",standard:"other"},{name:"SIGUNUSED",number:31,action:"terminate",description:"Invalid system call",standard:"other"}],Yr=()=>{const t=Zs();return[...ti,...t].map(ri)},ri=({name:t,number:e,description:r,action:o,forced:s=!1,standard:n})=>{const{signals:{[t]:i}}=pr,c=i!==void 0;return{name:t,number:c?i:e,description:r,supported:c,action:o,forced:s,standard:n}},oi=()=>{const t=Yr();return Object.fromEntries(t.map(ni))},ni=({name:t,number:e,description:r,supported:o,action:s,forced:n,standard:i})=>[t,{name:t,number:e,description:r,supported:o,action:s,forced:n,standard:i}],si=oi(),ii=()=>{const t=Yr(),e=Wr+1,r=Array.from({length:e},(o,s)=>ai(s,t));return Object.assign({},...r)},ai=(t,e)=>{const r=ci(t,e);if(r===void 0)return{};const{name:o,description:s,supported:n,action:i,forced:c,standard:l}=r;return{[t]:{name:o,number:t,description:s,supported:n,action:i,forced:c,standard:l}}},ci=(t,e)=>{const r=e.find(({name:o})=>pr.signals[o]===t);return r!==void 0?r:e.find(o=>o.number===t)};ii();const li=({timedOut:t,timeout:e,errorCode:r,signal:o,signalDescription:s,exitCode:n,isCanceled:i})=>t?`timed out after ${e} milliseconds`:i?"was canceled":r!==void 0?`failed with ${r}`:o!==void 0?`was killed with ${o} (${s})`:n!==void 0?`failed with exit code ${n}`:"failed",qr=({stdout:t,stderr:e,all:r,error:o,signal:s,exitCode:n,command:i,escapedCommand:c,timedOut:l,isCanceled:u,killed:m,parsed:{options:{timeout:a,cwd:d=ae.cwd()}}})=>{n=n===null?void 0:n,s=s===null?void 0:s;const f=s===void 0?void 0:si[s].description,h=o&&o.code,y=`Command ${li({timedOut:l,timeout:a,errorCode:h,signal:s,signalDescription:f,exitCode:n,isCanceled:u})}: ${i}`,w=Object.prototype.toString.call(o)==="[object Error]",v=w?`${y}
4
+ `.charCodeAt(),r=typeof t=="string"?"\r":"\r".charCodeAt();return t[t.length-1]===e&&(t=t.slice(0,-1)),t[t.length-1]===r&&(t=t.slice(0,-1)),t}function Ur(t={}){const{env:e=process.env,platform:r=process.platform}=t;return r!=="win32"?"PATH":Object.keys(e).reverse().find(o=>o.toUpperCase()==="PATH")||"Path"}const js=({cwd:t=ae.cwd(),path:e=ae.env[Ur()],preferLocal:r=!0,execPath:o=ae.execPath,addExecPath:s=!0}={})=>{const n=t instanceof URL?mr(t):t,i=ue.resolve(n),c=[];return r&&Bs(c,i),s&&Us(c,o,i),[...c,e].join(ue.delimiter)},Bs=(t,e)=>{let r;for(;r!==e;)t.push(ue.join(e,"node_modules/.bin")),r=e,e=ue.resolve(e,"..")},Us=(t,e,r)=>{const o=e instanceof URL?mr(e):e;t.push(ue.resolve(r,o,".."))},zs=({env:t=ae.env,...e}={})=>{t={...t};const r=Ur({env:t});return e.path=t[r],t[r]=js(e),t},Ks=(t,e,r,o)=>{if(r==="length"||r==="prototype"||r==="arguments"||r==="caller")return;const s=Object.getOwnPropertyDescriptor(t,r),n=Object.getOwnPropertyDescriptor(e,r);!Ws(s,n)&&o||Object.defineProperty(t,r,n)},Ws=function(t,e){return t===void 0||t.configurable||t.writable===e.writable&&t.enumerable===e.enumerable&&t.configurable===e.configurable&&(t.writable||t.value===e.value)},Ys=(t,e)=>{const r=Object.getPrototypeOf(e);r!==Object.getPrototypeOf(t)&&Object.setPrototypeOf(t,r)},qs=(t,e)=>`/* Wrapped ${t}*/
5
+ ${e}`,Js=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),Vs=Object.getOwnPropertyDescriptor(Function.prototype.toString,"name"),Xs=(t,e,r)=>{const o=r===""?"":`with ${r.trim()}() `,s=qs.bind(null,o,e.toString());Object.defineProperty(s,"name",Vs),Object.defineProperty(t,"toString",{...Js,value:s})};function Qs(t,e,{ignoreNonConfigurable:r=!1}={}){const{name:o}=t;for(const s of Reflect.ownKeys(e))Ks(t,e,s,r);return Ys(t,e),Xs(t,e,o),t}const Je=new WeakMap,zr=(t,e={})=>{if(typeof t!="function")throw new TypeError("Expected a function");let r,o=0;const s=t.displayName||t.name||"<anonymous>",n=function(...i){if(Je.set(n,++o),o===1)r=t.apply(this,i),t=null;else if(e.throw===!0)throw new Error(`Function \`${s}\` can only be called once`);return r};return Qs(n,t),Je.set(n,o),n};zr.callCount=t=>{if(!Je.has(t))throw new Error(`The given function \`${t.name}\` is not wrapped by the \`onetime\` package`);return Je.get(t)};const Zs=()=>{const t=Wr-Kr+1;return Array.from({length:t},ei)},ei=(t,e)=>({name:`SIGRT${e+1}`,number:Kr+e,action:"terminate",description:"Application-specific signal (realtime)",standard:"posix"}),Kr=34,Wr=64,ti=[{name:"SIGHUP",number:1,action:"terminate",description:"Terminal closed",standard:"posix"},{name:"SIGINT",number:2,action:"terminate",description:"User interruption with CTRL-C",standard:"ansi"},{name:"SIGQUIT",number:3,action:"core",description:"User interruption with CTRL-\\",standard:"posix"},{name:"SIGILL",number:4,action:"core",description:"Invalid machine instruction",standard:"ansi"},{name:"SIGTRAP",number:5,action:"core",description:"Debugger breakpoint",standard:"posix"},{name:"SIGABRT",number:6,action:"core",description:"Aborted",standard:"ansi"},{name:"SIGIOT",number:6,action:"core",description:"Aborted",standard:"bsd"},{name:"SIGBUS",number:7,action:"core",description:"Bus error due to misaligned, non-existing address or paging error",standard:"bsd"},{name:"SIGEMT",number:7,action:"terminate",description:"Command should be emulated but is not implemented",standard:"other"},{name:"SIGFPE",number:8,action:"core",description:"Floating point arithmetic error",standard:"ansi"},{name:"SIGKILL",number:9,action:"terminate",description:"Forced termination",standard:"posix",forced:!0},{name:"SIGUSR1",number:10,action:"terminate",description:"Application-specific signal",standard:"posix"},{name:"SIGSEGV",number:11,action:"core",description:"Segmentation fault",standard:"ansi"},{name:"SIGUSR2",number:12,action:"terminate",description:"Application-specific signal",standard:"posix"},{name:"SIGPIPE",number:13,action:"terminate",description:"Broken pipe or socket",standard:"posix"},{name:"SIGALRM",number:14,action:"terminate",description:"Timeout or timer",standard:"posix"},{name:"SIGTERM",number:15,action:"terminate",description:"Termination",standard:"ansi"},{name:"SIGSTKFLT",number:16,action:"terminate",description:"Stack is empty or overflowed",standard:"other"},{name:"SIGCHLD",number:17,action:"ignore",description:"Child process terminated, paused or unpaused",standard:"posix"},{name:"SIGCLD",number:17,action:"ignore",description:"Child process terminated, paused or unpaused",standard:"other"},{name:"SIGCONT",number:18,action:"unpause",description:"Unpaused",standard:"posix",forced:!0},{name:"SIGSTOP",number:19,action:"pause",description:"Paused",standard:"posix",forced:!0},{name:"SIGTSTP",number:20,action:"pause",description:'Paused using CTRL-Z or "suspend"',standard:"posix"},{name:"SIGTTIN",number:21,action:"pause",description:"Background process cannot read terminal input",standard:"posix"},{name:"SIGBREAK",number:21,action:"terminate",description:"User interruption with CTRL-BREAK",standard:"other"},{name:"SIGTTOU",number:22,action:"pause",description:"Background process cannot write to terminal output",standard:"posix"},{name:"SIGURG",number:23,action:"ignore",description:"Socket received out-of-band data",standard:"bsd"},{name:"SIGXCPU",number:24,action:"core",description:"Process timed out",standard:"bsd"},{name:"SIGXFSZ",number:25,action:"core",description:"File too big",standard:"bsd"},{name:"SIGVTALRM",number:26,action:"terminate",description:"Timeout or timer",standard:"bsd"},{name:"SIGPROF",number:27,action:"terminate",description:"Timeout or timer",standard:"bsd"},{name:"SIGWINCH",number:28,action:"ignore",description:"Terminal window size changed",standard:"bsd"},{name:"SIGIO",number:29,action:"terminate",description:"I/O is available",standard:"other"},{name:"SIGPOLL",number:29,action:"terminate",description:"Watched event",standard:"other"},{name:"SIGINFO",number:29,action:"ignore",description:"Request for process information",standard:"other"},{name:"SIGPWR",number:30,action:"terminate",description:"Device running out of power",standard:"systemv"},{name:"SIGSYS",number:31,action:"core",description:"Invalid system call",standard:"other"},{name:"SIGUNUSED",number:31,action:"terminate",description:"Invalid system call",standard:"other"}],Yr=()=>{const t=Zs();return[...ti,...t].map(ri)},ri=({name:t,number:e,description:r,action:o,forced:s=!1,standard:n})=>{const{signals:{[t]:i}}=fr,c=i!==void 0;return{name:t,number:c?i:e,description:r,supported:c,action:o,forced:s,standard:n}},oi=()=>{const t=Yr();return Object.fromEntries(t.map(ni))},ni=({name:t,number:e,description:r,supported:o,action:s,forced:n,standard:i})=>[t,{name:t,number:e,description:r,supported:o,action:s,forced:n,standard:i}],si=oi(),ii=()=>{const t=Yr(),e=Wr+1,r=Array.from({length:e},(o,s)=>ai(s,t));return Object.assign({},...r)},ai=(t,e)=>{const r=ci(t,e);if(r===void 0)return{};const{name:o,description:s,supported:n,action:i,forced:c,standard:l}=r;return{[t]:{name:o,number:t,description:s,supported:n,action:i,forced:c,standard:l}}},ci=(t,e)=>{const r=e.find(({name:o})=>fr.signals[o]===t);return r!==void 0?r:e.find(o=>o.number===t)};ii();const li=({timedOut:t,timeout:e,errorCode:r,signal:o,signalDescription:s,exitCode:n,isCanceled:i})=>t?`timed out after ${e} milliseconds`:i?"was canceled":r!==void 0?`failed with ${r}`:o!==void 0?`was killed with ${o} (${s})`:n!==void 0?`failed with exit code ${n}`:"failed",qr=({stdout:t,stderr:e,all:r,error:o,signal:s,exitCode:n,command:i,escapedCommand:c,timedOut:l,isCanceled:u,killed:m,parsed:{options:{timeout:a,cwd:d=ae.cwd()}}})=>{n=n===null?void 0:n,s=s===null?void 0:s;const f=s===void 0?void 0:si[s].description,h=o&&o.code,y=`Command ${li({timedOut:l,timeout:a,errorCode:h,signal:s,signalDescription:f,exitCode:n,isCanceled:u})}: ${i}`,w=Object.prototype.toString.call(o)==="[object Error]",v=w?`${y}
6
6
  ${o.message}`:y,P=[v,e,t].filter(Boolean).join(`
7
- `);return w?(o.originalMessage=o.message,o.message=P):o=new Error(P),o.shortMessage=v,o.command=i,o.escapedCommand=c,o.exitCode=n,o.signal=s,o.signalDescription=f,o.stdout=t,o.stderr=e,o.cwd=d,r!==void 0&&(o.all=r),"bufferedData"in o&&delete o.bufferedData,o.failed=!0,o.timedOut=!!l,o.isCanceled=u,o.killed=m&&!l,o},Ve=["stdin","stdout","stderr"],ui=t=>Ve.some(e=>t[e]!==void 0),di=t=>{if(!t)return;const{stdio:e}=t;if(e===void 0)return Ve.map(o=>t[o]);if(ui(t))throw new Error(`It's not possible to provide \`stdio\` in combination with one of ${Ve.map(o=>`\`${o}\``).join(", ")}`);if(typeof e=="string")return e;if(!Array.isArray(e))throw new TypeError(`Expected \`stdio\` to be of type \`string\` or \`Array\`, got \`${typeof e}\``);const r=Math.max(e.length,Ve.length);return Array.from({length:r},(o,s)=>e[s])};var ge={exports:{}},Xe={exports:{}};Xe.exports;var Jr;function mi(){return Jr||(Jr=1,function(t){t.exports=["SIGABRT","SIGALRM","SIGHUP","SIGINT","SIGTERM"],process.platform!=="win32"&&t.exports.push("SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT"),process.platform==="linux"&&t.exports.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT","SIGUNUSED")}(Xe)),Xe.exports}var D=F.process;const de=function(t){return t&&typeof t=="object"&&typeof t.removeListener=="function"&&typeof t.emit=="function"&&typeof t.reallyExit=="function"&&typeof t.listeners=="function"&&typeof t.kill=="function"&&typeof t.pid=="number"&&typeof t.on=="function"};if(!de(D))ge.exports=function(){return function(){}};else{var fi=hr,xe=mi(),pi=/^win/i.test(D.platform),Qe=gr;typeof Qe!="function"&&(Qe=Qe.EventEmitter);var G;D.__signal_exit_emitter__?G=D.__signal_exit_emitter__:(G=D.__signal_exit_emitter__=new Qe,G.count=0,G.emitted={}),G.infinite||(G.setMaxListeners(1/0),G.infinite=!0),ge.exports=function(t,e){if(!de(F.process))return function(){};fi.equal(typeof t,"function","a callback must be provided for exit handler"),Se===!1&&Vr();var r="exit";e&&e.alwaysLast&&(r="afterexit");var o=function(){G.removeListener(r,t),G.listeners("exit").length===0&&G.listeners("afterexit").length===0&&It()};return G.on(r,t),o};var It=function(){!Se||!de(F.process)||(Se=!1,xe.forEach(function(e){try{D.removeListener(e,Mt[e])}catch{}}),D.emit=Rt,D.reallyExit=Xr,G.count-=1)};ge.exports.unload=It;var ye=function(e,r,o){G.emitted[e]||(G.emitted[e]=!0,G.emit(e,r,o))},Mt={};xe.forEach(function(t){Mt[t]=function(){if(de(F.process)){var r=D.listeners(t);r.length===G.count&&(It(),ye("exit",null,t),ye("afterexit",null,t),pi&&t==="SIGHUP"&&(t="SIGINT"),D.kill(D.pid,t))}}}),ge.exports.signals=function(){return xe};var Se=!1,Vr=function(){Se||!de(F.process)||(Se=!0,G.count+=1,xe=xe.filter(function(e){try{return D.on(e,Mt[e]),!0}catch{return!1}}),D.emit=gi,D.reallyExit=hi)};ge.exports.load=Vr;var Xr=D.reallyExit,hi=function(e){de(F.process)&&(D.exitCode=e||0,ye("exit",D.exitCode,null),ye("afterexit",D.exitCode,null),Xr.call(D,D.exitCode))},Rt=D.emit,gi=function(e,r){if(e==="exit"&&de(F.process)){r!==void 0&&(D.exitCode=r);var o=Rt.apply(this,arguments);return ye("exit",D.exitCode,null),ye("afterexit",D.exitCode,null),o}else return Rt.apply(this,arguments)}}var yi=ge.exports,wi=fe(yi);const vi=1e3*5,bi=(t,e="SIGTERM",r={})=>{const o=t(e);return Ci(t,e,r,o),o},Ci=(t,e,r,o)=>{if(!Pi(e,r,o))return;const s=Ei(r),n=setTimeout(()=>{t("SIGKILL")},s);n.unref&&n.unref()},Pi=(t,{forceKillAfterTimeout:e},r)=>$i(t)&&e!==!1&&r,$i=t=>t===hn.constants.signals.SIGTERM||typeof t=="string"&&t.toUpperCase()==="SIGTERM",Ei=({forceKillAfterTimeout:t=!0})=>{if(t===!0)return vi;if(!Number.isFinite(t)||t<0)throw new TypeError(`Expected the \`forceKillAfterTimeout\` option to be a non-negative integer, got \`${t}\` (${typeof t})`);return t},ki=(t,e)=>{t.kill()&&(e.isCanceled=!0)},Ai=(t,e,r)=>{t.kill(e),r(Object.assign(new Error("Timed out"),{timedOut:!0,signal:e}))},xi=(t,{timeout:e,killSignal:r="SIGTERM"},o)=>{if(e===0||e===void 0)return o;let s;const n=new Promise((c,l)=>{s=setTimeout(()=>{Ai(t,r,l)},e)}),i=o.finally(()=>{clearTimeout(s)});return Promise.race([n,i])},Si=({timeout:t})=>{if(t!==void 0&&(!Number.isFinite(t)||t<0))throw new TypeError(`Expected the \`timeout\` option to be a non-negative integer, got \`${t}\` (${typeof t})`)},Ii=async(t,{cleanup:e,detached:r},o)=>{if(!e||r)return o;const s=wi(()=>{t.kill()});return o.finally(()=>{s()})};function Qr(t){return t!==null&&typeof t=="object"&&typeof t.pipe=="function"}function Zr(t){return Qr(t)&&t.writable!==!1&&typeof t._write=="function"&&typeof t._writableState=="object"}const Mi=t=>t instanceof mn&&typeof t.then=="function",Ot=(t,e,r)=>{if(typeof r=="string")return t[e].pipe(gn(r)),t;if(Zr(r))return t[e].pipe(r),t;if(!Mi(r))throw new TypeError("The second argument must be a string, a stream or an Execa child process.");if(!Zr(r.stdin))throw new TypeError("The target child process's stdin must be available.");return t[e].pipe(r.stdin),r},Ri=t=>{t.stdout!==null&&(t.pipeStdout=Ot.bind(void 0,t,"stdout")),t.stderr!==null&&(t.pipeStderr=Ot.bind(void 0,t,"stderr")),t.all!==void 0&&(t.pipeAll=Ot.bind(void 0,t,"all"))};var Ie={exports:{}};const{PassThrough:Oi}=gt;var Li=t=>{t={...t};const{array:e}=t;let{encoding:r}=t;const o=r==="buffer";let s=!1;e?s=!(r||o):r=r||"utf8",o&&(r=null);const n=new Oi({objectMode:s});r&&n.setEncoding(r);let i=0;const c=[];return n.on("data",l=>{c.push(l),s?i=c.length:i+=l.length}),n.getBufferedValue=()=>e?c:o?Buffer.concat(c,i):c.join(""),n.getBufferedLength=()=>i,n};const{constants:Ni}=wn,Ti=gt,{promisify:Di}=yr,_i=Li,Fi=Di(Ti.pipeline);class eo extends Error{constructor(){super("maxBuffer exceeded"),this.name="MaxBufferError"}}async function Lt(t,e){if(!t)throw new Error("Expected a stream");e={maxBuffer:1/0,...e};const{maxBuffer:r}=e,o=_i(e);return await new Promise((s,n)=>{const i=c=>{c&&o.getBufferedLength()<=Ni.MAX_LENGTH&&(c.bufferedData=o.getBufferedValue()),n(c)};(async()=>{try{await Fi(t,o),s()}catch(c){i(c)}})(),o.on("data",()=>{o.getBufferedLength()>r&&i(new eo)})}),o.getBufferedValue()}Ie.exports=Lt,Ie.exports.buffer=(t,e)=>Lt(t,{...e,encoding:"buffer"}),Ie.exports.array=(t,e)=>Lt(t,{...e,array:!0}),Ie.exports.MaxBufferError=eo;var Gi=Ie.exports,to=fe(Gi);const{PassThrough:Hi}=gt;var ji=function(){var t=[],e=new Hi({objectMode:!0});return e.setMaxListeners(0),e.add=r,e.isEmpty=o,e.on("unpipe",s),Array.prototype.slice.call(arguments).forEach(r),e;function r(n){return Array.isArray(n)?(n.forEach(r),this):(t.push(n),n.once("end",s.bind(null,n)),n.once("error",e.emit.bind(e,"error")),n.pipe(e,{end:!1}),this)}function o(){return t.length==0}function s(n){t=t.filter(function(i){return i!==n}),!t.length&&e.readable&&e.end()}},Bi=fe(ji);const Ui=t=>{if(t!==void 0)throw new TypeError("The `input` and `inputFile` options cannot be both set.")},zi=({input:t,inputFile:e})=>typeof e!="string"?t:(Ui(t),yn(e)),Ki=(t,e)=>{const r=zi(e);r!==void 0&&(Qr(r)?r.pipe(t.stdin):t.stdin.end(r))},Wi=(t,{all:e})=>{if(!e||!t.stdout&&!t.stderr)return;const r=Bi();return t.stdout&&r.add(t.stdout),t.stderr&&r.add(t.stderr),r},Nt=async(t,e)=>{if(!(!t||e===void 0)){t.destroy();try{return await e}catch(r){return r.bufferedData}}},Tt=(t,{encoding:e,buffer:r,maxBuffer:o})=>{if(!(!t||!r))return e?to(t,{encoding:e,maxBuffer:o}):to.buffer(t,{maxBuffer:o})},Yi=async({stdout:t,stderr:e,all:r},{encoding:o,buffer:s,maxBuffer:n},i)=>{const c=Tt(t,{encoding:o,buffer:s,maxBuffer:n}),l=Tt(e,{encoding:o,buffer:s,maxBuffer:n}),u=Tt(r,{encoding:o,buffer:s,maxBuffer:n*2});try{return await Promise.all([i,c,l,u])}catch(m){return Promise.all([{error:m,signal:m.signal,timedOut:m.timedOut},Nt(t,c),Nt(e,l),Nt(r,u)])}},qi=(async()=>{})().constructor.prototype,Ji=["then","catch","finally"].map(t=>[t,Reflect.getOwnPropertyDescriptor(qi,t)]),ro=(t,e)=>{for(const[r,o]of Ji){const s=typeof e=="function"?(...n)=>Reflect.apply(o.value,e(),n):o.value.bind(e);Reflect.defineProperty(t,r,{...o,value:s})}},Vi=t=>new Promise((e,r)=>{t.on("exit",(o,s)=>{e({exitCode:o,signal:s})}),t.on("error",o=>{r(o)}),t.stdin&&t.stdin.on("error",o=>{r(o)})}),oo=(t,e=[])=>Array.isArray(e)?[t,...e]:[t],Xi=/^[\w.-]+$/,Qi=/"/g,Zi=t=>typeof t!="string"||Xi.test(t)?t:`"${t.replace(Qi,'\\"')}"`,ea=(t,e)=>oo(t,e).join(" "),ta=(t,e)=>oo(t,e).map(r=>Zi(r)).join(" "),ra=vn("execa").enabled,Ze=(t,e)=>String(t).padStart(e,"0"),oa=()=>{const t=new Date;return`${Ze(t.getHours(),2)}:${Ze(t.getMinutes(),2)}:${Ze(t.getSeconds(),2)}.${Ze(t.getMilliseconds(),3)}`},na=(t,{verbose:e})=>{e&&ae.stderr.write(`[${oa()}] ${t}
8
- `)},sa=1e3*1e3*100,ia=({env:t,extendEnv:e,preferLocal:r,localDir:o,execPath:s})=>{const n=e?{...ae.env,...t}:t;return r?zs({env:n,cwd:o,execPath:s}):n},aa=(t,e,r={})=>{const o=Gs._parse(t,e,r);return t=o.command,e=o.args,r=o.options,r={maxBuffer:sa,buffer:!0,stripFinalNewline:!0,extendEnv:!0,preferLocal:!1,localDir:r.cwd||ae.cwd(),execPath:ae.execPath,encoding:"utf8",reject:!0,cleanup:!0,all:!1,windowsHide:!0,verbose:ra,...r},r.env=ia(r),r.stdio=di(r),ae.platform==="win32"&&ue.basename(t,".exe")==="cmd"&&e.unshift("/q"),{file:t,args:e,options:r,parsed:o}},Dt=(t,e,r)=>typeof e!="string"&&!dn.isBuffer(e)?r===void 0?void 0:"":t.stripFinalNewline?Hs(e):e;function ne(t,e,r){const o=aa(t,e,r),s=ea(t,e),n=ta(t,e);na(n,o.options),Si(o.options);let i;try{i=mr.spawn(o.file,o.args,o.options)}catch(f){const h=new mr.ChildProcess,g=Promise.reject(qr({error:f,stdout:"",stderr:"",all:"",command:s,escapedCommand:n,parsed:o,timedOut:!1,isCanceled:!1,killed:!1}));return ro(h,g),h}const c=Vi(i),l=xi(i,o.options,c),u=Ii(i,o.options,l),m={isCanceled:!1};i.kill=bi.bind(null,i.kill.bind(i)),i.cancel=ki.bind(null,i,m);const d=zr(async()=>{const[{error:f,exitCode:h,signal:g,timedOut:y},w,v,P]=await Yi(i,o.options,u),A=Dt(o.options,w),b=Dt(o.options,v),k=Dt(o.options,P);if(f||h!==0||g!==null){const E=qr({error:f,exitCode:h,signal:g,stdout:A,stderr:b,all:k,command:s,escapedCommand:n,parsed:o,timedOut:y,isCanceled:m.isCanceled||(o.options.signal?o.options.signal.aborted:!1),killed:i.killed});if(!o.options.reject)return E;throw E}return{command:s,escapedCommand:n,exitCode:0,stdout:A,stderr:b,all:k,failed:!1,timedOut:!1,isCanceled:!1,killed:!1}});return Ki(i,o.options),i.all=Wi(i,o.options),Ri(i),ro(i,d),i}class T{static create(e,r){return new e(r)}}const{hasOwnProperty:_t}=Object.prototype,et=typeof process<"u"&&process.platform==="win32"?`\r
7
+ `);return w?(o.originalMessage=o.message,o.message=P):o=new Error(P),o.shortMessage=v,o.command=i,o.escapedCommand=c,o.exitCode=n,o.signal=s,o.signalDescription=f,o.stdout=t,o.stderr=e,o.cwd=d,r!==void 0&&(o.all=r),"bufferedData"in o&&delete o.bufferedData,o.failed=!0,o.timedOut=!!l,o.isCanceled=u,o.killed=m&&!l,o},Ve=["stdin","stdout","stderr"],ui=t=>Ve.some(e=>t[e]!==void 0),di=t=>{if(!t)return;const{stdio:e}=t;if(e===void 0)return Ve.map(o=>t[o]);if(ui(t))throw new Error(`It's not possible to provide \`stdio\` in combination with one of ${Ve.map(o=>`\`${o}\``).join(", ")}`);if(typeof e=="string")return e;if(!Array.isArray(e))throw new TypeError(`Expected \`stdio\` to be of type \`string\` or \`Array\`, got \`${typeof e}\``);const r=Math.max(e.length,Ve.length);return Array.from({length:r},(o,s)=>e[s])};var ge={exports:{}},Xe={exports:{}};Xe.exports;var Jr;function mi(){return Jr||(Jr=1,function(t){t.exports=["SIGABRT","SIGALRM","SIGHUP","SIGINT","SIGTERM"],process.platform!=="win32"&&t.exports.push("SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT"),process.platform==="linux"&&t.exports.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT","SIGUNUSED")}(Xe)),Xe.exports}var D=F.process;const de=function(t){return t&&typeof t=="object"&&typeof t.removeListener=="function"&&typeof t.emit=="function"&&typeof t.reallyExit=="function"&&typeof t.listeners=="function"&&typeof t.kill=="function"&&typeof t.pid=="number"&&typeof t.on=="function"};if(!de(D))ge.exports=function(){return function(){}};else{var fi=pr,xe=mi(),pi=/^win/i.test(D.platform),Qe=hr;typeof Qe!="function"&&(Qe=Qe.EventEmitter);var G;D.__signal_exit_emitter__?G=D.__signal_exit_emitter__:(G=D.__signal_exit_emitter__=new Qe,G.count=0,G.emitted={}),G.infinite||(G.setMaxListeners(1/0),G.infinite=!0),ge.exports=function(t,e){if(!de(F.process))return function(){};fi.equal(typeof t,"function","a callback must be provided for exit handler"),Se===!1&&Vr();var r="exit";e&&e.alwaysLast&&(r="afterexit");var o=function(){G.removeListener(r,t),G.listeners("exit").length===0&&G.listeners("afterexit").length===0&&St()};return G.on(r,t),o};var St=function(){!Se||!de(F.process)||(Se=!1,xe.forEach(function(e){try{D.removeListener(e,It[e])}catch{}}),D.emit=Mt,D.reallyExit=Xr,G.count-=1)};ge.exports.unload=St;var ye=function(e,r,o){G.emitted[e]||(G.emitted[e]=!0,G.emit(e,r,o))},It={};xe.forEach(function(t){It[t]=function(){if(de(F.process)){var r=D.listeners(t);r.length===G.count&&(St(),ye("exit",null,t),ye("afterexit",null,t),pi&&t==="SIGHUP"&&(t="SIGINT"),D.kill(D.pid,t))}}}),ge.exports.signals=function(){return xe};var Se=!1,Vr=function(){Se||!de(F.process)||(Se=!0,G.count+=1,xe=xe.filter(function(e){try{return D.on(e,It[e]),!0}catch{return!1}}),D.emit=gi,D.reallyExit=hi)};ge.exports.load=Vr;var Xr=D.reallyExit,hi=function(e){de(F.process)&&(D.exitCode=e||0,ye("exit",D.exitCode,null),ye("afterexit",D.exitCode,null),Xr.call(D,D.exitCode))},Mt=D.emit,gi=function(e,r){if(e==="exit"&&de(F.process)){r!==void 0&&(D.exitCode=r);var o=Mt.apply(this,arguments);return ye("exit",D.exitCode,null),ye("afterexit",D.exitCode,null),o}else return Mt.apply(this,arguments)}}var yi=ge.exports,wi=fe(yi);const vi=1e3*5,bi=(t,e="SIGTERM",r={})=>{const o=t(e);return Ci(t,e,r,o),o},Ci=(t,e,r,o)=>{if(!Pi(e,r,o))return;const s=Ei(r),n=setTimeout(()=>{t("SIGKILL")},s);n.unref&&n.unref()},Pi=(t,{forceKillAfterTimeout:e},r)=>$i(t)&&e!==!1&&r,$i=t=>t===hn.constants.signals.SIGTERM||typeof t=="string"&&t.toUpperCase()==="SIGTERM",Ei=({forceKillAfterTimeout:t=!0})=>{if(t===!0)return vi;if(!Number.isFinite(t)||t<0)throw new TypeError(`Expected the \`forceKillAfterTimeout\` option to be a non-negative integer, got \`${t}\` (${typeof t})`);return t},ki=(t,e)=>{t.kill()&&(e.isCanceled=!0)},Ai=(t,e,r)=>{t.kill(e),r(Object.assign(new Error("Timed out"),{timedOut:!0,signal:e}))},xi=(t,{timeout:e,killSignal:r="SIGTERM"},o)=>{if(e===0||e===void 0)return o;let s;const n=new Promise((c,l)=>{s=setTimeout(()=>{Ai(t,r,l)},e)}),i=o.finally(()=>{clearTimeout(s)});return Promise.race([n,i])},Si=({timeout:t})=>{if(t!==void 0&&(!Number.isFinite(t)||t<0))throw new TypeError(`Expected the \`timeout\` option to be a non-negative integer, got \`${t}\` (${typeof t})`)},Ii=async(t,{cleanup:e,detached:r},o)=>{if(!e||r)return o;const s=wi(()=>{t.kill()});return o.finally(()=>{s()})};function Qr(t){return t!==null&&typeof t=="object"&&typeof t.pipe=="function"}function Zr(t){return Qr(t)&&t.writable!==!1&&typeof t._write=="function"&&typeof t._writableState=="object"}const Mi=t=>t instanceof mn&&typeof t.then=="function",Rt=(t,e,r)=>{if(typeof r=="string")return t[e].pipe(gn(r)),t;if(Zr(r))return t[e].pipe(r),t;if(!Mi(r))throw new TypeError("The second argument must be a string, a stream or an Execa child process.");if(!Zr(r.stdin))throw new TypeError("The target child process's stdin must be available.");return t[e].pipe(r.stdin),r},Ri=t=>{t.stdout!==null&&(t.pipeStdout=Rt.bind(void 0,t,"stdout")),t.stderr!==null&&(t.pipeStderr=Rt.bind(void 0,t,"stderr")),t.all!==void 0&&(t.pipeAll=Rt.bind(void 0,t,"all"))};var Ie={exports:{}};const{PassThrough:Oi}=gt;var Li=t=>{t={...t};const{array:e}=t;let{encoding:r}=t;const o=r==="buffer";let s=!1;e?s=!(r||o):r=r||"utf8",o&&(r=null);const n=new Oi({objectMode:s});r&&n.setEncoding(r);let i=0;const c=[];return n.on("data",l=>{c.push(l),s?i=c.length:i+=l.length}),n.getBufferedValue=()=>e?c:o?Buffer.concat(c,i):c.join(""),n.getBufferedLength=()=>i,n};const{constants:Ni}=wn,Ti=gt,{promisify:Di}=gr,_i=Li,Fi=Di(Ti.pipeline);class eo extends Error{constructor(){super("maxBuffer exceeded"),this.name="MaxBufferError"}}async function Ot(t,e){if(!t)throw new Error("Expected a stream");e={maxBuffer:1/0,...e};const{maxBuffer:r}=e,o=_i(e);return await new Promise((s,n)=>{const i=c=>{c&&o.getBufferedLength()<=Ni.MAX_LENGTH&&(c.bufferedData=o.getBufferedValue()),n(c)};(async()=>{try{await Fi(t,o),s()}catch(c){i(c)}})(),o.on("data",()=>{o.getBufferedLength()>r&&i(new eo)})}),o.getBufferedValue()}Ie.exports=Ot,Ie.exports.buffer=(t,e)=>Ot(t,{...e,encoding:"buffer"}),Ie.exports.array=(t,e)=>Ot(t,{...e,array:!0}),Ie.exports.MaxBufferError=eo;var Gi=Ie.exports,to=fe(Gi);const{PassThrough:Hi}=gt;var ji=function(){var t=[],e=new Hi({objectMode:!0});return e.setMaxListeners(0),e.add=r,e.isEmpty=o,e.on("unpipe",s),Array.prototype.slice.call(arguments).forEach(r),e;function r(n){return Array.isArray(n)?(n.forEach(r),this):(t.push(n),n.once("end",s.bind(null,n)),n.once("error",e.emit.bind(e,"error")),n.pipe(e,{end:!1}),this)}function o(){return t.length==0}function s(n){t=t.filter(function(i){return i!==n}),!t.length&&e.readable&&e.end()}},Bi=fe(ji);const Ui=t=>{if(t!==void 0)throw new TypeError("The `input` and `inputFile` options cannot be both set.")},zi=({input:t,inputFile:e})=>typeof e!="string"?t:(Ui(t),yn(e)),Ki=(t,e)=>{const r=zi(e);r!==void 0&&(Qr(r)?r.pipe(t.stdin):t.stdin.end(r))},Wi=(t,{all:e})=>{if(!e||!t.stdout&&!t.stderr)return;const r=Bi();return t.stdout&&r.add(t.stdout),t.stderr&&r.add(t.stderr),r},Lt=async(t,e)=>{if(!(!t||e===void 0)){t.destroy();try{return await e}catch(r){return r.bufferedData}}},Nt=(t,{encoding:e,buffer:r,maxBuffer:o})=>{if(!(!t||!r))return e?to(t,{encoding:e,maxBuffer:o}):to.buffer(t,{maxBuffer:o})},Yi=async({stdout:t,stderr:e,all:r},{encoding:o,buffer:s,maxBuffer:n},i)=>{const c=Nt(t,{encoding:o,buffer:s,maxBuffer:n}),l=Nt(e,{encoding:o,buffer:s,maxBuffer:n}),u=Nt(r,{encoding:o,buffer:s,maxBuffer:n*2});try{return await Promise.all([i,c,l,u])}catch(m){return Promise.all([{error:m,signal:m.signal,timedOut:m.timedOut},Lt(t,c),Lt(e,l),Lt(r,u)])}},qi=(async()=>{})().constructor.prototype,Ji=["then","catch","finally"].map(t=>[t,Reflect.getOwnPropertyDescriptor(qi,t)]),ro=(t,e)=>{for(const[r,o]of Ji){const s=typeof e=="function"?(...n)=>Reflect.apply(o.value,e(),n):o.value.bind(e);Reflect.defineProperty(t,r,{...o,value:s})}},Vi=t=>new Promise((e,r)=>{t.on("exit",(o,s)=>{e({exitCode:o,signal:s})}),t.on("error",o=>{r(o)}),t.stdin&&t.stdin.on("error",o=>{r(o)})}),oo=(t,e=[])=>Array.isArray(e)?[t,...e]:[t],Xi=/^[\w.-]+$/,Qi=/"/g,Zi=t=>typeof t!="string"||Xi.test(t)?t:`"${t.replace(Qi,'\\"')}"`,ea=(t,e)=>oo(t,e).join(" "),ta=(t,e)=>oo(t,e).map(r=>Zi(r)).join(" "),ra=vn("execa").enabled,Ze=(t,e)=>String(t).padStart(e,"0"),oa=()=>{const t=new Date;return`${Ze(t.getHours(),2)}:${Ze(t.getMinutes(),2)}:${Ze(t.getSeconds(),2)}.${Ze(t.getMilliseconds(),3)}`},na=(t,{verbose:e})=>{e&&ae.stderr.write(`[${oa()}] ${t}
8
+ `)},sa=1e3*1e3*100,ia=({env:t,extendEnv:e,preferLocal:r,localDir:o,execPath:s})=>{const n=e?{...ae.env,...t}:t;return r?zs({env:n,cwd:o,execPath:s}):n},aa=(t,e,r={})=>{const o=Gs._parse(t,e,r);return t=o.command,e=o.args,r=o.options,r={maxBuffer:sa,buffer:!0,stripFinalNewline:!0,extendEnv:!0,preferLocal:!1,localDir:r.cwd||ae.cwd(),execPath:ae.execPath,encoding:"utf8",reject:!0,cleanup:!0,all:!1,windowsHide:!0,verbose:ra,...r},r.env=ia(r),r.stdio=di(r),ae.platform==="win32"&&ue.basename(t,".exe")==="cmd"&&e.unshift("/q"),{file:t,args:e,options:r,parsed:o}},Tt=(t,e,r)=>typeof e!="string"&&!dn.isBuffer(e)?r===void 0?void 0:"":t.stripFinalNewline?Hs(e):e;function ne(t,e,r){const o=aa(t,e,r),s=ea(t,e),n=ta(t,e);na(n,o.options),Si(o.options);let i;try{i=dr.spawn(o.file,o.args,o.options)}catch(f){const h=new dr.ChildProcess,g=Promise.reject(qr({error:f,stdout:"",stderr:"",all:"",command:s,escapedCommand:n,parsed:o,timedOut:!1,isCanceled:!1,killed:!1}));return ro(h,g),h}const c=Vi(i),l=xi(i,o.options,c),u=Ii(i,o.options,l),m={isCanceled:!1};i.kill=bi.bind(null,i.kill.bind(i)),i.cancel=ki.bind(null,i,m);const d=zr(async()=>{const[{error:f,exitCode:h,signal:g,timedOut:y},w,v,P]=await Yi(i,o.options,u),A=Tt(o.options,w),b=Tt(o.options,v),k=Tt(o.options,P);if(f||h!==0||g!==null){const E=qr({error:f,exitCode:h,signal:g,stdout:A,stderr:b,all:k,command:s,escapedCommand:n,parsed:o,timedOut:y,isCanceled:m.isCanceled||(o.options.signal?o.options.signal.aborted:!1),killed:i.killed});if(!o.options.reject)return E;throw E}return{command:s,escapedCommand:n,exitCode:0,stdout:A,stderr:b,all:k,failed:!1,timedOut:!1,isCanceled:!1,killed:!1}});return Ki(i,o.options),i.all=Wi(i,o.options),Ri(i),ro(i,d),i}class T{static create(e,r){return new e(r)}}const{hasOwnProperty:Dt}=Object.prototype,et=typeof process<"u"&&process.platform==="win32"?`\r
9
9
  `:`
10
- `,Ft=(t,e)=>{const r=[];let o="";typeof e=="string"?e={section:e,whitespace:!1}:(e=e||Object.create(null),e.whitespace=e.whitespace===!0);const s=e.whitespace?" = ":"=";for(const n of Object.keys(t)){const i=t[n];if(i&&Array.isArray(i))for(const c of i)o+=we(n+"[]")+s+we(c)+et;else i&&typeof i=="object"?r.push(n):o+=we(n)+s+we(i)+et}e.section&&o.length&&(o="["+we(e.section)+"]"+et+o);for(const n of r){const i=no(n).join("\\."),c=(e.section?e.section+".":"")+i,{whitespace:l}=e,u=Ft(t[n],{section:c,whitespace:l});o.length&&u.length&&(o+=et),o+=u}return o},no=t=>t.replace(/\1/g,"LITERAL\\1LITERAL").replace(/\\\./g,"").split(/\./).map(e=>e.replace(/\1/g,"\\.").replace(/\2LITERAL\\1LITERAL\2/g,"")),so=t=>{const e=Object.create(null);let r=e,o=null;const s=/^\[([^\]]*)\]$|^([^=]+)(=(.*))?$/i,n=t.split(/[\r\n]+/g);for(const c of n){if(!c||c.match(/^\s*[;#]/))continue;const l=c.match(s);if(!l)continue;if(l[1]!==void 0){if(o=tt(l[1]),o==="__proto__"){r=Object.create(null);continue}r=e[o]=e[o]||Object.create(null);continue}const u=tt(l[2]),m=u.length>2&&u.slice(-2)==="[]",a=m?u.slice(0,-2):u;if(a==="__proto__")continue;const d=l[3]?tt(l[4]):!0,f=d==="true"||d==="false"||d==="null"?JSON.parse(d):d;m&&(_t.call(r,a)?Array.isArray(r[a])||(r[a]=[r[a]]):r[a]=[]),Array.isArray(r[a])?r[a].push(f):r[a]=f}const i=[];for(const c of Object.keys(e)){if(!_t.call(e,c)||typeof e[c]!="object"||Array.isArray(e[c]))continue;const l=no(c);r=e;const u=l.pop(),m=u.replace(/\\\./g,".");for(const a of l)a!=="__proto__"&&((!_t.call(r,a)||typeof r[a]!="object")&&(r[a]=Object.create(null)),r=r[a]);r===e&&m===u||(r[m]=e[c],i.push(c))}for(const c of i)delete e[c];return e},io=t=>t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'"),we=t=>typeof t!="string"||t.match(/[=\r\n]/)||t.match(/^\[/)||t.length>1&&io(t)||t!==t.trim()?JSON.stringify(t):t.split(";").join("\\;").split("#").join("\\#"),tt=(t,e)=>{if(t=(t||"").trim(),io(t)){t.charAt(0)==="'"&&(t=t.slice(1,-1));try{t=JSON.parse(t)}catch{}}else{let r=!1,o="";for(let s=0,n=t.length;s<n;s++){const i=t.charAt(s);if(r)"\\;#".indexOf(i)!==-1?o+=i:o+="\\"+i,r=!1;else{if(";#".indexOf(i)!==-1)break;i==="\\"?r=!0:o+=i}}return r&&(o+="\\"),o.trim()}return t};var ca={parse:so,decode:so,stringify:Ft,encode:Ft,safe:we,unsafe:tt},ve=fe(ca);class $ extends Error{}const Gt=" ",ce=t=>{t instanceof Error&&(t instanceof $||(t.stack&&console.error(C.dim(t.stack.split(`
10
+ `,_t=(t,e)=>{const r=[];let o="";typeof e=="string"?e={section:e,whitespace:!1}:(e=e||Object.create(null),e.whitespace=e.whitespace===!0);const s=e.whitespace?" = ":"=";for(const n of Object.keys(t)){const i=t[n];if(i&&Array.isArray(i))for(const c of i)o+=we(n+"[]")+s+we(c)+et;else i&&typeof i=="object"?r.push(n):o+=we(n)+s+we(i)+et}e.section&&o.length&&(o="["+we(e.section)+"]"+et+o);for(const n of r){const i=no(n).join("\\."),c=(e.section?e.section+".":"")+i,{whitespace:l}=e,u=_t(t[n],{section:c,whitespace:l});o.length&&u.length&&(o+=et),o+=u}return o},no=t=>t.replace(/\1/g,"LITERAL\\1LITERAL").replace(/\\\./g,"").split(/\./).map(e=>e.replace(/\1/g,"\\.").replace(/\2LITERAL\\1LITERAL\2/g,"")),so=t=>{const e=Object.create(null);let r=e,o=null;const s=/^\[([^\]]*)\]$|^([^=]+)(=(.*))?$/i,n=t.split(/[\r\n]+/g);for(const c of n){if(!c||c.match(/^\s*[;#]/))continue;const l=c.match(s);if(!l)continue;if(l[1]!==void 0){if(o=tt(l[1]),o==="__proto__"){r=Object.create(null);continue}r=e[o]=e[o]||Object.create(null);continue}const u=tt(l[2]),m=u.length>2&&u.slice(-2)==="[]",a=m?u.slice(0,-2):u;if(a==="__proto__")continue;const d=l[3]?tt(l[4]):!0,f=d==="true"||d==="false"||d==="null"?JSON.parse(d):d;m&&(Dt.call(r,a)?Array.isArray(r[a])||(r[a]=[r[a]]):r[a]=[]),Array.isArray(r[a])?r[a].push(f):r[a]=f}const i=[];for(const c of Object.keys(e)){if(!Dt.call(e,c)||typeof e[c]!="object"||Array.isArray(e[c]))continue;const l=no(c);r=e;const u=l.pop(),m=u.replace(/\\\./g,".");for(const a of l)a!=="__proto__"&&((!Dt.call(r,a)||typeof r[a]!="object")&&(r[a]=Object.create(null)),r=r[a]);r===e&&m===u||(r[m]=e[c],i.push(c))}for(const c of i)delete e[c];return e},io=t=>t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'"),we=t=>typeof t!="string"||t.match(/[=\r\n]/)||t.match(/^\[/)||t.length>1&&io(t)||t!==t.trim()?JSON.stringify(t):t.split(";").join("\\;").split("#").join("\\#"),tt=(t,e)=>{if(t=(t||"").trim(),io(t)){t.charAt(0)==="'"&&(t=t.slice(1,-1));try{t=JSON.parse(t)}catch{}}else{let r=!1,o="";for(let s=0,n=t.length;s<n;s++){const i=t.charAt(s);if(r)"\\;#".indexOf(i)!==-1?o+=i:o+="\\"+i,r=!1;else{if(";#".indexOf(i)!==-1)break;i==="\\"?r=!0:o+=i}}return r&&(o+="\\"),o.trim()}return t};var ca={parse:so,decode:so,stringify:_t,encode:_t,safe:we,unsafe:tt},ve=fe(ca);class $ extends Error{}const Ft=" ",ce=t=>{t instanceof Error&&(t instanceof $||(t.stack&&console.error(C.dim(t.stack.split(`
11
11
  `).slice(1).join(`
12
12
  `))),console.error(`
13
- ${Gt}${C.dim(`aicommit2 v${xr}`)}`),console.error(`
14
- ${Gt}Please open a Bug report with the information above:`),console.error(`${Gt}https://github.com/tak-bro/aicommit2/issues/new/choose`)))},ao=t=>O.lstat(t).then(()=>!0,()=>!1),co=async t=>{try{await O.mkdir(t,{recursive:!0})}catch(e){if(e.code!=="EEXIST")throw e}},rt=t=>t&&`${t[0].toUpperCase()}${t.slice(1)}`,ot=(t,e)=>{const r=Math.ceil(t),o=Math.floor(e);return Math.floor(Math.random()*(o-r+1))+r},la=(t,e)=>t.disabled&&!e.disabled?1:!t.disabled&&e.disabled?-1:0,nt=t=>t.reduce((e,r)=>Array.isArray(r)?e.concat(nt(r)):e.concat(r),[]),lo=(t,e=5)=>t.replace(/[\n\r]/g,"").split(" ").slice(0,e).join(" "),ua=t=>{let e=0;for(let r=0;r<t.length;r++){const o=t.charCodeAt(r);e=(e<<5)-e+o,e=e&e}return Math.abs(e)},da=t=>{const e=t%360,r=65+t%15,o=45+t%10;return`hsl(${e}, ${r}%, ${o}%)`},ma=t=>{const[e,r,o]=t.match(/\d+/g).map((a,d)=>d===0?Number(a):Number(a)/100),s=(1-Math.abs(2*o-1))*r,n=s*(1-Math.abs(e/60%2-1)),i=o-s/2;let c,l,u;e<60?[c,l,u]=[s,n,0]:e<120?[c,l,u]=[n,s,0]:e<180?[c,l,u]=[0,s,n]:e<240?[c,l,u]=[0,n,s]:e<300?[c,l,u]=[n,0,s]:[c,l,u]=[s,0,n];const m=a=>{const d=Math.round((a+i)*255).toString(16);return d.length===1?"0"+d:d};return`#${m(c)}${m(l)}${m(u)}`},fa=t=>{const e=ua(t),r=da(e);return{primary:ma(r),secondary:"#FFFFFF"}},pa=t=>{try{return{ok:!0,data:JSON.parse(t)}}catch(e){return{ok:!1,error:e}}},st=t=>{if(!t||typeof t!="string")return"";if(S.isAbsolute(t))return S.resolve(t);if(Re){const e=S.dirname(Re),r=S.join(e,t);return S.resolve(r)}else return""},ha=["","conventional","gitmoji"],Ht="http://localhost:11434",{hasOwnProperty:ga}=Object.prototype,jt=(t,e)=>ga.call(t,e),be=["OPENAI","OLLAMA","HUGGINGFACE","GEMINI","ANTHROPIC","MISTRAL","CODESTRAL","COHERE","GROQ","PERPLEXITY","DEEPSEEK","GITHUB_MODELS"],uo=t=>{const e=ze.platform(),r=ze.homedir();let o,s;switch(t){case"config":o=process.env.XDG_CONFIG_HOME;break;case"data":o=process.env.XDG_DATA_HOME;break;case"cache":o=process.env.XDG_CACHE_HOME;break;case"state":o=process.env.XDG_STATE_HOME;break;default:o=void 0}if(e==="darwin")t==="cache"?s=S.join(r,"Library","Caches"):s=S.join(r,"Application Support");else if(e==="win32")s=process.env.LOCALAPPDATA||r;else switch(t){case"config":s=S.join(r,".config");break;case"data":s=S.join(r,".local","share");break;case"cache":s=S.join(r,".cache");break;case"state":s=S.join(r,".local","state");break;default:s=r}return o||s},ya=S.join(uo("config"),"aicommit2"),ee=S.join(uo("state"),"aicommit2","logs"),mo=S.join(ya,"config.ini"),fo=S.join(ee,"aicommit2-%DATE%.log"),po=S.join(ee,"exceptions-%DATE%.log"),wa=t=>{const e=Object.keys(t),r=new Set([...be,...e.filter(o=>/^[A-Z][A-Z0-9_]*$/.test(o))]);return Array.from(r)},x=(t,e,r)=>{if(!e)throw new $(`Invalid config property ${t}: ${r}`)},p={systemPrompt(t){return t||""},systemPromptPath(t){return t||""},codeReviewPromptPath(t){return t||""},timeout(t){if(!t)return 1e4;x("timeout",/^\d+$/.test(t),"Must be an integer");const e=Number(t);return x("timeout",e>=500,"Must be greater than 500ms"),e},temperature(t){if(!t)return .7;x("temperature",/^(2|\d)(\.\d{1,2})?$/.test(t),"Must be decimal between 0 and 2");const e=Number(t);return x("temperature",e>0,"Must be greater than 0"),x("temperature",e<=2,"Must be less than or equal to 2"),e},maxTokens(t){return t?(x("maxTokens",/^\d+$/.test(t),"Must be an integer"),Number(t)):1024},logging(t){return typeof t=="boolean"?t:t==null?!0:(x("logging",/^(?:true|false)$/.test(t),"Must be a boolean(true or false)"),t==="true")},logLevel(t){return t?(x("logLevel",/^(?:error|warn|info|http|verbose|debug|silly)$/.test(t),"Must be a valid log level (error, warn, info, http, verbose, debug, silly)"),t):"info"},logFilePath(t){return t||fo},exceptionLogFilePath(t){return t||po},locale(t){return t?(x("locale",t,"Cannot be empty"),x("locale",/^[a-z-]+$/i.test(t),"Must be a valid locale (letters and dashes/underscores). You can consult the list of codes in: https://wikipedia.org/wiki/List_of_ISO_639-1_codes"),t):"en"},generate(t){if(!t)return 1;x("generate",/^\d+$/.test(t),"Must be an integer");const e=Number(t);return x("generate",e>0,"Must be greater than 0"),x("generate",e<=5,"Must be less or equal to 5"),e},type(t){return t?(x("type",ha.includes(t),"Invalid commit type"),t):"conventional"},maxLength(t){if(!t)return 50;x("maxLength",/^\d+$/.test(t),"Must be an integer");const e=Number(t);return x("maxLength",e>=20,"Must be greater than 20 characters"),e},includeBody(t){return typeof t=="boolean"?t:t==null?!1:(x("includeBody",/^(?:true|false)$/.test(t),"Must be a boolean(true or false)"),t==="true")},exclude:t=>t?(typeof t=="string"?t?.split(","):t).map(r=>r.trim()).filter(r=>!!r&&r.length>0):[],topP:t=>{if(!t)return .9;x("topP",/^(1|\d)(\.\d{1,2})?$/.test(t),"Must be decimal between 0 and 1");const e=Number(t);return x("topP",e>0,"Must be greater than 0"),x("topP",e<=1,"Must be less than or equal to 1"),e},codeReview(t){return typeof t=="boolean"?t:t==null?!1:(x("codeReview",/^(?:true|false)$/.test(t),"Must be a boolean(true or false)"),t==="true")},disabled(t){return typeof t=="boolean"?t:t==null?!1:(x("disabled",/^(?:true|false)$/.test(t),"Must be a boolean(true or false)"),t==="true")},watchMode(t){return typeof t=="boolean"?t:t==null?!1:(x("watchMode",/^(?:true|false)$/.test(t),"Must be a boolean(true or false)"),t==="true")}},Me={OPENAI:{key:t=>t||"",envKey:t=>t||"",model:t=>t?(typeof t=="string"?t?.split(","):t).map(r=>r.trim()).filter(r=>!!r&&r.length>0):["gpt-4o-mini"],url:t=>t?(x("OPENAI.url",/^https?:\/\//.test(t),"Must be a valid URL"),t):"https://api.openai.com",path:t=>t||"/v1/chat/completions",proxy:t=>t||"",topP:p.topP,systemPrompt:p.systemPrompt,systemPromptPath:p.systemPromptPath,codeReviewPromptPath:p.codeReviewPromptPath,timeout:p.timeout,temperature:p.temperature,maxTokens:p.maxTokens,logging:p.logging,locale:p.locale,generate:p.generate,type:p.type,maxLength:p.maxLength,includeBody:p.includeBody,codeReview:p.codeReview,disabled:p.disabled,watchMode:p.watchMode},HUGGINGFACE:{cookie:t=>t||"",model:t=>t?(typeof t=="string"?t?.split(","):t).map(r=>r.trim()).filter(r=>!!r&&r.length>0):["CohereForAI/c4ai-command-r-plus"],systemPrompt:p.systemPrompt,systemPromptPath:p.systemPromptPath,codeReviewPromptPath:p.codeReviewPromptPath,timeout:p.timeout,temperature:p.temperature,maxTokens:p.maxTokens,topP:p.topP,logging:p.logging,locale:p.locale,generate:p.generate,type:p.type,maxLength:p.maxLength,includeBody:p.includeBody,codeReview:p.codeReview,disabled:p.disabled,watchMode:p.watchMode},GEMINI:{key:t=>t||"",envKey:t=>t||"",model:t=>t?(typeof t=="string"?t?.split(","):t).map(r=>r.trim()).filter(r=>!!r&&r.length>0):["gemini-2.0-flash"],systemPrompt:p.systemPrompt,systemPromptPath:p.systemPromptPath,codeReviewPromptPath:p.codeReviewPromptPath,temperature:p.temperature,maxTokens:p.maxTokens,logging:p.logging,locale:p.locale,generate:p.generate,type:p.type,maxLength:p.maxLength,includeBody:p.includeBody,topP:p.topP,codeReview:p.codeReview,disabled:p.disabled,watchMode:p.watchMode},ANTHROPIC:{key:t=>t||"",envKey:t=>t||"",model:t=>t?(typeof t=="string"?t?.split(","):t).map(r=>r.trim()).filter(r=>!!r&&r.length>0):["claude-3-5-haiku-20241022"],systemPrompt:p.systemPrompt,systemPromptPath:p.systemPromptPath,codeReviewPromptPath:p.codeReviewPromptPath,temperature:p.temperature,maxTokens:p.maxTokens,logging:p.logging,locale:p.locale,generate:p.generate,type:p.type,maxLength:p.maxLength,includeBody:p.includeBody,topP:p.topP,codeReview:p.codeReview,disabled:p.disabled,watchMode:p.watchMode},MISTRAL:{key:t=>t||"",envKey:t=>t||"",model:t=>t?(typeof t=="string"?t?.split(","):t).map(r=>r.trim()).filter(r=>!!r&&r.length>0):["mistral-small-latest"],systemPrompt:p.systemPrompt,systemPromptPath:p.systemPromptPath,codeReviewPromptPath:p.codeReviewPromptPath,timeout:p.timeout,temperature:p.temperature,maxTokens:p.maxTokens,logging:p.logging,locale:p.locale,generate:p.generate,type:p.type,maxLength:p.maxLength,includeBody:p.includeBody,topP:p.topP,codeReview:p.codeReview,disabled:p.disabled,watchMode:p.watchMode},CODESTRAL:{key:t=>t||"",envKey:t=>t||"",model:t=>t?(typeof t=="string"?t?.split(","):t).map(r=>r.trim()).filter(r=>!!r&&r.length>0):["codestral-latest"],topP:p.topP,systemPrompt:p.systemPrompt,systemPromptPath:p.systemPromptPath,codeReviewPromptPath:p.codeReviewPromptPath,timeout:p.timeout,temperature:p.temperature,maxTokens:p.maxTokens,logging:p.logging,locale:p.locale,generate:p.generate,type:p.type,maxLength:p.maxLength,includeBody:p.includeBody,codeReview:p.codeReview,disabled:p.disabled,watchMode:p.watchMode},OLLAMA:{model:t=>t?(typeof t=="string"?t?.split(","):t).map(r=>r.trim()).filter(r=>!!r&&r.length>0):[],host:t=>t?(x("OLLAMA.host",/^https?:\/\//.test(t),"Must be a valid URL"),t):Ht,timeout:t=>{if(!t)return 1e5;x("OLLAMA.timeout",/^\d+$/.test(t),"Must be an integer");const e=Number(t);return x("OLLAMA.timeout",e>=500,"Must be greater than 500ms"),e},auth:t=>t||"",key:t=>t||"",envKey:t=>t||"",numCtx:t=>{if(!t)return 2048;x("OLLAMA.numCtx",/^\d+$/.test(t),"Must be an integer");const e=Number(t);return x("OLLAMA.numCtx",e>=2048,"Must be greater than 2048"),e},systemPrompt:p.systemPrompt,systemPromptPath:p.systemPromptPath,codeReviewPromptPath:p.codeReviewPromptPath,temperature:p.temperature,maxTokens:p.maxTokens,logging:p.logging,locale:p.locale,generate:p.generate,type:p.type,maxLength:p.maxLength,includeBody:p.includeBody,topP:p.topP,codeReview:p.codeReview,disabled:p.disabled,watchMode:p.watchMode},COHERE:{key:t=>t||"",envKey:t=>t||"",model:t=>t?(typeof t=="string"?t?.split(","):t).map(r=>r.trim()).filter(r=>!!r&&r.length>0):["command-r"],systemPrompt:p.systemPrompt,systemPromptPath:p.systemPromptPath,codeReviewPromptPath:p.codeReviewPromptPath,temperature:p.temperature,maxTokens:p.maxTokens,logging:p.logging,locale:p.locale,generate:p.generate,type:p.type,maxLength:p.maxLength,includeBody:p.includeBody,topP:p.topP,codeReview:p.codeReview,disabled:p.disabled,watchMode:p.watchMode},GROQ:{key:t=>t||"",envKey:t=>t||"",model:t=>t?(typeof t=="string"?t?.split(","):t).map(r=>r.trim()).filter(r=>!!r&&r.length>0):["llama-3.3-70b-versatile"],systemPrompt:p.systemPrompt,systemPromptPath:p.systemPromptPath,codeReviewPromptPath:p.codeReviewPromptPath,timeout:p.timeout,temperature:p.temperature,maxTokens:p.maxTokens,logging:p.logging,locale:p.locale,generate:p.generate,type:p.type,maxLength:p.maxLength,includeBody:p.includeBody,topP:p.topP,codeReview:p.codeReview,disabled:p.disabled,watchMode:p.watchMode},PERPLEXITY:{key:t=>t||"",envKey:t=>t||"",model:t=>t?(typeof t=="string"?t?.split(","):t).map(r=>r.trim()).filter(r=>!!r&&r.length>0):["sonar"],topP:p.topP,systemPrompt:p.systemPrompt,systemPromptPath:p.systemPromptPath,codeReviewPromptPath:p.codeReviewPromptPath,timeout:p.timeout,temperature:p.temperature,maxTokens:p.maxTokens,logging:p.logging,locale:p.locale,generate:p.generate,type:p.type,maxLength:p.maxLength,includeBody:p.includeBody,codeReview:p.codeReview,disabled:p.disabled,watchMode:p.watchMode},DEEPSEEK:{key:t=>t||"",envKey:t=>t||"",model:t=>t?(typeof t=="string"?t?.split(","):t).map(r=>r.trim()).filter(r=>!!r&&r.length>0):["deepseek-coder"],topP:p.topP,systemPrompt:p.systemPrompt,systemPromptPath:p.systemPromptPath,codeReviewPromptPath:p.codeReviewPromptPath,timeout:p.timeout,temperature:p.temperature,maxTokens:p.maxTokens,logging:p.logging,locale:p.locale,generate:p.generate,type:p.type,maxLength:p.maxLength,includeBody:p.includeBody,codeReview:p.codeReview,disabled:p.disabled,watchMode:p.watchMode},GITHUB_MODELS:{key:t=>t||"",envKey:t=>t||"",model:t=>t?(typeof t=="string"?t?.split(","):t).map(r=>r.trim()).filter(r=>!!r&&r.length>0):["gpt-4o-mini"],systemPrompt:p.systemPrompt,systemPromptPath:p.systemPromptPath,codeReviewPromptPath:p.codeReviewPromptPath,timeout:p.timeout,temperature:p.temperature,maxTokens:p.maxTokens,logging:p.logging,locale:p.locale,generate:p.generate,type:p.type,maxLength:p.maxLength,includeBody:p.includeBody,topP:p.topP,codeReview:p.codeReview,disabled:p.disabled,watchMode:p.watchMode}};let Re;const va=(t=[])=>{const e={};for(const r of t)if(r.startsWith("--")){const[o,s]=r.slice(2).split("="),[n,i]=o.split(".");n&&i&&n in Me?(e[n]||(e[n]={}),e[n][i]=s):e[o]=s}return e},ba=()=>{const t=ze.homedir(),e=process.env.AICOMMIT_CONFIG_PATH,r=mo,o=S.join(t,".aicommit2");return[e,r,o].filter(s=>!!s)},Ce=async()=>{const t=ba();for(const e of t)if(await ao(e))return e;return mo},Oe=async()=>{const t=await Ce();Re=t;try{const e=await O.readFile(t,"utf8");return ve.parse(e)}catch(e){return e.code==="ENOENT"?(Re=void 0,{}):(console.error(`Error reading config file ${t}:`,e),Re=void 0,{})}},Pe=async(t,e=[])=>{const r=await Oe(),o=va(e),s={...t,...o},n={},i=wa(r),c={};for(const u of i){const a=r[u]?.envKey||`${u}_API_KEY`,d=process.env[a];d&&(c[u]={key:d})}const l=(u,m)=>{const a=s[`${u}.${m}`]??s[u]?.[m],d=c[u]?.[m],f=r[u]?.[m],h=s[m]??r[m];return a!==void 0?a:d!==void 0?d:f!==void 0?f:h};for(const[u,m]of Object.entries(p)){const a=s[u]??r[u];n[u]=m(a)}for(const u of i){n[u]={};const m=Me[u]||it(u);for(const[a,d]of Object.entries(m)){const f=l(u,a);n[u][a]=d(f)}}return n},Bt=async t=>{const e=await Oe();for(const[s,n]of t){const[i,c]=s.split(".");if(!c){const m=p[s];if(!m)throw new $(`Invalid config property: ${s}`);e[s]=m(n);continue}if(e[i]||(e[i]={}),be.includes(i)){const m=Me[i][c];if(!m)throw new $(`Invalid config property: ${s}`);e[i][c]=m(n);continue}if(!/^[A-Z][A-Z0-9_]*$/.test(i))throw new $(`Invalid service name: ${i}. Service names must be uppercase letters, numbers, and underscores.`);const u=it(i);if(!u[c])throw new $(`Invalid config property for custom service: ${s}`);try{e[i][c]=u[c](n)}catch(m){throw m instanceof $?m:new $(`Invalid value for ${s}: ${m.message}`)}}const r=await Ce(),o=S.dirname(r);await O.mkdir(o,{recursive:!0}),await O.writeFile(r,ve.stringify(e),"utf8")},Ca=async t=>{const e=await Oe();for(const[s,n]of t){const[i,c]=s.split("."),l=e[i];if(c==="model"){l||(e[i]={});const m=e[i][c]||[],a=typeof n=="string"?n.split(",").map(d=>d.trim()).filter(d=>!!d):n;e[i][c]=nt([...m,...a]);continue}if(l&&l.compatible===!0){l||(e[i]={});const m=it(i);if(!m[c])throw new $(`Invalid config property: ${s}`);try{e[i][c]=m[c](n)}catch(a){throw a instanceof $?a:new $(`Invalid value for ${s}: ${a.message}`)}continue}if(i in Me){l||(e[i]={});const m=Me[i][c];if(!m)throw new $(`Invalid config property: ${s}`);e[i][c]=m(n)}else{const m=it(i);if(!m[c])throw new $(`Invalid config property: ${s}`);e[i]||(e[i]={}),e[i][c]=m[c](n)}}const r=await Ce(),o=S.dirname(r);await O.mkdir(o,{recursive:!0}),await O.writeFile(r,ve.stringify(e),"utf8")},Pa=async()=>{const t=await Oe();console.log(ve.stringify(t))},$a=async()=>{console.log(await Ce())},it=t=>({compatible:e=>typeof e=="boolean"?e:e==null?!1:(x("compatible",/^(?:true|false)$/.test(e),"Must be a boolean(true or false)"),e==="true"),stream:e=>typeof e=="boolean"?e:e==null?!1:(x("stream",/^(?:true|false)$/.test(e),"Must be a boolean(true or false)"),e==="true"),url:e=>e?(x(`${t}.url`,/^https?:\/\//.test(e),"Must be a valid URL"),e):"",path:e=>e||"",key:e=>e||"",envKey:e=>e||"",model:e=>e?(typeof e=="string"?e?.split(","):e).map(o=>o.trim()).filter(o=>!!o&&o.length>0):[],systemPrompt:p.systemPrompt,systemPromptPath:p.systemPromptPath,codeReviewPromptPath:p.codeReviewPromptPath,timeout:p.timeout,temperature:p.temperature,maxTokens:p.maxTokens,logging:p.logging,locale:p.locale,generate:p.generate,type:p.type,maxLength:p.maxLength,includeBody:p.includeBody,topP:p.topP,codeReview:p.codeReview,disabled:p.disabled,watchMode:p.watchMode}),Le=new Map,me=(t,e,r)=>{const o=$r(0).update(e).digest("hex").substring(0,8),s=`${t}_${o}_${r}`;if(Le.has(s))return Le.get(s);const n=new Date,i=Aa(n,t,e,r),c=`${ee}/${i}`,l=U.createLogger({level:"info",format:U.format.combine(U.format.timestamp({format:"YYYY-MM-DDTHH:mm:ss.SSSZ"}),U.format.printf(({timestamp:u,level:m,message:a,...d})=>d&&Object.keys(d).length>0?`[${u}] ${m}: ${a} ${JSON.stringify(d,null,2)}`:`[${u}] ${m}: ${a}`)),transports:[new U.transports.File({filename:c})]});return l.info(`=== ${t.toUpperCase()} AI SERVICE LOG ===`),l.info(`Diff Hash: ${o}`),l.info(`Request Type: ${r.toUpperCase()}`),l.info(`Start Time: ${n.toISOString()}`),l.info("=".repeat(50)),l.info(""),Le.set(s,l),l},Ea=t=>{const e={...t},r=["authorization","x-api-key","x-goog-api-key","api-key"];for(const o of r){const s=o.toLowerCase(),n=Object.keys(e).find(i=>i.toLowerCase()===s);n&&e[n]&&typeof e[n]=="string"&&(e[n].startsWith("Bearer ")?e[n]="Bearer [MASKED]":e[n]="[MASKED]")}return e},Y=(t,e,r,o,s,n,i=!0)=>{if(!i)return;const c=me(r,t,e);c.info(`Making request to ${r} API with model: ${o}`),c.info(`Request URL: ${s}`),c.info("Request headers:",Ea(n))},te=(t,e,r,o,s=!0)=>{if(!s)return;me(r,t,e).info("Request payload:",o)},q=(t,e,r,o,s,n=!0)=>{if(!n)return;const i=me(r,t,e);i.info("System prompt:",{prompt:o}),i.info("User prompt:",{prompt:s})},J=(t,e,r,o,s=!0)=>{if(!s)return;me(r,t,e).info("Response received:",o)},_=(t,e,r,o,s=!0)=>{if(!s)return;me(r,t,e).error("API request failed:",o)},K=(t,e,r,o,s,n=!0)=>{if(!n)return;const i=me(r,t,e);o?i.info(`Request completed successfully in ${o}ms`):i.info("Request completed successfully"),s&&i.info("Final processed response:",{response:s}),i.info(""),i.info("=".repeat(50)),i.info(`End Time: ${new Date().toISOString()}`),i.info("=== REQUEST COMPLETED ===")},ka=(t,e,r,o,s,n,i,c=!0)=>{if(!c)return;const l=me(r,t,e);i?l.error(`Request failed after ${n}ms:`,{error:i}):(l.info(`Request completed in ${n}ms`),l.info("Response:",{response:s})),K(t,e,r,n,s,c)},Aa=(t,e,r,o)=>{const{year:s,month:n,day:i,hours:c,minutes:l,seconds:u}=xa(t),a=$r(0).update(r).digest("hex").substring(0,8),d=e.toLowerCase().replace(/[^a-z0-9]/g,"").substring(0,20);return o==="review"?`${s}-${n}-${i}_${c}-${l}-${u}_${a}_${d}_review.log`:`${s}-${n}-${i}_${c}-${l}-${u}_${a}_${d}_commit.log`},xa=t=>{const e=t.getFullYear().toString(),r=(t.getMonth()+1).toString().padStart(2,"0"),o=t.getDate().toString().padStart(2,"0"),s=t.getHours().toString().padStart(2,"0"),n=t.getMinutes().toString().padStart(2,"0"),i=t.getSeconds().toString().padStart(2,"0");return{year:e,month:r,day:o,hours:s,minutes:n,seconds:i}},Ut=()=>{for(const[t,e]of Le.entries())try{e.close()}catch(r){console.error(`Failed to close logger ${t}:`,r)}Le.clear()};process.on("exit",Ut),process.on("SIGINT",()=>{Ut(),process.exit(0)}),process.on("SIGTERM",()=>{Ut(),process.exit(0)});let at;async function Sa(t){if(at){console.warn("Logger already initialized. Skipping re-initialization.");return}const e=t?.logLevel||"info",r=t?.logFilePath||fo,o=t?.exceptionLogFilePath||po,s=t?.logging??!0;await co(S.dirname(r)),await co(S.dirname(o));const n=[];s&&n.push(new U.transports.DailyRotateFile({filename:r,datePattern:"YYYY-MM-DD",zippedArchive:!0,maxSize:"20m",maxFiles:"14d",level:e,format:U.format.combine(U.format.timestamp(),U.format.printf(({level:i,message:c,timestamp:l})=>`[${l}] ${i}: ${c}`))})),at=U.createLogger({level:e,format:U.format.json(),transports:n,exceptionHandlers:s?[new U.transports.DailyRotateFile({filename:o,datePattern:"YYYY-MM-DD",zippedArchive:!0,maxSize:"20m",maxFiles:"14d",format:U.format.combine(U.format.timestamp(),U.format.json())})]:[],exitOnError:!1})}const $e=new Proxy({},{get:(t,e,r)=>{if(!at)throw new Error("Logger not initialized. Call initializeLogger() first.");return Reflect.get(at,e,r)}});class V{constructor(e){this.handleError$=r=>{const o=this.getDetailedErrorMessage(r),s=r.status?`HTTP ${r.status}: ${o}`:o;if(this.params.config.logging){const n=this.params.stagedDiff.diff,i=this.serviceName.replace(/\[|\]/g,"").trim();ka(n,"commit",i,"Error occurred","",void 0,s)}return $e.error(`${this.errorPrefix} ${s}`),r.stack&&$e.error(` ${r.stack}`),r.content&&$e.error(` Problematic content: ${r.content}`),r.originalError&&$e.error(` Original error: ${r.originalError}`),Ae({name:`${this.errorPrefix} ${s}`,value:s,isError:!0,disabled:!0})},this.serviceName="AI",this.errorPrefix="ERROR",this.colors={primary:""},this.params=e,this.logSessionId=e.logSessionId}getDetailedErrorMessage(e){const r=e.message||"";return r.includes("API key")||r.includes("api_key")?"Invalid API key. Check your API key configuration":r.includes("rate_limit")||r.includes("Rate limit")||r.includes("429")||r.includes("Too Many Requests")?"Rate limit exceeded. Wait a moment and try again, or upgrade your plan":r.includes("model")||r.includes("Model")?"Model not found or not accessible. Check if the model name is correct":r.includes("timeout")||r.includes("Timeout")?"Request timed out. Try again or increase the timeout setting":r.includes("network")||r.includes("connection")||r.includes("ECONNREFUSED")?"Network error. Check your internet connection and try again":r.includes("quota")||r.includes("usage")||r.includes("QUOTA_EXCEEDED")?"API quota exceeded. Check your usage limits":r.includes("401")||r.includes("Unauthorized")?"Authentication failed. Your API key may be invalid or expired":r.includes("403")||r.includes("Forbidden")?"Access denied. Your API key may not have permission for this model":r.includes("404")||r.includes("Not Found")?"Model or endpoint not found. Check your model configuration":r.includes("500")||r.includes("Internal Server Error")?"Server error. Try again later":r.includes("overloaded")||r.includes("capacity")||r.includes("SERVICE_UNAVAILABLE")||r.includes("unavailable")?"Service is temporarily unavailable. Try again in a few minutes":this.getServiceSpecificErrorMessage(e)||r||"Unknown error occurred"}getServiceSpecificErrorMessage(e){return null}cleanJsonCodeBlock(e){const r=/```(?:json|JSON)?\s*([\s\S]*?)\s*```/,o=e.match(r);return o?o[1].trim():e}parseMessage(e,r,o){const s=this.cleanJsonCodeBlock(e),n=/(\[\s*\{[\s\S]*?\}\s*\]|\{[\s\S]*?\})/,i=s.match(n);if(!i){const f=new Error("AI response did not contain a valid JSON object or array.");throw f.name="InvalidJsonResponse",f.content=e,f}const c=i[0],l=pa(c);if(!l.ok){const f=new Error("Failed to parse AI response as JSON");throw f.name="JsonParseError",f.content=c,f.originalError=l.error,f}const u=l.data,m=Array.isArray(u)?u:[u];if(!m.length||!m.every(f=>typeof f.subject=="string")){const f=new Error("AI response contained malformed commit message data.");throw f.name="MalformedCommitMessage",f.content=e,f}const d=m.map(f=>this.extractMessageAsType(f,r)).map(f=>({title:`${f.subject}`,value:`${f.subject}${f.body?`
13
+ ${Ft}${C.dim(`aicommit2 v${xr}`)}`),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`)))},ao=t=>O.lstat(t).then(()=>!0,()=>!1),co=async t=>{try{await O.mkdir(t,{recursive:!0})}catch(e){if(e.code!=="EEXIST")throw e}},rt=t=>t&&`${t[0].toUpperCase()}${t.slice(1)}`,ot=(t,e)=>{const r=Math.ceil(t),o=Math.floor(e);return Math.floor(Math.random()*(o-r+1))+r},la=(t,e)=>t.disabled&&!e.disabled?1:!t.disabled&&e.disabled?-1:0,nt=t=>t.reduce((e,r)=>Array.isArray(r)?e.concat(nt(r)):e.concat(r),[]),lo=(t,e=5)=>t.replace(/[\n\r]/g,"").split(" ").slice(0,e).join(" "),ua=t=>{let e=0;for(let r=0;r<t.length;r++){const o=t.charCodeAt(r);e=(e<<5)-e+o,e=e&e}return Math.abs(e)},da=t=>{const e=t%360,r=65+t%15,o=45+t%10;return`hsl(${e}, ${r}%, ${o}%)`},ma=t=>{const[e,r,o]=t.match(/\d+/g).map((a,d)=>d===0?Number(a):Number(a)/100),s=(1-Math.abs(2*o-1))*r,n=s*(1-Math.abs(e/60%2-1)),i=o-s/2;let c,l,u;e<60?[c,l,u]=[s,n,0]:e<120?[c,l,u]=[n,s,0]:e<180?[c,l,u]=[0,s,n]:e<240?[c,l,u]=[0,n,s]:e<300?[c,l,u]=[n,0,s]:[c,l,u]=[s,0,n];const m=a=>{const d=Math.round((a+i)*255).toString(16);return d.length===1?"0"+d:d};return`#${m(c)}${m(l)}${m(u)}`},fa=t=>{const e=ua(t),r=da(e);return{primary:ma(r),secondary:"#FFFFFF"}},pa=t=>{try{return{ok:!0,data:JSON.parse(t)}}catch(e){return{ok:!1,error:e}}},st=t=>{if(!t||typeof t!="string")return"";if(S.isAbsolute(t))return S.resolve(t);if(Re){const e=S.dirname(Re),r=S.join(e,t);return S.resolve(r)}else return""},ha=["","conventional","gitmoji"],Gt="http://localhost:11434",{hasOwnProperty:ga}=Object.prototype,Ht=(t,e)=>ga.call(t,e),be=["OPENAI","OLLAMA","HUGGINGFACE","GEMINI","ANTHROPIC","MISTRAL","CODESTRAL","COHERE","GROQ","PERPLEXITY","DEEPSEEK","GITHUB_MODELS"],uo=t=>{const e=ze.platform(),r=ze.homedir();let o,s;switch(t){case"config":o=process.env.XDG_CONFIG_HOME;break;case"data":o=process.env.XDG_DATA_HOME;break;case"cache":o=process.env.XDG_CACHE_HOME;break;case"state":o=process.env.XDG_STATE_HOME;break;default:o=void 0}if(e==="darwin")t==="cache"?s=S.join(r,"Library","Caches"):s=S.join(r,"Application Support");else if(e==="win32")s=process.env.LOCALAPPDATA||r;else switch(t){case"config":s=S.join(r,".config");break;case"data":s=S.join(r,".local","share");break;case"cache":s=S.join(r,".cache");break;case"state":s=S.join(r,".local","state");break;default:s=r}return o||s},ya=S.join(uo("config"),"aicommit2"),ee=S.join(uo("state"),"aicommit2","logs"),mo=S.join(ya,"config.ini"),fo=S.join(ee,"aicommit2-%DATE%.log"),po=S.join(ee,"exceptions-%DATE%.log"),wa=t=>{const e=Object.keys(t),r=new Set([...be,...e.filter(o=>/^[A-Z][A-Z0-9_]*$/.test(o))]);return Array.from(r)},x=(t,e,r)=>{if(!e)throw new $(`Invalid config property ${t}: ${r}`)},p={systemPrompt(t){return t||""},systemPromptPath(t){return t||""},codeReviewPromptPath(t){return t||""},timeout(t){if(!t)return 1e4;x("timeout",/^\d+$/.test(t),"Must be an integer");const e=Number(t);return x("timeout",e>=500,"Must be greater than 500ms"),e},temperature(t){if(!t)return .7;x("temperature",/^(2|\d)(\.\d{1,2})?$/.test(t),"Must be decimal between 0 and 2");const e=Number(t);return x("temperature",e>0,"Must be greater than 0"),x("temperature",e<=2,"Must be less than or equal to 2"),e},maxTokens(t){return t?(x("maxTokens",/^\d+$/.test(t),"Must be an integer"),Number(t)):1024},logging(t){return typeof t=="boolean"?t:t==null?!0:(x("logging",/^(?:true|false)$/.test(t),"Must be a boolean(true or false)"),t==="true")},logLevel(t){return t?(x("logLevel",/^(?:error|warn|info|http|verbose|debug|silly)$/.test(t),"Must be a valid log level (error, warn, info, http, verbose, debug, silly)"),t):"info"},logFilePath(t){return t||fo},exceptionLogFilePath(t){return t||po},locale(t){return t?(x("locale",t,"Cannot be empty"),x("locale",/^[a-z-]+$/i.test(t),"Must be a valid locale (letters and dashes/underscores). You can consult the list of codes in: https://wikipedia.org/wiki/List_of_ISO_639-1_codes"),t):"en"},generate(t){if(!t)return 1;x("generate",/^\d+$/.test(t),"Must be an integer");const e=Number(t);return x("generate",e>0,"Must be greater than 0"),x("generate",e<=5,"Must be less or equal to 5"),e},type(t){return t?(x("type",ha.includes(t),"Invalid commit type"),t):"conventional"},maxLength(t){if(!t)return 50;x("maxLength",/^\d+$/.test(t),"Must be an integer");const e=Number(t);return x("maxLength",e>=20,"Must be greater than 20 characters"),e},includeBody(t){return typeof t=="boolean"?t:t==null?!1:(x("includeBody",/^(?:true|false)$/.test(t),"Must be a boolean(true or false)"),t==="true")},exclude:t=>t?(typeof t=="string"?t?.split(","):t).map(r=>r.trim()).filter(r=>!!r&&r.length>0):[],topP:t=>{if(!t)return .9;x("topP",/^(1|\d)(\.\d{1,2})?$/.test(t),"Must be decimal between 0 and 1");const e=Number(t);return x("topP",e>0,"Must be greater than 0"),x("topP",e<=1,"Must be less than or equal to 1"),e},codeReview(t){return typeof t=="boolean"?t:t==null?!1:(x("codeReview",/^(?:true|false)$/.test(t),"Must be a boolean(true or false)"),t==="true")},disabled(t){return typeof t=="boolean"?t:t==null?!1:(x("disabled",/^(?:true|false)$/.test(t),"Must be a boolean(true or false)"),t==="true")},watchMode(t){return typeof t=="boolean"?t:t==null?!1:(x("watchMode",/^(?:true|false)$/.test(t),"Must be a boolean(true or false)"),t==="true")}},Me={OPENAI:{key:t=>t||"",envKey:t=>t||"",model:t=>t?(typeof t=="string"?t?.split(","):t).map(r=>r.trim()).filter(r=>!!r&&r.length>0):["gpt-4o-mini"],url:t=>t?(x("OPENAI.url",/^https?:\/\//.test(t),"Must be a valid URL"),t):"https://api.openai.com",path:t=>t||"/v1/chat/completions",proxy:t=>t||"",topP:p.topP,systemPrompt:p.systemPrompt,systemPromptPath:p.systemPromptPath,codeReviewPromptPath:p.codeReviewPromptPath,timeout:p.timeout,temperature:p.temperature,maxTokens:p.maxTokens,logging:p.logging,locale:p.locale,generate:p.generate,type:p.type,maxLength:p.maxLength,includeBody:p.includeBody,codeReview:p.codeReview,disabled:p.disabled,watchMode:p.watchMode},HUGGINGFACE:{cookie:t=>t||"",model:t=>t?(typeof t=="string"?t?.split(","):t).map(r=>r.trim()).filter(r=>!!r&&r.length>0):["CohereForAI/c4ai-command-r-plus"],systemPrompt:p.systemPrompt,systemPromptPath:p.systemPromptPath,codeReviewPromptPath:p.codeReviewPromptPath,timeout:p.timeout,temperature:p.temperature,maxTokens:p.maxTokens,topP:p.topP,logging:p.logging,locale:p.locale,generate:p.generate,type:p.type,maxLength:p.maxLength,includeBody:p.includeBody,codeReview:p.codeReview,disabled:p.disabled,watchMode:p.watchMode},GEMINI:{key:t=>t||"",envKey:t=>t||"",model:t=>t?(typeof t=="string"?t?.split(","):t).map(r=>r.trim()).filter(r=>!!r&&r.length>0):["gemini-2.0-flash"],systemPrompt:p.systemPrompt,systemPromptPath:p.systemPromptPath,codeReviewPromptPath:p.codeReviewPromptPath,temperature:p.temperature,maxTokens:p.maxTokens,logging:p.logging,locale:p.locale,generate:p.generate,type:p.type,maxLength:p.maxLength,includeBody:p.includeBody,topP:p.topP,codeReview:p.codeReview,disabled:p.disabled,watchMode:p.watchMode},ANTHROPIC:{key:t=>t||"",envKey:t=>t||"",model:t=>t?(typeof t=="string"?t?.split(","):t).map(r=>r.trim()).filter(r=>!!r&&r.length>0):["claude-3-5-haiku-20241022"],systemPrompt:p.systemPrompt,systemPromptPath:p.systemPromptPath,codeReviewPromptPath:p.codeReviewPromptPath,temperature:p.temperature,maxTokens:p.maxTokens,logging:p.logging,locale:p.locale,generate:p.generate,type:p.type,maxLength:p.maxLength,includeBody:p.includeBody,topP:p.topP,codeReview:p.codeReview,disabled:p.disabled,watchMode:p.watchMode},MISTRAL:{key:t=>t||"",envKey:t=>t||"",model:t=>t?(typeof t=="string"?t?.split(","):t).map(r=>r.trim()).filter(r=>!!r&&r.length>0):["mistral-small-latest"],systemPrompt:p.systemPrompt,systemPromptPath:p.systemPromptPath,codeReviewPromptPath:p.codeReviewPromptPath,timeout:p.timeout,temperature:p.temperature,maxTokens:p.maxTokens,logging:p.logging,locale:p.locale,generate:p.generate,type:p.type,maxLength:p.maxLength,includeBody:p.includeBody,topP:p.topP,codeReview:p.codeReview,disabled:p.disabled,watchMode:p.watchMode},CODESTRAL:{key:t=>t||"",envKey:t=>t||"",model:t=>t?(typeof t=="string"?t?.split(","):t).map(r=>r.trim()).filter(r=>!!r&&r.length>0):["codestral-latest"],topP:p.topP,systemPrompt:p.systemPrompt,systemPromptPath:p.systemPromptPath,codeReviewPromptPath:p.codeReviewPromptPath,timeout:p.timeout,temperature:p.temperature,maxTokens:p.maxTokens,logging:p.logging,locale:p.locale,generate:p.generate,type:p.type,maxLength:p.maxLength,includeBody:p.includeBody,codeReview:p.codeReview,disabled:p.disabled,watchMode:p.watchMode},OLLAMA:{model:t=>t?(typeof t=="string"?t?.split(","):t).map(r=>r.trim()).filter(r=>!!r&&r.length>0):[],host:t=>t?(x("OLLAMA.host",/^https?:\/\//.test(t),"Must be a valid URL"),t):Gt,timeout:t=>{if(!t)return 1e5;x("OLLAMA.timeout",/^\d+$/.test(t),"Must be an integer");const e=Number(t);return x("OLLAMA.timeout",e>=500,"Must be greater than 500ms"),e},auth:t=>t||"",key:t=>t||"",envKey:t=>t||"",numCtx:t=>{if(!t)return 2048;x("OLLAMA.numCtx",/^\d+$/.test(t),"Must be an integer");const e=Number(t);return x("OLLAMA.numCtx",e>=2048,"Must be greater than 2048"),e},systemPrompt:p.systemPrompt,systemPromptPath:p.systemPromptPath,codeReviewPromptPath:p.codeReviewPromptPath,temperature:p.temperature,maxTokens:p.maxTokens,logging:p.logging,locale:p.locale,generate:p.generate,type:p.type,maxLength:p.maxLength,includeBody:p.includeBody,topP:p.topP,codeReview:p.codeReview,disabled:p.disabled,watchMode:p.watchMode},COHERE:{key:t=>t||"",envKey:t=>t||"",model:t=>t?(typeof t=="string"?t?.split(","):t).map(r=>r.trim()).filter(r=>!!r&&r.length>0):["command-r"],systemPrompt:p.systemPrompt,systemPromptPath:p.systemPromptPath,codeReviewPromptPath:p.codeReviewPromptPath,temperature:p.temperature,maxTokens:p.maxTokens,logging:p.logging,locale:p.locale,generate:p.generate,type:p.type,maxLength:p.maxLength,includeBody:p.includeBody,topP:p.topP,codeReview:p.codeReview,disabled:p.disabled,watchMode:p.watchMode},GROQ:{key:t=>t||"",envKey:t=>t||"",model:t=>t?(typeof t=="string"?t?.split(","):t).map(r=>r.trim()).filter(r=>!!r&&r.length>0):["llama-3.3-70b-versatile"],systemPrompt:p.systemPrompt,systemPromptPath:p.systemPromptPath,codeReviewPromptPath:p.codeReviewPromptPath,timeout:p.timeout,temperature:p.temperature,maxTokens:p.maxTokens,logging:p.logging,locale:p.locale,generate:p.generate,type:p.type,maxLength:p.maxLength,includeBody:p.includeBody,topP:p.topP,codeReview:p.codeReview,disabled:p.disabled,watchMode:p.watchMode},PERPLEXITY:{key:t=>t||"",envKey:t=>t||"",model:t=>t?(typeof t=="string"?t?.split(","):t).map(r=>r.trim()).filter(r=>!!r&&r.length>0):["sonar"],topP:p.topP,systemPrompt:p.systemPrompt,systemPromptPath:p.systemPromptPath,codeReviewPromptPath:p.codeReviewPromptPath,timeout:p.timeout,temperature:p.temperature,maxTokens:p.maxTokens,logging:p.logging,locale:p.locale,generate:p.generate,type:p.type,maxLength:p.maxLength,includeBody:p.includeBody,codeReview:p.codeReview,disabled:p.disabled,watchMode:p.watchMode},DEEPSEEK:{key:t=>t||"",envKey:t=>t||"",model:t=>t?(typeof t=="string"?t?.split(","):t).map(r=>r.trim()).filter(r=>!!r&&r.length>0):["deepseek-coder"],topP:p.topP,systemPrompt:p.systemPrompt,systemPromptPath:p.systemPromptPath,codeReviewPromptPath:p.codeReviewPromptPath,timeout:p.timeout,temperature:p.temperature,maxTokens:p.maxTokens,logging:p.logging,locale:p.locale,generate:p.generate,type:p.type,maxLength:p.maxLength,includeBody:p.includeBody,codeReview:p.codeReview,disabled:p.disabled,watchMode:p.watchMode},GITHUB_MODELS:{key:t=>t||"",envKey:t=>t||"",model:t=>t?(typeof t=="string"?t?.split(","):t).map(r=>r.trim()).filter(r=>!!r&&r.length>0):["gpt-4o-mini"],systemPrompt:p.systemPrompt,systemPromptPath:p.systemPromptPath,codeReviewPromptPath:p.codeReviewPromptPath,timeout:p.timeout,temperature:p.temperature,maxTokens:p.maxTokens,logging:p.logging,locale:p.locale,generate:p.generate,type:p.type,maxLength:p.maxLength,includeBody:p.includeBody,topP:p.topP,codeReview:p.codeReview,disabled:p.disabled,watchMode:p.watchMode}};let Re;const va=(t=[])=>{const e={};for(const r of t)if(r.startsWith("--")){const[o,s]=r.slice(2).split("="),[n,i]=o.split(".");n&&i&&n in Me?(e[n]||(e[n]={}),e[n][i]=s):e[o]=s}return e},ba=()=>{const t=ze.homedir(),e=process.env.AICOMMIT_CONFIG_PATH,r=mo,o=S.join(t,".aicommit2");return[e,r,o].filter(s=>!!s)},Ce=async()=>{const t=ba();for(const e of t)if(await ao(e))return e;return mo},Oe=async()=>{const t=await Ce();Re=t;try{const e=await O.readFile(t,"utf8");return ve.parse(e)}catch(e){return e.code==="ENOENT"?(Re=void 0,{}):(console.error(`Error reading config file ${t}:`,e),Re=void 0,{})}},Pe=async(t,e=[])=>{const r=await Oe(),o=va(e),s={...t,...o},n={},i=wa(r),c={};for(const u of i){const a=r[u]?.envKey||`${u}_API_KEY`,d=process.env[a];d&&(c[u]={key:d})}const l=(u,m)=>{const a=s[`${u}.${m}`]??s[u]?.[m],d=c[u]?.[m],f=r[u]?.[m],h=s[m]??r[m];return a!==void 0?a:d!==void 0?d:f!==void 0?f:h};for(const[u,m]of Object.entries(p)){const a=s[u]??r[u];n[u]=m(a)}for(const u of i){n[u]={};const m=Me[u]||it(u);for(const[a,d]of Object.entries(m)){const f=l(u,a);n[u][a]=d(f)}}return n},jt=async t=>{const e=await Oe();for(const[s,n]of t){const[i,c]=s.split(".");if(!c){const m=p[s];if(!m)throw new $(`Invalid config property: ${s}`);e[s]=m(n);continue}if(e[i]||(e[i]={}),be.includes(i)){const m=Me[i][c];if(!m)throw new $(`Invalid config property: ${s}`);e[i][c]=m(n);continue}if(!/^[A-Z][A-Z0-9_]*$/.test(i))throw new $(`Invalid service name: ${i}. Service names must be uppercase letters, numbers, and underscores.`);const u=it(i);if(!u[c])throw new $(`Invalid config property for custom service: ${s}`);try{e[i][c]=u[c](n)}catch(m){throw m instanceof $?m:new $(`Invalid value for ${s}: ${m.message}`)}}const r=await Ce(),o=S.dirname(r);await O.mkdir(o,{recursive:!0}),await O.writeFile(r,ve.stringify(e),"utf8")},Ca=async t=>{const e=await Oe();for(const[s,n]of t){const[i,c]=s.split("."),l=e[i];if(c==="model"){l||(e[i]={});const m=e[i][c]||[],a=typeof n=="string"?n.split(",").map(d=>d.trim()).filter(d=>!!d):n;e[i][c]=nt([...m,...a]);continue}if(l&&l.compatible===!0){l||(e[i]={});const m=it(i);if(!m[c])throw new $(`Invalid config property: ${s}`);try{e[i][c]=m[c](n)}catch(a){throw a instanceof $?a:new $(`Invalid value for ${s}: ${a.message}`)}continue}if(i in Me){l||(e[i]={});const m=Me[i][c];if(!m)throw new $(`Invalid config property: ${s}`);e[i][c]=m(n)}else{const m=it(i);if(!m[c])throw new $(`Invalid config property: ${s}`);e[i]||(e[i]={}),e[i][c]=m[c](n)}}const r=await Ce(),o=S.dirname(r);await O.mkdir(o,{recursive:!0}),await O.writeFile(r,ve.stringify(e),"utf8")},Pa=async()=>{const t=await Oe();console.log(ve.stringify(t))},$a=async()=>{console.log(await Ce())},it=t=>({compatible:e=>typeof e=="boolean"?e:e==null?!1:(x("compatible",/^(?:true|false)$/.test(e),"Must be a boolean(true or false)"),e==="true"),stream:e=>typeof e=="boolean"?e:e==null?!1:(x("stream",/^(?:true|false)$/.test(e),"Must be a boolean(true or false)"),e==="true"),url:e=>e?(x(`${t}.url`,/^https?:\/\//.test(e),"Must be a valid URL"),e):"",path:e=>e||"",key:e=>e||"",envKey:e=>e||"",model:e=>e?(typeof e=="string"?e?.split(","):e).map(o=>o.trim()).filter(o=>!!o&&o.length>0):[],systemPrompt:p.systemPrompt,systemPromptPath:p.systemPromptPath,codeReviewPromptPath:p.codeReviewPromptPath,timeout:p.timeout,temperature:p.temperature,maxTokens:p.maxTokens,logging:p.logging,locale:p.locale,generate:p.generate,type:p.type,maxLength:p.maxLength,includeBody:p.includeBody,topP:p.topP,codeReview:p.codeReview,disabled:p.disabled,watchMode:p.watchMode}),Le=new Map,me=(t,e,r)=>{const o=Pr(0).update(e).digest("hex").substring(0,8),s=`${t}_${o}_${r}`;if(Le.has(s))return Le.get(s);const n=new Date,i=Aa(n,t,e,r),c=`${ee}/${i}`,l=H.createLogger({level:"info",format:H.format.combine(H.format.timestamp({format:"YYYY-MM-DDTHH:mm:ss.SSSZ"}),H.format.printf(({timestamp:u,level:m,message:a,...d})=>d&&Object.keys(d).length>0?`[${u}] ${m}: ${a} ${JSON.stringify(d,null,2)}`:`[${u}] ${m}: ${a}`)),transports:[new H.transports.File({filename:c})]});return l.info(`=== ${t.toUpperCase()} AI SERVICE LOG ===`),l.info(`Diff Hash: ${o}`),l.info(`Request Type: ${r.toUpperCase()}`),l.info(`Start Time: ${n.toISOString()}`),l.info("=".repeat(50)),l.info(""),Le.set(s,l),l},Ea=t=>{const e={...t},r=["authorization","x-api-key","x-goog-api-key","api-key"];for(const o of r){const s=o.toLowerCase(),n=Object.keys(e).find(i=>i.toLowerCase()===s);n&&e[n]&&typeof e[n]=="string"&&(e[n].startsWith("Bearer ")?e[n]="Bearer [MASKED]":e[n]="[MASKED]")}return e},Y=(t,e,r,o,s,n,i=!0)=>{if(!i)return;const c=me(r,t,e);c.info(`Making request to ${r} API with model: ${o}`),c.info(`Request URL: ${s}`),c.info("Request headers:",Ea(n))},te=(t,e,r,o,s=!0)=>{if(!s)return;me(r,t,e).info("Request payload:",o)},q=(t,e,r,o,s,n=!0)=>{if(!n)return;const i=me(r,t,e);i.info("System prompt:",{prompt:o}),i.info("User prompt:",{prompt:s})},J=(t,e,r,o,s=!0)=>{if(!s)return;me(r,t,e).info("Response received:",o)},_=(t,e,r,o,s=!0)=>{if(!s)return;me(r,t,e).error("API request failed:",o)},K=(t,e,r,o,s,n=!0)=>{if(!n)return;const i=me(r,t,e);o?i.info(`Request completed successfully in ${o}ms`):i.info("Request completed successfully"),s&&i.info("Final processed response:",{response:s}),i.info(""),i.info("=".repeat(50)),i.info(`End Time: ${new Date().toISOString()}`),i.info("=== REQUEST COMPLETED ===")},ka=(t,e,r,o,s,n,i,c=!0)=>{if(!c)return;const l=me(r,t,e);i?l.error(`Request failed after ${n}ms:`,{error:i}):(l.info(`Request completed in ${n}ms`),l.info("Response:",{response:s})),K(t,e,r,n,s,c)},Aa=(t,e,r,o)=>{const{year:s,month:n,day:i,hours:c,minutes:l,seconds:u}=xa(t),a=Pr(0).update(r).digest("hex").substring(0,8),d=e.toLowerCase().replace(/[^a-z0-9]/g,"").substring(0,20);return o==="review"?`${s}-${n}-${i}_${c}-${l}-${u}_${a}_${d}_review.log`:`${s}-${n}-${i}_${c}-${l}-${u}_${a}_${d}_commit.log`},xa=t=>{const e=t.getFullYear().toString(),r=(t.getMonth()+1).toString().padStart(2,"0"),o=t.getDate().toString().padStart(2,"0"),s=t.getHours().toString().padStart(2,"0"),n=t.getMinutes().toString().padStart(2,"0"),i=t.getSeconds().toString().padStart(2,"0");return{year:e,month:r,day:o,hours:s,minutes:n,seconds:i}},Bt=()=>{for(const[t,e]of Le.entries())try{e.close()}catch(r){console.error(`Failed to close logger ${t}:`,r)}Le.clear()};process.on("exit",Bt),process.on("SIGINT",()=>{Bt(),process.exit(0)}),process.on("SIGTERM",()=>{Bt(),process.exit(0)});let at;async function Sa(t){if(at){console.warn("Logger already initialized. Skipping re-initialization.");return}const e=t?.logLevel||"info",r=t?.logFilePath||fo,o=t?.exceptionLogFilePath||po,s=t?.logging??!0;await co(S.dirname(r)),await co(S.dirname(o));const n=[];s?n.push(new H.transports.DailyRotateFile({filename:r,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:l})=>`[${l}] ${i}: ${c}`))})):n.push(new H.transports.Console({silent:!0})),at=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 $e=new Proxy({},{get:(t,e,r)=>{if(!at)throw new Error("Logger not initialized. Call initializeLogger() first.");return Reflect.get(at,e,r)}});class V{constructor(e){this.handleError$=r=>{const o=this.getDetailedErrorMessage(r),s=r.status?`HTTP ${r.status}: ${o}`:o;if(this.params.config.logging){const n=this.params.stagedDiff.diff,i=this.serviceName.replace(/\[|\]/g,"").trim();ka(n,"commit",i,"Error occurred","",void 0,s)}return $e.error(`${this.errorPrefix} ${s}`),r.stack&&$e.error(` ${r.stack}`),r.content&&$e.error(` Problematic content: ${r.content}`),r.originalError&&$e.error(` Original error: ${r.originalError}`),Ae({name:`${this.errorPrefix} ${s}`,value:s,isError:!0,disabled:!0})},this.serviceName="AI",this.errorPrefix="ERROR",this.colors={primary:""},this.params=e,this.logSessionId=e.logSessionId}getDetailedErrorMessage(e){const r=e.message||"";return r.includes("API key")||r.includes("api_key")?"Invalid API key. Check your API key configuration":r.includes("rate_limit")||r.includes("Rate limit")||r.includes("429")||r.includes("Too Many Requests")?"Rate limit exceeded. Wait a moment and try again, or upgrade your plan":r.includes("model")||r.includes("Model")?"Model not found or not accessible. Check if the model name is correct":r.includes("timeout")||r.includes("Timeout")?"Request timed out. Try again or increase the timeout setting":r.includes("network")||r.includes("connection")||r.includes("ECONNREFUSED")?"Network error. Check your internet connection and try again":r.includes("quota")||r.includes("usage")||r.includes("QUOTA_EXCEEDED")?"API quota exceeded. Check your usage limits":r.includes("401")||r.includes("Unauthorized")?"Authentication failed. Your API key may be invalid or expired":r.includes("403")||r.includes("Forbidden")?"Access denied. Your API key may not have permission for this model":r.includes("404")||r.includes("Not Found")?"Model or endpoint not found. Check your model configuration":r.includes("500")||r.includes("Internal Server Error")?"Server error. Try again later":r.includes("overloaded")||r.includes("capacity")||r.includes("SERVICE_UNAVAILABLE")||r.includes("unavailable")?"Service is temporarily unavailable. Try again in a few minutes":this.getServiceSpecificErrorMessage(e)||r||"Unknown error occurred"}getServiceSpecificErrorMessage(e){return null}cleanJsonCodeBlock(e){const r=/```(?:json|JSON)?\s*([\s\S]*?)\s*```/,o=e.match(r);return o?o[1].trim():e}parseMessage(e,r,o){const s=this.cleanJsonCodeBlock(e),n=/(\[\s*\{[\s\S]*?\}\s*\]|\{[\s\S]*?\})/,i=s.match(n);if(!i){const f=new Error("AI response did not contain a valid JSON object or array.");throw f.name="InvalidJsonResponse",f.content=e,f}const c=i[0],l=pa(c);if(!l.ok){const f=new Error("Failed to parse AI response as JSON");throw f.name="JsonParseError",f.content=c,f.originalError=l.error,f}const u=l.data,m=Array.isArray(u)?u:[u];if(!m.length||!m.every(f=>typeof f.subject=="string")){const f=new Error("AI response contained malformed commit message data.");throw f.name="MalformedCommitMessage",f.content=e,f}const d=m.map(f=>this.extractMessageAsType(f,r)).map(f=>({title:`${f.subject}`,value:`${f.subject}${f.body?`
15
15
 
16
16
  ${f.body}`:""}${f.footer?`
17
17
 
@@ -66,27 +66,27 @@ Focus on code quality, potential issues, and improvement suggestions.`:`Please a
66
66
  ${t}
67
67
  \`\`\`
68
68
 
69
- Focus on understanding the purpose and impact of these changes to create meaningful commit message(s).`,Ra=10*60*1e3;class wo extends V{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 Pn({apiKey:this.params.config.key,...this.params.config.timeout>Ra&&{timeout:this.params.config.timeout}})}getServiceSpecificErrorMessage(e){const r=e.message||"";return r.includes("API key")||r.includes("api_key")?"Invalid API key. Check your Anthropic API key in configuration":r.includes("quota")||r.includes("usage")?"API quota exceeded. Check your Anthropic usage limits":r.includes("model")||r.includes("Model")?"Model not found or not accessible. Check if the Claude model name is correct":r.includes("403")||r.includes("Forbidden")?"Access denied. Your API key may not have permission for this Claude model":r.includes("404")||r.includes("Not Found")?"Model or endpoint not found. Check your Claude model configuration":r.includes("500")||r.includes("Internal Server Error")?"Anthropic server error. Try again later":null}generateCommitMessage$(){return N(this.generateMessage("commit")).pipe(L(e=>I(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})),R(this.handleError$))}generateCodeReview$(){return N(this.generateMessage("review")).pipe(L(e=>I(e)),M(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),R(this.handleError$))}async generateMessage(e){const r=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n,logging:i,temperature:c,locale:l,generate:u,type:m,maxLength:a,maxTokens:d,topP:f,model:h}=this.params.config,g={...W,locale:l,maxLength:a,type:m,generate:u,systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n},y=e==="review"?Q(g):X(g),w=Ee(r,e),P=`${this.params.config.url||"https://api.anthropic.com"}/v1/messages`,A={"Content-Type":"application/json","x-api-key":this.params.config.key,"anthropic-version":"2023-06-01"};Y(r,e,"Anthropic",h,P,A,i),q(r,e,"Anthropic",y,w,i);const b={max_tokens:d,temperature:c,system:y,messages:[{role:"user",content:w}],top_p:f,model:h};te(r,e,"Anthropic",b,i);const k=Date.now();try{const E=await this.anthropic.messages.create(b),j=Date.now()-k;J(r,e,"Anthropic",E,i);const B=E.content.map(({text:le})=>le).join("");return K(r,e,"Anthropic",j,B,i),e==="review"?this.sanitizeResponse(B):this.parseMessage(B,m,u)}catch(E){throw _(r,e,"Anthropic",E,i),E}}}class Ne{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=$n.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 vo extends V{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 r=e.message||"";return r.includes("API key")||r.includes("api_key")?"Invalid API key. Check your Codestral API key in configuration":r.includes("rate_limit")||r.includes("Rate limit")?"Rate limit exceeded. Wait a moment and try again, or upgrade your Codestral plan":r.includes("model")||r.includes("Model")?"Model not found or not accessible. Check if the Codestral model name is correct":r.includes("Invalid model type")?"Invalid model type. Use supported models: codestral-latest, codestral-2501":r.includes("overloaded")||r.includes("capacity")?"Codestral service is overloaded. Try again in a few minutes":r.includes("403")||r.includes("Forbidden")?"Access denied. Your API key may not have permission for this Codestral model":r.includes("404")||r.includes("Not Found")?"Model or endpoint not found. Check your Codestral model configuration":r.includes("500")||r.includes("Internal Server Error")?"Codestral server error. Try again later":null}generateCommitMessage$(){return N(this.generateMessage("commit")).pipe(L(e=>I(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})),R(this.handleError$))}generateCodeReview$(){return N(this.generateMessage("review")).pipe(L(e=>I(e)),M(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),R(this.handleError$))}async generateMessage(e){const r=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n,logging:i,locale:c,generate:l,type:u,maxLength:m}=this.params.config,a={...W,locale:c,maxLength:m,type:u,generate:l,systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n},d=e==="review"?Q(a):X(a);this.checkAvailableModels();const f=Ee(r,e),g=`${this.params.config.url||"https://codestral.mistral.ai"}/v1/chat/completions`,y={Authorization:`Bearer ${this.apiKey}`,"content-type":"application/json"};Y(r,e,"Codestral",this.params.config.model,g,y,i),q(r,e,"Codestral",d,f,i);const w=await this.createChatCompletions(d,e);return e==="review"?this.sanitizeResponse(w):this.parseMessage(w,u,l)}checkAvailableModels(){if(["codestral-latest","codestral-2501"].includes(this.params.config.model))return!0;throw new Error("Invalid model type of Codestral AI")}async createChatCompletions(e,r){const o=this.params.stagedDiff.diff,{logging:s}=this.params.config,n=this.params.config.url||"https://codestral.mistral.ai",i={model:this.params.config.model,messages:[{role:"system",content:e},{role:"user",content:Ee(this.params.stagedDiff.diff,r)}],temperature:this.params.config.temperature,top_p:this.params.config.topP,max_tokens:this.params.config.maxTokens,stream:!1,safe_prompt:!1,random_seed:ot(10,1e3)};r==="commit"&&(i.response_format={type:"json_object"}),te(o,r,"Codestral",i,s);const c=Date.now();try{const u=await new Ne({method:"POST",baseURL:`${n}/v1/chat/completions`,timeout:this.params.config.timeout}).setHeaders({Authorization:`Bearer ${this.apiKey}`,"content-type":"application/json"}).setBody(i).execute(),m=Date.now()-c,a=u.data;if(J(o,r,"Codestral",a,s),!a.choices||a.choices.length===0||!a.choices[0].message?.content)throw _(o,r,"Codestral",{message:"No Content on response",result:a},s),new Error("No Content on response. Please open a Bug report");const f=a.choices[0].message.content;return K(o,r,"Codestral",m,f,s),f}catch(l){throw _(o,r,"Codestral",l,s),l}}}class bo extends V{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 En({token:this.params.config.key})}getServiceSpecificErrorMessage(e){const r=e.message||"";return r.includes("API key")||r.includes("api_key")?"Invalid API key. Check your Cohere API key in configuration":r.includes("rate_limit")||r.includes("Rate limit")?"Rate limit exceeded. Wait a moment and try again, or upgrade your Cohere plan":r.includes("model")||r.includes("Model")?"Model not found or not accessible. Check if the Cohere model name is correct":r.includes("overloaded")||r.includes("capacity")?"Cohere service is overloaded. Try again in a few minutes":r.includes("403")||r.includes("Forbidden")?"Access denied. Your API key may not have permission for this Cohere model":r.includes("404")||r.includes("Not Found")?"Model or endpoint not found. Check your Cohere model configuration":r.includes("500")||r.includes("Internal Server Error")?"Cohere server error. Try again later":null}generateCommitMessage$(){return N(this.generateMessage("commit")).pipe(L(e=>I(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})),R(this.handleError$))}generateCodeReview$(){return N(this.generateMessage("review")).pipe(L(e=>I(e)),M(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),R(this.handleError$))}async generateMessage(e){const r=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n,logging:i,temperature:c,locale:l,generate:u,type:m,maxLength:a,maxTokens:d}=this.params.config,f={...W,locale:l,maxLength:a,type:m,generate:u,systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n},h=e==="review"?Q(f):X(f),g=`Here is the diff: ${r}`,w=`${this.params.config.url||"https://api.cohere.ai"}/v1/chat`,v={Authorization:`Bearer ${this.params.config.key}`,"Content-Type":"application/json"};Y(r,e,"Cohere",this.params.config.model,w,v,i),q(r,e,"Cohere",h,g,i);const P={chatHistory:h?[{role:"SYSTEM",message:h}]:[],message:g,connectors:[{id:"web-search"}],maxTokens:d,temperature:c,model:this.params.config.model,seed:ot(10,1e3),p:this.params.config.topP};te(r,e,"Cohere",P,i);const A=Date.now();try{const b=await this.cohere.chat(P,{timeoutInSeconds:Math.floor(this.params.config.timeout/1e3)}),k=Date.now()-A,E=b.text;return J(r,e,"Cohere",b,i),K(r,e,"Cohere",k,E,i),e==="review"?this.sanitizeResponse(E):this.parseMessage(E,m,u)}catch(b){throw _(r,e,"Cohere",b,i),b}}}class Co extends V{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 r=this.params.config.url||"https://api.deepseek.com";this.deepSeek=new Er({baseURL:r,apiKey:this.params.config.key})}getServiceSpecificErrorMessage(e){const r=e.message||"";return r.includes("API key")||r.includes("api_key")?"Invalid API key. Check your DeepSeek API key in configuration":r.includes("rate_limit")||r.includes("Rate limit")?"Rate limit exceeded. Wait a moment and try again, or upgrade your DeepSeek plan":r.includes("model")||r.includes("Model")?"Model not found or not accessible. Check if the DeepSeek model name is correct":r.includes("Invalid model type")?"Invalid model type. Use supported models: deepseek-reasoner, deepseek-chat":r.includes("overloaded")||r.includes("capacity")?"DeepSeek service is overloaded. Try again in a few minutes":r.includes("403")||r.includes("Forbidden")?"Access denied. Your API key may not have permission for this DeepSeek model":r.includes("404")||r.includes("Not Found")?"Model or endpoint not found. Check your DeepSeek model configuration":r.includes("500")||r.includes("Internal Server Error")?"DeepSeek server error. Try again later":null}generateCommitMessage$(){return N(this.generateMessage("commit")).pipe(L(e=>I(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})),R(this.handleError$))}generateCodeReview$(){return N(this.generateMessage("review")).pipe(L(e=>I(e)),M(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),R(this.handleError$))}async generateMessage(e){const r=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n,logging:i,locale:c,generate:l,type:u,maxLength:m}=this.params.config,a={...W,locale:c,maxLength:m,type:u,generate:l,systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n},d=e==="review"?Q(a):X(a);this.checkAvailableModels();const f=Ee(r,e),g=`${this.params.config.url||"https://api.deepseek.com"}/chat/completions`,y={Authorization:`Bearer ${this.params.config.key}`,"Content-Type":"application/json"};Y(r,e,"DeepSeek",this.params.config.model,g,y,i),q(r,e,"DeepSeek",d,f,i);const w=await this.createChatCompletions(d,f,e);return e==="review"?this.sanitizeResponse(w):this.parseMessage(w,u,l)}checkAvailableModels(){if(["deepseek-reasoner","deepseek-chat"].includes(this.params.config.model))return!0;throw new Error("Invalid model type of DeepSeek")}async createChatCompletions(e,r,o){const s=this.params.stagedDiff.diff,{logging:n}=this.params.config,i={messages:[{role:"system",content:e},{role:"user",content:r}],model:this.params.config.model,max_tokens:this.params.config.maxTokens,top_p:this.params.config.topP,temperature:this.params.config.temperature};te(s,o,"DeepSeek",i,n);const c=Date.now();try{const l=await this.deepSeek.chat.completions.create(i,{timeout:this.params.config.timeout}),u=Date.now()-c,m=l.choices[0].message.content||"";return J(s,o,"DeepSeek",l,n),K(s,o,"DeepSeek",u,m,n),m}catch(l){throw _(s,o,"DeepSeek",l,n),l}}}class Po extends V{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 kn(this.params.config.key)}getServiceSpecificErrorMessage(e){const r=e.message||"";return r.includes("API key")||r.includes("api_key")?"Invalid API key. Check your Google AI Studio API key in configuration":r.includes("quota")||r.includes("QUOTA_EXCEEDED")?"API quota exceeded. Check your Google AI Studio usage limits":r.includes("model")||r.includes("Model")?"Model not found or not accessible. Check if the Gemini model name is correct":r.includes("SAFETY")||r.includes("safety")?"Content blocked by safety filters. Try rephrasing your request":r.includes("RECITATION")||r.includes("recitation")?"Content blocked due to recitation concerns. Try a different approach":r.includes("403")||r.includes("Forbidden")?"Access denied. Your API key may not have permission for this Gemini model":r.includes("404")||r.includes("Not Found")?"Model or endpoint not found. Check your Gemini model configuration":r.includes("500")||r.includes("Internal Server Error")?"Google AI service error. Try again later":null}generateCommitMessage$(){return N(this.generateMessage("commit")).pipe(L(e=>I(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})),R(this.handleError$))}generateCodeReview$(){return N(this.generateMessage("review")).pipe(L(e=>I(e)),M(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),R(this.handleError$))}async generateMessage(e){const r=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:s,logging:n,locale:i,codeReviewPromptPath:c,generate:l,type:u,maxLength:m}=this.params.config,a=this.params.config.maxTokens,d={...W,locale:i,maxLength:m,type:u,generate:l,systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:c},f=e==="review"?Q(d):X(d),h={maxOutputTokens:a,temperature:this.params.config.temperature,topP:this.params.config.topP},g=this.genAI.getGenerativeModel({model:this.params.config.model,systemInstruction:f,generationConfig:h,safetySettings:[{category:Ke.HARM_CATEGORY_HATE_SPEECH,threshold:We.BLOCK_LOW_AND_ABOVE},{category:Ke.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:We.BLOCK_LOW_AND_ABOVE},{category:Ke.HARM_CATEGORY_HARASSMENT,threshold:We.BLOCK_LOW_AND_ABOVE},{category:Ke.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:We.BLOCK_LOW_AND_ABOVE}]}),y=Ee(r,e),v=`${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(r,e,"Gemini",this.params.config.model,v,P,n),q(r,e,"Gemini",f,y,n),te(r,e,"Gemini",{systemInstruction:{parts:[{text:f}]},contents:[{parts:[{text:y}]}],generationConfig:h},n);const b=Date.now();try{const k=this.params.config.timeout>1e4?{request:{timeout:this.params.config.timeout}}:void 0,E=await g.generateContent(y,k),B=E.response.text(),le=Date.now()-b;return J(r,e,"Gemini",{response:B,candidates:E.response.candidates,usageMetadata:E.response.usageMetadata},n),K(r,e,"Gemini",le,B,n),e==="review"?this.sanitizeResponse(B):this.parseMessage(B,u,l)}catch(k){throw _(r,e,"Gemini",k,n),k}}}class $o extends V{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 N(this.generateMessage("commit")).pipe(L(e=>I(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})),R(this.handleError$))}generateCodeReview$(){return N(this.generateMessage("review")).pipe(L(e=>I(e)),M(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 v=new Error("GitHub token is required for GitHub Models. Use: aicommit2 github-login");throw v.code="MISSING_TOKEN",v}const r=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n,logging:i,temperature:c,locale:l,generate:u,type:m,maxLength:a,maxTokens:d,topP:f,model:h}=this.params.config,g={...W,locale:l,maxLength:a,type:m,generate:u,systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n},y=e==="review"?Q(g):X(g),w=await this.makeRequest(y,r,e);return e==="review"?this.sanitizeResponse(w):this.parseMessage(w,m,u)}async makeRequest(e,r,o){const s=Array.isArray(this.params.config.model)?this.params.config.model[0]:this.params.config.model||"gpt-4o-mini",i={messages:[{role:"system",content:e},{role:"user",content:o==="review"?r:`Here's the git diff:
69
+ Focus on understanding the purpose and impact of these changes to create meaningful commit message(s).`,Ra=10*60*1e3;class wo extends V{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 Pn({apiKey:this.params.config.key,...this.params.config.timeout>Ra&&{timeout:this.params.config.timeout}})}getServiceSpecificErrorMessage(e){const r=e.message||"";return r.includes("API key")||r.includes("api_key")?"Invalid API key. Check your Anthropic API key in configuration":r.includes("quota")||r.includes("usage")?"API quota exceeded. Check your Anthropic usage limits":r.includes("model")||r.includes("Model")?"Model not found or not accessible. Check if the Claude model name is correct":r.includes("403")||r.includes("Forbidden")?"Access denied. Your API key may not have permission for this Claude model":r.includes("404")||r.includes("Not Found")?"Model or endpoint not found. Check your Claude model configuration":r.includes("500")||r.includes("Internal Server Error")?"Anthropic server error. Try again later":null}generateCommitMessage$(){return N(this.generateMessage("commit")).pipe(L(e=>I(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})),R(this.handleError$))}generateCodeReview$(){return N(this.generateMessage("review")).pipe(L(e=>I(e)),M(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),R(this.handleError$))}async generateMessage(e){const r=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n,logging:i,temperature:c,locale:l,generate:u,type:m,maxLength:a,maxTokens:d,topP:f,model:h}=this.params.config,g={...W,locale:l,maxLength:a,type:m,generate:u,systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n},y=e==="review"?Q(g):X(g),w=Ee(r,e),P=`${this.params.config.url||"https://api.anthropic.com"}/v1/messages`,A={"Content-Type":"application/json","x-api-key":this.params.config.key,"anthropic-version":"2023-06-01"};Y(r,e,"Anthropic",h,P,A,i),q(r,e,"Anthropic",y,w,i);const b={max_tokens:d,temperature:c,system:y,messages:[{role:"user",content:w}],top_p:f,model:h};te(r,e,"Anthropic",b,i);const k=Date.now();try{const E=await this.anthropic.messages.create(b),B=Date.now()-k;J(r,e,"Anthropic",E,i);const U=E.content.map(({text:le})=>le).join("");return K(r,e,"Anthropic",B,U,i),e==="review"?this.sanitizeResponse(U):this.parseMessage(U,m,u)}catch(E){throw _(r,e,"Anthropic",E,i),E}}}class Ne{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=$n.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 vo extends V{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 r=e.message||"";return r.includes("API key")||r.includes("api_key")?"Invalid API key. Check your Codestral API key in configuration":r.includes("rate_limit")||r.includes("Rate limit")?"Rate limit exceeded. Wait a moment and try again, or upgrade your Codestral plan":r.includes("model")||r.includes("Model")?"Model not found or not accessible. Check if the Codestral model name is correct":r.includes("Invalid model type")?"Invalid model type. Use supported models: codestral-latest, codestral-2501":r.includes("overloaded")||r.includes("capacity")?"Codestral service is overloaded. Try again in a few minutes":r.includes("403")||r.includes("Forbidden")?"Access denied. Your API key may not have permission for this Codestral model":r.includes("404")||r.includes("Not Found")?"Model or endpoint not found. Check your Codestral model configuration":r.includes("500")||r.includes("Internal Server Error")?"Codestral server error. Try again later":null}generateCommitMessage$(){return N(this.generateMessage("commit")).pipe(L(e=>I(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})),R(this.handleError$))}generateCodeReview$(){return N(this.generateMessage("review")).pipe(L(e=>I(e)),M(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),R(this.handleError$))}async generateMessage(e){const r=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n,logging:i,locale:c,generate:l,type:u,maxLength:m}=this.params.config,a={...W,locale:c,maxLength:m,type:u,generate:l,systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n},d=e==="review"?Q(a):X(a);this.checkAvailableModels();const f=Ee(r,e),g=`${this.params.config.url||"https://codestral.mistral.ai"}/v1/chat/completions`,y={Authorization:`Bearer ${this.apiKey}`,"content-type":"application/json"};Y(r,e,"Codestral",this.params.config.model,g,y,i),q(r,e,"Codestral",d,f,i);const w=await this.createChatCompletions(d,e);return e==="review"?this.sanitizeResponse(w):this.parseMessage(w,u,l)}checkAvailableModels(){if(["codestral-latest","codestral-2501"].includes(this.params.config.model))return!0;throw new Error("Invalid model type of Codestral AI")}async createChatCompletions(e,r){const o=this.params.stagedDiff.diff,{logging:s}=this.params.config,n=this.params.config.url||"https://codestral.mistral.ai",i={model:this.params.config.model,messages:[{role:"system",content:e},{role:"user",content:Ee(this.params.stagedDiff.diff,r)}],temperature:this.params.config.temperature,top_p:this.params.config.topP,max_tokens:this.params.config.maxTokens,stream:!1,safe_prompt:!1,random_seed:ot(10,1e3)};r==="commit"&&(i.response_format={type:"json_object"}),te(o,r,"Codestral",i,s);const c=Date.now();try{const u=await new Ne({method:"POST",baseURL:`${n}/v1/chat/completions`,timeout:this.params.config.timeout}).setHeaders({Authorization:`Bearer ${this.apiKey}`,"content-type":"application/json"}).setBody(i).execute(),m=Date.now()-c,a=u.data;if(J(o,r,"Codestral",a,s),!a.choices||a.choices.length===0||!a.choices[0].message?.content)throw _(o,r,"Codestral",{message:"No Content on response",result:a},s),new Error("No Content on response. Please open a Bug report");const f=a.choices[0].message.content;return K(o,r,"Codestral",m,f,s),f}catch(l){throw _(o,r,"Codestral",l,s),l}}}class bo extends V{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 En({token:this.params.config.key})}getServiceSpecificErrorMessage(e){const r=e.message||"";return r.includes("API key")||r.includes("api_key")?"Invalid API key. Check your Cohere API key in configuration":r.includes("rate_limit")||r.includes("Rate limit")?"Rate limit exceeded. Wait a moment and try again, or upgrade your Cohere plan":r.includes("model")||r.includes("Model")?"Model not found or not accessible. Check if the Cohere model name is correct":r.includes("overloaded")||r.includes("capacity")?"Cohere service is overloaded. Try again in a few minutes":r.includes("403")||r.includes("Forbidden")?"Access denied. Your API key may not have permission for this Cohere model":r.includes("404")||r.includes("Not Found")?"Model or endpoint not found. Check your Cohere model configuration":r.includes("500")||r.includes("Internal Server Error")?"Cohere server error. Try again later":null}generateCommitMessage$(){return N(this.generateMessage("commit")).pipe(L(e=>I(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})),R(this.handleError$))}generateCodeReview$(){return N(this.generateMessage("review")).pipe(L(e=>I(e)),M(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),R(this.handleError$))}async generateMessage(e){const r=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n,logging:i,temperature:c,locale:l,generate:u,type:m,maxLength:a,maxTokens:d}=this.params.config,f={...W,locale:l,maxLength:a,type:m,generate:u,systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n},h=e==="review"?Q(f):X(f),g=`Here is the diff: ${r}`,w=`${this.params.config.url||"https://api.cohere.ai"}/v1/chat`,v={Authorization:`Bearer ${this.params.config.key}`,"Content-Type":"application/json"};Y(r,e,"Cohere",this.params.config.model,w,v,i),q(r,e,"Cohere",h,g,i);const P={chatHistory:h?[{role:"SYSTEM",message:h}]:[],message:g,connectors:[{id:"web-search"}],maxTokens:d,temperature:c,model:this.params.config.model,seed:ot(10,1e3),p:this.params.config.topP};te(r,e,"Cohere",P,i);const A=Date.now();try{const b=await this.cohere.chat(P,{timeoutInSeconds:Math.floor(this.params.config.timeout/1e3)}),k=Date.now()-A,E=b.text;return J(r,e,"Cohere",b,i),K(r,e,"Cohere",k,E,i),e==="review"?this.sanitizeResponse(E):this.parseMessage(E,m,u)}catch(b){throw _(r,e,"Cohere",b,i),b}}}class Co extends V{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 r=this.params.config.url||"https://api.deepseek.com";this.deepSeek=new $r({baseURL:r,apiKey:this.params.config.key})}getServiceSpecificErrorMessage(e){const r=e.message||"";return r.includes("API key")||r.includes("api_key")?"Invalid API key. Check your DeepSeek API key in configuration":r.includes("rate_limit")||r.includes("Rate limit")?"Rate limit exceeded. Wait a moment and try again, or upgrade your DeepSeek plan":r.includes("model")||r.includes("Model")?"Model not found or not accessible. Check if the DeepSeek model name is correct":r.includes("Invalid model type")?"Invalid model type. Use supported models: deepseek-reasoner, deepseek-chat":r.includes("overloaded")||r.includes("capacity")?"DeepSeek service is overloaded. Try again in a few minutes":r.includes("403")||r.includes("Forbidden")?"Access denied. Your API key may not have permission for this DeepSeek model":r.includes("404")||r.includes("Not Found")?"Model or endpoint not found. Check your DeepSeek model configuration":r.includes("500")||r.includes("Internal Server Error")?"DeepSeek server error. Try again later":null}generateCommitMessage$(){return N(this.generateMessage("commit")).pipe(L(e=>I(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})),R(this.handleError$))}generateCodeReview$(){return N(this.generateMessage("review")).pipe(L(e=>I(e)),M(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),R(this.handleError$))}async generateMessage(e){const r=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n,logging:i,locale:c,generate:l,type:u,maxLength:m}=this.params.config,a={...W,locale:c,maxLength:m,type:u,generate:l,systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n},d=e==="review"?Q(a):X(a);this.checkAvailableModels();const f=Ee(r,e),g=`${this.params.config.url||"https://api.deepseek.com"}/chat/completions`,y={Authorization:`Bearer ${this.params.config.key}`,"Content-Type":"application/json"};Y(r,e,"DeepSeek",this.params.config.model,g,y,i),q(r,e,"DeepSeek",d,f,i);const w=await this.createChatCompletions(d,f,e);return e==="review"?this.sanitizeResponse(w):this.parseMessage(w,u,l)}checkAvailableModels(){if(["deepseek-reasoner","deepseek-chat"].includes(this.params.config.model))return!0;throw new Error("Invalid model type of DeepSeek")}async createChatCompletions(e,r,o){const s=this.params.stagedDiff.diff,{logging:n}=this.params.config,i={messages:[{role:"system",content:e},{role:"user",content:r}],model:this.params.config.model,max_tokens:this.params.config.maxTokens,top_p:this.params.config.topP,temperature:this.params.config.temperature};te(s,o,"DeepSeek",i,n);const c=Date.now();try{const l=await this.deepSeek.chat.completions.create(i,{timeout:this.params.config.timeout}),u=Date.now()-c,m=l.choices[0].message.content||"";return J(s,o,"DeepSeek",l,n),K(s,o,"DeepSeek",u,m,n),m}catch(l){throw _(s,o,"DeepSeek",l,n),l}}}class Po extends V{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 kn(this.params.config.key)}getServiceSpecificErrorMessage(e){const r=e.message||"";return r.includes("API key")||r.includes("api_key")?"Invalid API key. Check your Google AI Studio API key in configuration":r.includes("quota")||r.includes("QUOTA_EXCEEDED")?"API quota exceeded. Check your Google AI Studio usage limits":r.includes("model")||r.includes("Model")?"Model not found or not accessible. Check if the Gemini model name is correct":r.includes("SAFETY")||r.includes("safety")?"Content blocked by safety filters. Try rephrasing your request":r.includes("RECITATION")||r.includes("recitation")?"Content blocked due to recitation concerns. Try a different approach":r.includes("403")||r.includes("Forbidden")?"Access denied. Your API key may not have permission for this Gemini model":r.includes("404")||r.includes("Not Found")?"Model or endpoint not found. Check your Gemini model configuration":r.includes("500")||r.includes("Internal Server Error")?"Google AI service error. Try again later":null}generateCommitMessage$(){return N(this.generateMessage("commit")).pipe(L(e=>I(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})),R(this.handleError$))}generateCodeReview$(){return N(this.generateMessage("review")).pipe(L(e=>I(e)),M(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),R(this.handleError$))}async generateMessage(e){const r=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:s,logging:n,locale:i,codeReviewPromptPath:c,generate:l,type:u,maxLength:m}=this.params.config,a=this.params.config.maxTokens,d={...W,locale:i,maxLength:m,type:u,generate:l,systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:c},f=e==="review"?Q(d):X(d),h={maxOutputTokens:a,temperature:this.params.config.temperature,topP:this.params.config.topP},g=this.genAI.getGenerativeModel({model:this.params.config.model,systemInstruction:f,generationConfig:h,safetySettings:[{category:Ke.HARM_CATEGORY_HATE_SPEECH,threshold:We.BLOCK_LOW_AND_ABOVE},{category:Ke.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:We.BLOCK_LOW_AND_ABOVE},{category:Ke.HARM_CATEGORY_HARASSMENT,threshold:We.BLOCK_LOW_AND_ABOVE},{category:Ke.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:We.BLOCK_LOW_AND_ABOVE}]}),y=Ee(r,e),v=`${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(r,e,"Gemini",this.params.config.model,v,P,n),q(r,e,"Gemini",f,y,n),te(r,e,"Gemini",{systemInstruction:{parts:[{text:f}]},contents:[{parts:[{text:y}]}],generationConfig:h},n);const b=Date.now();try{const k=this.params.config.timeout>1e4?{request:{timeout:this.params.config.timeout}}:void 0,E=await g.generateContent(y,k),U=E.response.text(),le=Date.now()-b;return J(r,e,"Gemini",{response:U,candidates:E.response.candidates,usageMetadata:E.response.usageMetadata},n),K(r,e,"Gemini",le,U,n),e==="review"?this.sanitizeResponse(U):this.parseMessage(U,u,l)}catch(k){throw _(r,e,"Gemini",k,n),k}}}class $o extends V{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 N(this.generateMessage("commit")).pipe(L(e=>I(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})),R(this.handleError$))}generateCodeReview$(){return N(this.generateMessage("review")).pipe(L(e=>I(e)),M(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 v=new Error("GitHub token is required for GitHub Models. Use: aicommit2 github-login");throw v.code="MISSING_TOKEN",v}const r=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n,logging:i,temperature:c,locale:l,generate:u,type:m,maxLength:a,maxTokens:d,topP:f,model:h}=this.params.config,g={...W,locale:l,maxLength:a,type:m,generate:u,systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n},y=e==="review"?Q(g):X(g),w=await this.makeRequest(y,r,e);return e==="review"?this.sanitizeResponse(w):this.parseMessage(w,m,u)}async makeRequest(e,r,o){const s=Array.isArray(this.params.config.model)?this.params.config.model[0]:this.params.config.model||"gpt-4o-mini",i={messages:[{role:"system",content:e},{role:"user",content:o==="review"?r:`Here's the git diff:
70
70
 
71
71
  ${r}`}],model:s,temperature:this.params.config.temperature||.7,max_tokens:this.params.config.maxTokens||1024,top_p:this.params.config.topP||.95,stream:!1},c=`${this.baseURL}/inference/chat/completions`,l={"Content-Type":"application/json",Accept:"application/vnd.github+json",Authorization:`Bearer ${this.params.config.key}`},{logging:u}=this.params.config;Y(r,o,"GitHub Models",s,c,l,u),q(r,o,"GitHub Models",e,o==="review"?r:`Here's the git diff:
72
72
 
73
- ${r}`,u),te(r,o,"GitHub Models",i,u);const m=new AbortController,a=setTimeout(()=>m.abort(),this.params.config.timeout);try{const d=Date.now(),f=await fetch(c,{method:"POST",headers:l,body:JSON.stringify(i),signal:m.signal});if(clearTimeout(a),!f.ok){const w=await f.text(),v={status:f.status,statusText:f.statusText,url:c,headers:Object.fromEntries(f.headers),body:w};_(r,o,"GitHub Models",v,u);let P=`GitHub API request failed: ${f.status} ${f.statusText}`;try{const b=JSON.parse(w);b.error?.message?P+=` - ${b.error.message}`:b.message&&(P+=` - ${b.message}`)}catch{w&&(P+=` - ${w}`)}if(f.status===401){const b=new Error("GitHub authentication failed. Please run: aicommit2 github-login");throw b.status=f.status,b.code="AUTHENTICATION_FAILED",b.content=w,b}else if(f.status===403){const b=new Error('GitHub Models access denied. Make sure your token has "Models" permission.');throw b.status=f.status,b.code="ACCESS_DENIED",b.content=w,b}else if(f.status===404){const b=new Error(`Model "${s}" not found. Please check the model name.`);throw b.status=f.status,b.code="MODEL_NOT_FOUND",b.content=w,b}else if(f.status===429){const b=new Error("Rate limit exceeded. Please try again later.");throw b.status=f.status,b.code="RATE_LIMIT_EXCEEDED",b.content=w,b}const A=new Error(P);throw A.status=f.status,A.code="API_ERROR",A.content=w,A}const h=await f.json(),g=Date.now()-d;J(r,o,"GitHub Models",h,u);const y=h.choices?.[0]?.message?.content?.trim();if(!y){_(r,o,"GitHub Models",{message:"No content found in GitHub Models response",result:h},u);const v=new Error("No response content received from GitHub Models");throw v.code="NO_CONTENT",v.content=JSON.stringify(h,null,2),v}return K(r,o,"GitHub Models",g,y,u),y}catch(d){if(clearTimeout(a),d instanceof Error&&d.name==="AbortError"){const g={message:`GitHub Models request timeout after ${this.params.config.timeout}ms`,error:d};_(r,o,"GitHub Models",g,u);const y=new Error(`GitHub Models request timed out after ${this.params.config.timeout}ms`);throw y.code="REQUEST_TIMEOUT",y.originalError=d,y}if(d.code)throw d;_(r,o,"GitHub Models",{message:"GitHub Models request failed",error:d},u);const h=new Error(`GitHub Models request failed: ${d instanceof Error?d.message:String(d)}`);throw h.code="REQUEST_FAILED",h.originalError=d,h}}}class Eo extends V{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 An({apiKey:this.params.config.key})}getServiceSpecificErrorMessage(e){const r=e.message||"";return r.includes("API key")||r.includes("api_key")?"Invalid API key. Check your Groq API key in configuration":r.includes("rate_limit")||r.includes("Rate limit")?"Rate limit exceeded. Wait a moment and try again, or upgrade your Groq plan":r.includes("model")||r.includes("Model")?"Model not found or not accessible. Check if the Groq model name is correct":r.includes("overloaded")||r.includes("capacity")?"Groq service is overloaded. Try again in a few minutes":r.includes("403")||r.includes("Forbidden")?"Access denied. Your API key may not have permission for this Groq model":r.includes("404")||r.includes("Not Found")?"Model or endpoint not found. Check your Groq model configuration":r.includes("500")||r.includes("Internal Server Error")?"Groq server error. Try again later":null}generateCommitMessage$(){return N(this.generateMessage("commit")).pipe(L(e=>I(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})),R(this.handleError$))}generateCodeReview$(){return N(this.generateMessage("review")).pipe(L(e=>I(e)),M(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),R(this.handleError$))}async generateMessage(e){const r=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n,logging:i,locale:c,temperature:l,generate:u,type:m,maxLength:a}=this.params.config,d=this.params.config.maxTokens,f={...W,locale:c,maxLength:a,type:m,generate:u,systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n},h=e==="review"?Q(f):X(f),g=`Here is the diff: ${r}`,w=`${this.params.config.url||"https://api.groq.com"}/openai/v1/chat/completions`,v={Authorization:`Bearer ${this.params.config.key}`,"Content-Type":"application/json"};Y(r,e,"Groq",this.params.config.model,w,v,i),q(r,e,"Groq",h,g,i);const P={messages:[{role:"system",content:h},{role:"user",content:g}],model:this.params.config.model,max_tokens:d,top_p:this.params.config.topP,temperature:l};te(r,e,"Groq",P,i);const A=Date.now();try{const b=await this.groq.chat.completions.create(P,{timeout:this.params.config.timeout}),k=Date.now()-A,E=b.choices[0].message.content||"";return J(r,e,"Groq",b,i),K(r,e,"Groq",k,E,i),e==="review"?this.sanitizeResponse(E):this.parseMessage(E,m,u)}catch(b){throw _(r,e,"Groq",b,i),b}}}class ko extends V{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 r=this.params.config.url||"https://huggingface.co";this.headers={accept:"*/*","accept-language":"en-US,en;q=0.9","sec-ch-ua":'"Chromium";v="116", "Not)A;Brand";v="24", "Google Chrome";v="116"',"sec-ch-ua-mobile":"?0","sec-ch-ua-platform":'"Windows"',"sec-fetch-dest":"empty","sec-fetch-mode":"cors","sec-fetch-site":"same-origin",origin:r,"Referrer-Policy":"strict-origin-when-cross-origin"}}getServiceSpecificErrorMessage(e){const r=e.message||"";return r.includes("cookie")||r.includes("Cookie")?"Invalid cookie. Check your Hugging Face session cookie in configuration":r.includes("model")||r.includes("Model")?"Model not found or not accessible. Check if the Hugging Face model name is correct":r.includes("conversation")||r.includes("conversion")?"Failed to create conversation. Try again or check your session":r.includes("401")||r.includes("Unauthorized")?"Authentication failed. Your Hugging Face session may have expired":r.includes("403")||r.includes("Forbidden")?"Access denied. You may not have permission to access this model":r.includes("404")||r.includes("Not Found")?"Model not found. Check your Hugging Face model configuration":r.includes("500")||r.includes("Internal Server Error")?"Hugging Face server error. Try again later":r.includes("overloaded")||r.includes("capacity")?"Hugging Face service is overloaded. Try again in a few minutes":null}generateCommitMessage$(){return N(this.generateMessage("commit")).pipe(L(e=>I(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})),R(this.handleError$))}generateCodeReview$(){return N(this.generateMessage("review")).pipe(L(e=>I(e)),M(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),R(this.handleError$))}async generateMessage(e){await this.initialize();const r=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n,logging:i,locale:c,generate:l,type:u,maxLength:m,temperature:a,maxTokens:d,topP:f,timeout:h}=this.params.config,g={...W,locale:c,maxLength:m,type:u,generate:l,systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n},y=e==="review"?Q(g):X(g),w=`Here is the diff: ${r}`,P=`${this.params.config.url||"https://huggingface.co"}/chat/conversation`,A={...this.headers,cookie:this.cookie};Y(r,e,"HuggingFace",this.params.config.model,P,A,i),q(r,e,"HuggingFace",y,w,i);const b=Date.now();try{const k=await this.getNewChat(y),j=await(await this.sendMessage(w,k.id)).completeResponsePromise();await this.deleteConversation(k.id);const B=Date.now()-b;return J(r,e,"HuggingFace",{response:j},i),K(r,e,"HuggingFace",B,j,i),e==="review"?this.sanitizeResponse(j):this.parseMessage(j,u,l)}catch(k){throw _(r,e,"HuggingFace",k,i),k}}async initialize(){const e=await this.getRemoteLlms(),r=e.find(o=>o.name?.toLowerCase()===this.params.config.model.toLowerCase());if(r){this.currentModel=r,this.currentModelId=r.id;return}this.currentModel=e[0],this.currentModelId=e[0].id}async getRemoteLlms(){const e=this.params.config.url||"https://huggingface.co",r=await fetch(`${e}/chat/__data.json`,{headers:{...this.headers,cookie:this.cookie},body:null,method:"GET"});if(r.status!==200)throw new Error(`Failed to get remote LLMs with status code: ${r.status}`);const s=(await r.json()).nodes[0].data,n=s[s[0].models],i=[],c=l=>l===-1?null:s[l];for(const l of n){const u=s[l];if(s[u.unlisted])continue;const m={id:c(u.id),name:c(u.name),displayName:c(u.displayName),preprompt:c(u.preprompt),promptExamples:[],websiteUrl:c(u.websiteUrl),description:c(u.description),datasetName:c(u.datasetName),datasetUrl:c(u.datasetUrl),modelUrl:c(u.modelUrl),parameters:{}},a=c(u.promptExamples);if(a!==null){const h=a.map(g=>c(g));m.promptExamples=h.map(g=>({title:s[g.title],prompt:s[g.prompt]}))}const d=c(u.parameters),f={};for(const[h,g]of Object.entries(d)){if(g===-1){f[h]=null;continue}if(Array.isArray(s[g])){f[h]=s[g].map(y=>s[y]);continue}f[h]=s[g]}m.parameters=f,i.push(m)}return this.models=i,i}async getNewChat(e){const r={model:this.currentModelId,preprompt:e};let o=0;const s=this.params.config.url||"https://huggingface.co";for(;o<5;){const n=await fetch(`${s}/chat/conversation`,{headers:{...this.headers,"content-type":"application/json",cookie:this.cookie,Referer:`${s}/chat/`},body:JSON.stringify(r),method:"POST"}),{conversationId:i}=await n.json();if(i){this.currentConversionID=i;break}else o++}if(!this.currentConversionID)throw new Error("Failed to create new conversion");return await this.getConversationHistory(this.currentConversionID)}async getConversationHistory(e){if(!e)throw new Error("conversationId is required for getConversationHistory");const r=this.params.config.url||"https://huggingface.co",o=await fetch(`${r}/chat/conversation/${e}/__data.json`,{headers:{...this.headers,cookie:this.cookie,Referer:`${r}/chat/`},body:null,method:"GET"});if(o.status!=200)throw new Error("Unable get conversation details "+o);{const s=await o.json();return this.metadataParser(s,e)}}metadataParser(e,r){const o={id:"",model:"",systemPrompt:"",title:"",history:[]},s=e.nodes[1].data,n=s[s[0].model],i=s[s[0].preprompt],c=s[s[0].title],l=s[s[0].messages],u=[];for(const m of l){const a=s[m],d=new Date(s[a.createdAt][1]).getTime()/1e3,f=new Date(s[a.updatedAt][1]).getTime()/1e3;u.push({id:s[a.id],role:s[a.from],content:s[a.content],createdAt:d,updatedAt:f})}return o.id=r,o.model=n,o.systemPrompt=i,o.title=c,o.history=u,this.currentConversation=o,o}async sendMessage(e,r){if(e==="")throw new Error("the prompt can not be empty.");if(!r&&!this.currentConversionID?await this.getNewChat():r?(this.currentConversionID=r,await this.getConversationHistory(r)):this.currentConversionID&&await this.getConversationHistory(this.currentConversionID),!this.currentConversation)throw new Error("Failed to create new conversion");const o={inputs:e,id:this.currentConversation.history[this.currentConversation.history.length-1].id,is_retry:!1,is_continue:!1,web_search:!1,tools:[]},s=new FormData;s.append("data",JSON.stringify(o));const n=this.params.config.url||"https://huggingface.co",i=new AbortController,c=setTimeout(()=>i.abort(),this.params.config.timeout),l=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 u(g){try{const y=g.split(`
74
- `),w=[];for(const v of y)v.trim()&&w.push(JSON.parse(v));return w}catch{return[{}]}}const m=new TextDecoder;let a="";const d=new TransformStream({async transform(g,y){const w=m.decode(g);try{const v=u(w);for(const P of v)P.type==="finalAnswer"?(a=P?.text||"",y.terminate()):P.type==="stream"&&y.enqueue(P?.token||"")}catch{throw new Error("Error during parsing response")}}}),f=l.body?.pipeThrough(d);async function h(){return new Promise(async(g,y)=>{try{if(!f)y("ModifiedStream undefined");else{const w=f.getReader();for(;;){const{done:v,value:P}=await w.read();if(v){g(a);break}}}}catch(w){y(w)}})}return{id:this.currentConversionID,stream:f,completeResponsePromise:h}}async deleteConversation(e){const r=this.params.config.url||"https://huggingface.co";return(await fetch(`${r}/chat/conversation/${e}`,{headers:{...this.headers,cookie:this.cookie,Referer:`${r}/chat/`},body:null,method:"DELETE"})).json()}}class Ao extends V{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 r=e.message||"";return r.includes("API key")||r.includes("api_key")?"Invalid API key. Check your Mistral AI API key in configuration":r.includes("quota")||r.includes("usage")?"API quota exceeded. Check your Mistral AI usage limits":r.includes("model")||r.includes("Model")?"Model not found or not accessible. Check if the Mistral model name is correct":r.includes("403")||r.includes("Forbidden")?"Access denied. Your API key may not have permission for this Mistral model":r.includes("404")||r.includes("Not Found")?"Model or endpoint not found. Check your Mistral model configuration":r.includes("500")||r.includes("Internal Server Error")?"Mistral AI server error. Try again later":null}generateCommitMessage$(){return N(this.generateMessage("commit")).pipe(L(e=>I(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})),R(this.handleError$))}generateCodeReview$(){return N(this.generateMessage("review")).pipe(L(e=>I(e)),M(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),R(this.handleError$))}async generateMessage(e){const r=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n,logging:i,locale:c,generate:l,type:u,maxLength:m}=this.params.config,a={...W,locale:c,maxLength:m,type:u,generate:l,systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n},d=e==="review"?Q(a):X(a);await this.checkAvailableModels();const f=`Here is the diff: ${r}`,g=`${this.params.config.url||"https://api.mistral.ai"}/v1/chat/completions`,y={Authorization:`Bearer ${this.apiKey}`,"content-type":"application/json"};Y(r,e,"MistralAI",this.params.config.model,g,y,i),q(r,e,"MistralAI",d,f,i);const w=await this.createChatCompletions(d,f,e);return e==="review"?this.sanitizeResponse(w):this.parseMessage(w,u,l)}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 Ne({method:"GET",baseURL:`${e}/v1/models`,timeout:this.params.config.timeout}).setHeaders({Authorization:`Bearer ${this.apiKey}`,"content-type":"application/json"}).execute()).data.data.filter(o=>o.object==="model").map(o=>o.id)}async createChatCompletions(e,r,o){const s=this.params.stagedDiff.diff,{logging:n}=this.params.config,i={model:this.params.config.model,messages:[{role:"system",content:e},{role:"user",content:r}],temperature:this.params.config.temperature,top_p:this.params.config.topP,max_tokens:this.params.config.maxTokens,stream:!1,safe_prompt:!1,random_seed:ot(10,1e3)};te(s,o,"MistralAI",i,n);const c=Date.now();try{const l=this.params.config.url||"https://api.mistral.ai",u=await new Ne({method:"POST",baseURL:`${l}/v1/chat/completions`,timeout:this.params.config.timeout}).setHeaders({Authorization:`Bearer ${this.apiKey}`,"content-type":"application/json"}).setBody(i).execute(),m=Date.now()-c,a=u.data;if(J(s,o,"MistralAI",a,n),!a.choices||a.choices.length===0||!a.choices[0].message?.content)throw _(s,o,"MistralAI",{message:"No Content on response",result:a},n),new Error("No Content on response. Please open a Bug report");const f=a.choices[0].message.content;return K(s,o,"MistralAI",m,f,n),f}catch(l){throw _(s,o,"MistralAI",l,n),l}}}class xo extends V{constructor(e){super(e),this.params=e,this.host=Ht,this.model="",this.key="",this.auth="",this.setupFetch=(r,o={})=>Sn(r,{...o,dispatcher:new In({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(`[${rt(this.model)}]`),this.errorPrefix=C.red.bold(`[${rt(this.model)}]`),this.host=this.params.config.host||Ht,this.auth=this.params.config.auth||"Bearer",this.key=this.params.config.key||"",this.ollama=new xn({host:this.host,fetch:this.setupFetch,...this.key&&{headers:{Authorization:`${this.auth} ${this.key}`}}})}getServiceSpecificErrorMessage(e){const r=e.message||"";return r.includes("ECONNREFUSED")||r.includes("connection")?`Cannot connect to Ollama server at ${this.host}. Make sure Ollama is running`:r.includes("model")||r.includes("Model")?`Model '${this.model}' not found. Pull the model with: ollama pull ${this.model}`:r.includes("401")||r.includes("Unauthorized")?"Authentication failed. Check your Ollama API key if authentication is enabled":r.includes("403")||r.includes("Forbidden")?"Access denied. Check your Ollama server permissions":r.includes("404")||r.includes("Not Found")?`Model '${this.model}' not found on Ollama server. Pull it first with: ollama pull ${this.model}`:r.includes("500")||r.includes("Internal Server Error")?"Ollama server error. Check server logs and try again":r.includes("overloaded")||r.includes("capacity")?"Ollama server is overloaded. Try again in a few minutes":null}generateCommitMessage$(){return N(this.generateMessage("commit")).pipe(L(e=>I(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})),R(this.handleError$))}generateCodeReview$(){return N(this.generateMessage("review")).pipe(L(e=>I(e)),M(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),R(this.handleError$))}async generateMessage(e){const r=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n,logging:i,locale:c,generate:l,type:u,maxLength:m}=this.params.config,a={...W,locale:c,maxLength:m,type:u,generate:l,systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n},d=e==="review"?Q(a):X(a);await this.checkIsAvailableOllama();const f=`Here is the diff: ${r}`,h=`Ollama_${this.model}`,g=`${this.host}/api/chat`,y=this.key?{Authorization:`${this.auth} ${this.key}`}:{};Y(r,e,h,this.model,g,y,i),q(r,e,h,d,f,i);const w=await this.createChatCompletions(d,f,e);return e==="review"?this.sanitizeResponse(w):this.parseMessage(w,u,l)}async checkIsAvailableOllama(){const e=new Ne({method:"GET",baseURL:`${this.host}`,timeout:this.params.config.timeout});return this.key&&e.setHeaders({Authorization:`${this.auth} ${this.key}`}),(await e.execute()).data}async createChatCompletions(e,r,o){const{stream:s,numCtx:n,temperature:i,topP:c,timeout:l,maxTokens:u,logging:m}=this.params.config,a=s||!1,d=this.params.stagedDiff.diff,f=`Ollama_${this.model}`,h={model:this.model,messages:[{role:"system",content:e},{role:"user",content:r}],stream:a,keep_alive:l,options:{num_ctx:n,temperature:i,top_p:c,seed:ot(10,1e3),num_predict:u??-1}};te(d,o,f,h,m);const g=Date.now();try{const y=await this.ollama.chat(h),w=Date.now()-g;let v="";if(a){if(y)for await(const P of y)v+=P.message.content}else v=y.message.content;return J(d,o,f,{response:v,fullResponse:y},m),K(d,o,f,w,v,m),v}catch(y){throw _(d,o,f,y,m),y}}}class So extends V{constructor(e){super(e),this.params=e;const r=this.params.keyName||"OPENAI_COMPATIBLE";this.colors=fa(r),this.serviceName=C.bgHex(this.colors.primary).hex(this.colors.secondary).bold(`[${rt(r)}]`),this.errorPrefix=C.red.bold(`[${rt(r)}]`),this.openAI=new Er({apiKey:this.params.config.key,baseURL:`${this.params.config.url}${this.params.config.path}`})}getServiceSpecificErrorMessage(e){const r=e.message||"";return r.includes("API key")||r.includes("api_key")?"Invalid API key. Check your OpenAI-compatible API key in configuration":r.includes("rate_limit")||r.includes("Rate limit")?"Rate limit exceeded. Wait a moment and try again, or check your service limits":r.includes("model")||r.includes("Model")?"Model not found or not accessible. Check if the model name is correct":r.includes("network")||r.includes("connection")?"Network error. Check your internet connection and API endpoint":r.includes("quota")||r.includes("usage")?"API quota exceeded. Check your usage limits":r.includes("403")||r.includes("Forbidden")?"Access denied. Your API key may not have permission for this model":r.includes("404")||r.includes("Not Found")?"Model or endpoint not found. Check your API configuration":r.includes("500")||r.includes("Internal Server Error")?"Server error. Try again later":r.includes("overloaded")||r.includes("capacity")?"Service is overloaded. Try again in a few minutes":null}generateCommitMessage$(){return N(this.generateMessage("commit")).pipe(L(e=>I(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})),R(this.handleError$))}generateCodeReview$(){return N(this.generateMessage("review")).pipe(L(e=>I(e)),M(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),R(this.handleError$))}async generateMessage(e){const r=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n,logging:i,locale:c,temperature:l,generate:u,type:m,maxLength:a,timeout:d,stream:f=!1}=this.params.config,h=this.params.config.maxTokens,g={...W,locale:c,maxLength:a,type:m,generate:u,systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n},y=e==="review"?Q(g):X(g),w=`Here is the diff: ${r}`,v=this.params.keyName||"OpenAI-Compatible",P=`${this.params.config.url}${this.params.config.path}`,A={Authorization:`Bearer ${this.params.config.key}`,"Content-Type":"application/json"};Y(r,e,v,this.params.config.model,P,A,i),q(r,e,v,y,w,i);const b={messages:[{role:"system",content:y},{role:"user",content:w}],model:this.params.config.model,stream:f,max_tokens:h,top_p:this.params.config.topP,temperature:l};te(r,e,v,b,i);const k=Date.now();try{const E=await this.openAI.chat.completions.create(b,{timeout:d});let j="";if(f&&E){const le=E;for await(const dr of le){const sn=dr.choices?.[0]?.delta?.content||"",an=dr.choices?.[0]?.delta?.reasoning_content||"",cn=`${sn}${an}`;j+=cn}}else j=E.choices?.[0]?.message.content||"";const B=Date.now()-k;return J(r,e,v,E,i),K(r,e,v,B,j,i),e==="review"?this.sanitizeResponse(j):this.parseMessage(j,m,u)}catch(E){throw _(r,e,v,E,i),E}}}var zt={},Kt={exports:{}},Te={exports:{}},Wt,Io;function Oa(){if(Io)return Wt;Io=1;var t=1e3,e=t*60,r=e*60,o=r*24,s=o*7,n=o*365.25;Wt=function(m,a){a=a||{};var d=typeof m;if(d==="string"&&m.length>0)return i(m);if(d==="number"&&isFinite(m))return a.long?l(m):c(m);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(m))};function i(m){if(m=String(m),!(m.length>100)){var a=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(m);if(a){var d=parseFloat(a[1]),f=(a[2]||"ms").toLowerCase();switch(f){case"years":case"year":case"yrs":case"yr":case"y":return d*n;case"weeks":case"week":case"w":return d*s;case"days":case"day":case"d":return d*o;case"hours":case"hour":case"hrs":case"hr":case"h":return d*r;case"minutes":case"minute":case"mins":case"min":case"m":return d*e;case"seconds":case"second":case"secs":case"sec":case"s":return d*t;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return d;default:return}}}}function c(m){var a=Math.abs(m);return a>=o?Math.round(m/o)+"d":a>=r?Math.round(m/r)+"h":a>=e?Math.round(m/e)+"m":a>=t?Math.round(m/t)+"s":m+"ms"}function l(m){var a=Math.abs(m);return a>=o?u(m,a,o,"day"):a>=r?u(m,a,r,"hour"):a>=e?u(m,a,e,"minute"):a>=t?u(m,a,t,"second"):m+" ms"}function u(m,a,d,f){var h=a>=d*1.5;return Math.round(m/d)+" "+f+(h?"s":"")}return Wt}var Yt,Mo;function Ro(){if(Mo)return Yt;Mo=1;function t(e){o.debug=o,o.default=o,o.coerce=u,o.disable=c,o.enable=n,o.enabled=l,o.humanize=Oa(),o.destroy=m,Object.keys(e).forEach(a=>{o[a]=e[a]}),o.names=[],o.skips=[],o.formatters={};function r(a){let d=0;for(let f=0;f<a.length;f++)d=(d<<5)-d+a.charCodeAt(f),d|=0;return o.colors[Math.abs(d)%o.colors.length]}o.selectColor=r;function o(a){let d,f=null,h,g;function y(...w){if(!y.enabled)return;const v=y,P=Number(new Date),A=P-(d||P);v.diff=A,v.prev=d,v.curr=P,d=P,w[0]=o.coerce(w[0]),typeof w[0]!="string"&&w.unshift("%O");let b=0;w[0]=w[0].replace(/%([a-zA-Z%])/g,(E,j)=>{if(E==="%%")return"%";b++;const B=o.formatters[j];if(typeof B=="function"){const le=w[b];E=B.call(v,le),w.splice(b,1),b--}return E}),o.formatArgs.call(v,w),(v.log||o.log).apply(v,w)}return y.namespace=a,y.useColors=o.useColors(),y.color=o.selectColor(a),y.extend=s,y.destroy=o.destroy,Object.defineProperty(y,"enabled",{enumerable:!0,configurable:!1,get:()=>f!==null?f:(h!==o.namespaces&&(h=o.namespaces,g=o.enabled(a)),g),set:w=>{f=w}}),typeof o.init=="function"&&o.init(y),y}function s(a,d){const f=o(this.namespace+(typeof d>"u"?":":d)+a);return f.log=this.log,f}function n(a){o.save(a),o.namespaces=a,o.names=[],o.skips=[];const d=(typeof a=="string"?a:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(const f of d)f[0]==="-"?o.skips.push(f.slice(1)):o.names.push(f)}function i(a,d){let f=0,h=0,g=-1,y=0;for(;f<a.length;)if(h<d.length&&(d[h]===a[f]||d[h]==="*"))d[h]==="*"?(g=h,y=f,h++):(f++,h++);else if(g!==-1)h=g+1,y++,f=y;else return!1;for(;h<d.length&&d[h]==="*";)h++;return h===d.length}function c(){const a=[...o.names,...o.skips.map(d=>"-"+d)].join(",");return o.enable(""),a}function l(a){for(const d of o.skips)if(i(a,d))return!1;for(const d of o.names)if(i(a,d))return!0;return!1}function u(a){return a instanceof Error?a.stack||a.message:a}function m(){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 Yt=t,Yt}Te.exports;var Oo;function La(){return Oo||(Oo=1,function(t,e){e.formatArgs=o,e.save=s,e.load=n,e.useColors=r,e.storage=i(),e.destroy=(()=>{let l=!1;return()=>{l||(l=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),e.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function r(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let l;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&&(l=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(l[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function o(l){if(l[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+l[0]+(this.useColors?"%c ":" ")+"+"+t.exports.humanize(this.diff),!this.useColors)return;const u="color: "+this.color;l.splice(1,0,u,"color: inherit");let m=0,a=0;l[0].replace(/%[a-zA-Z%]/g,d=>{d!=="%%"&&(m++,d==="%c"&&(a=m))}),l.splice(a,0,u)}e.log=console.debug||console.log||(()=>{});function s(l){try{l?e.storage.setItem("debug",l):e.storage.removeItem("debug")}catch{}}function n(){let l;try{l=e.storage.getItem("debug")||e.storage.getItem("DEBUG")}catch{}return!l&&typeof process<"u"&&"env"in process&&(l=process.env.DEBUG),l}function i(){try{return localStorage}catch{}}t.exports=Ro()(e);const{formatters:c}=t.exports;c.j=function(l){try{return JSON.stringify(l)}catch(u){return"[UnexpectedJSONParseError]: "+u.message}}}(Te,Te.exports)),Te.exports}var De={exports:{}},qt,Lo;function Na(){return Lo||(Lo=1,qt=(t,e=process.argv)=>{const r=t.startsWith("-")?"":t.length===1?"-":"--",o=e.indexOf(r+t),s=e.indexOf("--");return o!==-1&&(s===-1||o<s)}),qt}var Jt,No;function Ta(){if(No)return Jt;No=1;const t=ze,e=kr,r=Na(),{env:o}=process;let s;r("no-color")||r("no-colors")||r("color=false")||r("color=never")?s=0:(r("color")||r("colors")||r("color=true")||r("color=always"))&&(s=1),"FORCE_COLOR"in o&&(o.FORCE_COLOR==="true"?s=1:o.FORCE_COLOR==="false"?s=0:s=o.FORCE_COLOR.length===0?1:Math.min(parseInt(o.FORCE_COLOR,10),3));function n(l){return l===0?!1:{level:l,hasBasic:!0,has256:l>=2,has16m:l>=3}}function i(l,u){if(s===0)return 0;if(r("color=16m")||r("color=full")||r("color=truecolor"))return 3;if(r("color=256"))return 2;if(l&&!u&&s===void 0)return 0;const m=s||0;if(o.TERM==="dumb")return m;if(process.platform==="win32"){const a=t.release().split(".");return Number(a[0])>=10&&Number(a[2])>=10586?Number(a[2])>=14931?3:2:1}if("CI"in o)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE"].some(a=>a in o)||o.CI_NAME==="codeship"?1:m;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 a=parseInt((o.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(o.TERM_PROGRAM){case"iTerm.app":return a>=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:m}function c(l){const u=i(l,l&&l.isTTY);return n(u)}return Jt={supportsColor:c,stdout:n(i(!0,e.isatty(1))),stderr:n(i(!0,e.isatty(2)))},Jt}De.exports;var To;function Da(){return To||(To=1,function(t,e){const r=kr,o=yr;e.init=m,e.log=c,e.formatArgs=n,e.save=l,e.load=u,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=Ta();d&&(d.stderr||d).level>=2&&(e.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221])}catch{}e.inspectOpts=Object.keys(process.env).filter(d=>/^debug_/i.test(d)).reduce((d,f)=>{const h=f.substring(6).toLowerCase().replace(/_([a-z])/g,(y,w)=>w.toUpperCase());let g=process.env[f];return/^(yes|on|true|enabled)$/i.test(g)?g=!0:/^(no|off|false|disabled)$/i.test(g)?g=!1:g==="null"?g=null:g=Number(g),d[h]=g,d},{});function s(){return"colors"in e.inspectOpts?!!e.inspectOpts.colors:r.isatty(process.stderr.fd)}function n(d){const{namespace:f,useColors:h}=this;if(h){const g=this.color,y="\x1B[3"+(g<8?g:"8;5;"+g),w=` ${y};1m${f} \x1B[0m`;d[0]=w+d[0].split(`
73
+ ${r}`,u),te(r,o,"GitHub Models",i,u);const m=new AbortController,a=setTimeout(()=>m.abort(),this.params.config.timeout);try{const d=Date.now(),f=await fetch(c,{method:"POST",headers:l,body:JSON.stringify(i),signal:m.signal});if(clearTimeout(a),!f.ok){const w=await f.text(),v={status:f.status,statusText:f.statusText,url:c,headers:Object.fromEntries(f.headers),body:w};_(r,o,"GitHub Models",v,u);let P=`GitHub API request failed: ${f.status} ${f.statusText}`;try{const b=JSON.parse(w);b.error?.message?P+=` - ${b.error.message}`:b.message&&(P+=` - ${b.message}`)}catch{w&&(P+=` - ${w}`)}if(f.status===401){const b=new Error("GitHub authentication failed. Please run: aicommit2 github-login");throw b.status=f.status,b.code="AUTHENTICATION_FAILED",b.content=w,b}else if(f.status===403){const b=new Error('GitHub Models access denied. Make sure your token has "Models" permission.');throw b.status=f.status,b.code="ACCESS_DENIED",b.content=w,b}else if(f.status===404){const b=new Error(`Model "${s}" not found. Please check the model name.`);throw b.status=f.status,b.code="MODEL_NOT_FOUND",b.content=w,b}else if(f.status===429){const b=new Error("Rate limit exceeded. Please try again later.");throw b.status=f.status,b.code="RATE_LIMIT_EXCEEDED",b.content=w,b}const A=new Error(P);throw A.status=f.status,A.code="API_ERROR",A.content=w,A}const h=await f.json(),g=Date.now()-d;J(r,o,"GitHub Models",h,u);const y=h.choices?.[0]?.message?.content?.trim();if(!y){_(r,o,"GitHub Models",{message:"No content found in GitHub Models response",result:h},u);const v=new Error("No response content received from GitHub Models");throw v.code="NO_CONTENT",v.content=JSON.stringify(h,null,2),v}return K(r,o,"GitHub Models",g,y,u),y}catch(d){if(clearTimeout(a),d instanceof Error&&d.name==="AbortError"){const g={message:`GitHub Models request timeout after ${this.params.config.timeout}ms`,error:d};_(r,o,"GitHub Models",g,u);const y=new Error(`GitHub Models request timed out after ${this.params.config.timeout}ms`);throw y.code="REQUEST_TIMEOUT",y.originalError=d,y}if(d.code)throw d;_(r,o,"GitHub Models",{message:"GitHub Models request failed",error:d},u);const h=new Error(`GitHub Models request failed: ${d instanceof Error?d.message:String(d)}`);throw h.code="REQUEST_FAILED",h.originalError=d,h}}}class Eo extends V{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 An({apiKey:this.params.config.key})}getServiceSpecificErrorMessage(e){const r=e.message||"";return r.includes("API key")||r.includes("api_key")?"Invalid API key. Check your Groq API key in configuration":r.includes("rate_limit")||r.includes("Rate limit")?"Rate limit exceeded. Wait a moment and try again, or upgrade your Groq plan":r.includes("model")||r.includes("Model")?"Model not found or not accessible. Check if the Groq model name is correct":r.includes("overloaded")||r.includes("capacity")?"Groq service is overloaded. Try again in a few minutes":r.includes("403")||r.includes("Forbidden")?"Access denied. Your API key may not have permission for this Groq model":r.includes("404")||r.includes("Not Found")?"Model or endpoint not found. Check your Groq model configuration":r.includes("500")||r.includes("Internal Server Error")?"Groq server error. Try again later":null}generateCommitMessage$(){return N(this.generateMessage("commit")).pipe(L(e=>I(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})),R(this.handleError$))}generateCodeReview$(){return N(this.generateMessage("review")).pipe(L(e=>I(e)),M(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),R(this.handleError$))}async generateMessage(e){const r=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n,logging:i,locale:c,temperature:l,generate:u,type:m,maxLength:a}=this.params.config,d=this.params.config.maxTokens,f={...W,locale:c,maxLength:a,type:m,generate:u,systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n},h=e==="review"?Q(f):X(f),g=`Here is the diff: ${r}`,w=`${this.params.config.url||"https://api.groq.com"}/openai/v1/chat/completions`,v={Authorization:`Bearer ${this.params.config.key}`,"Content-Type":"application/json"};Y(r,e,"Groq",this.params.config.model,w,v,i),q(r,e,"Groq",h,g,i);const P={messages:[{role:"system",content:h},{role:"user",content:g}],model:this.params.config.model,max_tokens:d,top_p:this.params.config.topP,temperature:l};te(r,e,"Groq",P,i);const A=Date.now();try{const b=await this.groq.chat.completions.create(P,{timeout:this.params.config.timeout}),k=Date.now()-A,E=b.choices[0].message.content||"";return J(r,e,"Groq",b,i),K(r,e,"Groq",k,E,i),e==="review"?this.sanitizeResponse(E):this.parseMessage(E,m,u)}catch(b){throw _(r,e,"Groq",b,i),b}}}class ko extends V{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 r=this.params.config.url||"https://huggingface.co";this.headers={accept:"*/*","accept-language":"en-US,en;q=0.9","sec-ch-ua":'"Chromium";v="116", "Not)A;Brand";v="24", "Google Chrome";v="116"',"sec-ch-ua-mobile":"?0","sec-ch-ua-platform":'"Windows"',"sec-fetch-dest":"empty","sec-fetch-mode":"cors","sec-fetch-site":"same-origin",origin:r,"Referrer-Policy":"strict-origin-when-cross-origin"}}getServiceSpecificErrorMessage(e){const r=e.message||"";return r.includes("cookie")||r.includes("Cookie")?"Invalid cookie. Check your Hugging Face session cookie in configuration":r.includes("model")||r.includes("Model")?"Model not found or not accessible. Check if the Hugging Face model name is correct":r.includes("conversation")||r.includes("conversion")?"Failed to create conversation. Try again or check your session":r.includes("401")||r.includes("Unauthorized")?"Authentication failed. Your Hugging Face session may have expired":r.includes("403")||r.includes("Forbidden")?"Access denied. You may not have permission to access this model":r.includes("404")||r.includes("Not Found")?"Model not found. Check your Hugging Face model configuration":r.includes("500")||r.includes("Internal Server Error")?"Hugging Face server error. Try again later":r.includes("overloaded")||r.includes("capacity")?"Hugging Face service is overloaded. Try again in a few minutes":null}generateCommitMessage$(){return N(this.generateMessage("commit")).pipe(L(e=>I(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})),R(this.handleError$))}generateCodeReview$(){return N(this.generateMessage("review")).pipe(L(e=>I(e)),M(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),R(this.handleError$))}async generateMessage(e){await this.initialize();const r=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n,logging:i,locale:c,generate:l,type:u,maxLength:m,temperature:a,maxTokens:d,topP:f,timeout:h}=this.params.config,g={...W,locale:c,maxLength:m,type:u,generate:l,systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n},y=e==="review"?Q(g):X(g),w=`Here is the diff: ${r}`,P=`${this.params.config.url||"https://huggingface.co"}/chat/conversation`,A={...this.headers,cookie:this.cookie};Y(r,e,"HuggingFace",this.params.config.model,P,A,i),q(r,e,"HuggingFace",y,w,i);const b=Date.now();try{const k=await this.getNewChat(y),B=await(await this.sendMessage(w,k.id)).completeResponsePromise();await this.deleteConversation(k.id);const U=Date.now()-b;return J(r,e,"HuggingFace",{response:B},i),K(r,e,"HuggingFace",U,B,i),e==="review"?this.sanitizeResponse(B):this.parseMessage(B,u,l)}catch(k){throw _(r,e,"HuggingFace",k,i),k}}async initialize(){const e=await this.getRemoteLlms(),r=e.find(o=>o.name?.toLowerCase()===this.params.config.model.toLowerCase());if(r){this.currentModel=r,this.currentModelId=r.id;return}this.currentModel=e[0],this.currentModelId=e[0].id}async getRemoteLlms(){const e=this.params.config.url||"https://huggingface.co",r=await fetch(`${e}/chat/__data.json`,{headers:{...this.headers,cookie:this.cookie},body:null,method:"GET"});if(r.status!==200)throw new Error(`Failed to get remote LLMs with status code: ${r.status}`);const s=(await r.json()).nodes[0].data,n=s[s[0].models],i=[],c=l=>l===-1?null:s[l];for(const l of n){const u=s[l];if(s[u.unlisted])continue;const m={id:c(u.id),name:c(u.name),displayName:c(u.displayName),preprompt:c(u.preprompt),promptExamples:[],websiteUrl:c(u.websiteUrl),description:c(u.description),datasetName:c(u.datasetName),datasetUrl:c(u.datasetUrl),modelUrl:c(u.modelUrl),parameters:{}},a=c(u.promptExamples);if(a!==null){const h=a.map(g=>c(g));m.promptExamples=h.map(g=>({title:s[g.title],prompt:s[g.prompt]}))}const d=c(u.parameters),f={};for(const[h,g]of Object.entries(d)){if(g===-1){f[h]=null;continue}if(Array.isArray(s[g])){f[h]=s[g].map(y=>s[y]);continue}f[h]=s[g]}m.parameters=f,i.push(m)}return this.models=i,i}async getNewChat(e){const r={model:this.currentModelId,preprompt:e};let o=0;const s=this.params.config.url||"https://huggingface.co";for(;o<5;){const n=await fetch(`${s}/chat/conversation`,{headers:{...this.headers,"content-type":"application/json",cookie:this.cookie,Referer:`${s}/chat/`},body:JSON.stringify(r),method:"POST"}),{conversationId:i}=await n.json();if(i){this.currentConversionID=i;break}else o++}if(!this.currentConversionID)throw new Error("Failed to create new conversion");return await this.getConversationHistory(this.currentConversionID)}async getConversationHistory(e){if(!e)throw new Error("conversationId is required for getConversationHistory");const r=this.params.config.url||"https://huggingface.co",o=await fetch(`${r}/chat/conversation/${e}/__data.json`,{headers:{...this.headers,cookie:this.cookie,Referer:`${r}/chat/`},body:null,method:"GET"});if(o.status!=200)throw new Error("Unable get conversation details "+o);{const s=await o.json();return this.metadataParser(s,e)}}metadataParser(e,r){const o={id:"",model:"",systemPrompt:"",title:"",history:[]},s=e.nodes[1].data,n=s[s[0].model],i=s[s[0].preprompt],c=s[s[0].title],l=s[s[0].messages],u=[];for(const m of l){const a=s[m],d=new Date(s[a.createdAt][1]).getTime()/1e3,f=new Date(s[a.updatedAt][1]).getTime()/1e3;u.push({id:s[a.id],role:s[a.from],content:s[a.content],createdAt:d,updatedAt:f})}return o.id=r,o.model=n,o.systemPrompt=i,o.title=c,o.history=u,this.currentConversation=o,o}async sendMessage(e,r){if(e==="")throw new Error("the prompt can not be empty.");if(!r&&!this.currentConversionID?await this.getNewChat():r?(this.currentConversionID=r,await this.getConversationHistory(r)):this.currentConversionID&&await this.getConversationHistory(this.currentConversionID),!this.currentConversation)throw new Error("Failed to create new conversion");const o={inputs:e,id:this.currentConversation.history[this.currentConversation.history.length-1].id,is_retry:!1,is_continue:!1,web_search:!1,tools:[]},s=new FormData;s.append("data",JSON.stringify(o));const n=this.params.config.url||"https://huggingface.co",i=new AbortController,c=setTimeout(()=>i.abort(),this.params.config.timeout),l=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 u(g){try{const y=g.split(`
74
+ `),w=[];for(const v of y)v.trim()&&w.push(JSON.parse(v));return w}catch{return[{}]}}const m=new TextDecoder;let a="";const d=new TransformStream({async transform(g,y){const w=m.decode(g);try{const v=u(w);for(const P of v)P.type==="finalAnswer"?(a=P?.text||"",y.terminate()):P.type==="stream"&&y.enqueue(P?.token||"")}catch{throw new Error("Error during parsing response")}}}),f=l.body?.pipeThrough(d);async function h(){return new Promise(async(g,y)=>{try{if(!f)y("ModifiedStream undefined");else{const w=f.getReader();for(;;){const{done:v,value:P}=await w.read();if(v){g(a);break}}}}catch(w){y(w)}})}return{id:this.currentConversionID,stream:f,completeResponsePromise:h}}async deleteConversation(e){const r=this.params.config.url||"https://huggingface.co";return(await fetch(`${r}/chat/conversation/${e}`,{headers:{...this.headers,cookie:this.cookie,Referer:`${r}/chat/`},body:null,method:"DELETE"})).json()}}class Ao extends V{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 r=e.message||"";return r.includes("API key")||r.includes("api_key")?"Invalid API key. Check your Mistral AI API key in configuration":r.includes("quota")||r.includes("usage")?"API quota exceeded. Check your Mistral AI usage limits":r.includes("model")||r.includes("Model")?"Model not found or not accessible. Check if the Mistral model name is correct":r.includes("403")||r.includes("Forbidden")?"Access denied. Your API key may not have permission for this Mistral model":r.includes("404")||r.includes("Not Found")?"Model or endpoint not found. Check your Mistral model configuration":r.includes("500")||r.includes("Internal Server Error")?"Mistral AI server error. Try again later":null}generateCommitMessage$(){return N(this.generateMessage("commit")).pipe(L(e=>I(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})),R(this.handleError$))}generateCodeReview$(){return N(this.generateMessage("review")).pipe(L(e=>I(e)),M(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),R(this.handleError$))}async generateMessage(e){const r=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n,logging:i,locale:c,generate:l,type:u,maxLength:m}=this.params.config,a={...W,locale:c,maxLength:m,type:u,generate:l,systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n},d=e==="review"?Q(a):X(a);await this.checkAvailableModels();const f=`Here is the diff: ${r}`,g=`${this.params.config.url||"https://api.mistral.ai"}/v1/chat/completions`,y={Authorization:`Bearer ${this.apiKey}`,"content-type":"application/json"};Y(r,e,"MistralAI",this.params.config.model,g,y,i),q(r,e,"MistralAI",d,f,i);const w=await this.createChatCompletions(d,f,e);return e==="review"?this.sanitizeResponse(w):this.parseMessage(w,u,l)}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 Ne({method:"GET",baseURL:`${e}/v1/models`,timeout:this.params.config.timeout}).setHeaders({Authorization:`Bearer ${this.apiKey}`,"content-type":"application/json"}).execute()).data.data.filter(o=>o.object==="model").map(o=>o.id)}async createChatCompletions(e,r,o){const s=this.params.stagedDiff.diff,{logging:n}=this.params.config,i={model:this.params.config.model,messages:[{role:"system",content:e},{role:"user",content:r}],temperature:this.params.config.temperature,top_p:this.params.config.topP,max_tokens:this.params.config.maxTokens,stream:!1,safe_prompt:!1,random_seed:ot(10,1e3)};te(s,o,"MistralAI",i,n);const c=Date.now();try{const l=this.params.config.url||"https://api.mistral.ai",u=await new Ne({method:"POST",baseURL:`${l}/v1/chat/completions`,timeout:this.params.config.timeout}).setHeaders({Authorization:`Bearer ${this.apiKey}`,"content-type":"application/json"}).setBody(i).execute(),m=Date.now()-c,a=u.data;if(J(s,o,"MistralAI",a,n),!a.choices||a.choices.length===0||!a.choices[0].message?.content)throw _(s,o,"MistralAI",{message:"No Content on response",result:a},n),new Error("No Content on response. Please open a Bug report");const f=a.choices[0].message.content;return K(s,o,"MistralAI",m,f,n),f}catch(l){throw _(s,o,"MistralAI",l,n),l}}}class xo extends V{constructor(e){super(e),this.params=e,this.host=Gt,this.model="",this.key="",this.auth="",this.setupFetch=(r,o={})=>Sn(r,{...o,dispatcher:new In({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(`[${rt(this.model)}]`),this.errorPrefix=C.red.bold(`[${rt(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 xn({host:this.host,fetch:this.setupFetch,...this.key&&{headers:{Authorization:`${this.auth} ${this.key}`}}})}getServiceSpecificErrorMessage(e){const r=e.message||"";return r.includes("ECONNREFUSED")||r.includes("connection")?`Cannot connect to Ollama server at ${this.host}. Make sure Ollama is running`:r.includes("model")||r.includes("Model")?`Model '${this.model}' not found. Pull the model with: ollama pull ${this.model}`:r.includes("401")||r.includes("Unauthorized")?"Authentication failed. Check your Ollama API key if authentication is enabled":r.includes("403")||r.includes("Forbidden")?"Access denied. Check your Ollama server permissions":r.includes("404")||r.includes("Not Found")?`Model '${this.model}' not found on Ollama server. Pull it first with: ollama pull ${this.model}`:r.includes("500")||r.includes("Internal Server Error")?"Ollama server error. Check server logs and try again":r.includes("overloaded")||r.includes("capacity")?"Ollama server is overloaded. Try again in a few minutes":null}generateCommitMessage$(){return N(this.generateMessage("commit")).pipe(L(e=>I(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})),R(this.handleError$))}generateCodeReview$(){return N(this.generateMessage("review")).pipe(L(e=>I(e)),M(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),R(this.handleError$))}async generateMessage(e){const r=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n,logging:i,locale:c,generate:l,type:u,maxLength:m}=this.params.config,a={...W,locale:c,maxLength:m,type:u,generate:l,systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n},d=e==="review"?Q(a):X(a);await this.checkIsAvailableOllama();const f=`Here is the diff: ${r}`,h=`Ollama_${this.model}`,g=`${this.host}/api/chat`,y=this.key?{Authorization:`${this.auth} ${this.key}`}:{};Y(r,e,h,this.model,g,y,i),q(r,e,h,d,f,i);const w=await this.createChatCompletions(d,f,e);return e==="review"?this.sanitizeResponse(w):this.parseMessage(w,u,l)}async checkIsAvailableOllama(){const e=new Ne({method:"GET",baseURL:`${this.host}`,timeout:this.params.config.timeout});return this.key&&e.setHeaders({Authorization:`${this.auth} ${this.key}`}),(await e.execute()).data}async createChatCompletions(e,r,o){const{stream:s,numCtx:n,temperature:i,topP:c,timeout:l,maxTokens:u,logging:m}=this.params.config,a=s||!1,d=this.params.stagedDiff.diff,f=`Ollama_${this.model}`,h={model:this.model,messages:[{role:"system",content:e},{role:"user",content:r}],stream:a,keep_alive:l,options:{num_ctx:n,temperature:i,top_p:c,seed:ot(10,1e3),num_predict:u??-1}};te(d,o,f,h,m);const g=Date.now();try{const y=await this.ollama.chat(h),w=Date.now()-g;let v="";if(a){if(y)for await(const P of y)v+=P.message.content}else v=y.message.content;return J(d,o,f,{response:v,fullResponse:y},m),K(d,o,f,w,v,m),v}catch(y){throw _(d,o,f,y,m),y}}}class So extends V{constructor(e){super(e),this.params=e;const r=this.params.keyName||"OPENAI_COMPATIBLE";this.colors=fa(r),this.serviceName=C.bgHex(this.colors.primary).hex(this.colors.secondary).bold(`[${rt(r)}]`),this.errorPrefix=C.red.bold(`[${rt(r)}]`),this.openAI=new $r({apiKey:this.params.config.key,baseURL:`${this.params.config.url}${this.params.config.path}`})}getServiceSpecificErrorMessage(e){const r=e.message||"";return r.includes("API key")||r.includes("api_key")?"Invalid API key. Check your OpenAI-compatible API key in configuration":r.includes("rate_limit")||r.includes("Rate limit")?"Rate limit exceeded. Wait a moment and try again, or check your service limits":r.includes("model")||r.includes("Model")?"Model not found or not accessible. Check if the model name is correct":r.includes("network")||r.includes("connection")?"Network error. Check your internet connection and API endpoint":r.includes("quota")||r.includes("usage")?"API quota exceeded. Check your usage limits":r.includes("403")||r.includes("Forbidden")?"Access denied. Your API key may not have permission for this model":r.includes("404")||r.includes("Not Found")?"Model or endpoint not found. Check your API configuration":r.includes("500")||r.includes("Internal Server Error")?"Server error. Try again later":r.includes("overloaded")||r.includes("capacity")?"Service is overloaded. Try again in a few minutes":null}generateCommitMessage$(){return N(this.generateMessage("commit")).pipe(L(e=>I(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})),R(this.handleError$))}generateCodeReview$(){return N(this.generateMessage("review")).pipe(L(e=>I(e)),M(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),R(this.handleError$))}async generateMessage(e){const r=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n,logging:i,locale:c,temperature:l,generate:u,type:m,maxLength:a,timeout:d,stream:f=!1}=this.params.config,h=this.params.config.maxTokens,g={...W,locale:c,maxLength:a,type:m,generate:u,systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n},y=e==="review"?Q(g):X(g),w=`Here is the diff: ${r}`,v=this.params.keyName||"OpenAI-Compatible",P=`${this.params.config.url}${this.params.config.path}`,A={Authorization:`Bearer ${this.params.config.key}`,"Content-Type":"application/json"};Y(r,e,v,this.params.config.model,P,A,i),q(r,e,v,y,w,i);const b={messages:[{role:"system",content:y},{role:"user",content:w}],model:this.params.config.model,stream:f,max_tokens:h,top_p:this.params.config.topP,temperature:l};te(r,e,v,b,i);const k=Date.now();try{const E=await this.openAI.chat.completions.create(b,{timeout:d});let B="";if(f&&E){const le=E;for await(const ur of le){const sn=ur.choices?.[0]?.delta?.content||"",an=ur.choices?.[0]?.delta?.reasoning_content||"",cn=`${sn}${an}`;B+=cn}}else B=E.choices?.[0]?.message.content||"";const U=Date.now()-k;return J(r,e,v,E,i),K(r,e,v,U,B,i),e==="review"?this.sanitizeResponse(B):this.parseMessage(B,m,u)}catch(E){throw _(r,e,v,E,i),E}}}var Ut={},zt={exports:{}},Te={exports:{}},Kt,Io;function Oa(){if(Io)return Kt;Io=1;var t=1e3,e=t*60,r=e*60,o=r*24,s=o*7,n=o*365.25;Kt=function(m,a){a=a||{};var d=typeof m;if(d==="string"&&m.length>0)return i(m);if(d==="number"&&isFinite(m))return a.long?l(m):c(m);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(m))};function i(m){if(m=String(m),!(m.length>100)){var a=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(m);if(a){var d=parseFloat(a[1]),f=(a[2]||"ms").toLowerCase();switch(f){case"years":case"year":case"yrs":case"yr":case"y":return d*n;case"weeks":case"week":case"w":return d*s;case"days":case"day":case"d":return d*o;case"hours":case"hour":case"hrs":case"hr":case"h":return d*r;case"minutes":case"minute":case"mins":case"min":case"m":return d*e;case"seconds":case"second":case"secs":case"sec":case"s":return d*t;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return d;default:return}}}}function c(m){var a=Math.abs(m);return a>=o?Math.round(m/o)+"d":a>=r?Math.round(m/r)+"h":a>=e?Math.round(m/e)+"m":a>=t?Math.round(m/t)+"s":m+"ms"}function l(m){var a=Math.abs(m);return a>=o?u(m,a,o,"day"):a>=r?u(m,a,r,"hour"):a>=e?u(m,a,e,"minute"):a>=t?u(m,a,t,"second"):m+" ms"}function u(m,a,d,f){var h=a>=d*1.5;return Math.round(m/d)+" "+f+(h?"s":"")}return Kt}var Wt,Mo;function Ro(){if(Mo)return Wt;Mo=1;function t(e){o.debug=o,o.default=o,o.coerce=u,o.disable=c,o.enable=n,o.enabled=l,o.humanize=Oa(),o.destroy=m,Object.keys(e).forEach(a=>{o[a]=e[a]}),o.names=[],o.skips=[],o.formatters={};function r(a){let d=0;for(let f=0;f<a.length;f++)d=(d<<5)-d+a.charCodeAt(f),d|=0;return o.colors[Math.abs(d)%o.colors.length]}o.selectColor=r;function o(a){let d,f=null,h,g;function y(...w){if(!y.enabled)return;const v=y,P=Number(new Date),A=P-(d||P);v.diff=A,v.prev=d,v.curr=P,d=P,w[0]=o.coerce(w[0]),typeof w[0]!="string"&&w.unshift("%O");let b=0;w[0]=w[0].replace(/%([a-zA-Z%])/g,(E,B)=>{if(E==="%%")return"%";b++;const U=o.formatters[B];if(typeof U=="function"){const le=w[b];E=U.call(v,le),w.splice(b,1),b--}return E}),o.formatArgs.call(v,w),(v.log||o.log).apply(v,w)}return y.namespace=a,y.useColors=o.useColors(),y.color=o.selectColor(a),y.extend=s,y.destroy=o.destroy,Object.defineProperty(y,"enabled",{enumerable:!0,configurable:!1,get:()=>f!==null?f:(h!==o.namespaces&&(h=o.namespaces,g=o.enabled(a)),g),set:w=>{f=w}}),typeof o.init=="function"&&o.init(y),y}function s(a,d){const f=o(this.namespace+(typeof d>"u"?":":d)+a);return f.log=this.log,f}function n(a){o.save(a),o.namespaces=a,o.names=[],o.skips=[];const d=(typeof a=="string"?a:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(const f of d)f[0]==="-"?o.skips.push(f.slice(1)):o.names.push(f)}function i(a,d){let f=0,h=0,g=-1,y=0;for(;f<a.length;)if(h<d.length&&(d[h]===a[f]||d[h]==="*"))d[h]==="*"?(g=h,y=f,h++):(f++,h++);else if(g!==-1)h=g+1,y++,f=y;else return!1;for(;h<d.length&&d[h]==="*";)h++;return h===d.length}function c(){const a=[...o.names,...o.skips.map(d=>"-"+d)].join(",");return o.enable(""),a}function l(a){for(const d of o.skips)if(i(a,d))return!1;for(const d of o.names)if(i(a,d))return!0;return!1}function u(a){return a instanceof Error?a.stack||a.message:a}function m(){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=t,Wt}Te.exports;var Oo;function La(){return Oo||(Oo=1,function(t,e){e.formatArgs=o,e.save=s,e.load=n,e.useColors=r,e.storage=i(),e.destroy=(()=>{let l=!1;return()=>{l||(l=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),e.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function r(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let l;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&&(l=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(l[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function o(l){if(l[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+l[0]+(this.useColors?"%c ":" ")+"+"+t.exports.humanize(this.diff),!this.useColors)return;const u="color: "+this.color;l.splice(1,0,u,"color: inherit");let m=0,a=0;l[0].replace(/%[a-zA-Z%]/g,d=>{d!=="%%"&&(m++,d==="%c"&&(a=m))}),l.splice(a,0,u)}e.log=console.debug||console.log||(()=>{});function s(l){try{l?e.storage.setItem("debug",l):e.storage.removeItem("debug")}catch{}}function n(){let l;try{l=e.storage.getItem("debug")||e.storage.getItem("DEBUG")}catch{}return!l&&typeof process<"u"&&"env"in process&&(l=process.env.DEBUG),l}function i(){try{return localStorage}catch{}}t.exports=Ro()(e);const{formatters:c}=t.exports;c.j=function(l){try{return JSON.stringify(l)}catch(u){return"[UnexpectedJSONParseError]: "+u.message}}}(Te,Te.exports)),Te.exports}var De={exports:{}},Yt,Lo;function Na(){return Lo||(Lo=1,Yt=(t,e=process.argv)=>{const r=t.startsWith("-")?"":t.length===1?"-":"--",o=e.indexOf(r+t),s=e.indexOf("--");return o!==-1&&(s===-1||o<s)}),Yt}var qt,No;function Ta(){if(No)return qt;No=1;const t=ze,e=Er,r=Na(),{env:o}=process;let s;r("no-color")||r("no-colors")||r("color=false")||r("color=never")?s=0:(r("color")||r("colors")||r("color=true")||r("color=always"))&&(s=1),"FORCE_COLOR"in o&&(o.FORCE_COLOR==="true"?s=1:o.FORCE_COLOR==="false"?s=0:s=o.FORCE_COLOR.length===0?1:Math.min(parseInt(o.FORCE_COLOR,10),3));function n(l){return l===0?!1:{level:l,hasBasic:!0,has256:l>=2,has16m:l>=3}}function i(l,u){if(s===0)return 0;if(r("color=16m")||r("color=full")||r("color=truecolor"))return 3;if(r("color=256"))return 2;if(l&&!u&&s===void 0)return 0;const m=s||0;if(o.TERM==="dumb")return m;if(process.platform==="win32"){const a=t.release().split(".");return Number(a[0])>=10&&Number(a[2])>=10586?Number(a[2])>=14931?3:2:1}if("CI"in o)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE"].some(a=>a in o)||o.CI_NAME==="codeship"?1:m;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 a=parseInt((o.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(o.TERM_PROGRAM){case"iTerm.app":return a>=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:m}function c(l){const u=i(l,l&&l.isTTY);return n(u)}return qt={supportsColor:c,stdout:n(i(!0,e.isatty(1))),stderr:n(i(!0,e.isatty(2)))},qt}De.exports;var To;function Da(){return To||(To=1,function(t,e){const r=Er,o=gr;e.init=m,e.log=c,e.formatArgs=n,e.save=l,e.load=u,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=Ta();d&&(d.stderr||d).level>=2&&(e.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221])}catch{}e.inspectOpts=Object.keys(process.env).filter(d=>/^debug_/i.test(d)).reduce((d,f)=>{const h=f.substring(6).toLowerCase().replace(/_([a-z])/g,(y,w)=>w.toUpperCase());let g=process.env[f];return/^(yes|on|true|enabled)$/i.test(g)?g=!0:/^(no|off|false|disabled)$/i.test(g)?g=!1:g==="null"?g=null:g=Number(g),d[h]=g,d},{});function s(){return"colors"in e.inspectOpts?!!e.inspectOpts.colors:r.isatty(process.stderr.fd)}function n(d){const{namespace:f,useColors:h}=this;if(h){const g=this.color,y="\x1B[3"+(g<8?g:"8;5;"+g),w=` ${y};1m${f} \x1B[0m`;d[0]=w+d[0].split(`
75
75
  `).join(`
76
76
  `+w),d.push(y+"m+"+t.exports.humanize(this.diff)+"\x1B[0m")}else d[0]=i()+f+" "+d[0]}function i(){return e.inspectOpts.hideDate?"":new Date().toISOString()+" "}function c(...d){return process.stderr.write(o.formatWithOptions(e.inspectOpts,...d)+`
77
77
  `)}function l(d){d?process.env.DEBUG=d:delete process.env.DEBUG}function u(){return process.env.DEBUG}function m(d){d.inspectOpts={};const f=Object.keys(e.inspectOpts);for(let h=0;h<f.length;h++)d.inspectOpts[f[h]]=e.inspectOpts[f[h]]}t.exports=Ro()(e);const{formatters:a}=t.exports;a.o=function(d){return this.inspectOpts.colors=this.useColors,o.inspect(d,this.inspectOpts).split(`
78
- `).map(f=>f.trim()).join(" ")},a.O=function(d){return this.inspectOpts.colors=this.useColors,o.inspect(d,this.inspectOpts)}}(De,De.exports)),De.exports}typeof process>"u"||process.type==="renderer"||process.browser===!0||process.__nwjs?Kt.exports=La():Kt.exports=Da();var Vt=Kt.exports,Xt={};Object.defineProperty(Xt,"__esModule",{value:!0});function _a(t){return function(e,r){return new Promise((o,s)=>{t.call(this,e,r,(n,i)=>{n?s(n):o(i)})})}}Xt.default=_a;var Do=F&&F.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};const Fa=gr,Ga=Do(Vt),Ha=Do(Xt),_e=Ga.default("agent-base");function ja(t){return!!t&&typeof t.addRequest=="function"}function Qt(){const{stack:t}=new Error;return typeof t!="string"?!1:t.split(`
79
- `).some(e=>e.indexOf("(https.js:")!==-1||e.indexOf("node:https:")!==-1)}function lt(t,e){return new lt.Agent(t,e)}(function(t){class e extends Fa.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 l=n.timeout||this.timeout,u=f=>{o._hadError||(o.emit("error",f),o._hadError=!0)},m=()=>{c=null,i=!0;const f=new Error(`A "socket" was not created for HTTP request before ${l}ms`);f.code="ETIMEOUT",u(f)},a=f=>{i||(c!==null&&(clearTimeout(c),c=null),u(f))},d=f=>{if(i)return;if(c!=null&&(clearTimeout(c),c=null),ja(f)){_e("Callback returned another Agent instance %o",f.constructor.name),f.addRequest(o,n);return}if(f){f.once("free",()=>{this.freeSocket(f,n)}),o.onSocket(f);return}const h=new Error(`no Duplex stream was returned to agent-base for \`${o.method} ${o.path}\``);u(h)};if(typeof this.callback!="function"){u(new Error("`callback` is not defined"));return}this.promisifiedCallback||(this.callback.length>=3?(_e("Converting legacy callback function to promise"),this.promisifiedCallback=Ha.default(this.callback)):this.promisifiedCallback=this.callback),typeof l=="number"&&l>0&&(c=setTimeout(m,l)),"port"in n&&typeof n.port!="number"&&(n.port=Number(n.port));try{_e("Resolving socket for %o request: %o",n.protocol,`${o.method} ${o.path}`),Promise.resolve(this.promisifiedCallback(o,n)).then(d,a)}catch(f){Promise.reject(f).catch(a)}}freeSocket(o,s){_e("Freeing socket %o %o",o.constructor.name,s),o.destroy()}destroy(){_e("Destroying agent %o",this.constructor.name)}}t.Agent=e,t.prototype=t.Agent.prototype})(lt||(lt={}));var Ba=lt,Zt={},Ua=F&&F.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Zt,"__esModule",{value:!0});const za=Ua(Vt),Fe=za.default("https-proxy-agent:parse-proxy-response");function Ka(t){return new Promise((e,r)=>{let o=0;const s=[];function n(){const a=t.read();a?m(a):t.once("readable",n)}function i(){t.removeListener("end",l),t.removeListener("error",u),t.removeListener("close",c),t.removeListener("readable",n)}function c(a){Fe("onclose had error %o",a)}function l(){Fe("onend")}function u(a){i(),Fe("onerror %o",a),r(a)}function m(a){s.push(a),o+=a.length;const d=Buffer.concat(s,o);if(d.indexOf(`\r
78
+ `).map(f=>f.trim()).join(" ")},a.O=function(d){return this.inspectOpts.colors=this.useColors,o.inspect(d,this.inspectOpts)}}(De,De.exports)),De.exports}typeof process>"u"||process.type==="renderer"||process.browser===!0||process.__nwjs?zt.exports=La():zt.exports=Da();var Jt=zt.exports,Vt={};Object.defineProperty(Vt,"__esModule",{value:!0});function _a(t){return function(e,r){return new Promise((o,s)=>{t.call(this,e,r,(n,i)=>{n?s(n):o(i)})})}}Vt.default=_a;var Do=F&&F.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};const Fa=hr,Ga=Do(Jt),Ha=Do(Vt),_e=Ga.default("agent-base");function ja(t){return!!t&&typeof t.addRequest=="function"}function Xt(){const{stack:t}=new Error;return typeof t!="string"?!1:t.split(`
79
+ `).some(e=>e.indexOf("(https.js:")!==-1||e.indexOf("node:https:")!==-1)}function lt(t,e){return new lt.Agent(t,e)}(function(t){class e extends Fa.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:Xt()?443:80}set defaultPort(o){this.explicitDefaultPort=o}get protocol(){return typeof this.explicitProtocol=="string"?this.explicitProtocol:Xt()?"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=Xt()),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 l=n.timeout||this.timeout,u=f=>{o._hadError||(o.emit("error",f),o._hadError=!0)},m=()=>{c=null,i=!0;const f=new Error(`A "socket" was not created for HTTP request before ${l}ms`);f.code="ETIMEOUT",u(f)},a=f=>{i||(c!==null&&(clearTimeout(c),c=null),u(f))},d=f=>{if(i)return;if(c!=null&&(clearTimeout(c),c=null),ja(f)){_e("Callback returned another Agent instance %o",f.constructor.name),f.addRequest(o,n);return}if(f){f.once("free",()=>{this.freeSocket(f,n)}),o.onSocket(f);return}const h=new Error(`no Duplex stream was returned to agent-base for \`${o.method} ${o.path}\``);u(h)};if(typeof this.callback!="function"){u(new Error("`callback` is not defined"));return}this.promisifiedCallback||(this.callback.length>=3?(_e("Converting legacy callback function to promise"),this.promisifiedCallback=Ha.default(this.callback)):this.promisifiedCallback=this.callback),typeof l=="number"&&l>0&&(c=setTimeout(m,l)),"port"in n&&typeof n.port!="number"&&(n.port=Number(n.port));try{_e("Resolving socket for %o request: %o",n.protocol,`${o.method} ${o.path}`),Promise.resolve(this.promisifiedCallback(o,n)).then(d,a)}catch(f){Promise.reject(f).catch(a)}}freeSocket(o,s){_e("Freeing socket %o %o",o.constructor.name,s),o.destroy()}destroy(){_e("Destroying agent %o",this.constructor.name)}}t.Agent=e,t.prototype=t.Agent.prototype})(lt||(lt={}));var Ba=lt,Qt={},Ua=F&&F.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Qt,"__esModule",{value:!0});const za=Ua(Jt),Fe=za.default("https-proxy-agent:parse-proxy-response");function Ka(t){return new Promise((e,r)=>{let o=0;const s=[];function n(){const a=t.read();a?m(a):t.once("readable",n)}function i(){t.removeListener("end",l),t.removeListener("error",u),t.removeListener("close",c),t.removeListener("readable",n)}function c(a){Fe("onclose had error %o",a)}function l(){Fe("onend")}function u(a){i(),Fe("onerror %o",a),r(a)}function m(a){s.push(a),o+=a.length;const d=Buffer.concat(s,o);if(d.indexOf(`\r
80
80
  \r
81
81
  `)===-1){Fe("have not received end of HTTP headers yet..."),n();return}const h=d.toString("ascii",0,d.indexOf(`\r
82
- `)),g=+h.split(" ")[1];Fe("got proxy server response: %o",h),e({statusCode:g,buffered:d})}t.on("error",u),t.on("close",c),t.on("end",l),n()})}Zt.default=Ka;var Wa=F&&F.__awaiter||function(t,e,r,o){function s(n){return n instanceof r?n:new r(function(i){i(n)})}return new(r||(r=Promise))(function(n,i){function c(m){try{u(o.next(m))}catch(a){i(a)}}function l(m){try{u(o.throw(m))}catch(a){i(a)}}function u(m){m.done?n(m.value):s(m.value).then(c,l)}u((o=o.apply(t,e||[])).next())})},ke=F&&F.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(zt,"__esModule",{value:!0});const _o=ke(On),Fo=ke(Ln),Ya=ke(Nn),qa=ke(hr),Ja=ke(Vt),Va=Ba,Xa=ke(Zt),Ge=Ja.default("https-proxy-agent:agent");class Qa extends Va.Agent{constructor(e){let r;if(typeof e=="string"?r=Ya.default.parse(e):r=e,!r)throw new Error("an HTTP(S) proxy server `host` and `port` must be specified!");Ge("creating new HttpsProxyAgent instance: %o",r),super(r);const o=Object.assign({},r);this.secureProxy=r.secureProxy||tc(o.protocol),o.host=o.hostname||o.host,typeof o.port=="string"&&(o.port=parseInt(o.port,10)),!o.port&&o.host&&(o.port=this.secureProxy?443:80),this.secureProxy&&!("ALPNProtocols"in o)&&(o.ALPNProtocols=["http 1.1"]),o.host&&o.path&&(delete o.path,delete o.pathname),this.proxy=o}callback(e,r){return Wa(this,void 0,void 0,function*(){const{proxy:o,secureProxy:s}=this;let n;s?(Ge("Creating `tls.Socket`: %o",o),n=Fo.default.connect(o)):(Ge("Creating `net.Socket`: %o",o),n=_o.default.connect(o));const i=Object.assign({},o.headers);let l=`CONNECT ${`${r.host}:${r.port}`} HTTP/1.1\r
82
+ `)),g=+h.split(" ")[1];Fe("got proxy server response: %o",h),e({statusCode:g,buffered:d})}t.on("error",u),t.on("close",c),t.on("end",l),n()})}Qt.default=Ka;var Wa=F&&F.__awaiter||function(t,e,r,o){function s(n){return n instanceof r?n:new r(function(i){i(n)})}return new(r||(r=Promise))(function(n,i){function c(m){try{u(o.next(m))}catch(a){i(a)}}function l(m){try{u(o.throw(m))}catch(a){i(a)}}function u(m){m.done?n(m.value):s(m.value).then(c,l)}u((o=o.apply(t,e||[])).next())})},ke=F&&F.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Ut,"__esModule",{value:!0});const _o=ke(On),Fo=ke(Ln),Ya=ke(Nn),qa=ke(pr),Ja=ke(Jt),Va=Ba,Xa=ke(Qt),Ge=Ja.default("https-proxy-agent:agent");class Qa extends Va.Agent{constructor(e){let r;if(typeof e=="string"?r=Ya.default.parse(e):r=e,!r)throw new Error("an HTTP(S) proxy server `host` and `port` must be specified!");Ge("creating new HttpsProxyAgent instance: %o",r),super(r);const o=Object.assign({},r);this.secureProxy=r.secureProxy||tc(o.protocol),o.host=o.hostname||o.host,typeof o.port=="string"&&(o.port=parseInt(o.port,10)),!o.port&&o.host&&(o.port=this.secureProxy?443:80),this.secureProxy&&!("ALPNProtocols"in o)&&(o.ALPNProtocols=["http 1.1"]),o.host&&o.path&&(delete o.path,delete o.pathname),this.proxy=o}callback(e,r){return Wa(this,void 0,void 0,function*(){const{proxy:o,secureProxy:s}=this;let n;s?(Ge("Creating `tls.Socket`: %o",o),n=Fo.default.connect(o)):(Ge("Creating `net.Socket`: %o",o),n=_o.default.connect(o));const i=Object.assign({},o.headers);let l=`CONNECT ${`${r.host}:${r.port}`} HTTP/1.1\r
83
83
  `;o.auth&&(i["Proxy-Authorization"]=`Basic ${Buffer.from(o.auth).toString("base64")}`);let{host:u,port:m,secureEndpoint:a}=r;ec(m,a)||(u+=`:${m}`),i.Host=u,i.Connection="close";for(const y of Object.keys(i))l+=`${y}: ${i[y]}\r
84
84
  `;const d=Xa.default(n);n.write(`${l}\r
85
- `);const{statusCode:f,buffered:h}=yield d;if(f===200){if(e.once("socket",Za),r.secureEndpoint){Ge("Upgrading socket connection to TLS");const y=r.servername||r.host;return Fo.default.connect(Object.assign(Object.assign({},rc(r,"host","hostname","path","port")),{socket:n,servername:y}))}return n}n.destroy();const g=new _o.default.Socket({writable:!1});return g.readable=!0,e.once("socket",y=>{Ge("replaying proxy buffer for failed request"),qa.default(y.listenerCount("data")>0),y.push(h),y.push(null)}),g})}}zt.default=Qa;function Za(t){t.resume()}function ec(t,e){return!!(!e&&t===80||e&&t===443)}function tc(t){return typeof t=="string"?/^https:?$/i.test(t):!1}function rc(t,...e){const r={};let o;for(o in t)e.includes(o)||(r[o]=t[o]);return r}var oc=F&&F.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};const er=oc(zt);function tr(t){return new er.default(t)}(function(t){t.HttpsProxyAgent=er.default,t.prototype=er.default.prototype})(tr||(tr={}));var nc=tr,sc=fe(nc);const ic=async(t,e,r,o,s,n,i)=>new Promise((c,l)=>{const u=JSON.stringify(o),a=(t.protocol.includes("https")?Rn:Mn).request({port:i||void 0,hostname:t.hostname,path:e,method:"POST",headers:{"Content-Type":"application/json","Content-Length":Buffer.byteLength(u),...r},timeout:s,agent:n?sc(n):void 0},d=>{const f=[];d.on("data",h=>f.push(h)),d.on("end",()=>{c({request:a,response:d,data:Buffer.concat(f).toString()})})});a.on("error",l),a.on("timeout",()=>{a.destroy(),l(new $(`Time out error: request took over ${s}ms. Try increasing the \`timeout\` config`))}),a.write(u),a.end()}),ac=async(t,e,r,o,s,n)=>{const i=new URL(t),{response:c,data:l}=await ic(i,e,{Authorization:`Bearer ${r}`},o,s,n);if(!c.statusCode||c.statusCode<200||c.statusCode>299){let u=`API Error: ${c.statusCode} - ${c.statusMessage}`;throw l&&(u+=`
85
+ `);const{statusCode:f,buffered:h}=yield d;if(f===200){if(e.once("socket",Za),r.secureEndpoint){Ge("Upgrading socket connection to TLS");const y=r.servername||r.host;return Fo.default.connect(Object.assign(Object.assign({},rc(r,"host","hostname","path","port")),{socket:n,servername:y}))}return n}n.destroy();const g=new _o.default.Socket({writable:!1});return g.readable=!0,e.once("socket",y=>{Ge("replaying proxy buffer for failed request"),qa.default(y.listenerCount("data")>0),y.push(h),y.push(null)}),g})}}Ut.default=Qa;function Za(t){t.resume()}function ec(t,e){return!!(!e&&t===80||e&&t===443)}function tc(t){return typeof t=="string"?/^https:?$/i.test(t):!1}function rc(t,...e){const r={};let o;for(o in t)e.includes(o)||(r[o]=t[o]);return r}var oc=F&&F.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};const Zt=oc(Ut);function er(t){return new Zt.default(t)}(function(t){t.HttpsProxyAgent=Zt.default,t.prototype=Zt.default.prototype})(er||(er={}));var nc=er,sc=fe(nc);const ic=async(t,e,r,o,s,n,i)=>new Promise((c,l)=>{const u=JSON.stringify(o),a=(t.protocol.includes("https")?Rn:Mn).request({port:i||void 0,hostname:t.hostname,path:e,method:"POST",headers:{"Content-Type":"application/json","Content-Length":Buffer.byteLength(u),...r},timeout:s,agent:n?sc(n):void 0},d=>{const f=[];d.on("data",h=>f.push(h)),d.on("end",()=>{c({request:a,response:d,data:Buffer.concat(f).toString()})})});a.on("error",l),a.on("timeout",()=>{a.destroy(),l(new $(`Time out error: request took over ${s}ms. Try increasing the \`timeout\` config`))}),a.write(u),a.end()}),ac=async(t,e,r,o,s,n)=>{const i=new URL(t),{response:c,data:l}=await ic(i,e,{Authorization:`Bearer ${r}`},o,s,n);if(!c.statusCode||c.statusCode<200||c.statusCode>299){let u=`API Error: ${c.statusCode} - ${c.statusMessage}`;throw l&&(u+=`
86
86
 
87
87
  ${l}`),c.statusCode===500&&(u+=`
88
88
 
89
- Check the API status: ${t}`),new $(u)}return JSON.parse(l)},Go=t=>t.trim(),cc=async(t,e,r,o,s,n,i,c,l,u,m,a,d,f)=>{try{const h=Ee(n,d),g={model:s,messages:[{role:"system",content:m},{role:"user",content:h}],temperature:l,max_tokens:c,stream:!1,n:1,top_p:u,frequency_penalty:0,presence_penalty:0},y=new URL(e),w=`${y.protocol}//${y.host}${r}`,v={Authorization:`Bearer ${o}`,"Content-Type":"application/json"};Y(n,d,t,s,w,v,a),q(n,d,t,m,h,a),te(n,d,t,g,a);const P=Date.now(),A=await ac(e,r,o,g,i,f),b=Date.now()-P;J(n,d,t,A,a);const k=A.choices.filter(E=>E.message?.content).map(E=>Go(E.message.content)).join();return K(n,d,t,b,k,a),A.choices.filter(E=>E.message?.content).map(E=>Go(E.message.content))}catch(h){_(n,d,t,h,a);const g=h;throw g.code==="ENOTFOUND"?new $(`Error connecting to ${g.hostname} (${g.syscall})`):g}};class Ho extends V{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 r=e.message||"";return r.includes("API key")?"Invalid API key. Check your OpenAI API key in configuration":r.includes("quota")?"API quota exceeded. Check your OpenAI usage limits":r.includes("500")?"OpenAI server error. Try again later":null}generateCommitMessage$(){return N(this.generateMessage("commit")).pipe(L(e=>I(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})),R(this.handleError$))}generateCodeReview$(){return N(this.generateMessage("review")).pipe(L(e=>I(e)),M(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),R(this.handleError$))}extractJSONFromError(e){const r=/[{[]{1}([,:{}[\]0-9.\-+Eaeflnr-u \n\r\t]|".*?")+[}\]]{1}/gis,o=e.match(r);return o?Object.assign({},...o.map(s=>JSON.parse(s))):{error:{message:"Unknown error"}}}async generateMessage(e){const r=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n,temperature:i,logging:c,locale:l,generate:u,type:m,maxLength:a,proxy:d,maxTokens:f,timeout:h}=this.params.config,g={...W,locale:l,maxLength:a,type:m,generate:u,systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n},y=e==="review"?Q(g):X(g),w=await cc("ChatGPT",this.params.config.url,this.params.config.path,this.params.config.key,this.params.config.model,r,h,f,i,this.params.config.topP,y,c,e,d);return nt(e==="review"?w.map(v=>this.sanitizeResponse(v)):w.map(v=>this.parseMessage(v,m,u)))}}class jo extends V{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 r=e.message||"";return r.includes("API key")||r.includes("api_key")?"Invalid API key. Check your Perplexity API key in configuration":r.includes("rate_limit")||r.includes("Rate limit")?"Rate limit exceeded. Wait a moment and try again, or upgrade your Perplexity plan":r.includes("model")||r.includes("Model")?"Model not found or not accessible. Check if the Perplexity model name is correct":r.includes("overloaded")||r.includes("capacity")?"Perplexity service is overloaded. Try again in a few minutes":r.includes("403")||r.includes("Forbidden")?"Access denied. Your API key may not have permission for this Perplexity model":r.includes("404")||r.includes("Not Found")?"Model or endpoint not found. Check your Perplexity model configuration":r.includes("500")||r.includes("Internal Server Error")?"Perplexity server error. Try again later":null}generateCommitMessage$(){return N(this.generateMessage("commit")).pipe(L(e=>I(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})),R(this.handleError$))}generateCodeReview$(){return N(this.generateMessage("review")).pipe(L(e=>I(e)),M(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),R(this.handleError$))}extractJSONFromError(e){const r=/[{[]{1}([,:{}[\]0-9.\-+Eaeflnr-u \n\r\t]|".*?")+[}\]]{1}/gis,o=e.match(r);return o?Object.assign({},...o.map(s=>JSON.parse(s))):{error:{message:"Unknown error"}}}async generateMessage(e){const r=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n,logging:i,locale:c,generate:l,type:u,maxLength:m}=this.params.config,a={...W,locale:c,maxLength:m,type:u,generate:l,systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n},d=e==="review"?Q(a):X(a),f=`Here is the diff: ${r}`,g=`${this.params.config.url||"https://api.perplexity.ai"}/chat/completions`,y={Authorization:`Bearer ${this.apiKey}`,"content-type":"application/json"};Y(r,e,"Perplexity",this.params.config.model,g,y,i),q(r,e,"Perplexity",d,f,i);const w=await this.createChatCompletions(d,f,e);return this.parseMessage(w,u,l)}async createChatCompletions(e,r,o){const s=this.params.stagedDiff.diff,{logging:n}=this.params.config,i={model:this.params.config.model,messages:[{role:"system",content:e},{role:"user",content:r}],temperature:this.params.config.temperature,top_p:this.params.config.topP,max_tokens:this.params.config.maxTokens,stream:!1};te(s,o,"Perplexity",i,n);const c=Date.now();try{const l=this.params.config.url||"https://api.perplexity.ai",u=await new Ne({method:"POST",baseURL:`${l}/chat/completions`,timeout:this.params.config.timeout}).setHeaders({Authorization:`Bearer ${this.apiKey}`,"content-type":"application/json"}).setBody(i).execute(),m=Date.now()-c,a=u.data;if(J(s,o,"Perplexity",a,n),!a.choices||a.choices.length===0||!a.choices[0].message?.content)throw _(s,o,"Perplexity",{message:"No Content on response",result:a},n),new Error("No Content on response. Please open a Bug report");const f=a.choices[0].message.content;return K(s,o,"Perplexity",m,f,n),f}catch(l){throw _(s,o,"Perplexity",l,n),l}}}class ut{constructor(e,r){this.config=e,this.stagedDiff=r}createCommitMsgRequests$(e){return I(e).pipe(Ue(r=>{const o=this.config[r],s=Array.isArray(o.model)?o.model:[o.model];return I(s).pipe(Ue(n=>{if(o.compatible)return T.create(So,{config:{...o,url:o.url||"",path:o.path||"",model:n},stagedDiff:this.stagedDiff,keyName:n}).generateCommitMessage$();switch(r){case"OPENAI":return T.create(Ho,{config:{...this.config.OPENAI,model:n},stagedDiff:this.stagedDiff,keyName:n}).generateCommitMessage$();case"GEMINI":return T.create(Po,{config:{...this.config.GEMINI,model:n},stagedDiff:this.stagedDiff,keyName:n}).generateCommitMessage$();case"ANTHROPIC":return T.create(wo,{config:{...this.config.ANTHROPIC,model:n},stagedDiff:this.stagedDiff,keyName:n}).generateCommitMessage$();case"HUGGINGFACE":return T.create(ko,{config:{...this.config.HUGGINGFACE,model:n},stagedDiff:this.stagedDiff,keyName:n}).generateCommitMessage$();case"MISTRAL":return T.create(Ao,{config:{...this.config.MISTRAL,model:n},stagedDiff:this.stagedDiff,keyName:n}).generateCommitMessage$();case"CODESTRAL":return T.create(vo,{config:{...this.config.CODESTRAL,model:n},stagedDiff:this.stagedDiff,keyName:n}).generateCommitMessage$();case"OLLAMA":return T.create(xo,{config:{...this.config.OLLAMA,model:n},keyName:n,stagedDiff:this.stagedDiff}).generateCommitMessage$();case"COHERE":return T.create(bo,{config:{...this.config.COHERE,model:n},stagedDiff:this.stagedDiff,keyName:n}).generateCommitMessage$();case"GROQ":return T.create(Eo,{config:{...this.config.GROQ,model:n},stagedDiff:this.stagedDiff,keyName:n}).generateCommitMessage$();case"PERPLEXITY":return T.create(jo,{config:{...this.config.PERPLEXITY,model:n},stagedDiff:this.stagedDiff,keyName:n}).generateCommitMessage$();case"GITHUB_MODELS":return T.create($o,{config:{...this.config.GITHUB_MODELS,model:n},stagedDiff:this.stagedDiff,keyName:n}).generateCommitMessage$();case"DEEPSEEK":return T.create(Co,{config:{...this.config.DEEPSEEK,model:n},stagedDiff:this.stagedDiff,keyName:n}).generateCommitMessage$();default:const i=C.red.bold(`[${r}]`);return Ae({name:i+" Invalid AI type",value:"Invalid AI type",isError:!0,disabled:!0})}}))}),R(r=>{const o=C.red.bold("[UNKNOWN]");return Ae({name:o+` ${r.message||""}`,value:"Unknown error",isError:!0,disabled:!0})}))}createCodeReviewRequests$(e){return I(e).pipe(Ue(r=>{const o=this.config[r],s=Array.isArray(o.model)?o.model:[o.model];return I(s).pipe(Ue(n=>{if(o.compatible)return T.create(So,{config:{...o,url:o.url||"",path:o.path||"",model:n},stagedDiff:this.stagedDiff,keyName:n}).generateCodeReview$();switch(r){case"OPENAI":return T.create(Ho,{config:{...this.config.OPENAI,model:n},stagedDiff:this.stagedDiff,keyName:n}).generateCodeReview$();case"GEMINI":return T.create(Po,{config:{...this.config.GEMINI,model:n},stagedDiff:this.stagedDiff,keyName:n}).generateCodeReview$();case"ANTHROPIC":return T.create(wo,{config:{...this.config.ANTHROPIC,model:n},stagedDiff:this.stagedDiff,keyName:n}).generateCodeReview$();case"HUGGINGFACE":return T.create(ko,{config:{...this.config.HUGGINGFACE,model:n},stagedDiff:this.stagedDiff,keyName:n}).generateCodeReview$();case"MISTRAL":return T.create(Ao,{config:{...this.config.MISTRAL,model:n},stagedDiff:this.stagedDiff,keyName:n}).generateCodeReview$();case"CODESTRAL":return T.create(vo,{config:{...this.config.CODESTRAL,model:n},stagedDiff:this.stagedDiff,keyName:n}).generateCodeReview$();case"OLLAMA":return T.create(xo,{config:{...this.config.OLLAMA,model:n},keyName:n,stagedDiff:this.stagedDiff}).generateCodeReview$();case"COHERE":return T.create(bo,{config:{...this.config.COHERE,model:n},stagedDiff:this.stagedDiff,keyName:n}).generateCodeReview$();case"GROQ":return T.create(Eo,{config:{...this.config.GROQ,model:n},stagedDiff:this.stagedDiff,keyName:n}).generateCodeReview$();case"PERPLEXITY":return T.create(jo,{config:{...this.config.PERPLEXITY,model:n},stagedDiff:this.stagedDiff,keyName:n}).generateCodeReview$();case"GITHUB_MODELS":return T.create($o,{config:{...this.config.GITHUB_MODELS,model:n},stagedDiff:this.stagedDiff,keyName:n}).generateCodeReview$();case"DEEPSEEK":return T.create(Co,{config:{...this.config.DEEPSEEK,model:n},stagedDiff:this.stagedDiff,keyName:n}).generateCodeReview$();default:const i=C.red.bold(`[${r}]`);return Ae({name:i+" Invalid AI type",value:"Invalid AI type",isError:!0,disabled:!0})}}))}),R(r=>{const o=C.red.bold("[UNKNOWN]");return Ae({name:o+` ${r.message||""}`,value:"Unknown error",isError:!0,disabled:!0})}))}}const rr=async()=>{const{stdout:t,failed:e}=await ne("git",["rev-parse","--show-toplevel"],{reject:!1});if(e)throw new $("The current directory must be a Git repository!");return t},Z=t=>`:(exclude)${t}`,dt=["package-lock.json","pnpm-lock.yaml","*.lock","*.lockb"].map(Z),or=async(t,e)=>{const r=["diff","--cached","--diff-algorithm=minimal"],{stdout:o}=await ne("git",[...r,"--name-only",...dt,...t?t.map(Z):[],...e?e.map(Z):[]]);if(!o)return null;const{stdout:s}=await ne("git",[...r,...dt,...t?t.map(Z):[],...e?e.map(Z):[]]),n=o.split(`
89
+ Check the API status: ${t}`),new $(u)}return JSON.parse(l)},Go=t=>t.trim(),cc=async(t,e,r,o,s,n,i,c,l,u,m,a,d,f)=>{try{const h=Ee(n,d),g={model:s,messages:[{role:"system",content:m},{role:"user",content:h}],temperature:l,max_tokens:c,stream:!1,n:1,top_p:u,frequency_penalty:0,presence_penalty:0},y=new URL(e),w=`${y.protocol}//${y.host}${r}`,v={Authorization:`Bearer ${o}`,"Content-Type":"application/json"};Y(n,d,t,s,w,v,a),q(n,d,t,m,h,a),te(n,d,t,g,a);const P=Date.now(),A=await ac(e,r,o,g,i,f),b=Date.now()-P;J(n,d,t,A,a);const k=A.choices.filter(E=>E.message?.content).map(E=>Go(E.message.content)).join();return K(n,d,t,b,k,a),A.choices.filter(E=>E.message?.content).map(E=>Go(E.message.content))}catch(h){_(n,d,t,h,a);const g=h;throw g.code==="ENOTFOUND"?new $(`Error connecting to ${g.hostname} (${g.syscall})`):g}};class Ho extends V{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 r=e.message||"";return r.includes("API key")?"Invalid API key. Check your OpenAI API key in configuration":r.includes("quota")?"API quota exceeded. Check your OpenAI usage limits":r.includes("500")?"OpenAI server error. Try again later":null}generateCommitMessage$(){return N(this.generateMessage("commit")).pipe(L(e=>I(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})),R(this.handleError$))}generateCodeReview$(){return N(this.generateMessage("review")).pipe(L(e=>I(e)),M(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),R(this.handleError$))}extractJSONFromError(e){const r=/[{[]{1}([,:{}[\]0-9.\-+Eaeflnr-u \n\r\t]|".*?")+[}\]]{1}/gis,o=e.match(r);return o?Object.assign({},...o.map(s=>JSON.parse(s))):{error:{message:"Unknown error"}}}async generateMessage(e){const r=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n,temperature:i,logging:c,locale:l,generate:u,type:m,maxLength:a,proxy:d,maxTokens:f,timeout:h}=this.params.config,g={...W,locale:l,maxLength:a,type:m,generate:u,systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n},y=e==="review"?Q(g):X(g),w=await cc("ChatGPT",this.params.config.url,this.params.config.path,this.params.config.key,this.params.config.model,r,h,f,i,this.params.config.topP,y,c,e,d);return nt(e==="review"?w.map(v=>this.sanitizeResponse(v)):w.map(v=>this.parseMessage(v,m,u)))}}class jo extends V{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 r=e.message||"";return r.includes("API key")||r.includes("api_key")?"Invalid API key. Check your Perplexity API key in configuration":r.includes("rate_limit")||r.includes("Rate limit")?"Rate limit exceeded. Wait a moment and try again, or upgrade your Perplexity plan":r.includes("model")||r.includes("Model")?"Model not found or not accessible. Check if the Perplexity model name is correct":r.includes("overloaded")||r.includes("capacity")?"Perplexity service is overloaded. Try again in a few minutes":r.includes("403")||r.includes("Forbidden")?"Access denied. Your API key may not have permission for this Perplexity model":r.includes("404")||r.includes("Not Found")?"Model or endpoint not found. Check your Perplexity model configuration":r.includes("500")||r.includes("Internal Server Error")?"Perplexity server error. Try again later":null}generateCommitMessage$(){return N(this.generateMessage("commit")).pipe(L(e=>I(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})),R(this.handleError$))}generateCodeReview$(){return N(this.generateMessage("review")).pipe(L(e=>I(e)),M(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),R(this.handleError$))}extractJSONFromError(e){const r=/[{[]{1}([,:{}[\]0-9.\-+Eaeflnr-u \n\r\t]|".*?")+[}\]]{1}/gis,o=e.match(r);return o?Object.assign({},...o.map(s=>JSON.parse(s))):{error:{message:"Unknown error"}}}async generateMessage(e){const r=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n,logging:i,locale:c,generate:l,type:u,maxLength:m}=this.params.config,a={...W,locale:c,maxLength:m,type:u,generate:l,systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:n},d=e==="review"?Q(a):X(a),f=`Here is the diff: ${r}`,g=`${this.params.config.url||"https://api.perplexity.ai"}/chat/completions`,y={Authorization:`Bearer ${this.apiKey}`,"content-type":"application/json"};Y(r,e,"Perplexity",this.params.config.model,g,y,i),q(r,e,"Perplexity",d,f,i);const w=await this.createChatCompletions(d,f,e);return this.parseMessage(w,u,l)}async createChatCompletions(e,r,o){const s=this.params.stagedDiff.diff,{logging:n}=this.params.config,i={model:this.params.config.model,messages:[{role:"system",content:e},{role:"user",content:r}],temperature:this.params.config.temperature,top_p:this.params.config.topP,max_tokens:this.params.config.maxTokens,stream:!1};te(s,o,"Perplexity",i,n);const c=Date.now();try{const l=this.params.config.url||"https://api.perplexity.ai",u=await new Ne({method:"POST",baseURL:`${l}/chat/completions`,timeout:this.params.config.timeout}).setHeaders({Authorization:`Bearer ${this.apiKey}`,"content-type":"application/json"}).setBody(i).execute(),m=Date.now()-c,a=u.data;if(J(s,o,"Perplexity",a,n),!a.choices||a.choices.length===0||!a.choices[0].message?.content)throw _(s,o,"Perplexity",{message:"No Content on response",result:a},n),new Error("No Content on response. Please open a Bug report");const f=a.choices[0].message.content;return K(s,o,"Perplexity",m,f,n),f}catch(l){throw _(s,o,"Perplexity",l,n),l}}}class ut{constructor(e,r){this.config=e,this.stagedDiff=r}createCommitMsgRequests$(e){return I(e).pipe(Ue(r=>{const o=this.config[r],s=Array.isArray(o.model)?o.model:[o.model];return I(s).pipe(Ue(n=>{if(o.compatible)return T.create(So,{config:{...o,url:o.url||"",path:o.path||"",model:n},stagedDiff:this.stagedDiff,keyName:n}).generateCommitMessage$();switch(r){case"OPENAI":return T.create(Ho,{config:{...this.config.OPENAI,model:n},stagedDiff:this.stagedDiff,keyName:n}).generateCommitMessage$();case"GEMINI":return T.create(Po,{config:{...this.config.GEMINI,model:n},stagedDiff:this.stagedDiff,keyName:n}).generateCommitMessage$();case"ANTHROPIC":return T.create(wo,{config:{...this.config.ANTHROPIC,model:n},stagedDiff:this.stagedDiff,keyName:n}).generateCommitMessage$();case"HUGGINGFACE":return T.create(ko,{config:{...this.config.HUGGINGFACE,model:n},stagedDiff:this.stagedDiff,keyName:n}).generateCommitMessage$();case"MISTRAL":return T.create(Ao,{config:{...this.config.MISTRAL,model:n},stagedDiff:this.stagedDiff,keyName:n}).generateCommitMessage$();case"CODESTRAL":return T.create(vo,{config:{...this.config.CODESTRAL,model:n},stagedDiff:this.stagedDiff,keyName:n}).generateCommitMessage$();case"OLLAMA":return T.create(xo,{config:{...this.config.OLLAMA,model:n},keyName:n,stagedDiff:this.stagedDiff}).generateCommitMessage$();case"COHERE":return T.create(bo,{config:{...this.config.COHERE,model:n},stagedDiff:this.stagedDiff,keyName:n}).generateCommitMessage$();case"GROQ":return T.create(Eo,{config:{...this.config.GROQ,model:n},stagedDiff:this.stagedDiff,keyName:n}).generateCommitMessage$();case"PERPLEXITY":return T.create(jo,{config:{...this.config.PERPLEXITY,model:n},stagedDiff:this.stagedDiff,keyName:n}).generateCommitMessage$();case"GITHUB_MODELS":return T.create($o,{config:{...this.config.GITHUB_MODELS,model:n},stagedDiff:this.stagedDiff,keyName:n}).generateCommitMessage$();case"DEEPSEEK":return T.create(Co,{config:{...this.config.DEEPSEEK,model:n},stagedDiff:this.stagedDiff,keyName:n}).generateCommitMessage$();default:const i=C.red.bold(`[${r}]`);return Ae({name:i+" Invalid AI type",value:"Invalid AI type",isError:!0,disabled:!0})}}))}),R(r=>{const o=C.red.bold("[UNKNOWN]");return Ae({name:o+` ${r.message||""}`,value:"Unknown error",isError:!0,disabled:!0})}))}createCodeReviewRequests$(e){return I(e).pipe(Ue(r=>{const o=this.config[r],s=Array.isArray(o.model)?o.model:[o.model];return I(s).pipe(Ue(n=>{if(o.compatible)return T.create(So,{config:{...o,url:o.url||"",path:o.path||"",model:n},stagedDiff:this.stagedDiff,keyName:n}).generateCodeReview$();switch(r){case"OPENAI":return T.create(Ho,{config:{...this.config.OPENAI,model:n},stagedDiff:this.stagedDiff,keyName:n}).generateCodeReview$();case"GEMINI":return T.create(Po,{config:{...this.config.GEMINI,model:n},stagedDiff:this.stagedDiff,keyName:n}).generateCodeReview$();case"ANTHROPIC":return T.create(wo,{config:{...this.config.ANTHROPIC,model:n},stagedDiff:this.stagedDiff,keyName:n}).generateCodeReview$();case"HUGGINGFACE":return T.create(ko,{config:{...this.config.HUGGINGFACE,model:n},stagedDiff:this.stagedDiff,keyName:n}).generateCodeReview$();case"MISTRAL":return T.create(Ao,{config:{...this.config.MISTRAL,model:n},stagedDiff:this.stagedDiff,keyName:n}).generateCodeReview$();case"CODESTRAL":return T.create(vo,{config:{...this.config.CODESTRAL,model:n},stagedDiff:this.stagedDiff,keyName:n}).generateCodeReview$();case"OLLAMA":return T.create(xo,{config:{...this.config.OLLAMA,model:n},keyName:n,stagedDiff:this.stagedDiff}).generateCodeReview$();case"COHERE":return T.create(bo,{config:{...this.config.COHERE,model:n},stagedDiff:this.stagedDiff,keyName:n}).generateCodeReview$();case"GROQ":return T.create(Eo,{config:{...this.config.GROQ,model:n},stagedDiff:this.stagedDiff,keyName:n}).generateCodeReview$();case"PERPLEXITY":return T.create(jo,{config:{...this.config.PERPLEXITY,model:n},stagedDiff:this.stagedDiff,keyName:n}).generateCodeReview$();case"GITHUB_MODELS":return T.create($o,{config:{...this.config.GITHUB_MODELS,model:n},stagedDiff:this.stagedDiff,keyName:n}).generateCodeReview$();case"DEEPSEEK":return T.create(Co,{config:{...this.config.DEEPSEEK,model:n},stagedDiff:this.stagedDiff,keyName:n}).generateCodeReview$();default:const i=C.red.bold(`[${r}]`);return Ae({name:i+" Invalid AI type",value:"Invalid AI type",isError:!0,disabled:!0})}}))}),R(r=>{const o=C.red.bold("[UNKNOWN]");return Ae({name:o+` ${r.message||""}`,value:"Unknown error",isError:!0,disabled:!0})}))}}const tr=async()=>{const{stdout:t,failed:e}=await ne("git",["rev-parse","--show-toplevel"],{reject:!1});if(e)throw new $("The current directory must be a Git repository!");return t},Z=t=>`:(exclude)${t}`,dt=["package-lock.json","pnpm-lock.yaml","*.lock","*.lockb"].map(Z),rr=async(t,e)=>{const r=["diff","--cached","--diff-algorithm=minimal"],{stdout:o}=await ne("git",[...r,"--name-only",...dt,...t?t.map(Z):[],...e?e.map(Z):[]]);if(!o)return null;const{stdout:s}=await ne("git",[...r,...dt,...t?t.map(Z):[],...e?e.map(Z):[]]),n=o.split(`
90
90
  `).filter(Boolean),{stdout:i}=await ne("git",[...r,"--numstat",...t?t.map(Z):[],...e?e.map(Z):[]]),c=[],l=i.split(`
91
91
  `).filter(Boolean);for(const a of l){const d=a.split(" ");d[0]==="-"&&d[1]==="-"&&d[2]&&c.push(d[2])}let u=s;if(c.length>0){s.trim()||(u=""),u+=`
92
92
 
@@ -98,7 +98,7 @@ Check the API status: ${t}`),new $(u)}return JSON.parse(l)},Go=t=>t.trim(),cc=as
98
98
  --- Binary Files Changed ---
99
99
  `;for(const a of c)u+=`Binary file ${a} changed
100
100
  `}const m=[...new Set([...s.split(`
101
- `).filter(Boolean),...c])];return{files:m,diff:u||`Files changed: ${m.join(", ")}`}},dc=async()=>{try{const{stdout:t}=await ne("git",["config","--get","core.commentChar"]);return t}catch{return"#"}};class se{constructor(){this.title="aicommit2"}printTitle(){console.log(_n.textSync(this.title,{font:"Small"}))}showLoader(e){if(this.loader){this.loader.text=e;return}this.loader=yt(e).start()}stopLoader(){this.loader?.stop(),this.loader=void 0}displaySpinner(e){return yt(e).start()}stopSpinner(e){e.stop(),e.clear()}printStagedFiles(e){console.log(C.bold.green("\u2714 ")+C.bold(`${lc(e)}:`)),console.log(`${e.files.map(r=>` ${r}`).join(`
101
+ `).filter(Boolean),...c])];return{files:m,diff:u||`Files changed: ${m.join(", ")}`}},dc=async()=>{try{const{stdout:t}=await ne("git",["config","--get","core.commentChar"]);return t}catch{return"#"}};class se{constructor(){this.title="aicommit2"}printTitle(){console.log(_n.textSync(this.title,{font:"Small"}))}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(`${lc(e)}:`)),console.log(`${e.files.map(r=>` ${r}`).join(`
102
102
  `)}
103
103
  `)}printAnalyzed(){console.log(`
104
104
  ${C.bold.green("\u2714")} ${C.bold("Changes analyzed")}`)}printCommitted(){console.log(`
@@ -110,14 +110,14 @@ ${C.bold.red("\u2716")} ${C.red(`${e}`)}`)}printWarning(e){console.log(`
110
110
  ${C.bold.yellow("\u26A0")} ${C.red(`${e}`)}`)}printSuccess(e){console.log(`
111
111
  ${C.bold.green("\u2714")} ${C.green(`${e}`)}`)}printInfo(e){console.log(`
112
112
  ${C.bold.blue("\u2139")} ${C.blue(`${e}`)}`)}printSetupGitEvent(e){console.log(`
113
- ${C.bold.green("\u2714")} ${C.bold(`Git ${e} hook has been set up`)}`)}moveCursorUp(){const e=Ye.createInterface({input:process.stdin,output:process.stdout});Ye.moveCursor(process.stdout,0,-1),e.close()}moveCursorDown(){const e=Ye.createInterface({input:process.stdin,output:process.stdout});Ye.moveCursor(process.stdout,0,2),e.close()}print(e){console.log(e)}}const mc={isLoading:!1,startOption:{text:"AI is analyzing your changes"}},Bo={isLoading:!1,startOption:{text:"AI is performing a code review"}},nr="No commit messages were generated",Uo="No code reviews were generated",sr={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 ir{constructor(e){this.choices$=new wr([]),this.destroyed$=new Cn(1),this.stopMessage="Changes analyzed",this.inquirerInstance=null,this.loader$=new wr(e)}initPrompt(e=sr){return this.stopMessage=e.stopMessage,Be.registerPrompt("reactiveListPrompt",Fn),this.inquirerInstance=Be.prompt({choices$:this.choices$,loader$:this.loader$,...e}),this.inquirerInstance}startLoader(){this.loader$.next({isLoading:!0})}clearLoader(){this.inquirerInstance&&this.loader$.next({isLoading:!1,clear:!0})}refreshChoices(e){const{value:r,isError:o}=e;!e||!r||this.choices$.next([...this.currentChoices,e].sort(la))}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(){this.choices$.complete(),this.loader$.complete(),this.destroyed$.next(!0),this.destroyed$.complete()}closeInquirerInstance(){this.inquirerInstance&&this.inquirerInstance.ui.close()}cancel(){this.inquirerInstance?.ui?.activePrompt&&this.inquirerInstance.ui.activePrompt.abortPrompt()}alertNoGeneratedMessage(){this.loader$.next({isLoading:!1,message:nr,stopOption:{doneFrame:"\u26A0",color:"yellow"}})}stopLoaderOnSuccess(){this.loader$.next({isLoading:!1,message:this.stopMessage})}logEmptyCommitMessage(){console.log(`${C.bold.yellow("\u26A0")} ${C.yellow(`${nr}`)}`)}get currentChoices(){return this.choices$.getValue().map(e=>e)}}const re=new se;var fc=async(t,e,r,o,s,n,i,c,l,u,m)=>(async()=>{re.printTitle(),await rr(),o&&await ne("git",["add","--update"]);const a=await Pe({locale:t?.toString(),generate:e?.toString(),type:s?.toString(),systemPrompt:c?.toString(),includeBody:l?.toString()},m);(l===!0||a.includeBody===!0)&&Object.keys(a).forEach(A=>{typeof a[A]=="object"&&a[A]!==null&&"includeBody"in a[A]&&(a[A].includeBody=!0)}),await yo(a);const f=re.displaySpinner("Detecting staged files"),h=await or(r,a.exclude);if(f.stop(),!h)throw new $("No staged changes found. Stage your changes manually, or automatically stage all changes with the `--all` flag.");re.printStagedFiles(h);const g=zo(a,"commit");if(g.length===0)throw new $("Please set at least one API key via the `aicommit2 config set` command");const y=new ut(a,h),w=zo(a,"review");w.length>0&&await pc(y,w);const v=await hc(y,g,u);i&&(ns("copy-paste").copy(v),re.printCopied(),process.exit()),(n||u&&g.length===1)&&(await Ko(v,m),process.exit());const{confirmationPrompt:P}=await Be.prompt([{type:"confirm",name:"confirmationPrompt",message:"Use selected message?",default:!0}]);P?await Ko(v,m):re.printCancelledCommit(),process.exit()})().catch(a=>{re.printError(a.message),ce(a),process.exit(1)});function zo(t,e){return Object.entries(t).map(([r,o])=>[r,o]).filter(([r,o])=>!o.disabled).filter(([r,o])=>be.includes(r)||o.compatible===!0).filter(([r,o])=>{switch(e){case"commit":return r==="OLLAMA"?!!o&&!!o.model&&o.model.length>0:r==="HUGGINGFACE"?!!o&&!!o.cookie:!!o.key&&o.key.length>0;case"review":const s=t.codeReview||o.codeReview;return r==="OLLAMA"?!!o&&!!o.model&&o.model.length>0&&s:r==="HUGGINGFACE"?!!o&&!!o.cookie&&s:!!o.key&&o.key.length>0&&s}}).map(([r])=>r)}async function pc(t,e){const r=new ir(Bo),o=r.initPrompt({...sr,name:"codeReviewPrompt",message:"Please check code reviews: ",emptyMessage:`\u26A0 ${Uo}`,isDescriptionDim:!1,stopMessage:"Code review completed",descPageSize:20});r.startLoader();const s=t.createCodeReviewRequests$(e).subscribe(l=>r.refreshChoices(l),()=>{},()=>r.checkErrorOnChoices());if(!(await o).codeReviewPrompt?.value)throw new $("An error occurred! No selected code review");s.unsubscribe(),r.completeSubject(),re.moveCursorUp();const{continuePrompt:c}=await Be.prompt([{type:"confirm",name:"continuePrompt",message:"Will you continue without changing the code?",default:!0}]);c||(re.printCancelledCommit(),process.exit())}async function hc(t,e,r){const o=new ir(mc);if(r&&e.length===1){const l=[];o.startLoader();const u=t.createCommitMsgRequests$(e).subscribe(a=>{l.push(a),o.refreshChoices(a)},()=>{},()=>o.checkErrorOnChoices(!1));await new Promise(a=>{u.add(()=>a())}),o.clearLoader(),o.completeSubject(),re.moveCursorUp();const m=l.find(a=>a.value&&!a.isError&&!a.disabled);if(!m||!m.value)throw new $("No valid commit message was generated");return re.print(`
113
+ ${C.bold.green("\u2714")} ${C.bold(`Git ${e} hook has been set up`)}`)}moveCursorUp(){const e=Ye.createInterface({input:process.stdin,output:process.stdout});Ye.moveCursor(process.stdout,0,-1),e.close()}moveCursorDown(){const e=Ye.createInterface({input:process.stdin,output:process.stdout});Ye.moveCursor(process.stdout,0,2),e.close()}print(e){console.log(e)}}const mc={isLoading:!1,startOption:{text:"AI is analyzing your changes"}},Bo={isLoading:!1,startOption:{text:"AI is performing a code review"}},or="No commit messages were generated",Uo="No code reviews were generated",nr={type:"reactiveListPrompt",name:"aicommit2Prompt",message:"Pick a commit message to use: ",emptyMessage:`\u26A0 ${or}`,loop:!1,descPageSize:15,showDescription:!0,pickKey:"short",isDescriptionDim:!0,stopMessage:"Changes analyzed"};class sr{constructor(e){this.choices$=new yr([]),this.destroyed$=new Cn(1),this.stopMessage="Changes analyzed",this.inquirerInstance=null,this.loader$=new yr(e)}initPrompt(e=nr){return this.stopMessage=e.stopMessage,Be.registerPrompt("reactiveListPrompt",Fn),this.inquirerInstance=Be.prompt({choices$:this.choices$,loader$:this.loader$,...e}),this.inquirerInstance}startLoader(){this.loader$.next({isLoading:!0})}clearLoader(){this.inquirerInstance&&this.loader$.next({isLoading:!1,clear:!0})}refreshChoices(e){const{value:r,isError:o}=e;!e||!r||this.choices$.next([...this.currentChoices,e].sort(la))}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(){this.choices$.complete(),this.loader$.complete(),this.destroyed$.next(!0),this.destroyed$.complete()}closeInquirerInstance(){this.inquirerInstance&&this.inquirerInstance.ui.close()}cancel(){this.inquirerInstance?.ui?.activePrompt&&this.inquirerInstance.ui.activePrompt.abortPrompt()}alertNoGeneratedMessage(){this.loader$.next({isLoading:!1,message:or,stopOption:{doneFrame:"\u26A0",color:"yellow"}})}stopLoaderOnSuccess(){this.loader$.next({isLoading:!1,message:this.stopMessage})}logEmptyCommitMessage(){console.log(`${C.bold.yellow("\u26A0")} ${C.yellow(`${or}`)}`)}get currentChoices(){return this.choices$.getValue().map(e=>e)}}const re=new se;var fc=async(t,e,r,o,s,n,i,c,l,u,m)=>(async()=>{re.printTitle(),await tr(),o&&await ne("git",["add","--update"]);const a=await Pe({locale:t?.toString(),generate:e?.toString(),type:s?.toString(),systemPrompt:c?.toString(),includeBody:l?.toString()},m);(l===!0||a.includeBody===!0)&&Object.keys(a).forEach(A=>{typeof a[A]=="object"&&a[A]!==null&&"includeBody"in a[A]&&(a[A].includeBody=!0)}),await yo(a);const f=re.displaySpinner("Detecting staged files"),h=await rr(r,a.exclude);if(f.stop(),!h)throw new $("No staged changes found. Stage your changes manually, or automatically stage all changes with the `--all` flag.");re.printStagedFiles(h);const g=zo(a,"commit");if(g.length===0)throw new $("Please set at least one API key via the `aicommit2 config set` command");const y=new ut(a,h),w=zo(a,"review");w.length>0&&await pc(y,w);const v=await hc(y,g,u);i&&(ns("copy-paste").copy(v),re.printCopied(),process.exit()),(n||u&&g.length===1)&&(await Ko(v,m),process.exit());const{confirmationPrompt:P}=await Be.prompt([{type:"confirm",name:"confirmationPrompt",message:"Use selected message?",default:!0}]);P?await Ko(v,m):re.printCancelledCommit(),process.exit()})().catch(a=>{re.printError(a.message),ce(a),process.exit(1)});function zo(t,e){return Object.entries(t).map(([r,o])=>[r,o]).filter(([r,o])=>!o.disabled).filter(([r,o])=>be.includes(r)||o.compatible===!0).filter(([r,o])=>{switch(e){case"commit":return r==="OLLAMA"?!!o&&!!o.model&&o.model.length>0:r==="HUGGINGFACE"?!!o&&!!o.cookie:!!o.key&&o.key.length>0;case"review":const s=t.codeReview||o.codeReview;return r==="OLLAMA"?!!o&&!!o.model&&o.model.length>0&&s:r==="HUGGINGFACE"?!!o&&!!o.cookie&&s:!!o.key&&o.key.length>0&&s}}).map(([r])=>r)}async function pc(t,e){const r=new sr(Bo),o=r.initPrompt({...nr,name:"codeReviewPrompt",message:"Please check code reviews: ",emptyMessage:`\u26A0 ${Uo}`,isDescriptionDim:!1,stopMessage:"Code review completed",descPageSize:20});r.startLoader();const s=t.createCodeReviewRequests$(e).subscribe(l=>r.refreshChoices(l),()=>{},()=>r.checkErrorOnChoices());if(!(await o).codeReviewPrompt?.value)throw new $("An error occurred! No selected code review");s.unsubscribe(),r.completeSubject(),re.moveCursorUp();const{continuePrompt:c}=await Be.prompt([{type:"confirm",name:"continuePrompt",message:"Will you continue without changing the code?",default:!0}]);c||(re.printCancelledCommit(),process.exit())}async function hc(t,e,r){const o=new sr(mc);if(r&&e.length===1){const l=[];o.startLoader();const u=t.createCommitMsgRequests$(e).subscribe(a=>{l.push(a),o.refreshChoices(a)},()=>{},()=>o.checkErrorOnChoices(!1));await new Promise(a=>{u.add(()=>a())}),o.clearLoader(),o.completeSubject(),re.moveCursorUp();const m=l.find(a=>a.value&&!a.isError&&!a.disabled);if(!m||!m.value)throw new $("No valid commit message was generated");return re.print(`
114
114
  ${m.name}
115
- `),m.value}const s=o.initPrompt();o.startLoader();const n=t.createCommitMsgRequests$(e).subscribe(l=>o.refreshChoices(l),()=>{},()=>o.checkErrorOnChoices()),i=await s;n.unsubscribe(),o.completeSubject(),re.moveCursorUp();const c=i.aicommit2Prompt?.value;if(!c)throw new $("An error occurred! No selected message");return c}async function Ko(t,e){const r=yt("Committing with the generated message").start();await ne("git",["commit","-m",t,...e]),r.stop(),r.clear(),re.printCommitted()}var gc=ie({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:[ie({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"]}}),ie({name:"get",parameters:["[<key>","[<key> ...]]"],help:{description:"Retrieve configuration values for specified AI provider.",examples:["aic2 config get OPENAI","aic2 config get ANTHROPIC"]}}),ie({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"']}}),ie({name:"list",parameters:[],help:{description:"Display all configuration keys and their values.",examples:["aic2 config list"]}}),ie({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"]}}),ie({name:"path",parameters:[],help:{description:"Display the path of the loaded configuration file.",examples:["aic2 config path"]}})]},t=>{(async()=>{const{mode:e,keyValue:r}=t._,o=t._[1];if(e==="get"){const s=await Pe({},[]);if(r.length===0){console.log(s);return}for(const n of r){const i=n.split(".");let c=s,l=!0;for(const u of i)if(jt(c,u))c=c[u];else{l=!1;break}l?console.log(n,c):console.log(`${n} not found`)}return}if(e==="set"){await Bt(r.map(s=>{const n=s.indexOf("=");if(n===-1)throw new $("Invalid format. Use: key=value");const i=s.slice(0,n),c=s.slice(n+1);return[i,c]}));return}if(e==="add"){await Ca(r.map(s=>{const n=s.indexOf("=");if(n===-1)throw new $("Invalid format. Use: key=value");const i=s.slice(0,n),c=s.slice(n+1);return[i,c]}));return}if(e==="list"){await Pa();return}if(e==="del"){if(!o)throw new $("Please provide the config name to delete.");const s=await Oe(),n=o.split(".");if(n.length===2){const[i,c]=n;if(s[i]&&typeof s[i]=="object"&&jt(s[i],c)){delete s[i][c],Object.keys(s[i]).length===0&&delete s[i];const l=await Ce();await O.writeFile(l,ve.stringify(s),"utf8"),console.log(`Successfully deleted config: ${o}`);const u=await O.readFile(l,"utf8");console.log("--- Updated Config Content ---"),console.log(u),console.log("----------------------------")}else throw new $(`Config not found: ${o}`)}else if(n.length===1){const i=n[0];if(jt(s,i)){delete s[i];const c=await Ce();await O.writeFile(c,ve.stringify(s),"utf8"),console.log(`Successfully deleted config: ${o}`);const l=await O.readFile(c,"utf8");console.log("--- Updated Config Content ---"),console.log(l),console.log("----------------------------")}else throw new $(`Config not found: ${o}`)}else throw new $(`Invalid config name format: ${o}`);return}if(e==="path"){await $a();return}throw new $(`Invalid mode: ${e}`)})().catch(e=>{new se().printError(e.message),ce(e),process.exit(1)})}),yc=ie({name:"github-login",parameters:[],flags:{token:{type:String,description:"Manually provide a GitHub token for authentication",alias:"t"}},help:{description:"Login to GitHub and setup access to GitHub Models",examples:["aic2 github-login","aic2 github-login --token ghp_xxxxxxxxxxxxxxxxxxxx"]}},t=>{(async()=>{const e=new se;if(t.flags.token){try{await wc(t.flags.token,e)}catch(r){throw new $(`Token authentication failed: ${r.message}`)}return}try{await vc(e)}catch(r){throw new $(`Browser authentication failed: ${r.message}`)}})().catch(e=>{new se().printError(e.message),ce(e),process.exit(1)})});async function wc(t,e){if(e.printWarning("Authenticating with provided token..."),!t.startsWith("ghp_")&&!t.startsWith("gho_")&&!t.startsWith("ghu_"))throw new Error("Invalid token format. GitHub tokens should start with ghp_, gho_, or ghu_");try{const r=await fetch("https://api.github.com/user",{headers:{Authorization:`Bearer ${t}`,Accept:"application/vnd.github.v3+json","User-Agent":"aicommit2-github-models"}});if(!r.ok)throw new Error(`GitHub API request failed: ${r.status} ${r.statusText}`);const o=await r.json();try{(await fetch("https://models.github.ai/inference/chat/completions",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/vnd.github+json",Authorization:`Bearer ${t}`,"User-Agent":"aicommit2-github-models"},body:JSON.stringify({messages:[{role:"user",content:"test"}],model:"gpt-4o-mini",max_tokens:1})})).ok?e.printSuccess("GitHub Models access verified!"):e.printWarning("Could not verify GitHub Models access, but proceeding with authentication...")}catch{e.printWarning("Could not verify GitHub Models access, but proceeding with authentication...")}await Bt([["GITHUB_MODELS.key",t]]),e.printSuccess(`Successfully authenticated as ${o.login}`)}catch(r){throw new Error(`Token validation failed: ${r.message}`)}}async function vc(t){t.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")&&t.printInfo("Already authenticated with GitHub CLI")}catch{t.printInfo("Authenticating with GitHub CLI..."),t.printInfo("Please follow the instructions in your browser to complete authentication.");try{je("gh auth login --web -h github.com",{stdio:"inherit"})}catch{throw new Error("GitHub CLI authentication failed")}}t.printInfo("Verifying GitHub Models access...");try{const e=je("gh auth token",{encoding:"utf8"}).trim();e&&(await Bt([["GITHUB_MODELS.key",e]]),t.printSuccess("GitHub token stored for GitHub Models access"))}catch{t.printWarning("Could not extract token from GitHub CLI, but authentication completed")}t.printSuccess("GitHub authentication completed and GitHub Models access verified!"),t.printInfo("See usage guide: https://github.com/tak-bro/aicommit2/blob/main/docs/providers/github-models.md"),t.printInfo("Available models: gpt-4o-mini, gpt-4o, meta-llama-3.1-405b-instruct, etc."),t.printInfo("Using GitHub Models API: https://models.github.ai")}catch(e){throw e}}const Wo="prepare-commit-msg",Yo=`.git/hooks/${Wo}`,mt=Tn(new URL("cli.mjs",import.meta.url)),bc=process.argv[1].replace(/\\/g,"/").endsWith(`/${Yo}`),qo=process.platform==="win32",Jo=`
115
+ `),m.value}const s=o.initPrompt();o.startLoader();const n=t.createCommitMsgRequests$(e).subscribe(l=>o.refreshChoices(l),()=>{},()=>o.checkErrorOnChoices()),i=await s;n.unsubscribe(),o.completeSubject(),re.moveCursorUp();const c=i.aicommit2Prompt?.value;if(!c)throw new $("An error occurred! No selected message");return c}async function Ko(t,e){await ne("git",["commit","-m",t,...e],{stdio:"inherit"}),re.printCommitted()}var gc=ie({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:[ie({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"]}}),ie({name:"get",parameters:["[<key>","[<key> ...]]"],help:{description:"Retrieve configuration values for specified AI provider.",examples:["aic2 config get OPENAI","aic2 config get ANTHROPIC"]}}),ie({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"']}}),ie({name:"list",parameters:[],help:{description:"Display all configuration keys and their values.",examples:["aic2 config list"]}}),ie({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"]}}),ie({name:"path",parameters:[],help:{description:"Display the path of the loaded configuration file.",examples:["aic2 config path"]}})]},t=>{(async()=>{const{mode:e,keyValue:r}=t._,o=t._[1];if(e==="get"){const s=await Pe({},[]);if(r.length===0){console.log(s);return}for(const n of r){const i=n.split(".");let c=s,l=!0;for(const u of i)if(Ht(c,u))c=c[u];else{l=!1;break}l?console.log(n,c):console.log(`${n} not found`)}return}if(e==="set"){await jt(r.map(s=>{const n=s.indexOf("=");if(n===-1)throw new $("Invalid format. Use: key=value");const i=s.slice(0,n),c=s.slice(n+1);return[i,c]}));return}if(e==="add"){await Ca(r.map(s=>{const n=s.indexOf("=");if(n===-1)throw new $("Invalid format. Use: key=value");const i=s.slice(0,n),c=s.slice(n+1);return[i,c]}));return}if(e==="list"){await Pa();return}if(e==="del"){if(!o)throw new $("Please provide the config name to delete.");const s=await Oe(),n=o.split(".");if(n.length===2){const[i,c]=n;if(s[i]&&typeof s[i]=="object"&&Ht(s[i],c)){delete s[i][c],Object.keys(s[i]).length===0&&delete s[i];const l=await Ce();await O.writeFile(l,ve.stringify(s),"utf8"),console.log(`Successfully deleted config: ${o}`);const u=await O.readFile(l,"utf8");console.log("--- Updated Config Content ---"),console.log(u),console.log("----------------------------")}else throw new $(`Config not found: ${o}`)}else if(n.length===1){const i=n[0];if(Ht(s,i)){delete s[i];const c=await Ce();await O.writeFile(c,ve.stringify(s),"utf8"),console.log(`Successfully deleted config: ${o}`);const l=await O.readFile(c,"utf8");console.log("--- Updated Config Content ---"),console.log(l),console.log("----------------------------")}else throw new $(`Config not found: ${o}`)}else throw new $(`Invalid config name format: ${o}`);return}if(e==="path"){await $a();return}throw new $(`Invalid mode: ${e}`)})().catch(e=>{new se().printError(e.message),ce(e),process.exit(1)})}),yc=ie({name:"github-login",parameters:[],flags:{token:{type:String,description:"Manually provide a GitHub token for authentication",alias:"t"}},help:{description:"Login to GitHub and setup access to GitHub Models",examples:["aic2 github-login","aic2 github-login --token ghp_xxxxxxxxxxxxxxxxxxxx"]}},t=>{(async()=>{const e=new se;if(t.flags.token){try{await wc(t.flags.token,e)}catch(r){throw new $(`Token authentication failed: ${r.message}`)}return}try{await vc(e)}catch(r){throw new $(`Browser authentication failed: ${r.message}`)}})().catch(e=>{new se().printError(e.message),ce(e),process.exit(1)})});async function wc(t,e){if(e.printWarning("Authenticating with provided token..."),!t.startsWith("ghp_")&&!t.startsWith("gho_")&&!t.startsWith("ghu_"))throw new Error("Invalid token format. GitHub tokens should start with ghp_, gho_, or ghu_");try{const r=await fetch("https://api.github.com/user",{headers:{Authorization:`Bearer ${t}`,Accept:"application/vnd.github.v3+json","User-Agent":"aicommit2-github-models"}});if(!r.ok)throw new Error(`GitHub API request failed: ${r.status} ${r.statusText}`);const o=await r.json();try{(await fetch("https://models.github.ai/inference/chat/completions",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/vnd.github+json",Authorization:`Bearer ${t}`,"User-Agent":"aicommit2-github-models"},body:JSON.stringify({messages:[{role:"user",content:"test"}],model:"gpt-4o-mini",max_tokens:1})})).ok?e.printSuccess("GitHub Models access verified!"):e.printWarning("Could not verify GitHub Models access, but proceeding with authentication...")}catch{e.printWarning("Could not verify GitHub Models access, but proceeding with authentication...")}await jt([["GITHUB_MODELS.key",t]]),e.printSuccess(`Successfully authenticated as ${o.login}`)}catch(r){throw new Error(`Token validation failed: ${r.message}`)}}async function vc(t){t.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")&&t.printInfo("Already authenticated with GitHub CLI")}catch{t.printInfo("Authenticating with GitHub CLI..."),t.printInfo("Please follow the instructions in your browser to complete authentication.");try{je("gh auth login --web -h github.com",{stdio:"inherit"})}catch{throw new Error("GitHub CLI authentication failed")}}t.printInfo("Verifying GitHub Models access...");try{const e=je("gh auth token",{encoding:"utf8"}).trim();e&&(await jt([["GITHUB_MODELS.key",e]]),t.printSuccess("GitHub token stored for GitHub Models access"))}catch{t.printWarning("Could not extract token from GitHub CLI, but authentication completed")}t.printSuccess("GitHub authentication completed and GitHub Models access verified!"),t.printInfo("See usage guide: https://github.com/tak-bro/aicommit2/blob/main/docs/providers/github-models.md"),t.printInfo("Available models: gpt-4o-mini, gpt-4o, meta-llama-3.1-405b-instruct, etc."),t.printInfo("Using GitHub Models API: https://models.github.ai")}catch(e){throw e}}const Wo="prepare-commit-msg",Yo=`.git/hooks/${Wo}`,mt=Tn(new URL("cli.mjs",import.meta.url)),bc=process.argv[1].replace(/\\/g,"/").endsWith(`/${Yo}`),qo=process.platform==="win32",Jo=`
116
116
  #!/usr/bin/env node
117
117
  import(${JSON.stringify(Dn(mt))})
118
- `.trim();var Cc=ie({name:"hook",parameters:["<install/uninstall>"],help:{description:"Install or uninstall the Git prepare-commit-msg hook",examples:["aic2 hook install","aic2 hook uninstall"]}},t=>{(async()=>{const e=await rr(),{installUninstall:r}=t._,o=S.join(e,Yo),s=await ao(o);if(r==="install"){if(s){if(await O.realpath(o).catch(()=>{})===mt){console.warn("The hook is already installed");return}throw new $(`A different ${Wo} hook seems to be installed. Please remove it before installing aicommit2.`)}await O.mkdir(S.dirname(o),{recursive:!0}),qo?await O.writeFile(o,Jo):(await O.symlink(mt,o,"file"),await O.chmod(o,493)),console.log(`${C.green("\u2714")} Hook installed`);return}if(r==="uninstall"){if(!s){console.warn("Hook is not installed");return}if(qo){if(await O.readFile(o,"utf8")!==Jo){console.warn("Hook is not installed");return}}else if(await O.realpath(o)!==mt){console.warn("Hook is not installed");return}await O.rm(o),console.log(`${C.green("\u2714")} Hook uninstalled`);return}throw new $(`Invalid mode: ${r}`)})().catch(e=>{console.error(`${C.red("\u2716")} ${e.message}`),ce(e),process.exit(1)})});const Pc=bn(fn),$c=t=>{const e=["B","KB","MB","GB"];if(t===0)return"0 B";const r=Math.floor(Math.log(t)/Math.log(1024));return Math.round(t/Math.pow(1024,r)*100)/100+" "+e[r]},Ec=t=>t.toLocaleDateString()+" "+t.toLocaleTimeString(),kc=async t=>{try{const e=await Ar(ee);if(e.length===0){console.log(`${C.yellow("No log files found.")}`);return}console.log(`${C.blue("Log files in")} ${ee}:
118
+ `.trim();var Cc=ie({name:"hook",parameters:["<install/uninstall>"],help:{description:"Install or uninstall the Git prepare-commit-msg hook",examples:["aic2 hook install","aic2 hook uninstall"]}},t=>{(async()=>{const e=await tr(),{installUninstall:r}=t._,o=S.join(e,Yo),s=await ao(o);if(r==="install"){if(s){if(await O.realpath(o).catch(()=>{})===mt){console.warn("The hook is already installed");return}throw new $(`A different ${Wo} hook seems to be installed. Please remove it before installing aicommit2.`)}await O.mkdir(S.dirname(o),{recursive:!0}),qo?await O.writeFile(o,Jo):(await O.symlink(mt,o,"file"),await O.chmod(o,493)),console.log(`${C.green("\u2714")} Hook installed`);return}if(r==="uninstall"){if(!s){console.warn("Hook is not installed");return}if(qo){if(await O.readFile(o,"utf8")!==Jo){console.warn("Hook is not installed");return}}else if(await O.realpath(o)!==mt){console.warn("Hook is not installed");return}await O.rm(o),console.log(`${C.green("\u2714")} Hook uninstalled`);return}throw new $(`Invalid mode: ${r}`)})().catch(e=>{console.error(`${C.red("\u2716")} ${e.message}`),ce(e),process.exit(1)})});const Pc=bn(fn),$c=t=>{const e=["B","KB","MB","GB"];if(t===0)return"0 B";const r=Math.floor(Math.log(t)/Math.log(1024));return Math.round(t/Math.pow(1024,r)*100)/100+" "+e[r]},Ec=t=>t.toLocaleDateString()+" "+t.toLocaleTimeString(),kc=async t=>{try{const e=await Ar(ee);if(e.length===0){console.log(`${C.yellow("No log files found.")}`);return}console.log(`${C.blue("Log files in")} ${ee}:
119
119
  `);const r=await Promise.all(e.map(async o=>{const s=ue.join(ee,o),n=await Gn(s);return{name:o,size:$c(n.size),modified:Ec(n.mtime)}}));r.sort((o,s)=>new Date(s.modified).getTime()-new Date(o.modified).getTime()),r.forEach((o,s)=>{console.log(`${s===0?"\u{1F4C4}":" "} ${C.cyan(o.name)} ${C.gray(`(${o.size}, ${o.modified})`)}`)}),console.log(`
120
- ${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}},Ac=async t=>{try{await Ar(ee);const e=process.platform;let r;switch(e){case"darwin":r=`open "${ee}"`;break;case"win32":r=`start "" "${ee}"`;break;default:r=`xdg-open "${ee}"`;break}await Pc(r),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.")}`):t.printError(`Failed to open logs directory: ${e.message}`)}},xc=async t=>{try{await Hn(ee,{recursive:!0,force:!0}),console.log(`${C.green("\u2714")} All log files removed!`)}catch(e){t.printError(`Failed to remove log files: ${e.message}`)}};var Sc=ie({name:"log",parameters:["<action>"],help:{description:"Manage log files generated by the application",examples:["aic2 log list # List all log files","aic2 log path # Show logs directory path","aic2 log open # Open logs directory","aic2 log removeAll # Remove all log files"]}},t=>{(async()=>{const{action:e}=t._,r=new se;switch(e){case"list":await kc();break;case"path":console.log(`${C.blue("Logs directory:")} ${ee}`);break;case"open":await Ac(r);break;case"removeAll":await xc(r);break;default:throw new $(`Invalid action: ${e}. Use 'list', 'path', 'open', or 'removeAll'`)}})().catch(e=>{new se().printError(e.message),ce(e),process.exit(1)})});const Ic=process.argv.slice(2).filter(t=>!t.startsWith("--pre-commit")),[ft,Vo]=Ic;var Mc=()=>(async()=>{if(!ft)throw new $('Commit message file path is missing. This file should be called from the "pre-commit framework"');if(Vo){console.log(`Skipping aicommit2 message generation for ${Vo} commit`);return}const t=await or();if(!t)return;const e=new se;e.printTitle();const r=await Pe({});if(r.systemPromptPath)try{await O.readFile(S.resolve(r.systemPromptPath),"utf-8")}catch{throw new $(`Error reading system prompt file: ${r.systemPromptPath}`)}const o=Object.entries(r).filter(([f])=>be.includes(f)).map(([f,h])=>[f,h]).filter(([f,h])=>!h.disabled).filter(([f,h])=>f==="OLLAMA"?!!h&&!!h.model&&h.model.length>0:f==="HUGGINGFACE"?!!h&&!!h.cookie:!!h.key&&h.key.length>0).map(([f])=>f);if(o.length===0)throw new $("Please set at least one API key via the `aicommit2 config set` command");const n=new ut(r,t);let i;try{i=await vr(n.createCommitMsgRequests$(o).pipe(br(f=>!f.isError),M(f=>f.value),Cr()))}finally{e.printAnalyzed()}const l=await O.readFile(ft,"utf8")!=="",u=i.length>1;let m="";l&&(m=`# \u{1F916} Generated by aicommit2 (https://github.com/tak-bro/aicommit2)
120
+ ${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}},Ac=async t=>{try{await Ar(ee);const e=process.platform;let r;switch(e){case"darwin":r=`open "${ee}"`;break;case"win32":r=`start "" "${ee}"`;break;default:r=`xdg-open "${ee}"`;break}await Pc(r),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.")}`):t.printError(`Failed to open logs directory: ${e.message}`)}},xc=async t=>{try{await Hn(ee,{recursive:!0,force:!0}),console.log(`${C.green("\u2714")} All log files removed!`)}catch(e){t.printError(`Failed to remove log files: ${e.message}`)}};var Sc=ie({name:"log",parameters:["<action>"],help:{description:"Manage log files generated by the application",examples:["aic2 log list # List all log files","aic2 log path # Show logs directory path","aic2 log open # Open logs directory","aic2 log removeAll # Remove all log files"]}},t=>{(async()=>{const{action:e}=t._,r=new se;switch(e){case"list":await kc();break;case"path":console.log(`${C.blue("Logs directory:")} ${ee}`);break;case"open":await Ac(r);break;case"removeAll":await xc(r);break;default:throw new $(`Invalid action: ${e}. Use 'list', 'path', 'open', or 'removeAll'`)}})().catch(e=>{new se().printError(e.message),ce(e),process.exit(1)})});const Ic=process.argv.slice(2).filter(t=>!t.startsWith("--pre-commit")),[ft,Vo]=Ic;var Mc=()=>(async()=>{if(!ft)throw new $('Commit message file path is missing. This file should be called from the "pre-commit framework"');if(Vo){console.log(`Skipping aicommit2 message generation for ${Vo} commit`);return}const t=await rr();if(!t)return;const e=new se;e.printTitle();const r=await Pe({});if(r.systemPromptPath)try{await O.readFile(S.resolve(r.systemPromptPath),"utf-8")}catch{throw new $(`Error reading system prompt file: ${r.systemPromptPath}`)}const o=Object.entries(r).filter(([f])=>be.includes(f)).map(([f,h])=>[f,h]).filter(([f,h])=>!h.disabled).filter(([f,h])=>f==="OLLAMA"?!!h&&!!h.model&&h.model.length>0:f==="HUGGINGFACE"?!!h&&!!h.cookie:!!h.key&&h.key.length>0).map(([f])=>f);if(o.length===0)throw new $("Please set at least one API key via the `aicommit2 config set` command");const n=new ut(r,t);let i;try{i=await wr(n.createCommitMsgRequests$(o).pipe(vr(f=>!f.isError),M(f=>f.value),br()))}finally{e.printAnalyzed()}const l=await O.readFile(ft,"utf8")!=="",u=i.length>1;let m="";l&&(m=`# \u{1F916} Generated by aicommit2 (https://github.com/tak-bro/aicommit2)
121
121
  `,m+=`# ----------------------------------------
122
122
  `,m+=`# How to use:
123
123
  `,u?(m+=`# 1. Remove the "#" from your chosen message
@@ -136,7 +136,7 @@ ${i.map(f=>`# ${f}`).join(`
136
136
  `),m+=`
137
137
  ${i[0]}
138
138
  `);const a=await O.readFile(ft,"utf8"),d=m+`
139
- `+a;await O.writeFile(ft,d),e.printSavedCommitMessage()})().catch(t=>{new se().printError(t.message),ce(t),process.exit(1)});const ar=process.argv.slice(2),Xo=[];let cr=!1;for(let t=0;t<ar.length;t++){const e=ar[t];if(cr){cr=!1;continue}if(e!=="--hook-mode"){if(e.startsWith("-")){const r=ar[t+1];r&&!r.startsWith("-")&&(cr=!0);continue}Xo.push(e)}}const[pt,Qo]=Xo;var Rc=(t,e,r,o,s,n)=>(async()=>{if(!pt)throw new $('Commit message file path is missing. This file should be called from the "prepare-commit-msg" git hook or with --hook-mode flag');if(Qo){console.log(`Skipping aicommit2 message generation for ${Qo} commit`);return}const i=await or();if(!i)return;const c=new se;c.printTitle();const l=await Pe({locale:t?.toString(),generate:e?.toString(),type:o?.toString(),systemPrompt:s?.toString(),includeBody:n?.toString()},r);if(l.systemPromptPath)try{await O.readFile(S.resolve(l.systemPromptPath),"utf-8")}catch{throw new $(`Error reading system prompt file: ${l.systemPromptPath}`)}const u=Object.entries(l).filter(([b])=>be.includes(b)).map(([b,k])=>[b,k]).filter(([b,k])=>!k.disabled).filter(([b,k])=>b==="OLLAMA"?!!k&&!!k.model&&k.model.length>0:b==="HUGGINGFACE"?!!k&&!!k.cookie:!!k.key&&k.key.length>0).map(([b])=>b);if(u.length===0)throw new $("Please set at least one API key via the `aicommit2 config set` command");const a=new ut(l,i),d=c.displaySpinner("The AI is analyzing your changes");let f;try{f=await vr(a.createCommitMsgRequests$(u).pipe(br(b=>!b.isError),M(b=>b.value),Cr()))}finally{d.stop(),d.clear(),c.printAnalyzed()}const g=await O.readFile(pt,"utf8")!=="",y=f.length>1,w=await dc();let v="";g&&(v=`${w} \u{1F916} Generated by aicommit2 (https://github.com/tak-bro/aicommit2)
139
+ `+a;await O.writeFile(ft,d),e.printSavedCommitMessage()})().catch(t=>{new se().printError(t.message),ce(t),process.exit(1)});const ir=process.argv.slice(2),Xo=[];let ar=!1;for(let t=0;t<ir.length;t++){const e=ir[t];if(ar){ar=!1;continue}if(e!=="--hook-mode"){if(e.startsWith("-")){const r=ir[t+1];r&&!r.startsWith("-")&&(ar=!0);continue}Xo.push(e)}}const[pt,Qo]=Xo;var Rc=(t,e,r,o,s,n)=>(async()=>{if(!pt)throw new $('Commit message file path is missing. This file should be called from the "prepare-commit-msg" git hook or with --hook-mode flag');if(Qo){console.log(`Skipping aicommit2 message generation for ${Qo} commit`);return}const i=await rr();if(!i)return;const c=new se;c.printTitle();const l=await Pe({locale:t?.toString(),generate:e?.toString(),type:o?.toString(),systemPrompt:s?.toString(),includeBody:n?.toString()},r);if(l.systemPromptPath)try{await O.readFile(S.resolve(l.systemPromptPath),"utf-8")}catch{throw new $(`Error reading system prompt file: ${l.systemPromptPath}`)}const u=Object.entries(l).filter(([b])=>be.includes(b)).map(([b,k])=>[b,k]).filter(([b,k])=>!k.disabled).filter(([b,k])=>b==="OLLAMA"?!!k&&!!k.model&&k.model.length>0:b==="HUGGINGFACE"?!!k&&!!k.cookie:!!k.key&&k.key.length>0).map(([b])=>b);if(u.length===0)throw new $("Please set at least one API key via the `aicommit2 config set` command");const a=new ut(l,i),d=c.displaySpinner("The AI is analyzing your changes");let f;try{f=await wr(a.createCommitMsgRequests$(u).pipe(vr(b=>!b.isError),M(b=>b.value),br()))}finally{d.stop(),d.clear(),c.printAnalyzed()}const g=await O.readFile(pt,"utf8")!=="",y=f.length>1,w=await dc();let v="";g&&(v=`${w} \u{1F916} Generated by aicommit2 (https://github.com/tak-bro/aicommit2)
140
140
  `,v+=`${w} ----------------------------------------
141
141
  `,v+=`${w} How to use:
142
142
  `,y?(v+=`${w} 1. Remove the "${w}" from your chosen message
@@ -155,13 +155,13 @@ ${w} \u{1F4DD} Generated commit message:
155
155
  `),v+=`
156
156
  ${f[0]}
157
157
  `);const P=await O.readFile(pt,"utf8"),A=v+`
158
- `+P;await O.writeFile(pt,A),c.printSavedCommitMessage()})().catch(i=>{new se().printError(i.message),ce(i),process.exit(1)});let ht=new Pr;const z=new se,Zo=process.cwd(),Oc=S.join(Zo,".git","hooks","post-commit"),He=S.join(Zo,".git","commit-log.txt"),Lc=`#!/bin/sh
158
+ `+P;await O.writeFile(pt,A),c.printSavedCommitMessage()})().catch(i=>{new se().printError(i.message),ce(i),process.exit(1)});let ht=new Cr;const z=new se,Zo=process.cwd(),Oc=S.join(Zo,".git","hooks","post-commit"),He=S.join(Zo,".git","commit-log.txt"),Lc=`#!/bin/sh
159
159
  commit_hash=$(git rev-parse HEAD)
160
160
  commit_message=$(git log -1 --pretty=%B)
161
161
  echo "$commit_hash: $commit_message" >> ${He}
162
- `;let lr=null,H=null;const en=async(t,e,r,o,s)=>{z.printTitle(),await rr();const n=await Nc(t,e,o,s);Fc(),Dc();try{await on(n)}catch(i){return Tc(i),en(t,e,r,o,s)}},Nc=async(t,e,r,o)=>{const s=await Pe({locale:t?.toString(),generate:e?.toString(),systemPrompt:r?.toString()},o);return await yo(s),tn(s).length===0&&(z.printError(`Please set at least one API key and watchMode via the config command:
162
+ `;let cr=null,j=null;const en=async(t,e,r,o,s)=>{z.printTitle(),await tr();const n=await Nc(t,e,o,s);Fc(),Dc();try{await on(n)}catch(i){return Tc(i),en(t,e,r,o,s)}},Nc=async(t,e,r,o)=>{const s=await Pe({locale:t?.toString(),generate:e?.toString(),systemPrompt:r?.toString()},o);return await yo(s),tn(s).length===0&&(z.printError(`Please set at least one API key and watchMode via the config command:
163
163
  aicommit2 config set [MODEL].key="YOUR_API_KEY"
164
164
  aicommit2 config set [MODEL].watchMode="true"`),process.exit()),s},Tc=async t=>{z.printError(`An error occurred: ${t.message}`),ce(t),await new Promise(e=>setTimeout(e,3e3)),z.printWarning("Restarting the commit monitoring process...")},Dc=()=>{oe.writeFileSync(He,"",{flag:"w"})},tn=t=>Object.entries(t).filter(([e,r])=>be.includes(e)||r.compatible===!0).map(([e,r])=>[e,r]).filter(([e,r])=>!r.disabled).filter(([e,r])=>_c(e,r,t)).map(([e])=>e),_c=(t,e,r)=>{const o=r.watchMode||e.watchMode;return t==="OLLAMA"?!!e&&!!e.model&&e.model.length>0&&o:t==="HUGGINGFACE"?!!e&&!!e.cookie&&o:e.compatible?!!e.url&&!!e.key&&o:!!e.key&&e.key.length>0&&o},Fc=()=>{oe.writeFileSync(Oc,Lc,{mode:493}),z.printSetupGitEvent("post-commit")},rn=()=>{process.stdout.write("\x1Bc")},Gc=async(t,e)=>{try{const r=await uc(e);if(!r){z.printWarning("No changes found in this commit");return}z.stopLoader(),z.printStagedFiles(r);const o=tn(t);if(o.length===0){z.printError(`Please set at least one API key and watchMode via the config command:
165
165
  aicommit2 config set [MODEL].key="YOUR_API_KEY"
166
- aicommit2 config set [MODEL].watchMode="true"`),process.exit();return}await Hc(t,r,o)}catch(r){z.printError(`Error processing commit ${e}: ${r.message}`)}},Hc=async(t,e,r)=>{jc();const o=new ut(t,e);H=new ir(Bo);const s=Bc();H.startLoader(),lr=Uc(o,r),await s,zc()},jc=()=>{H&&(lr?.unsubscribe(),H.clearLoader(),H.completeSubject(),H.cancel(),H.closeInquirerInstance()),ht.next(),ht.complete(),ht=new Pr},Bc=()=>H.initPrompt({...sr,name:"codeReviewPrompt",message:"Please check code reviews: ",emptyMessage:`\u26A0 ${Uo}`,isDescriptionDim:!1,stopMessage:"Code review completed",descPageSize:20}),Uc=(t,e)=>t.createCodeReviewRequests$(e).pipe(Bn(ht)).subscribe(r=>{H?.refreshChoices(r)},()=>{},()=>{H?.checkErrorOnChoices(!1)}),zc=()=>{H&&(lr?.unsubscribe(),H.clearLoader(),H.completeSubject(),H.cancel(),H.closeInquirerInstance(),H=null),rn(),z.showLoader("Watching for new Git commits...")},on=async t=>{const e=jn.watch(He,{persistent:!0});e.on("change",async()=>{try{const r=await Kc();for(const o of r)o&&await Wc(t,o)}catch(r){z.printError(`Error reading or processing commit log: ${r.message}`)}finally{Yc()}}),e.on("error",qc(t))},Kc=async()=>(await oe.promises.readFile(He,"utf8")).trim().split(`
167
- `),Wc=async(t,e)=>{const[r]=e.split(":");if(!r){z.printWarning("Empty commit hash detected, skipping...");return}rn(),await Gc(t,r.trim())},Yc=()=>{try{oe.truncateSync(He)}catch(t){z.printError(`Error truncating log file: ${t.message}`)}},qc=t=>e=>{z.printError(`Watcher error: ${e.message}`),setTimeout(()=>on(t),1e3)},ur=process.argv.slice(2),{version:nn,description:Jc}=os;ln({name:"aicommit2",version:nn,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}},commands:[gc,yc,Cc,Sc],help:{description:Jc},ignoreArgv:t=>t==="unknown-flag"||t==="argument"},async t=>{const e=await Pe({});if(await Sa(e),$e.info(`aicommit2 version: ${nn}`),t.flags["pre-commit"]){Mc();return}if(t.flags["hook-mode"]||bc){Rc(t.flags.locale,t.flags.generate,t.flags.exclude,t.flags.type,t.flags.prompt,t.flags["include-body"]);return}if(t.flags["watch-commit"]){en(t.flags.locale,t.flags.generate,t.flags.exclude,t.flags.prompt,ur);return}fc(t.flags.locale,t.flags.generate,t.flags.exclude,t.flags.all,t.flags.type,t.flags.confirm,t.flags.clipboard,t.flags.prompt,t.flags["include-body"],t.flags["auto-select"],ur)},ur);
166
+ aicommit2 config set [MODEL].watchMode="true"`),process.exit();return}await Hc(t,r,o)}catch(r){z.printError(`Error processing commit ${e}: ${r.message}`)}},Hc=async(t,e,r)=>{jc();const o=new ut(t,e);j=new sr(Bo);const s=Bc();j.startLoader(),cr=Uc(o,r),await s,zc()},jc=()=>{j&&(cr?.unsubscribe(),j.clearLoader(),j.completeSubject(),j.cancel(),j.closeInquirerInstance()),ht.next(),ht.complete(),ht=new Cr},Bc=()=>j.initPrompt({...nr,name:"codeReviewPrompt",message:"Please check code reviews: ",emptyMessage:`\u26A0 ${Uo}`,isDescriptionDim:!1,stopMessage:"Code review completed",descPageSize:20}),Uc=(t,e)=>t.createCodeReviewRequests$(e).pipe(Bn(ht)).subscribe(r=>{j?.refreshChoices(r)},()=>{},()=>{j?.checkErrorOnChoices(!1)}),zc=()=>{j&&(cr?.unsubscribe(),j.clearLoader(),j.completeSubject(),j.cancel(),j.closeInquirerInstance(),j=null),rn(),z.showLoader("Watching for new Git commits...")},on=async t=>{const e=jn.watch(He,{persistent:!0});e.on("change",async()=>{try{const r=await Kc();for(const o of r)o&&await Wc(t,o)}catch(r){z.printError(`Error reading or processing commit log: ${r.message}`)}finally{Yc()}}),e.on("error",qc(t))},Kc=async()=>(await oe.promises.readFile(He,"utf8")).trim().split(`
167
+ `),Wc=async(t,e)=>{const[r]=e.split(":");if(!r){z.printWarning("Empty commit hash detected, skipping...");return}rn(),await Gc(t,r.trim())},Yc=()=>{try{oe.truncateSync(He)}catch(t){z.printError(`Error truncating log file: ${t.message}`)}},qc=t=>e=>{z.printError(`Watcher error: ${e.message}`),setTimeout(()=>on(t),1e3)},lr=process.argv.slice(2),{version:nn,description:Jc}=os;ln({name:"aicommit2",version:nn,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}},commands:[gc,yc,Cc,Sc],help:{description:Jc},ignoreArgv:t=>t==="unknown-flag"||t==="argument"},async t=>{const e=await Pe({});if(await Sa(e),$e.info(`aicommit2 version: ${nn}`),t.flags["pre-commit"]){Mc();return}if(t.flags["hook-mode"]||bc){Rc(t.flags.locale,t.flags.generate,t.flags.exclude,t.flags.type,t.flags.prompt,t.flags["include-body"]);return}if(t.flags["watch-commit"]){en(t.flags.locale,t.flags.generate,t.flags.exclude,t.flags.prompt,lr);return}fc(t.flags.locale,t.flags.generate,t.flags.exclude,t.flags.all,t.flags.type,t.flags.confirm,t.flags.clipboard,t.flags.prompt,t.flags["include-body"],t.flags["auto-select"],lr)},lr);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "aicommit2",
3
- "version": "2.3.4",
3
+ "version": "2.3.6",
4
4
  "description": "A Reactive CLI that generates git commit messages with various AI",
5
5
  "keywords": [
6
6
  "cli",