aicommit2 2.4.2 → 2.4.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +23 -1
- package/dist/cli.mjs +81 -81
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -268,6 +268,9 @@ aicommit2 --all # or -a
|
|
|
268
268
|
- When enabled and only one AI provider is configured, the generated message is automatically selected
|
|
269
269
|
- Also skips the confirmation prompt for a seamless experience
|
|
270
270
|
- Has no effect when multiple AI providers are configured
|
|
271
|
+
- `--disable-lowercase`: Disable automatic lowercase conversion of commit messages (default: **false**)
|
|
272
|
+
- Preserves the original casing of commit types and descriptions
|
|
273
|
+
- Useful when working with custom commit conventions that require specific casing
|
|
271
274
|
- `--hook-mode`: Run as a Git hook, typically used with prepare-commit-msg hook (default: **false**)
|
|
272
275
|
- This mode is automatically enabled when running through the Git hook system
|
|
273
276
|
- See [Git hook](#git-hook) section for more details
|
|
@@ -487,6 +490,7 @@ Please check the documentation for each specific model to confirm which settings
|
|
|
487
490
|
| `logging` | Enable logging | true |
|
|
488
491
|
| `includeBody` | Whether the commit message includes body | false |
|
|
489
492
|
| `maxLength` | Maximum character length of the Subject of generated commit message | 50 |
|
|
493
|
+
| `disableLowerCase` | Disable automatic lowercase conversion of commit messages | false |
|
|
490
494
|
| `timeout` | Request timeout (milliseconds) | 10000 |
|
|
491
495
|
| `temperature` | Model's creativity (0.0 - 2.0) | 0.7 |
|
|
492
496
|
| `maxTokens` | Maximum number of tokens to generate | 1024 |
|
|
@@ -632,6 +636,24 @@ Default: `50`
|
|
|
632
636
|
aicommit2 config set maxLength=100
|
|
633
637
|
```
|
|
634
638
|
|
|
639
|
+
##### disableLowerCase
|
|
640
|
+
|
|
641
|
+
Disable automatic lowercase conversion of commit messages
|
|
642
|
+
|
|
643
|
+
Default: `false`
|
|
644
|
+
|
|
645
|
+
By default, AICommit2 converts the first character of commit types and descriptions to lowercase to follow conventional commit standards. Set this to `true` to preserve the original casing.
|
|
646
|
+
|
|
647
|
+
```sh
|
|
648
|
+
aicommit2 config set disableLowerCase=true
|
|
649
|
+
```
|
|
650
|
+
|
|
651
|
+
You can also use the CLI flag:
|
|
652
|
+
|
|
653
|
+
```sh
|
|
654
|
+
aicommit2 --disable-lowercase
|
|
655
|
+
```
|
|
656
|
+
|
|
635
657
|
##### timeout
|
|
636
658
|
|
|
637
659
|
The timeout for network requests in milliseconds.
|
|
@@ -737,7 +759,7 @@ aicommit2 config set codeReviewPromptPath="/path/to/user/prompt.txt"
|
|
|
737
759
|
|
|
738
760
|
> All AI support the following options in General Settings.
|
|
739
761
|
>
|
|
740
|
-
> - systemPrompt, systemPromptPath, codeReview, codeReviewPromptPath, exclude, type, locale, generate, logging, includeBody, maxLength
|
|
762
|
+
> - systemPrompt, systemPromptPath, codeReview, codeReviewPromptPath, exclude, type, locale, generate, logging, includeBody, maxLength, disableLowerCase
|
|
741
763
|
|
|
742
764
|
## Configuration Examples
|
|
743
765
|
|
package/dist/cli.mjs
CHANGED
|
@@ -1,21 +1,21 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{command as se,cli as fn}from"cleye";import{createRequire as pn}from"module";import H from"fs";import xe from"os";import x from"path";import{Buffer as hn}from"node:buffer";import le from"node:path";import fr,{ChildProcess as gn,exec as yn}from"node:child_process";import ie from"node:process";import wn,{execSync as He}from"child_process";import{fileURLToPath as pr}from"node:url";import vn,{constants as hr}from"node:os";import gr from"assert";import yr from"events";import{createWriteStream as bn,createReadStream as Cn}from"node:fs";import Pn from"buffer";import ht from"stream";import wr from"util";import{debuglog as $n,promisify as En}from"node:util";import Ue from"inquirer";import C from"chalk";import{of as Ae,concatMap as L,from as A,map as I,catchError as M,mergeMap as ze,BehaviorSubject as vr,ReplaySubject as kn,lastValueFrom as br,filter as Cr,toArray as Pr,Subject as $r}from"rxjs";import xn from"@anthropic-ai/sdk";import{fromPromise as D}from"rxjs/internal/observable/innerFrom";import{xxh64 as Er}from"@pacote/xxhash";import z from"winston";import R from"fs/promises";import"winston-daily-rotate-file";import An from"axios";import{CohereClient as Sn}from"cohere-ai";import kr from"openai";import{GoogleGenerativeAI as In,HarmCategory as Ke,HarmBlockThreshold as Je}from"@google/generative-ai";import Mn from"http";import Rn from"https";import On from"net";import Ln from"tls";import Dn,{fileURLToPath as jn,pathToFileURL as Nn}from"url";import xr from"tty";import Tn from"groq-sdk";import{Ollama as Fn}from"ollama";import{fetch as _n,Agent as Gn}from"undici";import We from"readline";import Bn from"figlet";import Ar from"ora";import Hn from"inquirer-reactive-list-prompt";import{readdir as Sr,stat as Un,rm as zn}from"node:fs/promises";import Kn from"chokidar";import{takeUntil as Jn}from"rxjs/operators";var Wn="aicommit2",Ir="2.4.2",Yn="A Reactive CLI that generates commit messages for Git and Jujutsu with various AI",qn=["cli","ai","git","jujutsu","jj","vcs","version-control","commit","git-commit","jujutsu-commit","command-line","commandline","aipick","aicommit","aicommits","aicommit2","openai","huggingface","anthropic","claude","claude3","gemini","gemini-pro","generative-ai","mistral","ollama","llama3","llama3.2","llama3.3","gemma","llm","chatgpt","cohere","groq","codestral","perplexity","deepseek","deepseek-r1","pre-commit"],Vn="MIT",Xn="tak-bro/aicommit2",Qn="Hyungtak Jin(@tak-bro)",Zn="module",es=["dist"],ts={aicommit2:"./dist/cli.mjs",aic2:"./dist/cli.mjs"},rs={prepare:"simple-git-hooks",build:"pkgroll --minify",lint:"eslint --cache .","type-check":"tsc",test:"tsx tests",prepack:"pnpm build && clean-pkg-json",prettier:"prettier"},os={"@anthropic-ai/sdk":"^0.39.0","@dqbd/tiktoken":"^1.0.21","@google/generative-ai":"^0.24.1","@inquirer/prompts":"^3.3.2","@pacote/xxhash":"^0.3.2","@types/winston":"^2.4.4",axios:"^1.9.0",chalk:"^5.4.1",chokidar:"^4.0.3",cleye:"^1.3.4","cohere-ai":"^7.17.1","copy-paste":"^1.5.3",figlet:"^1.8.1","formdata-node":"^6.0.3","groq-sdk":"^0.7.0",inquirer:"9.2.8","inquirer-reactive-list-prompt":"^1.0.15",ollama:"^0.5.15",openai:"^5.0.1",ora:"^8.2.0",readline:"^1.3.0",rxjs:"^7.8.2",undici:"^7.10.0",uuid:"^9.0.1",winston:"^3.17.0","winston-daily-rotate-file":"^5.0.0"},ns={"@pvtnbr/eslint-config":"^0.33.0","@semantic-release/changelog":"^6.0.3","@semantic-release/commit-analyzer":"^12.0.0","@semantic-release/git":"^10.0.1","@semantic-release/github":"^10.3.5","@semantic-release/npm":"^12.0.1","@semantic-release/release-notes-generator":"^13.0.0","@types/figlet":"^1.7.0","@types/ini":"^1.3.34","@types/inquirer":"^9.0.8","@types/node":"^18.19.103","@types/uuid":"^9.0.8","@typescript-eslint/eslint-plugin":"^6.21.0","@typescript-eslint/parser":"^6.21.0","clean-pkg-json":"^1.3.0","conventional-changelog-conventionalcommits":"^7.0.2","conventional-commits-parser":"^5.0.0",eslint:"^8.57.1","eslint-config-prettier":"^8.10.0","eslint-plugin-eslint-comments":"^3.2.0","eslint-plugin-import":"^2.31.0","eslint-plugin-jsonc":"^2.20.1","eslint-plugin-no-use-extend-native":"^0.5.0","eslint-plugin-promise":"^6.6.0","eslint-plugin-unicorn":"^49.0.0","eslint-plugin-unused-imports":"^3.2.0",execa:"^7.2.0","fs-fixture":"^1.2.0","https-proxy-agent":"^5.0.1",ini:"^3.0.1","lint-staged":"^13.3.0",manten:"^0.7.0",pkgroll:"^1.11.1",prettier:"^3.5.3","semantic-release":"^23.1.1","simple-git-hooks":"^2.13.0",tsx:"^3.14.0",typescript:"^4.9.5","undici-types":"^7.10.0"},ss={extends:["@pvtnbr","prettier"],rules:{"unicorn/no-process-exit":"off"},overrides:[{files:"./src/commands/prepare-commit-msg-hook.ts",rules:{"unicorn/prevent-abbreviations":"off"}}]},is={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"]},as={name:Wn,version:Ir,description:Yn,keywords:qn,license:Vn,repository:Xn,author:Qn,type:Zn,files:es,bin:ts,scripts:rs,"simple-git-hooks":{"pre-commit":"pnpm lint-staged"},"lint-staged":{"*.ts":["prettier --config ./.prettierrc --write","eslint --fix"]},dependencies:os,devDependencies:ns,eslintConfig:ss,release:is},cs=pn(import.meta.url),B=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:{}},gt,Mr;function ls(){if(Mr)return gt;Mr=1,gt=o,o.sync=n;var t=H;function e(s,i){var c=i.pathExt!==void 0?i.pathExt:process.env.PATHEXT;if(!c||(c=c.split(";"),c.indexOf("")!==-1))return!0;for(var a=0;a<c.length;a++){var f=c[a].toLowerCase();if(f&&s.substr(-f.length).toLowerCase()===f)return!0}return!1}function r(s,i,c){return!s.isSymbolicLink()&&!s.isFile()?!1:e(i,c)}function o(s,i,c){t.stat(s,function(a,f){c(a,a?!1:r(f,s,i))})}function n(s,i){return r(t.statSync(s),s,i)}return gt}var yt,Rr;function us(){if(Rr)return yt;Rr=1,yt=e,e.sync=r;var t=H;function e(s,i,c){t.stat(s,function(a,f){c(a,a?!1:o(f,i))})}function r(s,i){return o(t.statSync(s),i)}function o(s,i){return s.isFile()&&n(s,i)}function n(s,i){var c=s.mode,a=s.uid,f=s.gid,u=i.uid!==void 0?i.uid:process.getuid&&process.getuid(),l=i.gid!==void 0?i.gid:process.getgid&&process.getgid(),d=parseInt("100",8),m=parseInt("010",8),h=parseInt("001",8),g=d|m,y=c&h||c&m&&f===l||c&d&&a===u||c&g&&u===0;return y}return yt}var Ye;process.platform==="win32"||B.TESTING_WINDOWS?Ye=ls():Ye=us();var ds=wt;wt.sync=ms;function wt(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,n){wt(t,e||{},function(s,i){s?n(s):o(i)})})}Ye(t,e||{},function(o,n){o&&(o.code==="EACCES"||e&&e.ignoreErrors)&&(o=null,n=!1),r(o,n)})}function ms(t,e){try{return Ye.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",Or=x,fs=he?";":":",Lr=ds,Dr=t=>Object.assign(new Error(`not found: ${t}`),{code:"ENOENT"}),jr=(t,e)=>{const r=e.colon||fs,o=t.match(/\//)||he&&t.match(/\\/)?[""]:[...he?[process.cwd()]:[],...(e.path||process.env.PATH||"").split(r)],n=he?e.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",s=he?n.split(r):[""];return he&&t.indexOf(".")!==-1&&s[0]!==""&&s.unshift(""),{pathEnv:o,pathExt:s,pathExtExe:n}},Nr=(t,e,r)=>{typeof e=="function"&&(r=e,e={}),e||(e={});const{pathEnv:o,pathExt:n,pathExtExe:s}=jr(t,e),i=[],c=f=>new Promise((u,l)=>{if(f===o.length)return e.all&&i.length?u(i):l(Dr(t));const d=o[f],m=/^".*"$/.test(d)?d.slice(1,-1):d,h=Or.join(m,t),g=!m&&/^\.[\\\/]/.test(t)?t.slice(0,2)+h:h;u(a(g,f,0))}),a=(f,u,l)=>new Promise((d,m)=>{if(l===n.length)return d(c(u+1));const h=n[l];Lr(f+h,{pathExt:s},(g,y)=>{if(!g&&y)if(e.all)i.push(f+h);else return d(f+h);return d(a(f,u,l+1))})});return r?c(0).then(f=>r(null,f),r):c(0)},ps=(t,e)=>{e=e||{};const{pathEnv:r,pathExt:o,pathExtExe:n}=jr(t,e),s=[];for(let i=0;i<r.length;i++){const c=r[i],a=/^".*"$/.test(c)?c.slice(1,-1):c,f=Or.join(a,t),u=!a&&/^\.[\\\/]/.test(t)?t.slice(0,2)+f:f;for(let l=0;l<o.length;l++){const d=u+o[l];try{if(Lr.sync(d,{pathExt:n}))if(e.all)s.push(d);else return d}catch{}}}if(e.all&&s.length)return s;if(e.nothrow)return null;throw Dr(t)};var hs=Nr;Nr.sync=ps;var vt={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"};vt.exports=Tr,vt.exports.default=Tr;var gs=vt.exports;const Fr=x,ys=hs,ws=gs;function _r(t,e){const r=t.options.env||process.env,o=process.cwd(),n=t.options.cwd!=null,s=n&&process.chdir!==void 0&&!process.chdir.disabled;if(s)try{process.chdir(t.options.cwd)}catch{}let i;try{i=ys.sync(t.command,{path:r[ws({env:r})],pathExt:e?Fr.delimiter:void 0})}catch{}finally{s&&process.chdir(o)}return i&&(i=Fr.resolve(n?t.options.cwd:"",i)),i}function vs(t){return _r(t)||_r(t,!0)}var bs=vs,bt={};const Ct=/([()\][%!^"`<>&|;, *?])/g;function Cs(t){return t=t.replace(Ct,"^$1"),t}function Ps(t,e){return t=`${t}`,t=t.replace(/(?=(\\+?)?)\1"/g,'$1$1\\"'),t=t.replace(/(?=(\\+?)?)\1$/,"$1$1"),t=`"${t}"`,t=t.replace(Ct,"^$1"),e&&(t=t.replace(Ct,"^$1")),t}bt.command=Cs,bt.argument=Ps;var $s=/^#!(.*)/;const Es=$s;var ks=(t="")=>{const e=t.match(Es);if(!e)return null;const[r,o]=e[0].replace(/#! ?/,"").split(" "),n=r.split("/").pop();return n==="env"?o:o?`${n} ${o}`:n};const Pt=H,xs=ks;function As(t){const r=Buffer.alloc(150);let o;try{o=Pt.openSync(t,"r"),Pt.readSync(o,r,0,150,0),Pt.closeSync(o)}catch{}return xs(r.toString())}var Ss=As;const Is=x,Gr=bs,Br=bt,Ms=Ss,Rs=process.platform==="win32",Os=/\.(?:com|exe)$/i,Ls=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function Ds(t){t.file=Gr(t);const e=t.file&&Ms(t.file);return e?(t.args.unshift(t.file),t.command=e,Gr(t)):t.file}function js(t){if(!Rs)return t;const e=Ds(t),r=!Os.test(e);if(t.options.forceShell||r){const o=Ls.test(e);t.command=Is.normalize(t.command),t.command=Br.command(t.command),t.args=t.args.map(s=>Br.argument(s,o));const n=[t.command].concat(t.args).join(" ");t.args=["/d","/s","/c",`"${n}"`],t.command=process.env.comspec||"cmd.exe",t.options.windowsVerbatimArguments=!0}return t}function Ns(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:js(o)}var Ts=Ns;const $t=process.platform==="win32";function Et(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 Fs(t,e){if(!$t)return;const r=t.emit;t.emit=function(o,n){if(o==="exit"){const s=Hr(n,e);if(s)return r.call(t,"error",s)}return r.apply(t,arguments)}}function Hr(t,e){return $t&&t===1&&!e.file?Et(e.original,"spawn"):null}function _s(t,e){return $t&&t===1&&!e.file?Et(e.original,"spawnSync"):null}var Gs={hookChildProcess:Fs,verifyENOENT:Hr,verifyENOENTSync:_s,notFoundError:Et};const Ur=wn,kt=Ts,xt=Gs;function zr(t,e,r){const o=kt(t,e,r),n=Ur.spawn(o.command,o.args,o.options);return xt.hookChildProcess(n,o),n}function Bs(t,e,r){const o=kt(t,e,r),n=Ur.spawnSync(o.command,o.args,o.options);return n.error=n.error||xt.verifyENOENTSync(n.status,o),n}pe.exports=zr,pe.exports.spawn=zr,pe.exports.sync=Bs,pe.exports._parse=kt,pe.exports._enoent=xt;var Hs=pe.exports,Us=fe(Hs);function zs(t){const e=typeof t=="string"?`
|
|
2
|
+
import{command as se,cli as fn}from"cleye";import{createRequire as pn}from"module";import H from"fs";import xe from"os";import A from"path";import{Buffer as hn}from"node:buffer";import le from"node:path";import fr,{ChildProcess as gn,exec as yn}from"node:child_process";import ie from"node:process";import wn,{execSync as He}from"child_process";import{fileURLToPath as pr}from"node:url";import vn,{constants as hr}from"node:os";import gr from"assert";import yr from"events";import{createWriteStream as bn,createReadStream as Cn}from"node:fs";import Pn from"buffer";import ht from"stream";import wr from"util";import{debuglog as $n,promisify as En}from"node:util";import Ue from"inquirer";import P from"chalk";import{of as Ae,concatMap as L,from as S,map as M,catchError as R,mergeMap as ze,BehaviorSubject as vr,ReplaySubject as kn,lastValueFrom as br,filter as Cr,toArray as Pr,Subject as $r}from"rxjs";import xn from"@anthropic-ai/sdk";import{fromPromise as D}from"rxjs/internal/observable/innerFrom";import{xxh64 as Er}from"@pacote/xxhash";import z from"winston";import O from"fs/promises";import"winston-daily-rotate-file";import An from"axios";import{CohereClient as Sn}from"cohere-ai";import kr from"openai";import{GoogleGenerativeAI as In,HarmCategory as Ke,HarmBlockThreshold as Je}from"@google/generative-ai";import Mn from"http";import Rn from"https";import On from"net";import Ln from"tls";import Dn,{fileURLToPath as jn,pathToFileURL as Nn}from"url";import xr from"tty";import Tn from"groq-sdk";import{Ollama as Fn}from"ollama";import{fetch as _n,Agent as Gn}from"undici";import We from"readline";import Bn from"figlet";import Ar from"ora";import Hn from"inquirer-reactive-list-prompt";import{readdir as Sr,stat as Un,rm as zn}from"node:fs/promises";import Kn from"chokidar";import{takeUntil as Jn}from"rxjs/operators";var Wn="aicommit2",Ir="2.4.4",Yn="A Reactive CLI that generates commit messages for Git and Jujutsu with various AI",Vn=["cli","ai","git","jujutsu","jj","vcs","version-control","commit","git-commit","jujutsu-commit","command-line","commandline","aipick","aicommit","aicommits","aicommit2","openai","huggingface","anthropic","claude","claude3","gemini","gemini-pro","generative-ai","mistral","ollama","llama3","llama3.2","llama3.3","gemma","llm","chatgpt","cohere","groq","codestral","perplexity","deepseek","deepseek-r1","pre-commit"],qn="MIT",Xn="tak-bro/aicommit2",Qn="Hyungtak Jin(@tak-bro)",Zn="module",es=["dist"],ts={aicommit2:"./dist/cli.mjs",aic2:"./dist/cli.mjs"},rs={prepare:"simple-git-hooks",build:"pkgroll --minify",lint:"eslint --cache .","type-check":"tsc",test:"tsx tests",prepack:"pnpm build && clean-pkg-json",prettier:"prettier"},os={"@anthropic-ai/sdk":"^0.39.0","@dqbd/tiktoken":"^1.0.21","@google/generative-ai":"^0.24.1","@inquirer/prompts":"^3.3.2","@pacote/xxhash":"^0.3.2","@types/winston":"^2.4.4",axios:"^1.9.0",chalk:"^5.4.1",chokidar:"^4.0.3",cleye:"^1.3.4","cohere-ai":"^7.17.1","copy-paste":"^1.5.3",figlet:"^1.8.1","formdata-node":"^6.0.3","groq-sdk":"^0.7.0",inquirer:"9.2.8","inquirer-reactive-list-prompt":"^1.0.15",ollama:"^0.5.15",openai:"^5.0.1",ora:"^8.2.0",readline:"^1.3.0",rxjs:"^7.8.2",undici:"^7.10.0",uuid:"^9.0.1",winston:"^3.17.0","winston-daily-rotate-file":"^5.0.0"},ns={"@pvtnbr/eslint-config":"^0.33.0","@semantic-release/changelog":"^6.0.3","@semantic-release/commit-analyzer":"^12.0.0","@semantic-release/git":"^10.0.1","@semantic-release/github":"^10.3.5","@semantic-release/npm":"^12.0.1","@semantic-release/release-notes-generator":"^13.0.0","@types/figlet":"^1.7.0","@types/ini":"^1.3.34","@types/inquirer":"^9.0.8","@types/node":"^18.19.103","@types/uuid":"^9.0.8","@typescript-eslint/eslint-plugin":"^6.21.0","@typescript-eslint/parser":"^6.21.0","clean-pkg-json":"^1.3.0","conventional-changelog-conventionalcommits":"^7.0.2","conventional-commits-parser":"^5.0.0",eslint:"^8.57.1","eslint-config-prettier":"^8.10.0","eslint-plugin-eslint-comments":"^3.2.0","eslint-plugin-import":"^2.31.0","eslint-plugin-jsonc":"^2.20.1","eslint-plugin-no-use-extend-native":"^0.5.0","eslint-plugin-promise":"^6.6.0","eslint-plugin-unicorn":"^49.0.0","eslint-plugin-unused-imports":"^3.2.0",execa:"^7.2.0","fs-fixture":"^1.2.0","https-proxy-agent":"^5.0.1",ini:"^3.0.1","lint-staged":"^13.3.0",manten:"^0.7.0",pkgroll:"^1.11.1",prettier:"^3.5.3","semantic-release":"^23.1.1","simple-git-hooks":"^2.13.0",tsx:"^3.14.0",typescript:"^4.9.5","undici-types":"^7.10.0"},ss={extends:["@pvtnbr","prettier"],rules:{"unicorn/no-process-exit":"off"},overrides:[{files:"./src/commands/prepare-commit-msg-hook.ts",rules:{"unicorn/prevent-abbreviations":"off"}}]},is={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"]},as={name:Wn,version:Ir,description:Yn,keywords:Vn,license:qn,repository:Xn,author:Qn,type:Zn,files:es,bin:ts,scripts:rs,"simple-git-hooks":{"pre-commit":"pnpm lint-staged"},"lint-staged":{"*.ts":["prettier --config ./.prettierrc --write","eslint --fix"]},dependencies:os,devDependencies:ns,eslintConfig:ss,release:is},cs=pn(import.meta.url),B=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:{}},gt,Mr;function ls(){if(Mr)return gt;Mr=1,gt=o,o.sync=n;var t=H;function e(s,i){var c=i.pathExt!==void 0?i.pathExt:process.env.PATHEXT;if(!c||(c=c.split(";"),c.indexOf("")!==-1))return!0;for(var a=0;a<c.length;a++){var m=c[a].toLowerCase();if(m&&s.substr(-m.length).toLowerCase()===m)return!0}return!1}function r(s,i,c){return!s.isSymbolicLink()&&!s.isFile()?!1:e(i,c)}function o(s,i,c){t.stat(s,function(a,m){c(a,a?!1:r(m,s,i))})}function n(s,i){return r(t.statSync(s),s,i)}return gt}var yt,Rr;function us(){if(Rr)return yt;Rr=1,yt=e,e.sync=r;var t=H;function e(s,i,c){t.stat(s,function(a,m){c(a,a?!1:o(m,i))})}function r(s,i){return o(t.statSync(s),i)}function o(s,i){return s.isFile()&&n(s,i)}function n(s,i){var c=s.mode,a=s.uid,m=s.gid,d=i.uid!==void 0?i.uid:process.getuid&&process.getuid(),l=i.gid!==void 0?i.gid:process.getgid&&process.getgid(),p=parseInt("100",8),u=parseInt("010",8),h=parseInt("001",8),g=p|u,y=c&h||c&u&&m===l||c&p&&a===d||c&g&&d===0;return y}return yt}var Ye;process.platform==="win32"||B.TESTING_WINDOWS?Ye=ls():Ye=us();var ds=wt;wt.sync=ms;function wt(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,n){wt(t,e||{},function(s,i){s?n(s):o(i)})})}Ye(t,e||{},function(o,n){o&&(o.code==="EACCES"||e&&e.ignoreErrors)&&(o=null,n=!1),r(o,n)})}function ms(t,e){try{return Ye.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",Or=A,fs=he?";":":",Lr=ds,Dr=t=>Object.assign(new Error(`not found: ${t}`),{code:"ENOENT"}),jr=(t,e)=>{const r=e.colon||fs,o=t.match(/\//)||he&&t.match(/\\/)?[""]:[...he?[process.cwd()]:[],...(e.path||process.env.PATH||"").split(r)],n=he?e.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",s=he?n.split(r):[""];return he&&t.indexOf(".")!==-1&&s[0]!==""&&s.unshift(""),{pathEnv:o,pathExt:s,pathExtExe:n}},Nr=(t,e,r)=>{typeof e=="function"&&(r=e,e={}),e||(e={});const{pathEnv:o,pathExt:n,pathExtExe:s}=jr(t,e),i=[],c=m=>new Promise((d,l)=>{if(m===o.length)return e.all&&i.length?d(i):l(Dr(t));const p=o[m],u=/^".*"$/.test(p)?p.slice(1,-1):p,h=Or.join(u,t),g=!u&&/^\.[\\\/]/.test(t)?t.slice(0,2)+h:h;d(a(g,m,0))}),a=(m,d,l)=>new Promise((p,u)=>{if(l===n.length)return p(c(d+1));const h=n[l];Lr(m+h,{pathExt:s},(g,y)=>{if(!g&&y)if(e.all)i.push(m+h);else return p(m+h);return p(a(m,d,l+1))})});return r?c(0).then(m=>r(null,m),r):c(0)},ps=(t,e)=>{e=e||{};const{pathEnv:r,pathExt:o,pathExtExe:n}=jr(t,e),s=[];for(let i=0;i<r.length;i++){const c=r[i],a=/^".*"$/.test(c)?c.slice(1,-1):c,m=Or.join(a,t),d=!a&&/^\.[\\\/]/.test(t)?t.slice(0,2)+m:m;for(let l=0;l<o.length;l++){const p=d+o[l];try{if(Lr.sync(p,{pathExt:n}))if(e.all)s.push(p);else return p}catch{}}}if(e.all&&s.length)return s;if(e.nothrow)return null;throw Dr(t)};var hs=Nr;Nr.sync=ps;var vt={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"};vt.exports=Tr,vt.exports.default=Tr;var gs=vt.exports;const Fr=A,ys=hs,ws=gs;function _r(t,e){const r=t.options.env||process.env,o=process.cwd(),n=t.options.cwd!=null,s=n&&process.chdir!==void 0&&!process.chdir.disabled;if(s)try{process.chdir(t.options.cwd)}catch{}let i;try{i=ys.sync(t.command,{path:r[ws({env:r})],pathExt:e?Fr.delimiter:void 0})}catch{}finally{s&&process.chdir(o)}return i&&(i=Fr.resolve(n?t.options.cwd:"",i)),i}function vs(t){return _r(t)||_r(t,!0)}var bs=vs,bt={};const Ct=/([()\][%!^"`<>&|;, *?])/g;function Cs(t){return t=t.replace(Ct,"^$1"),t}function Ps(t,e){return t=`${t}`,t=t.replace(/(?=(\\+?)?)\1"/g,'$1$1\\"'),t=t.replace(/(?=(\\+?)?)\1$/,"$1$1"),t=`"${t}"`,t=t.replace(Ct,"^$1"),e&&(t=t.replace(Ct,"^$1")),t}bt.command=Cs,bt.argument=Ps;var $s=/^#!(.*)/;const Es=$s;var ks=(t="")=>{const e=t.match(Es);if(!e)return null;const[r,o]=e[0].replace(/#! ?/,"").split(" "),n=r.split("/").pop();return n==="env"?o:o?`${n} ${o}`:n};const Pt=H,xs=ks;function As(t){const r=Buffer.alloc(150);let o;try{o=Pt.openSync(t,"r"),Pt.readSync(o,r,0,150,0),Pt.closeSync(o)}catch{}return xs(r.toString())}var Ss=As;const Is=A,Gr=bs,Br=bt,Ms=Ss,Rs=process.platform==="win32",Os=/\.(?:com|exe)$/i,Ls=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function Ds(t){t.file=Gr(t);const e=t.file&&Ms(t.file);return e?(t.args.unshift(t.file),t.command=e,Gr(t)):t.file}function js(t){if(!Rs)return t;const e=Ds(t),r=!Os.test(e);if(t.options.forceShell||r){const o=Ls.test(e);t.command=Is.normalize(t.command),t.command=Br.command(t.command),t.args=t.args.map(s=>Br.argument(s,o));const n=[t.command].concat(t.args).join(" ");t.args=["/d","/s","/c",`"${n}"`],t.command=process.env.comspec||"cmd.exe",t.options.windowsVerbatimArguments=!0}return t}function Ns(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:js(o)}var Ts=Ns;const $t=process.platform==="win32";function Et(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 Fs(t,e){if(!$t)return;const r=t.emit;t.emit=function(o,n){if(o==="exit"){const s=Hr(n,e);if(s)return r.call(t,"error",s)}return r.apply(t,arguments)}}function Hr(t,e){return $t&&t===1&&!e.file?Et(e.original,"spawn"):null}function _s(t,e){return $t&&t===1&&!e.file?Et(e.original,"spawnSync"):null}var Gs={hookChildProcess:Fs,verifyENOENT:Hr,verifyENOENTSync:_s,notFoundError:Et};const Ur=wn,kt=Ts,xt=Gs;function zr(t,e,r){const o=kt(t,e,r),n=Ur.spawn(o.command,o.args,o.options);return xt.hookChildProcess(n,o),n}function Bs(t,e,r){const o=kt(t,e,r),n=Ur.spawnSync(o.command,o.args,o.options);return n.error=n.error||xt.verifyENOENTSync(n.status,o),n}pe.exports=zr,pe.exports.spawn=zr,pe.exports.sync=Bs,pe.exports._parse=kt,pe.exports._enoent=xt;var Hs=pe.exports,Us=fe(Hs);function zs(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 Kr(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 Ks=({cwd:t=ie.cwd(),path:e=ie.env[Kr()],preferLocal:r=!0,execPath:o=ie.execPath,addExecPath:n=!0}={})=>{const s=t instanceof URL?pr(t):t,i=le.resolve(s),c=[];return r&&Js(c,i),n&&Ws(c,o,i),[...c,e].join(le.delimiter)},Js=(t,e)=>{let r;for(;r!==e;)t.push(le.join(e,"node_modules/.bin")),r=e,e=le.resolve(e,"..")},Ws=(t,e,r)=>{const o=e instanceof URL?pr(e):e;t.push(le.resolve(r,o,".."))},Ys=({env:t=ie.env,...e}={})=>{t={...t};const r=Kr({env:t});return e.path=t[r],t[r]=Ks(e),t},
|
|
5
|
-
${e}`,Zs=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),ei=Object.getOwnPropertyDescriptor(Function.prototype.toString,"name"),ti=(t,e,r)=>{const o=r===""?"":`with ${r.trim()}() `,n=Qs.bind(null,o,e.toString());Object.defineProperty(n,"name",ei),Object.defineProperty(t,"toString",{...Zs,value:n})};function ri(t,e,{ignoreNonConfigurable:r=!1}={}){const{name:o}=t;for(const n of Reflect.ownKeys(e))
|
|
4
|
+
`.charCodeAt(),r=typeof t=="string"?"\r":"\r".charCodeAt();return t[t.length-1]===e&&(t=t.slice(0,-1)),t[t.length-1]===r&&(t=t.slice(0,-1)),t}function Kr(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 Ks=({cwd:t=ie.cwd(),path:e=ie.env[Kr()],preferLocal:r=!0,execPath:o=ie.execPath,addExecPath:n=!0}={})=>{const s=t instanceof URL?pr(t):t,i=le.resolve(s),c=[];return r&&Js(c,i),n&&Ws(c,o,i),[...c,e].join(le.delimiter)},Js=(t,e)=>{let r;for(;r!==e;)t.push(le.join(e,"node_modules/.bin")),r=e,e=le.resolve(e,"..")},Ws=(t,e,r)=>{const o=e instanceof URL?pr(e):e;t.push(le.resolve(r,o,".."))},Ys=({env:t=ie.env,...e}={})=>{t={...t};const r=Kr({env:t});return e.path=t[r],t[r]=Ks(e),t},Vs=(t,e,r,o)=>{if(r==="length"||r==="prototype"||r==="arguments"||r==="caller")return;const n=Object.getOwnPropertyDescriptor(t,r),s=Object.getOwnPropertyDescriptor(e,r);!qs(n,s)&&o||Object.defineProperty(t,r,s)},qs=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)},Xs=(t,e)=>{const r=Object.getPrototypeOf(e);r!==Object.getPrototypeOf(t)&&Object.setPrototypeOf(t,r)},Qs=(t,e)=>`/* Wrapped ${t}*/
|
|
5
|
+
${e}`,Zs=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),ei=Object.getOwnPropertyDescriptor(Function.prototype.toString,"name"),ti=(t,e,r)=>{const o=r===""?"":`with ${r.trim()}() `,n=Qs.bind(null,o,e.toString());Object.defineProperty(n,"name",ei),Object.defineProperty(t,"toString",{...Zs,value:n})};function ri(t,e,{ignoreNonConfigurable:r=!1}={}){const{name:o}=t;for(const n of Reflect.ownKeys(e))Vs(t,e,n,r);return Xs(t,e),ti(t,e,o),t}const Ve=new WeakMap,Jr=(t,e={})=>{if(typeof t!="function")throw new TypeError("Expected a function");let r,o=0;const n=t.displayName||t.name||"<anonymous>",s=function(...i){if(Ve.set(s,++o),o===1)r=t.apply(this,i),t=null;else if(e.throw===!0)throw new Error(`Function \`${n}\` can only be called once`);return r};return ri(s,t),Ve.set(s,o),s};Jr.callCount=t=>{if(!Ve.has(t))throw new Error(`The given function \`${t.name}\` is not wrapped by the \`onetime\` package`);return Ve.get(t)};const oi=()=>{const t=Yr-Wr+1;return Array.from({length:t},ni)},ni=(t,e)=>({name:`SIGRT${e+1}`,number:Wr+e,action:"terminate",description:"Application-specific signal (realtime)",standard:"posix"}),Wr=34,Yr=64,si=[{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"}],Vr=()=>{const t=oi();return[...si,...t].map(ii)},ii=({name:t,number:e,description:r,action:o,forced:n=!1,standard:s})=>{const{signals:{[t]:i}}=hr,c=i!==void 0;return{name:t,number:c?i:e,description:r,supported:c,action:o,forced:n,standard:s}},ai=()=>{const t=Vr();return Object.fromEntries(t.map(ci))},ci=({name:t,number:e,description:r,supported:o,action:n,forced:s,standard:i})=>[t,{name:t,number:e,description:r,supported:o,action:n,forced:s,standard:i}],li=ai(),ui=()=>{const t=Vr(),e=Yr+1,r=Array.from({length:e},(o,n)=>di(n,t));return Object.assign({},...r)},di=(t,e)=>{const r=mi(t,e);if(r===void 0)return{};const{name:o,description:n,supported:s,action:i,forced:c,standard:a}=r;return{[t]:{name:o,number:t,description:n,supported:s,action:i,forced:c,standard:a}}},mi=(t,e)=>{const r=e.find(({name:o})=>hr.signals[o]===t);return r!==void 0?r:e.find(o=>o.number===t)};ui();const fi=({timedOut:t,timeout:e,errorCode:r,signal:o,signalDescription:n,exitCode:s,isCanceled:i})=>t?`timed out after ${e} milliseconds`:i?"was canceled":r!==void 0?`failed with ${r}`:o!==void 0?`was killed with ${o} (${n})`:s!==void 0?`failed with exit code ${s}`:"failed",qr=({stdout:t,stderr:e,all:r,error:o,signal:n,exitCode:s,command:i,escapedCommand:c,timedOut:a,isCanceled:m,killed:d,parsed:{options:{timeout:l,cwd:p=ie.cwd()}}})=>{s=s===null?void 0:s,n=n===null?void 0:n;const u=n===void 0?void 0:li[n].description,h=o&&o.code,y=`Command ${fi({timedOut:a,timeout:l,errorCode:h,signal:n,signalDescription:u,exitCode:s,isCanceled:m})}: ${i}`,w=Object.prototype.toString.call(o)==="[object Error]",v=w?`${y}
|
|
6
6
|
${o.message}`:y,E=[v,e,t].filter(Boolean).join(`
|
|
7
|
-
`);return w?(o.originalMessage=o.message,o.message=E):o=new Error(E),o.shortMessage=v,o.command=i,o.escapedCommand=c,o.exitCode=s,o.signal=n,o.signalDescription=
|
|
8
|
-
`)},la=1e3*1e3*100,ua=({env:t,extendEnv:e,preferLocal:r,localDir:o,execPath:n})=>{const s=e?{...ie.env,...t}:t;return r?Ys({env:s,cwd:o,execPath:n}):s},da=(t,e,r={})=>{const o=Us._parse(t,e,r);return t=o.command,e=o.args,r=o.options,r={maxBuffer:la,buffer:!0,stripFinalNewline:!0,extendEnv:!0,preferLocal:!1,localDir:r.cwd||ie.cwd(),execPath:ie.execPath,encoding:"utf8",reject:!0,cleanup:!0,all:!1,windowsHide:!0,verbose:ia,...r},r.env=ua(r),r.stdio=hi(r),ie.platform==="win32"&&le.basename(t,".exe")==="cmd"&&e.unshift("/q"),{file:t,args:e,options:r,parsed:o}},Dt=(t,e,r)=>typeof e!="string"&&!hn.isBuffer(e)?r===void 0?void 0:"":t.stripFinalNewline?zs(e):e;function F(t,e,r){const o=da(t,e,r),n=na(t,e),s=sa(t,e);ca(s,o.options),Oi(o.options);let i;try{i=fr.spawn(o.file,o.args,o.options)}catch(
|
|
7
|
+
`);return w?(o.originalMessage=o.message,o.message=E):o=new Error(E),o.shortMessage=v,o.command=i,o.escapedCommand=c,o.exitCode=s,o.signal=n,o.signalDescription=u,o.stdout=t,o.stderr=e,o.cwd=p,r!==void 0&&(o.all=r),"bufferedData"in o&&delete o.bufferedData,o.failed=!0,o.timedOut=!!a,o.isCanceled=m,o.killed=d&&!a,o},qe=["stdin","stdout","stderr"],pi=t=>qe.some(e=>t[e]!==void 0),hi=t=>{if(!t)return;const{stdio:e}=t;if(e===void 0)return qe.map(o=>t[o]);if(pi(t))throw new Error(`It's not possible to provide \`stdio\` in combination with one of ${qe.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,qe.length);return Array.from({length:r},(o,n)=>e[n])};var ge={exports:{}},Xe={exports:{}};Xe.exports;var Xr;function gi(){return Xr||(Xr=1,function(t){t.exports=["SIGABRT","SIGALRM","SIGHUP","SIGINT","SIGTERM"],process.platform!=="win32"&&t.exports.push("SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT"),process.platform==="linux"&&t.exports.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT","SIGUNUSED")}(Xe)),Xe.exports}var T=B.process;const ue=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(!ue(T))ge.exports=function(){return function(){}};else{var yi=gr,Se=gi(),wi=/^win/i.test(T.platform),Qe=yr;typeof Qe!="function"&&(Qe=Qe.EventEmitter);var U;T.__signal_exit_emitter__?U=T.__signal_exit_emitter__:(U=T.__signal_exit_emitter__=new Qe,U.count=0,U.emitted={}),U.infinite||(U.setMaxListeners(1/0),U.infinite=!0),ge.exports=function(t,e){if(!ue(B.process))return function(){};yi.equal(typeof t,"function","a callback must be provided for exit handler"),Ie===!1&&Qr();var r="exit";e&&e.alwaysLast&&(r="afterexit");var o=function(){U.removeListener(r,t),U.listeners("exit").length===0&&U.listeners("afterexit").length===0&&At()};return U.on(r,t),o};var At=function(){!Ie||!ue(B.process)||(Ie=!1,Se.forEach(function(e){try{T.removeListener(e,St[e])}catch{}}),T.emit=It,T.reallyExit=Zr,U.count-=1)};ge.exports.unload=At;var ye=function(e,r,o){U.emitted[e]||(U.emitted[e]=!0,U.emit(e,r,o))},St={};Se.forEach(function(t){St[t]=function(){if(ue(B.process)){var r=T.listeners(t);r.length===U.count&&(At(),ye("exit",null,t),ye("afterexit",null,t),wi&&t==="SIGHUP"&&(t="SIGINT"),T.kill(T.pid,t))}}}),ge.exports.signals=function(){return Se};var Ie=!1,Qr=function(){Ie||!ue(B.process)||(Ie=!0,U.count+=1,Se=Se.filter(function(e){try{return T.on(e,St[e]),!0}catch{return!1}}),T.emit=bi,T.reallyExit=vi)};ge.exports.load=Qr;var Zr=T.reallyExit,vi=function(e){ue(B.process)&&(T.exitCode=e||0,ye("exit",T.exitCode,null),ye("afterexit",T.exitCode,null),Zr.call(T,T.exitCode))},It=T.emit,bi=function(e,r){if(e==="exit"&&ue(B.process)){r!==void 0&&(T.exitCode=r);var o=It.apply(this,arguments);return ye("exit",T.exitCode,null),ye("afterexit",T.exitCode,null),o}else return It.apply(this,arguments)}}var Ci=ge.exports,Pi=fe(Ci);const $i=1e3*5,Ei=(t,e="SIGTERM",r={})=>{const o=t(e);return ki(t,e,r,o),o},ki=(t,e,r,o)=>{if(!xi(e,r,o))return;const n=Si(r),s=setTimeout(()=>{t("SIGKILL")},n);s.unref&&s.unref()},xi=(t,{forceKillAfterTimeout:e},r)=>Ai(t)&&e!==!1&&r,Ai=t=>t===vn.constants.signals.SIGTERM||typeof t=="string"&&t.toUpperCase()==="SIGTERM",Si=({forceKillAfterTimeout:t=!0})=>{if(t===!0)return $i;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},Ii=(t,e)=>{t.kill()&&(e.isCanceled=!0)},Mi=(t,e,r)=>{t.kill(e),r(Object.assign(new Error("Timed out"),{timedOut:!0,signal:e}))},Ri=(t,{timeout:e,killSignal:r="SIGTERM"},o)=>{if(e===0||e===void 0)return o;let n;const s=new Promise((c,a)=>{n=setTimeout(()=>{Mi(t,r,a)},e)}),i=o.finally(()=>{clearTimeout(n)});return Promise.race([s,i])},Oi=({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})`)},Li=async(t,{cleanup:e,detached:r},o)=>{if(!e||r)return o;const n=Pi(()=>{t.kill()});return o.finally(()=>{n()})};function eo(t){return t!==null&&typeof t=="object"&&typeof t.pipe=="function"}function to(t){return eo(t)&&t.writable!==!1&&typeof t._write=="function"&&typeof t._writableState=="object"}const Di=t=>t instanceof gn&&typeof t.then=="function",Mt=(t,e,r)=>{if(typeof r=="string")return t[e].pipe(bn(r)),t;if(to(r))return t[e].pipe(r),t;if(!Di(r))throw new TypeError("The second argument must be a string, a stream or an Execa child process.");if(!to(r.stdin))throw new TypeError("The target child process's stdin must be available.");return t[e].pipe(r.stdin),r},ji=t=>{t.stdout!==null&&(t.pipeStdout=Mt.bind(void 0,t,"stdout")),t.stderr!==null&&(t.pipeStderr=Mt.bind(void 0,t,"stderr")),t.all!==void 0&&(t.pipeAll=Mt.bind(void 0,t,"all"))};var Me={exports:{}};const{PassThrough:Ni}=ht;var Ti=t=>{t={...t};const{array:e}=t;let{encoding:r}=t;const o=r==="buffer";let n=!1;e?n=!(r||o):r=r||"utf8",o&&(r=null);const s=new Ni({objectMode:n});r&&s.setEncoding(r);let i=0;const c=[];return s.on("data",a=>{c.push(a),n?i=c.length:i+=a.length}),s.getBufferedValue=()=>e?c:o?Buffer.concat(c,i):c.join(""),s.getBufferedLength=()=>i,s};const{constants:Fi}=Pn,_i=ht,{promisify:Gi}=wr,Bi=Ti,Hi=Gi(_i.pipeline);class ro extends Error{constructor(){super("maxBuffer exceeded"),this.name="MaxBufferError"}}async function Rt(t,e){if(!t)throw new Error("Expected a stream");e={maxBuffer:1/0,...e};const{maxBuffer:r}=e,o=Bi(e);return await new Promise((n,s)=>{const i=c=>{c&&o.getBufferedLength()<=Fi.MAX_LENGTH&&(c.bufferedData=o.getBufferedValue()),s(c)};(async()=>{try{await Hi(t,o),n()}catch(c){i(c)}})(),o.on("data",()=>{o.getBufferedLength()>r&&i(new ro)})}),o.getBufferedValue()}Me.exports=Rt,Me.exports.buffer=(t,e)=>Rt(t,{...e,encoding:"buffer"}),Me.exports.array=(t,e)=>Rt(t,{...e,array:!0}),Me.exports.MaxBufferError=ro;var Ui=Me.exports,oo=fe(Ui);const{PassThrough:zi}=ht;var Ki=function(){var t=[],e=new zi({objectMode:!0});return e.setMaxListeners(0),e.add=r,e.isEmpty=o,e.on("unpipe",n),Array.prototype.slice.call(arguments).forEach(r),e;function r(s){return Array.isArray(s)?(s.forEach(r),this):(t.push(s),s.once("end",n.bind(null,s)),s.once("error",e.emit.bind(e,"error")),s.pipe(e,{end:!1}),this)}function o(){return t.length==0}function n(s){t=t.filter(function(i){return i!==s}),!t.length&&e.readable&&e.end()}},Ji=fe(Ki);const Wi=t=>{if(t!==void 0)throw new TypeError("The `input` and `inputFile` options cannot be both set.")},Yi=({input:t,inputFile:e})=>typeof e!="string"?t:(Wi(t),Cn(e)),Vi=(t,e)=>{const r=Yi(e);r!==void 0&&(eo(r)?r.pipe(t.stdin):t.stdin.end(r))},qi=(t,{all:e})=>{if(!e||!t.stdout&&!t.stderr)return;const r=Ji();return t.stdout&&r.add(t.stdout),t.stderr&&r.add(t.stderr),r},Ot=async(t,e)=>{if(!(!t||e===void 0)){t.destroy();try{return await e}catch(r){return r.bufferedData}}},Lt=(t,{encoding:e,buffer:r,maxBuffer:o})=>{if(!(!t||!r))return e?oo(t,{encoding:e,maxBuffer:o}):oo.buffer(t,{maxBuffer:o})},Xi=async({stdout:t,stderr:e,all:r},{encoding:o,buffer:n,maxBuffer:s},i)=>{const c=Lt(t,{encoding:o,buffer:n,maxBuffer:s}),a=Lt(e,{encoding:o,buffer:n,maxBuffer:s}),m=Lt(r,{encoding:o,buffer:n,maxBuffer:s*2});try{return await Promise.all([i,c,a,m])}catch(d){return Promise.all([{error:d,signal:d.signal,timedOut:d.timedOut},Ot(t,c),Ot(e,a),Ot(r,m)])}},Qi=(async()=>{})().constructor.prototype,Zi=["then","catch","finally"].map(t=>[t,Reflect.getOwnPropertyDescriptor(Qi,t)]),no=(t,e)=>{for(const[r,o]of Zi){const n=typeof e=="function"?(...s)=>Reflect.apply(o.value,e(),s):o.value.bind(e);Reflect.defineProperty(t,r,{...o,value:n})}},ea=t=>new Promise((e,r)=>{t.on("exit",(o,n)=>{e({exitCode:o,signal:n})}),t.on("error",o=>{r(o)}),t.stdin&&t.stdin.on("error",o=>{r(o)})}),so=(t,e=[])=>Array.isArray(e)?[t,...e]:[t],ta=/^[\w.-]+$/,ra=/"/g,oa=t=>typeof t!="string"||ta.test(t)?t:`"${t.replace(ra,'\\"')}"`,na=(t,e)=>so(t,e).join(" "),sa=(t,e)=>so(t,e).map(r=>oa(r)).join(" "),ia=$n("execa").enabled,Ze=(t,e)=>String(t).padStart(e,"0"),aa=()=>{const t=new Date;return`${Ze(t.getHours(),2)}:${Ze(t.getMinutes(),2)}:${Ze(t.getSeconds(),2)}.${Ze(t.getMilliseconds(),3)}`},ca=(t,{verbose:e})=>{e&&ie.stderr.write(`[${aa()}] ${t}
|
|
8
|
+
`)},la=1e3*1e3*100,ua=({env:t,extendEnv:e,preferLocal:r,localDir:o,execPath:n})=>{const s=e?{...ie.env,...t}:t;return r?Ys({env:s,cwd:o,execPath:n}):s},da=(t,e,r={})=>{const o=Us._parse(t,e,r);return t=o.command,e=o.args,r=o.options,r={maxBuffer:la,buffer:!0,stripFinalNewline:!0,extendEnv:!0,preferLocal:!1,localDir:r.cwd||ie.cwd(),execPath:ie.execPath,encoding:"utf8",reject:!0,cleanup:!0,all:!1,windowsHide:!0,verbose:ia,...r},r.env=ua(r),r.stdio=hi(r),ie.platform==="win32"&&le.basename(t,".exe")==="cmd"&&e.unshift("/q"),{file:t,args:e,options:r,parsed:o}},Dt=(t,e,r)=>typeof e!="string"&&!hn.isBuffer(e)?r===void 0?void 0:"":t.stripFinalNewline?zs(e):e;function F(t,e,r){const o=da(t,e,r),n=na(t,e),s=sa(t,e);ca(s,o.options),Oi(o.options);let i;try{i=fr.spawn(o.file,o.args,o.options)}catch(u){const h=new fr.ChildProcess,g=Promise.reject(qr({error:u,stdout:"",stderr:"",all:"",command:n,escapedCommand:s,parsed:o,timedOut:!1,isCanceled:!1,killed:!1}));return no(h,g),h}const c=ea(i),a=Ri(i,o.options,c),m=Li(i,o.options,a),d={isCanceled:!1};i.kill=Ei.bind(null,i.kill.bind(i)),i.cancel=Ii.bind(null,i,d);const p=Jr(async()=>{const[{error:u,exitCode:h,signal:g,timedOut:y},w,v,E]=await Xi(i,o.options,m),x=Dt(o.options,w),$=Dt(o.options,v),C=Dt(o.options,E);if(u||h!==0||g!==null){const I=qr({error:u,exitCode:h,signal:g,stdout:x,stderr:$,all:C,command:n,escapedCommand:s,parsed:o,timedOut:y,isCanceled:d.isCanceled||(o.options.signal?o.options.signal.aborted:!1),killed:i.killed});if(!o.options.reject)return I;throw I}return{command:n,escapedCommand:s,exitCode:0,stdout:x,stderr:$,all:C,failed:!1,timedOut:!1,isCanceled:!1,killed:!1}});return Vi(i,o.options),i.all=qi(i,o.options),ji(i),no(i,p),i}class j{static create(e,r){return new e(r)}}const{hasOwnProperty:jt}=Object.prototype,et=typeof process<"u"&&process.platform==="win32"?`\r
|
|
9
9
|
`:`
|
|
10
|
-
`,Nt=(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 n=e.whitespace?" = ":"=";for(const s of Object.keys(t)){const i=t[s];if(i&&Array.isArray(i))for(const c of i)o+=we(s+"[]")+n+we(c)+et;else i&&typeof i=="object"?r.push(s):o+=we(s)+n+we(i)+et}e.section&&o.length&&(o="["+we(e.section)+"]"+et+o);for(const s of r){const i=io(s).join("\\."),c=(e.section?e.section+".":"")+i,{whitespace:a}=e,
|
|
10
|
+
`,Nt=(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 n=e.whitespace?" = ":"=";for(const s of Object.keys(t)){const i=t[s];if(i&&Array.isArray(i))for(const c of i)o+=we(s+"[]")+n+we(c)+et;else i&&typeof i=="object"?r.push(s):o+=we(s)+n+we(i)+et}e.section&&o.length&&(o="["+we(e.section)+"]"+et+o);for(const s of r){const i=io(s).join("\\."),c=(e.section?e.section+".":"")+i,{whitespace:a}=e,m=Nt(t[s],{section:c,whitespace:a});o.length&&m.length&&(o+=et),o+=m}return o},io=t=>t.replace(/\1/g,"LITERAL\\1LITERAL").replace(/\\\./g,"").split(/\./).map(e=>e.replace(/\1/g,"\\.").replace(/\2LITERAL\\1LITERAL\2/g,"")),ao=t=>{const e=Object.create(null);let r=e,o=null;const n=/^\[([^\]]*)\]$|^([^=]+)(=(.*))?$/i,s=t.split(/[\r\n]+/g);for(const c of s){if(!c||c.match(/^\s*[;#]/))continue;const a=c.match(n);if(!a)continue;if(a[1]!==void 0){if(o=tt(a[1]),o==="__proto__"){r=Object.create(null);continue}r=e[o]=e[o]||Object.create(null);continue}const m=tt(a[2]),d=m.length>2&&m.slice(-2)==="[]",l=d?m.slice(0,-2):m;if(l==="__proto__")continue;const p=a[3]?tt(a[4]):!0,u=p==="true"||p==="false"||p==="null"?JSON.parse(p):p;d&&(jt.call(r,l)?Array.isArray(r[l])||(r[l]=[r[l]]):r[l]=[]),Array.isArray(r[l])?r[l].push(u):r[l]=u}const i=[];for(const c of Object.keys(e)){if(!jt.call(e,c)||typeof e[c]!="object"||Array.isArray(e[c]))continue;const a=io(c);r=e;const m=a.pop(),d=m.replace(/\\\./g,".");for(const l of a)l!=="__proto__"&&((!jt.call(r,l)||typeof r[l]!="object")&&(r[l]=Object.create(null)),r=r[l]);r===e&&d===m||(r[d]=e[c],i.push(c))}for(const c of i)delete e[c];return e},co=t=>t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'"),we=t=>typeof t!="string"||t.match(/[=\r\n]/)||t.match(/^\[/)||t.length>1&&co(t)||t!==t.trim()?JSON.stringify(t):t.split(";").join("\\;").split("#").join("\\#"),tt=(t,e)=>{if(t=(t||"").trim(),co(t)){t.charAt(0)==="'"&&(t=t.slice(1,-1));try{t=JSON.parse(t)}catch{}}else{let r=!1,o="";for(let n=0,s=t.length;n<s;n++){const i=t.charAt(n);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 ma={parse:ao,decode:ao,stringify:Nt,encode:Nt,safe:we,unsafe:tt},ve=fe(ma);class b extends Error{}const Tt=" ",ae=t=>{t instanceof Error&&(t instanceof b||(t.stack&&console.error(P.dim(t.stack.split(`
|
|
11
11
|
`).slice(1).join(`
|
|
12
12
|
`))),console.error(`
|
|
13
|
-
${Tt}${
|
|
14
|
-
${Tt}Please open a Bug report with the information above:`),console.error(`${Tt}https://github.com/tak-bro/aicommit2/issues/new/choose`)))},lo=t=>R.lstat(t).then(()=>!0,()=>!1),uo=async t=>{try{await R.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},fa=(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),[]),mo=(t,e=5)=>t.replace(/[\n\r]/g,"").split(" ").slice(0,e).join(" "),pa=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)},ha=t=>{const e=t%360,r=65+t%15,o=45+t%10;return`hsl(${e}, ${r}%, ${o}%)`},ga=t=>{const[e,r,o]=t.match(/\d+/g).map((l,d)=>d===0?Number(l):Number(l)/100),n=(1-Math.abs(2*o-1))*r,s=n*(1-Math.abs(e/60%2-1)),i=o-n/2;let c,a,f;e<60?[c,a,f]=[n,s,0]:e<120?[c,a,f]=[s,n,0]:e<180?[c,a,f]=[0,n,s]:e<240?[c,a,f]=[0,s,n]:e<300?[c,a,f]=[s,0,n]:[c,a,f]=[n,0,s];const u=l=>{const d=Math.round((l+i)*255).toString(16);return d.length===1?"0"+d:d};return`#${u(c)}${u(a)}${u(f)}`},ya=t=>{const e=pa(t),r=ha(e);return{primary:ga(r),secondary:"#FFFFFF"}},wa=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(x.isAbsolute(t))return x.resolve(t);if(Oe){const e=x.dirname(Oe),r=x.join(e,t);return x.resolve(r)}else return""},va=["","conventional","gitmoji","jujutsu"],Ft="http://localhost:11434",{hasOwnProperty:ba}=Object.prototype,_t=(t,e)=>ba.call(t,e),be=["OPENAI","OLLAMA","HUGGINGFACE","GEMINI","ANTHROPIC","MISTRAL","CODESTRAL","COHERE","GROQ","PERPLEXITY","DEEPSEEK","GITHUB_MODELS"],fo=t=>{const e=xe.platform(),r=xe.homedir();let o,n;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"?n=x.join(r,"Library","Caches"):n=x.join(r,"Application Support");else if(e==="win32")n=process.env.LOCALAPPDATA||r;else switch(t){case"config":n=x.join(r,".config");break;case"data":n=x.join(r,".local","share");break;case"cache":n=x.join(r,".cache");break;case"state":n=x.join(r,".local","state");break;default:n=r}return o||n},Ca=x.join(fo("config"),"aicommit2"),re=x.join(fo("state"),"aicommit2","logs"),po=x.join(Ca,"config.ini"),ho=x.join(re,"aicommit2-%DATE%.log"),go=x.join(re,"exceptions-%DATE%.log"),Pa=t=>{const e=Object.keys(t),r=new Set([...be,...e.filter(o=>/^[A-Z][A-Z0-9_]*$/.test(o))]);return Array.from(r)},k=(t,e,r)=>{if(!e)throw new b(`Invalid config property ${t}: ${r}`)},p={systemPrompt(t){return t||""},systemPromptPath(t){return t||""},codeReviewPromptPath(t){return t||""},timeout(t){if(!t)return 1e4;k("timeout",/^\d+$/.test(t),"Must be an integer");const e=Number(t);return k("timeout",e>=500,"Must be greater than 500ms"),e},temperature(t){if(!t)return .7;k("temperature",/^(2|\d)(\.\d{1,2})?$/.test(t),"Must be decimal between 0 and 2");const e=Number(t);return k("temperature",e>0,"Must be greater than 0"),k("temperature",e<=2,"Must be less than or equal to 2"),e},maxTokens(t){return t?(k("maxTokens",/^\d+$/.test(t),"Must be an integer"),Number(t)):1024},logging(t){return typeof t=="boolean"?t:t==null?!0:(k("logging",/^(?:true|false)$/.test(t),"Must be a boolean(true or false)"),t==="true")},logLevel(t){return t?(k("logLevel",/^(?:error|warn|info|http|verbose|debug|silly)$/.test(t),"Must be a valid log level (error, warn, info, http, verbose, debug, silly)"),t):"info"},logFilePath(t){return t||ho},exceptionLogFilePath(t){return t||go},locale(t){return t?(k("locale",t,"Cannot be empty"),k("locale",/^[a-z-]+$/i.test(t),"Must be a valid locale (letters and dashes/underscores). You can consult the list of codes in: https://wikipedia.org/wiki/List_of_ISO_639-1_codes"),t):"en"},generate(t){if(!t)return 1;k("generate",/^\d+$/.test(t),"Must be an integer");const e=Number(t);return k("generate",e>0,"Must be greater than 0"),k("generate",e<=5,"Must be less or equal to 5"),e},type(t){return t?(k("type",va.includes(t),"Invalid commit type"),t):"conventional"},maxLength(t){if(!t)return 50;k("maxLength",/^\d+$/.test(t),"Must be an integer");const e=Number(t);return k("maxLength",e>=20,"Must be greater than 20 characters"),e},includeBody(t){return typeof t=="boolean"?t:t==null?!1:(k("includeBody",/^(?:true|false)$/.test(t),"Must be a boolean(true or false)"),t==="true")},exclude:t=>t?(typeof t=="string"?t?.split(","):t).map(r=>r.trim()).filter(r=>!!r&&r.length>0):[],topP:t=>{if(!t)return .9;k("topP",/^(1|\d)(\.\d{1,2})?$/.test(t),"Must be decimal between 0 and 1");const e=Number(t);return k("topP",e>0,"Must be greater than 0"),k("topP",e<=1,"Must be less than or equal to 1"),e},codeReview(t){return typeof t=="boolean"?t:t==null?!1:(k("codeReview",/^(?:true|false)$/.test(t),"Must be a boolean(true or false)"),t==="true")},disabled(t){return typeof t=="boolean"?t:t==null?!1:(k("disabled",/^(?:true|false)$/.test(t),"Must be a boolean(true or false)"),t==="true")},watchMode(t){return typeof t=="boolean"?t:t==null?!1:(k("watchMode",/^(?:true|false)$/.test(t),"Must be a boolean(true or false)"),t==="true")},jujutsu(t){return typeof t=="boolean"?t:t==null?!1:(k("jujutsu",/^(?:true|false)$/.test(t),"Must be a boolean(true or false)"),t==="true")}},Re={OPENAI:{key:t=>t||"",envKey:t=>t||"",model:t=>t?(typeof t=="string"?t?.split(","):t).map(r=>r.trim()).filter(r=>!!r&&r.length>0):["gpt-4o-mini"],url:t=>t?(k("OPENAI.url",/^https?:\/\//.test(t),"Must be a valid URL"),t):"https://api.openai.com",path:t=>t||"/v1/chat/completions",proxy:t=>t||"",topP: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?(k("OLLAMA.host",/^https?:\/\//.test(t),"Must be a valid URL"),t):Ft,timeout:t=>{if(!t)return 1e5;k("OLLAMA.timeout",/^\d+$/.test(t),"Must be an integer");const e=Number(t);return k("OLLAMA.timeout",e>=500,"Must be greater than 500ms"),e},auth:t=>t||"",key:t=>t||"",envKey:t=>t||"",numCtx:t=>{if(!t)return 2048;k("OLLAMA.numCtx",/^\d+$/.test(t),"Must be an integer");const e=Number(t);return k("OLLAMA.numCtx",e>=2048,"Must be greater than 2048"),e},systemPrompt: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 Oe;const $a=(t=[])=>{const e={};for(const r of t)if(r.startsWith("--")){const[o,n]=r.slice(2).split("="),[s,i]=o.split(".");s&&i&&s in Re?(e[s]||(e[s]={}),e[s][i]=n):e[o]=n}return e},Ea=()=>{const t=xe.homedir(),e=process.env.AICOMMIT_CONFIG_PATH,r=po,o=x.join(t,".aicommit2");return[e,r,o].filter(n=>!!n)},Ce=async()=>{const t=Ea();for(const e of t)if(await lo(e))return e;return po},Le=async()=>{const t=await Ce();Oe=t;try{const e=await R.readFile(t,"utf8");return ve.parse(e)}catch(e){return e.code==="ENOENT"?(Oe=void 0,{}):(console.error(`Error reading config file ${t}:`,e),Oe=void 0,{})}},de=async(t,e=[])=>{const r=await Le(),o=$a(e),n={...t,...o},s={},i=Pa(r),c={};for(const f of i){const l=r[f]?.envKey||`${f}_API_KEY`,d=process.env[l];d&&(c[f]={key:d})}const a=(f,u)=>{const l=n[`${f}.${u}`]??n[f]?.[u],d=c[f]?.[u],m=r[f]?.[u],h=n[u]??r[u];return l!==void 0?l:d!==void 0?d:m!==void 0?m:h};for(const[f,u]of Object.entries(p)){const l=n[f]??r[f];s[f]=u(l)}for(const f of i){s[f]={};const u=Re[f]||it(f);for(const[l,d]of Object.entries(u)){const m=a(f,l);s[f][l]=d(m)}}return s},Gt=async t=>{const e=await Le();for(const[n,s]of t){const[i,c]=n.split(".");if(!c){const u=p[n];if(!u)throw new b(`Invalid config property: ${n}`);e[n]=u(s);continue}if(e[i]||(e[i]={}),be.includes(i)){const u=Re[i][c];if(!u)throw new b(`Invalid config property: ${n}`);e[i][c]=u(s);continue}if(!/^[A-Z][A-Z0-9_]*$/.test(i))throw new b(`Invalid service name: ${i}. Service names must be uppercase letters, numbers, and underscores.`);const f=it(i);if(!f[c])throw new b(`Invalid config property for custom service: ${n}`);try{e[i][c]=f[c](s)}catch(u){throw u instanceof b?u:new b(`Invalid value for ${n}: ${u.message}`)}}const r=await Ce(),o=x.dirname(r);await R.mkdir(o,{recursive:!0}),await R.writeFile(r,ve.stringify(e),"utf8")},ka=async t=>{const e=await Le();for(const[n,s]of t){const[i,c]=n.split("."),a=e[i];if(c==="model"){a||(e[i]={});const u=e[i][c]||[],l=typeof s=="string"?s.split(",").map(d=>d.trim()).filter(d=>!!d):s;e[i][c]=nt([...u,...l]);continue}if(a&&a.compatible===!0){a||(e[i]={});const u=it(i);if(!u[c])throw new b(`Invalid config property: ${n}`);try{e[i][c]=u[c](s)}catch(l){throw l instanceof b?l:new b(`Invalid value for ${n}: ${l.message}`)}continue}if(i in Re){a||(e[i]={});const u=Re[i][c];if(!u)throw new b(`Invalid config property: ${n}`);e[i][c]=u(s)}else{const u=it(i);if(!u[c])throw new b(`Invalid config property: ${n}`);e[i]||(e[i]={}),e[i][c]=u[c](s)}}const r=await Ce(),o=x.dirname(r);await R.mkdir(o,{recursive:!0}),await R.writeFile(r,ve.stringify(e),"utf8")},xa=async()=>{const t=await Le();console.log(ve.stringify(t))},Aa=async()=>{console.log(await Ce())},it=t=>({compatible:e=>typeof e=="boolean"?e:e==null?!1:(k("compatible",/^(?:true|false)$/.test(e),"Must be a boolean(true or false)"),e==="true"),stream:e=>typeof e=="boolean"?e:e==null?!1:(k("stream",/^(?:true|false)$/.test(e),"Must be a boolean(true or false)"),e==="true"),url:e=>e?(k(`${t}.url`,/^https?:\/\//.test(e),"Must be a valid URL"),e):"",path:e=>e||"",key:e=>e||"",envKey:e=>e||"",model:e=>e?(typeof e=="string"?e?.split(","):e).map(o=>o.trim()).filter(o=>!!o&&o.length>0):[],systemPrompt: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}),De=new Map,me=(t,e,r)=>{const o=Er(0).update(e).digest("hex").substring(0,8),n=`${t}_${o}_${r}`;if(De.has(n))return De.get(n);const s=new Date,i=Ma(s,t,e,r),c=`${re}/${i}`,a=z.createLogger({level:"info",format:z.format.combine(z.format.timestamp({format:"YYYY-MM-DDTHH:mm:ss.SSSZ"}),z.format.printf(({timestamp:f,level:u,message:l,...d})=>d&&Object.keys(d).length>0?`[${f}] ${u}: ${l} ${JSON.stringify(d,null,2)}`:`[${f}] ${u}: ${l}`)),transports:[new z.transports.File({filename:c})]});return a.info(`=== ${t.toUpperCase()} AI SERVICE LOG ===`),a.info(`Diff Hash: ${o}`),a.info(`Request Type: ${r.toUpperCase()}`),a.info(`Start Time: ${s.toISOString()}`),a.info("=".repeat(50)),a.info(""),De.set(n,a),a},Sa=t=>{const e={...t},r=["authorization","x-api-key","x-goog-api-key","api-key"];for(const o of r){const n=o.toLowerCase(),s=Object.keys(e).find(i=>i.toLowerCase()===n);s&&e[s]&&typeof e[s]=="string"&&(e[s].startsWith("Bearer ")?e[s]="Bearer [MASKED]":e[s]="[MASKED]")}return e},V=(t,e,r,o,n,s,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: ${n}`),c.info("Request headers:",Sa(s))},oe=(t,e,r,o,n=!0)=>{if(!n)return;me(r,t,e).info("Request payload:",o)},X=(t,e,r,o,n,s=!0)=>{if(!s)return;const i=me(r,t,e);i.info("System prompt:",{prompt:o}),i.info("User prompt:",{prompt:n})},Q=(t,e,r,o,n=!0)=>{if(!n)return;me(r,t,e).info("Response received:",o)},G=(t,e,r,o,n=!0)=>{if(!n)return;me(r,t,e).error("API request failed:",o)},W=(t,e,r,o,n,s=!0)=>{if(!s)return;const i=me(r,t,e);o?i.info(`Request completed successfully in ${o}ms`):i.info("Request completed successfully"),n&&i.info("Final processed response:",{response:n}),i.info(""),i.info("=".repeat(50)),i.info(`End Time: ${new Date().toISOString()}`),i.info("=== REQUEST COMPLETED ===")},Ia=(t,e,r,o,n,s,i,c=!0)=>{if(!c)return;const a=me(r,t,e);i?a.error(`Request failed after ${s}ms:`,{error:i}):(a.info(`Request completed in ${s}ms`),a.info("Response:",{response:n})),W(t,e,r,s,n,c)},Ma=(t,e,r,o)=>{const{year:n,month:s,day:i,hours:c,minutes:a,seconds:f}=Ra(t),l=Er(0).update(r).digest("hex").substring(0,8),d=e.toLowerCase().replace(/[^a-z0-9]/g,"").substring(0,20);return o==="review"?`${n}-${s}-${i}_${c}-${a}-${f}_${l}_${d}_review.log`:`${n}-${s}-${i}_${c}-${a}-${f}_${l}_${d}_commit.log`},Ra=t=>{const e=t.getFullYear().toString(),r=(t.getMonth()+1).toString().padStart(2,"0"),o=t.getDate().toString().padStart(2,"0"),n=t.getHours().toString().padStart(2,"0"),s=t.getMinutes().toString().padStart(2,"0"),i=t.getSeconds().toString().padStart(2,"0");return{year:e,month:r,day:o,hours:n,minutes:s,seconds:i}},Bt=()=>{for(const[t,e]of De.entries())try{e.close()}catch(r){console.error(`Failed to close logger ${t}:`,r)}De.clear()};process.on("exit",Bt),process.on("SIGINT",()=>{Bt(),process.exit(0)}),process.on("SIGTERM",()=>{Bt(),process.exit(0)});let at;async function Oa(t){if(at){console.warn("Logger already initialized. Skipping re-initialization.");return}const e=t?.logLevel||"info",r=t?.logFilePath||ho,o=t?.exceptionLogFilePath||go,n=t?.logging??!0;await uo(x.dirname(r)),await uo(x.dirname(o));const s=[];n?s.push(new z.transports.DailyRotateFile({filename:r,datePattern:"YYYY-MM-DD",zippedArchive:!0,maxSize:"20m",maxFiles:"14d",level:e,format:z.format.combine(z.format.timestamp(),z.format.printf(({level:i,message:c,timestamp:a})=>`[${a}] ${i}: ${c}`))})):s.push(new z.transports.Console({silent:!0})),at=z.createLogger({level:e,format:z.format.json(),transports:s,exceptionHandlers:n?[new z.transports.DailyRotateFile({filename:o,datePattern:"YYYY-MM-DD",zippedArchive:!0,maxSize:"20m",maxFiles:"14d",format:z.format.combine(z.format.timestamp(),z.format.json())})]:[],exitOnError:!1,silent:!n})}const Pe=new Proxy({},{get:(t,e,r)=>{if(!at)throw new Error("Logger not initialized. Call initializeLogger() first.");return Reflect.get(at,e,r)}});class Z{constructor(e){this.handleError$=r=>{const o=this.getDetailedErrorMessage(r),n=r.status?`HTTP ${r.status}: ${o}`:o;if(this.params.config.logging){const s=this.params.stagedDiff.diff,i=this.serviceName.replace(/\[|\]/g,"").trim();Ia(s,"commit",i,"Error occurred","",void 0,n)}return Pe.error(`${this.errorPrefix} ${n}`),r.stack&&Pe.error(` ${r.stack}`),r.content&&Pe.error(` Problematic content: ${r.content}`),r.originalError&&Pe.error(` Original error: ${r.originalError}`),Ae({name:`${this.errorPrefix} ${n}`,value:n,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 n=this.cleanJsonCodeBlock(e),s=/(\[\s*\{[\s\S]*?\}\s*\]|\{[\s\S]*?\})/,i=n.match(s);if(!i){const m=new Error("AI response did not contain a valid JSON object or array.");throw m.name="InvalidJsonResponse",m.content=e,m}const c=i[0],a=wa(c);if(!a.ok){const m=new Error("Failed to parse AI response as JSON");throw m.name="JsonParseError",m.content=c,m.originalError=a.error,m}const f=a.data,u=Array.isArray(f)?f:[f];if(!u.length||!u.every(m=>typeof m.subject=="string")){const m=new Error("AI response contained malformed commit message data.");throw m.name="MalformedCommitMessage",m.content=e,m}const d=u.map(m=>this.extractMessageAsType(m,r)).map(m=>({title:`${m.subject}`,value:`${m.subject}${m.body?`
|
|
13
|
+
${Tt}${P.dim(`aicommit2 v${Ir}`)}`),console.error(`
|
|
14
|
+
${Tt}Please open a Bug report with the information above:`),console.error(`${Tt}https://github.com/tak-bro/aicommit2/issues/new/choose`)))},lo=t=>O.lstat(t).then(()=>!0,()=>!1),uo=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},fa=(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),[]),mo=(t,e=5)=>t.replace(/[\n\r]/g,"").split(" ").slice(0,e).join(" "),pa=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)},ha=t=>{const e=t%360,r=65+t%15,o=45+t%10;return`hsl(${e}, ${r}%, ${o}%)`},ga=t=>{const[e,r,o]=t.match(/\d+/g).map((l,p)=>p===0?Number(l):Number(l)/100),n=(1-Math.abs(2*o-1))*r,s=n*(1-Math.abs(e/60%2-1)),i=o-n/2;let c,a,m;e<60?[c,a,m]=[n,s,0]:e<120?[c,a,m]=[s,n,0]:e<180?[c,a,m]=[0,n,s]:e<240?[c,a,m]=[0,s,n]:e<300?[c,a,m]=[s,0,n]:[c,a,m]=[n,0,s];const d=l=>{const p=Math.round((l+i)*255).toString(16);return p.length===1?"0"+p:p};return`#${d(c)}${d(a)}${d(m)}`},ya=t=>{const e=pa(t),r=ha(e);return{primary:ga(r),secondary:"#FFFFFF"}},wa=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(A.isAbsolute(t))return A.resolve(t);if(Oe){const e=A.dirname(Oe),r=A.join(e,t);return A.resolve(r)}else return""},va=["","conventional","gitmoji","jujutsu"],Ft="http://localhost:11434",{hasOwnProperty:ba}=Object.prototype,_t=(t,e)=>ba.call(t,e),be=["OPENAI","OLLAMA","HUGGINGFACE","GEMINI","ANTHROPIC","MISTRAL","CODESTRAL","COHERE","GROQ","PERPLEXITY","DEEPSEEK","GITHUB_MODELS"],fo=t=>{const e=xe.platform(),r=xe.homedir();let o,n;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"?n=A.join(r,"Library","Caches"):n=A.join(r,"Application Support");else if(e==="win32")n=process.env.LOCALAPPDATA||r;else switch(t){case"config":n=A.join(r,".config");break;case"data":n=A.join(r,".local","share");break;case"cache":n=A.join(r,".cache");break;case"state":n=A.join(r,".local","state");break;default:n=r}return o||n},Ca=A.join(fo("config"),"aicommit2"),re=A.join(fo("state"),"aicommit2","logs"),po=A.join(Ca,"config.ini"),ho=A.join(re,"aicommit2-%DATE%.log"),go=A.join(re,"exceptions-%DATE%.log"),Pa=t=>{const e=Object.keys(t),r=new Set([...be,...e.filter(o=>/^[A-Z][A-Z0-9_]*$/.test(o))]);return Array.from(r)},k=(t,e,r)=>{if(!e)throw new b(`Invalid config property ${t}: ${r}`)},f={systemPrompt(t){return t||""},systemPromptPath(t){return t||""},codeReviewPromptPath(t){return t||""},timeout(t){if(!t)return 1e4;k("timeout",/^\d+$/.test(t),"Must be an integer");const e=Number(t);return k("timeout",e>=500,"Must be greater than 500ms"),e},temperature(t){if(!t)return .7;k("temperature",/^(2|\d)(\.\d{1,2})?$/.test(t),"Must be decimal between 0 and 2");const e=Number(t);return k("temperature",e>0,"Must be greater than 0"),k("temperature",e<=2,"Must be less than or equal to 2"),e},maxTokens(t){return t?(k("maxTokens",/^\d+$/.test(t),"Must be an integer"),Number(t)):1024},logging(t){return typeof t=="boolean"?t:t==null?!0:(k("logging",/^(?:true|false)$/.test(t),"Must be a boolean(true or false)"),t==="true")},logLevel(t){return t?(k("logLevel",/^(?:error|warn|info|http|verbose|debug|silly)$/.test(t),"Must be a valid log level (error, warn, info, http, verbose, debug, silly)"),t):"info"},logFilePath(t){return t||ho},exceptionLogFilePath(t){return t||go},locale(t){return t?(k("locale",t,"Cannot be empty"),k("locale",/^[a-z-]+$/i.test(t),"Must be a valid locale (letters and dashes/underscores). You can consult the list of codes in: https://wikipedia.org/wiki/List_of_ISO_639-1_codes"),t):"en"},generate(t){if(!t)return 1;k("generate",/^\d+$/.test(t),"Must be an integer");const e=Number(t);return k("generate",e>0,"Must be greater than 0"),k("generate",e<=5,"Must be less or equal to 5"),e},type(t){return t?(k("type",va.includes(t),"Invalid commit type"),t):"conventional"},maxLength(t){if(!t)return 50;k("maxLength",/^\d+$/.test(t),"Must be an integer");const e=Number(t);return k("maxLength",e>=20,"Must be greater than 20 characters"),e},includeBody(t){return typeof t=="boolean"?t:t==null?!1:(k("includeBody",/^(?:true|false)$/.test(t),"Must be a boolean(true or false)"),t==="true")},exclude:t=>t?(typeof t=="string"?t?.split(","):t).map(r=>r.trim()).filter(r=>!!r&&r.length>0):[],topP:t=>{if(!t)return .9;k("topP",/^(1|\d)(\.\d{1,2})?$/.test(t),"Must be decimal between 0 and 1");const e=Number(t);return k("topP",e>0,"Must be greater than 0"),k("topP",e<=1,"Must be less than or equal to 1"),e},codeReview(t){return typeof t=="boolean"?t:t==null?!1:(k("codeReview",/^(?:true|false)$/.test(t),"Must be a boolean(true or false)"),t==="true")},disabled(t){return typeof t=="boolean"?t:t==null?!1:(k("disabled",/^(?:true|false)$/.test(t),"Must be a boolean(true or false)"),t==="true")},watchMode(t){return typeof t=="boolean"?t:t==null?!1:(k("watchMode",/^(?:true|false)$/.test(t),"Must be a boolean(true or false)"),t==="true")},jujutsu(t){return typeof t=="boolean"?t:t==null?!1:(k("jujutsu",/^(?:true|false)$/.test(t),"Must be a boolean(true or false)"),t==="true")},disableLowerCase(t){return typeof t=="boolean"?t:t==null?!1:(k("disableLowerCase",/^(?:true|false)$/.test(t),"Must be a boolean(true or false)"),t==="true")}},Re={OPENAI:{key:t=>t||"",envKey:t=>t||"",model:t=>t?(typeof t=="string"?t?.split(","):t).map(r=>r.trim()).filter(r=>!!r&&r.length>0):["gpt-4o-mini"],url:t=>t?(k("OPENAI.url",/^https?:\/\//.test(t),"Must be a valid URL"),t):"https://api.openai.com",path:t=>t||"/v1/chat/completions",proxy:t=>t||"",topP:f.topP,systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,timeout:f.timeout,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode,disableLowerCase:f.disableLowerCase},HUGGINGFACE:{cookie:t=>t||"",model:t=>t?(typeof t=="string"?t?.split(","):t).map(r=>r.trim()).filter(r=>!!r&&r.length>0):["CohereForAI/c4ai-command-r-plus"],systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,timeout:f.timeout,temperature:f.temperature,maxTokens:f.maxTokens,topP:f.topP,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode,disableLowerCase:f.disableLowerCase},GEMINI:{key:t=>t||"",envKey:t=>t||"",model:t=>t?(typeof t=="string"?t?.split(","):t).map(r=>r.trim()).filter(r=>!!r&&r.length>0):["gemini-2.0-flash"],systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,topP:f.topP,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode,disableLowerCase:f.disableLowerCase},ANTHROPIC:{key:t=>t||"",envKey:t=>t||"",model:t=>t?(typeof t=="string"?t?.split(","):t).map(r=>r.trim()).filter(r=>!!r&&r.length>0):["claude-3-5-haiku-20241022"],systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,topP:f.topP,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode,disableLowerCase:f.disableLowerCase},MISTRAL:{key:t=>t||"",envKey:t=>t||"",model:t=>t?(typeof t=="string"?t?.split(","):t).map(r=>r.trim()).filter(r=>!!r&&r.length>0):["mistral-small-latest"],systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,timeout:f.timeout,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,topP:f.topP,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode,disableLowerCase:f.disableLowerCase},CODESTRAL:{key:t=>t||"",envKey:t=>t||"",model:t=>t?(typeof t=="string"?t?.split(","):t).map(r=>r.trim()).filter(r=>!!r&&r.length>0):["codestral-latest"],topP:f.topP,systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,timeout:f.timeout,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode,disableLowerCase:f.disableLowerCase},OLLAMA:{model:t=>t?(typeof t=="string"?t?.split(","):t).map(r=>r.trim()).filter(r=>!!r&&r.length>0):[],host:t=>t?(k("OLLAMA.host",/^https?:\/\//.test(t),"Must be a valid URL"),t):Ft,timeout:t=>{if(!t)return 1e5;k("OLLAMA.timeout",/^\d+$/.test(t),"Must be an integer");const e=Number(t);return k("OLLAMA.timeout",e>=500,"Must be greater than 500ms"),e},auth:t=>t||"",key:t=>t||"",envKey:t=>t||"",numCtx:t=>{if(!t)return 2048;k("OLLAMA.numCtx",/^\d+$/.test(t),"Must be an integer");const e=Number(t);return k("OLLAMA.numCtx",e>=2048,"Must be greater than 2048"),e},systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,topP:f.topP,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode,disableLowerCase:f.disableLowerCase},COHERE:{key:t=>t||"",envKey:t=>t||"",model:t=>t?(typeof t=="string"?t?.split(","):t).map(r=>r.trim()).filter(r=>!!r&&r.length>0):["command-r"],systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,topP:f.topP,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode,disableLowerCase:f.disableLowerCase},GROQ:{key:t=>t||"",envKey:t=>t||"",model:t=>t?(typeof t=="string"?t?.split(","):t).map(r=>r.trim()).filter(r=>!!r&&r.length>0):["llama-3.3-70b-versatile"],systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,timeout:f.timeout,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,topP:f.topP,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode,disableLowerCase:f.disableLowerCase},PERPLEXITY:{key:t=>t||"",envKey:t=>t||"",model:t=>t?(typeof t=="string"?t?.split(","):t).map(r=>r.trim()).filter(r=>!!r&&r.length>0):["sonar"],topP:f.topP,systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,timeout:f.timeout,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode,disableLowerCase:f.disableLowerCase},DEEPSEEK:{key:t=>t||"",envKey:t=>t||"",model:t=>t?(typeof t=="string"?t?.split(","):t).map(r=>r.trim()).filter(r=>!!r&&r.length>0):["deepseek-coder"],topP:f.topP,systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,timeout:f.timeout,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode,disableLowerCase:f.disableLowerCase},GITHUB_MODELS:{key:t=>t||"",envKey:t=>t||"",model:t=>t?(typeof t=="string"?t?.split(","):t).map(r=>r.trim()).filter(r=>!!r&&r.length>0):["gpt-4o-mini"],systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,timeout:f.timeout,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,topP:f.topP,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode,disableLowerCase:f.disableLowerCase}};let Oe;const $a=(t=[])=>{const e={};for(const r of t)if(r.startsWith("--")){const[o,n]=r.slice(2).split("="),[s,i]=o.split(".");s&&i&&s in Re?(e[s]||(e[s]={}),e[s][i]=n):e[o]=n}return e},Ea=()=>{const t=xe.homedir(),e=process.env.AICOMMIT_CONFIG_PATH,r=po,o=A.join(t,".aicommit2");return[e,r,o].filter(n=>!!n)},Ce=async()=>{const t=Ea();for(const e of t)if(await lo(e))return e;return po},Le=async()=>{const t=await Ce();Oe=t;try{const e=await O.readFile(t,"utf8");return ve.parse(e)}catch(e){return e.code==="ENOENT"?(Oe=void 0,{}):(console.error(`Error reading config file ${t}:`,e),Oe=void 0,{})}},de=async(t,e=[])=>{const r=await Le(),o=$a(e),n={...t,...o},s={},i=Pa(r),c={};for(const m of i){const l=r[m]?.envKey||`${m}_API_KEY`,p=process.env[l];p&&(c[m]={key:p})}const a=(m,d)=>{const l=n[`${m}.${d}`]??n[m]?.[d],p=c[m]?.[d],u=r[m]?.[d],h=n[d]??r[d];return l!==void 0?l:p!==void 0?p:u!==void 0?u:h};for(const[m,d]of Object.entries(f)){const l=n[m]??r[m];s[m]=d(l)}for(const m of i){s[m]={};const d=Re[m]||it(m);for(const[l,p]of Object.entries(d)){const u=a(m,l);s[m][l]=p(u)}}return s},Gt=async t=>{const e=await Le();for(const[n,s]of t){const[i,c]=n.split(".");if(!c){const d=f[n];if(!d)throw new b(`Invalid config property: ${n}`);e[n]=d(s);continue}if(e[i]||(e[i]={}),be.includes(i)){const d=Re[i][c];if(!d)throw new b(`Invalid config property: ${n}`);e[i][c]=d(s);continue}if(!/^[A-Z][A-Z0-9_]*$/.test(i))throw new b(`Invalid service name: ${i}. Service names must be uppercase letters, numbers, and underscores.`);const m=it(i);if(!m[c])throw new b(`Invalid config property for custom service: ${n}`);try{e[i][c]=m[c](s)}catch(d){throw d instanceof b?d:new b(`Invalid value for ${n}: ${d.message}`)}}const r=await Ce(),o=A.dirname(r);await O.mkdir(o,{recursive:!0}),await O.writeFile(r,ve.stringify(e),"utf8")},ka=async t=>{const e=await Le();for(const[n,s]of t){const[i,c]=n.split("."),a=e[i];if(c==="model"){a||(e[i]={});const d=e[i][c]||[],l=typeof s=="string"?s.split(",").map(p=>p.trim()).filter(p=>!!p):s;e[i][c]=nt([...d,...l]);continue}if(a&&a.compatible===!0){a||(e[i]={});const d=it(i);if(!d[c])throw new b(`Invalid config property: ${n}`);try{e[i][c]=d[c](s)}catch(l){throw l instanceof b?l:new b(`Invalid value for ${n}: ${l.message}`)}continue}if(i in Re){a||(e[i]={});const d=Re[i][c];if(!d)throw new b(`Invalid config property: ${n}`);e[i][c]=d(s)}else{const d=it(i);if(!d[c])throw new b(`Invalid config property: ${n}`);e[i]||(e[i]={}),e[i][c]=d[c](s)}}const r=await Ce(),o=A.dirname(r);await O.mkdir(o,{recursive:!0}),await O.writeFile(r,ve.stringify(e),"utf8")},xa=async()=>{const t=await Le();console.log(ve.stringify(t))},Aa=async()=>{console.log(await Ce())},it=t=>({compatible:e=>typeof e=="boolean"?e:e==null?!1:(k("compatible",/^(?:true|false)$/.test(e),"Must be a boolean(true or false)"),e==="true"),stream:e=>typeof e=="boolean"?e:e==null?!1:(k("stream",/^(?:true|false)$/.test(e),"Must be a boolean(true or false)"),e==="true"),url:e=>e?(k(`${t}.url`,/^https?:\/\//.test(e),"Must be a valid URL"),e):"",path:e=>e||"",key:e=>e||"",envKey:e=>e||"",model:e=>e?(typeof e=="string"?e?.split(","):e).map(o=>o.trim()).filter(o=>!!o&&o.length>0):[],systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,timeout:f.timeout,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,topP:f.topP,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode,disableLowerCase:f.disableLowerCase}),De=new Map,me=(t,e,r)=>{const o=Er(0).update(e).digest("hex").substring(0,8),n=`${t}_${o}_${r}`;if(De.has(n))return De.get(n);const s=new Date,i=Ma(s,t,e,r),c=`${re}/${i}`,a=z.createLogger({level:"info",format:z.format.combine(z.format.timestamp({format:"YYYY-MM-DDTHH:mm:ss.SSSZ"}),z.format.printf(({timestamp:m,level:d,message:l,...p})=>p&&Object.keys(p).length>0?`[${m}] ${d}: ${l} ${JSON.stringify(p,null,2)}`:`[${m}] ${d}: ${l}`)),transports:[new z.transports.File({filename:c})]});return a.info(`=== ${t.toUpperCase()} AI SERVICE LOG ===`),a.info(`Diff Hash: ${o}`),a.info(`Request Type: ${r.toUpperCase()}`),a.info(`Start Time: ${s.toISOString()}`),a.info("=".repeat(50)),a.info(""),De.set(n,a),a},Sa=t=>{const e={...t},r=["authorization","x-api-key","x-goog-api-key","api-key"];for(const o of r){const n=o.toLowerCase(),s=Object.keys(e).find(i=>i.toLowerCase()===n);s&&e[s]&&typeof e[s]=="string"&&(e[s].startsWith("Bearer ")?e[s]="Bearer [MASKED]":e[s]="[MASKED]")}return e},q=(t,e,r,o,n,s,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: ${n}`),c.info("Request headers:",Sa(s))},oe=(t,e,r,o,n=!0)=>{if(!n)return;me(r,t,e).info("Request payload:",o)},X=(t,e,r,o,n,s=!0)=>{if(!s)return;const i=me(r,t,e);i.info("System prompt:",{prompt:o}),i.info("User prompt:",{prompt:n})},Q=(t,e,r,o,n=!0)=>{if(!n)return;me(r,t,e).info("Response received:",o)},G=(t,e,r,o,n=!0)=>{if(!n)return;me(r,t,e).error("API request failed:",o)},W=(t,e,r,o,n,s=!0)=>{if(!s)return;const i=me(r,t,e);o?i.info(`Request completed successfully in ${o}ms`):i.info("Request completed successfully"),n&&i.info("Final processed response:",{response:n}),i.info(""),i.info("=".repeat(50)),i.info(`End Time: ${new Date().toISOString()}`),i.info("=== REQUEST COMPLETED ===")},Ia=(t,e,r,o,n,s,i,c=!0)=>{if(!c)return;const a=me(r,t,e);i?a.error(`Request failed after ${s}ms:`,{error:i}):(a.info(`Request completed in ${s}ms`),a.info("Response:",{response:n})),W(t,e,r,s,n,c)},Ma=(t,e,r,o)=>{const{year:n,month:s,day:i,hours:c,minutes:a,seconds:m}=Ra(t),l=Er(0).update(r).digest("hex").substring(0,8),p=e.toLowerCase().replace(/[^a-z0-9]/g,"").substring(0,20);return o==="review"?`${n}-${s}-${i}_${c}-${a}-${m}_${l}_${p}_review.log`:`${n}-${s}-${i}_${c}-${a}-${m}_${l}_${p}_commit.log`},Ra=t=>{const e=t.getFullYear().toString(),r=(t.getMonth()+1).toString().padStart(2,"0"),o=t.getDate().toString().padStart(2,"0"),n=t.getHours().toString().padStart(2,"0"),s=t.getMinutes().toString().padStart(2,"0"),i=t.getSeconds().toString().padStart(2,"0");return{year:e,month:r,day:o,hours:n,minutes:s,seconds:i}},Bt=()=>{for(const[t,e]of De.entries())try{e.close()}catch(r){console.error(`Failed to close logger ${t}:`,r)}De.clear()};process.on("exit",Bt),process.on("SIGINT",()=>{Bt(),process.exit(0)}),process.on("SIGTERM",()=>{Bt(),process.exit(0)});let at;async function Oa(t){if(at){console.warn("Logger already initialized. Skipping re-initialization.");return}const e=t?.logLevel||"info",r=t?.logFilePath||ho,o=t?.exceptionLogFilePath||go,n=t?.logging??!0;await uo(A.dirname(r)),await uo(A.dirname(o));const s=[];n?s.push(new z.transports.DailyRotateFile({filename:r,datePattern:"YYYY-MM-DD",zippedArchive:!0,maxSize:"20m",maxFiles:"14d",level:e,format:z.format.combine(z.format.timestamp(),z.format.printf(({level:i,message:c,timestamp:a})=>`[${a}] ${i}: ${c}`))})):s.push(new z.transports.Console({silent:!0})),at=z.createLogger({level:e,format:z.format.json(),transports:s,exceptionHandlers:n?[new z.transports.DailyRotateFile({filename:o,datePattern:"YYYY-MM-DD",zippedArchive:!0,maxSize:"20m",maxFiles:"14d",format:z.format.combine(z.format.timestamp(),z.format.json())})]:[],exitOnError:!1,silent:!n})}const Pe=new Proxy({},{get:(t,e,r)=>{if(!at)throw new Error("Logger not initialized. Call initializeLogger() first.");return Reflect.get(at,e,r)}});class Z{constructor(e){this.handleError$=r=>{const o=this.getDetailedErrorMessage(r),n=r.status?`HTTP ${r.status}: ${o}`:o;if(this.params.config.logging){const s=this.params.stagedDiff.diff,i=this.serviceName.replace(/\[|\]/g,"").trim();Ia(s,"commit",i,"Error occurred","",void 0,n)}return Pe.error(`${this.errorPrefix} ${n}`),r.stack&&Pe.error(` ${r.stack}`),r.content&&Pe.error(` Problematic content: ${r.content}`),r.originalError&&Pe.error(` Original error: ${r.originalError}`),Ae({name:`${this.errorPrefix} ${n}`,value:n,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 n=this.cleanJsonCodeBlock(e),s=/(\[\s*\{[\s\S]*?\}\s*\]|\{[\s\S]*?\})/,i=n.match(s);if(!i){const u=new Error("AI response did not contain a valid JSON object or array.");throw u.name="InvalidJsonResponse",u.content=e,u}const c=i[0],a=wa(c);if(!a.ok){const u=new Error("Failed to parse AI response as JSON");throw u.name="JsonParseError",u.content=c,u.originalError=a.error,u}const m=a.data,d=Array.isArray(m)?m:[m];if(!d.length||!d.every(u=>typeof u.subject=="string")){const u=new Error("AI response contained malformed commit message data.");throw u.name="MalformedCommitMessage",u.content=e,u}const p=d.map(u=>this.extractMessageAsType(u,r)).map(u=>({title:`${u.subject}`,value:`${u.subject}${u.body?`
|
|
15
15
|
|
|
16
|
-
${
|
|
16
|
+
${u.body}`:""}${u.footer?`
|
|
17
17
|
|
|
18
|
-
${
|
|
18
|
+
${u.footer}`:""}`})).slice(0,o);if(this.isLoggingEnabled()){const u=p.map(h=>h.title).join(", ");Pe.info(`${this.serviceName} Parsed ${p.length} commit messages: ${u}`)}return p}extractMessageAsType(e,r){switch(r){case"conventional":const o=/(\w+)(?:\(.*?\))?:\s*(.*)/,n=e.subject.match(o),s=n?n[0]:e.subject;return{...e,subject:this.normalizeCommitMessage(s)};case"gitmoji":const i=/:\w*:\s*(.*)/,c=e.subject.match(i),a=this.params.config.disableLowerCase??!1;return{...e,subject:c&&!a?c[0].toLowerCase():e.subject};default:return e}}normalizeCommitMessage(e){const r=/^(\w+)(\(.*?\))?:\s(.*)$/,o=e.match(r);if(o){const[,n,s,i]=o,c=this.params.config.disableLowerCase??!1,a=n.toLowerCase(),m=c?i:i.charAt(0).toLowerCase()+i.slice(1);e=`${a}${s||""}: ${m}`}return e}sanitizeResponse(e){if(typeof e=="string")try{return[{title:`${mo(e)}...`,value:e}]}catch{return[]}return e.map(r=>{try{return{title:`${mo(r)}...`,value:r}}catch{return{title:"",value:""}}})}isLoggingEnabled(){return this.params.config.logging&&!!this.logSessionId}}const Y={locale:"en",maxLength:50,type:"conventional",generate:1,systemPrompt:"",systemPromptPath:"",codeReviewPromptPath:""},La={"":"<commit message>",conventional:`<type>(<optional scope>): <description>
|
|
19
19
|
|
|
20
20
|
[optional body]
|
|
21
21
|
|
|
@@ -29,7 +29,7 @@ ${m.footer}`:""}`})).slice(0,o);if(this.isLoggingEnabled()){const m=d.map(h=>h.t
|
|
|
29
29
|
${Object.entries({":sparkles:":"Introduce new features.",":bug:":"Fix a bug.",":memo:":"Add or update documentation.",":art:":"Improve structure / format of the code.",":zap:":"Improve performance.",":fire:":"Remove code or files.",":ambulance:":"Critical hotfix.",":white_check_mark:":"Add, update, or pass tests.",":lock:":"Fix security or privacy issues.",":rocket:":"Deploy stuff.",":lipstick:":"Add or update the UI and style files.",":tada:":"Begin a project.",":recycle:":"Refactor code.",":wrench:":"Add or update configuration files.",":bulb:":"Add or update comments in source code.",":twisted_rightwards_arrows:":"Merge branches."}).map(([t,e])=>` - ${t}: ${e}`).join(`
|
|
30
30
|
`)}`,conventional:`
|
|
31
31
|
${Object.entries({docs:"Documentation only changes",style:"Changes that do not affect the meaning of the code (white-space, formatting, missing semi-colons, etc)",refactor:"A code change that neither fixes a bug nor adds a feature",perf:"A code change that improves performance",test:"Adding missing tests or correcting existing tests",build:"Changes that affect the build system or external dependencies",ci:"Changes to CI configuration files, scripts",chore:"Other changes that don't modify src or test files",revert:"Reverts a previous commit",feat:"A new feature",fix:"A bug fix"}).map(([t,e])=>` - ${t}: ${e}`).join(`
|
|
32
|
-
`)}`},yo=(t,e)=>t.replace(/{(\w+)}/g,(r,o)=>e[o]?.toString()||Y[o]?.toString()),wo=t=>{const{type:e,maxLength:r,generate:o,locale:n}=t,s=e==="jujutsu"?"You are a Jujutsu commit message writer. You create simple, clear commit messages following Jujutsu's format.":"You are an expert Git commit message writer specializing in analyzing code changes and creating precise, meaningful commit messages.",i=e==="jujutsu"?`Generate exactly ${o} Jujutsu-style commit message${o!==1?"s":""} based on the provided diff.`:`Your task is to generate exactly ${o} ${e} style commit message${o!==1?"s":""} based on the provided git diff.`;return[s,i,"",e==="jujutsu"?["## Format:","<topic>: <description>","","## Rules:","- Topic: The
|
|
32
|
+
`)}`},yo=(t,e)=>t.replace(/{(\w+)}/g,(r,o)=>e[o]?.toString()||Y[o]?.toString()),wo=t=>{const{type:e,maxLength:r,generate:o,locale:n}=t,s=e==="jujutsu"?"You are a Jujutsu commit message writer. You create simple, clear commit messages following Jujutsu's format.":"You are an expert Git commit message writer specializing in analyzing code changes and creating precise, meaningful commit messages.",i=e==="jujutsu"?`Generate exactly ${o} Jujutsu-style commit message${o!==1?"s":""} based on the provided diff.`:`Your task is to generate exactly ${o} ${e} style commit message${o!==1?"s":""} based on the provided git diff.`;return[s,i,"",e==="jujutsu"?["## Format:","<topic>: <description>","","## Rules:","- Topic: The module/feature/scope being changed (e.g., cli, docs, config, next/prev)","- Description: Clear, imperative mood statement of what changed",`- Maximum ${r} characters`,`- Language: ${n}`,"- Focus on clarity and simplicity - no conventional commit types or emojis","- Each commit should do one thing","- Explain the reason for change when not obvious","","## Examples from Jujutsu's actual commits:",'- "cli: make jj abandon print abandoned commit info"','- "docs: mention that @ can be used in revsets"','- "backend: make commit signature a property of the backend"','- "templater: add commit.annotate() method"','- "conflicts: simplify conflict marker parsing"'].join(`
|
|
33
33
|
`):["## Requirements:",`1. Language: Write all messages in ${n}`,`2. Format: Strictly follow the ${e} commit format:`,`${La[e]}`,`3. Allowed Types:${Da[e]}`,"","## Guidelines:",`- Subject line: Max ${r} characters, imperative mood, no period`,"- Analyze the diff to understand:"," * What files were changed"," * What functionality was added, modified, or removed"," * The scope and impact of changes","- For the commit type, choose based on:"," * feat: New functionality or feature"," * fix: Bug fixes or error corrections"," * refactor: Code restructuring without changing functionality"," * docs: Documentation changes only"," * style: Formatting, missing semi-colons, etc"," * test: Adding or modifying tests"," * chore: Maintenance tasks, dependency updates"," * perf: Performance improvements"," * build: Build system or external dependency changes"," * ci: CI configuration changes","- Scope: Extract from file paths or logical grouping (e.g., auth, api, ui)","- Body (when needed):"," * Explain the motivation for the change"," * Compare previous behavior with new behavior"," * Note any breaking changes or important details","- Footer: Include references to issues, breaking changes if applicable","","## Analysis Approach:","1. Identify the primary purpose of the changes","2. Group related changes together","3. Determine the most appropriate type and scope","4. Write a clear, concise subject line","5. Add body details for complex changes","","Remember: The commit message should help future developers understand WHY this change was made, not just WHAT was changed."].join(`
|
|
34
34
|
`)].filter(Boolean).join(`
|
|
35
35
|
`)},ct=(t,e)=>{const r=o=>o==="conventional"?`${Array(e).fill(null).map((n,s)=>`
|
|
@@ -59,39 +59,39 @@ ${ct(o,n)}`}},te=t=>{const{codeReviewPromptPath:e,locale:r}=t,o=`I'll give you t
|
|
|
59
59
|
4. Performance improvements
|
|
60
60
|
5. Readability and maintainability
|
|
61
61
|
|
|
62
|
-
Please structure your response with appropriate Markdown headings, code blocks, and bullet points.`;if(!e)return o;try{const n=H.readFileSync(st(e),"utf-8");return`${yo(n,t)}`}catch{return o}},vo=async t=>{if(t.systemPromptPath)try{H.readFileSync(st(t.systemPromptPath),"utf-8")}catch(e){throw new b(`Error reading system prompt file: ${t.systemPromptPath}, ${e}`)}if(t.codeReview&&t.codeReviewPromptPath)try{H.readFileSync(st(t.codeReviewPromptPath),"utf-8")}catch(e){throw new b(`Error reading code review prompt file: ${t.codeReviewPromptPath}, ${e}`)}},$e=(t,e="commit")=>e==="review"?`Please analyze the following
|
|
62
|
+
Please structure your response with appropriate Markdown headings, code blocks, and bullet points.`;if(!e)return o;try{const n=H.readFileSync(st(e),"utf-8");return`${yo(n,t)}`}catch{return o}},vo=async t=>{if(t.systemPromptPath)try{H.readFileSync(st(t.systemPromptPath),"utf-8")}catch(e){throw new b(`Error reading system prompt file: ${t.systemPromptPath}, ${e}`)}if(t.codeReview&&t.codeReviewPromptPath)try{H.readFileSync(st(t.codeReviewPromptPath),"utf-8")}catch(e){throw new b(`Error reading code review prompt file: ${t.codeReviewPromptPath}, ${e}`)}},$e=(t,e="commit")=>e==="review"?`Please analyze the following diff and provide a comprehensive code review:
|
|
63
63
|
|
|
64
64
|
\`\`\`diff
|
|
65
65
|
${t}
|
|
66
66
|
\`\`\`
|
|
67
67
|
|
|
68
|
-
Focus on code quality, potential issues, and improvement suggestions.`:`Please analyze the following
|
|
68
|
+
Focus on code quality, potential issues, and improvement suggestions.`:`Please analyze the following diff and generate commit message(s) based on the changes:
|
|
69
69
|
|
|
70
70
|
\`\`\`diff
|
|
71
71
|
${t}
|
|
72
72
|
\`\`\`
|
|
73
73
|
|
|
74
|
-
Focus on understanding the purpose and impact of these changes to create meaningful commit message(s).`,ja=10*60*1e3;class bo extends Z{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 xn({apiKey:this.params.config.key,...this.params.config.timeout>ja&&{timeout:this.params.config.timeout}})}getServiceSpecificErrorMessage(e){const r=e.message||"";return r.includes("API key")||r.includes("api_key")?"Invalid API key. Check your Anthropic API key in configuration":r.includes("quota")||r.includes("usage")?"API quota exceeded. Check your Anthropic usage limits":r.includes("model")||r.includes("Model")?"Model not found or not accessible. Check if the Claude model name is correct":r.includes("403")||r.includes("Forbidden")?"Access denied. Your API key may not have permission for this Claude model":r.includes("404")||r.includes("Not Found")?"Model or endpoint not found. Check your Claude model configuration":r.includes("500")||r.includes("Internal Server Error")?"Anthropic server error. Try again later":null}generateCommitMessage$(){return D(this.generateMessage("commit")).pipe(L(e=>A(e)),I(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:this.params.config.includeBody?e.value:e.title,description:this.params.config.includeBody?e.value:"",isError:!1})),M(this.handleError$))}generateCodeReview$(){return D(this.generateMessage("review")).pipe(L(e=>A(e)),I(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),M(this.handleError$))}async generateMessage(e){const r=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:n,codeReviewPromptPath:s,logging:i,temperature:c,locale:a,generate:f,type:u,maxLength:l,maxTokens:d,topP:m,model:h}=this.params.config,g={...Y,locale:a,maxLength:l,type:u,generate:f,systemPrompt:o,systemPromptPath:n,codeReviewPromptPath:s},y=e==="review"?te(g):ee(g),w=$e(r,e),E=`${this.params.config.url||"https://api.anthropic.com"}/v1/messages`,O={"Content-Type":"application/json","x-api-key":this.params.config.key,"anthropic-version":"2023-06-01"};V(r,e,"Anthropic",h,E,O,i),X(r,e,"Anthropic",y,w,i);const $={max_tokens:d,temperature:c,system:y,messages:[{role:"user",content:w}],top_p:m,model:h};oe(r,e,"Anthropic",$,i);const P=Date.now();try{const S=await this.anthropic.messages.create($),N=Date.now()-P;Q(r,e,"Anthropic",S,i);const _=S.content.map(({text:ce})=>ce).join("");return W(r,e,"Anthropic",N,_,i),e==="review"?this.sanitizeResponse(_):this.parseMessage(_,u,f)}catch(S){throw G(r,e,"Anthropic",S,i),S}}}class je{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=An.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 Co extends Z{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 D(this.generateMessage("commit")).pipe(L(e=>A(e)),I(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:this.params.config.includeBody?e.value:e.title,description:this.params.config.includeBody?e.value:"",isError:!1})),M(this.handleError$))}generateCodeReview$(){return D(this.generateMessage("review")).pipe(L(e=>A(e)),I(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),M(this.handleError$))}async generateMessage(e){const r=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:n,codeReviewPromptPath:s,logging:i,locale:c,generate:a,type:f,maxLength:u}=this.params.config,l={...Y,locale:c,maxLength:u,type:f,generate:a,systemPrompt:o,systemPromptPath:n,codeReviewPromptPath:s},d=e==="review"?te(l):ee(l);this.checkAvailableModels();const m=$e(r,e),g=`${this.params.config.url||"https://codestral.mistral.ai"}/v1/chat/completions`,y={Authorization:`Bearer ${this.apiKey}`,"content-type":"application/json"};V(r,e,"Codestral",this.params.config.model,g,y,i),X(r,e,"Codestral",d,m,i);const w=await this.createChatCompletions(d,e);return e==="review"?this.sanitizeResponse(w):this.parseMessage(w,f,a)}checkAvailableModels(){if(["codestral-latest","codestral-2501"].includes(this.params.config.model))return!0;throw new Error("Invalid model type of Codestral AI")}async createChatCompletions(e,r){const o=this.params.stagedDiff.diff,{logging:n}=this.params.config,s=this.params.config.url||"https://codestral.mistral.ai",i={model:this.params.config.model,messages:[{role:"system",content:e},{role:"user",content:$e(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"}),oe(o,r,"Codestral",i,n);const c=Date.now();try{const f=await new je({method:"POST",baseURL:`${s}/v1/chat/completions`,timeout:this.params.config.timeout}).setHeaders({Authorization:`Bearer ${this.apiKey}`,"content-type":"application/json"}).setBody(i).execute(),u=Date.now()-c,l=f.data;if(Q(o,r,"Codestral",l,n),!l.choices||l.choices.length===0||!l.choices[0].message?.content)throw G(o,r,"Codestral",{message:"No Content on response",result:l},n),new Error("No Content on response. Please open a Bug report");const m=l.choices[0].message.content;return W(o,r,"Codestral",u,m,n),m}catch(a){throw G(o,r,"Codestral",a,n),a}}}class Po extends Z{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 Sn({token:this.params.config.key})}getServiceSpecificErrorMessage(e){const r=e.message||"";return r.includes("API key")||r.includes("api_key")?"Invalid API key. Check your Cohere API key in configuration":r.includes("rate_limit")||r.includes("Rate limit")?"Rate limit exceeded. Wait a moment and try again, or upgrade your Cohere plan":r.includes("model")||r.includes("Model")?"Model not found or not accessible. Check if the Cohere model name is correct":r.includes("overloaded")||r.includes("capacity")?"Cohere service is overloaded. Try again in a few minutes":r.includes("403")||r.includes("Forbidden")?"Access denied. Your API key may not have permission for this Cohere model":r.includes("404")||r.includes("Not Found")?"Model or endpoint not found. Check your Cohere model configuration":r.includes("500")||r.includes("Internal Server Error")?"Cohere server error. Try again later":null}generateCommitMessage$(){return D(this.generateMessage("commit")).pipe(L(e=>A(e)),I(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:this.params.config.includeBody?e.value:e.title,description:this.params.config.includeBody?e.value:"",isError:!1})),M(this.handleError$))}generateCodeReview$(){return D(this.generateMessage("review")).pipe(L(e=>A(e)),I(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),M(this.handleError$))}async generateMessage(e){const r=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:n,codeReviewPromptPath:s,logging:i,temperature:c,locale:a,generate:f,type:u,maxLength:l,maxTokens:d}=this.params.config,m={...Y,locale:a,maxLength:l,type:u,generate:f,systemPrompt:o,systemPromptPath:n,codeReviewPromptPath:s},h=e==="review"?te(m):ee(m),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"};V(r,e,"Cohere",this.params.config.model,w,v,i),X(r,e,"Cohere",h,g,i);const E={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};oe(r,e,"Cohere",E,i);const O=Date.now();try{const $=await this.cohere.chat(E,{timeoutInSeconds:Math.floor(this.params.config.timeout/1e3)}),P=Date.now()-O,S=$.text;return Q(r,e,"Cohere",$,i),W(r,e,"Cohere",P,S,i),e==="review"?this.sanitizeResponse(S):this.parseMessage(S,u,f)}catch($){throw G(r,e,"Cohere",$,i),$}}}class $o extends Z{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 kr({baseURL:r,apiKey:this.params.config.key})}getServiceSpecificErrorMessage(e){const r=e.message||"";return r.includes("API key")||r.includes("api_key")?"Invalid API key. Check your DeepSeek API key in configuration":r.includes("rate_limit")||r.includes("Rate limit")?"Rate limit exceeded. Wait a moment and try again, or upgrade your DeepSeek plan":r.includes("model")||r.includes("Model")?"Model not found or not accessible. Check if the DeepSeek model name is correct":r.includes("Invalid model type")?"Invalid model type. Use supported models: deepseek-reasoner, deepseek-chat":r.includes("overloaded")||r.includes("capacity")?"DeepSeek service is overloaded. Try again in a few minutes":r.includes("403")||r.includes("Forbidden")?"Access denied. Your API key may not have permission for this DeepSeek model":r.includes("404")||r.includes("Not Found")?"Model or endpoint not found. Check your DeepSeek model configuration":r.includes("500")||r.includes("Internal Server Error")?"DeepSeek server error. Try again later":null}generateCommitMessage$(){return D(this.generateMessage("commit")).pipe(L(e=>A(e)),I(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:this.params.config.includeBody?e.value:e.title,description:this.params.config.includeBody?e.value:"",isError:!1})),M(this.handleError$))}generateCodeReview$(){return D(this.generateMessage("review")).pipe(L(e=>A(e)),I(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),M(this.handleError$))}async generateMessage(e){const r=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:n,codeReviewPromptPath:s,logging:i,locale:c,generate:a,type:f,maxLength:u}=this.params.config,l={...Y,locale:c,maxLength:u,type:f,generate:a,systemPrompt:o,systemPromptPath:n,codeReviewPromptPath:s},d=e==="review"?te(l):ee(l);this.checkAvailableModels();const m=$e(r,e),g=`${this.params.config.url||"https://api.deepseek.com"}/chat/completions`,y={Authorization:`Bearer ${this.params.config.key}`,"Content-Type":"application/json"};V(r,e,"DeepSeek",this.params.config.model,g,y,i),X(r,e,"DeepSeek",d,m,i);const w=await this.createChatCompletions(d,m,e);return e==="review"?this.sanitizeResponse(w):this.parseMessage(w,f,a)}checkAvailableModels(){if(["deepseek-reasoner","deepseek-chat"].includes(this.params.config.model))return!0;throw new Error("Invalid model type of DeepSeek")}async createChatCompletions(e,r,o){const n=this.params.stagedDiff.diff,{logging:s}=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};oe(n,o,"DeepSeek",i,s);const c=Date.now();try{const a=await this.deepSeek.chat.completions.create(i,{timeout:this.params.config.timeout}),f=Date.now()-c,u=a.choices[0].message.content||"";return Q(n,o,"DeepSeek",a,s),W(n,o,"DeepSeek",f,u,s),u}catch(a){throw G(n,o,"DeepSeek",a,s),a}}}class Eo extends Z{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 In(this.params.config.key)}getServiceSpecificErrorMessage(e){const r=e.message||"";return r.includes("API key")||r.includes("api_key")?"Invalid API key. Check your Google AI Studio API key in configuration":r.includes("quota")||r.includes("QUOTA_EXCEEDED")?"API quota exceeded. Check your Google AI Studio usage limits":r.includes("model")||r.includes("Model")?"Model not found or not accessible. Check if the Gemini model name is correct":r.includes("SAFETY")||r.includes("safety")?"Content blocked by safety filters. Try rephrasing your request":r.includes("RECITATION")||r.includes("recitation")?"Content blocked due to recitation concerns. Try a different approach":r.includes("403")||r.includes("Forbidden")?"Access denied. Your API key may not have permission for this Gemini model":r.includes("404")||r.includes("Not Found")?"Model or endpoint not found. Check your Gemini model configuration":r.includes("500")||r.includes("Internal Server Error")?"Google AI service error. Try again later":null}generateCommitMessage$(){return D(this.generateMessage("commit")).pipe(L(e=>A(e)),I(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:this.params.config.includeBody?e.value:e.title,description:this.params.config.includeBody?e.value:"",isError:!1})),M(this.handleError$))}generateCodeReview$(){return D(this.generateMessage("review")).pipe(L(e=>A(e)),I(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),M(this.handleError$))}async generateMessage(e){const r=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:n,logging:s,locale:i,codeReviewPromptPath:c,generate:a,type:f,maxLength:u}=this.params.config,l=this.params.config.maxTokens,d={...Y,locale:i,maxLength:u,type:f,generate:a,systemPrompt:o,systemPromptPath:n,codeReviewPromptPath:c},m=e==="review"?te(d):ee(d),h={maxOutputTokens:l,temperature:this.params.config.temperature,topP:this.params.config.topP},g=this.genAI.getGenerativeModel({model:this.params.config.model,systemInstruction:m,generationConfig:h,safetySettings:[{category:Ke.HARM_CATEGORY_HATE_SPEECH,threshold:Je.BLOCK_LOW_AND_ABOVE},{category:Ke.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:Je.BLOCK_LOW_AND_ABOVE},{category:Ke.HARM_CATEGORY_HARASSMENT,threshold:Je.BLOCK_LOW_AND_ABOVE},{category:Ke.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:Je.BLOCK_LOW_AND_ABOVE}]}),y=$e(r,e),v=`${this.params.config.url||"https://generativelanguage.googleapis.com"}/v1beta/models/${this.params.config.model}:generateContent`,E={"Content-Type":"application/json","x-goog-api-key":this.params.config.key};V(r,e,"Gemini",this.params.config.model,v,E,s),X(r,e,"Gemini",m,y,s),oe(r,e,"Gemini",{systemInstruction:{parts:[{text:m}]},contents:[{parts:[{text:y}]}],generationConfig:h},s);const $=Date.now();try{const P=this.params.config.timeout>1e4?{request:{timeout:this.params.config.timeout}}:void 0,S=await g.generateContent(y,P),_=S.response.text(),ce=Date.now()-$;return Q(r,e,"Gemini",{response:_,candidates:S.response.candidates,usageMetadata:S.response.usageMetadata},s),W(r,e,"Gemini",ce,_,s),e==="review"?this.sanitizeResponse(_):this.parseMessage(_,f,a)}catch(P){throw G(r,e,"Gemini",P,s),P}}}var Ht={},Ut={exports:{}},Ne={exports:{}},zt,ko;function Na(){if(ko)return zt;ko=1;var t=1e3,e=t*60,r=e*60,o=r*24,n=o*7,s=o*365.25;zt=function(u,l){l=l||{};var d=typeof u;if(d==="string"&&u.length>0)return i(u);if(d==="number"&&isFinite(u))return l.long?a(u):c(u);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(u))};function i(u){if(u=String(u),!(u.length>100)){var l=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(u);if(l){var d=parseFloat(l[1]),m=(l[2]||"ms").toLowerCase();switch(m){case"years":case"year":case"yrs":case"yr":case"y":return d*s;case"weeks":case"week":case"w":return d*n;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(u){var l=Math.abs(u);return l>=o?Math.round(u/o)+"d":l>=r?Math.round(u/r)+"h":l>=e?Math.round(u/e)+"m":l>=t?Math.round(u/t)+"s":u+"ms"}function a(u){var l=Math.abs(u);return l>=o?f(u,l,o,"day"):l>=r?f(u,l,r,"hour"):l>=e?f(u,l,e,"minute"):l>=t?f(u,l,t,"second"):u+" ms"}function f(u,l,d,m){var h=l>=d*1.5;return Math.round(u/d)+" "+m+(h?"s":"")}return zt}var Kt,xo;function Ao(){if(xo)return Kt;xo=1;function t(e){o.debug=o,o.default=o,o.coerce=f,o.disable=c,o.enable=s,o.enabled=a,o.humanize=Na(),o.destroy=u,Object.keys(e).forEach(l=>{o[l]=e[l]}),o.names=[],o.skips=[],o.formatters={};function r(l){let d=0;for(let m=0;m<l.length;m++)d=(d<<5)-d+l.charCodeAt(m),d|=0;return o.colors[Math.abs(d)%o.colors.length]}o.selectColor=r;function o(l){let d,m=null,h,g;function y(...w){if(!y.enabled)return;const v=y,E=Number(new Date),O=E-(d||E);v.diff=O,v.prev=d,v.curr=E,d=E,w[0]=o.coerce(w[0]),typeof w[0]!="string"&&w.unshift("%O");let $=0;w[0]=w[0].replace(/%([a-zA-Z%])/g,(S,N)=>{if(S==="%%")return"%";$++;const _=o.formatters[N];if(typeof _=="function"){const ce=w[$];S=_.call(v,ce),w.splice($,1),$--}return S}),o.formatArgs.call(v,w),(v.log||o.log).apply(v,w)}return y.namespace=l,y.useColors=o.useColors(),y.color=o.selectColor(l),y.extend=n,y.destroy=o.destroy,Object.defineProperty(y,"enabled",{enumerable:!0,configurable:!1,get:()=>m!==null?m:(h!==o.namespaces&&(h=o.namespaces,g=o.enabled(l)),g),set:w=>{m=w}}),typeof o.init=="function"&&o.init(y),y}function n(l,d){const m=o(this.namespace+(typeof d>"u"?":":d)+l);return m.log=this.log,m}function s(l){o.save(l),o.namespaces=l,o.names=[],o.skips=[];const d=(typeof l=="string"?l:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(const m of d)m[0]==="-"?o.skips.push(m.slice(1)):o.names.push(m)}function i(l,d){let m=0,h=0,g=-1,y=0;for(;m<l.length;)if(h<d.length&&(d[h]===l[m]||d[h]==="*"))d[h]==="*"?(g=h,y=m,h++):(m++,h++);else if(g!==-1)h=g+1,y++,m=y;else return!1;for(;h<d.length&&d[h]==="*";)h++;return h===d.length}function c(){const l=[...o.names,...o.skips.map(d=>"-"+d)].join(",");return o.enable(""),l}function a(l){for(const d of o.skips)if(i(l,d))return!1;for(const d of o.names)if(i(l,d))return!0;return!1}function f(l){return l instanceof Error?l.stack||l.message:l}function u(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return o.enable(o.load()),o}return Kt=t,Kt}Ne.exports;var So;function Ta(){return So||(So=1,function(t,e){e.formatArgs=o,e.save=n,e.load=s,e.useColors=r,e.storage=i(),e.destroy=(()=>{let a=!1;return()=>{a||(a=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),e.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function r(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let a;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&(a=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(a[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function o(a){if(a[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+a[0]+(this.useColors?"%c ":" ")+"+"+t.exports.humanize(this.diff),!this.useColors)return;const f="color: "+this.color;a.splice(1,0,f,"color: inherit");let u=0,l=0;a[0].replace(/%[a-zA-Z%]/g,d=>{d!=="%%"&&(u++,d==="%c"&&(l=u))}),a.splice(l,0,f)}e.log=console.debug||console.log||(()=>{});function n(a){try{a?e.storage.setItem("debug",a):e.storage.removeItem("debug")}catch{}}function s(){let a;try{a=e.storage.getItem("debug")||e.storage.getItem("DEBUG")}catch{}return!a&&typeof process<"u"&&"env"in process&&(a=process.env.DEBUG),a}function i(){try{return localStorage}catch{}}t.exports=Ao()(e);const{formatters:c}=t.exports;c.j=function(a){try{return JSON.stringify(a)}catch(f){return"[UnexpectedJSONParseError]: "+f.message}}}(Ne,Ne.exports)),Ne.exports}var Te={exports:{}},Jt,Io;function Fa(){return Io||(Io=1,Jt=(t,e=process.argv)=>{const r=t.startsWith("-")?"":t.length===1?"-":"--",o=e.indexOf(r+t),n=e.indexOf("--");return o!==-1&&(n===-1||o<n)}),Jt}var Wt,Mo;function _a(){if(Mo)return Wt;Mo=1;const t=xe,e=xr,r=Fa(),{env:o}=process;let n;r("no-color")||r("no-colors")||r("color=false")||r("color=never")?n=0:(r("color")||r("colors")||r("color=true")||r("color=always"))&&(n=1),"FORCE_COLOR"in o&&(o.FORCE_COLOR==="true"?n=1:o.FORCE_COLOR==="false"?n=0:n=o.FORCE_COLOR.length===0?1:Math.min(parseInt(o.FORCE_COLOR,10),3));function s(a){return a===0?!1:{level:a,hasBasic:!0,has256:a>=2,has16m:a>=3}}function i(a,f){if(n===0)return 0;if(r("color=16m")||r("color=full")||r("color=truecolor"))return 3;if(r("color=256"))return 2;if(a&&!f&&n===void 0)return 0;const u=n||0;if(o.TERM==="dumb")return u;if(process.platform==="win32"){const l=t.release().split(".");return Number(l[0])>=10&&Number(l[2])>=10586?Number(l[2])>=14931?3:2:1}if("CI"in o)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE"].some(l=>l in o)||o.CI_NAME==="codeship"?1:u;if("TEAMCITY_VERSION"in o)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(o.TEAMCITY_VERSION)?1:0;if(o.COLORTERM==="truecolor")return 3;if("TERM_PROGRAM"in o){const l=parseInt((o.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(o.TERM_PROGRAM){case"iTerm.app":return l>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(o.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(o.TERM)||"COLORTERM"in o?1:u}function c(a){const f=i(a,a&&a.isTTY);return s(f)}return Wt={supportsColor:c,stdout:s(i(!0,e.isatty(1))),stderr:s(i(!0,e.isatty(2)))},Wt}Te.exports;var Ro;function Ga(){return Ro||(Ro=1,function(t,e){const r=xr,o=wr;e.init=u,e.log=c,e.formatArgs=s,e.save=a,e.load=f,e.useColors=n,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=_a();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,m)=>{const h=m.substring(6).toLowerCase().replace(/_([a-z])/g,(y,w)=>w.toUpperCase());let g=process.env[m];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 n(){return"colors"in e.inspectOpts?!!e.inspectOpts.colors:r.isatty(process.stderr.fd)}function s(d){const{namespace:m,useColors:h}=this;if(h){const g=this.color,y="\x1B[3"+(g<8?g:"8;5;"+g),w=` ${y};1m${m} \x1B[0m`;d[0]=w+d[0].split(`
|
|
74
|
+
Focus on understanding the purpose and impact of these changes to create meaningful commit message(s).`,ja=10*60*1e3;class bo extends Z{constructor(e){super(e),this.params=e,this.colors={primary:"#AE5630",secondary:"#fff"},this.serviceName=P.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[Anthropic]"),this.errorPrefix=P.red.bold("[Anthropic]"),this.anthropic=new xn({apiKey:this.params.config.key,...this.params.config.timeout>ja&&{timeout:this.params.config.timeout}})}getServiceSpecificErrorMessage(e){const r=e.message||"";return r.includes("API key")||r.includes("api_key")?"Invalid API key. Check your Anthropic API key in configuration":r.includes("quota")||r.includes("usage")?"API quota exceeded. Check your Anthropic usage limits":r.includes("model")||r.includes("Model")?"Model not found or not accessible. Check if the Claude model name is correct":r.includes("403")||r.includes("Forbidden")?"Access denied. Your API key may not have permission for this Claude model":r.includes("404")||r.includes("Not Found")?"Model or endpoint not found. Check your Claude model configuration":r.includes("500")||r.includes("Internal Server Error")?"Anthropic server error. Try again later":null}generateCommitMessage$(){return D(this.generateMessage("commit")).pipe(L(e=>S(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 D(this.generateMessage("review")).pipe(L(e=>S(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:n,codeReviewPromptPath:s,logging:i,temperature:c,locale:a,generate:m,type:d,maxLength:l,maxTokens:p,topP:u,model:h}=this.params.config,g={...Y,locale:a,maxLength:l,type:d,generate:m,systemPrompt:o,systemPromptPath:n,codeReviewPromptPath:s},y=e==="review"?te(g):ee(g),w=$e(r,e),E=`${this.params.config.url||"https://api.anthropic.com"}/v1/messages`,x={"Content-Type":"application/json","x-api-key":this.params.config.key,"anthropic-version":"2023-06-01"};q(r,e,"Anthropic",h,E,x,i),X(r,e,"Anthropic",y,w,i);const $={max_tokens:p,temperature:c,system:y,messages:[{role:"user",content:w}],top_p:u,model:h};oe(r,e,"Anthropic",$,i);const C=Date.now();try{const I=await this.anthropic.messages.create($),N=Date.now()-C;Q(r,e,"Anthropic",I,i);const _=I.content.map(({text:ce})=>ce).join("");return W(r,e,"Anthropic",N,_,i),e==="review"?this.sanitizeResponse(_):this.parseMessage(_,d,m)}catch(I){throw G(r,e,"Anthropic",I,i),I}}}class je{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=An.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 Co extends Z{constructor(e){super(e),this.params=e,this.apiKey="",this.colors={primary:"#e28c58",secondary:"#fff"},this.serviceName=P.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[Codestral]"),this.errorPrefix=P.red.bold("[Codestral]"),this.apiKey=this.params.config.key}getServiceSpecificErrorMessage(e){const r=e.message||"";return r.includes("API key")||r.includes("api_key")?"Invalid API key. Check your Codestral API key in configuration":r.includes("rate_limit")||r.includes("Rate limit")?"Rate limit exceeded. Wait a moment and try again, or upgrade your Codestral plan":r.includes("model")||r.includes("Model")?"Model not found or not accessible. Check if the Codestral model name is correct":r.includes("Invalid model type")?"Invalid model type. Use supported models: codestral-latest, codestral-2501":r.includes("overloaded")||r.includes("capacity")?"Codestral service is overloaded. Try again in a few minutes":r.includes("403")||r.includes("Forbidden")?"Access denied. Your API key may not have permission for this Codestral model":r.includes("404")||r.includes("Not Found")?"Model or endpoint not found. Check your Codestral model configuration":r.includes("500")||r.includes("Internal Server Error")?"Codestral server error. Try again later":null}generateCommitMessage$(){return D(this.generateMessage("commit")).pipe(L(e=>S(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 D(this.generateMessage("review")).pipe(L(e=>S(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:n,codeReviewPromptPath:s,logging:i,locale:c,generate:a,type:m,maxLength:d}=this.params.config,l={...Y,locale:c,maxLength:d,type:m,generate:a,systemPrompt:o,systemPromptPath:n,codeReviewPromptPath:s},p=e==="review"?te(l):ee(l);this.checkAvailableModels();const u=$e(r,e),g=`${this.params.config.url||"https://codestral.mistral.ai"}/v1/chat/completions`,y={Authorization:`Bearer ${this.apiKey}`,"content-type":"application/json"};q(r,e,"Codestral",this.params.config.model,g,y,i),X(r,e,"Codestral",p,u,i);const w=await this.createChatCompletions(p,e);return e==="review"?this.sanitizeResponse(w):this.parseMessage(w,m,a)}checkAvailableModels(){if(["codestral-latest","codestral-2501"].includes(this.params.config.model))return!0;throw new Error("Invalid model type of Codestral AI")}async createChatCompletions(e,r){const o=this.params.stagedDiff.diff,{logging:n}=this.params.config,s=this.params.config.url||"https://codestral.mistral.ai",i={model:this.params.config.model,messages:[{role:"system",content:e},{role:"user",content:$e(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"}),oe(o,r,"Codestral",i,n);const c=Date.now();try{const m=await new je({method:"POST",baseURL:`${s}/v1/chat/completions`,timeout:this.params.config.timeout}).setHeaders({Authorization:`Bearer ${this.apiKey}`,"content-type":"application/json"}).setBody(i).execute(),d=Date.now()-c,l=m.data;if(Q(o,r,"Codestral",l,n),!l.choices||l.choices.length===0||!l.choices[0].message?.content)throw G(o,r,"Codestral",{message:"No Content on response",result:l},n),new Error("No Content on response. Please open a Bug report");const u=l.choices[0].message.content;return W(o,r,"Codestral",d,u,n),u}catch(a){throw G(o,r,"Codestral",a,n),a}}}class Po extends Z{constructor(e){super(e),this.params=e,this.colors={primary:"#D18EE2",secondary:"#fff"},this.serviceName=P.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[Cohere]"),this.errorPrefix=P.red.bold("[Cohere]"),this.cohere=new Sn({token:this.params.config.key})}getServiceSpecificErrorMessage(e){const r=e.message||"";return r.includes("API key")||r.includes("api_key")?"Invalid API key. Check your Cohere API key in configuration":r.includes("rate_limit")||r.includes("Rate limit")?"Rate limit exceeded. Wait a moment and try again, or upgrade your Cohere plan":r.includes("model")||r.includes("Model")?"Model not found or not accessible. Check if the Cohere model name is correct":r.includes("overloaded")||r.includes("capacity")?"Cohere service is overloaded. Try again in a few minutes":r.includes("403")||r.includes("Forbidden")?"Access denied. Your API key may not have permission for this Cohere model":r.includes("404")||r.includes("Not Found")?"Model or endpoint not found. Check your Cohere model configuration":r.includes("500")||r.includes("Internal Server Error")?"Cohere server error. Try again later":null}generateCommitMessage$(){return D(this.generateMessage("commit")).pipe(L(e=>S(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 D(this.generateMessage("review")).pipe(L(e=>S(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:n,codeReviewPromptPath:s,logging:i,temperature:c,locale:a,generate:m,type:d,maxLength:l,maxTokens:p}=this.params.config,u={...Y,locale:a,maxLength:l,type:d,generate:m,systemPrompt:o,systemPromptPath:n,codeReviewPromptPath:s},h=e==="review"?te(u):ee(u),g=`Here is the diff: ${r}`,w=`${this.params.config.url||"https://api.cohere.ai"}/v1/chat`,v={Authorization:`Bearer ${this.params.config.key}`,"Content-Type":"application/json"};q(r,e,"Cohere",this.params.config.model,w,v,i),X(r,e,"Cohere",h,g,i);const E={chatHistory:h?[{role:"SYSTEM",message:h}]:[],message:g,connectors:[{id:"web-search"}],maxTokens:p,temperature:c,model:this.params.config.model,seed:ot(10,1e3),p:this.params.config.topP};oe(r,e,"Cohere",E,i);const x=Date.now();try{const $=await this.cohere.chat(E,{timeoutInSeconds:Math.floor(this.params.config.timeout/1e3)}),C=Date.now()-x,I=$.text;return Q(r,e,"Cohere",$,i),W(r,e,"Cohere",C,I,i),e==="review"?this.sanitizeResponse(I):this.parseMessage(I,d,m)}catch($){throw G(r,e,"Cohere",$,i),$}}}class $o extends Z{constructor(e){super(e),this.params=e,this.colors={primary:"#53a3f9",secondary:"#fff"},this.serviceName=P.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[DeepSeek]"),this.errorPrefix=P.red.bold("[DeepSeek]");const r=this.params.config.url||"https://api.deepseek.com";this.deepSeek=new kr({baseURL:r,apiKey:this.params.config.key})}getServiceSpecificErrorMessage(e){const r=e.message||"";return r.includes("API key")||r.includes("api_key")?"Invalid API key. Check your DeepSeek API key in configuration":r.includes("rate_limit")||r.includes("Rate limit")?"Rate limit exceeded. Wait a moment and try again, or upgrade your DeepSeek plan":r.includes("model")||r.includes("Model")?"Model not found or not accessible. Check if the DeepSeek model name is correct":r.includes("Invalid model type")?"Invalid model type. Use supported models: deepseek-reasoner, deepseek-chat":r.includes("overloaded")||r.includes("capacity")?"DeepSeek service is overloaded. Try again in a few minutes":r.includes("403")||r.includes("Forbidden")?"Access denied. Your API key may not have permission for this DeepSeek model":r.includes("404")||r.includes("Not Found")?"Model or endpoint not found. Check your DeepSeek model configuration":r.includes("500")||r.includes("Internal Server Error")?"DeepSeek server error. Try again later":null}generateCommitMessage$(){return D(this.generateMessage("commit")).pipe(L(e=>S(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 D(this.generateMessage("review")).pipe(L(e=>S(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:n,codeReviewPromptPath:s,logging:i,locale:c,generate:a,type:m,maxLength:d}=this.params.config,l={...Y,locale:c,maxLength:d,type:m,generate:a,systemPrompt:o,systemPromptPath:n,codeReviewPromptPath:s},p=e==="review"?te(l):ee(l);this.checkAvailableModels();const u=$e(r,e),g=`${this.params.config.url||"https://api.deepseek.com"}/chat/completions`,y={Authorization:`Bearer ${this.params.config.key}`,"Content-Type":"application/json"};q(r,e,"DeepSeek",this.params.config.model,g,y,i),X(r,e,"DeepSeek",p,u,i);const w=await this.createChatCompletions(p,u,e);return e==="review"?this.sanitizeResponse(w):this.parseMessage(w,m,a)}checkAvailableModels(){if(["deepseek-reasoner","deepseek-chat"].includes(this.params.config.model))return!0;throw new Error("Invalid model type of DeepSeek")}async createChatCompletions(e,r,o){const n=this.params.stagedDiff.diff,{logging:s}=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};oe(n,o,"DeepSeek",i,s);const c=Date.now();try{const a=await this.deepSeek.chat.completions.create(i,{timeout:this.params.config.timeout}),m=Date.now()-c,d=a.choices[0].message.content||"";return Q(n,o,"DeepSeek",a,s),W(n,o,"DeepSeek",m,d,s),d}catch(a){throw G(n,o,"DeepSeek",a,s),a}}}class Eo extends Z{constructor(e){super(e),this.params=e,this.colors={primary:"#0077FF",secondary:"#fff"},this.serviceName=P.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[Gemini]"),this.errorPrefix=P.red.bold("[Gemini]"),this.genAI=new In(this.params.config.key)}getServiceSpecificErrorMessage(e){const r=e.message||"";return r.includes("API key")||r.includes("api_key")?"Invalid API key. Check your Google AI Studio API key in configuration":r.includes("quota")||r.includes("QUOTA_EXCEEDED")?"API quota exceeded. Check your Google AI Studio usage limits":r.includes("model")||r.includes("Model")?"Model not found or not accessible. Check if the Gemini model name is correct":r.includes("SAFETY")||r.includes("safety")?"Content blocked by safety filters. Try rephrasing your request":r.includes("RECITATION")||r.includes("recitation")?"Content blocked due to recitation concerns. Try a different approach":r.includes("403")||r.includes("Forbidden")?"Access denied. Your API key may not have permission for this Gemini model":r.includes("404")||r.includes("Not Found")?"Model or endpoint not found. Check your Gemini model configuration":r.includes("500")||r.includes("Internal Server Error")?"Google AI service error. Try again later":null}generateCommitMessage$(){return D(this.generateMessage("commit")).pipe(L(e=>S(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 D(this.generateMessage("review")).pipe(L(e=>S(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:n,logging:s,locale:i,codeReviewPromptPath:c,generate:a,type:m,maxLength:d}=this.params.config,l=this.params.config.maxTokens,p={...Y,locale:i,maxLength:d,type:m,generate:a,systemPrompt:o,systemPromptPath:n,codeReviewPromptPath:c},u=e==="review"?te(p):ee(p),h={maxOutputTokens:l,temperature:this.params.config.temperature,topP:this.params.config.topP},g=this.genAI.getGenerativeModel({model:this.params.config.model,systemInstruction:u,generationConfig:h,safetySettings:[{category:Ke.HARM_CATEGORY_HATE_SPEECH,threshold:Je.BLOCK_LOW_AND_ABOVE},{category:Ke.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:Je.BLOCK_LOW_AND_ABOVE},{category:Ke.HARM_CATEGORY_HARASSMENT,threshold:Je.BLOCK_LOW_AND_ABOVE},{category:Ke.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:Je.BLOCK_LOW_AND_ABOVE}]}),y=$e(r,e),v=`${this.params.config.url||"https://generativelanguage.googleapis.com"}/v1beta/models/${this.params.config.model}:generateContent`,E={"Content-Type":"application/json","x-goog-api-key":this.params.config.key};q(r,e,"Gemini",this.params.config.model,v,E,s),X(r,e,"Gemini",u,y,s),oe(r,e,"Gemini",{systemInstruction:{parts:[{text:u}]},contents:[{parts:[{text:y}]}],generationConfig:h},s);const $=Date.now();try{const C=this.params.config.timeout>1e4?{request:{timeout:this.params.config.timeout}}:void 0,I=await g.generateContent(y,C),_=I.response.text(),ce=Date.now()-$;return Q(r,e,"Gemini",{response:_,candidates:I.response.candidates,usageMetadata:I.response.usageMetadata},s),W(r,e,"Gemini",ce,_,s),e==="review"?this.sanitizeResponse(_):this.parseMessage(_,m,a)}catch(C){throw G(r,e,"Gemini",C,s),C}}}var Ht={},Ut={exports:{}},Ne={exports:{}},zt,ko;function Na(){if(ko)return zt;ko=1;var t=1e3,e=t*60,r=e*60,o=r*24,n=o*7,s=o*365.25;zt=function(d,l){l=l||{};var p=typeof d;if(p==="string"&&d.length>0)return i(d);if(p==="number"&&isFinite(d))return l.long?a(d):c(d);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(d))};function i(d){if(d=String(d),!(d.length>100)){var l=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(d);if(l){var p=parseFloat(l[1]),u=(l[2]||"ms").toLowerCase();switch(u){case"years":case"year":case"yrs":case"yr":case"y":return p*s;case"weeks":case"week":case"w":return p*n;case"days":case"day":case"d":return p*o;case"hours":case"hour":case"hrs":case"hr":case"h":return p*r;case"minutes":case"minute":case"mins":case"min":case"m":return p*e;case"seconds":case"second":case"secs":case"sec":case"s":return p*t;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return p;default:return}}}}function c(d){var l=Math.abs(d);return l>=o?Math.round(d/o)+"d":l>=r?Math.round(d/r)+"h":l>=e?Math.round(d/e)+"m":l>=t?Math.round(d/t)+"s":d+"ms"}function a(d){var l=Math.abs(d);return l>=o?m(d,l,o,"day"):l>=r?m(d,l,r,"hour"):l>=e?m(d,l,e,"minute"):l>=t?m(d,l,t,"second"):d+" ms"}function m(d,l,p,u){var h=l>=p*1.5;return Math.round(d/p)+" "+u+(h?"s":"")}return zt}var Kt,xo;function Ao(){if(xo)return Kt;xo=1;function t(e){o.debug=o,o.default=o,o.coerce=m,o.disable=c,o.enable=s,o.enabled=a,o.humanize=Na(),o.destroy=d,Object.keys(e).forEach(l=>{o[l]=e[l]}),o.names=[],o.skips=[],o.formatters={};function r(l){let p=0;for(let u=0;u<l.length;u++)p=(p<<5)-p+l.charCodeAt(u),p|=0;return o.colors[Math.abs(p)%o.colors.length]}o.selectColor=r;function o(l){let p,u=null,h,g;function y(...w){if(!y.enabled)return;const v=y,E=Number(new Date),x=E-(p||E);v.diff=x,v.prev=p,v.curr=E,p=E,w[0]=o.coerce(w[0]),typeof w[0]!="string"&&w.unshift("%O");let $=0;w[0]=w[0].replace(/%([a-zA-Z%])/g,(I,N)=>{if(I==="%%")return"%";$++;const _=o.formatters[N];if(typeof _=="function"){const ce=w[$];I=_.call(v,ce),w.splice($,1),$--}return I}),o.formatArgs.call(v,w),(v.log||o.log).apply(v,w)}return y.namespace=l,y.useColors=o.useColors(),y.color=o.selectColor(l),y.extend=n,y.destroy=o.destroy,Object.defineProperty(y,"enabled",{enumerable:!0,configurable:!1,get:()=>u!==null?u:(h!==o.namespaces&&(h=o.namespaces,g=o.enabled(l)),g),set:w=>{u=w}}),typeof o.init=="function"&&o.init(y),y}function n(l,p){const u=o(this.namespace+(typeof p>"u"?":":p)+l);return u.log=this.log,u}function s(l){o.save(l),o.namespaces=l,o.names=[],o.skips=[];const p=(typeof l=="string"?l:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(const u of p)u[0]==="-"?o.skips.push(u.slice(1)):o.names.push(u)}function i(l,p){let u=0,h=0,g=-1,y=0;for(;u<l.length;)if(h<p.length&&(p[h]===l[u]||p[h]==="*"))p[h]==="*"?(g=h,y=u,h++):(u++,h++);else if(g!==-1)h=g+1,y++,u=y;else return!1;for(;h<p.length&&p[h]==="*";)h++;return h===p.length}function c(){const l=[...o.names,...o.skips.map(p=>"-"+p)].join(",");return o.enable(""),l}function a(l){for(const p of o.skips)if(i(l,p))return!1;for(const p of o.names)if(i(l,p))return!0;return!1}function m(l){return l instanceof Error?l.stack||l.message:l}function d(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return o.enable(o.load()),o}return Kt=t,Kt}Ne.exports;var So;function Ta(){return So||(So=1,function(t,e){e.formatArgs=o,e.save=n,e.load=s,e.useColors=r,e.storage=i(),e.destroy=(()=>{let a=!1;return()=>{a||(a=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),e.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function r(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let a;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&(a=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(a[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function o(a){if(a[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+a[0]+(this.useColors?"%c ":" ")+"+"+t.exports.humanize(this.diff),!this.useColors)return;const m="color: "+this.color;a.splice(1,0,m,"color: inherit");let d=0,l=0;a[0].replace(/%[a-zA-Z%]/g,p=>{p!=="%%"&&(d++,p==="%c"&&(l=d))}),a.splice(l,0,m)}e.log=console.debug||console.log||(()=>{});function n(a){try{a?e.storage.setItem("debug",a):e.storage.removeItem("debug")}catch{}}function s(){let a;try{a=e.storage.getItem("debug")||e.storage.getItem("DEBUG")}catch{}return!a&&typeof process<"u"&&"env"in process&&(a=process.env.DEBUG),a}function i(){try{return localStorage}catch{}}t.exports=Ao()(e);const{formatters:c}=t.exports;c.j=function(a){try{return JSON.stringify(a)}catch(m){return"[UnexpectedJSONParseError]: "+m.message}}}(Ne,Ne.exports)),Ne.exports}var Te={exports:{}},Jt,Io;function Fa(){return Io||(Io=1,Jt=(t,e=process.argv)=>{const r=t.startsWith("-")?"":t.length===1?"-":"--",o=e.indexOf(r+t),n=e.indexOf("--");return o!==-1&&(n===-1||o<n)}),Jt}var Wt,Mo;function _a(){if(Mo)return Wt;Mo=1;const t=xe,e=xr,r=Fa(),{env:o}=process;let n;r("no-color")||r("no-colors")||r("color=false")||r("color=never")?n=0:(r("color")||r("colors")||r("color=true")||r("color=always"))&&(n=1),"FORCE_COLOR"in o&&(o.FORCE_COLOR==="true"?n=1:o.FORCE_COLOR==="false"?n=0:n=o.FORCE_COLOR.length===0?1:Math.min(parseInt(o.FORCE_COLOR,10),3));function s(a){return a===0?!1:{level:a,hasBasic:!0,has256:a>=2,has16m:a>=3}}function i(a,m){if(n===0)return 0;if(r("color=16m")||r("color=full")||r("color=truecolor"))return 3;if(r("color=256"))return 2;if(a&&!m&&n===void 0)return 0;const d=n||0;if(o.TERM==="dumb")return d;if(process.platform==="win32"){const l=t.release().split(".");return Number(l[0])>=10&&Number(l[2])>=10586?Number(l[2])>=14931?3:2:1}if("CI"in o)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE"].some(l=>l in o)||o.CI_NAME==="codeship"?1:d;if("TEAMCITY_VERSION"in o)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(o.TEAMCITY_VERSION)?1:0;if(o.COLORTERM==="truecolor")return 3;if("TERM_PROGRAM"in o){const l=parseInt((o.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(o.TERM_PROGRAM){case"iTerm.app":return l>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(o.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(o.TERM)||"COLORTERM"in o?1:d}function c(a){const m=i(a,a&&a.isTTY);return s(m)}return Wt={supportsColor:c,stdout:s(i(!0,e.isatty(1))),stderr:s(i(!0,e.isatty(2)))},Wt}Te.exports;var Ro;function Ga(){return Ro||(Ro=1,function(t,e){const r=xr,o=wr;e.init=d,e.log=c,e.formatArgs=s,e.save=a,e.load=m,e.useColors=n,e.destroy=o.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."),e.colors=[6,2,3,4,5,1];try{const p=_a();p&&(p.stderr||p).level>=2&&(e.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221])}catch{}e.inspectOpts=Object.keys(process.env).filter(p=>/^debug_/i.test(p)).reduce((p,u)=>{const h=u.substring(6).toLowerCase().replace(/_([a-z])/g,(y,w)=>w.toUpperCase());let g=process.env[u];return/^(yes|on|true|enabled)$/i.test(g)?g=!0:/^(no|off|false|disabled)$/i.test(g)?g=!1:g==="null"?g=null:g=Number(g),p[h]=g,p},{});function n(){return"colors"in e.inspectOpts?!!e.inspectOpts.colors:r.isatty(process.stderr.fd)}function s(p){const{namespace:u,useColors:h}=this;if(h){const g=this.color,y="\x1B[3"+(g<8?g:"8;5;"+g),w=` ${y};1m${u} \x1B[0m`;p[0]=w+p[0].split(`
|
|
75
75
|
`).join(`
|
|
76
|
-
`+w),
|
|
77
|
-
`)}function a(
|
|
78
|
-
`).map(
|
|
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 Ha.EventEmitter{constructor(o,n){super();let s=n;typeof o=="function"?this.callback=o:o&&(s=o),this.timeout=null,s&&typeof s.timeout=="number"&&(this.timeout=s.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:
|
|
76
|
+
`+w),p.push(y+"m+"+t.exports.humanize(this.diff)+"\x1B[0m")}else p[0]=i()+u+" "+p[0]}function i(){return e.inspectOpts.hideDate?"":new Date().toISOString()+" "}function c(...p){return process.stderr.write(o.formatWithOptions(e.inspectOpts,...p)+`
|
|
77
|
+
`)}function a(p){p?process.env.DEBUG=p:delete process.env.DEBUG}function m(){return process.env.DEBUG}function d(p){p.inspectOpts={};const u=Object.keys(e.inspectOpts);for(let h=0;h<u.length;h++)p.inspectOpts[u[h]]=e.inspectOpts[u[h]]}t.exports=Ao()(e);const{formatters:l}=t.exports;l.o=function(p){return this.inspectOpts.colors=this.useColors,o.inspect(p,this.inspectOpts).split(`
|
|
78
|
+
`).map(u=>u.trim()).join(" ")},l.O=function(p){return this.inspectOpts.colors=this.useColors,o.inspect(p,this.inspectOpts)}}(Te,Te.exports)),Te.exports}typeof process>"u"||process.type==="renderer"||process.browser===!0||process.__nwjs?Ut.exports=Ta():Ut.exports=Ga();var Yt=Ut.exports,Vt={};Object.defineProperty(Vt,"__esModule",{value:!0});function Ba(t){return function(e,r){return new Promise((o,n)=>{t.call(this,e,r,(s,i)=>{s?n(s):o(i)})})}}Vt.default=Ba;var Oo=B&&B.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};const Ha=yr,Ua=Oo(Yt),za=Oo(Vt),Fe=Ua.default("agent-base");function Ka(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 Ha.EventEmitter{constructor(o,n){super();let s=n;typeof o=="function"?this.callback=o:o&&(s=o),this.timeout=null,s&&typeof s.timeout=="number"&&(this.timeout=s.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,n,s){throw new Error('"agent-base" has no default implementation, you must subclass and override `callback()`')}addRequest(o,n){const s=Object.assign({},n);typeof s.secureEndpoint!="boolean"&&(s.secureEndpoint=qt()),s.host==null&&(s.host="localhost"),s.port==null&&(s.port=s.secureEndpoint?443:80),s.protocol==null&&(s.protocol=s.secureEndpoint?"https:":"http:"),s.host&&s.path&&delete s.path,delete s.agent,delete s.hostname,delete s._defaultAgent,delete s.defaultPort,delete s.createConnection,o._last=!0,o.shouldKeepAlive=!1;let i=!1,c=null;const a=s.timeout||this.timeout,m=u=>{o._hadError||(o.emit("error",u),o._hadError=!0)},d=()=>{c=null,i=!0;const u=new Error(`A "socket" was not created for HTTP request before ${a}ms`);u.code="ETIMEOUT",m(u)},l=u=>{i||(c!==null&&(clearTimeout(c),c=null),m(u))},p=u=>{if(i)return;if(c!=null&&(clearTimeout(c),c=null),Ka(u)){Fe("Callback returned another Agent instance %o",u.constructor.name),u.addRequest(o,s);return}if(u){u.once("free",()=>{this.freeSocket(u,s)}),o.onSocket(u);return}const h=new Error(`no Duplex stream was returned to agent-base for \`${o.method} ${o.path}\``);m(h)};if(typeof this.callback!="function"){m(new Error("`callback` is not defined"));return}this.promisifiedCallback||(this.callback.length>=3?(Fe("Converting legacy callback function to promise"),this.promisifiedCallback=za.default(this.callback)):this.promisifiedCallback=this.callback),typeof a=="number"&&a>0&&(c=setTimeout(d,a)),"port"in s&&typeof s.port!="number"&&(s.port=Number(s.port));try{Fe("Resolving socket for %o request: %o",s.protocol,`${o.method} ${o.path}`),Promise.resolve(this.promisifiedCallback(o,s)).then(p,l)}catch(u){Promise.reject(u).catch(l)}}freeSocket(o,n){Fe("Freeing socket %o %o",o.constructor.name,n),o.destroy()}destroy(){Fe("Destroying agent %o",this.constructor.name)}}t.Agent=e,t.prototype=t.Agent.prototype})(lt||(lt={}));var Ja=lt,Xt={},Wa=B&&B.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Xt,"__esModule",{value:!0});const Ya=Wa(Yt),_e=Ya.default("https-proxy-agent:parse-proxy-response");function Va(t){return new Promise((e,r)=>{let o=0;const n=[];function s(){const l=t.read();l?d(l):t.once("readable",s)}function i(){t.removeListener("end",a),t.removeListener("error",m),t.removeListener("close",c),t.removeListener("readable",s)}function c(l){_e("onclose had error %o",l)}function a(){_e("onend")}function m(l){i(),_e("onerror %o",l),r(l)}function d(l){n.push(l),o+=l.length;const p=Buffer.concat(n,o);if(p.indexOf(`\r
|
|
80
80
|
\r
|
|
81
|
-
`)===-1){_e("have not received end of HTTP headers yet..."),s();return}const h=
|
|
82
|
-
`)),g=+h.split(" ")[1];_e("got proxy server response: %o",h),e({statusCode:g,buffered:
|
|
83
|
-
`;o.auth&&(i["Proxy-Authorization"]=`Basic ${Buffer.from(o.auth).toString("base64")}`);let{host:
|
|
84
|
-
`;const
|
|
85
|
-
`);const{statusCode:
|
|
81
|
+
`)===-1){_e("have not received end of HTTP headers yet..."),s();return}const h=p.toString("ascii",0,p.indexOf(`\r
|
|
82
|
+
`)),g=+h.split(" ")[1];_e("got proxy server response: %o",h),e({statusCode:g,buffered:p})}t.on("error",m),t.on("close",c),t.on("end",a),s()})}Xt.default=Va;var qa=B&&B.__awaiter||function(t,e,r,o){function n(s){return s instanceof r?s:new r(function(i){i(s)})}return new(r||(r=Promise))(function(s,i){function c(d){try{m(o.next(d))}catch(l){i(l)}}function a(d){try{m(o.throw(d))}catch(l){i(l)}}function m(d){d.done?s(d.value):n(d.value).then(c,a)}m((o=o.apply(t,e||[])).next())})},Ee=B&&B.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Ht,"__esModule",{value:!0});const Lo=Ee(On),Do=Ee(Ln),Xa=Ee(Dn),Qa=Ee(gr),Za=Ee(Yt),ec=Ja,tc=Ee(Xt),Ge=Za.default("https-proxy-agent:agent");class rc extends ec.Agent{constructor(e){let r;if(typeof e=="string"?r=Xa.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||sc(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 qa(this,void 0,void 0,function*(){const{proxy:o,secureProxy:n}=this;let s;n?(Ge("Creating `tls.Socket`: %o",o),s=Do.default.connect(o)):(Ge("Creating `net.Socket`: %o",o),s=Lo.default.connect(o));const i=Object.assign({},o.headers);let a=`CONNECT ${`${r.host}:${r.port}`} HTTP/1.1\r
|
|
83
|
+
`;o.auth&&(i["Proxy-Authorization"]=`Basic ${Buffer.from(o.auth).toString("base64")}`);let{host:m,port:d,secureEndpoint:l}=r;nc(d,l)||(m+=`:${d}`),i.Host=m,i.Connection="close";for(const y of Object.keys(i))a+=`${y}: ${i[y]}\r
|
|
84
|
+
`;const p=tc.default(s);s.write(`${a}\r
|
|
85
|
+
`);const{statusCode:u,buffered:h}=yield p;if(u===200){if(e.once("socket",oc),r.secureEndpoint){Ge("Upgrading socket connection to TLS");const y=r.servername||r.host;return Do.default.connect(Object.assign(Object.assign({},ic(r,"host","hostname","path","port")),{socket:s,servername:y}))}return s}s.destroy();const g=new Lo.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})}}Ht.default=rc;function oc(t){t.resume()}function nc(t,e){return!!(!e&&t===80||e&&t===443)}function sc(t){return typeof t=="string"?/^https:?$/i.test(t):!1}function ic(t,...e){const r={};let o;for(o in t)e.includes(o)||(r[o]=t[o]);return r}var ac=B&&B.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};const Qt=ac(Ht);function Zt(t){return new Qt.default(t)}(function(t){t.HttpsProxyAgent=Qt.default,t.prototype=Qt.default.prototype})(Zt||(Zt={}));var cc=Zt,lc=fe(cc);const uc=async(t,e,r,o,n,s,i)=>new Promise((c,a)=>{const m=JSON.stringify(o),l=(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(m),...r},timeout:n,agent:s?lc(s):void 0},p=>{const u=[];p.on("data",h=>u.push(h)),p.on("end",()=>{c({request:l,response:p,data:Buffer.concat(u).toString()})})});l.on("error",a),l.on("timeout",()=>{l.destroy(),a(new b(`Time out error: request took over ${n}ms. Try increasing the \`timeout\` config`))}),l.write(m),l.end()}),dc=async(t,e,r,o,n,s)=>{const i=new URL(t),{response:c,data:a}=await uc(i,e,{Authorization:`Bearer ${r}`},o,n,s);if(!c.statusCode||c.statusCode<200||c.statusCode>299){let m=`API Error: ${c.statusCode} - ${c.statusMessage}`;throw a&&(m+=`
|
|
86
86
|
|
|
87
|
-
${a}`),c.statusCode===500&&(
|
|
87
|
+
${a}`),c.statusCode===500&&(m+=`
|
|
88
88
|
|
|
89
|
-
Check the API status: ${t}`),new b(
|
|
89
|
+
Check the API status: ${t}`),new b(m)}return JSON.parse(a)},jo=t=>t.trim(),er=t=>["gpt-5","gpt-5-mini","gpt-5-nano"].some(e=>t.includes(e)),mc=async(t,e,r,o,n,s,i,c,a,m,d,l,p,u)=>{try{const h=$e(s,p),g=er(n),y={model:n,messages:[{role:"system",content:d},{role:"user",content:h}],stream:!1,n:1,frequency_penalty:0,presence_penalty:0,...g?{max_completion_tokens:c,temperature:1}:{max_tokens:c,top_p:m,temperature:a}},w=new URL(e),v=`${w.protocol}//${w.host}${r}`,E={Authorization:`Bearer ${o}`,"Content-Type":"application/json"};q(s,p,t,n,v,E,l),X(s,p,t,d,h,l),oe(s,p,t,y,l);const x=Date.now(),$=await dc(e,r,o,y,i,u),C=Date.now()-x;Q(s,p,t,$,l);const I=$.choices.filter(N=>N.message?.content).map(N=>jo(N.message.content)).join();return W(s,p,t,C,I,l),$.choices.filter(N=>N.message?.content).map(N=>jo(N.message.content))}catch(h){G(s,p,t,h,l);const g=h;throw g.code==="ENOTFOUND"?new b(`Error connecting to ${g.hostname} (${g.syscall})`):g}};class No extends Z{constructor(e){super(e),this.params=e,this.baseURL="https://models.github.ai",this.colors={primary:"#24292e",secondary:"#FFF"},this.serviceName=P.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[GitHub Models]"),this.errorPrefix=P.red.bold("[GitHub Models]")}getServiceSpecificErrorMessage(e){switch(e.code){case"MISSING_TOKEN":return"GitHub token is required. Run: aicommit2 github-login";case"AUTHENTICATION_FAILED":return"Authentication failed. Your GitHub token may be expired or invalid. Run: aicommit2 github-login";case"ACCESS_DENIED":return'Access denied. Make sure your GitHub token has "Models" permission in GitHub settings';case"NO_CONTENT":return"No content received from GitHub Models. The model may have failed to generate a response";default:return null}}generateCommitMessage$(){return D(this.generateMessage("commit")).pipe(L(e=>S(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 D(this.generateMessage("review")).pipe(L(e=>S(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 u=new Error("GitHub token is required for GitHub Models. Use: aicommit2 github-login");throw u.code="MISSING_TOKEN",u}const r=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:n,codeReviewPromptPath:s,locale:i,generate:c,type:a,maxLength:m}=this.params.config,d={...Y,locale:i,maxLength:m,type:a,generate:c,systemPrompt:o,systemPromptPath:n,codeReviewPromptPath:s},l=e==="review"?te(d):ee(d),p=await this.makeRequest(l,r,e);return e==="review"?this.sanitizeResponse(p):this.parseMessage(p,a,c)}async makeRequest(e,r,o){const n=Array.isArray(this.params.config.model)?this.params.config.model[0]:this.params.config.model||"gpt-4o-mini",s=[{role:"system",content:e},{role:"user",content:o==="review"?r:`Here's the diff:
|
|
90
90
|
|
|
91
|
-
${r}`}],i=er(n),c={messages:s,model:n,stream:!1,...i?{max_completion_tokens:this.params.config.maxTokens||1024,temperature:1}:{max_tokens:this.params.config.maxTokens||1024,top_p:this.params.config.topP||.95,temperature:this.params.config.temperature||.7}},a=`${this.baseURL}/inference/chat/completions`,
|
|
91
|
+
${r}`}],i=er(n),c={messages:s,model:n,stream:!1,...i?{max_completion_tokens:this.params.config.maxTokens||1024,temperature:1}:{max_tokens:this.params.config.maxTokens||1024,top_p:this.params.config.topP||.95,temperature:this.params.config.temperature||.7}},a=`${this.baseURL}/inference/chat/completions`,m={"Content-Type":"application/json",Accept:"application/vnd.github+json",Authorization:`Bearer ${this.params.config.key}`},{logging:d}=this.params.config;q(r,o,"GitHub Models",n,a,m,d),X(r,o,"GitHub Models",e,o==="review"?r:`Here's the diff:
|
|
92
92
|
|
|
93
|
-
${r}`,u),oe(r,o,"GitHub Models",c,u);const l=new AbortController,d=setTimeout(()=>l.abort(),this.params.config.timeout);try{const m=Date.now(),h=await fetch(a,{method:"POST",headers:f,body:JSON.stringify(c),signal:l.signal});if(clearTimeout(d),!h.ok){const v=await h.text(),E={status:h.status,statusText:h.statusText,url:a,headers:Object.fromEntries(h.headers),body:v};G(r,o,"GitHub Models",E,u);let O=`GitHub API request failed: ${h.status} ${h.statusText}`;try{const P=JSON.parse(v);P.error?.message?O+=` - ${P.error.message}`:P.message&&(O+=` - ${P.message}`)}catch{v&&(O+=` - ${v}`)}if(h.status===401){const P=new Error("GitHub authentication failed. Please run: aicommit2 github-login");throw P.status=h.status,P.code="AUTHENTICATION_FAILED",P.content=v,P}else if(h.status===403){const P=new Error('GitHub Models access denied. Make sure your token has "Models" permission.');throw P.status=h.status,P.code="ACCESS_DENIED",P.content=v,P}else if(h.status===404){const P=new Error(`Model "${n}" not found. Please check the model name.`);throw P.status=h.status,P.code="MODEL_NOT_FOUND",P.content=v,P}else if(h.status===429){const P=new Error("Rate limit exceeded. Please try again later.");throw P.status=h.status,P.code="RATE_LIMIT_EXCEEDED",P.content=v,P}const $=new Error(O);throw $.status=h.status,$.code="API_ERROR",$.content=v,$}const g=await h.json(),y=Date.now()-m;Q(r,o,"GitHub Models",g,u);const w=g.choices?.[0]?.message?.content?.trim();if(!w){G(r,o,"GitHub Models",{message:"No content found in GitHub Models response",result:g},u);const E=new Error("No response content received from GitHub Models");throw E.code="NO_CONTENT",E.content=JSON.stringify(g,null,2),E}return W(r,o,"GitHub Models",y,w,u),w}catch(m){if(clearTimeout(d),m instanceof Error&&m.name==="AbortError"){const y={message:`GitHub Models request timeout after ${this.params.config.timeout}ms`,error:m};G(r,o,"GitHub Models",y,u);const w=new Error(`GitHub Models request timed out after ${this.params.config.timeout}ms`);throw w.code="REQUEST_TIMEOUT",w.originalError=m,w}if(m.code)throw m;G(r,o,"GitHub Models",{message:"GitHub Models request failed",error:m},u);const g=new Error(`GitHub Models request failed: ${m instanceof Error?m.message:String(m)}`);throw g.code="REQUEST_FAILED",g.originalError=m,g}}}class To extends Z{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 Tn({apiKey:this.params.config.key})}getServiceSpecificErrorMessage(e){const r=e.message||"";return r.includes("API key")||r.includes("api_key")?"Invalid API key. Check your Groq API key in configuration":r.includes("rate_limit")||r.includes("Rate limit")?"Rate limit exceeded. Wait a moment and try again, or upgrade your Groq plan":r.includes("model")||r.includes("Model")?"Model not found or not accessible. Check if the Groq model name is correct":r.includes("overloaded")||r.includes("capacity")?"Groq service is overloaded. Try again in a few minutes":r.includes("403")||r.includes("Forbidden")?"Access denied. Your API key may not have permission for this Groq model":r.includes("404")||r.includes("Not Found")?"Model or endpoint not found. Check your Groq model configuration":r.includes("500")||r.includes("Internal Server Error")?"Groq server error. Try again later":null}generateCommitMessage$(){return D(this.generateMessage("commit")).pipe(L(e=>A(e)),I(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:this.params.config.includeBody?e.value:e.title,description:this.params.config.includeBody?e.value:"",isError:!1})),M(this.handleError$))}generateCodeReview$(){return D(this.generateMessage("review")).pipe(L(e=>A(e)),I(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),M(this.handleError$))}async generateMessage(e){const r=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:n,codeReviewPromptPath:s,logging:i,locale:c,temperature:a,generate:f,type:u,maxLength:l}=this.params.config,d=this.params.config.maxTokens,m={...Y,locale:c,maxLength:l,type:u,generate:f,systemPrompt:o,systemPromptPath:n,codeReviewPromptPath:s},h=e==="review"?te(m):ee(m),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"};V(r,e,"Groq",this.params.config.model,w,v,i),X(r,e,"Groq",h,g,i);const E={messages:[{role:"system",content:h},{role:"user",content:g}],model:this.params.config.model,max_tokens:d,top_p:this.params.config.topP,temperature:a};oe(r,e,"Groq",E,i);const O=Date.now();try{const $=await this.groq.chat.completions.create(E,{timeout:this.params.config.timeout}),P=Date.now()-O,S=$.choices[0].message.content||"";return Q(r,e,"Groq",$,i),W(r,e,"Groq",P,S,i),e==="review"?this.sanitizeResponse(S):this.parseMessage(S,u,f)}catch($){throw G(r,e,"Groq",$,i),$}}}class Fo extends Z{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 D(this.generateMessage("commit")).pipe(L(e=>A(e)),I(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:this.params.config.includeBody?e.value:e.title,description:this.params.config.includeBody?e.value:"",isError:!1})),M(this.handleError$))}generateCodeReview$(){return D(this.generateMessage("review")).pipe(L(e=>A(e)),I(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),M(this.handleError$))}async generateMessage(e){await this.initialize();const r=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:n,codeReviewPromptPath:s,logging:i,locale:c,generate:a,type:f,maxLength:u,temperature:l,maxTokens:d,topP:m,timeout:h}=this.params.config,g={...Y,locale:c,maxLength:u,type:f,generate:a,systemPrompt:o,systemPromptPath:n,codeReviewPromptPath:s},y=e==="review"?te(g):ee(g),w=`Here is the diff: ${r}`,E=`${this.params.config.url||"https://huggingface.co"}/chat/conversation`,O={...this.headers,cookie:this.cookie};V(r,e,"HuggingFace",this.params.config.model,E,O,i),X(r,e,"HuggingFace",y,w,i);const $=Date.now();try{const P=await this.getNewChat(y),N=await(await this.sendMessage(w,P.id)).completeResponsePromise();await this.deleteConversation(P.id);const _=Date.now()-$;return Q(r,e,"HuggingFace",{response:N},i),W(r,e,"HuggingFace",_,N,i),e==="review"?this.sanitizeResponse(N):this.parseMessage(N,f,a)}catch(P){throw G(r,e,"HuggingFace",P,i),P}}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 n=(await r.json()).nodes[0].data,s=n[n[0].models],i=[],c=a=>a===-1?null:n[a];for(const a of s){const f=n[a];if(n[f.unlisted])continue;const u={id:c(f.id),name:c(f.name),displayName:c(f.displayName),preprompt:c(f.preprompt),promptExamples:[],websiteUrl:c(f.websiteUrl),description:c(f.description),datasetName:c(f.datasetName),datasetUrl:c(f.datasetUrl),modelUrl:c(f.modelUrl),parameters:{}},l=c(f.promptExamples);if(l!==null){const h=l.map(g=>c(g));u.promptExamples=h.map(g=>({title:n[g.title],prompt:n[g.prompt]}))}const d=c(f.parameters),m={};for(const[h,g]of Object.entries(d)){if(g===-1){m[h]=null;continue}if(Array.isArray(n[g])){m[h]=n[g].map(y=>n[y]);continue}m[h]=n[g]}u.parameters=m,i.push(u)}return this.models=i,i}async getNewChat(e){const r={model:this.currentModelId,preprompt:e};let o=0;const n=this.params.config.url||"https://huggingface.co";for(;o<5;){const s=await fetch(`${n}/chat/conversation`,{headers:{...this.headers,"content-type":"application/json",cookie:this.cookie,Referer:`${n}/chat/`},body:JSON.stringify(r),method:"POST"}),{conversationId:i}=await s.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 n=await o.json();return this.metadataParser(n,e)}}metadataParser(e,r){const o={id:"",model:"",systemPrompt:"",title:"",history:[]},n=e.nodes[1].data,s=n[n[0].model],i=n[n[0].preprompt],c=n[n[0].title],a=n[n[0].messages],f=[];for(const u of a){const l=n[u],d=new Date(n[l.createdAt][1]).getTime()/1e3,m=new Date(n[l.updatedAt][1]).getTime()/1e3;f.push({id:n[l.id],role:n[l.from],content:n[l.content],createdAt:d,updatedAt:m})}return o.id=r,o.model=s,o.systemPrompt=i,o.title=c,o.history=f,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:[]},n=new FormData;n.append("data",JSON.stringify(o));const s=this.params.config.url||"https://huggingface.co",i=new AbortController,c=setTimeout(()=>i.abort(),this.params.config.timeout),a=await fetch(`${s}/chat/conversation/${this.currentConversionID}`,{headers:{...this.headers,cookie:this.cookie,Referer:`${s}/chat/conversation/${this.currentConversionID}`},body:n,method:"POST",signal:i.signal});clearTimeout(c);function f(g){try{const y=g.split(`
|
|
94
|
-
`),w=[];for(const v of y)v.trim()&&w.push(JSON.parse(v));return w}catch{return[{}]}}const u=new TextDecoder;let l="";const d=new TransformStream({async transform(g,y){const w=u.decode(g);try{const v=f(w);for(const E of v)E.type==="finalAnswer"?(l=E?.text||"",y.terminate()):E.type==="stream"&&y.enqueue(E?.token||"")}catch{throw new Error("Error during parsing response")}}}),m=a.body?.pipeThrough(d);async function h(){return new Promise(async(g,y)=>{try{if(!m)y("ModifiedStream undefined");else{const w=m.getReader();for(;;){const{done:v,value:E}=await w.read();if(v){g(l);break}}}}catch(w){y(w)}})}return{id:this.currentConversionID,stream:m,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 _o extends Z{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 D(this.generateMessage("commit")).pipe(L(e=>A(e)),I(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:this.params.config.includeBody?e.value:e.title,description:this.params.config.includeBody?e.value:"",isError:!1})),M(this.handleError$))}generateCodeReview$(){return D(this.generateMessage("review")).pipe(L(e=>A(e)),I(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),M(this.handleError$))}async generateMessage(e){const r=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:n,codeReviewPromptPath:s,logging:i,locale:c,generate:a,type:f,maxLength:u}=this.params.config,l={...Y,locale:c,maxLength:u,type:f,generate:a,systemPrompt:o,systemPromptPath:n,codeReviewPromptPath:s},d=e==="review"?te(l):ee(l);await this.checkAvailableModels();const m=`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"};V(r,e,"MistralAI",this.params.config.model,g,y,i),X(r,e,"MistralAI",d,m,i);const w=await this.createChatCompletions(d,m,e);return e==="review"?this.sanitizeResponse(w):this.parseMessage(w,f,a)}async checkAvailableModels(){if((await this.getAvailableModels()).includes(this.params.config.model))return!0;throw new Error(`Invalid model type of Mistral AI: ${this.params.config.model}`)}async getAvailableModels(){const e=this.params.config.url||"https://api.mistral.ai";return(await new je({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 n=this.params.stagedDiff.diff,{logging:s}=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)};oe(n,o,"MistralAI",i,s);const c=Date.now();try{const a=this.params.config.url||"https://api.mistral.ai",f=await new je({method:"POST",baseURL:`${a}/v1/chat/completions`,timeout:this.params.config.timeout}).setHeaders({Authorization:`Bearer ${this.apiKey}`,"content-type":"application/json"}).setBody(i).execute(),u=Date.now()-c,l=f.data;if(Q(n,o,"MistralAI",l,s),!l.choices||l.choices.length===0||!l.choices[0].message?.content)throw G(n,o,"MistralAI",{message:"No Content on response",result:l},s),new Error("No Content on response. Please open a Bug report");const m=l.choices[0].message.content;return W(n,o,"MistralAI",u,m,s),m}catch(a){throw G(n,o,"MistralAI",a,s),a}}}class Go extends Z{constructor(e){super(e),this.params=e,this.host=Ft,this.model="",this.key="",this.auth="",this.setupFetch=(r,o={})=>_n(r,{...o,dispatcher:new Gn({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||Ft,this.auth=this.params.config.auth||"Bearer",this.key=this.params.config.key||"",this.ollama=new Fn({host:this.host,fetch:this.setupFetch,...this.key&&{headers:{Authorization:`${this.auth} ${this.key}`}}})}getServiceSpecificErrorMessage(e){const r=e.message||"";return r.includes("ECONNREFUSED")||r.includes("connection")?`Cannot connect to Ollama server at ${this.host}. Make sure Ollama is running`:r.includes("model")||r.includes("Model")?`Model '${this.model}' not found. Pull the model with: ollama pull ${this.model}`:r.includes("401")||r.includes("Unauthorized")?"Authentication failed. Check your Ollama API key if authentication is enabled":r.includes("403")||r.includes("Forbidden")?"Access denied. Check your Ollama server permissions":r.includes("404")||r.includes("Not Found")?`Model '${this.model}' not found on Ollama server. Pull it first with: ollama pull ${this.model}`:r.includes("500")||r.includes("Internal Server Error")?"Ollama server error. Check server logs and try again":r.includes("overloaded")||r.includes("capacity")?"Ollama server is overloaded. Try again in a few minutes":null}generateCommitMessage$(){return D(this.generateMessage("commit")).pipe(L(e=>A(e)),I(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:this.params.config.includeBody?e.value:e.title,description:this.params.config.includeBody?e.value:"",isError:!1})),M(this.handleError$))}generateCodeReview$(){return D(this.generateMessage("review")).pipe(L(e=>A(e)),I(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),M(this.handleError$))}async generateMessage(e){const r=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:n,codeReviewPromptPath:s,logging:i,locale:c,generate:a,type:f,maxLength:u}=this.params.config,l={...Y,locale:c,maxLength:u,type:f,generate:a,systemPrompt:o,systemPromptPath:n,codeReviewPromptPath:s},d=e==="review"?te(l):ee(l);await this.checkIsAvailableOllama();const m=`Here is the diff: ${r}`,h=`Ollama_${this.model}`,g=`${this.host}/api/chat`,y=this.key?{Authorization:`${this.auth} ${this.key}`}:{};V(r,e,h,this.model,g,y,i),X(r,e,h,d,m,i);const w=await this.createChatCompletions(d,m,e);return e==="review"?this.sanitizeResponse(w):this.parseMessage(w,f,a)}async checkIsAvailableOllama(){const e=new je({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:n,numCtx:s,temperature:i,topP:c,timeout:a,maxTokens:f,logging:u}=this.params.config,l=n||!1,d=this.params.stagedDiff.diff,m=`Ollama_${this.model}`,h={model:this.model,messages:[{role:"system",content:e},{role:"user",content:r}],stream:l,keep_alive:a,options:{num_ctx:s,temperature:i,top_p:c,seed:ot(10,1e3),num_predict:f??-1}};oe(d,o,m,h,u);const g=Date.now();try{const y=await this.ollama.chat(h),w=Date.now()-g;let v="";if(l){if(y)for await(const E of y)v+=E.message.content}else v=y.message.content;return Q(d,o,m,{response:v,fullResponse:y},u),W(d,o,m,w,v,u),v}catch(y){throw G(d,o,m,y,u),y}}}class Bo extends Z{constructor(e){super(e),this.params=e;const r=this.params.keyName||"OPENAI_COMPATIBLE";this.colors=ya(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 kr({apiKey:this.params.config.key,baseURL:`${this.params.config.url}${this.params.config.path}`})}getServiceSpecificErrorMessage(e){const r=e.message||"";return r.includes("API key")||r.includes("api_key")?"Invalid API key. Check your OpenAI-compatible API key in configuration":r.includes("rate_limit")||r.includes("Rate limit")?"Rate limit exceeded. Wait a moment and try again, or check your service limits":r.includes("model")||r.includes("Model")?"Model not found or not accessible. Check if the model name is correct":r.includes("network")||r.includes("connection")?"Network error. Check your internet connection and API endpoint":r.includes("quota")||r.includes("usage")?"API quota exceeded. Check your usage limits":r.includes("403")||r.includes("Forbidden")?"Access denied. Your API key may not have permission for this model":r.includes("404")||r.includes("Not Found")?"Model or endpoint not found. Check your API configuration":r.includes("500")||r.includes("Internal Server Error")?"Server error. Try again later":r.includes("overloaded")||r.includes("capacity")?"Service is overloaded. Try again in a few minutes":null}generateCommitMessage$(){return D(this.generateMessage("commit")).pipe(L(e=>A(e)),I(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:this.params.config.includeBody?e.value:e.title,description:this.params.config.includeBody?e.value:"",isError:!1})),M(this.handleError$))}generateCodeReview$(){return D(this.generateMessage("review")).pipe(L(e=>A(e)),I(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),M(this.handleError$))}async generateMessage(e){const r=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:n,codeReviewPromptPath:s,logging:i,locale:c,temperature:a,generate:f,type:u,maxLength:l,timeout:d,stream:m=!1}=this.params.config,h=this.params.config.maxTokens,g={...Y,locale:c,maxLength:l,type:u,generate:f,systemPrompt:o,systemPromptPath:n,codeReviewPromptPath:s},y=e==="review"?te(g):ee(g),w=`Here is the diff: ${r}`,v=this.params.keyName||"OpenAI-Compatible",E=`${this.params.config.url}${this.params.config.path}`,O={Authorization:`Bearer ${this.params.config.key}`,"Content-Type":"application/json"};V(r,e,v,this.params.config.model,E,O,i),X(r,e,v,y,w,i);const $=er(this.params.config.model),P={messages:[{role:"system",content:y},{role:"user",content:w}],model:this.params.config.model,stream:m,...$?{max_completion_tokens:h,temperature:1}:{max_tokens:h,top_p:this.params.config.topP,temperature:a}};oe(r,e,v,P,i);const S=Date.now();try{const N=await this.openAI.chat.completions.create(P,{timeout:d});let _="";if(m&&N){const ln=N;for await(const mr of ln){const un=mr.choices?.[0]?.delta?.content||"",dn=mr.choices?.[0]?.delta?.reasoning_content||"",mn=`${un}${dn}`;_+=mn}}else _=N.choices?.[0]?.message.content||"";const ce=Date.now()-S;return Q(r,e,v,N,i),W(r,e,v,ce,_,i),e==="review"?this.sanitizeResponse(_):this.parseMessage(_,u,f)}catch(N){throw G(r,e,v,N,i),N}}}class Ho extends Z{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 D(this.generateMessage("commit")).pipe(L(e=>A(e)),I(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:this.params.config.includeBody?e.value:e.title,description:this.params.config.includeBody?e.value:"",isError:!1})),M(this.handleError$))}generateCodeReview$(){return D(this.generateMessage("review")).pipe(L(e=>A(e)),I(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),M(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(n=>JSON.parse(n))):{error:{message:"Unknown error"}}}async generateMessage(e){const r=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:n,codeReviewPromptPath:s,temperature:i,logging:c,locale:a,generate:f,type:u,maxLength:l,proxy:d,maxTokens:m,timeout:h}=this.params.config,g={...Y,locale:a,maxLength:l,type:u,generate:f,systemPrompt:o,systemPromptPath:n,codeReviewPromptPath:s},y=e==="review"?te(g):ee(g),w=await mc("ChatGPT",this.params.config.url,this.params.config.path,this.params.config.key,this.params.config.model,r,h,m,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,u,f)))}}class Uo extends Z{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 D(this.generateMessage("commit")).pipe(L(e=>A(e)),I(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:this.params.config.includeBody?e.value:e.title,description:this.params.config.includeBody?e.value:"",isError:!1})),M(this.handleError$))}generateCodeReview$(){return D(this.generateMessage("review")).pipe(L(e=>A(e)),I(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),M(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(n=>JSON.parse(n))):{error:{message:"Unknown error"}}}async generateMessage(e){const r=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:n,codeReviewPromptPath:s,logging:i,locale:c,generate:a,type:f,maxLength:u}=this.params.config,l={...Y,locale:c,maxLength:u,type:f,generate:a,systemPrompt:o,systemPromptPath:n,codeReviewPromptPath:s},d=e==="review"?te(l):ee(l),m=`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"};V(r,e,"Perplexity",this.params.config.model,g,y,i),X(r,e,"Perplexity",d,m,i);const w=await this.createChatCompletions(d,m,e);return this.parseMessage(w,f,a)}async createChatCompletions(e,r,o){const n=this.params.stagedDiff.diff,{logging:s}=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};oe(n,o,"Perplexity",i,s);const c=Date.now();try{const a=this.params.config.url||"https://api.perplexity.ai",f=await new je({method:"POST",baseURL:`${a}/chat/completions`,timeout:this.params.config.timeout}).setHeaders({Authorization:`Bearer ${this.apiKey}`,"content-type":"application/json"}).setBody(i).execute(),u=Date.now()-c,l=f.data;if(Q(n,o,"Perplexity",l,s),!l.choices||l.choices.length===0||!l.choices[0].message?.content)throw G(n,o,"Perplexity",{message:"No Content on response",result:l},s),new Error("No Content on response. Please open a Bug report");const m=l.choices[0].message.content;return W(n,o,"Perplexity",u,m,s),m}catch(a){throw G(n,o,"Perplexity",a,s),a}}}class ut{constructor(e,r){this.config=e,this.stagedDiff=r}createCommitMsgRequests$(e){return A(e).pipe(ze(r=>{const o=this.config[r],n=Array.isArray(o.model)?o.model:[o.model];return A(n).pipe(ze(s=>{if(o.compatible)return j.create(Bo,{config:{...o,url:o.url||"",path:o.path||"",model:s},stagedDiff:this.stagedDiff,keyName:s}).generateCommitMessage$();switch(r){case"OPENAI":return j.create(Ho,{config:{...this.config.OPENAI,model:s},stagedDiff:this.stagedDiff,keyName:s}).generateCommitMessage$();case"GEMINI":return j.create(Eo,{config:{...this.config.GEMINI,model:s},stagedDiff:this.stagedDiff,keyName:s}).generateCommitMessage$();case"ANTHROPIC":return j.create(bo,{config:{...this.config.ANTHROPIC,model:s},stagedDiff:this.stagedDiff,keyName:s}).generateCommitMessage$();case"HUGGINGFACE":return j.create(Fo,{config:{...this.config.HUGGINGFACE,model:s},stagedDiff:this.stagedDiff,keyName:s}).generateCommitMessage$();case"MISTRAL":return j.create(_o,{config:{...this.config.MISTRAL,model:s},stagedDiff:this.stagedDiff,keyName:s}).generateCommitMessage$();case"CODESTRAL":return j.create(Co,{config:{...this.config.CODESTRAL,model:s},stagedDiff:this.stagedDiff,keyName:s}).generateCommitMessage$();case"OLLAMA":return j.create(Go,{config:{...this.config.OLLAMA,model:s},keyName:s,stagedDiff:this.stagedDiff}).generateCommitMessage$();case"COHERE":return j.create(Po,{config:{...this.config.COHERE,model:s},stagedDiff:this.stagedDiff,keyName:s}).generateCommitMessage$();case"GROQ":return j.create(To,{config:{...this.config.GROQ,model:s},stagedDiff:this.stagedDiff,keyName:s}).generateCommitMessage$();case"PERPLEXITY":return j.create(Uo,{config:{...this.config.PERPLEXITY,model:s},stagedDiff:this.stagedDiff,keyName:s}).generateCommitMessage$();case"GITHUB_MODELS":return j.create(No,{config:{...this.config.GITHUB_MODELS,model:s},stagedDiff:this.stagedDiff,keyName:s}).generateCommitMessage$();case"DEEPSEEK":return j.create($o,{config:{...this.config.DEEPSEEK,model:s},stagedDiff:this.stagedDiff,keyName:s}).generateCommitMessage$();default:const i=C.red.bold(`[${r}]`);return Ae({name:i+" Invalid AI type",value:"Invalid AI type",isError:!0,disabled:!0})}}))}),M(r=>{const o=C.red.bold("[UNKNOWN]");return Ae({name:o+` ${r.message||""}`,value:"Unknown error",isError:!0,disabled:!0})}))}createCodeReviewRequests$(e){return A(e).pipe(ze(r=>{const o=this.config[r],n=Array.isArray(o.model)?o.model:[o.model];return A(n).pipe(ze(s=>{if(o.compatible)return j.create(Bo,{config:{...o,url:o.url||"",path:o.path||"",model:s},stagedDiff:this.stagedDiff,keyName:s}).generateCodeReview$();switch(r){case"OPENAI":return j.create(Ho,{config:{...this.config.OPENAI,model:s},stagedDiff:this.stagedDiff,keyName:s}).generateCodeReview$();case"GEMINI":return j.create(Eo,{config:{...this.config.GEMINI,model:s},stagedDiff:this.stagedDiff,keyName:s}).generateCodeReview$();case"ANTHROPIC":return j.create(bo,{config:{...this.config.ANTHROPIC,model:s},stagedDiff:this.stagedDiff,keyName:s}).generateCodeReview$();case"HUGGINGFACE":return j.create(Fo,{config:{...this.config.HUGGINGFACE,model:s},stagedDiff:this.stagedDiff,keyName:s}).generateCodeReview$();case"MISTRAL":return j.create(_o,{config:{...this.config.MISTRAL,model:s},stagedDiff:this.stagedDiff,keyName:s}).generateCodeReview$();case"CODESTRAL":return j.create(Co,{config:{...this.config.CODESTRAL,model:s},stagedDiff:this.stagedDiff,keyName:s}).generateCodeReview$();case"OLLAMA":return j.create(Go,{config:{...this.config.OLLAMA,model:s},keyName:s,stagedDiff:this.stagedDiff}).generateCodeReview$();case"COHERE":return j.create(Po,{config:{...this.config.COHERE,model:s},stagedDiff:this.stagedDiff,keyName:s}).generateCodeReview$();case"GROQ":return j.create(To,{config:{...this.config.GROQ,model:s},stagedDiff:this.stagedDiff,keyName:s}).generateCodeReview$();case"PERPLEXITY":return j.create(Uo,{config:{...this.config.PERPLEXITY,model:s},stagedDiff:this.stagedDiff,keyName:s}).generateCodeReview$();case"GITHUB_MODELS":return j.create(No,{config:{...this.config.GITHUB_MODELS,model:s},stagedDiff:this.stagedDiff,keyName:s}).generateCodeReview$();case"DEEPSEEK":return j.create($o,{config:{...this.config.DEEPSEEK,model:s},stagedDiff:this.stagedDiff,keyName:s}).generateCodeReview$();default:const i=C.red.bold(`[${r}]`);return Ae({name:i+" Invalid AI type",value:"Invalid AI type",isError:!0,disabled:!0})}}))}),M(r=>{const o=C.red.bold("[UNKNOWN]");return Ae({name:o+` ${r.message||""}`,value:"Unknown error",isError:!0,disabled:!0})}))}}class zo{getDetectedMessage(e){return`Detected ${e.files.length.toLocaleString()} changed file${e.files.length>1?"s":""} (${e.diff.length.toLocaleString()} characters)`}getDetectedFiles(e){return`Detected ${e.length.toLocaleString()} changed file${e.length>1?"s":""}`}}class fc extends zo{constructor(){super(...arguments),this.name="git",this.excludeFromDiff=e=>`:(exclude)${e}`,this.filesToExclude=["package-lock.json","pnpm-lock.yaml","*.lock","*.lockb"].map(this.excludeFromDiff)}async assertRepo(){try{const{stdout:e}=await F("git",["rev-parse","--show-toplevel"],{reject:!0});return e.trim()}catch(e){const r=e;if(r.code==="ENOENT")throw new b(`Git command not found!
|
|
93
|
+
${r}`,d),oe(r,o,"GitHub Models",c,d);const l=new AbortController,p=setTimeout(()=>l.abort(),this.params.config.timeout);try{const u=Date.now(),h=await fetch(a,{method:"POST",headers:m,body:JSON.stringify(c),signal:l.signal});if(clearTimeout(p),!h.ok){const v=await h.text(),E={status:h.status,statusText:h.statusText,url:a,headers:Object.fromEntries(h.headers),body:v};G(r,o,"GitHub Models",E,d);let x=`GitHub API request failed: ${h.status} ${h.statusText}`;try{const C=JSON.parse(v);C.error?.message?x+=` - ${C.error.message}`:C.message&&(x+=` - ${C.message}`)}catch{v&&(x+=` - ${v}`)}if(h.status===401){const C=new Error("GitHub authentication failed. Please run: aicommit2 github-login");throw C.status=h.status,C.code="AUTHENTICATION_FAILED",C.content=v,C}else if(h.status===403){const C=new Error('GitHub Models access denied. Make sure your token has "Models" permission.');throw C.status=h.status,C.code="ACCESS_DENIED",C.content=v,C}else if(h.status===404){const C=new Error(`Model "${n}" not found. Please check the model name.`);throw C.status=h.status,C.code="MODEL_NOT_FOUND",C.content=v,C}else if(h.status===429){const C=new Error("Rate limit exceeded. Please try again later.");throw C.status=h.status,C.code="RATE_LIMIT_EXCEEDED",C.content=v,C}const $=new Error(x);throw $.status=h.status,$.code="API_ERROR",$.content=v,$}const g=await h.json(),y=Date.now()-u;Q(r,o,"GitHub Models",g,d);const w=g.choices?.[0]?.message?.content?.trim();if(!w){G(r,o,"GitHub Models",{message:"No content found in GitHub Models response",result:g},d);const E=new Error("No response content received from GitHub Models");throw E.code="NO_CONTENT",E.content=JSON.stringify(g,null,2),E}return W(r,o,"GitHub Models",y,w,d),w}catch(u){if(clearTimeout(p),u instanceof Error&&u.name==="AbortError"){const y={message:`GitHub Models request timeout after ${this.params.config.timeout}ms`,error:u};G(r,o,"GitHub Models",y,d);const w=new Error(`GitHub Models request timed out after ${this.params.config.timeout}ms`);throw w.code="REQUEST_TIMEOUT",w.originalError=u,w}if(u.code)throw u;G(r,o,"GitHub Models",{message:"GitHub Models request failed",error:u},d);const g=new Error(`GitHub Models request failed: ${u instanceof Error?u.message:String(u)}`);throw g.code="REQUEST_FAILED",g.originalError=u,g}}}class To extends Z{constructor(e){super(e),this.params=e,this.colors={primary:"#f55036",secondary:"#fff"},this.serviceName=P.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[Groq]"),this.errorPrefix=P.red.bold("[Groq]"),this.groq=new Tn({apiKey:this.params.config.key})}getServiceSpecificErrorMessage(e){const r=e.message||"";return r.includes("API key")||r.includes("api_key")?"Invalid API key. Check your Groq API key in configuration":r.includes("rate_limit")||r.includes("Rate limit")?"Rate limit exceeded. Wait a moment and try again, or upgrade your Groq plan":r.includes("model")||r.includes("Model")?"Model not found or not accessible. Check if the Groq model name is correct":r.includes("overloaded")||r.includes("capacity")?"Groq service is overloaded. Try again in a few minutes":r.includes("403")||r.includes("Forbidden")?"Access denied. Your API key may not have permission for this Groq model":r.includes("404")||r.includes("Not Found")?"Model or endpoint not found. Check your Groq model configuration":r.includes("500")||r.includes("Internal Server Error")?"Groq server error. Try again later":null}generateCommitMessage$(){return D(this.generateMessage("commit")).pipe(L(e=>S(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 D(this.generateMessage("review")).pipe(L(e=>S(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:n,codeReviewPromptPath:s,logging:i,locale:c,temperature:a,generate:m,type:d,maxLength:l}=this.params.config,p=this.params.config.maxTokens,u={...Y,locale:c,maxLength:l,type:d,generate:m,systemPrompt:o,systemPromptPath:n,codeReviewPromptPath:s},h=e==="review"?te(u):ee(u),g=`Here is the diff: ${r}`,w=`${this.params.config.url||"https://api.groq.com"}/openai/v1/chat/completions`,v={Authorization:`Bearer ${this.params.config.key}`,"Content-Type":"application/json"};q(r,e,"Groq",this.params.config.model,w,v,i),X(r,e,"Groq",h,g,i);const E={messages:[{role:"system",content:h},{role:"user",content:g}],model:this.params.config.model,max_tokens:p,top_p:this.params.config.topP,temperature:a};oe(r,e,"Groq",E,i);const x=Date.now();try{const $=await this.groq.chat.completions.create(E,{timeout:this.params.config.timeout}),C=Date.now()-x,I=$.choices[0].message.content||"";return Q(r,e,"Groq",$,i),W(r,e,"Groq",C,I,i),e==="review"?this.sanitizeResponse(I):this.parseMessage(I,d,m)}catch($){throw G(r,e,"Groq",$,i),$}}}class Fo extends Z{constructor(e){super(e),this.params=e,this.headers={},this.models=[],this.currentModelId=null,this.currentConversation=void 0,this.currentConversionID=void 0,this.cookie="",this.colors={primary:"#FED21F",secondary:"#000"},this.serviceName=P.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[HuggingFace]"),this.errorPrefix=P.red.bold("[HuggingFace]"),this.cookie=this.params.config.cookie;const r=this.params.config.url||"https://huggingface.co";this.headers={accept:"*/*","accept-language":"en-US,en;q=0.9","sec-ch-ua":'"Chromium";v="116", "Not)A;Brand";v="24", "Google Chrome";v="116"',"sec-ch-ua-mobile":"?0","sec-ch-ua-platform":'"Windows"',"sec-fetch-dest":"empty","sec-fetch-mode":"cors","sec-fetch-site":"same-origin",origin:r,"Referrer-Policy":"strict-origin-when-cross-origin"}}getServiceSpecificErrorMessage(e){const r=e.message||"";return r.includes("cookie")||r.includes("Cookie")?"Invalid cookie. Check your Hugging Face session cookie in configuration":r.includes("model")||r.includes("Model")?"Model not found or not accessible. Check if the Hugging Face model name is correct":r.includes("conversation")||r.includes("conversion")?"Failed to create conversation. Try again or check your session":r.includes("401")||r.includes("Unauthorized")?"Authentication failed. Your Hugging Face session may have expired":r.includes("403")||r.includes("Forbidden")?"Access denied. You may not have permission to access this model":r.includes("404")||r.includes("Not Found")?"Model not found. Check your Hugging Face model configuration":r.includes("500")||r.includes("Internal Server Error")?"Hugging Face server error. Try again later":r.includes("overloaded")||r.includes("capacity")?"Hugging Face service is overloaded. Try again in a few minutes":null}generateCommitMessage$(){return D(this.generateMessage("commit")).pipe(L(e=>S(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 D(this.generateMessage("review")).pipe(L(e=>S(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:n,codeReviewPromptPath:s,logging:i,locale:c,generate:a,type:m,maxLength:d,temperature:l,maxTokens:p,topP:u,timeout:h}=this.params.config,g={...Y,locale:c,maxLength:d,type:m,generate:a,systemPrompt:o,systemPromptPath:n,codeReviewPromptPath:s},y=e==="review"?te(g):ee(g),w=`Here is the diff: ${r}`,E=`${this.params.config.url||"https://huggingface.co"}/chat/conversation`,x={...this.headers,cookie:this.cookie};q(r,e,"HuggingFace",this.params.config.model,E,x,i),X(r,e,"HuggingFace",y,w,i);const $=Date.now();try{const C=await this.getNewChat(y),N=await(await this.sendMessage(w,C.id)).completeResponsePromise();await this.deleteConversation(C.id);const _=Date.now()-$;return Q(r,e,"HuggingFace",{response:N},i),W(r,e,"HuggingFace",_,N,i),e==="review"?this.sanitizeResponse(N):this.parseMessage(N,m,a)}catch(C){throw G(r,e,"HuggingFace",C,i),C}}async initialize(){const e=await this.getRemoteLlms(),r=e.find(o=>o.name?.toLowerCase()===this.params.config.model.toLowerCase());if(r){this.currentModel=r,this.currentModelId=r.id;return}this.currentModel=e[0],this.currentModelId=e[0].id}async getRemoteLlms(){const e=this.params.config.url||"https://huggingface.co",r=await fetch(`${e}/chat/__data.json`,{headers:{...this.headers,cookie:this.cookie},body:null,method:"GET"});if(r.status!==200)throw new Error(`Failed to get remote LLMs with status code: ${r.status}`);const n=(await r.json()).nodes[0].data,s=n[n[0].models],i=[],c=a=>a===-1?null:n[a];for(const a of s){const m=n[a];if(n[m.unlisted])continue;const d={id:c(m.id),name:c(m.name),displayName:c(m.displayName),preprompt:c(m.preprompt),promptExamples:[],websiteUrl:c(m.websiteUrl),description:c(m.description),datasetName:c(m.datasetName),datasetUrl:c(m.datasetUrl),modelUrl:c(m.modelUrl),parameters:{}},l=c(m.promptExamples);if(l!==null){const h=l.map(g=>c(g));d.promptExamples=h.map(g=>({title:n[g.title],prompt:n[g.prompt]}))}const p=c(m.parameters),u={};for(const[h,g]of Object.entries(p)){if(g===-1){u[h]=null;continue}if(Array.isArray(n[g])){u[h]=n[g].map(y=>n[y]);continue}u[h]=n[g]}d.parameters=u,i.push(d)}return this.models=i,i}async getNewChat(e){const r={model:this.currentModelId,preprompt:e};let o=0;const n=this.params.config.url||"https://huggingface.co";for(;o<5;){const s=await fetch(`${n}/chat/conversation`,{headers:{...this.headers,"content-type":"application/json",cookie:this.cookie,Referer:`${n}/chat/`},body:JSON.stringify(r),method:"POST"}),{conversationId:i}=await s.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 n=await o.json();return this.metadataParser(n,e)}}metadataParser(e,r){const o={id:"",model:"",systemPrompt:"",title:"",history:[]},n=e.nodes[1].data,s=n[n[0].model],i=n[n[0].preprompt],c=n[n[0].title],a=n[n[0].messages],m=[];for(const d of a){const l=n[d],p=new Date(n[l.createdAt][1]).getTime()/1e3,u=new Date(n[l.updatedAt][1]).getTime()/1e3;m.push({id:n[l.id],role:n[l.from],content:n[l.content],createdAt:p,updatedAt:u})}return o.id=r,o.model=s,o.systemPrompt=i,o.title=c,o.history=m,this.currentConversation=o,o}async sendMessage(e,r){if(e==="")throw new Error("the prompt can not be empty.");if(!r&&!this.currentConversionID?await this.getNewChat():r?(this.currentConversionID=r,await this.getConversationHistory(r)):this.currentConversionID&&await this.getConversationHistory(this.currentConversionID),!this.currentConversation)throw new Error("Failed to create new conversion");const o={inputs:e,id:this.currentConversation.history[this.currentConversation.history.length-1].id,is_retry:!1,is_continue:!1,web_search:!1,tools:[]},n=new FormData;n.append("data",JSON.stringify(o));const s=this.params.config.url||"https://huggingface.co",i=new AbortController,c=setTimeout(()=>i.abort(),this.params.config.timeout),a=await fetch(`${s}/chat/conversation/${this.currentConversionID}`,{headers:{...this.headers,cookie:this.cookie,Referer:`${s}/chat/conversation/${this.currentConversionID}`},body:n,method:"POST",signal:i.signal});clearTimeout(c);function m(g){try{const y=g.split(`
|
|
94
|
+
`),w=[];for(const v of y)v.trim()&&w.push(JSON.parse(v));return w}catch{return[{}]}}const d=new TextDecoder;let l="";const p=new TransformStream({async transform(g,y){const w=d.decode(g);try{const v=m(w);for(const E of v)E.type==="finalAnswer"?(l=E?.text||"",y.terminate()):E.type==="stream"&&y.enqueue(E?.token||"")}catch{throw new Error("Error during parsing response")}}}),u=a.body?.pipeThrough(p);async function h(){return new Promise(async(g,y)=>{try{if(!u)y("ModifiedStream undefined");else{const w=u.getReader();for(;;){const{done:v,value:E}=await w.read();if(v){g(l);break}}}}catch(w){y(w)}})}return{id:this.currentConversionID,stream:u,completeResponsePromise:h}}async deleteConversation(e){const r=this.params.config.url||"https://huggingface.co";return(await fetch(`${r}/chat/conversation/${e}`,{headers:{...this.headers,cookie:this.cookie,Referer:`${r}/chat/`},body:null,method:"DELETE"})).json()}}class _o extends Z{constructor(e){super(e),this.params=e,this.apiKey="",this.colors={primary:"#ff7000",secondary:"#fff"},this.serviceName=P.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[MistralAI]"),this.errorPrefix=P.red.bold("[MistralAI]"),this.apiKey=this.params.config.key}getServiceSpecificErrorMessage(e){const r=e.message||"";return r.includes("API key")||r.includes("api_key")?"Invalid API key. Check your Mistral AI API key in configuration":r.includes("quota")||r.includes("usage")?"API quota exceeded. Check your Mistral AI usage limits":r.includes("model")||r.includes("Model")?"Model not found or not accessible. Check if the Mistral model name is correct":r.includes("403")||r.includes("Forbidden")?"Access denied. Your API key may not have permission for this Mistral model":r.includes("404")||r.includes("Not Found")?"Model or endpoint not found. Check your Mistral model configuration":r.includes("500")||r.includes("Internal Server Error")?"Mistral AI server error. Try again later":null}generateCommitMessage$(){return D(this.generateMessage("commit")).pipe(L(e=>S(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 D(this.generateMessage("review")).pipe(L(e=>S(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:n,codeReviewPromptPath:s,logging:i,locale:c,generate:a,type:m,maxLength:d}=this.params.config,l={...Y,locale:c,maxLength:d,type:m,generate:a,systemPrompt:o,systemPromptPath:n,codeReviewPromptPath:s},p=e==="review"?te(l):ee(l);await this.checkAvailableModels();const u=`Here is the diff: ${r}`,g=`${this.params.config.url||"https://api.mistral.ai"}/v1/chat/completions`,y={Authorization:`Bearer ${this.apiKey}`,"content-type":"application/json"};q(r,e,"MistralAI",this.params.config.model,g,y,i),X(r,e,"MistralAI",p,u,i);const w=await this.createChatCompletions(p,u,e);return e==="review"?this.sanitizeResponse(w):this.parseMessage(w,m,a)}async checkAvailableModels(){if((await this.getAvailableModels()).includes(this.params.config.model))return!0;throw new Error(`Invalid model type of Mistral AI: ${this.params.config.model}`)}async getAvailableModels(){const e=this.params.config.url||"https://api.mistral.ai";return(await new je({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 n=this.params.stagedDiff.diff,{logging:s}=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)};oe(n,o,"MistralAI",i,s);const c=Date.now();try{const a=this.params.config.url||"https://api.mistral.ai",m=await new je({method:"POST",baseURL:`${a}/v1/chat/completions`,timeout:this.params.config.timeout}).setHeaders({Authorization:`Bearer ${this.apiKey}`,"content-type":"application/json"}).setBody(i).execute(),d=Date.now()-c,l=m.data;if(Q(n,o,"MistralAI",l,s),!l.choices||l.choices.length===0||!l.choices[0].message?.content)throw G(n,o,"MistralAI",{message:"No Content on response",result:l},s),new Error("No Content on response. Please open a Bug report");const u=l.choices[0].message.content;return W(n,o,"MistralAI",d,u,s),u}catch(a){throw G(n,o,"MistralAI",a,s),a}}}class Go extends Z{constructor(e){super(e),this.params=e,this.host=Ft,this.model="",this.key="",this.auth="",this.setupFetch=(r,o={})=>_n(r,{...o,dispatcher:new Gn({headersTimeout:this.params.config.timeout})}),this.colors={primary:"#FFF",secondary:"#000"},this.model=this.params.keyName,this.serviceName=P.bgHex(this.colors.primary).hex(this.colors.secondary).bold(`[${rt(this.model)}]`),this.errorPrefix=P.red.bold(`[${rt(this.model)}]`),this.host=this.params.config.host||Ft,this.auth=this.params.config.auth||"Bearer",this.key=this.params.config.key||"",this.ollama=new Fn({host:this.host,fetch:this.setupFetch,...this.key&&{headers:{Authorization:`${this.auth} ${this.key}`}}})}getServiceSpecificErrorMessage(e){const r=e.message||"";return r.includes("ECONNREFUSED")||r.includes("connection")?`Cannot connect to Ollama server at ${this.host}. Make sure Ollama is running`:r.includes("model")||r.includes("Model")?`Model '${this.model}' not found. Pull the model with: ollama pull ${this.model}`:r.includes("401")||r.includes("Unauthorized")?"Authentication failed. Check your Ollama API key if authentication is enabled":r.includes("403")||r.includes("Forbidden")?"Access denied. Check your Ollama server permissions":r.includes("404")||r.includes("Not Found")?`Model '${this.model}' not found on Ollama server. Pull it first with: ollama pull ${this.model}`:r.includes("500")||r.includes("Internal Server Error")?"Ollama server error. Check server logs and try again":r.includes("overloaded")||r.includes("capacity")?"Ollama server is overloaded. Try again in a few minutes":null}generateCommitMessage$(){return D(this.generateMessage("commit")).pipe(L(e=>S(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 D(this.generateMessage("review")).pipe(L(e=>S(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:n,codeReviewPromptPath:s,logging:i,locale:c,generate:a,type:m,maxLength:d}=this.params.config,l={...Y,locale:c,maxLength:d,type:m,generate:a,systemPrompt:o,systemPromptPath:n,codeReviewPromptPath:s},p=e==="review"?te(l):ee(l);await this.checkIsAvailableOllama();const u=`Here is the diff: ${r}`,h=`Ollama_${this.model}`,g=`${this.host}/api/chat`,y=this.key?{Authorization:`${this.auth} ${this.key}`}:{};q(r,e,h,this.model,g,y,i),X(r,e,h,p,u,i);const w=await this.createChatCompletions(p,u,e);return e==="review"?this.sanitizeResponse(w):this.parseMessage(w,m,a)}async checkIsAvailableOllama(){const e=new je({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:n,numCtx:s,temperature:i,topP:c,timeout:a,maxTokens:m,logging:d}=this.params.config,l=n||!1,p=this.params.stagedDiff.diff,u=`Ollama_${this.model}`,h={model:this.model,messages:[{role:"system",content:e},{role:"user",content:r}],stream:l,keep_alive:a,options:{num_ctx:s,temperature:i,top_p:c,seed:ot(10,1e3),num_predict:m??-1}};oe(p,o,u,h,d);const g=Date.now();try{const y=await this.ollama.chat(h),w=Date.now()-g;let v="";if(l){if(y)for await(const E of y)v+=E.message.content}else v=y.message.content;return Q(p,o,u,{response:v,fullResponse:y},d),W(p,o,u,w,v,d),v}catch(y){throw G(p,o,u,y,d),y}}}class Bo extends Z{constructor(e){super(e),this.params=e;const r=this.params.keyName||"OPENAI_COMPATIBLE";this.colors=ya(r),this.serviceName=P.bgHex(this.colors.primary).hex(this.colors.secondary).bold(`[${rt(r)}]`),this.errorPrefix=P.red.bold(`[${rt(r)}]`),this.openAI=new kr({apiKey:this.params.config.key,baseURL:`${this.params.config.url}${this.params.config.path}`})}getServiceSpecificErrorMessage(e){const r=e.message||"";return r.includes("API key")||r.includes("api_key")?"Invalid API key. Check your OpenAI-compatible API key in configuration":r.includes("rate_limit")||r.includes("Rate limit")?"Rate limit exceeded. Wait a moment and try again, or check your service limits":r.includes("model")||r.includes("Model")?"Model not found or not accessible. Check if the model name is correct":r.includes("network")||r.includes("connection")?"Network error. Check your internet connection and API endpoint":r.includes("quota")||r.includes("usage")?"API quota exceeded. Check your usage limits":r.includes("403")||r.includes("Forbidden")?"Access denied. Your API key may not have permission for this model":r.includes("404")||r.includes("Not Found")?"Model or endpoint not found. Check your API configuration":r.includes("500")||r.includes("Internal Server Error")?"Server error. Try again later":r.includes("overloaded")||r.includes("capacity")?"Service is overloaded. Try again in a few minutes":null}generateCommitMessage$(){return D(this.generateMessage("commit")).pipe(L(e=>S(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 D(this.generateMessage("review")).pipe(L(e=>S(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:n,codeReviewPromptPath:s,logging:i,locale:c,temperature:a,generate:m,type:d,maxLength:l,timeout:p,stream:u=!1}=this.params.config,h=this.params.config.maxTokens,g={...Y,locale:c,maxLength:l,type:d,generate:m,systemPrompt:o,systemPromptPath:n,codeReviewPromptPath:s},y=e==="review"?te(g):ee(g),w=`Here is the diff: ${r}`,v=this.params.keyName||"OpenAI-Compatible",E=`${this.params.config.url}${this.params.config.path}`,x={Authorization:`Bearer ${this.params.config.key}`,"Content-Type":"application/json"};q(r,e,v,this.params.config.model,E,x,i),X(r,e,v,y,w,i);const $=er(this.params.config.model),C={messages:[{role:"system",content:y},{role:"user",content:w}],model:this.params.config.model,stream:u,...$?{max_completion_tokens:h,temperature:1}:{max_tokens:h,top_p:this.params.config.topP,temperature:a}};oe(r,e,v,C,i);const I=Date.now();try{const N=await this.openAI.chat.completions.create(C,{timeout:p});let _="";if(u&&N){const ln=N;for await(const mr of ln){const un=mr.choices?.[0]?.delta?.content||"",dn=mr.choices?.[0]?.delta?.reasoning_content||"",mn=`${un}${dn}`;_+=mn}}else _=N.choices?.[0]?.message.content||"";const ce=Date.now()-I;return Q(r,e,v,N,i),W(r,e,v,ce,_,i),e==="review"?this.sanitizeResponse(_):this.parseMessage(_,d,m)}catch(N){throw G(r,e,v,N,i),N}}}class Ho extends Z{constructor(e){super(e),this.params=e,this.colors={primary:"#74AA9C",secondary:"#FFF"},this.serviceName=P.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[ChatGPT]"),this.errorPrefix=P.red.bold("[ChatGPT]")}getServiceSpecificErrorMessage(e){const r=e.message||"";return r.includes("API key")?"Invalid API key. Check your OpenAI API key in configuration":r.includes("quota")?"API quota exceeded. Check your OpenAI usage limits":r.includes("500")?"OpenAI server error. Try again later":null}generateCommitMessage$(){return D(this.generateMessage("commit")).pipe(L(e=>S(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 D(this.generateMessage("review")).pipe(L(e=>S(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(n=>JSON.parse(n))):{error:{message:"Unknown error"}}}async generateMessage(e){const r=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:n,codeReviewPromptPath:s,temperature:i,logging:c,locale:a,generate:m,type:d,maxLength:l,proxy:p,maxTokens:u,timeout:h}=this.params.config,g={...Y,locale:a,maxLength:l,type:d,generate:m,systemPrompt:o,systemPromptPath:n,codeReviewPromptPath:s},y=e==="review"?te(g):ee(g),w=await mc("ChatGPT",this.params.config.url,this.params.config.path,this.params.config.key,this.params.config.model,r,h,u,i,this.params.config.topP,y,c,e,p);return nt(e==="review"?w.map(v=>this.sanitizeResponse(v)):w.map(v=>this.parseMessage(v,d,m)))}}class Uo extends Z{constructor(e){super(e),this.params=e,this.apiKey="",this.colors={primary:"#20808D",secondary:"#FFF"},this.serviceName=P.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[Perplexity]"),this.errorPrefix=P.red.bold("[Perplexity]"),this.apiKey=this.params.config.key}getServiceSpecificErrorMessage(e){const r=e.message||"";return r.includes("API key")||r.includes("api_key")?"Invalid API key. Check your Perplexity API key in configuration":r.includes("rate_limit")||r.includes("Rate limit")?"Rate limit exceeded. Wait a moment and try again, or upgrade your Perplexity plan":r.includes("model")||r.includes("Model")?"Model not found or not accessible. Check if the Perplexity model name is correct":r.includes("overloaded")||r.includes("capacity")?"Perplexity service is overloaded. Try again in a few minutes":r.includes("403")||r.includes("Forbidden")?"Access denied. Your API key may not have permission for this Perplexity model":r.includes("404")||r.includes("Not Found")?"Model or endpoint not found. Check your Perplexity model configuration":r.includes("500")||r.includes("Internal Server Error")?"Perplexity server error. Try again later":null}generateCommitMessage$(){return D(this.generateMessage("commit")).pipe(L(e=>S(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 D(this.generateMessage("review")).pipe(L(e=>S(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(n=>JSON.parse(n))):{error:{message:"Unknown error"}}}async generateMessage(e){const r=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:n,codeReviewPromptPath:s,logging:i,locale:c,generate:a,type:m,maxLength:d}=this.params.config,l={...Y,locale:c,maxLength:d,type:m,generate:a,systemPrompt:o,systemPromptPath:n,codeReviewPromptPath:s},p=e==="review"?te(l):ee(l),u=`Here is the diff: ${r}`,g=`${this.params.config.url||"https://api.perplexity.ai"}/chat/completions`,y={Authorization:`Bearer ${this.apiKey}`,"content-type":"application/json"};q(r,e,"Perplexity",this.params.config.model,g,y,i),X(r,e,"Perplexity",p,u,i);const w=await this.createChatCompletions(p,u,e);return this.parseMessage(w,m,a)}async createChatCompletions(e,r,o){const n=this.params.stagedDiff.diff,{logging:s}=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};oe(n,o,"Perplexity",i,s);const c=Date.now();try{const a=this.params.config.url||"https://api.perplexity.ai",m=await new je({method:"POST",baseURL:`${a}/chat/completions`,timeout:this.params.config.timeout}).setHeaders({Authorization:`Bearer ${this.apiKey}`,"content-type":"application/json"}).setBody(i).execute(),d=Date.now()-c,l=m.data;if(Q(n,o,"Perplexity",l,s),!l.choices||l.choices.length===0||!l.choices[0].message?.content)throw G(n,o,"Perplexity",{message:"No Content on response",result:l},s),new Error("No Content on response. Please open a Bug report");const u=l.choices[0].message.content;return W(n,o,"Perplexity",d,u,s),u}catch(a){throw G(n,o,"Perplexity",a,s),a}}}class ut{constructor(e,r){this.config=e,this.stagedDiff=r}createCommitMsgRequests$(e){return S(e).pipe(ze(r=>{const o=this.config[r],n=Array.isArray(o.model)?o.model:[o.model];return S(n).pipe(ze(s=>{if(o.compatible)return j.create(Bo,{config:{...o,url:o.url||"",path:o.path||"",model:s},stagedDiff:this.stagedDiff,keyName:s}).generateCommitMessage$();switch(r){case"OPENAI":return j.create(Ho,{config:{...this.config.OPENAI,model:s},stagedDiff:this.stagedDiff,keyName:s}).generateCommitMessage$();case"GEMINI":return j.create(Eo,{config:{...this.config.GEMINI,model:s},stagedDiff:this.stagedDiff,keyName:s}).generateCommitMessage$();case"ANTHROPIC":return j.create(bo,{config:{...this.config.ANTHROPIC,model:s},stagedDiff:this.stagedDiff,keyName:s}).generateCommitMessage$();case"HUGGINGFACE":return j.create(Fo,{config:{...this.config.HUGGINGFACE,model:s},stagedDiff:this.stagedDiff,keyName:s}).generateCommitMessage$();case"MISTRAL":return j.create(_o,{config:{...this.config.MISTRAL,model:s},stagedDiff:this.stagedDiff,keyName:s}).generateCommitMessage$();case"CODESTRAL":return j.create(Co,{config:{...this.config.CODESTRAL,model:s},stagedDiff:this.stagedDiff,keyName:s}).generateCommitMessage$();case"OLLAMA":return j.create(Go,{config:{...this.config.OLLAMA,model:s},keyName:s,stagedDiff:this.stagedDiff}).generateCommitMessage$();case"COHERE":return j.create(Po,{config:{...this.config.COHERE,model:s},stagedDiff:this.stagedDiff,keyName:s}).generateCommitMessage$();case"GROQ":return j.create(To,{config:{...this.config.GROQ,model:s},stagedDiff:this.stagedDiff,keyName:s}).generateCommitMessage$();case"PERPLEXITY":return j.create(Uo,{config:{...this.config.PERPLEXITY,model:s},stagedDiff:this.stagedDiff,keyName:s}).generateCommitMessage$();case"GITHUB_MODELS":return j.create(No,{config:{...this.config.GITHUB_MODELS,model:s},stagedDiff:this.stagedDiff,keyName:s}).generateCommitMessage$();case"DEEPSEEK":return j.create($o,{config:{...this.config.DEEPSEEK,model:s},stagedDiff:this.stagedDiff,keyName:s}).generateCommitMessage$();default:const i=P.red.bold(`[${r}]`);return Ae({name:i+" Invalid AI type",value:"Invalid AI type",isError:!0,disabled:!0})}}))}),R(r=>{const o=P.red.bold("[UNKNOWN]");return Ae({name:o+` ${r.message||""}`,value:"Unknown error",isError:!0,disabled:!0})}))}createCodeReviewRequests$(e){return S(e).pipe(ze(r=>{const o=this.config[r],n=Array.isArray(o.model)?o.model:[o.model];return S(n).pipe(ze(s=>{if(o.compatible)return j.create(Bo,{config:{...o,url:o.url||"",path:o.path||"",model:s},stagedDiff:this.stagedDiff,keyName:s}).generateCodeReview$();switch(r){case"OPENAI":return j.create(Ho,{config:{...this.config.OPENAI,model:s},stagedDiff:this.stagedDiff,keyName:s}).generateCodeReview$();case"GEMINI":return j.create(Eo,{config:{...this.config.GEMINI,model:s},stagedDiff:this.stagedDiff,keyName:s}).generateCodeReview$();case"ANTHROPIC":return j.create(bo,{config:{...this.config.ANTHROPIC,model:s},stagedDiff:this.stagedDiff,keyName:s}).generateCodeReview$();case"HUGGINGFACE":return j.create(Fo,{config:{...this.config.HUGGINGFACE,model:s},stagedDiff:this.stagedDiff,keyName:s}).generateCodeReview$();case"MISTRAL":return j.create(_o,{config:{...this.config.MISTRAL,model:s},stagedDiff:this.stagedDiff,keyName:s}).generateCodeReview$();case"CODESTRAL":return j.create(Co,{config:{...this.config.CODESTRAL,model:s},stagedDiff:this.stagedDiff,keyName:s}).generateCodeReview$();case"OLLAMA":return j.create(Go,{config:{...this.config.OLLAMA,model:s},keyName:s,stagedDiff:this.stagedDiff}).generateCodeReview$();case"COHERE":return j.create(Po,{config:{...this.config.COHERE,model:s},stagedDiff:this.stagedDiff,keyName:s}).generateCodeReview$();case"GROQ":return j.create(To,{config:{...this.config.GROQ,model:s},stagedDiff:this.stagedDiff,keyName:s}).generateCodeReview$();case"PERPLEXITY":return j.create(Uo,{config:{...this.config.PERPLEXITY,model:s},stagedDiff:this.stagedDiff,keyName:s}).generateCodeReview$();case"GITHUB_MODELS":return j.create(No,{config:{...this.config.GITHUB_MODELS,model:s},stagedDiff:this.stagedDiff,keyName:s}).generateCodeReview$();case"DEEPSEEK":return j.create($o,{config:{...this.config.DEEPSEEK,model:s},stagedDiff:this.stagedDiff,keyName:s}).generateCodeReview$();default:const i=P.red.bold(`[${r}]`);return Ae({name:i+" Invalid AI type",value:"Invalid AI type",isError:!0,disabled:!0})}}))}),R(r=>{const o=P.red.bold("[UNKNOWN]");return Ae({name:o+` ${r.message||""}`,value:"Unknown error",isError:!0,disabled:!0})}))}}class zo{getDetectedMessage(e){return`Detected ${e.files.length.toLocaleString()} changed file${e.files.length>1?"s":""} (${e.diff.length.toLocaleString()} characters)`}getDetectedFiles(e){return`Detected ${e.length.toLocaleString()} changed file${e.length>1?"s":""}`}}class fc extends zo{constructor(){super(...arguments),this.name="git",this.excludeFromDiff=e=>`:(exclude)${e}`,this.filesToExclude=["package-lock.json","pnpm-lock.yaml","*.lock","*.lockb"].map(this.excludeFromDiff)}async assertRepo(){try{const{stdout:e}=await F("git",["rev-parse","--show-toplevel"],{reject:!0});return e.trim()}catch(e){const r=e;if(r.code==="ENOENT")throw new b(`Git command not found!
|
|
95
95
|
|
|
96
96
|
Please install Git first: https://git-scm.com/downloads`);if(r.stderr){if(r.stderr.includes("not a git repository"))throw new b(`Not in a Git repository!
|
|
97
97
|
|
|
@@ -99,18 +99,18 @@ Initialize with: git init
|
|
|
99
99
|
Or navigate to an existing Git repository.`);if(r.stderr.includes("permission denied"))throw new b(`Git permission denied: ${r.stderr.trim()}
|
|
100
100
|
|
|
101
101
|
Check file permissions and repository access.`)}throw new b(`Failed to verify Git repository: ${r.message||"Unknown error"}`)}}async getStagedDiff(e,r){const o=["diff","--cached","--diff-algorithm=minimal"],{stdout:n}=await F("git",[...o,"--name-only",...this.filesToExclude,...e?e.map(this.excludeFromDiff):[],...r?r.map(this.excludeFromDiff):[]]);if(!n)return null;const{stdout:s}=await F("git",[...o,...this.filesToExclude,...e?e.map(this.excludeFromDiff):[],...r?r.map(this.excludeFromDiff):[]]),i=n.split(`
|
|
102
|
-
`).filter(Boolean),{stdout:c}=await F("git",[...o,"--numstat",...e?e.map(this.excludeFromDiff):[],...r?r.map(this.excludeFromDiff):[]]),a=[],
|
|
103
|
-
`).filter(Boolean);for(const
|
|
102
|
+
`).filter(Boolean),{stdout:c}=await F("git",[...o,"--numstat",...e?e.map(this.excludeFromDiff):[],...r?r.map(this.excludeFromDiff):[]]),a=[],m=c.split(`
|
|
103
|
+
`).filter(Boolean);for(const p of m){const u=p.split(" ");u[0]==="-"&&u[1]==="-"&&u[2]&&a.push(u[2])}let d=s;if(a.length>0){s.trim()||(d=""),d+=`
|
|
104
104
|
|
|
105
105
|
--- Binary Files Changed ---
|
|
106
|
-
`;for(const
|
|
107
|
-
`}}const l=[...new Set([...i,...a])];return{files:l,diff:
|
|
108
|
-
`).filter(Boolean);for(const
|
|
106
|
+
`;for(const p of a){const{stdout:u}=await F("git",["status","--porcelain",p]),h=u.substring(0,2).trim();d+=`Binary file ${p} ${h==="A"?"added":h==="M"?"modified":h==="D"?"deleted":"changed"}
|
|
107
|
+
`}}const l=[...new Set([...i,...a])];return{files:l,diff:d||`Files changed: ${l.join(", ")}`}}async getCommitDiff(e,r,o){const n=["diff-tree","-r","--no-commit-id","--name-only",e],{stdout:s}=await F("git",[...n,...this.filesToExclude,...r?r.map(this.excludeFromDiff):[],...o?o.map(this.excludeFromDiff):[]]);if(!s)return null;const{stdout:i}=await F("git",["show",e,"--",...this.filesToExclude,...r?r.map(this.excludeFromDiff):[],...o?o.map(this.excludeFromDiff):[]]),{stdout:c}=await F("git",["diff-tree","-r","--numstat",e,...r?r.map(this.excludeFromDiff):[],...o?o.map(this.excludeFromDiff):[]]),a=[],m=c.split(`
|
|
108
|
+
`).filter(Boolean);for(const p of m){const u=p.split(" ");u[0]==="-"&&u[1]==="-"&&u[2]&&a.push(u[2])}let d=i;if(a.length>0){i.trim()||(d=""),d+=`
|
|
109
109
|
|
|
110
110
|
--- Binary Files Changed ---
|
|
111
|
-
`;for(const
|
|
111
|
+
`;for(const p of a)d+=`Binary file ${p} changed
|
|
112
112
|
`}const l=[...new Set([...s.split(`
|
|
113
|
-
`).filter(Boolean),...a])];return{files:l,diff:
|
|
113
|
+
`).filter(Boolean),...a])];return{files:l,diff:d||`Files changed: ${l.join(", ")}`}}async commit(e,r=[]){try{await F("git",["commit","-m",e,...r],{stdio:"inherit"})}catch(o){const n=o;throw n.stderr?n.stderr.includes("nothing to commit")?new b(`Nothing to commit.
|
|
114
114
|
|
|
115
115
|
Stage your changes with: git add <files>
|
|
116
116
|
Or use the --all flag to stage all changes.`):n.stderr.includes("Please enter the commit message")?new b(`Commit message cannot be empty.
|
|
@@ -127,27 +127,27 @@ Please install Jujutsu:
|
|
|
127
127
|
- macOS: brew install jj
|
|
128
128
|
- Linux: cargo install jj-cli
|
|
129
129
|
- Windows: cargo install jj-cli
|
|
130
|
-
- See: https://github.com/martinvonz/jj#installation`):new b(`Failed to execute jj command: ${r.message}`)}try{const{stdout:e,stderr:r}=await F("jj",["workspace","root"],{reject:!0}),o=e.trim();if(!o)throw new b("jj workspace root returned empty path");const n=
|
|
130
|
+
- See: https://github.com/martinvonz/jj#installation`):new b(`Failed to execute jj command: ${r.message}`)}try{const{stdout:e,stderr:r}=await F("jj",["workspace","root"],{reject:!0}),o=e.trim();if(!o)throw new b("jj workspace root returned empty path");const n=A.join(o,".jj");if(!H.existsSync(n))throw new b(`Jujutsu repository directory not found at ${n}
|
|
131
131
|
|
|
132
132
|
Initialize a jj repository with: jj init`);return o}catch(e){if(e instanceof b)throw e;const r=e;throw r.stderr?r.stderr.includes("not in a jj repo")?new b(`Not in a Jujutsu repository!
|
|
133
133
|
|
|
134
134
|
Initialize with: jj init
|
|
135
135
|
Or navigate to an existing jj repository.`):r.stderr.includes("No workspace found")?new b(`No Jujutsu workspace found!
|
|
136
136
|
|
|
137
|
-
This may be a bare repository. Navigate to a workspace directory.`):new b(`Jujutsu error: ${r.stderr.trim()}`):new b(`Failed to verify Jujutsu repository: ${r.message||"Unknown error"}`)}}async getStagedDiff(e,r){try{const{stdout:o}=await F("jj",["status","--no-pager"]);if(process.env.DEBUG&&(console.log("jj status output:",JSON.stringify(o)),console.log("excludeFiles:",e),console.log("exclude:",r)),o.includes("No changes.")||o.includes("The working copy is clean"))return null;const n=this.filesToExclude.map(this.excludeFromDiff),s=[...e?e.map(this.excludeFromDiff):[],...r?r.map(this.excludeFromDiff):[]],i=[...n,...s];let c="all()";i.length>0&&(c=`all() & ${i.join(" & ")}`);const a=["diff","--name-only"],
|
|
138
|
-
`).filter(Boolean),h=[],g=
|
|
137
|
+
This may be a bare repository. Navigate to a workspace directory.`):new b(`Jujutsu error: ${r.stderr.trim()}`):new b(`Failed to verify Jujutsu repository: ${r.message||"Unknown error"}`)}}async getStagedDiff(e,r){try{const{stdout:o}=await F("jj",["status","--no-pager"]);if(process.env.DEBUG&&(console.log("jj status output:",JSON.stringify(o)),console.log("excludeFiles:",e),console.log("exclude:",r)),o.includes("No changes.")||o.includes("The working copy is clean"))return null;const n=this.filesToExclude.map(this.excludeFromDiff),s=[...e?e.map(this.excludeFromDiff):[],...r?r.map(this.excludeFromDiff):[]],i=[...n,...s];let c="all()";i.length>0&&(c=`all() & ${i.join(" & ")}`);const a=["diff","--name-only"],m=["diff","--git"];i.length>0&&(a.push(c),m.push(c)),process.env.DEBUG&&(console.log("jj diff command with fileset:",a),console.log("fileset expression:",c));const{stdout:d}=await F("jj",a);if(process.env.DEBUG&&console.log("jj diff --name-only output:",JSON.stringify(d)),!d.trim())return null;const{stdout:l}=await F("jj",m),{stdout:p}=await F("jj",["status","--no-pager"]),u=d.split(`
|
|
138
|
+
`).filter(Boolean),h=[],g=p.split(`
|
|
139
139
|
`);for(const v of g)if(v.includes("(binary)")||v.includes("Binary file")){const E=v.match(/([^\s]+)\s*\(binary\)/);E&&E[1]&&h.push(E[1])}let y=l;if(h.length>0){y+=`
|
|
140
140
|
|
|
141
141
|
--- Binary Files Changed ---
|
|
142
142
|
`;for(const v of h)y+=`Binary file ${v} changed
|
|
143
|
-
`}const w=[...new Set([...
|
|
143
|
+
`}const w=[...new Set([...u,...h])];return{files:w,diff:y||`Files changed: ${w.join(", ")}`}}catch(o){const n=o;if(n.stderr){if(n.stderr.includes("No changes to show"))return null;if(n.stderr.includes("Operation not allowed"))throw new b(`Jujutsu diff failed: ${n.stderr.trim()}
|
|
144
144
|
|
|
145
145
|
Try: jj status --no-pager`);if(n.stderr.includes("Invalid revision"))throw new b(`Jujutsu revision error: ${n.stderr.trim()}
|
|
146
146
|
|
|
147
147
|
Check if you're in a valid workspace.`)}if(n.exitCode===1&&!n.stderr)return null;if(process.env.DEBUG)throw new b(`Jujutsu diff failed: ${n.message}
|
|
148
148
|
stderr: ${n.stderr}
|
|
149
|
-
exitCode: ${n.exitCode}`);return null}}async getCommitDiff(e,r,o){const n=[...r?r.map(this.excludeFromDiff):[],...o?o.map(this.excludeFromDiff):[]];try{const s=["diff","--name-only","--revision",e],i=["diff","--git","--revision",e];if(n.length>0){const
|
|
150
|
-
`).filter(Boolean);return{files:
|
|
149
|
+
exitCode: ${n.exitCode}`);return null}}async getCommitDiff(e,r,o){const n=[...r?r.map(this.excludeFromDiff):[],...o?o.map(this.excludeFromDiff):[]];try{const s=["diff","--name-only","--revision",e],i=["diff","--git","--revision",e];if(n.length>0){const d=`all() & ${n.join(" & ")}`;s.push(d),i.push(d),process.env.DEBUG&&console.log("jj getCommitDiff fileset expression:",d)}const{stdout:c}=await F("jj",s);if(!c.trim())return null;const{stdout:a}=await F("jj",i),m=c.split(`
|
|
150
|
+
`).filter(Boolean);return{files:m,diff:a||`Files changed: ${m.join(", ")}`}}catch(s){if(process.env.DEBUG){const i=s;console.log("jj getCommitDiff error:",i.message,i.stderr)}return null}}async commit(e,r=[]){try{await F("jj",["describe","-m",e,...r],{stdio:"inherit"}),await F("jj",["new"],{stdio:"inherit"})}catch(o){const n=o;throw n.stderr?n.stderr.includes("Empty commit message")?new b(`Commit message cannot be empty.
|
|
151
151
|
|
|
152
152
|
Provide a meaningful commit message.`):n.stderr.includes("No changes to commit")?new b(`No changes to commit.
|
|
153
153
|
|
|
@@ -170,47 +170,47 @@ Solutions:
|
|
|
170
170
|
\u2022 Initialize a Jujutsu repository: jj init
|
|
171
171
|
\u2022 Navigate to an existing Git or Jujutsu repository
|
|
172
172
|
\u2022 Set JJ="true" environment variable to force Jujutsu detection
|
|
173
|
-
\u2022 Set jujutsu=true in config file to prefer Jujutsu`)}throw new b("Unexpected error during VCS detection")}async function ke(){return rr||(rr=await pc()),rr}const or=async()=>(await ke()).assertRepo(),nr=async(t,e)=>(await ke()).getStagedDiff(t,e),hc=async(t,e,r)=>{const o=await ke();if(!o.getCommitDiff)throw new b(`Commit diff not supported for ${o.name}`);return o.getCommitDiff(t,e,r)},gc=async()=>(await ke()).getCommentChar(),yc=t=>`Detected ${t.files.length.toLocaleString()} changed file${t.files.length>1?"s":""} (${t.diff.length.toLocaleString()} characters)`,wc=async()=>(await ke()).name,vc=async(t,e)=>{await(await ke()).commit(t,e||[])};class ne{constructor(){this.title="aicommit2"}printTitle(){console.log(Bn.textSync(this.title,{font:"Small"}))}showLoader(e){if(this.loader){this.loader.text=e;return}this.loader=Ar(e).start()}stopLoader(){this.loader?.stop(),this.loader=void 0}displaySpinner(e){return Ar(e).start()}stopSpinner(e){e.stop(),e.clear()}printStagedFiles(e){console.log(
|
|
173
|
+
\u2022 Set jujutsu=true in config file to prefer Jujutsu`)}throw new b("Unexpected error during VCS detection")}async function ke(){return rr||(rr=await pc()),rr}const or=async()=>(await ke()).assertRepo(),nr=async(t,e)=>(await ke()).getStagedDiff(t,e),hc=async(t,e,r)=>{const o=await ke();if(!o.getCommitDiff)throw new b(`Commit diff not supported for ${o.name}`);return o.getCommitDiff(t,e,r)},gc=async()=>(await ke()).getCommentChar(),yc=t=>`Detected ${t.files.length.toLocaleString()} changed file${t.files.length>1?"s":""} (${t.diff.length.toLocaleString()} characters)`,wc=async()=>(await ke()).name,vc=async(t,e)=>{await(await ke()).commit(t,e||[])};class ne{constructor(){this.title="aicommit2"}printTitle(){console.log(Bn.textSync(this.title,{font:"Small"}))}showLoader(e){if(this.loader){this.loader.text=e;return}this.loader=Ar(e).start()}stopLoader(){this.loader?.stop(),this.loader=void 0}displaySpinner(e){return Ar(e).start()}stopSpinner(e){e.stop(),e.clear()}printStagedFiles(e){console.log(P.bold.green("\u2714 ")+P.bold(`${yc(e)}:`)),console.log(`${e.files.map(r=>` ${r}`).join(`
|
|
174
174
|
`)}
|
|
175
175
|
`)}printAnalyzed(){console.log(`
|
|
176
|
-
${
|
|
177
|
-
${
|
|
178
|
-
${
|
|
179
|
-
${
|
|
180
|
-
${
|
|
181
|
-
${
|
|
182
|
-
${
|
|
183
|
-
${
|
|
184
|
-
${
|
|
185
|
-
${
|
|
186
|
-
${
|
|
187
|
-
`)}i&&(cs("copy-paste").copy(
|
|
188
|
-
${
|
|
189
|
-
`),
|
|
176
|
+
${P.bold.green("\u2714")} ${P.bold("Changes analyzed")}`)}printCommitted(){console.log(`
|
|
177
|
+
${P.bold.green("\u2714")} ${P.bold("Successfully committed!")}`)}printCopied(){console.log(`
|
|
178
|
+
${P.bold.green("\u2714")} ${P.bold("Successfully copied! Press 'Ctrl + V' to paste")}`)}printSavedCommitMessage(){console.log(`
|
|
179
|
+
${P.bold.green("\u2714")} ${P.bold("Saved commit message")}`)}printCancelledCommit(){console.log(`
|
|
180
|
+
${P.bold.yellow("\u26A0")} ${P.yellow("Commit cancelled")}`)}printError(e){console.log(`
|
|
181
|
+
${P.bold.red("\u2716")} ${P.red(`${e}`)}`)}printWarning(e){console.log(`
|
|
182
|
+
${P.bold.yellow("\u26A0")} ${P.red(`${e}`)}`)}printSuccess(e){console.log(`
|
|
183
|
+
${P.bold.green("\u2714")} ${P.green(`${e}`)}`)}printInfo(e){console.log(`
|
|
184
|
+
${P.bold.blue("\u2139")} ${P.blue(`${e}`)}`)}printSetupGitEvent(e){console.log(`
|
|
185
|
+
${P.bold.green("\u2714")} ${P.bold(`Git ${e} hook has been set up`)}`)}moveCursorUp(){const e=We.createInterface({input:process.stdin,output:process.stdout});We.moveCursor(process.stdout,0,-1),e.close()}moveCursorDown(){const e=We.createInterface({input:process.stdin,output:process.stdout});We.moveCursor(process.stdout,0,2),e.close()}print(e){console.log(e)}}const bc={isLoading:!1,startOption:{text:"AI is analyzing your changes"}},Ko={isLoading:!1,startOption:{text:"AI is performing a code review"}},sr="No commit messages were generated",Jo="No code reviews were generated",ir={type:"reactiveListPrompt",name:"aicommit2Prompt",message:"Pick a commit message to use: ",emptyMessage:`\u26A0 ${sr}`,loop:!1,descPageSize:15,showDescription:!0,pickKey:"short",isDescriptionDim:!0,stopMessage:"Changes analyzed"};class ar{constructor(e){this.choices$=new vr([]),this.destroyed$=new kn(1),this.stopMessage="Changes analyzed",this.inquirerInstance=null,this.loader$=new vr(e)}initPrompt(e=ir){return this.stopMessage=e.stopMessage,Ue.registerPrompt("reactiveListPrompt",Hn),this.inquirerInstance=Ue.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(fa))}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:sr,stopOption:{doneFrame:"\u26A0",color:"yellow"}})}stopLoaderOnSuccess(){this.loader$.next({isLoading:!1,message:this.stopMessage})}logEmptyCommitMessage(){console.log(`${P.bold.yellow("\u26A0")} ${P.yellow(`${sr}`)}`)}get currentChoices(){return this.choices$.getValue().map(e=>e)}}const V=new ne;var Cc=async(t,e,r,o,n,s,i,c,a,m,d,l,p)=>(async()=>{V.printTitle(),await or(),o&&await wc()==="git"&&await F("git",["add","--update"]);const u=await de({locale:t?.toString(),generate:e?.toString(),type:n?.toString(),systemPrompt:c?.toString(),includeBody:a?.toString(),disableLowerCase:l?.toString()},p);(a===!0||u.includeBody===!0)&&Object.keys(u).forEach(C=>{typeof u[C]=="object"&&u[C]!==null&&"includeBody"in u[C]&&(u[C].includeBody=!0)}),l&&Object.keys(u).forEach(C=>{typeof u[C]=="object"&&u[C]!==null&&"disableLowerCase"in u[C]&&(u[C].disableLowerCase=!0)}),await vo(u);const g=V.displaySpinner("Detecting staged files"),y=await nr(r,u.exclude);if(g.stop(),!y)throw new b("No staged changes found. Stage your changes manually, or automatically stage all changes with the `--all` flag.");V.printStagedFiles(y);const w=Wo(u,"commit");if(w.length===0)throw new b("Please set at least one API key via the `aicommit2 config set` command");const v=new ut(u,y),E=Wo(u,"review");E.length>0&&await Pc(v,E);let x=await $c(v,w,m);if(d){if(V.printInfo("Opening editor to modify commit message..."),x=await Ec(x),!x.trim())throw new b("Commit message cannot be empty");V.printSuccess("Commit message edited successfully!"),console.log(`
|
|
186
|
+
${x}
|
|
187
|
+
`)}i&&(cs("copy-paste").copy(x),V.printCopied(),process.exit()),(s||m&&w.length===1)&&(await Yo(x,p),process.exit());const{confirmationPrompt:$}=await Ue.prompt([{type:"confirm",name:"confirmationPrompt",message:"Use selected message?",default:!0}]);$?await Yo(x,p):V.printCancelledCommit(),process.exit()})().catch(u=>{V.printError(u.message),ae(u),process.exit(1)});function Wo(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 n=t.codeReview||o.codeReview;return r==="OLLAMA"?!!o&&!!o.model&&o.model.length>0&&n:r==="HUGGINGFACE"?!!o&&!!o.cookie&&n:!!o.key&&o.key.length>0&&n}}).map(([r])=>r)}async function Pc(t,e){const r=new ar(Ko),o=r.initPrompt({...ir,name:"codeReviewPrompt",message:"Please check code reviews: ",emptyMessage:`\u26A0 ${Jo}`,isDescriptionDim:!1,stopMessage:"Code review completed",descPageSize:20});r.startLoader();const n=t.createCodeReviewRequests$(e).subscribe(a=>r.refreshChoices(a),()=>{},()=>r.checkErrorOnChoices());if(!(await o).codeReviewPrompt?.value)throw new b("An error occurred! No selected code review");n.unsubscribe(),r.completeSubject(),V.moveCursorUp();const{continuePrompt:c}=await Ue.prompt([{type:"confirm",name:"continuePrompt",message:"Will you continue without changing the code?",default:!0}]);c||(V.printCancelledCommit(),process.exit())}async function $c(t,e,r){const o=new ar(bc);if(r&&e.length===1){const a=[];o.startLoader();const m=t.createCommitMsgRequests$(e).subscribe(l=>{a.push(l),o.refreshChoices(l)},()=>{},()=>o.checkErrorOnChoices(!1));await new Promise(l=>{m.add(()=>l())}),o.clearLoader(),o.completeSubject(),V.moveCursorUp();const d=a.find(l=>l.value&&!l.isError&&!l.disabled);if(!d||!d.value)throw new b("No valid commit message was generated");return V.print(`
|
|
188
|
+
${d.name}
|
|
189
|
+
`),d.value}const n=o.initPrompt();o.startLoader();const s=t.createCommitMsgRequests$(e).subscribe(a=>o.refreshChoices(a),()=>{},()=>o.checkErrorOnChoices()),i=await n;s.unsubscribe(),o.completeSubject(),V.moveCursorUp();const c=i.aicommit2Prompt?.value;if(!c)throw new b("An error occurred! No selected message");return c}async function Ec(t){const e=process.env.VISUAL||process.env.EDITOR||(process.platform==="win32"?"notepad":"vi"),r=A.join(xe.tmpdir(),`aicommit2-${Date.now()}.txt`);try{H.writeFileSync(r,t,"utf8"),await F(e,[r],{stdio:"inherit"});const o=H.readFileSync(r,"utf8").trim();if(H.unlinkSync(r),!o)throw new b("Commit cancelled - empty message");return o}catch(o){throw H.existsSync(r)&&H.unlinkSync(r),o instanceof b?o:o&&typeof o=="object"&&"exitCode"in o&&o.exitCode!==0?new b("Commit cancelled"):process.env.VISUAL||process.env.EDITOR?new b(`Failed to open editor "${e}". Please check that the editor command is valid and available.`):new b(`Failed to open editor "${e}". Please set your EDITOR or VISUAL environment variable to a valid editor command.`)}}async function Yo(t,e){await vc(t,e),V.printCommitted()}var kc=se({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:[se({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"]}}),se({name:"get",parameters:["[<key>","[<key> ...]]"],help:{description:"Retrieve configuration values for specified AI provider.",examples:["aic2 config get OPENAI","aic2 config get ANTHROPIC"]}}),se({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"']}}),se({name:"list",parameters:[],help:{description:"Display all configuration keys and their values.",examples:["aic2 config list"]}}),se({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"]}}),se({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 n=await de({},[]);if(r.length===0){console.log(n);return}for(const s of r){const i=s.split(".");let c=n,a=!0;for(const m of i)if(_t(c,m))c=c[m];else{a=!1;break}a?console.log(s,c):console.log(`${s} not found`)}return}if(e==="set"){await Gt(r.map(n=>{const s=n.indexOf("=");if(s===-1)throw new b("Invalid format. Use: key=value");const i=n.slice(0,s),c=n.slice(s+1);return[i,c]}));return}if(e==="add"){await ka(r.map(n=>{const s=n.indexOf("=");if(s===-1)throw new b("Invalid format. Use: key=value");const i=n.slice(0,s),c=n.slice(s+1);return[i,c]}));return}if(e==="list"){await xa();return}if(e==="del"){if(!o)throw new b("Please provide the config name to delete.");const n=await Le(),s=o.split(".");if(s.length===2){const[i,c]=s;if(n[i]&&typeof n[i]=="object"&&_t(n[i],c)){delete n[i][c],Object.keys(n[i]).length===0&&delete n[i];const a=await Ce();await O.writeFile(a,ve.stringify(n),"utf8"),console.log(`Successfully deleted config: ${o}`);const m=await O.readFile(a,"utf8");console.log("--- Updated Config Content ---"),console.log(m),console.log("----------------------------")}else throw new b(`Config not found: ${o}`)}else if(s.length===1){const i=s[0];if(_t(n,i)){delete n[i];const c=await Ce();await O.writeFile(c,ve.stringify(n),"utf8"),console.log(`Successfully deleted config: ${o}`);const a=await O.readFile(c,"utf8");console.log("--- Updated Config Content ---"),console.log(a),console.log("----------------------------")}else throw new b(`Config not found: ${o}`)}else throw new b(`Invalid config name format: ${o}`);return}if(e==="path"){await Aa();return}throw new b(`Invalid mode: ${e}`)})().catch(e=>{new ne().printError(e.message),ae(e),process.exit(1)})}),xc=se({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 ne;if(t.flags.token){try{await Ac(t.flags.token,e)}catch(r){throw new b(`Token authentication failed: ${r.message}`)}return}try{await Sc(e)}catch(r){throw new b(`Browser authentication failed: ${r.message}`)}})().catch(e=>{new ne().printError(e.message),ae(e),process.exit(1)})});async function Ac(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 Gt([["GITHUB_MODELS.key",t]]),e.printSuccess(`Successfully authenticated as ${o.login}`)}catch(r){throw new Error(`Token validation failed: ${r.message}`)}}async function Sc(t){t.printInfo("Starting GitHub browser authentication for GitHub Models...");try{try{He("gh --version",{stdio:"ignore"})}catch{throw new Error("GitHub CLI (gh) is not installed. Please install it first: https://cli.github.com/")}try{He("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{He("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=He("gh auth token",{encoding:"utf8"}).trim();e&&(await Gt([["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 Vo="prepare-commit-msg",qo=`.git/hooks/${Vo}`,dt=jn(new URL("cli.mjs",import.meta.url)),Ic=process.argv[1].replace(/\\/g,"/").endsWith(`/${qo}`),Xo=process.platform==="win32",Qo=`
|
|
190
190
|
#!/usr/bin/env node
|
|
191
191
|
import(${JSON.stringify(Nn(dt))})
|
|
192
|
-
`.trim();var Mc=se({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 or(),{installUninstall:r}=t._,o=
|
|
193
|
-
`);const r=await Promise.all(e.map(async o=>{const n=le.join(re,o),s=await Un(n);return{name:o,size:Oc(s.size),modified:Lc(s.mtime)}}));r.sort((o,n)=>new Date(n.modified).getTime()-new Date(o.modified).getTime()),r.forEach((o,n)=>{console.log(`${n===0?"\u{1F4C4}":" "} ${
|
|
194
|
-
${
|
|
195
|
-
`,
|
|
196
|
-
`,
|
|
197
|
-
`,
|
|
198
|
-
`,
|
|
199
|
-
`,
|
|
200
|
-
`):(
|
|
201
|
-
`,
|
|
202
|
-
`,
|
|
203
|
-
`),
|
|
204
|
-
`),
|
|
192
|
+
`.trim();var Mc=se({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 or(),{installUninstall:r}=t._,o=A.join(e,qo),n=await lo(o);if(r==="install"){if(n){if(await O.realpath(o).catch(()=>{})===dt){console.warn("The hook is already installed");return}throw new b(`A different ${Vo} hook seems to be installed. Please remove it before installing aicommit2.`)}await O.mkdir(A.dirname(o),{recursive:!0}),Xo?await O.writeFile(o,Qo):(await O.symlink(dt,o,"file"),await O.chmod(o,493)),console.log(`${P.green("\u2714")} Hook installed`);return}if(r==="uninstall"){if(!n){console.warn("Hook is not installed");return}if(Xo){if(await O.readFile(o,"utf8")!==Qo){console.warn("Hook is not installed");return}}else if(await O.realpath(o)!==dt){console.warn("Hook is not installed");return}await O.rm(o),console.log(`${P.green("\u2714")} Hook uninstalled`);return}throw new b(`Invalid mode: ${r}`)})().catch(e=>{console.error(`${P.red("\u2716")} ${e.message}`),ae(e),process.exit(1)})});const Rc=En(yn),Oc=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]},Lc=t=>t.toLocaleDateString()+" "+t.toLocaleTimeString(),Dc=async t=>{try{const e=await Sr(re);if(e.length===0){console.log(`${P.yellow("No log files found.")}`);return}console.log(`${P.blue("Log files in")} ${re}:
|
|
193
|
+
`);const r=await Promise.all(e.map(async o=>{const n=le.join(re,o),s=await Un(n);return{name:o,size:Oc(s.size),modified:Lc(s.mtime)}}));r.sort((o,n)=>new Date(n.modified).getTime()-new Date(o.modified).getTime()),r.forEach((o,n)=>{console.log(`${n===0?"\u{1F4C4}":" "} ${P.cyan(o.name)} ${P.gray(`(${o.size}, ${o.modified})`)}`)}),console.log(`
|
|
194
|
+
${P.green("Total:")} ${e.length} file${e.length!==1?"s":""}`)}catch(e){if(e.code==="ENOENT")console.log(`${P.yellow("Logs directory does not exist yet.")}`);else throw e}},jc=async t=>{try{await Sr(re);const e=process.platform;let r;switch(e){case"darwin":r=`open "${re}"`;break;case"win32":r=`start "" "${re}"`;break;default:r=`xdg-open "${re}"`;break}await Rc(r),console.log(`${P.green("\u2714")} Opened logs directory in file manager`)}catch(e){e.code==="ENOENT"?console.log(`${P.yellow("Logs directory does not exist yet.")}`):t.printError(`Failed to open logs directory: ${e.message}`)}},Nc=async t=>{try{await zn(re,{recursive:!0,force:!0}),console.log(`${P.green("\u2714")} All log files removed!`)}catch(e){t.printError(`Failed to remove log files: ${e.message}`)}};var Tc=se({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 ne;switch(e){case"list":await Dc();break;case"path":console.log(`${P.blue("Logs directory:")} ${re}`);break;case"open":await jc(r);break;case"removeAll":await Nc(r);break;default:throw new b(`Invalid action: ${e}. Use 'list', 'path', 'open', or 'removeAll'`)}})().catch(e=>{new ne().printError(e.message),ae(e),process.exit(1)})});const Fc=process.argv.slice(2).filter(t=>!t.startsWith("--pre-commit")),[mt,Zo]=Fc;var _c=()=>(async()=>{if(!mt)throw new b('Commit message file path is missing. This file should be called from the "pre-commit framework"');if(Zo){console.log(`Skipping aicommit2 message generation for ${Zo} commit`);return}const t=await nr();if(!t)return;const e=new ne;e.printTitle();const r=await de({});if(r.systemPromptPath)try{await O.readFile(A.resolve(r.systemPromptPath),"utf-8")}catch{throw new b(`Error reading system prompt file: ${r.systemPromptPath}`)}const o=Object.entries(r).filter(([u])=>be.includes(u)).map(([u,h])=>[u,h]).filter(([u,h])=>!h.disabled).filter(([u,h])=>u==="OLLAMA"?!!h&&!!h.model&&h.model.length>0:u==="HUGGINGFACE"?!!h&&!!h.cookie:!!h.key&&h.key.length>0).map(([u])=>u);if(o.length===0)throw new b("Please set at least one API key via the `aicommit2 config set` command");const s=new ut(r,t);let i;try{i=await br(s.createCommitMsgRequests$(o).pipe(Cr(u=>!u.isError),M(u=>u.value),Pr()))}finally{e.printAnalyzed()}const a=await O.readFile(mt,"utf8")!=="",m=i.length>1;let d="";a&&(d=`# \u{1F916} Generated by aicommit2 (https://github.com/tak-bro/aicommit2)
|
|
195
|
+
`,d+=`# ----------------------------------------
|
|
196
|
+
`,d+=`# How to use:
|
|
197
|
+
`,m?(d+=`# 1. Remove the "#" from your chosen message
|
|
198
|
+
`,d+=`# 2. Edit the message if needed
|
|
199
|
+
`,d+=`# 3. Save and close the editor
|
|
200
|
+
`):(d+=`# 1. The message below will be used
|
|
201
|
+
`,d+=`# 2. Edit the message if needed
|
|
202
|
+
`,d+=`# 3. Save and close the editor
|
|
203
|
+
`),d+=`# ----------------------------------------
|
|
204
|
+
`),m?(a&&(d+=`
|
|
205
205
|
# \u{1F4DD} Choose one of these messages:
|
|
206
|
-
`),
|
|
207
|
-
${i.map(
|
|
208
|
-
`)}`):(a&&(
|
|
206
|
+
`),d+=`
|
|
207
|
+
${i.map(u=>`# ${u}`).join(`
|
|
208
|
+
`)}`):(a&&(d+=`
|
|
209
209
|
# \u{1F4DD} Generated commit message:
|
|
210
|
-
`),
|
|
210
|
+
`),d+=`
|
|
211
211
|
${i[0]}
|
|
212
|
-
`);const l=await
|
|
213
|
-
`+l;await
|
|
212
|
+
`);const l=await O.readFile(mt,"utf8"),p=d+`
|
|
213
|
+
`+l;await O.writeFile(mt,p),e.printSavedCommitMessage()})().catch(t=>{new ne().printError(t.message),ae(t),process.exit(1)});const cr=process.argv.slice(2),en=[];let lr=!1;for(let t=0;t<cr.length;t++){const e=cr[t];if(lr){lr=!1;continue}if(e!=="--hook-mode"){if(e.startsWith("-")){const r=cr[t+1];r&&!r.startsWith("-")&&(lr=!0);continue}en.push(e)}}const[ft,tn]=en;var Gc=(t,e,r,o,n,s)=>(async()=>{if(!ft)throw new b('Commit message file path is missing. This file should be called from the "prepare-commit-msg" git hook or with --hook-mode flag');if(tn){console.log(`Skipping aicommit2 message generation for ${tn} commit`);return}const i=await nr();if(!i)return;const c=new ne;c.printTitle();const a=await de({locale:t?.toString(),generate:e?.toString(),type:o?.toString(),systemPrompt:n?.toString(),includeBody:s?.toString()},r);if(a.systemPromptPath)try{await O.readFile(A.resolve(a.systemPromptPath),"utf-8")}catch{throw new b(`Error reading system prompt file: ${a.systemPromptPath}`)}const m=Object.entries(a).filter(([$])=>be.includes($)).map(([$,C])=>[$,C]).filter(([$,C])=>!C.disabled).filter(([$,C])=>$==="OLLAMA"?!!C&&!!C.model&&C.model.length>0:$==="HUGGINGFACE"?!!C&&!!C.cookie:!!C.key&&C.key.length>0).map(([$])=>$);if(m.length===0)throw new b("Please set at least one API key via the `aicommit2 config set` command");const l=new ut(a,i),p=c.displaySpinner("The AI is analyzing your changes");let u;try{u=await br(l.createCommitMsgRequests$(m).pipe(Cr($=>!$.isError),M($=>$.value),Pr()))}finally{p.stop(),p.clear(),c.printAnalyzed()}const g=await O.readFile(ft,"utf8")!=="",y=u.length>1,w=await gc();let v="";g&&(v=`${w} \u{1F916} Generated by aicommit2 (https://github.com/tak-bro/aicommit2)
|
|
214
214
|
`,v+=`${w} ----------------------------------------
|
|
215
215
|
`,v+=`${w} How to use:
|
|
216
216
|
`,y?(v+=`${w} 1. Remove the "${w}" from your chosen message
|
|
@@ -223,13 +223,13 @@ ${i[0]}
|
|
|
223
223
|
`),y?(g&&(v+=`
|
|
224
224
|
${w} \u{1F4DD} Choose one of these messages:
|
|
225
225
|
`),v+=`
|
|
226
|
-
${
|
|
226
|
+
${u.map($=>`${w} ${$}`).join(`
|
|
227
227
|
`)}`):(g&&(v+=`
|
|
228
228
|
${w} \u{1F4DD} Generated commit message:
|
|
229
229
|
`),v+=`
|
|
230
|
-
${
|
|
231
|
-
`);const E=await
|
|
232
|
-
`+E;await
|
|
230
|
+
${u[0]}
|
|
231
|
+
`);const E=await O.readFile(ft,"utf8"),x=v+`
|
|
232
|
+
`+E;await O.writeFile(ft,x),c.printSavedCommitMessage()})().catch(i=>{new ne().printError(i.message),ae(i),process.exit(1)});let pt=new $r;const J=new ne,rn=process.cwd(),Bc=A.join(rn,".git","hooks","post-commit"),Be=A.join(rn,".git","commit-log.txt"),Hc=`#!/bin/sh
|
|
233
233
|
commit_hash=$(git rev-parse HEAD)
|
|
234
234
|
commit_message=$(git log -1 --pretty=%B)
|
|
235
235
|
echo "$commit_hash: $commit_message" >> ${Be}
|
|
@@ -237,5 +237,5 @@ echo "$commit_hash: $commit_message" >> ${Be}
|
|
|
237
237
|
aicommit2 config set [MODEL].key="YOUR_API_KEY"
|
|
238
238
|
aicommit2 config set [MODEL].watchMode="true"`),process.exit()),n},zc=async t=>{J.printError(`An error occurred: ${t.message}`),ae(t),await new Promise(e=>setTimeout(e,3e3)),J.printWarning("Restarting the commit monitoring process...")},Kc=()=>{H.writeFileSync(Be,"",{flag:"w"})},nn=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])=>Jc(e,r,t)).map(([e])=>e),Jc=(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},Wc=()=>{H.writeFileSync(Bc,Hc,{mode:493}),J.printSetupGitEvent("post-commit")},sn=()=>{process.stdout.write("\x1Bc")},Yc=async(t,e)=>{try{const r=await hc(e);if(!r){J.printWarning("No changes found in this commit");return}J.stopLoader(),J.printStagedFiles(r);const o=nn(t);if(o.length===0){J.printError(`Please set at least one API key and watchMode via the config command:
|
|
239
239
|
aicommit2 config set [MODEL].key="YOUR_API_KEY"
|
|
240
|
-
aicommit2 config set [MODEL].watchMode="true"`),process.exit();return}await
|
|
241
|
-
`),tl=async(t,e)=>{const[r]=e.split(":");if(!r){J.printWarning("Empty commit hash detected, skipping...");return}sn(),await Yc(t,r.trim())},rl=()=>{try{H.truncateSync(Be)}catch(t){J.printError(`Error truncating log file: ${t.message}`)}},ol=t=>e=>{J.printError(`Watcher error: ${e.message}`),setTimeout(()=>an(t),1e3)},dr=process.argv.slice(2),{version:cn,description:nl}=as;fn({name:"aicommit2",version:cn,flags:{locale:{type:String,description:"Locale to use for the generated commit messages (default: en)",alias:"l"},generate:{type:Number,description:"Number of messages to generate (Warning: generating multiple costs more) (default: 1)",alias:"g"},exclude:{type:[String],description:"Files to exclude from AI analysis",alias:"x"},all:{type:Boolean,description:"Automatically stage changes in tracked files for the commit",alias:"a",default:!1},type:{type:String,description:"Type of commit message to generate (default: conventional)",alias:"t"},confirm:{type:Boolean,description:"Skip confirmation when committing after message generation (default: false)",alias:"y",default:!1},clipboard:{type:Boolean,description:"Copy the selected message to the clipboard",alias:"c",default:!1},prompt:{type:String,description:"Custom prompt to let users fine-tune provided prompt",alias:"p"},"watch-commit":{type:Boolean,default:!1},"hook-mode":{type:Boolean,description:"Run in git hook mode, allowing chaining with other hooks",default:!1},"pre-commit":{type:Boolean,description:"Run in pre-commit Framework, allowing chaining with other hooks",default:!1},"include-body":{type:Boolean,description:"Force include commit body in all generated messages",alias:"i",default:!1},"auto-select":{type:Boolean,description:"Automatically select the message when only one is generated",alias:"s",default:!1},edit:{type:Boolean,description:"Open the AI-generated commit message in your default editor",alias:"e",default:!1}},commands:[kc,xc,Mc,Tc],help:{description:nl},ignoreArgv:t=>t==="unknown-flag"||t==="argument"},async t=>{const e=await de({});if(await Oa(e),Pe.info(`aicommit2 version: ${cn}`),t.flags["pre-commit"]){_c();return}if(t.flags["hook-mode"]||Ic){Gc(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"]){on(t.flags.locale,t.flags.generate,t.flags.exclude,t.flags.prompt,dr);return}Cc(t.flags.locale,t.flags.generate,t.flags.exclude,t.flags.all,t.flags.type,t.flags.confirm,t.flags.clipboard,t.flags.prompt,t.flags["include-body"],t.flags["auto-select"],t.flags.edit,dr)},dr);
|
|
240
|
+
aicommit2 config set [MODEL].watchMode="true"`),process.exit();return}await Vc(t,r,o)}catch(r){J.printError(`Error processing commit ${e}: ${r.message}`)}},Vc=async(t,e,r)=>{qc();const o=new ut(t,e);K=new ar(Ko);const n=Xc();K.startLoader(),ur=Qc(o,r),await n,Zc()},qc=()=>{K&&(ur?.unsubscribe(),K.clearLoader(),K.completeSubject(),K.cancel(),K.closeInquirerInstance()),pt.next(),pt.complete(),pt=new $r},Xc=()=>K.initPrompt({...ir,name:"codeReviewPrompt",message:"Please check code reviews: ",emptyMessage:`\u26A0 ${Jo}`,isDescriptionDim:!1,stopMessage:"Code review completed",descPageSize:20}),Qc=(t,e)=>t.createCodeReviewRequests$(e).pipe(Jn(pt)).subscribe(r=>{K?.refreshChoices(r)},()=>{},()=>{K?.checkErrorOnChoices(!1)}),Zc=()=>{K&&(ur?.unsubscribe(),K.clearLoader(),K.completeSubject(),K.cancel(),K.closeInquirerInstance(),K=null),sn(),J.showLoader("Watching for new Git commits...")},an=async t=>{const e=Kn.watch(Be,{persistent:!0});e.on("change",async()=>{try{const r=await el();for(const o of r)o&&await tl(t,o)}catch(r){J.printError(`Error reading or processing commit log: ${r.message}`)}finally{rl()}}),e.on("error",ol(t))},el=async()=>(await H.promises.readFile(Be,"utf8")).trim().split(`
|
|
241
|
+
`),tl=async(t,e)=>{const[r]=e.split(":");if(!r){J.printWarning("Empty commit hash detected, skipping...");return}sn(),await Yc(t,r.trim())},rl=()=>{try{H.truncateSync(Be)}catch(t){J.printError(`Error truncating log file: ${t.message}`)}},ol=t=>e=>{J.printError(`Watcher error: ${e.message}`),setTimeout(()=>an(t),1e3)},dr=process.argv.slice(2),{version:cn,description:nl}=as;fn({name:"aicommit2",version:cn,flags:{locale:{type:String,description:"Locale to use for the generated commit messages (default: en)",alias:"l"},generate:{type:Number,description:"Number of messages to generate (Warning: generating multiple costs more) (default: 1)",alias:"g"},exclude:{type:[String],description:"Files to exclude from AI analysis",alias:"x"},all:{type:Boolean,description:"Automatically stage changes in tracked files for the commit",alias:"a",default:!1},type:{type:String,description:"Type of commit message to generate (default: conventional)",alias:"t"},confirm:{type:Boolean,description:"Skip confirmation when committing after message generation (default: false)",alias:"y",default:!1},clipboard:{type:Boolean,description:"Copy the selected message to the clipboard",alias:"c",default:!1},prompt:{type:String,description:"Custom prompt to let users fine-tune provided prompt",alias:"p"},"watch-commit":{type:Boolean,default:!1},"hook-mode":{type:Boolean,description:"Run in git hook mode, allowing chaining with other hooks",default:!1},"pre-commit":{type:Boolean,description:"Run in pre-commit Framework, allowing chaining with other hooks",default:!1},"include-body":{type:Boolean,description:"Force include commit body in all generated messages",alias:"i",default:!1},"auto-select":{type:Boolean,description:"Automatically select the message when only one is generated",alias:"s",default:!1},edit:{type:Boolean,description:"Open the AI-generated commit message in your default editor",alias:"e",default:!1},"disable-lowercase":{type:Boolean,description:"Disable automatic lowercase conversion of commit messages",default:!1}},commands:[kc,xc,Mc,Tc],help:{description:nl},ignoreArgv:t=>t==="unknown-flag"||t==="argument"},async t=>{const e=await de({});if(await Oa(e),Pe.info(`aicommit2 version: ${cn}`),t.flags["pre-commit"]){_c();return}if(t.flags["hook-mode"]||Ic){Gc(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"]){on(t.flags.locale,t.flags.generate,t.flags.exclude,t.flags.prompt,dr);return}Cc(t.flags.locale,t.flags.generate,t.flags.exclude,t.flags.all,t.flags.type,t.flags.confirm,t.flags.clipboard,t.flags.prompt,t.flags["include-body"],t.flags["auto-select"],t.flags.edit,t.flags["disable-lowercase"],dr)},dr);
|