aicommit2 2.4.24 → 2.4.25
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/dist/cli.mjs +85 -85
- package/package.json +1 -1
package/dist/cli.mjs
CHANGED
|
@@ -1,26 +1,26 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{command as le,cli as Mn}from"cleye";import{createRequire as Rn}from"module";import Dn from"crypto";import q from"fs";import De from"os";import I from"path";import{Buffer as Rr}from"node:buffer";import fe from"node:path";import xt,{ChildProcess as Dr,exec as On}from"node:child_process";import se from"node:process";import Nn,{execSync as qe,exec as Fn}from"child_process";import{fileURLToPath as Or}from"node:url";import Ln,{constants as Nr}from"node:os";import Fr from"assert";import Lr from"events";import{createWriteStream as _n,createReadStream as Tn,readFileSync as jn}from"node:fs";import Bn from"buffer";import It from"stream";import _r,{promisify as Gn}from"util";import{debuglog as Hn,promisify as Un}from"node:util";import Xe from"inquirer";import L from"fs/promises";import C from"chalk";import{of as Mt,concatMap as _,from as O,map as N,catchError as F,mergeMap as Tr,BehaviorSubject as jr,ReplaySubject as zn,Subscription as Rt,lastValueFrom as Br,filter as Gr,toArray as Hr,Subject as Dt}from"rxjs";import Kn from"@anthropic-ai/sdk";import{fromPromise as T}from"rxjs/internal/observable/innerFrom";import{xxh64 as Ur}from"@pacote/xxhash";import H from"winston";import"winston-daily-rotate-file";import zr from"https";import Wn from"axios";import{CohereClientV2 as Yn}from"cohere-ai";import Kr from"openai";import{GoogleGenerativeAI as Jn,HarmCategory as Qe,HarmBlockThreshold as Ze}from"@google/generative-ai";import Vn from"http";import qn from"net";import Xn from"tls";import Qn,{fileURLToPath as Zn,pathToFileURL as es}from"url";import Wr from"tty";import ts from"groq-sdk";import{Ollama as rs}from"ollama";import{fetch as os,Agent as ns}from"undici";import et from"readline";import Yr from"figlet";import ss from"gradient-string";import Jr from"ora";import is from"inquirer-reactive-list-prompt";import{readdir as Vr,stat as as,rm as cs}from"node:fs/promises";import ls from"chokidar";import{takeUntil as qr,finalize as Xr}from"rxjs/operators";var us="aicommit2",Qr="2.4.24",ds="A Reactive CLI that generates commit messages for Git and Jujutsu with various AI",ms=["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"],fs="MIT",ps="tak-bro/aicommit2",hs="Hyungtak Jin(@tak-bro)",gs="module",ys=["dist"],ws={aicommit2:"./dist/cli.mjs",aic2:"./dist/cli.mjs"},vs={prepare:"simple-git-hooks",build:"pkgroll --minify",lint:"eslint --cache .","type-check":"tsc",test:"tsx tests",prepack:"pnpm build && clean-pkg-json",prettier:"prettier"},Cs={"@anthropic-ai/sdk":"^0.39.0","@aws-sdk/client-bedrock-runtime":"^3.678.0","@aws-sdk/credential-providers":"^3.678.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.19.0","copy-paste":"^1.5.3",figlet:"^1.8.1","formdata-node":"^6.0.3","gradient-string":"^3.0.0","groq-sdk":"^0.7.0",inquirer:"9.2.8","inquirer-reactive-list-prompt":"^1.0.16",ollama:"^0.5.15",openai:"^6.3.0",ora:"^8.2.0",readline:"^1.3.0",rxjs:"^7.8.2",undici:"^7.10.0",uuid:"^9.0.1",winston:"^3.17.0","winston-daily-rotate-file":"^5.0.0"},bs={"@pvtnbr/eslint-config":"^0.33.0","@semantic-release/changelog":"^6.0.3","@semantic-release/commit-analyzer":"^12.0.0","@semantic-release/git":"^10.0.1","@semantic-release/github":"^10.3.5","@semantic-release/npm":"^12.0.1","@semantic-release/release-notes-generator":"^13.0.0","@types/figlet":"^1.7.0","@types/ini":"^1.3.34","@types/inquirer":"^9.0.8","@types/node":"^18.19.103","@types/uuid":"^9.0.8","@typescript-eslint/eslint-plugin":"^6.21.0","@typescript-eslint/parser":"^6.21.0","clean-pkg-json":"^1.3.0","conventional-changelog-conventionalcommits":"^7.0.2","conventional-commits-parser":"^5.0.0",eslint:"^8.57.1","eslint-config-prettier":"^8.10.0","eslint-plugin-eslint-comments":"^3.2.0","eslint-plugin-import":"^2.31.0","eslint-plugin-jsonc":"^2.20.1","eslint-plugin-no-use-extend-native":"^0.5.0","eslint-plugin-promise":"^6.6.0","eslint-plugin-unicorn":"^49.0.0","eslint-plugin-unused-imports":"^3.2.0",execa:"^7.2.0","fs-fixture":"^1.2.0","https-proxy-agent":"^5.0.1",ini:"^3.0.1","lint-staged":"^13.3.0",manten:"^0.7.0",pkgroll:"^1.11.1",prettier:"^3.5.3","semantic-release":"^23.1.1","simple-git-hooks":"^2.13.0",tsx:"^3.14.0",typescript:"^4.9.5","undici-types":"^7.10.0"},Es={extends:["@pvtnbr","prettier"],rules:{"unicorn/no-process-exit":"off"},overrides:[{files:"./src/commands/prepare-commit-msg-hook.ts",rules:{"unicorn/prevent-abbreviations":"off"}}]},Ps={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:us,version:Qr,description:ds,keywords:ms,license:fs,repository:ps,author:hs,type:gs,files:ys,bin:ws,scripts:vs,"simple-git-hooks":{"pre-commit":"pnpm lint-staged"},"lint-staged":{"*.ts":["prettier --config ./.prettierrc --write","eslint --fix"]},dependencies:Cs,devDependencies:bs,eslintConfig:Es,release:Ps},$s=Rn(import.meta.url),G=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function ve(r){return r&&r.__esModule&&Object.prototype.hasOwnProperty.call(r,"default")?r.default:r}var Ce={exports:{}},Ot,Zr;function ks(){if(Zr)return Ot;Zr=1,Ot=o,o.sync=n;var r=q;function e(s,i){var l=i.pathExt!==void 0?i.pathExt:process.env.PATHEXT;if(!l||(l=l.split(";"),l.indexOf("")!==-1))return!0;for(var a=0;a<l.length;a++){var d=l[a].toLowerCase();if(d&&s.substr(-d.length).toLowerCase()===d)return!0}return!1}function t(s,i,l){return!s.isSymbolicLink()&&!s.isFile()?!1:e(i,l)}function o(s,i,l){r.stat(s,function(a,d){l(a,a?!1:t(d,s,i))})}function n(s,i){return t(r.statSync(s),s,i)}return Ot}var Nt,eo;function Ss(){if(eo)return Nt;eo=1,Nt=e,e.sync=t;var r=q;function e(s,i,l){r.stat(s,function(a,d){l(a,a?!1:o(d,i))})}function t(s,i){return o(r.statSync(s),i)}function o(s,i){return s.isFile()&&n(s,i)}function n(s,i){var l=s.mode,a=s.uid,d=s.gid,c=i.uid!==void 0?i.uid:process.getuid&&process.getuid(),u=i.gid!==void 0?i.gid:process.getgid&&process.getgid(),f=parseInt("100",8),p=parseInt("010",8),h=parseInt("001",8),y=f|p,g=l&h||l&p&&d===u||l&f&&a===c||l&y&&c===0;return g}return Nt}var tt;process.platform==="win32"||G.TESTING_WINDOWS?tt=ks():tt=Ss();var xs=Ft;Ft.sync=Is;function Ft(r,e,t){if(typeof e=="function"&&(t=e,e={}),!t){if(typeof Promise!="function")throw new TypeError("callback not provided");return new Promise(function(o,n){Ft(r,e||{},function(s,i){s?n(s):o(i)})})}tt(r,e||{},function(o,n){o&&(o.code==="EACCES"||e&&e.ignoreErrors)&&(o=null,n=!1),t(o,n)})}function Is(r,e){try{return tt.sync(r,e||{})}catch(t){if(e&&e.ignoreErrors||t.code==="EACCES")return!1;throw t}}const be=process.platform==="win32"||process.env.OSTYPE==="cygwin"||process.env.OSTYPE==="msys",to=I,Ms=be?";":":",ro=xs,oo=r=>Object.assign(new Error(`not found: ${r}`),{code:"ENOENT"}),no=(r,e)=>{const t=e.colon||Ms,o=r.match(/\//)||be&&r.match(/\\/)?[""]:[...be?[process.cwd()]:[],...(e.path||process.env.PATH||"").split(t)],n=be?e.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",s=be?n.split(t):[""];return be&&r.indexOf(".")!==-1&&s[0]!==""&&s.unshift(""),{pathEnv:o,pathExt:s,pathExtExe:n}},so=(r,e,t)=>{typeof e=="function"&&(t=e,e={}),e||(e={});const{pathEnv:o,pathExt:n,pathExtExe:s}=no(r,e),i=[],l=d=>new Promise((c,u)=>{if(d===o.length)return e.all&&i.length?c(i):u(oo(r));const f=o[d],p=/^".*"$/.test(f)?f.slice(1,-1):f,h=to.join(p,r),y=!p&&/^\.[\\\/]/.test(r)?r.slice(0,2)+h:h;c(a(y,d,0))}),a=(d,c,u)=>new Promise((f,p)=>{if(u===n.length)return f(l(c+1));const h=n[u];ro(d+h,{pathExt:s},(y,g)=>{if(!y&&g)if(e.all)i.push(d+h);else return f(d+h);return f(a(d,c,u+1))})});return t?l(0).then(d=>t(null,d),t):l(0)},Rs=(r,e)=>{e=e||{};const{pathEnv:t,pathExt:o,pathExtExe:n}=no(r,e),s=[];for(let i=0;i<t.length;i++){const l=t[i],a=/^".*"$/.test(l)?l.slice(1,-1):l,d=to.join(a,r),c=!a&&/^\.[\\\/]/.test(r)?r.slice(0,2)+d:d;for(let u=0;u<o.length;u++){const f=c+o[u];try{if(ro.sync(f,{pathExt:n}))if(e.all)s.push(f);else return f}catch{}}}if(e.all&&s.length)return s;if(e.nothrow)return null;throw oo(r)};var Ds=so;so.sync=Rs;var Lt={exports:{}};const io=(r={})=>{const e=r.env||process.env;return(r.platform||process.platform)!=="win32"?"PATH":Object.keys(e).reverse().find(o=>o.toUpperCase()==="PATH")||"Path"};Lt.exports=io,Lt.exports.default=io;var Os=Lt.exports;const ao=I,Ns=Ds,Fs=Os;function co(r,e){const t=r.options.env||process.env,o=process.cwd(),n=r.options.cwd!=null,s=n&&process.chdir!==void 0&&!process.chdir.disabled;if(s)try{process.chdir(r.options.cwd)}catch{}let i;try{i=Ns.sync(r.command,{path:t[Fs({env:t})],pathExt:e?ao.delimiter:void 0})}catch{}finally{s&&process.chdir(o)}return i&&(i=ao.resolve(n?r.options.cwd:"",i)),i}function Ls(r){return co(r)||co(r,!0)}var _s=Ls,_t={};const Tt=/([()\][%!^"`<>&|;, *?])/g;function Ts(r){return r=r.replace(Tt,"^$1"),r}function js(r,e){return r=`${r}`,r=r.replace(/(?=(\\+?)?)\1"/g,'$1$1\\"'),r=r.replace(/(?=(\\+?)?)\1$/,"$1$1"),r=`"${r}"`,r=r.replace(Tt,"^$1"),e&&(r=r.replace(Tt,"^$1")),r}_t.command=Ts,_t.argument=js;var Bs=/^#!(.*)/;const Gs=Bs;var Hs=(r="")=>{const e=r.match(Gs);if(!e)return null;const[t,o]=e[0].replace(/#! ?/,"").split(" "),n=t.split("/").pop();return n==="env"?o:o?`${n} ${o}`:n};const jt=q,Us=Hs;function zs(r){const t=Buffer.alloc(150);let o;try{o=jt.openSync(r,"r"),jt.readSync(o,t,0,150,0),jt.closeSync(o)}catch{}return Us(t.toString())}var Ks=zs;const Ws=I,lo=_s,uo=_t,Ys=Ks,Js=process.platform==="win32",Vs=/\.(?:com|exe)$/i,qs=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function Xs(r){r.file=lo(r);const e=r.file&&Ys(r.file);return e?(r.args.unshift(r.file),r.command=e,lo(r)):r.file}function Qs(r){if(!Js)return r;const e=Xs(r),t=!Vs.test(e);if(r.options.forceShell||t){const o=qs.test(e);r.command=Ws.normalize(r.command),r.command=uo.command(r.command),r.args=r.args.map(s=>uo.argument(s,o));const n=[r.command].concat(r.args).join(" ");r.args=["/d","/s","/c",`"${n}"`],r.command=process.env.comspec||"cmd.exe",r.options.windowsVerbatimArguments=!0}return r}function Zs(r,e,t){e&&!Array.isArray(e)&&(t=e,e=null),e=e?e.slice(0):[],t=Object.assign({},t);const o={command:r,args:e,options:t,file:void 0,original:{command:r,args:e}};return t.shell?o:Qs(o)}var ei=Zs;const Bt=process.platform==="win32";function Gt(r,e){return Object.assign(new Error(`${e} ${r.command} ENOENT`),{code:"ENOENT",errno:"ENOENT",syscall:`${e} ${r.command}`,path:r.command,spawnargs:r.args})}function ti(r,e){if(!Bt)return;const t=r.emit;r.emit=function(o,n){if(o==="exit"){const s=mo(n,e);if(s)return t.call(r,"error",s)}return t.apply(r,arguments)}}function mo(r,e){return Bt&&r===1&&!e.file?Gt(e.original,"spawn"):null}function ri(r,e){return Bt&&r===1&&!e.file?Gt(e.original,"spawnSync"):null}var oi={hookChildProcess:ti,verifyENOENT:mo,verifyENOENTSync:ri,notFoundError:Gt};const fo=Nn,Ht=ei,Ut=oi;function po(r,e,t){const o=Ht(r,e,t),n=fo.spawn(o.command,o.args,o.options);return Ut.hookChildProcess(n,o),n}function ni(r,e,t){const o=Ht(r,e,t),n=fo.spawnSync(o.command,o.args,o.options);return n.error=n.error||Ut.verifyENOENTSync(n.status,o),n}Ce.exports=po,Ce.exports.spawn=po,Ce.exports.sync=ni,Ce.exports._parse=Ht,Ce.exports._enoent=Ut;var si=Ce.exports,ii=ve(si);function ai(r){const e=typeof r=="string"?`
|
|
2
|
+
import{command as le,cli as Mn}from"cleye";import{createRequire as Rn}from"module";import Dn from"crypto";import q from"fs";import Oe from"os";import I from"path";import{Buffer as Or}from"node:buffer";import fe from"node:path";import xt,{ChildProcess as Nr,exec as On}from"node:child_process";import se from"node:process";import Nn,{execSync as Xe,exec as Fn}from"child_process";import{fileURLToPath as Fr}from"node:url";import _n,{constants as _r}from"node:os";import Lr from"assert";import Tr from"events";import{createWriteStream as Ln,createReadStream as Tn,readFileSync as jn}from"node:fs";import Bn from"buffer";import It from"stream";import jr,{promisify as Gn}from"util";import{debuglog as Hn,promisify as Un}from"node:util";import Qe from"inquirer";import F from"fs/promises";import C from"chalk";import{of as Mt,concatMap as _,from as D,map as O,catchError as N,mergeMap as Br,BehaviorSubject as Gr,ReplaySubject as zn,Subscription as Rt,lastValueFrom as Hr,filter as Ur,toArray as zr,Subject as Dt}from"rxjs";import Kn from"@anthropic-ai/sdk";import{fromPromise as L}from"rxjs/internal/observable/innerFrom";import{xxh64 as Kr}from"@pacote/xxhash";import H from"winston";import"winston-daily-rotate-file";import Wr from"https";import Wn from"axios";import{CohereClientV2 as Yn}from"cohere-ai";import Yr from"openai";import{GoogleGenerativeAI as Jn,HarmCategory as Ze,HarmBlockThreshold as et}from"@google/generative-ai";import Vn from"http";import qn from"net";import Xn from"tls";import Qn,{fileURLToPath as Zn,pathToFileURL as es}from"url";import Jr from"tty";import ts from"groq-sdk";import{Ollama as rs}from"ollama";import{fetch as os,Agent as ns}from"undici";import tt from"readline";import Vr from"figlet";import ss from"gradient-string";import qr from"ora";import is from"inquirer-reactive-list-prompt";import{readdir as Xr,stat as as,rm as cs}from"node:fs/promises";import ls from"chokidar";import{takeUntil as Qr,finalize as Zr}from"rxjs/operators";var us="aicommit2",eo="2.4.25",ds="A Reactive CLI that generates commit messages for Git and Jujutsu with various AI",ms=["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"],fs="MIT",ps="tak-bro/aicommit2",hs="Hyungtak Jin(@tak-bro)",gs="module",ys=["dist"],ws={aicommit2:"./dist/cli.mjs",aic2:"./dist/cli.mjs"},vs={prepare:"simple-git-hooks",build:"pkgroll --minify",lint:"eslint --cache .","type-check":"tsc",test:"tsx tests",prepack:"pnpm build && clean-pkg-json",prettier:"prettier"},Cs={"@anthropic-ai/sdk":"^0.39.0","@aws-sdk/client-bedrock-runtime":"^3.678.0","@aws-sdk/credential-providers":"^3.678.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.19.0","copy-paste":"^1.5.3",figlet:"^1.8.1","formdata-node":"^6.0.3","gradient-string":"^3.0.0","groq-sdk":"^0.7.0",inquirer:"9.2.8","inquirer-reactive-list-prompt":"^1.0.16",ollama:"^0.5.15",openai:"^6.3.0",ora:"^8.2.0",readline:"^1.3.0",rxjs:"^7.8.2",undici:"^7.10.0",uuid:"^9.0.1",winston:"^3.17.0","winston-daily-rotate-file":"^5.0.0"},bs={"@pvtnbr/eslint-config":"^0.33.0","@semantic-release/changelog":"^6.0.3","@semantic-release/commit-analyzer":"^12.0.0","@semantic-release/git":"^10.0.1","@semantic-release/github":"^10.3.5","@semantic-release/npm":"^12.0.1","@semantic-release/release-notes-generator":"^13.0.0","@types/figlet":"^1.7.0","@types/ini":"^1.3.34","@types/inquirer":"^9.0.8","@types/node":"^18.19.103","@types/uuid":"^9.0.8","@typescript-eslint/eslint-plugin":"^6.21.0","@typescript-eslint/parser":"^6.21.0","clean-pkg-json":"^1.3.0","conventional-changelog-conventionalcommits":"^7.0.2","conventional-commits-parser":"^5.0.0",eslint:"^8.57.1","eslint-config-prettier":"^8.10.0","eslint-plugin-eslint-comments":"^3.2.0","eslint-plugin-import":"^2.31.0","eslint-plugin-jsonc":"^2.20.1","eslint-plugin-no-use-extend-native":"^0.5.0","eslint-plugin-promise":"^6.6.0","eslint-plugin-unicorn":"^49.0.0","eslint-plugin-unused-imports":"^3.2.0",execa:"^7.2.0","fs-fixture":"^1.2.0","https-proxy-agent":"^5.0.1",ini:"^3.0.1","lint-staged":"^13.3.0",manten:"^0.7.0",pkgroll:"^1.11.1",prettier:"^3.5.3","semantic-release":"^23.1.1","simple-git-hooks":"^2.13.0",tsx:"^3.14.0",typescript:"^4.9.5","undici-types":"^7.10.0"},Es={extends:["@pvtnbr","prettier"],rules:{"unicorn/no-process-exit":"off"},overrides:[{files:"./src/commands/prepare-commit-msg-hook.ts",rules:{"unicorn/prevent-abbreviations":"off"}}]},Ps={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"]},$s={name:us,version:eo,description:ds,keywords:ms,license:fs,repository:ps,author:hs,type:gs,files:ys,bin:ws,scripts:vs,"simple-git-hooks":{"pre-commit":"pnpm lint-staged"},"lint-staged":{"*.ts":["prettier --config ./.prettierrc --write","eslint --fix"]},dependencies:Cs,devDependencies:bs,eslintConfig:Es,release:Ps},As=Rn(import.meta.url),G=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function ve(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Ce={exports:{}},Ot,to;function ks(){if(to)return Ot;to=1,Ot=o,o.sync=n;var t=q;function e(s,i){var l=i.pathExt!==void 0?i.pathExt:process.env.PATHEXT;if(!l||(l=l.split(";"),l.indexOf("")!==-1))return!0;for(var a=0;a<l.length;a++){var d=l[a].toLowerCase();if(d&&s.substr(-d.length).toLowerCase()===d)return!0}return!1}function r(s,i,l){return!s.isSymbolicLink()&&!s.isFile()?!1:e(i,l)}function o(s,i,l){t.stat(s,function(a,d){l(a,a?!1:r(d,s,i))})}function n(s,i){return r(t.statSync(s),s,i)}return Ot}var Nt,ro;function Ss(){if(ro)return Nt;ro=1,Nt=e,e.sync=r;var t=q;function e(s,i,l){t.stat(s,function(a,d){l(a,a?!1:o(d,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 l=s.mode,a=s.uid,d=s.gid,c=i.uid!==void 0?i.uid:process.getuid&&process.getuid(),u=i.gid!==void 0?i.gid:process.getgid&&process.getgid(),f=parseInt("100",8),p=parseInt("010",8),h=parseInt("001",8),y=f|p,g=l&h||l&p&&d===u||l&f&&a===c||l&y&&c===0;return g}return Nt}var rt;process.platform==="win32"||G.TESTING_WINDOWS?rt=ks():rt=Ss();var xs=Ft;Ft.sync=Is;function Ft(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){Ft(t,e||{},function(s,i){s?n(s):o(i)})})}rt(t,e||{},function(o,n){o&&(o.code==="EACCES"||e&&e.ignoreErrors)&&(o=null,n=!1),r(o,n)})}function Is(t,e){try{return rt.sync(t,e||{})}catch(r){if(e&&e.ignoreErrors||r.code==="EACCES")return!1;throw r}}const be=process.platform==="win32"||process.env.OSTYPE==="cygwin"||process.env.OSTYPE==="msys",oo=I,Ms=be?";":":",no=xs,so=t=>Object.assign(new Error(`not found: ${t}`),{code:"ENOENT"}),io=(t,e)=>{const r=e.colon||Ms,o=t.match(/\//)||be&&t.match(/\\/)?[""]:[...be?[process.cwd()]:[],...(e.path||process.env.PATH||"").split(r)],n=be?e.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",s=be?n.split(r):[""];return be&&t.indexOf(".")!==-1&&s[0]!==""&&s.unshift(""),{pathEnv:o,pathExt:s,pathExtExe:n}},ao=(t,e,r)=>{typeof e=="function"&&(r=e,e={}),e||(e={});const{pathEnv:o,pathExt:n,pathExtExe:s}=io(t,e),i=[],l=d=>new Promise((c,u)=>{if(d===o.length)return e.all&&i.length?c(i):u(so(t));const f=o[d],p=/^".*"$/.test(f)?f.slice(1,-1):f,h=oo.join(p,t),y=!p&&/^\.[\\\/]/.test(t)?t.slice(0,2)+h:h;c(a(y,d,0))}),a=(d,c,u)=>new Promise((f,p)=>{if(u===n.length)return f(l(c+1));const h=n[u];no(d+h,{pathExt:s},(y,g)=>{if(!y&&g)if(e.all)i.push(d+h);else return f(d+h);return f(a(d,c,u+1))})});return r?l(0).then(d=>r(null,d),r):l(0)},Rs=(t,e)=>{e=e||{};const{pathEnv:r,pathExt:o,pathExtExe:n}=io(t,e),s=[];for(let i=0;i<r.length;i++){const l=r[i],a=/^".*"$/.test(l)?l.slice(1,-1):l,d=oo.join(a,t),c=!a&&/^\.[\\\/]/.test(t)?t.slice(0,2)+d:d;for(let u=0;u<o.length;u++){const f=c+o[u];try{if(no.sync(f,{pathExt:n}))if(e.all)s.push(f);else return f}catch{}}}if(e.all&&s.length)return s;if(e.nothrow)return null;throw so(t)};var Ds=ao;ao.sync=Rs;var _t={exports:{}};const co=(t={})=>{const e=t.env||process.env;return(t.platform||process.platform)!=="win32"?"PATH":Object.keys(e).reverse().find(o=>o.toUpperCase()==="PATH")||"Path"};_t.exports=co,_t.exports.default=co;var Os=_t.exports;const lo=I,Ns=Ds,Fs=Os;function uo(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=Ns.sync(t.command,{path:r[Fs({env:r})],pathExt:e?lo.delimiter:void 0})}catch{}finally{s&&process.chdir(o)}return i&&(i=lo.resolve(n?t.options.cwd:"",i)),i}function _s(t){return uo(t)||uo(t,!0)}var Ls=_s,Lt={};const Tt=/([()\][%!^"`<>&|;, *?])/g;function Ts(t){return t=t.replace(Tt,"^$1"),t}function js(t,e){return t=`${t}`,t=t.replace(/(?=(\\+?)?)\1"/g,'$1$1\\"'),t=t.replace(/(?=(\\+?)?)\1$/,"$1$1"),t=`"${t}"`,t=t.replace(Tt,"^$1"),e&&(t=t.replace(Tt,"^$1")),t}Lt.command=Ts,Lt.argument=js;var Bs=/^#!(.*)/;const Gs=Bs;var Hs=(t="")=>{const e=t.match(Gs);if(!e)return null;const[r,o]=e[0].replace(/#! ?/,"").split(" "),n=r.split("/").pop();return n==="env"?o:o?`${n} ${o}`:n};const jt=q,Us=Hs;function zs(t){const r=Buffer.alloc(150);let o;try{o=jt.openSync(t,"r"),jt.readSync(o,r,0,150,0),jt.closeSync(o)}catch{}return Us(r.toString())}var Ks=zs;const Ws=I,mo=Ls,fo=Lt,Ys=Ks,Js=process.platform==="win32",Vs=/\.(?:com|exe)$/i,qs=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function Xs(t){t.file=mo(t);const e=t.file&&Ys(t.file);return e?(t.args.unshift(t.file),t.command=e,mo(t)):t.file}function Qs(t){if(!Js)return t;const e=Xs(t),r=!Vs.test(e);if(t.options.forceShell||r){const o=qs.test(e);t.command=Ws.normalize(t.command),t.command=fo.command(t.command),t.args=t.args.map(s=>fo.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 Zs(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:Qs(o)}var ei=Zs;const Bt=process.platform==="win32";function Gt(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 ti(t,e){if(!Bt)return;const r=t.emit;t.emit=function(o,n){if(o==="exit"){const s=po(n,e);if(s)return r.call(t,"error",s)}return r.apply(t,arguments)}}function po(t,e){return Bt&&t===1&&!e.file?Gt(e.original,"spawn"):null}function ri(t,e){return Bt&&t===1&&!e.file?Gt(e.original,"spawnSync"):null}var oi={hookChildProcess:ti,verifyENOENT:po,verifyENOENTSync:ri,notFoundError:Gt};const ho=Nn,Ht=ei,Ut=oi;function go(t,e,r){const o=Ht(t,e,r),n=ho.spawn(o.command,o.args,o.options);return Ut.hookChildProcess(n,o),n}function ni(t,e,r){const o=Ht(t,e,r),n=ho.spawnSync(o.command,o.args,o.options);return n.error=n.error||Ut.verifyENOENTSync(n.status,o),n}Ce.exports=go,Ce.exports.spawn=go,Ce.exports.sync=ni,Ce.exports._parse=Ht,Ce.exports._enoent=Ut;var si=Ce.exports,ii=ve(si);function ai(t){const e=typeof t=="string"?`
|
|
3
3
|
`:`
|
|
4
|
-
`.charCodeAt(),
|
|
5
|
-
${e}`,gi=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),yi=Object.getOwnPropertyDescriptor(Function.prototype.toString,"name"),wi=(
|
|
6
|
-
${o.message}`:g,E=[b,e,
|
|
7
|
-
`);return v?(o.originalMessage=o.message,o.message=E):o=new Error(E),o.shortMessage=b,o.command=i,o.escapedCommand=l,o.exitCode=s,o.signal=n,o.signalDescription=p,o.stdout=
|
|
8
|
-
`)}
|
|
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 yo(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 ci=({cwd:t=se.cwd(),path:e=se.env[yo()],preferLocal:r=!0,execPath:o=se.execPath,addExecPath:n=!0}={})=>{const s=t instanceof URL?Fr(t):t,i=fe.resolve(s),l=[];return r&&li(l,i),n&&ui(l,o,i),[...l,e].join(fe.delimiter)},li=(t,e)=>{let r;for(;r!==e;)t.push(fe.join(e,"node_modules/.bin")),r=e,e=fe.resolve(e,"..")},ui=(t,e,r)=>{const o=e instanceof URL?Fr(e):e;t.push(fe.resolve(r,o,".."))},di=({env:t=se.env,...e}={})=>{t={...t};const r=yo({env:t});return e.path=t[r],t[r]=ci(e),t},mi=(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);!fi(n,s)&&o||Object.defineProperty(t,r,s)},fi=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)},pi=(t,e)=>{const r=Object.getPrototypeOf(e);r!==Object.getPrototypeOf(t)&&Object.setPrototypeOf(t,r)},hi=(t,e)=>`/* Wrapped ${t}*/
|
|
5
|
+
${e}`,gi=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),yi=Object.getOwnPropertyDescriptor(Function.prototype.toString,"name"),wi=(t,e,r)=>{const o=r===""?"":`with ${r.trim()}() `,n=hi.bind(null,o,e.toString());Object.defineProperty(n,"name",yi),Object.defineProperty(t,"toString",{...gi,value:n})};function vi(t,e,{ignoreNonConfigurable:r=!1}={}){const{name:o}=t;for(const n of Reflect.ownKeys(e))mi(t,e,n,r);return pi(t,e),wi(t,e,o),t}const ot=new WeakMap,wo=(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(ot.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 vi(s,t),ot.set(s,o),s};wo.callCount=t=>{if(!ot.has(t))throw new Error(`The given function \`${t.name}\` is not wrapped by the \`onetime\` package`);return ot.get(t)};const Ci=()=>{const t=Co-vo+1;return Array.from({length:t},bi)},bi=(t,e)=>({name:`SIGRT${e+1}`,number:vo+e,action:"terminate",description:"Application-specific signal (realtime)",standard:"posix"}),vo=34,Co=64,Ei=[{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"}],bo=()=>{const t=Ci();return[...Ei,...t].map(Pi)},Pi=({name:t,number:e,description:r,action:o,forced:n=!1,standard:s})=>{const{signals:{[t]:i}}=_r,l=i!==void 0;return{name:t,number:l?i:e,description:r,supported:l,action:o,forced:n,standard:s}},$i=()=>{const t=bo();return Object.fromEntries(t.map(Ai))},Ai=({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}],ki=$i(),Si=()=>{const t=bo(),e=Co+1,r=Array.from({length:e},(o,n)=>xi(n,t));return Object.assign({},...r)},xi=(t,e)=>{const r=Ii(t,e);if(r===void 0)return{};const{name:o,description:n,supported:s,action:i,forced:l,standard:a}=r;return{[t]:{name:o,number:t,description:n,supported:s,action:i,forced:l,standard:a}}},Ii=(t,e)=>{const r=e.find(({name:o})=>_r.signals[o]===t);return r!==void 0?r:e.find(o=>o.number===t)};Si();const Mi=({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",nt=({stdout:t,stderr:e,all:r,error:o,signal:n,exitCode:s,command:i,escapedCommand:l,timedOut:a,isCanceled:d,killed:c,parsed:{options:{timeout:u,cwd:f=se.cwd()}}})=>{s=s===null?void 0:s,n=n===null?void 0:n;const p=n===void 0?void 0:ki[n].description,h=o&&o.code,g=`Command ${Mi({timedOut:a,timeout:u,errorCode:h,signal:n,signalDescription:p,exitCode:s,isCanceled:d})}: ${i}`,v=Object.prototype.toString.call(o)==="[object Error]",b=v?`${g}
|
|
6
|
+
${o.message}`:g,E=[b,e,t].filter(Boolean).join(`
|
|
7
|
+
`);return v?(o.originalMessage=o.message,o.message=E):o=new Error(E),o.shortMessage=b,o.command=i,o.escapedCommand=l,o.exitCode=s,o.signal=n,o.signalDescription=p,o.stdout=t,o.stderr=e,o.cwd=f,r!==void 0&&(o.all=r),"bufferedData"in o&&delete o.bufferedData,o.failed=!0,o.timedOut=!!a,o.isCanceled=d,o.killed=c&&!a,o},st=["stdin","stdout","stderr"],Ri=t=>st.some(e=>t[e]!==void 0),Eo=t=>{if(!t)return;const{stdio:e}=t;if(e===void 0)return st.map(o=>t[o]);if(Ri(t))throw new Error(`It's not possible to provide \`stdio\` in combination with one of ${st.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,st.length);return Array.from({length:r},(o,n)=>e[n])},Di=t=>{const e=Eo(t);return e==="ipc"?"ipc":e===void 0||typeof e=="string"?[e,e,e,"ipc"]:e.includes("ipc")?e:[...e,"ipc"]};var Ee={exports:{}},it={exports:{}};it.exports;var Po;function Oi(){return Po||(Po=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")}(it)),it.exports}var T=G.process;const pe=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(!pe(T))Ee.exports=function(){return function(){}};else{var Ni=Lr,Ne=Oi(),Fi=/^win/i.test(T.platform),at=Tr;typeof at!="function"&&(at=at.EventEmitter);var U;T.__signal_exit_emitter__?U=T.__signal_exit_emitter__:(U=T.__signal_exit_emitter__=new at,U.count=0,U.emitted={}),U.infinite||(U.setMaxListeners(1/0),U.infinite=!0),Ee.exports=function(t,e){if(!pe(G.process))return function(){};Ni.equal(typeof t,"function","a callback must be provided for exit handler"),Fe===!1&&$o();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&&zt()};return U.on(r,t),o};var zt=function(){!Fe||!pe(G.process)||(Fe=!1,Ne.forEach(function(e){try{T.removeListener(e,Kt[e])}catch{}}),T.emit=Wt,T.reallyExit=Ao,U.count-=1)};Ee.exports.unload=zt;var Pe=function(e,r,o){U.emitted[e]||(U.emitted[e]=!0,U.emit(e,r,o))},Kt={};Ne.forEach(function(t){Kt[t]=function(){if(pe(G.process)){var r=T.listeners(t);r.length===U.count&&(zt(),Pe("exit",null,t),Pe("afterexit",null,t),Fi&&t==="SIGHUP"&&(t="SIGINT"),T.kill(T.pid,t))}}}),Ee.exports.signals=function(){return Ne};var Fe=!1,$o=function(){Fe||!pe(G.process)||(Fe=!0,U.count+=1,Ne=Ne.filter(function(e){try{return T.on(e,Kt[e]),!0}catch{return!1}}),T.emit=Li,T.reallyExit=_i)};Ee.exports.load=$o;var Ao=T.reallyExit,_i=function(e){pe(G.process)&&(T.exitCode=e||0,Pe("exit",T.exitCode,null),Pe("afterexit",T.exitCode,null),Ao.call(T,T.exitCode))},Wt=T.emit,Li=function(e,r){if(e==="exit"&&pe(G.process)){r!==void 0&&(T.exitCode=r);var o=Wt.apply(this,arguments);return Pe("exit",T.exitCode,null),Pe("afterexit",T.exitCode,null),o}else return Wt.apply(this,arguments)}}var Ti=Ee.exports,ji=ve(Ti);const Bi=1e3*5,Gi=(t,e="SIGTERM",r={})=>{const o=t(e);return Hi(t,e,r,o),o},Hi=(t,e,r,o)=>{if(!Ui(e,r,o))return;const n=Ki(r),s=setTimeout(()=>{t("SIGKILL")},n);s.unref&&s.unref()},Ui=(t,{forceKillAfterTimeout:e},r)=>zi(t)&&e!==!1&&r,zi=t=>t===_n.constants.signals.SIGTERM||typeof t=="string"&&t.toUpperCase()==="SIGTERM",Ki=({forceKillAfterTimeout:t=!0})=>{if(t===!0)return Bi;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},Wi=(t,e)=>{t.kill()&&(e.isCanceled=!0)},Yi=(t,e,r)=>{t.kill(e),r(Object.assign(new Error("Timed out"),{timedOut:!0,signal:e}))},Ji=(t,{timeout:e,killSignal:r="SIGTERM"},o)=>{if(e===0||e===void 0)return o;let n;const s=new Promise((l,a)=>{n=setTimeout(()=>{Yi(t,r,a)},e)}),i=o.finally(()=>{clearTimeout(n)});return Promise.race([s,i])},Vi=({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})`)},qi=async(t,{cleanup:e,detached:r},o)=>{if(!e||r)return o;const n=ji(()=>{t.kill()});return o.finally(()=>{n()})};function Yt(t){return t!==null&&typeof t=="object"&&typeof t.pipe=="function"}function ko(t){return Yt(t)&&t.writable!==!1&&typeof t._write=="function"&&typeof t._writableState=="object"}const Xi=t=>t instanceof Nr&&typeof t.then=="function",Jt=(t,e,r)=>{if(typeof r=="string")return t[e].pipe(Ln(r)),t;if(ko(r))return t[e].pipe(r),t;if(!Xi(r))throw new TypeError("The second argument must be a string, a stream or an Execa child process.");if(!ko(r.stdin))throw new TypeError("The target child process's stdin must be available.");return t[e].pipe(r.stdin),r},Qi=t=>{t.stdout!==null&&(t.pipeStdout=Jt.bind(void 0,t,"stdout")),t.stderr!==null&&(t.pipeStderr=Jt.bind(void 0,t,"stderr")),t.all!==void 0&&(t.pipeAll=Jt.bind(void 0,t,"all"))};var _e={exports:{}};const{PassThrough:Zi}=It;var ea=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 Zi({objectMode:n});r&&s.setEncoding(r);let i=0;const l=[];return s.on("data",a=>{l.push(a),n?i=l.length:i+=a.length}),s.getBufferedValue=()=>e?l:o?Buffer.concat(l,i):l.join(""),s.getBufferedLength=()=>i,s};const{constants:ta}=Bn,ra=It,{promisify:oa}=jr,na=ea,sa=oa(ra.pipeline);class So extends Error{constructor(){super("maxBuffer exceeded"),this.name="MaxBufferError"}}async function Vt(t,e){if(!t)throw new Error("Expected a stream");e={maxBuffer:1/0,...e};const{maxBuffer:r}=e,o=na(e);return await new Promise((n,s)=>{const i=l=>{l&&o.getBufferedLength()<=ta.MAX_LENGTH&&(l.bufferedData=o.getBufferedValue()),s(l)};(async()=>{try{await sa(t,o),n()}catch(l){i(l)}})(),o.on("data",()=>{o.getBufferedLength()>r&&i(new So)})}),o.getBufferedValue()}_e.exports=Vt,_e.exports.buffer=(t,e)=>Vt(t,{...e,encoding:"buffer"}),_e.exports.array=(t,e)=>Vt(t,{...e,array:!0}),_e.exports.MaxBufferError=So;var ia=_e.exports,xo=ve(ia);const{PassThrough:aa}=It;var ca=function(){var t=[],e=new aa({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()}},la=ve(ca);const Io=t=>{if(t!==void 0)throw new TypeError("The `input` and `inputFile` options cannot be both set.")},ua=({input:t,inputFile:e})=>typeof e!="string"?t:(Io(t),jn(e)),da=t=>{const e=ua(t);if(Yt(e))throw new TypeError("The `input` option cannot be a stream in sync mode");return e},ma=({input:t,inputFile:e})=>typeof e!="string"?t:(Io(t),Tn(e)),fa=(t,e)=>{const r=ma(e);r!==void 0&&(Yt(r)?r.pipe(t.stdin):t.stdin.end(r))},pa=(t,{all:e})=>{if(!e||!t.stdout&&!t.stderr)return;const r=la();return t.stdout&&r.add(t.stdout),t.stderr&&r.add(t.stderr),r},qt=async(t,e)=>{if(!(!t||e===void 0)){t.destroy();try{return await e}catch(r){return r.bufferedData}}},Xt=(t,{encoding:e,buffer:r,maxBuffer:o})=>{if(!(!t||!r))return e?xo(t,{encoding:e,maxBuffer:o}):xo.buffer(t,{maxBuffer:o})},ha=async({stdout:t,stderr:e,all:r},{encoding:o,buffer:n,maxBuffer:s},i)=>{const l=Xt(t,{encoding:o,buffer:n,maxBuffer:s}),a=Xt(e,{encoding:o,buffer:n,maxBuffer:s}),d=Xt(r,{encoding:o,buffer:n,maxBuffer:s*2});try{return await Promise.all([i,l,a,d])}catch(c){return Promise.all([{error:c,signal:c.signal,timedOut:c.timedOut},qt(t,l),qt(e,a),qt(r,d)])}},ga=(async()=>{})().constructor.prototype,ya=["then","catch","finally"].map(t=>[t,Reflect.getOwnPropertyDescriptor(ga,t)]),Mo=(t,e)=>{for(const[r,o]of ya){const n=typeof e=="function"?(...s)=>Reflect.apply(o.value,e(),s):o.value.bind(e);Reflect.defineProperty(t,r,{...o,value:n})}},wa=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)})}),Ro=(t,e=[])=>Array.isArray(e)?[t,...e]:[t],va=/^[\w.-]+$/,Ca=/"/g,ba=t=>typeof t!="string"||va.test(t)?t:`"${t.replace(Ca,'\\"')}"`,Do=(t,e)=>Ro(t,e).join(" "),Oo=(t,e)=>Ro(t,e).map(r=>ba(r)).join(" "),No=/ +/g,Fo=t=>{const e=[];for(const r of t.trim().split(No)){const o=e[e.length-1];o&&o.endsWith("\\")?e[e.length-1]=`${o.slice(0,-1)} ${r}`:e.push(r)}return e},_o=t=>{const e=typeof t;if(e==="string")return t;if(e==="number")return String(t);if(e==="object"&&t!==null&&!(t instanceof Nr)&&"stdout"in t){const r=typeof t.stdout;if(r==="string")return t.stdout;if(Or.isBuffer(t.stdout))return t.stdout.toString();throw new TypeError(`Unexpected "${r}" stdout in template expression`)}throw new TypeError(`Unexpected "${e}" in template expression`)},Lo=(t,e,r)=>r||t.length===0||e.length===0?[...t,...e]:[...t.slice(0,-1),`${t[t.length-1]}${e[0]}`,...e.slice(1)],Ea=({templates:t,expressions:e,tokens:r,index:o,template:n})=>{const s=n??t.raw[o],i=s.split(No).filter(Boolean),l=Lo(r,i,s.startsWith(" "));if(o===e.length)return l;const a=e[o],d=Array.isArray(a)?a.map(c=>_o(c)):[_o(a)];return Lo(l,d,s.endsWith(" "))},To=(t,e)=>{let r=[];for(const[o,n]of t.entries())r=Ea({templates:t,expressions:e,tokens:r,index:o,template:n});return r},Pa=Hn("execa").enabled,ct=(t,e)=>String(t).padStart(e,"0"),$a=()=>{const t=new Date;return`${ct(t.getHours(),2)}:${ct(t.getMinutes(),2)}:${ct(t.getSeconds(),2)}.${ct(t.getMilliseconds(),3)}`},jo=(t,{verbose:e})=>{e&&se.stderr.write(`[${$a()}] ${t}
|
|
8
|
+
`)},Aa=1e3*1e3*100,ka=({env:t,extendEnv:e,preferLocal:r,localDir:o,execPath:n})=>{const s=e?{...se.env,...t}:t;return r?di({env:s,cwd:o,execPath:n}):s},Bo=(t,e,r={})=>{const o=ii._parse(t,e,r);return t=o.command,e=o.args,r=o.options,r={maxBuffer:Aa,buffer:!0,stripFinalNewline:!0,extendEnv:!0,preferLocal:!1,localDir:r.cwd||se.cwd(),execPath:se.execPath,encoding:"utf8",reject:!0,cleanup:!0,all:!1,windowsHide:!0,verbose:Pa,...r},r.env=ka(r),r.stdio=Eo(r),se.platform==="win32"&&fe.basename(t,".exe")==="cmd"&&e.unshift("/q"),{file:t,args:e,options:r,parsed:o}},Le=(t,e,r)=>typeof e!="string"&&!Or.isBuffer(e)?r===void 0?void 0:"":t.stripFinalNewline?ai(e):e;function x(t,e,r){const o=Bo(t,e,r),n=Do(t,e),s=Oo(t,e);jo(s,o.options),Vi(o.options);let i;try{i=xt.spawn(o.file,o.args,o.options)}catch(p){const h=new xt.ChildProcess,y=Promise.reject(nt({error:p,stdout:"",stderr:"",all:"",command:n,escapedCommand:s,parsed:o,timedOut:!1,isCanceled:!1,killed:!1}));return Mo(h,y),h}const l=wa(i),a=Ji(i,o.options,l),d=qi(i,o.options,a),c={isCanceled:!1};i.kill=Gi.bind(null,i.kill.bind(i)),i.cancel=Wi.bind(null,i,c);const f=wo(async()=>{const[{error:p,exitCode:h,signal:y,timedOut:g},v,b,E]=await ha(i,o.options,d),k=Le(o.options,v),$=Le(o.options,b),P=Le(o.options,E);if(p||h!==0||y!==null){const R=nt({error:p,exitCode:h,signal:y,stdout:k,stderr:$,all:P,command:n,escapedCommand:s,parsed:o,timedOut:g,isCanceled:c.isCanceled||(o.options.signal?o.options.signal.aborted:!1),killed:i.killed});if(!o.options.reject)return R;throw R}return{command:n,escapedCommand:s,exitCode:0,stdout:k,stderr:$,all:P,failed:!1,timedOut:!1,isCanceled:!1,killed:!1}});return fa(i,o.options),i.all=pa(i,o.options),Qi(i),Mo(i,f),i}function Qt(t,e,r){const o=Bo(t,e,r),n=Do(t,e),s=Oo(t,e);jo(s,o.options);const i=da(o.options);let l;try{l=xt.spawnSync(o.file,o.args,{...o.options,input:i})}catch(c){throw nt({error:c,stdout:"",stderr:"",all:"",command:n,escapedCommand:s,parsed:o,timedOut:!1,isCanceled:!1,killed:!1})}const a=Le(o.options,l.stdout,l.error),d=Le(o.options,l.stderr,l.error);if(l.error||l.status!==0||l.signal!==null){const c=nt({stdout:a,stderr:d,error:l.error,signal:l.signal,exitCode:l.status,command:n,escapedCommand:s,parsed:o,timedOut:l.error&&l.error.code==="ETIMEDOUT",isCanceled:!1,killed:l.signal!==null});if(!o.options.reject)return c;throw c}return{command:n,escapedCommand:s,exitCode:0,stdout:a,stderr:d,failed:!1,timedOut:!1,isCanceled:!1,killed:!1}}const Sa=({input:t,inputFile:e,stdio:r})=>t===void 0&&e===void 0&&r===void 0?{stdin:"inherit"}:{},Go=(t={})=>({preferLocal:!0,...Sa(t),...t});function Ho(t){function e(r,...o){if(!Array.isArray(r))return Ho({...t,...r});const[n,...s]=To(r,o);return x(n,s,Go(t))}return e.sync=(r,...o)=>{if(!Array.isArray(r))throw new TypeError("Please use $(options).sync`command` instead of $.sync(options)`command`.");const[n,...s]=To(r,o);return Qt(n,s,Go(t))},e}const xa=Ho();function Ia(t,e){const[r,...o]=Fo(t);return x(r,o,e)}function Ma(t,e){const[r,...o]=Fo(t);return Qt(r,o,e)}function Ra(t,e,r={}){e&&!Array.isArray(e)&&typeof e=="object"&&(r=e,e=[]);const o=Di(r),n=se.execArgv.filter(l=>!l.startsWith("--inspect")),{nodePath:s=se.execPath,nodeOptions:i=n}=r;return x(s,[...i,t,...Array.isArray(e)?e:[]],{...r,stdin:void 0,stdout:void 0,stderr:void 0,stdio:o,shell:!1})}var Da=Object.freeze({__proto__:null,execa:x,execaSync:Qt,$:xa,execaCommand:Ia,execaCommandSync:Ma,execaNode:Ra});const{hasOwnProperty:Zt}=Object.prototype,lt=typeof process<"u"&&process.platform==="win32"?`\r
|
|
9
9
|
`:`
|
|
10
|
-
`,er=(
|
|
10
|
+
`,er=(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 l of i)o+=$e(s+"[]")+n+$e(l)+lt;else i&&typeof i=="object"?r.push(s):o+=$e(s)+n+$e(i)+lt}e.section&&o.length&&(o="["+$e(e.section)+"]"+lt+o);for(const s of r){const i=Uo(s).join("\\."),l=(e.section?e.section+".":"")+i,{whitespace:a}=e,d=er(t[s],{section:l,whitespace:a});o.length&&d.length&&(o+=lt),o+=d}return o},Uo=t=>t.replace(/\1/g,"LITERAL\\1LITERAL").replace(/\\\./g,"").split(/\./).map(e=>e.replace(/\1/g,"\\.").replace(/\2LITERAL\\1LITERAL\2/g,"")),zo=t=>{const e=Object.create(null);let r=e,o=null;const n=/^\[([^\]]*)\]$|^([^=]+)(=(.*))?$/i,s=t.split(/[\r\n]+/g);for(const l of s){if(!l||l.match(/^\s*[;#]/))continue;const a=l.match(n);if(!a)continue;if(a[1]!==void 0){if(o=ut(a[1]),o==="__proto__"){r=Object.create(null);continue}r=e[o]=e[o]||Object.create(null);continue}const d=ut(a[2]),c=d.length>2&&d.slice(-2)==="[]",u=c?d.slice(0,-2):d;if(u==="__proto__")continue;const f=a[3]?ut(a[4]):!0,p=f==="true"||f==="false"||f==="null"?JSON.parse(f):f;c&&(Zt.call(r,u)?Array.isArray(r[u])||(r[u]=[r[u]]):r[u]=[]),Array.isArray(r[u])?r[u].push(p):r[u]=p}const i=[];for(const l of Object.keys(e)){if(!Zt.call(e,l)||typeof e[l]!="object"||Array.isArray(e[l]))continue;const a=Uo(l);r=e;const d=a.pop(),c=d.replace(/\\\./g,".");for(const u of a)u!=="__proto__"&&((!Zt.call(r,u)||typeof r[u]!="object")&&(r[u]=Object.create(null)),r=r[u]);r===e&&c===d||(r[c]=e[l],i.push(l))}for(const l of i)delete e[l];return e},Ko=t=>t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'"),$e=t=>typeof t!="string"||t.match(/[=\r\n]/)||t.match(/^\[/)||t.length>1&&Ko(t)||t!==t.trim()?JSON.stringify(t):t.split(";").join("\\;").split("#").join("\\#"),ut=(t,e)=>{if(t=(t||"").trim(),Ko(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 Oa={parse:zo,decode:zo,stringify:er,encode:er,safe:$e,unsafe:ut},Ae=ve(Oa);class w extends Error{}const tr=" ",de=t=>{t instanceof Error&&(t instanceof w||(t.stack&&console.error(C.dim(t.stack.split(`
|
|
11
11
|
`).slice(1).join(`
|
|
12
12
|
`))),console.error(`
|
|
13
|
-
${tr}${C.dim(`aicommit2 v${
|
|
14
|
-
${tr}Please open a Bug report with the information above:`),console.error(`${tr}https://github.com/tak-bro/aicommit2/issues/new/choose`)))},zo=r=>L.lstat(r).then(()=>!0,()=>!1),Ko=async r=>{try{await L.mkdir(r,{recursive:!0})}catch(e){if(e.code!=="EEXIST")throw e}},ut=r=>r&&`${r[0].toUpperCase()}${r.slice(1)}`,dt=(r,e)=>{const t=Math.ceil(r),o=Math.floor(e);return Math.floor(Math.random()*(o-t+1))+t},Na=(r,e)=>r.disabled&&!e.disabled?1:!r.disabled&&e.disabled?-1:0,mt=r=>r.reduce((e,t)=>Array.isArray(t)?e.concat(mt(t)):e.concat(t),[]),Wo=(r,e=5)=>r.replace(/[\n\r]/g,"").split(" ").slice(0,e).join(" "),Fa=r=>{let e=0;for(let t=0;t<r.length;t++){const o=r.charCodeAt(t);e=(e<<5)-e+o,e=e&e}return Math.abs(e)},La=r=>{const e=r%360,t=65+r%15,o=45+r%10;return`hsl(${e}, ${t}%, ${o}%)`},_a=r=>{const[e,t,o]=r.match(/\d+/g).map((u,f)=>f===0?Number(u):Number(u)/100),n=(1-Math.abs(2*o-1))*t,s=n*(1-Math.abs(e/60%2-1)),i=o-n/2;let l,a,d;e<60?[l,a,d]=[n,s,0]:e<120?[l,a,d]=[s,n,0]:e<180?[l,a,d]=[0,n,s]:e<240?[l,a,d]=[0,s,n]:e<300?[l,a,d]=[s,0,n]:[l,a,d]=[n,0,s];const c=u=>{const f=Math.round((u+i)*255).toString(16);return f.length===1?"0"+f:f};return`#${c(l)}${c(a)}${c(d)}`},Ta=r=>{const e=Fa(r),t=La(e);return{primary:_a(t),secondary:"#FFFFFF"}},Yo=r=>{try{return{ok:!0,data:JSON.parse(r)}}catch(e){return{ok:!1,error:e}}},ft=r=>{if(!r||typeof r!="string")return"";if(I.isAbsolute(r))return I.resolve(r);if(Te){const e=I.dirname(Te),t=I.join(e,r);return I.resolve(t)}else return""},ja=["","conventional","gitmoji"],rr="http://localhost:11434",{hasOwnProperty:Ba}=Object.prototype,or=(r,e)=>Ba.call(r,e),ke=["OPENAI","OLLAMA","HUGGINGFACE","GEMINI","ANTHROPIC","MISTRAL","CODESTRAL","COHERE","GROQ","PERPLEXITY","DEEPSEEK","GITHUB_MODELS","BEDROCK"],Jo=r=>{const e=De.platform(),t=De.homedir();let o,n;switch(r){case"config":o=process.env.XDG_CONFIG_HOME;break;case"data":o=process.env.XDG_DATA_HOME;break;case"cache":o=process.env.XDG_CACHE_HOME;break;case"state":o=process.env.XDG_STATE_HOME;break;default:o=void 0}if(e==="darwin")r==="cache"?n=I.join(t,"Library","Caches"):n=I.join(t,"Library","Application Support");else if(e==="win32")n=process.env.LOCALAPPDATA||t;else switch(r){case"config":n=I.join(t,".config");break;case"data":n=I.join(t,".local","share");break;case"cache":n=I.join(t,".cache");break;case"state":n=I.join(t,".local","state");break;default:n=t}return o||n},Ga=I.join(Jo("config"),"aicommit2"),ie=I.join(Jo("state"),"aicommit2","logs"),Vo=I.join(Ga,"config.ini"),qo=I.join(ie,"aicommit2-%DATE%.log"),Xo=I.join(ie,"exceptions-%DATE%.log"),Ha=r=>{const e=Object.keys(r),t=new Set([...ke,...e.filter(o=>/^[A-Z][A-Z0-9_]*$/.test(o))]);return Array.from(t)},M=(r,e,t)=>{if(!e)throw new w(`Invalid config property ${r}: ${t}`)},ue=(r,e=!1)=>t=>typeof t=="boolean"?t:t==null?e:(M(r,/^(?:true|false)$/.test(t),"Must be a boolean(true or false)"),t==="true"),m={systemPrompt(r){return r||""},systemPromptPath(r){return r||""},codeReviewPromptPath(r){return r||""},timeout(r){if(!r)return 6e4;M("timeout",/^\d+$/.test(r),"Must be an integer");const e=Number(r);return M("timeout",e>=500,"Must be greater than 500ms"),e},temperature(r){if(!r)return .7;M("temperature",/^(2|\d)(\.\d{1,2})?$/.test(r),"Must be decimal between 0 and 2");const e=Number(r);return M("temperature",e>0,"Must be greater than 0"),M("temperature",e<=2,"Must be less than or equal to 2"),e},maxTokens(r){return r?(M("maxTokens",/^\d+$/.test(r),"Must be an integer"),Number(r)):8192},logLevel(r){return r?(M("logLevel",/^(?:error|warn|info|http|verbose|debug|silly)$/.test(r),"Must be a valid log level (error, warn, info, http, verbose, debug, silly)"),r):"info"},logFilePath(r){return r||qo},exceptionLogFilePath(r){return r||Xo},locale(r){return r?(M("locale",r,"Cannot be empty"),M("locale",/^[a-z-]+$/i.test(r),"Must be a valid locale (letters and dashes/underscores). You can consult the list of codes in: https://wikipedia.org/wiki/List_of_ISO_639-1_codes"),r):"en"},generate(r){if(!r)return 1;M("generate",/^\d+$/.test(r),"Must be an integer");const e=Number(r);return M("generate",e>0,"Must be greater than 0"),M("generate",e<=5,"Must be less or equal to 5"),e},type(r){return r?(M("type",ja.includes(r),"Invalid commit type"),r):"conventional"},maxLength(r){if(!r)return 50;M("maxLength",/^\d+$/.test(r),"Must be an integer");const e=Number(r);return M("maxLength",e>=20,"Must be greater than 20 characters"),e},exclude:r=>r?(typeof r=="string"?r?.split(","):r).map(t=>t.trim()).filter(t=>!!t&&t.length>0):[],topP:r=>{if(!r)return .9;M("topP",/^(1|\d)(\.\d{1,2})?$/.test(r),"Must be decimal between 0 and 1");const e=Number(r);return M("topP",e>0,"Must be greater than 0"),M("topP",e<=1,"Must be less than or equal to 1"),e},logging:ue("logging",!0),includeBody:ue("includeBody"),codeReview:ue("codeReview"),disabled:ue("disabled"),watchMode:ue("watchMode"),forceGit:ue("forceGit"),disableLowerCase:ue("disableLowerCase")},_e={OPENAI:{key:r=>r||"",envKey:r=>r||"",model:r=>r?(typeof r=="string"?r?.split(","):r).map(t=>t.trim()).filter(t=>!!t&&t.length>0):["gpt-4o-mini"],url:r=>r?(M("OPENAI.url",/^https?:\/\//.test(r),"Must be a valid URL"),r):"https://api.openai.com",path:r=>r||"/v1/chat/completions",proxy:r=>r||"",topP:m.topP,systemPrompt:m.systemPrompt,systemPromptPath:m.systemPromptPath,codeReviewPromptPath:m.codeReviewPromptPath,timeout:m.timeout,temperature:m.temperature,maxTokens:m.maxTokens,logging:m.logging,locale:m.locale,generate:m.generate,type:m.type,maxLength:m.maxLength,includeBody:m.includeBody,codeReview:m.codeReview,disabled:m.disabled,watchMode:m.watchMode,disableLowerCase:m.disableLowerCase},HUGGINGFACE:{cookie:r=>r||"",model:r=>r?(typeof r=="string"?r?.split(","):r).map(t=>t.trim()).filter(t=>!!t&&t.length>0):["CohereForAI/c4ai-command-r-plus"],systemPrompt:m.systemPrompt,systemPromptPath:m.systemPromptPath,codeReviewPromptPath:m.codeReviewPromptPath,timeout:m.timeout,temperature:m.temperature,maxTokens:m.maxTokens,topP:m.topP,logging:m.logging,locale:m.locale,generate:m.generate,type:m.type,maxLength:m.maxLength,includeBody:m.includeBody,codeReview:m.codeReview,disabled:m.disabled,watchMode:m.watchMode,disableLowerCase:m.disableLowerCase},GEMINI:{key:r=>r||"",envKey:r=>r||"",model:r=>r?(typeof r=="string"?r?.split(","):r).map(t=>t.trim()).filter(t=>!!t&&t.length>0):["gemini-2.5-flash"],systemPrompt:m.systemPrompt,systemPromptPath:m.systemPromptPath,codeReviewPromptPath:m.codeReviewPromptPath,timeout:m.timeout,temperature:m.temperature,maxTokens:m.maxTokens,logging:m.logging,locale:m.locale,generate:m.generate,type:m.type,maxLength:m.maxLength,includeBody:m.includeBody,topP:m.topP,codeReview:m.codeReview,disabled:m.disabled,watchMode:m.watchMode,disableLowerCase:m.disableLowerCase},ANTHROPIC:{key:r=>r||"",envKey:r=>r||"",model:r=>r?(typeof r=="string"?r?.split(","):r).map(t=>t.trim()).filter(t=>!!t&&t.length>0):["claude-3-5-haiku-20241022"],systemPrompt:m.systemPrompt,systemPromptPath:m.systemPromptPath,codeReviewPromptPath:m.codeReviewPromptPath,timeout:m.timeout,temperature:m.temperature,maxTokens:m.maxTokens,logging:m.logging,locale:m.locale,generate:m.generate,type:m.type,maxLength:m.maxLength,includeBody:m.includeBody,topP:m.topP,codeReview:m.codeReview,disabled:m.disabled,watchMode:m.watchMode,disableLowerCase:m.disableLowerCase},MISTRAL:{key:r=>r||"",envKey:r=>r||"",model:r=>r?(typeof r=="string"?r?.split(","):r).map(t=>t.trim()).filter(t=>!!t&&t.length>0):["mistral-small-latest"],systemPrompt:m.systemPrompt,systemPromptPath:m.systemPromptPath,codeReviewPromptPath:m.codeReviewPromptPath,timeout:m.timeout,temperature:m.temperature,maxTokens:m.maxTokens,logging:m.logging,locale:m.locale,generate:m.generate,type:m.type,maxLength:m.maxLength,includeBody:m.includeBody,topP:m.topP,codeReview:m.codeReview,disabled:m.disabled,watchMode:m.watchMode,disableLowerCase:m.disableLowerCase},CODESTRAL:{key:r=>r||"",envKey:r=>r||"",model:r=>r?(typeof r=="string"?r?.split(","):r).map(t=>t.trim()).filter(t=>!!t&&t.length>0):["codestral-latest"],topP:m.topP,systemPrompt:m.systemPrompt,systemPromptPath:m.systemPromptPath,codeReviewPromptPath:m.codeReviewPromptPath,timeout:m.timeout,temperature:m.temperature,maxTokens:m.maxTokens,logging:m.logging,locale:m.locale,generate:m.generate,type:m.type,maxLength:m.maxLength,includeBody:m.includeBody,codeReview:m.codeReview,disabled:m.disabled,watchMode:m.watchMode,disableLowerCase:m.disableLowerCase},OLLAMA:{model:r=>r?(typeof r=="string"?r?.split(","):r).map(t=>t.trim()).filter(t=>!!t&&t.length>0):[],host:r=>r?(M("OLLAMA.host",/^https?:\/\//.test(r),"Must be a valid URL"),r):rr,timeout:r=>{if(!r)return 1e5;M("OLLAMA.timeout",/^\d+$/.test(r),"Must be an integer");const e=Number(r);return M("OLLAMA.timeout",e>=500,"Must be greater than 500ms"),e},auth:r=>r||"",key:r=>r||"",envKey:r=>r||"",numCtx:r=>{if(!r)return 2048;M("OLLAMA.numCtx",/^\d+$/.test(r),"Must be an integer");const e=Number(r);return M("OLLAMA.numCtx",e>=2048,"Must be greater than 2048"),e},systemPrompt:m.systemPrompt,systemPromptPath:m.systemPromptPath,codeReviewPromptPath:m.codeReviewPromptPath,temperature:m.temperature,maxTokens:m.maxTokens,logging:m.logging,locale:m.locale,generate:m.generate,type:m.type,maxLength:m.maxLength,includeBody:m.includeBody,topP:m.topP,codeReview:m.codeReview,disabled:m.disabled,watchMode:m.watchMode,disableLowerCase:m.disableLowerCase},COHERE:{key:r=>r||"",envKey:r=>r||"",url:r=>r?(M("COHERE.url",/^https?:\/\//.test(r),"Must be a valid URL"),r):"https://api.cohere.ai",model:r=>r?(typeof r=="string"?r?.split(","):r).map(t=>t.trim()).filter(t=>!!t&&t.length>0):["command-a-03-2025"],systemPrompt:m.systemPrompt,systemPromptPath:m.systemPromptPath,codeReviewPromptPath:m.codeReviewPromptPath,temperature:m.temperature,maxTokens:m.maxTokens,logging:m.logging,locale:m.locale,timeout:m.timeout,generate:m.generate,type:m.type,maxLength:m.maxLength,includeBody:m.includeBody,topP:m.topP,codeReview:m.codeReview,disabled:m.disabled,watchMode:m.watchMode,disableLowerCase:m.disableLowerCase},GROQ:{key:r=>r||"",envKey:r=>r||"",model:r=>r?(typeof r=="string"?r?.split(","):r).map(t=>t.trim()).filter(t=>!!t&&t.length>0):["llama-3.3-70b-versatile"],systemPrompt:m.systemPrompt,systemPromptPath:m.systemPromptPath,codeReviewPromptPath:m.codeReviewPromptPath,timeout:m.timeout,temperature:m.temperature,maxTokens:m.maxTokens,logging:m.logging,locale:m.locale,generate:m.generate,type:m.type,maxLength:m.maxLength,includeBody:m.includeBody,topP:m.topP,codeReview:m.codeReview,disabled:m.disabled,watchMode:m.watchMode,disableLowerCase:m.disableLowerCase},PERPLEXITY:{key:r=>r||"",envKey:r=>r||"",model:r=>r?(typeof r=="string"?r?.split(","):r).map(t=>t.trim()).filter(t=>!!t&&t.length>0):["sonar"],topP:m.topP,systemPrompt:m.systemPrompt,systemPromptPath:m.systemPromptPath,codeReviewPromptPath:m.codeReviewPromptPath,timeout:m.timeout,temperature:m.temperature,maxTokens:m.maxTokens,logging:m.logging,locale:m.locale,generate:m.generate,type:m.type,maxLength:m.maxLength,includeBody:m.includeBody,codeReview:m.codeReview,disabled:m.disabled,watchMode:m.watchMode,disableLowerCase:m.disableLowerCase},DEEPSEEK:{key:r=>r||"",envKey:r=>r||"",model:r=>r?(typeof r=="string"?r?.split(","):r).map(t=>t.trim()).filter(t=>!!t&&t.length>0):["deepseek-coder"],topP:m.topP,systemPrompt:m.systemPrompt,systemPromptPath:m.systemPromptPath,codeReviewPromptPath:m.codeReviewPromptPath,timeout:m.timeout,temperature:m.temperature,maxTokens:m.maxTokens,logging:m.logging,locale:m.locale,generate:m.generate,type:m.type,maxLength:m.maxLength,includeBody:m.includeBody,codeReview:m.codeReview,disabled:m.disabled,watchMode:m.watchMode,disableLowerCase:m.disableLowerCase},GITHUB_MODELS:{key:r=>r||"",envKey:r=>r||"",model:r=>r?(typeof r=="string"?r?.split(","):r).map(t=>t.trim()).filter(t=>!!t&&t.length>0):["gpt-4o-mini"],systemPrompt:m.systemPrompt,systemPromptPath:m.systemPromptPath,codeReviewPromptPath:m.codeReviewPromptPath,timeout:m.timeout,temperature:m.temperature,maxTokens:m.maxTokens,logging:m.logging,locale:m.locale,generate:m.generate,type:m.type,maxLength:m.maxLength,includeBody:m.includeBody,topP:m.topP,codeReview:m.codeReview,disabled:m.disabled,watchMode:m.watchMode,disableLowerCase:m.disableLowerCase},BEDROCK:{key:r=>r||"",envKey:r=>r&&r.length>0?r:"BEDROCK_API_KEY",model:r=>r?(typeof r=="string"?r?.split(","):r).map(t=>{const o=t.trim();return o&&!o.includes(".")&&!o.includes(":")&&console.warn(`[Bedrock] Model ID "${o}" may be invalid.
|
|
13
|
+
${tr}${C.dim(`aicommit2 v${eo}`)}`),console.error(`
|
|
14
|
+
${tr}Please open a Bug report with the information above:`),console.error(`${tr}https://github.com/tak-bro/aicommit2/issues/new/choose`)))},Wo=t=>F.lstat(t).then(()=>!0,()=>!1),Yo=async t=>{try{await F.mkdir(t,{recursive:!0})}catch(e){if(e.code!=="EEXIST")throw e}},dt=t=>t&&`${t[0].toUpperCase()}${t.slice(1)}`,mt=(t,e)=>{const r=Math.ceil(t),o=Math.floor(e);return Math.floor(Math.random()*(o-r+1))+r},Na=(t,e)=>t.disabled&&!e.disabled?1:!t.disabled&&e.disabled?-1:0,ft=t=>t.reduce((e,r)=>Array.isArray(r)?e.concat(ft(r)):e.concat(r),[]),Jo=(t,e=5)=>t.replace(/[\n\r]/g,"").split(" ").slice(0,e).join(" "),Fa=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)},_a=t=>{const e=t%360,r=65+t%15,o=45+t%10;return`hsl(${e}, ${r}%, ${o}%)`},La=t=>{const[e,r,o]=t.match(/\d+/g).map((u,f)=>f===0?Number(u):Number(u)/100),n=(1-Math.abs(2*o-1))*r,s=n*(1-Math.abs(e/60%2-1)),i=o-n/2;let l,a,d;e<60?[l,a,d]=[n,s,0]:e<120?[l,a,d]=[s,n,0]:e<180?[l,a,d]=[0,n,s]:e<240?[l,a,d]=[0,s,n]:e<300?[l,a,d]=[s,0,n]:[l,a,d]=[n,0,s];const c=u=>{const f=Math.round((u+i)*255).toString(16);return f.length===1?"0"+f:f};return`#${c(l)}${c(a)}${c(d)}`},Ta=t=>{const e=Fa(t),r=_a(e);return{primary:La(r),secondary:"#FFFFFF"}},Vo=t=>{try{return{ok:!0,data:JSON.parse(t)}}catch(e){return{ok:!1,error:e}}},pt=t=>{if(!t||typeof t!="string")return"";if(I.isAbsolute(t))return I.resolve(t);if(je){const e=I.dirname(je),r=I.join(e,t);return I.resolve(r)}else return""},ja=["","conventional","gitmoji"],rr="http://localhost:11434",{hasOwnProperty:Ba}=Object.prototype,or=(t,e)=>Ba.call(t,e),nr=["OPENAI","OLLAMA","HUGGINGFACE","GEMINI","ANTHROPIC","MISTRAL","CODESTRAL","COHERE","GROQ","PERPLEXITY","DEEPSEEK","GITHUB_MODELS","BEDROCK"],qo=t=>{const e=Oe.platform(),r=Oe.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=I.join(r,"Library","Caches"):n=I.join(r,"Library","Application Support");else if(e==="win32")n=process.env.LOCALAPPDATA||r;else switch(t){case"config":n=I.join(r,".config");break;case"data":n=I.join(r,".local","share");break;case"cache":n=I.join(r,".cache");break;case"state":n=I.join(r,".local","state");break;default:n=r}return o||n},Ga=I.join(qo("config"),"aicommit2"),ie=I.join(qo("state"),"aicommit2","logs"),Xo=I.join(Ga,"config.ini"),Qo=I.join(ie,"aicommit2-%DATE%.log"),Zo=I.join(ie,"exceptions-%DATE%.log"),Ha=t=>{const e=Object.keys(t),r=new Set([...nr,...e.filter(o=>/^[A-Z][A-Z0-9_]*$/.test(o))]);return Array.from(r)},M=(t,e,r)=>{if(!e)throw new w(`Invalid config property ${t}: ${r}`)},ue=(t,e=!1)=>r=>typeof r=="boolean"?r:r==null?e:(M(t,/^(?:true|false)$/.test(r),"Must be a boolean(true or false)"),r==="true"),m={systemPrompt(t){return t||""},systemPromptPath(t){return t||""},codeReviewPromptPath(t){return t||""},timeout(t){if(!t)return 6e4;M("timeout",/^\d+$/.test(t),"Must be an integer");const e=Number(t);return M("timeout",e>=500,"Must be greater than 500ms"),e},temperature(t){if(!t)return .7;M("temperature",/^(2|\d)(\.\d{1,2})?$/.test(t),"Must be decimal between 0 and 2");const e=Number(t);return M("temperature",e>0,"Must be greater than 0"),M("temperature",e<=2,"Must be less than or equal to 2"),e},maxTokens(t){return t?(M("maxTokens",/^\d+$/.test(t),"Must be an integer"),Number(t)):8192},logLevel(t){return t?(M("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||Qo},exceptionLogFilePath(t){return t||Zo},locale(t){return t?(M("locale",t,"Cannot be empty"),M("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;M("generate",/^\d+$/.test(t),"Must be an integer");const e=Number(t);return M("generate",e>0,"Must be greater than 0"),M("generate",e<=5,"Must be less or equal to 5"),e},type(t){return t?(M("type",ja.includes(t),"Invalid commit type"),t):"conventional"},maxLength(t){if(!t)return 50;M("maxLength",/^\d+$/.test(t),"Must be an integer");const e=Number(t);return M("maxLength",e>=20,"Must be greater than 20 characters"),e},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;M("topP",/^(1|\d)(\.\d{1,2})?$/.test(t),"Must be decimal between 0 and 1");const e=Number(t);return M("topP",e>0,"Must be greater than 0"),M("topP",e<=1,"Must be less than or equal to 1"),e},logging:ue("logging",!0),includeBody:ue("includeBody"),codeReview:ue("codeReview"),disabled:ue("disabled"),watchMode:ue("watchMode"),forceGit:ue("forceGit"),disableLowerCase:ue("disableLowerCase")},Te={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?(M("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:m.topP,systemPrompt:m.systemPrompt,systemPromptPath:m.systemPromptPath,codeReviewPromptPath:m.codeReviewPromptPath,timeout:m.timeout,temperature:m.temperature,maxTokens:m.maxTokens,logging:m.logging,locale:m.locale,generate:m.generate,type:m.type,maxLength:m.maxLength,includeBody:m.includeBody,codeReview:m.codeReview,disabled:m.disabled,watchMode:m.watchMode,disableLowerCase:m.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:m.systemPrompt,systemPromptPath:m.systemPromptPath,codeReviewPromptPath:m.codeReviewPromptPath,timeout:m.timeout,temperature:m.temperature,maxTokens:m.maxTokens,topP:m.topP,logging:m.logging,locale:m.locale,generate:m.generate,type:m.type,maxLength:m.maxLength,includeBody:m.includeBody,codeReview:m.codeReview,disabled:m.disabled,watchMode:m.watchMode,disableLowerCase:m.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.5-flash"],systemPrompt:m.systemPrompt,systemPromptPath:m.systemPromptPath,codeReviewPromptPath:m.codeReviewPromptPath,timeout:m.timeout,temperature:m.temperature,maxTokens:m.maxTokens,logging:m.logging,locale:m.locale,generate:m.generate,type:m.type,maxLength:m.maxLength,includeBody:m.includeBody,topP:m.topP,codeReview:m.codeReview,disabled:m.disabled,watchMode:m.watchMode,disableLowerCase:m.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:m.systemPrompt,systemPromptPath:m.systemPromptPath,codeReviewPromptPath:m.codeReviewPromptPath,timeout:m.timeout,temperature:m.temperature,maxTokens:m.maxTokens,logging:m.logging,locale:m.locale,generate:m.generate,type:m.type,maxLength:m.maxLength,includeBody:m.includeBody,topP:m.topP,codeReview:m.codeReview,disabled:m.disabled,watchMode:m.watchMode,disableLowerCase:m.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:m.systemPrompt,systemPromptPath:m.systemPromptPath,codeReviewPromptPath:m.codeReviewPromptPath,timeout:m.timeout,temperature:m.temperature,maxTokens:m.maxTokens,logging:m.logging,locale:m.locale,generate:m.generate,type:m.type,maxLength:m.maxLength,includeBody:m.includeBody,topP:m.topP,codeReview:m.codeReview,disabled:m.disabled,watchMode:m.watchMode,disableLowerCase:m.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:m.topP,systemPrompt:m.systemPrompt,systemPromptPath:m.systemPromptPath,codeReviewPromptPath:m.codeReviewPromptPath,timeout:m.timeout,temperature:m.temperature,maxTokens:m.maxTokens,logging:m.logging,locale:m.locale,generate:m.generate,type:m.type,maxLength:m.maxLength,includeBody:m.includeBody,codeReview:m.codeReview,disabled:m.disabled,watchMode:m.watchMode,disableLowerCase:m.disableLowerCase},OLLAMA:{model:t=>t?(typeof t=="string"?t?.split(","):t).map(r=>r.trim()).filter(r=>!!r&&r.length>0):[],host:t=>t?(M("OLLAMA.host",/^https?:\/\//.test(t),"Must be a valid URL"),t):rr,timeout:t=>{if(!t)return 1e5;M("OLLAMA.timeout",/^\d+$/.test(t),"Must be an integer");const e=Number(t);return M("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;M("OLLAMA.numCtx",/^\d+$/.test(t),"Must be an integer");const e=Number(t);return M("OLLAMA.numCtx",e>=2048,"Must be greater than 2048"),e},systemPrompt:m.systemPrompt,systemPromptPath:m.systemPromptPath,codeReviewPromptPath:m.codeReviewPromptPath,temperature:m.temperature,maxTokens:m.maxTokens,logging:m.logging,locale:m.locale,generate:m.generate,type:m.type,maxLength:m.maxLength,includeBody:m.includeBody,topP:m.topP,codeReview:m.codeReview,disabled:m.disabled,watchMode:m.watchMode,disableLowerCase:m.disableLowerCase},COHERE:{key:t=>t||"",envKey:t=>t||"",url:t=>t?(M("COHERE.url",/^https?:\/\//.test(t),"Must be a valid URL"),t):"https://api.cohere.ai",model:t=>t?(typeof t=="string"?t?.split(","):t).map(r=>r.trim()).filter(r=>!!r&&r.length>0):["command-a-03-2025"],systemPrompt:m.systemPrompt,systemPromptPath:m.systemPromptPath,codeReviewPromptPath:m.codeReviewPromptPath,temperature:m.temperature,maxTokens:m.maxTokens,logging:m.logging,locale:m.locale,timeout:m.timeout,generate:m.generate,type:m.type,maxLength:m.maxLength,includeBody:m.includeBody,topP:m.topP,codeReview:m.codeReview,disabled:m.disabled,watchMode:m.watchMode,disableLowerCase:m.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:m.systemPrompt,systemPromptPath:m.systemPromptPath,codeReviewPromptPath:m.codeReviewPromptPath,timeout:m.timeout,temperature:m.temperature,maxTokens:m.maxTokens,logging:m.logging,locale:m.locale,generate:m.generate,type:m.type,maxLength:m.maxLength,includeBody:m.includeBody,topP:m.topP,codeReview:m.codeReview,disabled:m.disabled,watchMode:m.watchMode,disableLowerCase:m.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:m.topP,systemPrompt:m.systemPrompt,systemPromptPath:m.systemPromptPath,codeReviewPromptPath:m.codeReviewPromptPath,timeout:m.timeout,temperature:m.temperature,maxTokens:m.maxTokens,logging:m.logging,locale:m.locale,generate:m.generate,type:m.type,maxLength:m.maxLength,includeBody:m.includeBody,codeReview:m.codeReview,disabled:m.disabled,watchMode:m.watchMode,disableLowerCase:m.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:m.topP,systemPrompt:m.systemPrompt,systemPromptPath:m.systemPromptPath,codeReviewPromptPath:m.codeReviewPromptPath,timeout:m.timeout,temperature:m.temperature,maxTokens:m.maxTokens,logging:m.logging,locale:m.locale,generate:m.generate,type:m.type,maxLength:m.maxLength,includeBody:m.includeBody,codeReview:m.codeReview,disabled:m.disabled,watchMode:m.watchMode,disableLowerCase:m.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:m.systemPrompt,systemPromptPath:m.systemPromptPath,codeReviewPromptPath:m.codeReviewPromptPath,timeout:m.timeout,temperature:m.temperature,maxTokens:m.maxTokens,logging:m.logging,locale:m.locale,generate:m.generate,type:m.type,maxLength:m.maxLength,includeBody:m.includeBody,topP:m.topP,codeReview:m.codeReview,disabled:m.disabled,watchMode:m.watchMode,disableLowerCase:m.disableLowerCase},BEDROCK:{key:t=>t||"",envKey:t=>t&&t.length>0?t:"BEDROCK_API_KEY",model:t=>t?(typeof t=="string"?t?.split(","):t).map(r=>{const o=r.trim();return o&&!o.includes(".")&&!o.includes(":")&&console.warn(`[Bedrock] Model ID "${o}" may be invalid.
|
|
15
15
|
Expected formats:
|
|
16
16
|
- Foundation model: "provider.model-name-version" (e.g., "anthropic.claude-haiku-4-5-20251001-v1:0")
|
|
17
17
|
- Inference profile: "prefix.provider.model-name-version" (e.g., "us.anthropic.claude-haiku-4-5-20251001-v1:0")
|
|
18
18
|
- ARN: Full Amazon Resource Name
|
|
19
|
-
See https://docs.aws.amazon.com/bedrock/latest/userguide/inference-profiles.html`),o}).filter(t=>!!t&&t.length>0):["anthropic.claude-haiku-4-5-20251001-v1:0"],runtimeMode:r=>{r&&console.warn("[Bedrock] DEPRECATION: runtimeMode is no longer used. Authentication method is now auto-detected from configured credentials.")},region:r=>r||process.env.AWS_REGION||process.env.AWS_DEFAULT_REGION||"",profile:r=>r||process.env.AWS_PROFILE||"",accessKeyId:r=>r||process.env.AWS_ACCESS_KEY_ID||"",secretAccessKey:r=>r||process.env.AWS_SECRET_ACCESS_KEY||"",sessionToken:r=>r||process.env.AWS_SESSION_TOKEN||"",applicationEndpointId:r=>r||process.env.BEDROCK_APPLICATION_ENDPOINT_ID||"",applicationInferenceProfileArn:r=>r||process.env.BEDROCK_APPLICATION_INFERENCE_PROFILE_ARN||process.env.BEDROCK_INFERENCE_PROFILE_ARN||"",applicationBaseUrl:r=>r||process.env.BEDROCK_APPLICATION_BASE_URL||"",systemPrompt:m.systemPrompt,systemPromptPath:m.systemPromptPath,codeReviewPromptPath:m.codeReviewPromptPath,timeout:m.timeout,temperature:r=>{if(!r)return;M("temperature",/^(2|\d)(\.\d{1,2})?$/.test(r),"Must be decimal between 0 and 2");const e=Number(r);return M("temperature",e>0,"Must be greater than 0"),M("temperature",e<=2,"Must be less than or equal to 2"),e},maxTokens:r=>{if(r)return M("maxTokens",/^\d+$/.test(r),"Must be an integer"),Number(r)},logging:m.logging,locale:m.locale,generate:m.generate,type:m.type,maxLength:m.maxLength,includeBody:m.includeBody,topP:r=>{if(!r)return;M("topP",/^(1|\d)(\.\d{1,2})?$/.test(r),"Must be decimal between 0 and 1");const e=Number(r);return M("topP",e>0,"Must be greater than 0"),M("topP",e<=1,"Must be less than or equal to 1"),e},codeReview:m.codeReview,disabled:m.disabled,watchMode:m.watchMode,disableLowerCase:m.disableLowerCase,inferenceParameters:r=>{if(!r)return{};if(typeof r=="object")return r;try{const e=JSON.parse(r);return M("BEDROCK.inferenceParameters",typeof e=="object"&&e!==null&&!Array.isArray(e),"Must be a valid JSON object"),e}catch(e){throw new w(`Invalid BEDROCK.inferenceParameters: Must be valid JSON. Error: ${e.message}`)}}}};let Te;const Ua=(r=[])=>{const e={};for(const t of r)if(t.startsWith("--")){const[o,n]=t.slice(2).split("="),[s,i]=o.split(".");s&&i&&s in _e?(e[s]||(e[s]={}),e[s][i]=n):e[o]=n}return e},za=()=>{const r=De.homedir(),e=process.env.AICOMMIT_CONFIG_PATH,t=Vo,o=I.join(r,".aicommit2");return[e,t,o].filter(n=>!!n)},Se=async()=>{const r=za();for(const e of r)if(await zo(e))return e;return Vo},Ka=r=>r.replace(/\$\{([a-zA-Z_][a-zA-Z0-9_]*)\}|\$([a-zA-Z_][a-zA-Z0-9_]*)/g,(e,t,o)=>{const n=t||o;return process.env[n]??""}),je=async()=>{const r=await Se();Te=r;try{const e=await L.readFile(r,"utf8"),t=Ka(e);return $e.parse(t)}catch(e){return e.code==="ENOENT"?(Te=void 0,{}):(console.error(`Error reading config file ${r}:`,e),Te=void 0,{})}},he=async(r,e=[])=>{const t=await je(),o=Ua(e),n={...r,...o},s={},i=Ha(t),l={};for(const d of i){const c=t[d]?.envKey;let u;c?(u=[c],d==="BEDROCK"&&c!=="BEDROCK_APPLICATION_API_KEY"&&u.push("BEDROCK_APPLICATION_API_KEY")):d==="BEDROCK"?u=["BEDROCK_API_KEY","BEDROCK_APPLICATION_API_KEY"]:u=[`${d}_API_KEY`];const f=u.map(p=>p?process.env[p]:void 0).find(p=>typeof p=="string"&&p.length>0);f&&(l[d]={key:f})}const a=(d,c)=>{const u=n[`${d}.${c}`]??n[d]?.[c],f=l[d]?.[c],p=t[d]?.[c],h=n[c]??t[c];return u!==void 0?u:f!==void 0?f:p!==void 0?p:h};for(const[d,c]of Object.entries(m)){const u=n[d]??t[d];s[d]=c(u)}for(const d of i){s[d]={};const c=_e[d]||pt(d);for(const[u,f]of Object.entries(c)){const p=a(d,u);s[d][u]=f(p)}}return s},nr=async r=>{const e=await je();for(const[n,s]of r){const[i,l]=n.split(".");if(!l){const c=m[n];if(!c)throw new w(`Invalid config property: ${n}`);e[n]=c(s);continue}if(e[i]||(e[i]={}),ke.includes(i)){const c=_e[i][l];if(!c)throw new w(`Invalid config property: ${n}`);e[i][l]=c(s);continue}if(!/^[A-Z][A-Z0-9_]*$/.test(i))throw new w(`Invalid service name: ${i}. Service names must be uppercase letters, numbers, and underscores.`);const d=pt(i);if(!d[l])throw new w(`Invalid config property for custom service: ${n}`);try{e[i][l]=d[l](s)}catch(c){throw c instanceof w?c:new w(`Invalid value for ${n}: ${c.message}`)}}const t=await Se(),o=I.dirname(t);await L.mkdir(o,{recursive:!0}),await L.writeFile(t,$e.stringify(e),"utf8")},Wa=async r=>{const e=await je();for(const[n,s]of r){const[i,l]=n.split("."),a=e[i];if(l==="model"){a||(e[i]={});const c=e[i][l]||[],u=typeof s=="string"?s.split(",").map(f=>f.trim()).filter(f=>!!f):s;e[i][l]=mt([...c,...u]);continue}if(a&&a.compatible===!0){a||(e[i]={});const c=pt(i);if(!c[l])throw new w(`Invalid config property: ${n}`);try{e[i][l]=c[l](s)}catch(u){throw u instanceof w?u:new w(`Invalid value for ${n}: ${u.message}`)}continue}if(i in _e){a||(e[i]={});const c=_e[i][l];if(!c)throw new w(`Invalid config property: ${n}`);e[i][l]=c(s)}else{const c=pt(i);if(!c[l])throw new w(`Invalid config property: ${n}`);e[i]||(e[i]={}),e[i][l]=c[l](s)}}const t=await Se(),o=I.dirname(t);await L.mkdir(o,{recursive:!0}),await L.writeFile(t,$e.stringify(e),"utf8")},Ya=async()=>{const r=await je();console.log($e.stringify(r))},Ja=async()=>{console.log(await Se())},pt=r=>({compatible:ue("compatible"),stream:ue("stream"),url:e=>e?(M(`${r}.url`,/^https?:\/\//.test(e),"Must be a valid URL"),e):"",path:e=>e||"",key:e=>e||"",envKey:e=>e||"",model:e=>e?(typeof e=="string"?e?.split(","):e).map(o=>o.trim()).filter(o=>!!o&&o.length>0):[],systemPrompt:m.systemPrompt,systemPromptPath:m.systemPromptPath,codeReviewPromptPath:m.codeReviewPromptPath,timeout:m.timeout,temperature:m.temperature,maxTokens:m.maxTokens,logging:m.logging,locale:m.locale,generate:m.generate,type:m.type,maxLength:m.maxLength,includeBody:m.includeBody,topP:m.topP,codeReview:m.codeReview,disabled:m.disabled,watchMode:m.watchMode,disableLowerCase:m.disableLowerCase}),ae=r=>typeof r=="string"&&r.trim().length>0,ht=r=>(Array.isArray(r.model)?r.model:ae(r.model)?[r.model.trim()]:[]).length>0,Qo=r=>{const e=ae(r.key),t=ae(r.region)||ae(process.env.AWS_REGION)||ae(process.env.AWS_DEFAULT_REGION),o=ae(r.profile)||ae(process.env.AWS_PROFILE),n=ae(r.accessKeyId)&&ae(r.secretAccessKey)||ae(process.env.AWS_ACCESS_KEY_ID)&&ae(process.env.AWS_SECRET_ACCESS_KEY);return t&&(e||o||n)},Zo=(r,e)=>Object.entries(r).map(([t,o])=>[t,o]).filter(([t,o])=>!o.disabled).filter(([t,o])=>ke.includes(t)||o.compatible===!0).filter(([t,o])=>{switch(e){case"commit":return t==="OLLAMA"?!!o&&ht(o):t==="HUGGINGFACE"?!!o&&!!o.cookie:t==="BEDROCK"?ht(o)&&Qo(o):!!o.key&&o.key.length>0;case"review":const n=r.codeReview||o.codeReview;return t==="OLLAMA"?!!o&&ht(o)&&n:t==="HUGGINGFACE"?!!o&&!!o.cookie&&n:t==="BEDROCK"?ht(o)&&Qo(o)&&n:!!o.key&&o.key.length>0&&n}}).map(([t])=>t);class X{static create(e,t){return new e(t)}}const Be=new Map,ge=(r,e,t)=>{const o=Ur(0).update(e).digest("hex").substring(0,8),n=`${r}_${o}_${t}`;if(Be.has(n))return Be.get(n);const s=new Date,i=Xa(s,r,e,t),l=`${ie}/${i}`,a=H.createLogger({level:"info",format:H.format.combine(H.format.timestamp({format:"YYYY-MM-DDTHH:mm:ss.SSSZ"}),H.format.printf(({timestamp:d,level:c,message:u,...f})=>f&&Object.keys(f).length>0?`[${d}] ${c}: ${u} ${JSON.stringify(f,null,2)}`:`[${d}] ${c}: ${u}`)),transports:[new H.transports.File({filename:l})]});return a.info(`=== ${r.toUpperCase()} AI SERVICE LOG ===`),a.info(`Diff Hash: ${o}`),a.info(`Request Type: ${t.toUpperCase()}`),a.info(`Start Time: ${s.toISOString()}`),a.info("=".repeat(50)),a.info(""),Be.set(n,a),a},Va=r=>{const e={...r},t=["authorization","x-api-key","x-goog-api-key","api-key","x-amzn-bedrock-application-key"];for(const o of t){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=(r,e,t,o,n,s,i=!0)=>{if(!i)return;const l=ge(t,r,e);l.info(`Making request to ${t} API with model: ${o}`),l.info(`Request URL: ${n}`),l.info("Request headers:",Va(s))},oe=(r,e,t,o,n=!0)=>{if(!n)return;ge(t,r,e).info("Request payload:",o)},Z=(r,e,t,o,n,s=!0)=>{if(!s)return;const i=ge(t,r,e);i.info("System prompt:",{prompt:o}),i.info("User prompt:",{prompt:n})},W=(r,e,t,o,n=!0)=>{if(!n)return;ge(t,r,e).info("Response received:",o)},B=(r,e,t,o,n=!0)=>{if(!n)return;ge(t,r,e).error("API request failed:",o)},Y=(r,e,t,o,n,s=!0)=>{if(!s)return;const i=ge(t,r,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 ===")},qa=(r,e,t,o,n,s,i,l=!0)=>{if(!l)return;const a=ge(t,r,e);i?a.error(`Request failed after ${s}ms:`,{error:i}):(a.info(`Request completed in ${s}ms`),a.info("Response:",{response:n})),Y(r,e,t,s,n,l)},Xa=(r,e,t,o)=>{const{year:n,month:s,day:i,hours:l,minutes:a,seconds:d}=Qa(r),u=Ur(0).update(t).digest("hex").substring(0,8),f=e.toLowerCase().replace(/[^a-z0-9]/g,"").substring(0,20);return o==="review"?`${n}-${s}-${i}_${l}-${a}-${d}_${u}_${f}_review.log`:`${n}-${s}-${i}_${l}-${a}-${d}_${u}_${f}_commit.log`},Qa=r=>{const e=r.getFullYear().toString(),t=(r.getMonth()+1).toString().padStart(2,"0"),o=r.getDate().toString().padStart(2,"0"),n=r.getHours().toString().padStart(2,"0"),s=r.getMinutes().toString().padStart(2,"0"),i=r.getSeconds().toString().padStart(2,"0");return{year:e,month:t,day:o,hours:n,minutes:s,seconds:i}},sr=()=>{for(const[r,e]of Be.entries())try{e.close()}catch(t){console.error(`Failed to close logger ${r}:`,t)}Be.clear()};process.on("exit",sr),process.on("SIGINT",()=>{sr(),process.exit(0)}),process.on("SIGTERM",()=>{sr(),process.exit(0)});let gt,en="info";async function Za(r){if(gt){console.warn("Logger already initialized. Skipping re-initialization.");return}const e=r?.logLevel||"info";en=e;const t=r?.logFilePath||qo,o=r?.exceptionLogFilePath||Xo,n=r?.logging??!0;await Ko(I.dirname(t)),await Ko(I.dirname(o));const s=[];n?s.push(new H.transports.DailyRotateFile({filename:t,datePattern:"YYYY-MM-DD",zippedArchive:!0,maxSize:"20m",maxFiles:"14d",level:e,format:H.format.combine(H.format.timestamp(),H.format.printf(({level:i,message:l,timestamp:a})=>`[${a}] ${i}: ${l}`))})):s.push(new H.transports.Console({silent:!0})),gt=H.createLogger({level:e,format:H.format.json(),transports:s,exceptionHandlers:n?[new H.transports.DailyRotateFile({filename:o,datePattern:"YYYY-MM-DD",zippedArchive:!0,maxSize:"20m",maxFiles:"14d",format:H.format.combine(H.format.timestamp(),H.format.json())})]:[],exitOnError:!1,silent:!n})}const xe=new Proxy({},{get:(r,e,t)=>{if(!gt)throw new Error("Logger not initialized. Call initializeLogger() first.");return Reflect.get(gt,e,t)}});function yt(){const r=H.config.npm.levels;return(r[en]??r.info)>=r.verbose}class ee{constructor(e){this.handleError$=t=>{const o=this.getDetailedErrorMessage(t),n=t.status?`HTTP ${t.status}: ${o}`:o;if(this.params.config.logging){const s=this.params.stagedDiff.diff,i=this.serviceName.replace(/\[|\]/g,"").trim();qa(s,"commit",i,"Error occurred","",void 0,n)}return xe.error(`${this.errorPrefix} ${n}`),t.stack&&xe.error(` ${t.stack}`),t.content&&xe.error(` Problematic content: ${t.content}`),t.originalError&&xe.error(` Original error: ${t.originalError}`),Mt({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 t=e.message||"";return t.includes("API key")||t.includes("api_key")?"Invalid API key. Check your API key configuration":t.includes("rate_limit")||t.includes("Rate limit")||t.includes("429")||t.includes("Too Many Requests")?"Rate limit exceeded. Wait a moment and try again, or upgrade your plan":t.includes("model")||t.includes("Model")?"Model not found or not accessible. Check if the model name is correct":t.includes("timeout")||t.includes("Timeout")?"Request timed out. Try again or increase the timeout setting":t.includes("network")||t.includes("connection")||t.includes("ECONNREFUSED")?"Network error. Check your internet connection and try again":t.includes("quota")||t.includes("usage")||t.includes("QUOTA_EXCEEDED")?"API quota exceeded. Check your usage limits":t.includes("401")||t.includes("Unauthorized")?"Authentication failed. Your API key may be invalid or expired":t.includes("403")||t.includes("Forbidden")?"Access denied. Your API key may not have permission for this model":t.includes("404")||t.includes("Not Found")?"Model or endpoint not found. Check your model configuration":t.includes("500")||t.includes("Internal Server Error")?"Server error. Try again later":t.includes("overloaded")||t.includes("capacity")||t.includes("SERVICE_UNAVAILABLE")||t.includes("unavailable")?"Service is temporarily unavailable. Try again in a few minutes":this.getServiceSpecificErrorMessage(e)||t||"Unknown error occurred"}getServiceSpecificErrorMessage(e){return null}cleanJsonCodeBlock(e){const t=/```(?:json|JSON)?\s*([\s\S]*?)\s*```/,o=e.match(t);return o?o[1].trim():e}extractJsonFromResponse(e){let t=e.indexOf("[");if(t!==-1){const o=this.extractBalancedJson(e,t,"[","]");if(o)return o}if(t=e.indexOf("{"),t!==-1){const o=this.extractBalancedJson(e,t,"{","}");if(o)return o}return null}extractBalancedJson(e,t,o,n){let s=0,i=!1,l=!1;for(let a=t;a<e.length;a++){const d=e[a];if(l){l=!1;continue}if(d==="\\"&&i){l=!0;continue}if(d==='"'){i=!i;continue}if(!i&&(d===o&&s++,d===n&&s--,s===0))return e.slice(t,a+1)}return null}parseMessage(e,t,o){const n=this.cleanJsonCodeBlock(e),s=this.extractJsonFromResponse(n);if(!s){const u=new Error("AI response did not contain a valid JSON object or array.");throw u.name="InvalidJsonResponse",u.content=e,u}const i=Yo(s);if(!i.ok){const u=new Error("Failed to parse AI response as JSON");throw u.name="JsonParseError",u.content=s,u.originalError=i.error,u}const l=i.data,a=Array.isArray(l)?l:[l];if(!a.length||!a.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 c=a.map(u=>this.extractMessageAsType(u,t)).map(u=>({title:`${u.subject}`,value:`${u.subject}${u.body?`
|
|
19
|
+
See https://docs.aws.amazon.com/bedrock/latest/userguide/inference-profiles.html`),o}).filter(r=>!!r&&r.length>0):["anthropic.claude-haiku-4-5-20251001-v1:0"],runtimeMode:t=>{t&&console.warn("[Bedrock] DEPRECATION: runtimeMode is no longer used. Authentication method is now auto-detected from configured credentials.")},region:t=>t||process.env.AWS_REGION||process.env.AWS_DEFAULT_REGION||"",profile:t=>t||process.env.AWS_PROFILE||"",accessKeyId:t=>t||process.env.AWS_ACCESS_KEY_ID||"",secretAccessKey:t=>t||process.env.AWS_SECRET_ACCESS_KEY||"",sessionToken:t=>t||process.env.AWS_SESSION_TOKEN||"",applicationEndpointId:t=>t||process.env.BEDROCK_APPLICATION_ENDPOINT_ID||"",applicationInferenceProfileArn:t=>t||process.env.BEDROCK_APPLICATION_INFERENCE_PROFILE_ARN||process.env.BEDROCK_INFERENCE_PROFILE_ARN||"",applicationBaseUrl:t=>t||process.env.BEDROCK_APPLICATION_BASE_URL||"",systemPrompt:m.systemPrompt,systemPromptPath:m.systemPromptPath,codeReviewPromptPath:m.codeReviewPromptPath,timeout:m.timeout,temperature:t=>{if(!t)return;M("temperature",/^(2|\d)(\.\d{1,2})?$/.test(t),"Must be decimal between 0 and 2");const e=Number(t);return M("temperature",e>0,"Must be greater than 0"),M("temperature",e<=2,"Must be less than or equal to 2"),e},maxTokens:t=>{if(t)return M("maxTokens",/^\d+$/.test(t),"Must be an integer"),Number(t)},logging:m.logging,locale:m.locale,generate:m.generate,type:m.type,maxLength:m.maxLength,includeBody:m.includeBody,topP:t=>{if(!t)return;M("topP",/^(1|\d)(\.\d{1,2})?$/.test(t),"Must be decimal between 0 and 1");const e=Number(t);return M("topP",e>0,"Must be greater than 0"),M("topP",e<=1,"Must be less than or equal to 1"),e},codeReview:m.codeReview,disabled:m.disabled,watchMode:m.watchMode,disableLowerCase:m.disableLowerCase,inferenceParameters:t=>{if(!t)return{};if(typeof t=="object")return t;try{const e=JSON.parse(t);return M("BEDROCK.inferenceParameters",typeof e=="object"&&e!==null&&!Array.isArray(e),"Must be a valid JSON object"),e}catch(e){throw new w(`Invalid BEDROCK.inferenceParameters: Must be valid JSON. Error: ${e.message}`)}}}};let je;const Ua=(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 Te?(e[s]||(e[s]={}),e[s][i]=n):e[o]=n}return e},za=()=>{const t=Oe.homedir(),e=process.env.AICOMMIT_CONFIG_PATH,r=Xo,o=I.join(t,".aicommit2");return[e,r,o].filter(n=>!!n)},ke=async()=>{const t=za();for(const e of t)if(await Wo(e))return e;return Xo},Ka=t=>t.replace(/\$\{([a-zA-Z_][a-zA-Z0-9_]*)\}|\$([a-zA-Z_][a-zA-Z0-9_]*)/g,(e,r,o)=>{const n=r||o;return process.env[n]??""}),Be=async()=>{const t=await ke();je=t;try{const e=await F.readFile(t,"utf8"),r=Ka(e);return Ae.parse(r)}catch(e){return e.code==="ENOENT"?(je=void 0,{}):(console.error(`Error reading config file ${t}:`,e),je=void 0,{})}},he=async(t,e=[])=>{const r=await Be(),o=Ua(e),n={...t,...o},s={},i=Ha(r),l={};for(const d of i){const c=r[d]?.envKey;let u;c?(u=[c],d==="BEDROCK"&&c!=="BEDROCK_APPLICATION_API_KEY"&&u.push("BEDROCK_APPLICATION_API_KEY")):d==="BEDROCK"?u=["BEDROCK_API_KEY","BEDROCK_APPLICATION_API_KEY"]:u=[`${d}_API_KEY`];const f=u.map(p=>p?process.env[p]:void 0).find(p=>typeof p=="string"&&p.length>0);f&&(l[d]={key:f})}const a=(d,c)=>{const u=n[`${d}.${c}`]??n[d]?.[c],f=l[d]?.[c],p=r[d]?.[c],h=n[c]??r[c];return u!==void 0?u:f!==void 0?f:p!==void 0?p:h};for(const[d,c]of Object.entries(m)){const u=n[d]??r[d];s[d]=c(u)}for(const d of i){s[d]={};const c=Te[d]||ht(d);for(const[u,f]of Object.entries(c)){const p=a(d,u);s[d][u]=f(p)}}return s},sr=async t=>{const e=await Be();for(const[n,s]of t){const[i,l]=n.split(".");if(!l){const c=m[n];if(!c)throw new w(`Invalid config property: ${n}`);e[n]=c(s);continue}if(e[i]||(e[i]={}),nr.includes(i)){const c=Te[i][l];if(!c)throw new w(`Invalid config property: ${n}`);e[i][l]=c(s);continue}if(!/^[A-Z][A-Z0-9_]*$/.test(i))throw new w(`Invalid service name: ${i}. Service names must be uppercase letters, numbers, and underscores.`);const d=ht(i);if(!d[l])throw new w(`Invalid config property for custom service: ${n}`);try{e[i][l]=d[l](s)}catch(c){throw c instanceof w?c:new w(`Invalid value for ${n}: ${c.message}`)}}const r=await ke(),o=I.dirname(r);await F.mkdir(o,{recursive:!0}),await F.writeFile(r,Ae.stringify(e),"utf8")},Wa=async t=>{const e=await Be();for(const[n,s]of t){const[i,l]=n.split("."),a=e[i];if(l==="model"){a||(e[i]={});const c=e[i][l]||[],u=typeof s=="string"?s.split(",").map(f=>f.trim()).filter(f=>!!f):s;e[i][l]=ft([...c,...u]);continue}if(a&&a.compatible===!0){a||(e[i]={});const c=ht(i);if(!c[l])throw new w(`Invalid config property: ${n}`);try{e[i][l]=c[l](s)}catch(u){throw u instanceof w?u:new w(`Invalid value for ${n}: ${u.message}`)}continue}if(i in Te){a||(e[i]={});const c=Te[i][l];if(!c)throw new w(`Invalid config property: ${n}`);e[i][l]=c(s)}else{const c=ht(i);if(!c[l])throw new w(`Invalid config property: ${n}`);e[i]||(e[i]={}),e[i][l]=c[l](s)}}const r=await ke(),o=I.dirname(r);await F.mkdir(o,{recursive:!0}),await F.writeFile(r,Ae.stringify(e),"utf8")},Ya=async()=>{const t=await Be();console.log(Ae.stringify(t))},Ja=async()=>{console.log(await ke())},ht=t=>({compatible:ue("compatible"),stream:ue("stream"),url:e=>e?(M(`${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:m.systemPrompt,systemPromptPath:m.systemPromptPath,codeReviewPromptPath:m.codeReviewPromptPath,timeout:m.timeout,temperature:m.temperature,maxTokens:m.maxTokens,logging:m.logging,locale:m.locale,generate:m.generate,type:m.type,maxLength:m.maxLength,includeBody:m.includeBody,topP:m.topP,codeReview:m.codeReview,disabled:m.disabled,watchMode:m.watchMode,disableLowerCase:m.disableLowerCase}),ae=t=>typeof t=="string"&&t.trim().length>0,Se=t=>(Array.isArray(t.model)?t.model:ae(t.model)?[t.model.trim()]:[]).length>0,ir=t=>{const e=ae(t.key),r=ae(t.region)||ae(process.env.AWS_REGION)||ae(process.env.AWS_DEFAULT_REGION),o=ae(t.profile)||ae(process.env.AWS_PROFILE),n=ae(t.accessKeyId)&&ae(t.secretAccessKey)||ae(process.env.AWS_ACCESS_KEY_ID)&&ae(process.env.AWS_SECRET_ACCESS_KEY);return r&&(e||o||n)},xe=(t,e)=>Object.entries(t).map(([r,o])=>[r,o]).filter(([r,o])=>!o.disabled).filter(([r,o])=>nr.includes(r)||o.compatible===!0).filter(([r,o])=>{switch(e){case"commit":return r==="OLLAMA"?!!o&&Se(o):r==="HUGGINGFACE"?!!o&&!!o.cookie:r==="BEDROCK"?Se(o)&&ir(o):!!o.key&&o.key.length>0;case"review":const n=t.codeReview||o.codeReview;return r==="OLLAMA"?!!o&&Se(o)&&n:r==="HUGGINGFACE"?!!o&&!!o.cookie&&n:r==="BEDROCK"?Se(o)&&ir(o)&&n:!!o.key&&o.key.length>0&&n;case"watch":const s=t.watchMode||o.watchMode;return r==="OLLAMA"?!!o&&Se(o)&&s:r==="HUGGINGFACE"?!!o&&!!o.cookie&&s:r==="BEDROCK"?Se(o)&&ir(o)&&s:o.compatible?!!o.url&&!!o.key&&s:!!o.key&&o.key.length>0&&s}}).map(([r])=>r);class X{static create(e,r){return new e(r)}}const Ge=new Map,ge=(t,e,r)=>{const o=Kr(0).update(e).digest("hex").substring(0,8),n=`${t}_${o}_${r}`;if(Ge.has(n))return Ge.get(n);const s=new Date,i=Xa(s,t,e,r),l=`${ie}/${i}`,a=H.createLogger({level:"info",format:H.format.combine(H.format.timestamp({format:"YYYY-MM-DDTHH:mm:ss.SSSZ"}),H.format.printf(({timestamp:d,level:c,message:u,...f})=>f&&Object.keys(f).length>0?`[${d}] ${c}: ${u} ${JSON.stringify(f,null,2)}`:`[${d}] ${c}: ${u}`)),transports:[new H.transports.File({filename:l})]});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(""),Ge.set(n,a),a},Va=t=>{const e={...t},r=["authorization","x-api-key","x-goog-api-key","api-key","x-amzn-bedrock-application-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 l=ge(r,t,e);l.info(`Making request to ${r} API with model: ${o}`),l.info(`Request URL: ${n}`),l.info("Request headers:",Va(s))},oe=(t,e,r,o,n=!0)=>{if(!n)return;ge(r,t,e).info("Request payload:",o)},Z=(t,e,r,o,n,s=!0)=>{if(!s)return;const i=ge(r,t,e);i.info("System prompt:",{prompt:o}),i.info("User prompt:",{prompt:n})},W=(t,e,r,o,n=!0)=>{if(!n)return;ge(r,t,e).info("Response received:",o)},j=(t,e,r,o,n=!0)=>{if(!n)return;ge(r,t,e).error("API request failed:",o)},Y=(t,e,r,o,n,s=!0)=>{if(!s)return;const i=ge(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 ===")},qa=(t,e,r,o,n,s,i,l=!0)=>{if(!l)return;const a=ge(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})),Y(t,e,r,s,n,l)},Xa=(t,e,r,o)=>{const{year:n,month:s,day:i,hours:l,minutes:a,seconds:d}=Qa(t),u=Kr(0).update(r).digest("hex").substring(0,8),f=e.toLowerCase().replace(/[^a-z0-9]/g,"").substring(0,20);return o==="review"?`${n}-${s}-${i}_${l}-${a}-${d}_${u}_${f}_review.log`:`${n}-${s}-${i}_${l}-${a}-${d}_${u}_${f}_commit.log`},Qa=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}},ar=()=>{for(const[t,e]of Ge.entries())try{e.close()}catch(r){console.error(`Failed to close logger ${t}:`,r)}Ge.clear()};process.on("exit",ar),process.on("SIGINT",()=>{ar(),process.exit(0)}),process.on("SIGTERM",()=>{ar(),process.exit(0)});let gt,en="info";async function Za(t){if(gt){console.warn("Logger already initialized. Skipping re-initialization.");return}const e=t?.logLevel||"info";en=e;const r=t?.logFilePath||Qo,o=t?.exceptionLogFilePath||Zo,n=t?.logging??!0;await Yo(I.dirname(r)),await Yo(I.dirname(o));const s=[];n?s.push(new H.transports.DailyRotateFile({filename:r,datePattern:"YYYY-MM-DD",zippedArchive:!0,maxSize:"20m",maxFiles:"14d",level:e,format:H.format.combine(H.format.timestamp(),H.format.printf(({level:i,message:l,timestamp:a})=>`[${a}] ${i}: ${l}`))})):s.push(new H.transports.Console({silent:!0})),gt=H.createLogger({level:e,format:H.format.json(),transports:s,exceptionHandlers:n?[new H.transports.DailyRotateFile({filename:o,datePattern:"YYYY-MM-DD",zippedArchive:!0,maxSize:"20m",maxFiles:"14d",format:H.format.combine(H.format.timestamp(),H.format.json())})]:[],exitOnError:!1,silent:!n})}const Ie=new Proxy({},{get:(t,e,r)=>{if(!gt)throw new Error("Logger not initialized. Call initializeLogger() first.");return Reflect.get(gt,e,r)}});function yt(){const t=H.config.npm.levels;return(t[en]??t.info)>=t.verbose}class ee{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();qa(s,"commit",i,"Error occurred","",void 0,n)}return Ie.error(`${this.errorPrefix} ${n}`),r.stack&&Ie.error(` ${r.stack}`),r.content&&Ie.error(` Problematic content: ${r.content}`),r.originalError&&Ie.error(` Original error: ${r.originalError}`),Mt({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}extractJsonFromResponse(e){let r=e.indexOf("[");if(r!==-1){const o=this.extractBalancedJson(e,r,"[","]");if(o)return o}if(r=e.indexOf("{"),r!==-1){const o=this.extractBalancedJson(e,r,"{","}");if(o)return o}return null}extractBalancedJson(e,r,o,n){let s=0,i=!1,l=!1;for(let a=r;a<e.length;a++){const d=e[a];if(l){l=!1;continue}if(d==="\\"&&i){l=!0;continue}if(d==='"'){i=!i;continue}if(!i&&(d===o&&s++,d===n&&s--,s===0))return e.slice(r,a+1)}return null}parseMessage(e,r,o){const n=this.cleanJsonCodeBlock(e),s=this.extractJsonFromResponse(n);if(!s){const u=new Error("AI response did not contain a valid JSON object or array.");throw u.name="InvalidJsonResponse",u.content=e,u}const i=Vo(s);if(!i.ok){const u=new Error("Failed to parse AI response as JSON");throw u.name="JsonParseError",u.content=s,u.originalError=i.error,u}const l=i.data,a=Array.isArray(l)?l:[l];if(!a.length||!a.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 c=a.map(u=>this.extractMessageAsType(u,r)).map(u=>({title:`${u.subject}`,value:`${u.subject}${u.body?`
|
|
20
20
|
|
|
21
21
|
${u.body}`:""}${u.footer?`
|
|
22
22
|
|
|
23
|
-
${u.footer}`:""}`})).slice(0,o);if(this.isLoggingEnabled()){const u=c.map(f=>f.title).join(", ");
|
|
23
|
+
${u.footer}`:""}`})).slice(0,o);if(this.isLoggingEnabled()){const u=c.map(f=>f.title).join(", ");Ie.info(`${this.serviceName} Parsed ${c.length} commit messages: ${u}`)}return c}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*(.*)/,l=e.subject.match(i),a=this.params.config.disableLowerCase??!1;return{...e,subject:l&&!a?l[0].toLowerCase():e.subject};default:return e}}normalizeCommitMessage(e){const r=/^(\w+)(\(.*?\))?:\s(.*)$/,o=e.match(r);if(o){const[,n,s,i]=o,l=this.params.config.disableLowerCase??!1,a=n.toLowerCase(),d=l?i:i.charAt(0).toLowerCase()+i.slice(1);e=`${a}${s||""}: ${d}`}return e}sanitizeResponse(e){if(typeof e=="string")try{return[{title:`${Jo(e)}...`,value:e}]}catch{return[]}return e.map(r=>{try{return{title:`${Jo(r)}...`,value:r}}catch{return{title:"",value:""}}})}isLoggingEnabled(){return this.params.config.logging&&!!this.logSessionId}}const ec=["claude-4","claude-haiku-4","claude-sonnet-4","claude-opus-4"],tc=t=>{const e=t.toLowerCase();return ec.some(r=>e===r||e.startsWith(`${r}-`)||e.startsWith(`${r}.`))},J={locale:"en",maxLength:50,type:"conventional",generate:1,systemPrompt:"",systemPromptPath:"",codeReviewPromptPath:"",vcs_branch:""},rc={"":"<commit message>",conventional:`<type>(<optional scope>): <description>
|
|
24
24
|
|
|
25
25
|
[optional body]
|
|
26
26
|
|
|
@@ -29,84 +29,84 @@ ${u.footer}`:""}`})).slice(0,o);if(this.isLoggingEnabled()){const u=c.map(f=>f.t
|
|
|
29
29
|
[optional body]
|
|
30
30
|
|
|
31
31
|
[optional footer(s)]`},oc={"":"",gitmoji:`
|
|
32
|
-
${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(([
|
|
32
|
+
${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(`
|
|
33
33
|
`)}`,conventional:`
|
|
34
|
-
${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(([
|
|
35
|
-
`)}`},
|
|
34
|
+
${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(`
|
|
35
|
+
`)}`},cr=(t,e)=>t.replace(/{(\w+)}/g,(r,o)=>e[o]?.toString()||J[o]?.toString()),nc=(t,e)=>{const r=e.split("-")[0].toLowerCase(),o={conventional:{en:{subject:"fix(auth): fix bug in user authentication process",body:"- Update login function to handle edge cases\\n- Add additional error logging for debugging"},zh:{subject:"fix(auth): \u4FEE\u590D\u7528\u6237\u8BA4\u8BC1\u8FC7\u7A0B\u4E2D\u7684\u9519\u8BEF",body:"- \u66F4\u65B0\u767B\u5F55\u51FD\u6570\u4EE5\u5904\u7406\u8FB9\u7F18\u60C5\u51B5\\n- \u6DFB\u52A0\u989D\u5916\u7684\u9519\u8BEF\u65E5\u5FD7\u7528\u4E8E\u8C03\u8BD5"},ja:{subject:"fix(auth): \u30E6\u30FC\u30B6\u30FC\u8A8D\u8A3C\u30D7\u30ED\u30BB\u30B9\u306E\u30D0\u30B0\u3092\u4FEE\u6B63",body:"- \u30A8\u30C3\u30B8\u30B1\u30FC\u30B9\u3092\u51E6\u7406\u3059\u308B\u305F\u3081\u306B\u30ED\u30B0\u30A4\u30F3\u6A5F\u80FD\u3092\u66F4\u65B0\\n- \u30C7\u30D0\u30C3\u30B0\u7528\u306E\u8FFD\u52A0\u30A8\u30E9\u30FC\u30ED\u30B0\u3092\u8FFD\u52A0"},ko:{subject:"fix(auth): \uC0AC\uC6A9\uC790 \uC778\uC99D \uD504\uB85C\uC138\uC2A4\uC758 \uBC84\uADF8 \uC218\uC815",body:"- \uC5E3\uC9C0 \uCF00\uC774\uC2A4\uB97C \uCC98\uB9AC\uD558\uB3C4\uB85D \uB85C\uADF8\uC778 \uD568\uC218 \uC5C5\uB370\uC774\uD2B8\\n- \uB514\uBC84\uAE45\uC744 \uC704\uD55C \uCD94\uAC00 \uC624\uB958 \uB85C\uAE45 \uCD94\uAC00"},es:{subject:"fix(auth): corregir error en el proceso de autenticaci\xF3n",body:"- Actualizar funci\xF3n de inicio de sesi\xF3n para manejar casos extremos\\n- Agregar registro de errores adicional para depuraci\xF3n"},fr:{subject:"fix(auth): corriger un bug dans le processus d'authentification",body:"- Mettre \xE0 jour la fonction de connexion pour g\xE9rer les cas limites\\n- Ajouter une journalisation d'erreurs suppl\xE9mentaire pour le d\xE9bogage"},de:{subject:"fix(auth): Fehler im Benutzerauthentifizierungsprozess beheben",body:"- Login-Funktion aktualisiert, um Randf\xE4lle zu behandeln\\n- Zus\xE4tzliche Fehlerprotokollierung f\xFCr Debugging hinzugef\xFCgt"}},gitmoji:{en:{subject:":sparkles: Add real-time chat feature",body:"- Implement WebSocket connection\\n- Add message encryption\\n- Include typing indicators"},zh:{subject:":sparkles: \u6DFB\u52A0\u5B9E\u65F6\u804A\u5929\u529F\u80FD",body:"- \u5B9E\u73B0WebSocket\u8FDE\u63A5\\n- \u6DFB\u52A0\u6D88\u606F\u52A0\u5BC6\\n- \u5305\u542B\u8F93\u5165\u6307\u793A\u5668"},ja:{subject:":sparkles: \u30EA\u30A2\u30EB\u30BF\u30A4\u30E0\u30C1\u30E3\u30C3\u30C8\u6A5F\u80FD\u3092\u8FFD\u52A0",body:"- WebSocket\u63A5\u7D9A\u3092\u5B9F\u88C5\\n- \u30E1\u30C3\u30BB\u30FC\u30B8\u6697\u53F7\u5316\u3092\u8FFD\u52A0\\n- \u5165\u529B\u30A4\u30F3\u30B8\u30B1\u30FC\u30BF\u30FC\u3092\u542B\u3080"},ko:{subject:":sparkles: \uC2E4\uC2DC\uAC04 \uCC44\uD305 \uAE30\uB2A5 \uCD94\uAC00",body:"- WebSocket \uC5F0\uACB0 \uAD6C\uD604\\n- \uBA54\uC2DC\uC9C0 \uC554\uD638\uD654 \uCD94\uAC00\\n- \uC785\uB825 \uD45C\uC2DC\uAE30 \uD3EC\uD568"},es:{subject:":sparkles: Agregar funci\xF3n de chat en tiempo real",body:"- Implementar conexi\xF3n WebSocket\\n- Agregar cifrado de mensajes\\n- Incluir indicadores de escritura"},fr:{subject:":sparkles: Ajouter une fonctionnalit\xE9 de chat en temps r\xE9el",body:"- Impl\xE9menter une connexion WebSocket\\n- Ajouter le chiffrement des messages\\n- Inclure des indicateurs de saisie"},de:{subject:":sparkles: Echtzeit-Chat-Funktion hinzuf\xFCgen",body:"- WebSocket-Verbindung implementieren\\n- Nachrichtenverschl\xFCsselung hinzuf\xFCgen\\n- Tippindikatoren einschlie\xDFen"}},"":{en:{subject:"",body:""}}},n=o[t]||o[""];return n[r]||n.en},tn=t=>{const{type:e,maxLength:r,generate:o,locale:n}=t,s="You are an expert Git commit message writer specializing in analyzing code changes and creating precise, meaningful commit messages.",i=`Your task is to generate exactly ${o} ${e} style commit message${o!==1?"s":""} based on the provided git diff.`;return[s,i,"",["## Requirements:",`1. Language: Write all messages in ${n}`,`2. Format: Strictly follow the ${e} commit format:`,`${rc[e]}`,`3. Allowed Types:${oc[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(`
|
|
36
36
|
`)].filter(Boolean).join(`
|
|
37
|
-
`)},wt=(
|
|
37
|
+
`)},wt=(t,e,r)=>{const o=n=>{const s=nc(n,r);return n==="conventional"||n==="gitmoji"?`${Array(e).fill(null).map((i,l)=>`
|
|
38
38
|
{
|
|
39
39
|
"subject": "${s.subject}",
|
|
40
40
|
"body": "${s.body}",
|
|
41
41
|
"footer": ""
|
|
42
42
|
}`).join(",")}`:""};return[`
|
|
43
|
-
Lastly, Provide your response as a JSON array containing exactly ${e} object${e!==1?"s":""}, each with the following keys:`,`- "subject": The main commit message using the ${
|
|
44
|
-
[${o(
|
|
43
|
+
Lastly, Provide your response as a JSON array containing exactly ${e} object${e!==1?"s":""}, each with the following keys:`,`- "subject": The main commit message using the ${t} style. It should be a concise summary of the changes.`,'- "body": An optional detailed explanation of the changes. If not needed, use an empty string.','- "footer": An optional footer for metadata like BREAKING CHANGES. If not needed, use an empty string.',`The array must always contain ${e} element${e!==1?"s":""}, no more and no less.`,`Example response format:
|
|
44
|
+
[${o(t)}
|
|
45
45
|
]`,`Ensure you generate exactly ${e} commit message${e!==1?"s":""}, even if it requires creating slightly varied versions for similar changes.`,"The response should be valid JSON that can be parsed without errors."].filter(Boolean).join(`
|
|
46
|
-
`)},te=
|
|
47
|
-
${wt(o,n,s)}`;if(!
|
|
48
|
-
${wt(o,n,s)}`;try{const i=q.readFileSync(
|
|
49
|
-
${wt(o,n,s)}`}catch{return`${tn(
|
|
50
|
-
${wt(o,n,s)}`}},re=
|
|
46
|
+
`)},te=t=>{const{systemPrompt:e,systemPromptPath:r,type:o,generate:n,locale:s}=t;if(e)return`${cr(e,t)}
|
|
47
|
+
${wt(o,n,s)}`;if(!r)return`${tn(t)}
|
|
48
|
+
${wt(o,n,s)}`;try{const i=q.readFileSync(pt(r),"utf-8");return`${cr(i,t)}
|
|
49
|
+
${wt(o,n,s)}`}catch{return`${tn(t)}
|
|
50
|
+
${wt(o,n,s)}`}},re=t=>{const{codeReviewPromptPath:e,locale:r}=t,o=`I'll give you the output of the "git diff" command as an input. Please review the following code and provide your feedback in Markdown format. Focus on:
|
|
51
51
|
|
|
52
|
-
1. Language: ${
|
|
52
|
+
1. Language: ${r}
|
|
53
53
|
2. Code quality and best practices
|
|
54
54
|
3. Potential bugs or errors
|
|
55
55
|
4. Performance improvements
|
|
56
56
|
5. Readability and maintainability
|
|
57
57
|
|
|
58
|
-
Please structure your response with appropriate Markdown headings, code blocks, and bullet points.`;if(!e)return o;try{const n=q.readFileSync(
|
|
58
|
+
Please structure your response with appropriate Markdown headings, code blocks, and bullet points.`;if(!e)return o;try{const n=q.readFileSync(pt(e),"utf-8");return`${cr(n,t)}`}catch{return o}},rn=async t=>{if(t.systemPromptPath)try{q.readFileSync(pt(t.systemPromptPath),"utf-8")}catch(e){throw new w(`Error reading system prompt file: ${t.systemPromptPath}, ${e}`)}if(t.codeReview&&t.codeReviewPromptPath)try{q.readFileSync(pt(t.codeReviewPromptPath),"utf-8")}catch(e){throw new w(`Error reading code review prompt file: ${t.codeReviewPromptPath}, ${e}`)}},ye=(t,e="commit")=>e==="review"?`Please analyze the following diff and provide a comprehensive code review:
|
|
59
59
|
|
|
60
60
|
\`\`\`diff
|
|
61
|
-
${
|
|
61
|
+
${t}
|
|
62
62
|
\`\`\`
|
|
63
63
|
|
|
64
64
|
Focus on code quality, potential issues, and improvement suggestions.`:`Please analyze the following diff and generate commit message(s) based on the changes:
|
|
65
65
|
|
|
66
66
|
\`\`\`diff
|
|
67
|
-
${
|
|
67
|
+
${t}
|
|
68
68
|
\`\`\`
|
|
69
69
|
|
|
70
|
-
Focus on understanding the purpose and impact of these changes to create meaningful commit message(s).`,sc=10*60*1e3;class ic extends ee{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 Kn({apiKey:this.params.config.key,...this.params.config.timeout>sc&&{timeout:this.params.config.timeout}})}getServiceSpecificErrorMessage(e){const t=e.message||"";return t.includes("API key")||t.includes("api_key")?"Invalid API key. Check your Anthropic API key in configuration":t.includes("quota")||t.includes("usage")?"API quota exceeded. Check your Anthropic usage limits":t.includes("model_not_found")||t.includes("Model not found")||/model.*does not exist/i.test(t)?"Model not found or not accessible. Check if the Claude model name is correct":t.includes("403")||t.includes("Forbidden")?"Access denied. Your API key may not have permission for this Claude model":t.includes("404")||t.includes("Not Found")?"Model or endpoint not found. Check your Claude model configuration":t.includes("500")||t.includes("Internal Server Error")?"Anthropic server error. Try again later":null}generateCommitMessage$(){return T(this.generateMessage("commit")).pipe(_(e=>O(e)),N(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})),F(this.handleError$))}generateCodeReview$(){return T(this.generateMessage("review")).pipe(_(e=>O(e)),N(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),F(this.handleError$))}async generateMessage(e){const t=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:n,codeReviewPromptPath:s,logging:i,temperature:l,locale:a,generate:d,type:c,maxLength:u,maxTokens:f,topP:p,model:h}=this.params.config,y={...J,locale:a,maxLength:u,type:c,generate:d,systemPrompt:o,systemPromptPath:n,codeReviewPromptPath:s,vcs_branch:this.params.branchName||""},g=e==="review"?re(y):te(y),v=ye(t,e),E=`${this.params.config.url||"https://api.anthropic.com"}/v1/messages`,k={"Content-Type":"application/json","x-api-key":this.params.config.key,"anthropic-version":"2023-06-01"};Q(t,e,"Anthropic",h,E,k,i),Z(t,e,"Anthropic",g,v,i);const $=tc(h),P={max_tokens:f,temperature:l,system:g,messages:[{role:"user",content:v}],model:h,...$?{}:{top_p:p}};oe(t,e,"Anthropic",P,i);const R=Date.now();try{const A=await this.anthropic.messages.create(P),D=Date.now()-R;W(t,e,"Anthropic",A,i);const S=A.content.map(({text:K})=>K).join("");return Y(t,e,"Anthropic",D,S,i),e==="review"?this.sanitizeResponse(S):this.parseMessage(S,c,d)}catch(A){throw B(t,e,"Anthropic",A,i),A}}}const ne="Bedrock",me={MISSING_DEPENDENCY:"MissingDependencyError",MISSING_REGION:"MissingRegionError",MISSING_MODEL_ID:"MissingModelIdError",MISSING_API_KEY:"MissingApiKeyError",MISSING_APPLICATION_KEY:"MissingApplicationKeyError",INVALID_RESPONSE:"InvalidResponseError",EMPTY_RESPONSE:"EmptyResponseError"},z=r=>typeof r=="string"&&r.length>0;let Ge=null,He=null;const on=r=>{const e=new Error('Amazon Bedrock support requires "@aws-sdk/client-bedrock-runtime" and "@aws-sdk/credential-providers". Install them with `pnpm add @aws-sdk/client-bedrock-runtime @aws-sdk/credential-providers`.');return e.name=me.MISSING_DEPENDENCY,e.originalError=r,e},ac=async()=>{if(Ge)return Ge;try{return Ge=await import("@aws-sdk/client-bedrock-runtime"),Ge}catch(r){throw Ge=null,on(r)}},nn=async()=>{if(He)return He;try{return He=await import("@aws-sdk/credential-providers"),He}catch(r){throw He=null,on(r)}};class cc extends ee{constructor(e){super(e),this.params=e,this.credentialCache=void 0,this.credentialCacheTimestamp=0,this.CREDENTIAL_CACHE_TTL=5*60*1e3,this.bedrockConfig=this.params.config,this.colors={primary:"#232F3E",secondary:"#FF9900"},this.serviceName=C.bgHex(this.colors.primary).hex(this.colors.secondary).bold(`[${ne}]`),this.errorPrefix=C.red.bold(`[${ne}]`),this.validateConfiguration()}validateConfiguration(){const e=this.bedrockConfig;if(!z(e.model)){const n=new Error("Model ID or inference profile ARN is required.");throw n.name=me.MISSING_MODEL_ID,n}if(!this.getRegion()){const n=new Error("AWS region is required. Configure BEDROCK.region or set AWS_REGION/AWS_DEFAULT_REGION.");throw n.name=me.MISSING_REGION,n}const t=z(e.key),o=this.canUseAwsSdk();if(!t&&!o){const n=new Error("Authentication required: Configure AWS credentials (profile, access keys, IAM role) or API key (BEDROCK.key).");throw n.name=me.MISSING_API_KEY,n}if(t&&!o&&!this.getRegion()&&!z(e.applicationBaseUrl)){const n=new Error("Bearer token authentication requires region or applicationBaseUrl to construct endpoint.");throw n.name=me.MISSING_REGION,n}}canUseAwsSdk(){const e=this.bedrockConfig,t=z(e.profile)||z(process.env.AWS_PROFILE),o=z(e.accessKeyId)&&z(e.secretAccessKey)||z(process.env.AWS_ACCESS_KEY_ID)&&z(process.env.AWS_SECRET_ACCESS_KEY);return t||o}determineAuthMethod(){const e=z(this.bedrockConfig.key);if(this.canUseAwsSdk())return"aws-sdk";if(e)return"bearer-token";throw new Error("No authentication method configured")}getServiceSpecificErrorMessage(e){const t=e?.name||e.code,o=e.message||"";switch(t){case"UnrecognizedClientException":case"InvalidSignatureException":return"Authentication with AWS failed. Check your IAM credentials or Bedrock API key settings.";case"AccessDeniedException":return"Access denied. Ensure the IAM principal or application key has permission to invoke the Bedrock resource.";case"ValidationException":return"Invalid request for the selected Bedrock model. Verify the model ID and payload.";case"ResourceNotFoundException":return"The specified Bedrock model, endpoint, or inference profile could not be found.";case"ThrottlingException":return"Request throttled by Bedrock. Reduce request rate or check service quotas."}return o.includes("Region")?"AWS region is required for Bedrock. Configure BEDROCK.region or set AWS_REGION/AWS_DEFAULT_REGION.":null}generateCommitMessage$(){return T(this.generateMessage("commit")).pipe(_(e=>O(e)),N(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})),F(this.handleError$))}generateCodeReview$(){return T(this.generateMessage("review")).pipe(_(e=>O(e)),N(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),F(this.handleError$))}async generateMessage(e){const t=this.params.stagedDiff.diff,o=this.bedrockConfig,n=o.model,{logging:s,inferenceParameters:i}=o,l={...J,locale:o.locale,maxLength:o.maxLength,type:o.type,generate:o.generate,systemPrompt:o.systemPrompt,systemPromptPath:o.systemPromptPath,codeReviewPromptPath:o.codeReviewPromptPath},a=e==="review"?re(l):te(l),d=ye(t,e),c={region:this.getRegion(),profile:o.profile,modelId:n},u=`https://bedrock-runtime.${this.getRegion()||"unknown"}.amazonaws.com/model/${encodeURIComponent(n)}/converse`;Q(t,e,ne,n,u,c,s),Z(t,e,ne,a,d,s);const f={modelId:n,systemPrompt:a,userPrompt:d,...i&&Object.keys(i).length>0&&{inferenceConfig:i}};oe(t,e,ne,f,s);const p=Date.now();try{const h=this.determineAuthMethod();yt()&&(console.log(C.cyan(`[Bedrock] Authentication method: ${h}`)),console.log(C.cyan(`[Bedrock] Model ID: ${n}`)),console.log(C.cyan(`[Bedrock] Region: ${this.getRegion()}`)),console.log(C.cyan(`[Bedrock] Has AWS credentials: ${this.canUseAwsSdk()}`)),console.log(C.cyan(`[Bedrock] Has API key: ${z(o.key)}`)));const y=h==="bearer-token"?await this.invokeWithBearerToken({model:n,systemPrompt:a,userPrompt:d,logging:s,requestType:e,diff:t,inferenceConfig:i}):await this.invokeWithAwsSdk({model:n,systemPrompt:a,userPrompt:d,logging:s,requestType:e,diff:t,inferenceConfig:i}),g=Date.now()-p;return Y(t,e,ne,g,y,s),e==="review"?this.sanitizeResponse(y):this.parseMessage(y,o.type,o.generate)}catch(h){throw B(t,e,ne,h,s),h instanceof Error&&(h.status=h?.status||h?.$metadata?.httpStatusCode),h}}async invokeWithAwsSdk(e){const t=this.getRegion(),{model:o,systemPrompt:n,userPrompt:s,inferenceConfig:i,logging:l,requestType:a,diff:d}=e,{BedrockRuntimeClient:c,ConverseCommand:u}=await ac(),f=this.bedrockConfig,p={region:t,requestHandler:{requestTimeout:f.timeout||12e4}},h=await this.resolveCredentials();h&&(p.credentials=h);const y=new c(p),g=new u({modelId:o,messages:[{role:"user",content:[{text:s}]}],...n?{system:[{text:n}]}:{},...i&&Object.keys(i).length>0&&{inferenceConfig:i}});yt()&&console.log(C.cyan(`[Bedrock] Sending ConverseCommand with modelId: ${o}`));let v;try{v=await y.send(g),W(d,a,ne,v,l)}catch(E){throw yt()&&(console.error(C.red(`[Bedrock] AWS SDK Error: ${E.name}`)),console.error(C.red(`[Bedrock] Error message: ${E.message}`)),E.$metadata&&(console.error(C.red(`[Bedrock] Request ID: ${E.$metadata.requestId}`)),console.error(C.red(`[Bedrock] HTTP Status: ${E.$metadata.httpStatusCode}`))),E.$fault&&console.error(C.red(`[Bedrock] Fault: ${E.$fault}`))),E}const b=v.output?.message?.content?.[0]?.text||"";if(!b){const E=new Error("No text content found in Bedrock response.");throw E.name=me.EMPTY_RESPONSE,E.content=v,E}return b}invokeWithBearerToken(e){const{model:t,systemPrompt:o,userPrompt:n,inferenceConfig:s,logging:i,requestType:l,diff:a}=e,d=this.bedrockConfig,c=this.getRegion(),u=encodeURIComponent(t),f=d.applicationBaseUrl||`https://bedrock-runtime.${c}.amazonaws.com/model/${u}/converse`,p=new URL(f),h={modelId:t,messages:[{role:"user",content:[{text:n}]}],...s&&Object.keys(s).length>0&&{inferenceConfig:s}};o&&(h.system=[{text:o}]);const y=JSON.stringify(h),g={"Content-Type":"application/json","Content-Length":Buffer.byteLength(y).toString()};return z(d.key)&&(g.Authorization=`Bearer ${d.key}`),z(d.applicationInferenceProfileArn)&&(g["x-amzn-bedrock-inference-profile-arn"]=d.applicationInferenceProfileArn),z(d.applicationEndpointId)&&(g["x-amzn-bedrock-endpoint-id"]=d.applicationEndpointId),new Promise((v,b)=>{const E=zr.request({method:"POST",protocol:p.protocol,hostname:p.hostname,port:p.port,path:p.pathname+p.search,headers:g,timeout:d.timeout},k=>{const $=[];k.on("data",P=>$.push(P)),k.on("end",()=>{const P=Buffer.concat($).toString("utf8");if(k.statusCode&&k.statusCode>=400){const S=new Error(`Bedrock application endpoint responded with status ${k.statusCode}.`);return S.status=k.statusCode,S.content=P,B(a,l,ne,S,i),b(S)}const R=Yo(P);if(!R.ok){const S=new Error("Failed to parse Bedrock application response as JSON. The Bedrock Converse API should always return valid JSON.");return S.name=me.INVALID_RESPONSE,S.content=P,B(a,l,ne,S,i),b(S)}const A=R.data;W(a,l,ne,A,i);const D=A.output?.message?.content?.[0]?.text||"";if(!D){const S=new Error("No text content found in Bedrock response.");return S.name=me.EMPTY_RESPONSE,S.content=A,B(a,l,ne,S,i),b(S)}v(D)})});E.on("error",k=>{const $=k;B(a,l,ne,$,i),b($)}),E.write(y),E.end()})}getRegion(){return this.bedrockConfig.region||process.env.AWS_REGION||process.env.AWS_DEFAULT_REGION||""}async resolveCredentials(){const e=Date.now();if(this.credentialCache&&e-this.credentialCacheTimestamp<this.CREDENTIAL_CACHE_TTL)return this.credentialCache;const t=this.bedrockConfig,o=t.profile,n=t.accessKeyId,s=t.secretAccessKey,i=t.sessionToken;let l;if(z(o)){const{fromIni:a}=await nn();l=a({profile:o})}else if(z(n)&&z(s))l=async()=>({accessKeyId:n,secretAccessKey:s,sessionToken:i||process.env.AWS_SESSION_TOKEN||void 0});else if(process.env.AWS_PROFILE){const{fromIni:a}=await nn();l=a({profile:process.env.AWS_PROFILE})}return l&&(this.credentialCache=l,this.credentialCacheTimestamp=e),l}}class Ue{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=Wn.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 lc extends ee{constructor(e){super(e),this.params=e,this.apiKey="",this.colors={primary:"#e28c58",secondary:"#fff"},this.serviceName=C.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[Codestral]"),this.errorPrefix=C.red.bold("[Codestral]"),this.apiKey=this.params.config.key}getServiceSpecificErrorMessage(e){const t=e.message||"";return t.includes("API key")||t.includes("api_key")?"Invalid API key. Check your Codestral API key in configuration":t.includes("rate_limit")||t.includes("Rate limit")?"Rate limit exceeded. Wait a moment and try again, or upgrade your Codestral plan":t.includes("model")||t.includes("Model")?"Model not found or not accessible. Check if the Codestral model name is correct":t.includes("Invalid model type")?"Invalid model type. Use supported models: codestral-latest, codestral-2501":t.includes("overloaded")||t.includes("capacity")?"Codestral service is overloaded. Try again in a few minutes":t.includes("403")||t.includes("Forbidden")?"Access denied. Your API key may not have permission for this Codestral model":t.includes("404")||t.includes("Not Found")?"Model or endpoint not found. Check your Codestral model configuration":t.includes("500")||t.includes("Internal Server Error")?"Codestral server error. Try again later":null}generateCommitMessage$(){return T(this.generateMessage("commit")).pipe(_(e=>O(e)),N(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})),F(this.handleError$))}generateCodeReview$(){return T(this.generateMessage("review")).pipe(_(e=>O(e)),N(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),F(this.handleError$))}async generateMessage(e){const t=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:n,codeReviewPromptPath:s,logging:i,locale:l,generate:a,type:d,maxLength:c}=this.params.config,u={...J,locale:l,maxLength:c,type:d,generate:a,systemPrompt:o,systemPromptPath:n,codeReviewPromptPath:s,vcs_branch:this.params.branchName||""},f=e==="review"?re(u):te(u);this.checkAvailableModels();const p=ye(t,e),y=`${this.params.config.url||"https://codestral.mistral.ai"}/v1/chat/completions`,g={Authorization:`Bearer ${this.apiKey}`,"content-type":"application/json"};Q(t,e,"Codestral",this.params.config.model,y,g,i),Z(t,e,"Codestral",f,p,i);const v=await this.createChatCompletions(f,e);return e==="review"?this.sanitizeResponse(v):this.parseMessage(v,d,a)}checkAvailableModels(){if(["codestral-latest","codestral-2501"].includes(this.params.config.model))return!0;throw new Error("Invalid model type of Codestral AI")}async createChatCompletions(e,t){const o=this.params.stagedDiff.diff,{logging: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:ye(this.params.stagedDiff.diff,t)}],temperature:this.params.config.temperature,top_p:this.params.config.topP,max_tokens:this.params.config.maxTokens,stream:!1,safe_prompt:!1,random_seed:dt(10,1e3)};t==="commit"&&(i.response_format={type:"json_object"}),oe(o,t,"Codestral",i,n);const l=Date.now();try{const d=await new Ue({method:"POST",baseURL:`${s}/v1/chat/completions`,timeout:this.params.config.timeout}).setHeaders({Authorization:`Bearer ${this.apiKey}`,"content-type":"application/json"}).setBody(i).execute(),c=Date.now()-l,u=d.data;if(W(o,t,"Codestral",u,n),!u.choices||u.choices.length===0||!u.choices[0].message?.content)throw B(o,t,"Codestral",{message:"No Content on response",result:u},n),new Error("No Content on response. Please open a Bug report");const p=u.choices[0].message.content;return Y(o,t,"Codestral",c,p,n),p}catch(a){throw B(o,t,"Codestral",a,n),a}}}class uc extends ee{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 Yn({token:this.params.config.key})}isValidCohereV2Response(e){const t=e;return t?.message?.content!==void 0&&Array.isArray(t.message.content)&&t.message.content.length>0&&typeof t.message.content[0]?.text=="string"}getServiceSpecificErrorMessage(e){const t=e.message||"";return t.includes("API key")||t.includes("api_key")?"Invalid API key. Check your Cohere API key in configuration":t.includes("rate_limit")||t.includes("Rate limit")?"Rate limit exceeded. Wait a moment and try again, or upgrade your Cohere plan":t.includes("model")||t.includes("Model")?"Model not found or not accessible. Check if the Cohere model name is correct":t.includes("overloaded")||t.includes("capacity")?"Cohere service is overloaded. Try again in a few minutes":t.includes("403")||t.includes("Forbidden")?"Access denied. Your API key may not have permission for this Cohere model":t.includes("404")||t.includes("Not Found")?"Model or endpoint not found. Check your Cohere model configuration":t.includes("500")||t.includes("Internal Server Error")?"Cohere server error. Try again later":null}generateCommitMessage$(){return T(this.generateMessage("commit")).pipe(_(e=>O(e)),N(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})),F(this.handleError$))}generateCodeReview$(){return T(this.generateMessage("review")).pipe(_(e=>O(e)),N(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),F(this.handleError$))}async generateMessage(e){const t=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:n,codeReviewPromptPath:s,logging:i,temperature:l,locale:a,generate:d,type:c,maxLength:u,maxTokens:f}=this.params.config,p={...J,locale:a,maxLength:u,type:c,generate:d,systemPrompt:o,systemPromptPath:n,codeReviewPromptPath:s,vcs_branch:this.params.branchName||""},h=e==="review"?re(p):te(p),y=`Here is the diff: ${t}`,g=[...h?[{role:"system",content:h}]:[],{role:"user",content:y}],b=`${this.params.config.url}/v2/chat`;Q(t,e,"Cohere",this.params.config.model,b,{},i),Z(t,e,"Cohere",h,y,i);const E={model:this.params.config.model,messages:g,max_tokens:f,temperature:l,seed:dt(10,1e3),p:this.params.config.topP};oe(t,e,"Cohere",E,i);const k=Date.now();try{const $=await this.cohere.chat(E,{timeoutInSeconds:Math.floor(this.params.config.timeout/1e3)}),P=Date.now()-k;if(!this.isValidCohereV2Response($))throw new Error("Invalid response structure from Cohere v2 API");const R=$.message.content[0].text;return W(t,e,"Cohere",$,i),Y(t,e,"Cohere",P,R,i),e==="review"?this.sanitizeResponse(R):this.parseMessage(R,c,d)}catch($){throw B(t,e,"Cohere",$,i),$}}}class dc extends ee{constructor(e){super(e),this.params=e,this.colors={primary:"#53a3f9",secondary:"#fff"},this.serviceName=C.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[DeepSeek]"),this.errorPrefix=C.red.bold("[DeepSeek]");const t=this.params.config.url||"https://api.deepseek.com";this.deepSeek=new Kr({baseURL:t,apiKey:this.params.config.key})}getServiceSpecificErrorMessage(e){const t=e.message||"";return t.includes("API key")||t.includes("api_key")?"Invalid API key. Check your DeepSeek API key in configuration":t.includes("rate_limit")||t.includes("Rate limit")?"Rate limit exceeded. Wait a moment and try again, or upgrade your DeepSeek plan":t.includes("model")||t.includes("Model")?"Model not found or not accessible. Check if the DeepSeek model name is correct":t.includes("Invalid model type")?"Invalid model type. Use supported models: deepseek-reasoner, deepseek-chat":t.includes("overloaded")||t.includes("capacity")?"DeepSeek service is overloaded. Try again in a few minutes":t.includes("403")||t.includes("Forbidden")?"Access denied. Your API key may not have permission for this DeepSeek model":t.includes("404")||t.includes("Not Found")?"Model or endpoint not found. Check your DeepSeek model configuration":t.includes("500")||t.includes("Internal Server Error")?"DeepSeek server error. Try again later":null}generateCommitMessage$(){return T(this.generateMessage("commit")).pipe(_(e=>O(e)),N(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})),F(this.handleError$))}generateCodeReview$(){return T(this.generateMessage("review")).pipe(_(e=>O(e)),N(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),F(this.handleError$))}async generateMessage(e){const t=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:n,codeReviewPromptPath:s,logging:i,locale:l,generate:a,type:d,maxLength:c}=this.params.config,u={...J,locale:l,maxLength:c,type:d,generate:a,systemPrompt:o,systemPromptPath:n,codeReviewPromptPath:s,vcs_branch:this.params.branchName||""},f=e==="review"?re(u):te(u);this.checkAvailableModels();const p=ye(t,e),y=`${this.params.config.url||"https://api.deepseek.com"}/chat/completions`,g={Authorization:`Bearer ${this.params.config.key}`,"Content-Type":"application/json"};Q(t,e,"DeepSeek",this.params.config.model,y,g,i),Z(t,e,"DeepSeek",f,p,i);const v=await this.createChatCompletions(f,p,e);return e==="review"?this.sanitizeResponse(v):this.parseMessage(v,d,a)}checkAvailableModels(){if(["deepseek-reasoner","deepseek-chat"].includes(this.params.config.model))return!0;throw new Error("Invalid model type of DeepSeek")}async createChatCompletions(e,t,o){const n=this.params.stagedDiff.diff,{logging:s}=this.params.config,i={messages:[{role:"system",content:e},{role:"user",content:t}],model:this.params.config.model,max_tokens:this.params.config.maxTokens,top_p:this.params.config.topP,temperature:this.params.config.temperature};oe(n,o,"DeepSeek",i,s);const l=Date.now();try{const a=await this.deepSeek.chat.completions.create(i,{timeout:this.params.config.timeout}),d=Date.now()-l,c=a.choices?.[0];if(!c?.message)throw new Error("DeepSeek API returned invalid response structure");const u=c.message.content||c.message.reasoning_content||"";if(!u)throw new Error("DeepSeek API returned empty response");return W(n,o,"DeepSeek",a,s),Y(n,o,"DeepSeek",d,u,s),u}catch(a){throw B(n,o,"DeepSeek",a,s),a}}}class mc extends ee{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 Jn(this.params.config.key)}getServiceSpecificErrorMessage(e){const t=e.message||"";return t.includes("API key")||t.includes("api_key")?"Invalid API key. Check your Google AI Studio API key in configuration":t.includes("quota")||t.includes("QUOTA_EXCEEDED")?"API quota exceeded. Check your Google AI Studio usage limits":t.includes("model")||t.includes("Model")?"Model not found or not accessible. Check if the Gemini model name is correct":t.includes("SAFETY")||t.includes("safety")?"Content blocked by safety filters. Try rephrasing your request":t.includes("RECITATION")||t.includes("recitation")?"Content blocked due to recitation concerns. Try a different approach":t.includes("403")||t.includes("Forbidden")?"Access denied. Your API key may not have permission for this Gemini model":t.includes("404")||t.includes("Not Found")?"Model or endpoint not found. Check your Gemini model configuration":t.includes("500")||t.includes("Internal Server Error")?"Google AI service error. Try again later":t.includes("MAX_TOKENS")||t.includes("truncated")||t.includes("maxOutputTokens")?"Response truncated due to token limit. Gemini 2.5+ models use thinking tokens. Try increasing maxTokens (recommended: 8192+)":null}generateCommitMessage$(){return T(this.generateMessage("commit")).pipe(_(e=>O(e)),N(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})),F(this.handleError$))}generateCodeReview$(){return T(this.generateMessage("review")).pipe(_(e=>O(e)),N(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),F(this.handleError$))}async generateMessage(e){const t=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:n,logging:s,locale:i,codeReviewPromptPath:l,generate:a,type:d,maxLength:c}=this.params.config,u=this.params.config.maxTokens,f={...J,locale:i,maxLength:c,type:d,generate:a,systemPrompt:o,systemPromptPath:n,codeReviewPromptPath:l,vcs_branch:this.params.branchName||""},p=e==="review"?re(f):te(f),h={maxOutputTokens:u,temperature:this.params.config.temperature,topP:this.params.config.topP},y=this.genAI.getGenerativeModel({model:this.params.config.model,systemInstruction:p,generationConfig:h,safetySettings:[{category:Qe.HARM_CATEGORY_HATE_SPEECH,threshold:Ze.BLOCK_LOW_AND_ABOVE},{category:Qe.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:Ze.BLOCK_LOW_AND_ABOVE},{category:Qe.HARM_CATEGORY_HARASSMENT,threshold:Ze.BLOCK_LOW_AND_ABOVE},{category:Qe.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:Ze.BLOCK_LOW_AND_ABOVE}]}),g=ye(t,e),b=`${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(t,e,"Gemini",this.params.config.model,b,E,s),Z(t,e,"Gemini",p,g,s),oe(t,e,"Gemini",{systemInstruction:{parts:[{text:p}]},contents:[{parts:[{text:g}]}],generationConfig:h},s);const $=Date.now();try{const P=this.params.config.timeout>1e4?{request:{timeout:this.params.config.timeout}}:void 0,R=await y.generateContent(g,P),A=R.response;if(A.candidates?.[0]?.finishReason==="MAX_TOKENS"){const Re=A.usageMetadata;throw new Error(`Response truncated: maxOutputTokens exceeded. Thinking tokens: ${Re?.thoughtsTokenCount??"N/A"}, Output tokens: ${Re?.candidatesTokenCount??"N/A"}. Increase maxTokens config for Gemini 2.5+ thinking models.`)}const S=A.text(),K=Date.now()-$;return W(t,e,"Gemini",{response:S,candidates:R.response.candidates,usageMetadata:R.response.usageMetadata},s),Y(t,e,"Gemini",K,S,s),e==="review"?this.sanitizeResponse(S):this.parseMessage(S,d,a)}catch(P){throw B(t,e,"Gemini",P,s),P}}}var ar={},cr={exports:{}},ze={exports:{}},lr,sn;function fc(){if(sn)return lr;sn=1;var r=1e3,e=r*60,t=e*60,o=t*24,n=o*7,s=o*365.25;lr=function(c,u){u=u||{};var f=typeof c;if(f==="string"&&c.length>0)return i(c);if(f==="number"&&isFinite(c))return u.long?a(c):l(c);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(c))};function i(c){if(c=String(c),!(c.length>100)){var u=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(c);if(u){var f=parseFloat(u[1]),p=(u[2]||"ms").toLowerCase();switch(p){case"years":case"year":case"yrs":case"yr":case"y":return f*s;case"weeks":case"week":case"w":return f*n;case"days":case"day":case"d":return f*o;case"hours":case"hour":case"hrs":case"hr":case"h":return f*t;case"minutes":case"minute":case"mins":case"min":case"m":return f*e;case"seconds":case"second":case"secs":case"sec":case"s":return f*r;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return f;default:return}}}}function l(c){var u=Math.abs(c);return u>=o?Math.round(c/o)+"d":u>=t?Math.round(c/t)+"h":u>=e?Math.round(c/e)+"m":u>=r?Math.round(c/r)+"s":c+"ms"}function a(c){var u=Math.abs(c);return u>=o?d(c,u,o,"day"):u>=t?d(c,u,t,"hour"):u>=e?d(c,u,e,"minute"):u>=r?d(c,u,r,"second"):c+" ms"}function d(c,u,f,p){var h=u>=f*1.5;return Math.round(c/f)+" "+p+(h?"s":"")}return lr}var ur,an;function cn(){if(an)return ur;an=1;function r(e){o.debug=o,o.default=o,o.coerce=d,o.disable=l,o.enable=s,o.enabled=a,o.humanize=fc(),o.destroy=c,Object.keys(e).forEach(u=>{o[u]=e[u]}),o.names=[],o.skips=[],o.formatters={};function t(u){let f=0;for(let p=0;p<u.length;p++)f=(f<<5)-f+u.charCodeAt(p),f|=0;return o.colors[Math.abs(f)%o.colors.length]}o.selectColor=t;function o(u){let f,p=null,h,y;function g(...v){if(!g.enabled)return;const b=g,E=Number(new Date),k=E-(f||E);b.diff=k,b.prev=f,b.curr=E,f=E,v[0]=o.coerce(v[0]),typeof v[0]!="string"&&v.unshift("%O");let $=0;v[0]=v[0].replace(/%([a-zA-Z%])/g,(R,A)=>{if(R==="%%")return"%";$++;const D=o.formatters[A];if(typeof D=="function"){const S=v[$];R=D.call(b,S),v.splice($,1),$--}return R}),o.formatArgs.call(b,v),(b.log||o.log).apply(b,v)}return g.namespace=u,g.useColors=o.useColors(),g.color=o.selectColor(u),g.extend=n,g.destroy=o.destroy,Object.defineProperty(g,"enabled",{enumerable:!0,configurable:!1,get:()=>p!==null?p:(h!==o.namespaces&&(h=o.namespaces,y=o.enabled(u)),y),set:v=>{p=v}}),typeof o.init=="function"&&o.init(g),g}function n(u,f){const p=o(this.namespace+(typeof f>"u"?":":f)+u);return p.log=this.log,p}function s(u){o.save(u),o.namespaces=u,o.names=[],o.skips=[];const f=(typeof u=="string"?u:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(const p of f)p[0]==="-"?o.skips.push(p.slice(1)):o.names.push(p)}function i(u,f){let p=0,h=0,y=-1,g=0;for(;p<u.length;)if(h<f.length&&(f[h]===u[p]||f[h]==="*"))f[h]==="*"?(y=h,g=p,h++):(p++,h++);else if(y!==-1)h=y+1,g++,p=g;else return!1;for(;h<f.length&&f[h]==="*";)h++;return h===f.length}function l(){const u=[...o.names,...o.skips.map(f=>"-"+f)].join(",");return o.enable(""),u}function a(u){for(const f of o.skips)if(i(u,f))return!1;for(const f of o.names)if(i(u,f))return!0;return!1}function d(u){return u instanceof Error?u.stack||u.message:u}function c(){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 ur=r,ur}ze.exports;var ln;function pc(){return ln||(ln=1,function(r,e){e.formatArgs=o,e.save=n,e.load=s,e.useColors=t,e.storage=i(),e.destroy=(()=>{let a=!1;return()=>{a||(a=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),e.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function t(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let a;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&(a=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(a[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function o(a){if(a[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+a[0]+(this.useColors?"%c ":" ")+"+"+r.exports.humanize(this.diff),!this.useColors)return;const d="color: "+this.color;a.splice(1,0,d,"color: inherit");let c=0,u=0;a[0].replace(/%[a-zA-Z%]/g,f=>{f!=="%%"&&(c++,f==="%c"&&(u=c))}),a.splice(u,0,d)}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{}}r.exports=cn()(e);const{formatters:l}=r.exports;l.j=function(a){try{return JSON.stringify(a)}catch(d){return"[UnexpectedJSONParseError]: "+d.message}}}(ze,ze.exports)),ze.exports}var Ke={exports:{}},dr,un;function hc(){return un||(un=1,dr=(r,e=process.argv)=>{const t=r.startsWith("-")?"":r.length===1?"-":"--",o=e.indexOf(t+r),n=e.indexOf("--");return o!==-1&&(n===-1||o<n)}),dr}var mr,dn;function gc(){if(dn)return mr;dn=1;const r=De,e=Wr,t=hc(),{env:o}=process;let n;t("no-color")||t("no-colors")||t("color=false")||t("color=never")?n=0:(t("color")||t("colors")||t("color=true")||t("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,d){if(n===0)return 0;if(t("color=16m")||t("color=full")||t("color=truecolor"))return 3;if(t("color=256"))return 2;if(a&&!d&&n===void 0)return 0;const c=n||0;if(o.TERM==="dumb")return c;if(process.platform==="win32"){const u=r.release().split(".");return Number(u[0])>=10&&Number(u[2])>=10586?Number(u[2])>=14931?3:2:1}if("CI"in o)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE"].some(u=>u in o)||o.CI_NAME==="codeship"?1:c;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 u=parseInt((o.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(o.TERM_PROGRAM){case"iTerm.app":return u>=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:c}function l(a){const d=i(a,a&&a.isTTY);return s(d)}return mr={supportsColor:l,stdout:s(i(!0,e.isatty(1))),stderr:s(i(!0,e.isatty(2)))},mr}Ke.exports;var mn;function yc(){return mn||(mn=1,function(r,e){const t=Wr,o=_r;e.init=c,e.log=l,e.formatArgs=s,e.save=a,e.load=d,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 f=gc();f&&(f.stderr||f).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(f=>/^debug_/i.test(f)).reduce((f,p)=>{const h=p.substring(6).toLowerCase().replace(/_([a-z])/g,(g,v)=>v.toUpperCase());let y=process.env[p];return/^(yes|on|true|enabled)$/i.test(y)?y=!0:/^(no|off|false|disabled)$/i.test(y)?y=!1:y==="null"?y=null:y=Number(y),f[h]=y,f},{});function n(){return"colors"in e.inspectOpts?!!e.inspectOpts.colors:t.isatty(process.stderr.fd)}function s(f){const{namespace:p,useColors:h}=this;if(h){const y=this.color,g="\x1B[3"+(y<8?y:"8;5;"+y),v=` ${g};1m${p} \x1B[0m`;f[0]=v+f[0].split(`
|
|
70
|
+
Focus on understanding the purpose and impact of these changes to create meaningful commit message(s).`,sc=10*60*1e3;class ic extends ee{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 Kn({apiKey:this.params.config.key,...this.params.config.timeout>sc&&{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_not_found")||r.includes("Model not found")||/model.*does not exist/i.test(r)?"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 L(this.generateMessage("commit")).pipe(_(e=>D(e)),O(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})),N(this.handleError$))}generateCodeReview$(){return L(this.generateMessage("review")).pipe(_(e=>D(e)),O(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),N(this.handleError$))}async generateMessage(e){const r=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:n,codeReviewPromptPath:s,logging:i,temperature:l,locale:a,generate:d,type:c,maxLength:u,maxTokens:f,topP:p,model:h}=this.params.config,y={...J,locale:a,maxLength:u,type:c,generate:d,systemPrompt:o,systemPromptPath:n,codeReviewPromptPath:s,vcs_branch:this.params.branchName||""},g=e==="review"?re(y):te(y),v=ye(r,e),E=`${this.params.config.url||"https://api.anthropic.com"}/v1/messages`,k={"Content-Type":"application/json","x-api-key":this.params.config.key,"anthropic-version":"2023-06-01"};Q(r,e,"Anthropic",h,E,k,i),Z(r,e,"Anthropic",g,v,i);const $=tc(h),P={max_tokens:f,temperature:l,system:g,messages:[{role:"user",content:v}],model:h,...$?{}:{top_p:p}};oe(r,e,"Anthropic",P,i);const R=Date.now();try{const A=await this.anthropic.messages.create(P),B=Date.now()-R;W(r,e,"Anthropic",A,i);const S=A.content.map(({text:K})=>K).join("");return Y(r,e,"Anthropic",B,S,i),e==="review"?this.sanitizeResponse(S):this.parseMessage(S,c,d)}catch(A){throw j(r,e,"Anthropic",A,i),A}}}const ne="Bedrock",me={MISSING_DEPENDENCY:"MissingDependencyError",MISSING_REGION:"MissingRegionError",MISSING_MODEL_ID:"MissingModelIdError",MISSING_API_KEY:"MissingApiKeyError",MISSING_APPLICATION_KEY:"MissingApplicationKeyError",INVALID_RESPONSE:"InvalidResponseError",EMPTY_RESPONSE:"EmptyResponseError"},z=t=>typeof t=="string"&&t.length>0;let He=null,Ue=null;const on=t=>{const e=new Error('Amazon Bedrock support requires "@aws-sdk/client-bedrock-runtime" and "@aws-sdk/credential-providers". Install them with `pnpm add @aws-sdk/client-bedrock-runtime @aws-sdk/credential-providers`.');return e.name=me.MISSING_DEPENDENCY,e.originalError=t,e},ac=async()=>{if(He)return He;try{return He=await import("@aws-sdk/client-bedrock-runtime"),He}catch(t){throw He=null,on(t)}},nn=async()=>{if(Ue)return Ue;try{return Ue=await import("@aws-sdk/credential-providers"),Ue}catch(t){throw Ue=null,on(t)}};class cc extends ee{constructor(e){super(e),this.params=e,this.credentialCache=void 0,this.credentialCacheTimestamp=0,this.CREDENTIAL_CACHE_TTL=5*60*1e3,this.bedrockConfig=this.params.config,this.colors={primary:"#232F3E",secondary:"#FF9900"},this.serviceName=C.bgHex(this.colors.primary).hex(this.colors.secondary).bold(`[${ne}]`),this.errorPrefix=C.red.bold(`[${ne}]`),this.validateConfiguration()}validateConfiguration(){const e=this.bedrockConfig;if(!z(e.model)){const n=new Error("Model ID or inference profile ARN is required.");throw n.name=me.MISSING_MODEL_ID,n}if(!this.getRegion()){const n=new Error("AWS region is required. Configure BEDROCK.region or set AWS_REGION/AWS_DEFAULT_REGION.");throw n.name=me.MISSING_REGION,n}const r=z(e.key),o=this.canUseAwsSdk();if(!r&&!o){const n=new Error("Authentication required: Configure AWS credentials (profile, access keys, IAM role) or API key (BEDROCK.key).");throw n.name=me.MISSING_API_KEY,n}if(r&&!o&&!this.getRegion()&&!z(e.applicationBaseUrl)){const n=new Error("Bearer token authentication requires region or applicationBaseUrl to construct endpoint.");throw n.name=me.MISSING_REGION,n}}canUseAwsSdk(){const e=this.bedrockConfig,r=z(e.profile)||z(process.env.AWS_PROFILE),o=z(e.accessKeyId)&&z(e.secretAccessKey)||z(process.env.AWS_ACCESS_KEY_ID)&&z(process.env.AWS_SECRET_ACCESS_KEY);return r||o}determineAuthMethod(){const e=z(this.bedrockConfig.key);if(this.canUseAwsSdk())return"aws-sdk";if(e)return"bearer-token";throw new Error("No authentication method configured")}getServiceSpecificErrorMessage(e){const r=e?.name||e.code,o=e.message||"";switch(r){case"UnrecognizedClientException":case"InvalidSignatureException":return"Authentication with AWS failed. Check your IAM credentials or Bedrock API key settings.";case"AccessDeniedException":return"Access denied. Ensure the IAM principal or application key has permission to invoke the Bedrock resource.";case"ValidationException":return"Invalid request for the selected Bedrock model. Verify the model ID and payload.";case"ResourceNotFoundException":return"The specified Bedrock model, endpoint, or inference profile could not be found.";case"ThrottlingException":return"Request throttled by Bedrock. Reduce request rate or check service quotas."}return o.includes("Region")?"AWS region is required for Bedrock. Configure BEDROCK.region or set AWS_REGION/AWS_DEFAULT_REGION.":null}generateCommitMessage$(){return L(this.generateMessage("commit")).pipe(_(e=>D(e)),O(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})),N(this.handleError$))}generateCodeReview$(){return L(this.generateMessage("review")).pipe(_(e=>D(e)),O(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),N(this.handleError$))}async generateMessage(e){const r=this.params.stagedDiff.diff,o=this.bedrockConfig,n=o.model,{logging:s,inferenceParameters:i}=o,l={...J,locale:o.locale,maxLength:o.maxLength,type:o.type,generate:o.generate,systemPrompt:o.systemPrompt,systemPromptPath:o.systemPromptPath,codeReviewPromptPath:o.codeReviewPromptPath},a=e==="review"?re(l):te(l),d=ye(r,e),c={region:this.getRegion(),profile:o.profile,modelId:n},u=`https://bedrock-runtime.${this.getRegion()||"unknown"}.amazonaws.com/model/${encodeURIComponent(n)}/converse`;Q(r,e,ne,n,u,c,s),Z(r,e,ne,a,d,s);const f={modelId:n,systemPrompt:a,userPrompt:d,...i&&Object.keys(i).length>0&&{inferenceConfig:i}};oe(r,e,ne,f,s);const p=Date.now();try{const h=this.determineAuthMethod();yt()&&(console.log(C.cyan(`[Bedrock] Authentication method: ${h}`)),console.log(C.cyan(`[Bedrock] Model ID: ${n}`)),console.log(C.cyan(`[Bedrock] Region: ${this.getRegion()}`)),console.log(C.cyan(`[Bedrock] Has AWS credentials: ${this.canUseAwsSdk()}`)),console.log(C.cyan(`[Bedrock] Has API key: ${z(o.key)}`)));const y=h==="bearer-token"?await this.invokeWithBearerToken({model:n,systemPrompt:a,userPrompt:d,logging:s,requestType:e,diff:r,inferenceConfig:i}):await this.invokeWithAwsSdk({model:n,systemPrompt:a,userPrompt:d,logging:s,requestType:e,diff:r,inferenceConfig:i}),g=Date.now()-p;return Y(r,e,ne,g,y,s),e==="review"?this.sanitizeResponse(y):this.parseMessage(y,o.type,o.generate)}catch(h){throw j(r,e,ne,h,s),h instanceof Error&&(h.status=h?.status||h?.$metadata?.httpStatusCode),h}}async invokeWithAwsSdk(e){const r=this.getRegion(),{model:o,systemPrompt:n,userPrompt:s,inferenceConfig:i,logging:l,requestType:a,diff:d}=e,{BedrockRuntimeClient:c,ConverseCommand:u}=await ac(),f=this.bedrockConfig,p={region:r,requestHandler:{requestTimeout:f.timeout||12e4}},h=await this.resolveCredentials();h&&(p.credentials=h);const y=new c(p),g=new u({modelId:o,messages:[{role:"user",content:[{text:s}]}],...n?{system:[{text:n}]}:{},...i&&Object.keys(i).length>0&&{inferenceConfig:i}});yt()&&console.log(C.cyan(`[Bedrock] Sending ConverseCommand with modelId: ${o}`));let v;try{v=await y.send(g),W(d,a,ne,v,l)}catch(E){throw yt()&&(console.error(C.red(`[Bedrock] AWS SDK Error: ${E.name}`)),console.error(C.red(`[Bedrock] Error message: ${E.message}`)),E.$metadata&&(console.error(C.red(`[Bedrock] Request ID: ${E.$metadata.requestId}`)),console.error(C.red(`[Bedrock] HTTP Status: ${E.$metadata.httpStatusCode}`))),E.$fault&&console.error(C.red(`[Bedrock] Fault: ${E.$fault}`))),E}const b=v.output?.message?.content?.[0]?.text||"";if(!b){const E=new Error("No text content found in Bedrock response.");throw E.name=me.EMPTY_RESPONSE,E.content=v,E}return b}invokeWithBearerToken(e){const{model:r,systemPrompt:o,userPrompt:n,inferenceConfig:s,logging:i,requestType:l,diff:a}=e,d=this.bedrockConfig,c=this.getRegion(),u=encodeURIComponent(r),f=d.applicationBaseUrl||`https://bedrock-runtime.${c}.amazonaws.com/model/${u}/converse`,p=new URL(f),h={modelId:r,messages:[{role:"user",content:[{text:n}]}],...s&&Object.keys(s).length>0&&{inferenceConfig:s}};o&&(h.system=[{text:o}]);const y=JSON.stringify(h),g={"Content-Type":"application/json","Content-Length":Buffer.byteLength(y).toString()};return z(d.key)&&(g.Authorization=`Bearer ${d.key}`),z(d.applicationInferenceProfileArn)&&(g["x-amzn-bedrock-inference-profile-arn"]=d.applicationInferenceProfileArn),z(d.applicationEndpointId)&&(g["x-amzn-bedrock-endpoint-id"]=d.applicationEndpointId),new Promise((v,b)=>{const E=Wr.request({method:"POST",protocol:p.protocol,hostname:p.hostname,port:p.port,path:p.pathname+p.search,headers:g,timeout:d.timeout},k=>{const $=[];k.on("data",P=>$.push(P)),k.on("end",()=>{const P=Buffer.concat($).toString("utf8");if(k.statusCode&&k.statusCode>=400){const S=new Error(`Bedrock application endpoint responded with status ${k.statusCode}.`);return S.status=k.statusCode,S.content=P,j(a,l,ne,S,i),b(S)}const R=Vo(P);if(!R.ok){const S=new Error("Failed to parse Bedrock application response as JSON. The Bedrock Converse API should always return valid JSON.");return S.name=me.INVALID_RESPONSE,S.content=P,j(a,l,ne,S,i),b(S)}const A=R.data;W(a,l,ne,A,i);const B=A.output?.message?.content?.[0]?.text||"";if(!B){const S=new Error("No text content found in Bedrock response.");return S.name=me.EMPTY_RESPONSE,S.content=A,j(a,l,ne,S,i),b(S)}v(B)})});E.on("error",k=>{const $=k;j(a,l,ne,$,i),b($)}),E.write(y),E.end()})}getRegion(){return this.bedrockConfig.region||process.env.AWS_REGION||process.env.AWS_DEFAULT_REGION||""}async resolveCredentials(){const e=Date.now();if(this.credentialCache&&e-this.credentialCacheTimestamp<this.CREDENTIAL_CACHE_TTL)return this.credentialCache;const r=this.bedrockConfig,o=r.profile,n=r.accessKeyId,s=r.secretAccessKey,i=r.sessionToken;let l;if(z(o)){const{fromIni:a}=await nn();l=a({profile:o})}else if(z(n)&&z(s))l=async()=>({accessKeyId:n,secretAccessKey:s,sessionToken:i||process.env.AWS_SESSION_TOKEN||void 0});else if(process.env.AWS_PROFILE){const{fromIni:a}=await nn();l=a({profile:process.env.AWS_PROFILE})}return l&&(this.credentialCache=l,this.credentialCacheTimestamp=e),l}}class ze{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=Wn.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 lc extends ee{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 L(this.generateMessage("commit")).pipe(_(e=>D(e)),O(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})),N(this.handleError$))}generateCodeReview$(){return L(this.generateMessage("review")).pipe(_(e=>D(e)),O(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),N(this.handleError$))}async generateMessage(e){const r=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:n,codeReviewPromptPath:s,logging:i,locale:l,generate:a,type:d,maxLength:c}=this.params.config,u={...J,locale:l,maxLength:c,type:d,generate:a,systemPrompt:o,systemPromptPath:n,codeReviewPromptPath:s,vcs_branch:this.params.branchName||""},f=e==="review"?re(u):te(u);this.checkAvailableModels();const p=ye(r,e),y=`${this.params.config.url||"https://codestral.mistral.ai"}/v1/chat/completions`,g={Authorization:`Bearer ${this.apiKey}`,"content-type":"application/json"};Q(r,e,"Codestral",this.params.config.model,y,g,i),Z(r,e,"Codestral",f,p,i);const v=await this.createChatCompletions(f,e);return e==="review"?this.sanitizeResponse(v):this.parseMessage(v,d,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:ye(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:mt(10,1e3)};r==="commit"&&(i.response_format={type:"json_object"}),oe(o,r,"Codestral",i,n);const l=Date.now();try{const d=await new ze({method:"POST",baseURL:`${s}/v1/chat/completions`,timeout:this.params.config.timeout}).setHeaders({Authorization:`Bearer ${this.apiKey}`,"content-type":"application/json"}).setBody(i).execute(),c=Date.now()-l,u=d.data;if(W(o,r,"Codestral",u,n),!u.choices||u.choices.length===0||!u.choices[0].message?.content)throw j(o,r,"Codestral",{message:"No Content on response",result:u},n),new Error("No Content on response. Please open a Bug report");const p=u.choices[0].message.content;return Y(o,r,"Codestral",c,p,n),p}catch(a){throw j(o,r,"Codestral",a,n),a}}}class uc extends ee{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 Yn({token:this.params.config.key})}isValidCohereV2Response(e){const r=e;return r?.message?.content!==void 0&&Array.isArray(r.message.content)&&r.message.content.length>0&&typeof r.message.content[0]?.text=="string"}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 L(this.generateMessage("commit")).pipe(_(e=>D(e)),O(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})),N(this.handleError$))}generateCodeReview$(){return L(this.generateMessage("review")).pipe(_(e=>D(e)),O(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),N(this.handleError$))}async generateMessage(e){const r=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:n,codeReviewPromptPath:s,logging:i,temperature:l,locale:a,generate:d,type:c,maxLength:u,maxTokens:f}=this.params.config,p={...J,locale:a,maxLength:u,type:c,generate:d,systemPrompt:o,systemPromptPath:n,codeReviewPromptPath:s,vcs_branch:this.params.branchName||""},h=e==="review"?re(p):te(p),y=`Here is the diff: ${r}`,g=[...h?[{role:"system",content:h}]:[],{role:"user",content:y}],b=`${this.params.config.url}/v2/chat`;Q(r,e,"Cohere",this.params.config.model,b,{},i),Z(r,e,"Cohere",h,y,i);const E={model:this.params.config.model,messages:g,max_tokens:f,temperature:l,seed:mt(10,1e3),p:this.params.config.topP};oe(r,e,"Cohere",E,i);const k=Date.now();try{const $=await this.cohere.chat(E,{timeoutInSeconds:Math.floor(this.params.config.timeout/1e3)}),P=Date.now()-k;if(!this.isValidCohereV2Response($))throw new Error("Invalid response structure from Cohere v2 API");const R=$.message.content[0].text;return W(r,e,"Cohere",$,i),Y(r,e,"Cohere",P,R,i),e==="review"?this.sanitizeResponse(R):this.parseMessage(R,c,d)}catch($){throw j(r,e,"Cohere",$,i),$}}}class dc extends ee{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 Yr({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 L(this.generateMessage("commit")).pipe(_(e=>D(e)),O(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})),N(this.handleError$))}generateCodeReview$(){return L(this.generateMessage("review")).pipe(_(e=>D(e)),O(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),N(this.handleError$))}async generateMessage(e){const r=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:n,codeReviewPromptPath:s,logging:i,locale:l,generate:a,type:d,maxLength:c}=this.params.config,u={...J,locale:l,maxLength:c,type:d,generate:a,systemPrompt:o,systemPromptPath:n,codeReviewPromptPath:s,vcs_branch:this.params.branchName||""},f=e==="review"?re(u):te(u);this.checkAvailableModels();const p=ye(r,e),y=`${this.params.config.url||"https://api.deepseek.com"}/chat/completions`,g={Authorization:`Bearer ${this.params.config.key}`,"Content-Type":"application/json"};Q(r,e,"DeepSeek",this.params.config.model,y,g,i),Z(r,e,"DeepSeek",f,p,i);const v=await this.createChatCompletions(f,p,e);return e==="review"?this.sanitizeResponse(v):this.parseMessage(v,d,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 l=Date.now();try{const a=await this.deepSeek.chat.completions.create(i,{timeout:this.params.config.timeout}),d=Date.now()-l,c=a.choices?.[0];if(!c?.message)throw new Error("DeepSeek API returned invalid response structure");const u=c.message.content||c.message.reasoning_content||"";if(!u)throw new Error("DeepSeek API returned empty response");return W(n,o,"DeepSeek",a,s),Y(n,o,"DeepSeek",d,u,s),u}catch(a){throw j(n,o,"DeepSeek",a,s),a}}}class mc extends ee{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 Jn(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":r.includes("MAX_TOKENS")||r.includes("truncated")||r.includes("maxOutputTokens")?"Response truncated due to token limit. Gemini 2.5+ models use thinking tokens. Try increasing maxTokens (recommended: 8192+)":null}generateCommitMessage$(){return L(this.generateMessage("commit")).pipe(_(e=>D(e)),O(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})),N(this.handleError$))}generateCodeReview$(){return L(this.generateMessage("review")).pipe(_(e=>D(e)),O(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),N(this.handleError$))}async generateMessage(e){const r=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:n,logging:s,locale:i,codeReviewPromptPath:l,generate:a,type:d,maxLength:c}=this.params.config,u=this.params.config.maxTokens,f={...J,locale:i,maxLength:c,type:d,generate:a,systemPrompt:o,systemPromptPath:n,codeReviewPromptPath:l,vcs_branch:this.params.branchName||""},p=e==="review"?re(f):te(f),h={maxOutputTokens:u,temperature:this.params.config.temperature,topP:this.params.config.topP},y=this.genAI.getGenerativeModel({model:this.params.config.model,systemInstruction:p,generationConfig:h,safetySettings:[{category:Ze.HARM_CATEGORY_HATE_SPEECH,threshold:et.BLOCK_LOW_AND_ABOVE},{category:Ze.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:et.BLOCK_LOW_AND_ABOVE},{category:Ze.HARM_CATEGORY_HARASSMENT,threshold:et.BLOCK_LOW_AND_ABOVE},{category:Ze.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:et.BLOCK_LOW_AND_ABOVE}]}),g=ye(r,e),b=`${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,b,E,s),Z(r,e,"Gemini",p,g,s),oe(r,e,"Gemini",{systemInstruction:{parts:[{text:p}]},contents:[{parts:[{text:g}]}],generationConfig:h},s);const $=Date.now();try{const P=this.params.config.timeout>1e4?{request:{timeout:this.params.config.timeout}}:void 0,R=await y.generateContent(g,P),A=R.response;if(A.candidates?.[0]?.finishReason==="MAX_TOKENS"){const De=A.usageMetadata;throw new Error(`Response truncated: maxOutputTokens exceeded. Thinking tokens: ${De?.thoughtsTokenCount??"N/A"}, Output tokens: ${De?.candidatesTokenCount??"N/A"}. Increase maxTokens config for Gemini 2.5+ thinking models.`)}const S=A.text(),K=Date.now()-$;return W(r,e,"Gemini",{response:S,candidates:R.response.candidates,usageMetadata:R.response.usageMetadata},s),Y(r,e,"Gemini",K,S,s),e==="review"?this.sanitizeResponse(S):this.parseMessage(S,d,a)}catch(P){throw j(r,e,"Gemini",P,s),P}}}var lr={},ur={exports:{}},Ke={exports:{}},dr,sn;function fc(){if(sn)return dr;sn=1;var t=1e3,e=t*60,r=e*60,o=r*24,n=o*7,s=o*365.25;dr=function(c,u){u=u||{};var f=typeof c;if(f==="string"&&c.length>0)return i(c);if(f==="number"&&isFinite(c))return u.long?a(c):l(c);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(c))};function i(c){if(c=String(c),!(c.length>100)){var u=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(c);if(u){var f=parseFloat(u[1]),p=(u[2]||"ms").toLowerCase();switch(p){case"years":case"year":case"yrs":case"yr":case"y":return f*s;case"weeks":case"week":case"w":return f*n;case"days":case"day":case"d":return f*o;case"hours":case"hour":case"hrs":case"hr":case"h":return f*r;case"minutes":case"minute":case"mins":case"min":case"m":return f*e;case"seconds":case"second":case"secs":case"sec":case"s":return f*t;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return f;default:return}}}}function l(c){var u=Math.abs(c);return u>=o?Math.round(c/o)+"d":u>=r?Math.round(c/r)+"h":u>=e?Math.round(c/e)+"m":u>=t?Math.round(c/t)+"s":c+"ms"}function a(c){var u=Math.abs(c);return u>=o?d(c,u,o,"day"):u>=r?d(c,u,r,"hour"):u>=e?d(c,u,e,"minute"):u>=t?d(c,u,t,"second"):c+" ms"}function d(c,u,f,p){var h=u>=f*1.5;return Math.round(c/f)+" "+p+(h?"s":"")}return dr}var mr,an;function cn(){if(an)return mr;an=1;function t(e){o.debug=o,o.default=o,o.coerce=d,o.disable=l,o.enable=s,o.enabled=a,o.humanize=fc(),o.destroy=c,Object.keys(e).forEach(u=>{o[u]=e[u]}),o.names=[],o.skips=[],o.formatters={};function r(u){let f=0;for(let p=0;p<u.length;p++)f=(f<<5)-f+u.charCodeAt(p),f|=0;return o.colors[Math.abs(f)%o.colors.length]}o.selectColor=r;function o(u){let f,p=null,h,y;function g(...v){if(!g.enabled)return;const b=g,E=Number(new Date),k=E-(f||E);b.diff=k,b.prev=f,b.curr=E,f=E,v[0]=o.coerce(v[0]),typeof v[0]!="string"&&v.unshift("%O");let $=0;v[0]=v[0].replace(/%([a-zA-Z%])/g,(R,A)=>{if(R==="%%")return"%";$++;const B=o.formatters[A];if(typeof B=="function"){const S=v[$];R=B.call(b,S),v.splice($,1),$--}return R}),o.formatArgs.call(b,v),(b.log||o.log).apply(b,v)}return g.namespace=u,g.useColors=o.useColors(),g.color=o.selectColor(u),g.extend=n,g.destroy=o.destroy,Object.defineProperty(g,"enabled",{enumerable:!0,configurable:!1,get:()=>p!==null?p:(h!==o.namespaces&&(h=o.namespaces,y=o.enabled(u)),y),set:v=>{p=v}}),typeof o.init=="function"&&o.init(g),g}function n(u,f){const p=o(this.namespace+(typeof f>"u"?":":f)+u);return p.log=this.log,p}function s(u){o.save(u),o.namespaces=u,o.names=[],o.skips=[];const f=(typeof u=="string"?u:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(const p of f)p[0]==="-"?o.skips.push(p.slice(1)):o.names.push(p)}function i(u,f){let p=0,h=0,y=-1,g=0;for(;p<u.length;)if(h<f.length&&(f[h]===u[p]||f[h]==="*"))f[h]==="*"?(y=h,g=p,h++):(p++,h++);else if(y!==-1)h=y+1,g++,p=g;else return!1;for(;h<f.length&&f[h]==="*";)h++;return h===f.length}function l(){const u=[...o.names,...o.skips.map(f=>"-"+f)].join(",");return o.enable(""),u}function a(u){for(const f of o.skips)if(i(u,f))return!1;for(const f of o.names)if(i(u,f))return!0;return!1}function d(u){return u instanceof Error?u.stack||u.message:u}function c(){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 mr=t,mr}Ke.exports;var ln;function pc(){return ln||(ln=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 d="color: "+this.color;a.splice(1,0,d,"color: inherit");let c=0,u=0;a[0].replace(/%[a-zA-Z%]/g,f=>{f!=="%%"&&(c++,f==="%c"&&(u=c))}),a.splice(u,0,d)}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=cn()(e);const{formatters:l}=t.exports;l.j=function(a){try{return JSON.stringify(a)}catch(d){return"[UnexpectedJSONParseError]: "+d.message}}}(Ke,Ke.exports)),Ke.exports}var We={exports:{}},fr,un;function hc(){return un||(un=1,fr=(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)}),fr}var pr,dn;function gc(){if(dn)return pr;dn=1;const t=Oe,e=Jr,r=hc(),{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,d){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&&!d&&n===void 0)return 0;const c=n||0;if(o.TERM==="dumb")return c;if(process.platform==="win32"){const u=t.release().split(".");return Number(u[0])>=10&&Number(u[2])>=10586?Number(u[2])>=14931?3:2:1}if("CI"in o)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE"].some(u=>u in o)||o.CI_NAME==="codeship"?1:c;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 u=parseInt((o.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(o.TERM_PROGRAM){case"iTerm.app":return u>=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:c}function l(a){const d=i(a,a&&a.isTTY);return s(d)}return pr={supportsColor:l,stdout:s(i(!0,e.isatty(1))),stderr:s(i(!0,e.isatty(2)))},pr}We.exports;var mn;function yc(){return mn||(mn=1,function(t,e){const r=Jr,o=jr;e.init=c,e.log=l,e.formatArgs=s,e.save=a,e.load=d,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 f=gc();f&&(f.stderr||f).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(f=>/^debug_/i.test(f)).reduce((f,p)=>{const h=p.substring(6).toLowerCase().replace(/_([a-z])/g,(g,v)=>v.toUpperCase());let y=process.env[p];return/^(yes|on|true|enabled)$/i.test(y)?y=!0:/^(no|off|false|disabled)$/i.test(y)?y=!1:y==="null"?y=null:y=Number(y),f[h]=y,f},{});function n(){return"colors"in e.inspectOpts?!!e.inspectOpts.colors:r.isatty(process.stderr.fd)}function s(f){const{namespace:p,useColors:h}=this;if(h){const y=this.color,g="\x1B[3"+(y<8?y:"8;5;"+y),v=` ${g};1m${p} \x1B[0m`;f[0]=v+f[0].split(`
|
|
71
71
|
`).join(`
|
|
72
|
-
`+v),f.push(g+"m+"+
|
|
73
|
-
`)}function a(f){f?process.env.DEBUG=f:delete process.env.DEBUG}function d(){return process.env.DEBUG}function c(f){f.inspectOpts={};const p=Object.keys(e.inspectOpts);for(let h=0;h<p.length;h++)f.inspectOpts[p[h]]=e.inspectOpts[p[h]]}
|
|
74
|
-
`).map(p=>p.trim()).join(" ")},u.O=function(f){return this.inspectOpts.colors=this.useColors,o.inspect(f,this.inspectOpts)}}(
|
|
75
|
-
`).some(e=>e.indexOf("(https.js:")!==-1||e.indexOf("node:https:")!==-1)}function vt(
|
|
72
|
+
`+v),f.push(g+"m+"+t.exports.humanize(this.diff)+"\x1B[0m")}else f[0]=i()+p+" "+f[0]}function i(){return e.inspectOpts.hideDate?"":new Date().toISOString()+" "}function l(...f){return process.stderr.write(o.formatWithOptions(e.inspectOpts,...f)+`
|
|
73
|
+
`)}function a(f){f?process.env.DEBUG=f:delete process.env.DEBUG}function d(){return process.env.DEBUG}function c(f){f.inspectOpts={};const p=Object.keys(e.inspectOpts);for(let h=0;h<p.length;h++)f.inspectOpts[p[h]]=e.inspectOpts[p[h]]}t.exports=cn()(e);const{formatters:u}=t.exports;u.o=function(f){return this.inspectOpts.colors=this.useColors,o.inspect(f,this.inspectOpts).split(`
|
|
74
|
+
`).map(p=>p.trim()).join(" ")},u.O=function(f){return this.inspectOpts.colors=this.useColors,o.inspect(f,this.inspectOpts)}}(We,We.exports)),We.exports}typeof process>"u"||process.type==="renderer"||process.browser===!0||process.__nwjs?ur.exports=pc():ur.exports=yc();var hr=ur.exports,gr={};Object.defineProperty(gr,"__esModule",{value:!0});function wc(t){return function(e,r){return new Promise((o,n)=>{t.call(this,e,r,(s,i)=>{s?n(s):o(i)})})}}gr.default=wc;var fn=G&&G.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};const vc=Tr,Cc=fn(hr),bc=fn(gr),Ye=Cc.default("agent-base");function Ec(t){return!!t&&typeof t.addRequest=="function"}function yr(){const{stack:t}=new Error;return typeof t!="string"?!1:t.split(`
|
|
75
|
+
`).some(e=>e.indexOf("(https.js:")!==-1||e.indexOf("node:https:")!==-1)}function vt(t,e){return new vt.Agent(t,e)}(function(t){class e extends vc.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:yr()?443:80}set defaultPort(o){this.explicitDefaultPort=o}get protocol(){return typeof this.explicitProtocol=="string"?this.explicitProtocol:yr()?"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=yr()),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,l=null;const a=s.timeout||this.timeout,d=p=>{o._hadError||(o.emit("error",p),o._hadError=!0)},c=()=>{l=null,i=!0;const p=new Error(`A "socket" was not created for HTTP request before ${a}ms`);p.code="ETIMEOUT",d(p)},u=p=>{i||(l!==null&&(clearTimeout(l),l=null),d(p))},f=p=>{if(i)return;if(l!=null&&(clearTimeout(l),l=null),Ec(p)){Ye("Callback returned another Agent instance %o",p.constructor.name),p.addRequest(o,s);return}if(p){p.once("free",()=>{this.freeSocket(p,s)}),o.onSocket(p);return}const h=new Error(`no Duplex stream was returned to agent-base for \`${o.method} ${o.path}\``);d(h)};if(typeof this.callback!="function"){d(new Error("`callback` is not defined"));return}this.promisifiedCallback||(this.callback.length>=3?(Ye("Converting legacy callback function to promise"),this.promisifiedCallback=bc.default(this.callback)):this.promisifiedCallback=this.callback),typeof a=="number"&&a>0&&(l=setTimeout(c,a)),"port"in s&&typeof s.port!="number"&&(s.port=Number(s.port));try{Ye("Resolving socket for %o request: %o",s.protocol,`${o.method} ${o.path}`),Promise.resolve(this.promisifiedCallback(o,s)).then(f,u)}catch(p){Promise.reject(p).catch(u)}}freeSocket(o,n){Ye("Freeing socket %o %o",o.constructor.name,n),o.destroy()}destroy(){Ye("Destroying agent %o",this.constructor.name)}}t.Agent=e,t.prototype=t.Agent.prototype})(vt||(vt={}));var Pc=vt,wr={},$c=G&&G.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(wr,"__esModule",{value:!0});const Ac=$c(hr),Je=Ac.default("https-proxy-agent:parse-proxy-response");function kc(t){return new Promise((e,r)=>{let o=0;const n=[];function s(){const u=t.read();u?c(u):t.once("readable",s)}function i(){t.removeListener("end",a),t.removeListener("error",d),t.removeListener("close",l),t.removeListener("readable",s)}function l(u){Je("onclose had error %o",u)}function a(){Je("onend")}function d(u){i(),Je("onerror %o",u),r(u)}function c(u){n.push(u),o+=u.length;const f=Buffer.concat(n,o);if(f.indexOf(`\r
|
|
76
76
|
\r
|
|
77
|
-
`)===-1){
|
|
78
|
-
`)),y=+h.split(" ")[1];
|
|
79
|
-
`;o.auth&&(i["Proxy-Authorization"]=`Basic ${Buffer.from(o.auth).toString("base64")}`);let{host:d,port:c,secureEndpoint:u}=
|
|
77
|
+
`)===-1){Je("have not received end of HTTP headers yet..."),s();return}const h=f.toString("ascii",0,f.indexOf(`\r
|
|
78
|
+
`)),y=+h.split(" ")[1];Je("got proxy server response: %o",h),e({statusCode:y,buffered:f})}t.on("error",d),t.on("close",l),t.on("end",a),s()})}wr.default=kc;var Sc=G&&G.__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 l(c){try{d(o.next(c))}catch(u){i(u)}}function a(c){try{d(o.throw(c))}catch(u){i(u)}}function d(c){c.done?s(c.value):n(c.value).then(l,a)}d((o=o.apply(t,e||[])).next())})},Me=G&&G.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(lr,"__esModule",{value:!0});const pn=Me(qn),hn=Me(Xn),xc=Me(Qn),Ic=Me(Lr),Mc=Me(hr),Rc=Pc,Dc=Me(wr),Ve=Mc.default("https-proxy-agent:agent");class Oc extends Rc.Agent{constructor(e){let r;if(typeof e=="string"?r=xc.default.parse(e):r=e,!r)throw new Error("an HTTP(S) proxy server `host` and `port` must be specified!");Ve("creating new HttpsProxyAgent instance: %o",r),super(r);const o=Object.assign({},r);this.secureProxy=r.secureProxy||_c(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 Sc(this,void 0,void 0,function*(){const{proxy:o,secureProxy:n}=this;let s;n?(Ve("Creating `tls.Socket`: %o",o),s=hn.default.connect(o)):(Ve("Creating `net.Socket`: %o",o),s=pn.default.connect(o));const i=Object.assign({},o.headers);let a=`CONNECT ${`${r.host}:${r.port}`} HTTP/1.1\r
|
|
79
|
+
`;o.auth&&(i["Proxy-Authorization"]=`Basic ${Buffer.from(o.auth).toString("base64")}`);let{host:d,port:c,secureEndpoint:u}=r;Fc(c,u)||(d+=`:${c}`),i.Host=d,i.Connection="close";for(const g of Object.keys(i))a+=`${g}: ${i[g]}\r
|
|
80
80
|
`;const f=Dc.default(s);s.write(`${a}\r
|
|
81
|
-
`);const{statusCode:p,buffered:h}=yield f;if(p===200){if(e.once("socket",Nc),
|
|
81
|
+
`);const{statusCode:p,buffered:h}=yield f;if(p===200){if(e.once("socket",Nc),r.secureEndpoint){Ve("Upgrading socket connection to TLS");const g=r.servername||r.host;return hn.default.connect(Object.assign(Object.assign({},Lc(r,"host","hostname","path","port")),{socket:s,servername:g}))}return s}s.destroy();const y=new pn.default.Socket({writable:!1});return y.readable=!0,e.once("socket",g=>{Ve("replaying proxy buffer for failed request"),Ic.default(g.listenerCount("data")>0),g.push(h),g.push(null)}),y})}}lr.default=Oc;function Nc(t){t.resume()}function Fc(t,e){return!!(!e&&t===80||e&&t===443)}function _c(t){return typeof t=="string"?/^https:?$/i.test(t):!1}function Lc(t,...e){const r={};let o;for(o in t)e.includes(o)||(r[o]=t[o]);return r}var Tc=G&&G.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};const vr=Tc(lr);function Cr(t){return new vr.default(t)}(function(t){t.HttpsProxyAgent=vr.default,t.prototype=vr.default.prototype})(Cr||(Cr={}));var jc=Cr,Bc=ve(jc);const Gc=async(t,e,r,o,n,s,i)=>new Promise((l,a)=>{const d=JSON.stringify(o),u=(t.protocol.includes("https")?Wr:Vn).request({port:i||void 0,hostname:t.hostname,path:e,method:"POST",headers:{"Content-Type":"application/json","Content-Length":Buffer.byteLength(d),...r},timeout:n,agent:s?Bc(s):void 0},f=>{const p=[];f.on("data",h=>p.push(h)),f.on("end",()=>{l({request:u,response:f,data:Buffer.concat(p).toString()})})});u.on("error",a),u.on("timeout",()=>{u.destroy(),a(new w(`Time out error: request took over ${n}ms. Try increasing the \`timeout\` config`))}),u.write(d),u.end()}),Hc=async(t,e,r,o,n,s)=>{const i=new URL(t),{response:l,data:a}=await Gc(i,e,{Authorization:`Bearer ${r}`},o,n,s);if(!l.statusCode||l.statusCode<200||l.statusCode>299){let d=`API Error: ${l.statusCode} - ${l.statusMessage}`;throw a&&(d+=`
|
|
82
82
|
|
|
83
83
|
${a}`),l.statusCode===500&&(d+=`
|
|
84
84
|
|
|
85
|
-
Check the API status: ${
|
|
85
|
+
Check the API status: ${t}`),new w(d)}return JSON.parse(a)},gn=t=>t.trim(),Uc=["gpt-5","gpt-5-mini","gpt-5-nano","gpt-5-codex","o1","o1-mini","o1-pro","o3","o3-mini","o3-pro","o4-mini"],br=t=>{const e=t.toLowerCase();return Uc.some(r=>e===r||e.startsWith(`${r}-`)||e.startsWith(`${r}.`))},zc=async(t,e,r,o,n,s,i,l,a,d,c,u,f,p)=>{try{const h=ye(s,f),y=br(n),g={model:n,messages:[{role:"system",content:c},{role:"user",content:h}],stream:!1,n:1,frequency_penalty:0,presence_penalty:0,...y?{max_completion_tokens:l,temperature:1}:{max_tokens:l,top_p:d,temperature:a}},v=new URL(e),b=`${v.protocol}//${v.host}${r}`,E={Authorization:`Bearer ${o}`,"Content-Type":"application/json"};Q(s,f,t,n,b,E,u),Z(s,f,t,c,h,u),oe(s,f,t,g,u);const k=Date.now(),$=await Hc(e,r,o,g,i,p),P=Date.now()-k;W(s,f,t,$,u);const R=$.choices.filter(A=>A.message?.content).map(A=>gn(A.message.content)).join();return Y(s,f,t,P,R,u),$.choices.filter(A=>A.message?.content).map(A=>gn(A.message.content))}catch(h){j(s,f,t,h,u);const y=h;throw y.code==="ENOTFOUND"?new w(`Error connecting to ${y.hostname} (${y.syscall})`):y}};class Kc extends ee{constructor(e){super(e),this.params=e,this.baseURL="https://models.github.ai",this.colors={primary:"#24292e",secondary:"#FFF"},this.serviceName=C.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[GitHub Models]"),this.errorPrefix=C.red.bold("[GitHub Models]")}getServiceSpecificErrorMessage(e){switch(e.code){case"MISSING_TOKEN":return"GitHub token is required. Run: aicommit2 github-login";case"AUTHENTICATION_FAILED":return"Authentication failed. Your GitHub token may be expired or invalid. Run: aicommit2 github-login";case"ACCESS_DENIED":return'Access denied. Make sure your GitHub token has "Models" permission in GitHub settings';case"NO_CONTENT":return"No content received from GitHub Models. The model may have failed to generate a response";default:return null}}generateCommitMessage$(){return L(this.generateMessage("commit")).pipe(_(e=>D(e)),O(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})),N(this.handleError$))}generateCodeReview$(){return L(this.generateMessage("review")).pipe(_(e=>D(e)),O(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),N(this.handleError$))}async generateMessage(e){if(!this.params.config.key){const p=new Error("GitHub token is required for GitHub Models. Use: aicommit2 github-login");throw p.code="MISSING_TOKEN",p}const r=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:n,codeReviewPromptPath:s,locale:i,generate:l,type:a,maxLength:d}=this.params.config,c={...J,locale:i,maxLength:d,type:a,generate:l,systemPrompt:o,systemPromptPath:n,codeReviewPromptPath:s,vcs_branch:this.params.branchName||""},u=e==="review"?re(c):te(c),f=await this.makeRequest(u,r,e);return e==="review"?this.sanitizeResponse(f):this.parseMessage(f,a,l)}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:
|
|
86
86
|
|
|
87
|
-
${
|
|
87
|
+
${r}`}],i=br(n),l={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`,d={"Content-Type":"application/json",Accept:"application/vnd.github+json",Authorization:`Bearer ${this.params.config.key}`},{logging:c}=this.params.config;Q(r,o,"GitHub Models",n,a,d,c),Z(r,o,"GitHub Models",e,o==="review"?r:`Here's the diff:
|
|
88
88
|
|
|
89
|
-
${t}`,c),oe(t,o,"GitHub Models",l,c);const u=new AbortController,f=setTimeout(()=>u.abort(),this.params.config.timeout);try{const p=Date.now(),h=await fetch(a,{method:"POST",headers:d,body:JSON.stringify(l),signal:u.signal});if(clearTimeout(f),!h.ok){const b=await h.text(),E={status:h.status,statusText:h.statusText,url:a,headers:Object.fromEntries(h.headers),body:b};B(t,o,"GitHub Models",E,c);let k=`GitHub API request failed: ${h.status} ${h.statusText}`;try{const P=JSON.parse(b);P.error?.message?k+=` - ${P.error.message}`:P.message&&(k+=` - ${P.message}`)}catch{b&&(k+=` - ${b}`)}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=b,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=b,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=b,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=b,P}const $=new Error(k);throw $.status=h.status,$.code="API_ERROR",$.content=b,$}const y=await h.json(),g=Date.now()-p;W(t,o,"GitHub Models",y,c);const v=y.choices?.[0]?.message?.content?.trim();if(!v){B(t,o,"GitHub Models",{message:"No content found in GitHub Models response",result:y},c);const E=new Error("No response content received from GitHub Models");throw E.code="NO_CONTENT",E.content=JSON.stringify(y,null,2),E}return Y(t,o,"GitHub Models",g,v,c),v}catch(p){if(clearTimeout(f),p instanceof Error&&p.name==="AbortError"){const g={message:`GitHub Models request timeout after ${this.params.config.timeout}ms`,error:p};B(t,o,"GitHub Models",g,c);const v=new Error(`GitHub Models request timed out after ${this.params.config.timeout}ms`);throw v.code="REQUEST_TIMEOUT",v.originalError=p,v}if(p.code)throw p;B(t,o,"GitHub Models",{message:"GitHub Models request failed",error:p},c);const y=new Error(`GitHub Models request failed: ${p instanceof Error?p.message:String(p)}`);throw y.code="REQUEST_FAILED",y.originalError=p,y}}}class Wc extends ee{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 ts({apiKey:this.params.config.key})}getServiceSpecificErrorMessage(e){const t=e.message||"";return t.includes("API key")||t.includes("api_key")?"Invalid API key. Check your Groq API key in configuration":t.includes("rate_limit")||t.includes("Rate limit")?"Rate limit exceeded. Wait a moment and try again, or upgrade your Groq plan":t.includes("model")||t.includes("Model")?"Model not found or not accessible. Check if the Groq model name is correct":t.includes("overloaded")||t.includes("capacity")?"Groq service is overloaded. Try again in a few minutes":t.includes("403")||t.includes("Forbidden")?"Access denied. Your API key may not have permission for this Groq model":t.includes("404")||t.includes("Not Found")?"Model or endpoint not found. Check your Groq model configuration":t.includes("500")||t.includes("Internal Server Error")?"Groq server error. Try again later":null}generateCommitMessage$(){return T(this.generateMessage("commit")).pipe(_(e=>O(e)),N(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})),F(this.handleError$))}generateCodeReview$(){return T(this.generateMessage("review")).pipe(_(e=>O(e)),N(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),F(this.handleError$))}async generateMessage(e){const t=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:n,codeReviewPromptPath:s,logging:i,locale:l,temperature:a,generate:d,type:c,maxLength:u}=this.params.config,f=this.params.config.maxTokens,p={...J,locale:l,maxLength:u,type:c,generate:d,systemPrompt:o,systemPromptPath:n,codeReviewPromptPath:s,vcs_branch:this.params.branchName||""},h=e==="review"?re(p):te(p),y=`Here is the diff: ${t}`,v=`${this.params.config.url||"https://api.groq.com"}/openai/v1/chat/completions`,b={Authorization:`Bearer ${this.params.config.key}`,"Content-Type":"application/json"};Q(t,e,"Groq",this.params.config.model,v,b,i),Z(t,e,"Groq",h,y,i);const E={messages:[{role:"system",content:h},{role:"user",content:y}],model:this.params.config.model,max_tokens:f,top_p:this.params.config.topP,temperature:a};oe(t,e,"Groq",E,i);const k=Date.now();try{const $=await this.groq.chat.completions.create(E,{timeout:this.params.config.timeout}),P=Date.now()-k,R=$.choices[0].message.content||"";return W(t,e,"Groq",$,i),Y(t,e,"Groq",P,R,i),e==="review"?this.sanitizeResponse(R):this.parseMessage(R,c,d)}catch($){throw B(t,e,"Groq",$,i),$}}}class Yc extends ee{constructor(e){super(e),this.params=e,this.headers={},this.models=[],this.currentModelId=null,this.currentConversation=void 0,this.currentConversionID=void 0,this.cookie="",this.colors={primary:"#FED21F",secondary:"#000"},this.serviceName=C.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[HuggingFace]"),this.errorPrefix=C.red.bold("[HuggingFace]"),this.cookie=this.params.config.cookie;const t=this.params.config.url||"https://huggingface.co";this.headers={accept:"*/*","accept-language":"en-US,en;q=0.9","sec-ch-ua":'"Chromium";v="116", "Not)A;Brand";v="24", "Google Chrome";v="116"',"sec-ch-ua-mobile":"?0","sec-ch-ua-platform":'"Windows"',"sec-fetch-dest":"empty","sec-fetch-mode":"cors","sec-fetch-site":"same-origin",origin:t,"Referrer-Policy":"strict-origin-when-cross-origin"}}getServiceSpecificErrorMessage(e){const t=e.message||"";return t.includes("cookie")||t.includes("Cookie")?"Invalid cookie. Check your Hugging Face session cookie in configuration":t.includes("model")||t.includes("Model")?"Model not found or not accessible. Check if the Hugging Face model name is correct":t.includes("conversation")||t.includes("conversion")?"Failed to create conversation. Try again or check your session":t.includes("401")||t.includes("Unauthorized")?"Authentication failed. Your Hugging Face session may have expired":t.includes("403")||t.includes("Forbidden")?"Access denied. You may not have permission to access this model":t.includes("404")||t.includes("Not Found")?"Model not found. Check your Hugging Face model configuration":t.includes("500")||t.includes("Internal Server Error")?"Hugging Face server error. Try again later":t.includes("overloaded")||t.includes("capacity")?"Hugging Face service is overloaded. Try again in a few minutes":null}generateCommitMessage$(){return T(this.generateMessage("commit")).pipe(_(e=>O(e)),N(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})),F(this.handleError$))}generateCodeReview$(){return T(this.generateMessage("review")).pipe(_(e=>O(e)),N(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),F(this.handleError$))}async generateMessage(e){await this.initialize();const t=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:n,codeReviewPromptPath:s,logging:i,locale:l,generate:a,type:d,maxLength:c,temperature:u,maxTokens:f,topP:p,timeout:h}=this.params.config,y={...J,locale:l,maxLength:c,type:d,generate:a,systemPrompt:o,systemPromptPath:n,codeReviewPromptPath:s,vcs_branch:this.params.branchName||""},g=e==="review"?re(y):te(y),v=`Here is the diff: ${t}`,E=`${this.params.config.url||"https://huggingface.co"}/chat/conversation`,k={...this.headers,cookie:this.cookie};Q(t,e,"HuggingFace",this.params.config.model,E,k,i),Z(t,e,"HuggingFace",g,v,i);const $=Date.now();try{const P=await this.getNewChat(g),A=await(await this.sendMessage(v,P.id)).completeResponsePromise();await this.deleteConversation(P.id);const D=Date.now()-$;return W(t,e,"HuggingFace",{response:A},i),Y(t,e,"HuggingFace",D,A,i),e==="review"?this.sanitizeResponse(A):this.parseMessage(A,d,a)}catch(P){throw B(t,e,"HuggingFace",P,i),P}}async initialize(){const e=await this.getRemoteLlms(),t=e.find(o=>o.name?.toLowerCase()===this.params.config.model.toLowerCase());if(t){this.currentModel=t,this.currentModelId=t.id;return}this.currentModel=e[0],this.currentModelId=e[0].id}async getRemoteLlms(){const e=this.params.config.url||"https://huggingface.co",t=await fetch(`${e}/chat/__data.json`,{headers:{...this.headers,cookie:this.cookie},body:null,method:"GET"});if(t.status!==200)throw new Error(`Failed to get remote LLMs with status code: ${t.status}`);const n=(await t.json()).nodes[0].data,s=n[n[0].models],i=[],l=a=>a===-1?null:n[a];for(const a of s){const d=n[a];if(n[d.unlisted])continue;const c={id:l(d.id),name:l(d.name),displayName:l(d.displayName),preprompt:l(d.preprompt),promptExamples:[],websiteUrl:l(d.websiteUrl),description:l(d.description),datasetName:l(d.datasetName),datasetUrl:l(d.datasetUrl),modelUrl:l(d.modelUrl),parameters:{}},u=l(d.promptExamples);if(u!==null){const h=u.map(y=>l(y));c.promptExamples=h.map(y=>({title:n[y.title],prompt:n[y.prompt]}))}const f=l(d.parameters),p={};for(const[h,y]of Object.entries(f)){if(y===-1){p[h]=null;continue}if(Array.isArray(n[y])){p[h]=n[y].map(g=>n[g]);continue}p[h]=n[y]}c.parameters=p,i.push(c)}return this.models=i,i}async getNewChat(e){const t={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(t),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 t=this.params.config.url||"https://huggingface.co",o=await fetch(`${t}/chat/conversation/${e}/__data.json`,{headers:{...this.headers,cookie:this.cookie,Referer:`${t}/chat/`},body:null,method:"GET"});if(o.status!=200)throw new Error("Unable get conversation details "+o);{const n=await o.json();return this.metadataParser(n,e)}}metadataParser(e,t){const o={id:"",model:"",systemPrompt:"",title:"",history:[]},n=e.nodes[1].data,s=n[n[0].model],i=n[n[0].preprompt],l=n[n[0].title],a=n[n[0].messages],d=[];for(const c of a){const u=n[c],f=new Date(n[u.createdAt][1]).getTime()/1e3,p=new Date(n[u.updatedAt][1]).getTime()/1e3;d.push({id:n[u.id],role:n[u.from],content:n[u.content],createdAt:f,updatedAt:p})}return o.id=t,o.model=s,o.systemPrompt=i,o.title=l,o.history=d,this.currentConversation=o,o}async sendMessage(e,t){if(e==="")throw new Error("the prompt can not be empty.");if(!t&&!this.currentConversionID?await this.getNewChat():t?(this.currentConversionID=t,await this.getConversationHistory(t)):this.currentConversionID&&await this.getConversationHistory(this.currentConversionID),!this.currentConversation)throw new Error("Failed to create new conversion");const o={inputs:e,id:this.currentConversation.history[this.currentConversation.history.length-1].id,is_retry:!1,is_continue:!1,web_search:!1,tools:[]},n=new FormData;n.append("data",JSON.stringify(o));const s=this.params.config.url||"https://huggingface.co",i=new AbortController,l=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(l);function d(y){try{const g=y.split(`
|
|
90
|
-
`),v=[];for(const b of g)b.trim()&&v.push(JSON.parse(b));return v}catch{return[{}]}}const c=new TextDecoder;let u="";const f=new TransformStream({async transform(y,g){const v=c.decode(y);try{const b=d(v);for(const E of b)E.type==="finalAnswer"?(u=E?.text||"",g.terminate()):E.type==="stream"&&g.enqueue(E?.token||"")}catch{throw new Error("Error during parsing response")}}}),p=a.body?.pipeThrough(f);async function h(){return new Promise(async(y,g)=>{try{if(!p)g("ModifiedStream undefined");else{const v=p.getReader();for(;;){const{done:b,value:E}=await v.read();if(b){y(u);break}}}}catch(v){g(v)}})}return{id:this.currentConversionID,stream:p,completeResponsePromise:h}}async deleteConversation(e){const t=this.params.config.url||"https://huggingface.co";return(await fetch(`${t}/chat/conversation/${e}`,{headers:{...this.headers,cookie:this.cookie,Referer:`${t}/chat/`},body:null,method:"DELETE"})).json()}}class Jc extends ee{constructor(e){super(e),this.params=e,this.apiKey="",this.colors={primary:"#ff7000",secondary:"#fff"},this.serviceName=C.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[MistralAI]"),this.errorPrefix=C.red.bold("[MistralAI]"),this.apiKey=this.params.config.key}getServiceSpecificErrorMessage(e){const t=e.message||"";return t.includes("API key")||t.includes("api_key")?"Invalid API key. Check your Mistral AI API key in configuration":t.includes("quota")||t.includes("usage")?"API quota exceeded. Check your Mistral AI usage limits":t.includes("model")||t.includes("Model")?"Model not found or not accessible. Check if the Mistral model name is correct":t.includes("403")||t.includes("Forbidden")?"Access denied. Your API key may not have permission for this Mistral model":t.includes("404")||t.includes("Not Found")?"Model or endpoint not found. Check your Mistral model configuration":t.includes("500")||t.includes("Internal Server Error")?"Mistral AI server error. Try again later":null}generateCommitMessage$(){return T(this.generateMessage("commit")).pipe(_(e=>O(e)),N(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})),F(this.handleError$))}generateCodeReview$(){return T(this.generateMessage("review")).pipe(_(e=>O(e)),N(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),F(this.handleError$))}async generateMessage(e){const t=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:n,codeReviewPromptPath:s,logging:i,locale:l,generate:a,type:d,maxLength:c}=this.params.config,u={...J,locale:l,maxLength:c,type:d,generate:a,systemPrompt:o,systemPromptPath:n,codeReviewPromptPath:s,vcs_branch:this.params.branchName||""},f=e==="review"?re(u):te(u);await this.checkAvailableModels();const p=`Here is the diff: ${t}`,y=`${this.params.config.url||"https://api.mistral.ai"}/v1/chat/completions`,g={Authorization:`Bearer ${this.apiKey}`,"content-type":"application/json"};Q(t,e,"MistralAI",this.params.config.model,y,g,i),Z(t,e,"MistralAI",f,p,i);const v=await this.createChatCompletions(f,p,e);return e==="review"?this.sanitizeResponse(v):this.parseMessage(v,d,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 Ue({method:"GET",baseURL:`${e}/v1/models`,timeout:this.params.config.timeout}).setHeaders({Authorization:`Bearer ${this.apiKey}`,"content-type":"application/json"}).execute()).data.data.filter(o=>o.object==="model").map(o=>o.id)}async createChatCompletions(e,t,o){const n=this.params.stagedDiff.diff,{logging:s}=this.params.config,i={model:this.params.config.model,messages:[{role:"system",content:e},{role:"user",content:t}],temperature:this.params.config.temperature,top_p:this.params.config.topP,max_tokens:this.params.config.maxTokens,stream:!1,safe_prompt:!1,random_seed:dt(10,1e3)};oe(n,o,"MistralAI",i,s);const l=Date.now();try{const a=this.params.config.url||"https://api.mistral.ai",d=await new Ue({method:"POST",baseURL:`${a}/v1/chat/completions`,timeout:this.params.config.timeout}).setHeaders({Authorization:`Bearer ${this.apiKey}`,"content-type":"application/json"}).setBody(i).execute(),c=Date.now()-l,u=d.data;if(W(n,o,"MistralAI",u,s),!u.choices||u.choices.length===0||!u.choices[0].message?.content)throw B(n,o,"MistralAI",{message:"No Content on response",result:u},s),new Error("No Content on response. Please open a Bug report");const p=u.choices[0].message.content;return Y(n,o,"MistralAI",c,p,s),p}catch(a){throw B(n,o,"MistralAI",a,s),a}}}class Vc extends ee{constructor(e){super(e),this.params=e,this.host=rr,this.model="",this.key="",this.auth="",this.setupFetch=(t,o={})=>os(t,{...o,dispatcher:new ns({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(`[${ut(this.model)}]`),this.errorPrefix=C.red.bold(`[${ut(this.model)}]`),this.host=this.params.config.host||rr,this.auth=this.params.config.auth||"Bearer",this.key=this.params.config.key||"",this.ollama=new rs({host:this.host,fetch:this.setupFetch,...this.key&&{headers:{Authorization:`${this.auth} ${this.key}`}}})}getServiceSpecificErrorMessage(e){const t=e.message||"";return t.includes("ECONNREFUSED")||t.includes("connection")?`Cannot connect to Ollama server at ${this.host}. Make sure Ollama is running`:t.includes("model")||t.includes("Model")?`Model '${this.model}' not found. Pull the model with: ollama pull ${this.model}`:t.includes("401")||t.includes("Unauthorized")?"Authentication failed. Check your Ollama API key if authentication is enabled":t.includes("403")||t.includes("Forbidden")?"Access denied. Check your Ollama server permissions":t.includes("404")||t.includes("Not Found")?`Model '${this.model}' not found on Ollama server. Pull it first with: ollama pull ${this.model}`:t.includes("500")||t.includes("Internal Server Error")?"Ollama server error. Check server logs and try again":t.includes("overloaded")||t.includes("capacity")?"Ollama server is overloaded. Try again in a few minutes":null}generateCommitMessage$(){return T(this.generateMessage("commit")).pipe(_(e=>O(e)),N(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})),F(this.handleError$))}generateCodeReview$(){return T(this.generateMessage("review")).pipe(_(e=>O(e)),N(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),F(this.handleError$))}async generateMessage(e){const t=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:n,codeReviewPromptPath:s,logging:i,locale:l,generate:a,type:d,maxLength:c}=this.params.config,u={...J,locale:l,maxLength:c,type:d,generate:a,systemPrompt:o,systemPromptPath:n,codeReviewPromptPath:s,vcs_branch:this.params.branchName||""},f=e==="review"?re(u):te(u);await this.checkIsAvailableOllama();const p=`Here is the diff: ${t}`,h=`Ollama_${this.model}`,y=`${this.host}/api/chat`,g=this.key?{Authorization:`${this.auth} ${this.key}`}:{};Q(t,e,h,this.model,y,g,i),Z(t,e,h,f,p,i);const v=await this.createChatCompletions(f,p,e);return e==="review"?this.sanitizeResponse(v):this.parseMessage(v,d,a)}async checkIsAvailableOllama(){const e=new Ue({method:"GET",baseURL:`${this.host}`,timeout:this.params.config.timeout});return this.key&&e.setHeaders({Authorization:`${this.auth} ${this.key}`}),(await e.execute()).data}async createChatCompletions(e,t,o){const{stream:n,numCtx:s,temperature:i,topP:l,timeout:a,maxTokens:d,logging:c}=this.params.config,u=n||!1,f=this.params.stagedDiff.diff,p=`Ollama_${this.model}`,h={model:this.model,messages:[{role:"system",content:e},{role:"user",content:t}],stream:u,keep_alive:a,options:{num_ctx:s,temperature:i,top_p:l,seed:dt(10,1e3),num_predict:d??-1}};oe(f,o,p,h,c);const y=Date.now();try{const g=await this.ollama.chat(h),v=Date.now()-y;let b="";if(u){if(g)for await(const E of g)b+=E.message.content}else b=g.message.content;return W(f,o,p,{response:b,fullResponse:g},c),Y(f,o,p,v,b,c),b}catch(g){throw B(f,o,p,g,c),g}}}class qc extends ee{constructor(e){super(e),this.params=e;const t=this.params.keyName||"OPENAI_COMPATIBLE";this.colors=Ta(t),this.serviceName=C.bgHex(this.colors.primary).hex(this.colors.secondary).bold(`[${ut(t)}]`),this.errorPrefix=C.red.bold(`[${ut(t)}]`),this.openAI=new Kr({apiKey:this.params.config.key,baseURL:`${this.params.config.url}${this.params.config.path}`})}getServiceSpecificErrorMessage(e){const t=e.message||"";return t.includes("API key")||t.includes("api_key")?"Invalid API key. Check your OpenAI-compatible API key in configuration":t.includes("rate_limit")||t.includes("Rate limit")?"Rate limit exceeded. Wait a moment and try again, or check your service limits":t.includes("model")||t.includes("Model")?"Model not found or not accessible. Check if the model name is correct":t.includes("network")||t.includes("connection")?"Network error. Check your internet connection and API endpoint":t.includes("quota")||t.includes("usage")?"API quota exceeded. Check your usage limits":t.includes("403")||t.includes("Forbidden")?"Access denied. Your API key may not have permission for this model":t.includes("404")||t.includes("Not Found")?"Model or endpoint not found. Check your API configuration":t.includes("500")||t.includes("Internal Server Error")?"Server error. Try again later":t.includes("overloaded")||t.includes("capacity")?"Service is overloaded. Try again in a few minutes":null}generateCommitMessage$(){return T(this.generateMessage("commit")).pipe(_(e=>O(e)),N(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})),F(this.handleError$))}generateCodeReview$(){return T(this.generateMessage("review")).pipe(_(e=>O(e)),N(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),F(this.handleError$))}async generateMessage(e){const t=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:n,codeReviewPromptPath:s,logging:i,locale:l,temperature:a,generate:d,type:c,maxLength:u,timeout:f,stream:p=!1}=this.params.config,h=this.params.config.maxTokens,y={...J,locale:l,maxLength:u,type:c,generate:d,systemPrompt:o,systemPromptPath:n,codeReviewPromptPath:s,vcs_branch:this.params.branchName||""},g=e==="review"?re(y):te(y),v=`Here is the diff: ${t}`,b=this.params.keyName||"OpenAI-Compatible",E=`${this.params.config.url}${this.params.config.path}`,k={Authorization:`Bearer ${this.params.config.key}`,"Content-Type":"application/json"};Q(t,e,b,this.params.config.model,E,k,i),Z(t,e,b,g,v,i);const $=vr(this.params.config.model),P={messages:[{role:"system",content:g},{role:"user",content:v}],model:this.params.config.model,stream:p,...$?{max_completion_tokens:h,temperature:1}:{max_tokens:h,top_p:this.params.config.topP,temperature:a}};oe(t,e,b,P,i);const R=Date.now();try{const A=await this.openAI.chat.completions.create(P,{timeout:f});let D="";if(p&&A){const K=A;for await(const Re of K){const Sn=Re.choices?.[0]?.delta?.content||"",xn=Re.choices?.[0]?.delta?.reasoning_content||"",In=`${Sn}${xn}`;D+=In}}else D=A.choices?.[0]?.message.content||"";const S=Date.now()-R;return W(t,e,b,A,i),Y(t,e,b,S,D,i),e==="review"?this.sanitizeResponse(D):this.parseMessage(D,c,d)}catch(A){throw B(t,e,b,A,i),A}}}class Xc extends ee{constructor(e){super(e),this.params=e,this.colors={primary:"#74AA9C",secondary:"#FFF"},this.serviceName=C.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[ChatGPT]"),this.errorPrefix=C.red.bold("[ChatGPT]")}getServiceSpecificErrorMessage(e){const t=e.message||"";return t.includes("API key")?"Invalid API key. Check your OpenAI API key in configuration":t.includes("quota")?"API quota exceeded. Check your OpenAI usage limits":t.includes("500")?"OpenAI server error. Try again later":null}generateCommitMessage$(){return T(this.generateMessage("commit")).pipe(_(e=>O(e)),N(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})),F(this.handleError$))}generateCodeReview$(){return T(this.generateMessage("review")).pipe(_(e=>O(e)),N(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),F(this.handleError$))}extractJSONFromError(e){const t=/[{[]{1}([,:{}[\]0-9.\-+Eaeflnr-u \n\r\t]|".*?")+[}\]]{1}/gis,o=e.match(t);return o?Object.assign({},...o.map(n=>JSON.parse(n))):{error:{message:"Unknown error"}}}async generateMessage(e){const t=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:n,codeReviewPromptPath:s,temperature:i,logging:l,locale:a,generate:d,type:c,maxLength:u,proxy:f,maxTokens:p,timeout:h}=this.params.config,y={...J,locale:a,maxLength:u,type:c,generate:d,systemPrompt:o,systemPromptPath:n,codeReviewPromptPath:s,vcs_branch:this.params.branchName||""},g=e==="review"?re(y):te(y),v=await zc("ChatGPT",this.params.config.url,this.params.config.path,this.params.config.key,this.params.config.model,t,h,p,i,this.params.config.topP,g,l,e,f);return mt(e==="review"?v.map(b=>this.sanitizeResponse(b)):v.map(b=>this.parseMessage(b,c,d)))}}class Qc extends ee{constructor(e){super(e),this.params=e,this.apiKey="",this.colors={primary:"#20808D",secondary:"#FFF"},this.serviceName=C.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[Perplexity]"),this.errorPrefix=C.red.bold("[Perplexity]"),this.apiKey=this.params.config.key}getServiceSpecificErrorMessage(e){const t=e.message||"";return t.includes("API key")||t.includes("api_key")?"Invalid API key. Check your Perplexity API key in configuration":t.includes("rate_limit")||t.includes("Rate limit")?"Rate limit exceeded. Wait a moment and try again, or upgrade your Perplexity plan":t.includes("model")||t.includes("Model")?"Model not found or not accessible. Check if the Perplexity model name is correct":t.includes("overloaded")||t.includes("capacity")?"Perplexity service is overloaded. Try again in a few minutes":t.includes("403")||t.includes("Forbidden")?"Access denied. Your API key may not have permission for this Perplexity model":t.includes("404")||t.includes("Not Found")?"Model or endpoint not found. Check your Perplexity model configuration":t.includes("500")||t.includes("Internal Server Error")?"Perplexity server error. Try again later":null}generateCommitMessage$(){return T(this.generateMessage("commit")).pipe(_(e=>O(e)),N(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})),F(this.handleError$))}generateCodeReview$(){return T(this.generateMessage("review")).pipe(_(e=>O(e)),N(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),F(this.handleError$))}extractJSONFromError(e){const t=/[{[]{1}([,:{}[\]0-9.\-+Eaeflnr-u \n\r\t]|".*?")+[}\]]{1}/gis,o=e.match(t);return o?Object.assign({},...o.map(n=>JSON.parse(n))):{error:{message:"Unknown error"}}}async generateMessage(e){const t=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:n,codeReviewPromptPath:s,logging:i,locale:l,generate:a,type:d,maxLength:c}=this.params.config,u={...J,locale:l,maxLength:c,type:d,generate:a,systemPrompt:o,systemPromptPath:n,codeReviewPromptPath:s,vcs_branch:this.params.branchName||""},f=e==="review"?re(u):te(u),p=`Here is the diff: ${t}`,y=`${this.params.config.url||"https://api.perplexity.ai"}/chat/completions`,g={Authorization:`Bearer ${this.apiKey}`,"content-type":"application/json"};Q(t,e,"Perplexity",this.params.config.model,y,g,i),Z(t,e,"Perplexity",f,p,i);const v=await this.createChatCompletions(f,p,e);return this.parseMessage(v,d,a)}async createChatCompletions(e,t,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:t}],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 l=Date.now();try{const a=this.params.config.url||"https://api.perplexity.ai",d=await new Ue({method:"POST",baseURL:`${a}/chat/completions`,timeout:this.params.config.timeout}).setHeaders({Authorization:`Bearer ${this.apiKey}`,"content-type":"application/json"}).setBody(i).execute(),c=Date.now()-l,u=d.data;if(W(n,o,"Perplexity",u,s),!u.choices||u.choices.length===0||!u.choices[0].message?.content)throw B(n,o,"Perplexity",{message:"No Content on response",result:u},s),new Error("No Content on response. Please open a Bug report");const p=u.choices[0].message.content;return Y(n,o,"Perplexity",c,p,s),p}catch(a){throw B(n,o,"Perplexity",a,s),a}}}class Ct{constructor(e,t,o=""){this.config=e,this.stagedDiff=t,this.branchName=o}createCommitMsgRequests$(e){return this.createServiceRequests$(e,"commit")}createCodeReviewRequests$(e){return this.createServiceRequests$(e,"review")}createServiceRequests$(e,t){return O(e).pipe(Tr(o=>{const n=this.config[o],s=Array.isArray(n.model)?n.model:[n.model];return O(s).pipe(Tr(i=>{if(n.compatible){const l=X.create(qc,{config:{...n,url:n.url||"",path:n.path||"",model:i},stagedDiff:this.stagedDiff,keyName:i,branchName:this.branchName});return t==="commit"?l.generateCommitMessage$():l.generateCodeReview$()}switch(o){case"OPENAI":{const a=X.create(Xc,{config:{...this.config.OPENAI,model:i},stagedDiff:this.stagedDiff,keyName:i,branchName:this.branchName});return t==="commit"?a.generateCommitMessage$():a.generateCodeReview$()}case"GEMINI":{const a=X.create(mc,{config:{...this.config.GEMINI,model:i},stagedDiff:this.stagedDiff,keyName:i,branchName:this.branchName});return t==="commit"?a.generateCommitMessage$():a.generateCodeReview$()}case"ANTHROPIC":{const a=X.create(ic,{config:{...this.config.ANTHROPIC,model:i},stagedDiff:this.stagedDiff,keyName:i,branchName:this.branchName});return t==="commit"?a.generateCommitMessage$():a.generateCodeReview$()}case"HUGGINGFACE":{const a=X.create(Yc,{config:{...this.config.HUGGINGFACE,model:i},stagedDiff:this.stagedDiff,keyName:i,branchName:this.branchName});return t==="commit"?a.generateCommitMessage$():a.generateCodeReview$()}case"MISTRAL":{const a=X.create(Jc,{config:{...this.config.MISTRAL,model:i},stagedDiff:this.stagedDiff,keyName:i,branchName:this.branchName});return t==="commit"?a.generateCommitMessage$():a.generateCodeReview$()}case"CODESTRAL":{const a=X.create(lc,{config:{...this.config.CODESTRAL,model:i},stagedDiff:this.stagedDiff,keyName:i,branchName:this.branchName});return t==="commit"?a.generateCommitMessage$():a.generateCodeReview$()}case"OLLAMA":{const a=X.create(Vc,{config:{...this.config.OLLAMA,model:i},keyName:i,stagedDiff:this.stagedDiff,branchName:this.branchName});return t==="commit"?a.generateCommitMessage$():a.generateCodeReview$()}case"COHERE":{const a=X.create(uc,{config:{...this.config.COHERE,model:i},stagedDiff:this.stagedDiff,keyName:i,branchName:this.branchName});return t==="commit"?a.generateCommitMessage$():a.generateCodeReview$()}case"GROQ":{const a=X.create(Wc,{config:{...this.config.GROQ,model:i},stagedDiff:this.stagedDiff,keyName:i,branchName:this.branchName});return t==="commit"?a.generateCommitMessage$():a.generateCodeReview$()}case"PERPLEXITY":{const a=X.create(Qc,{config:{...this.config.PERPLEXITY,model:i},stagedDiff:this.stagedDiff,keyName:i,branchName:this.branchName});return t==="commit"?a.generateCommitMessage$():a.generateCodeReview$()}case"BEDROCK":{const a=X.create(cc,{config:{...this.config.BEDROCK,model:i},stagedDiff:this.stagedDiff,keyName:i});return t==="commit"?a.generateCommitMessage$():a.generateCodeReview$()}case"GITHUB_MODELS":{const a=X.create(Kc,{config:{...this.config.GITHUB_MODELS,model:i},stagedDiff:this.stagedDiff,keyName:i,branchName:this.branchName});return t==="commit"?a.generateCommitMessage$():a.generateCodeReview$()}case"DEEPSEEK":{const a=X.create(dc,{config:{...this.config.DEEPSEEK,model:i},stagedDiff:this.stagedDiff,keyName:i,branchName:this.branchName});return t==="commit"?a.generateCommitMessage$():a.generateCodeReview$()}default:const l=C.red.bold(`[${o}]`);return Mt({name:l+" Invalid AI type",value:"Invalid AI type",isError:!0,disabled:!0})}}))}),F(o=>{const n=C.red.bold("[UNKNOWN]");return Mt({name:n+` ${o.message||""}`,value:"Unknown error",isError:!0,disabled:!0})}))}}class Cr{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 bt extends Cr{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 x("git",["rev-parse","--show-toplevel"],{reject:!0});return e.trim()}catch(e){const t=e;if(t.code==="ENOENT")throw new w(`Git command not found!
|
|
89
|
+
${r}`,c),oe(r,o,"GitHub Models",l,c);const u=new AbortController,f=setTimeout(()=>u.abort(),this.params.config.timeout);try{const p=Date.now(),h=await fetch(a,{method:"POST",headers:d,body:JSON.stringify(l),signal:u.signal});if(clearTimeout(f),!h.ok){const b=await h.text(),E={status:h.status,statusText:h.statusText,url:a,headers:Object.fromEntries(h.headers),body:b};j(r,o,"GitHub Models",E,c);let k=`GitHub API request failed: ${h.status} ${h.statusText}`;try{const P=JSON.parse(b);P.error?.message?k+=` - ${P.error.message}`:P.message&&(k+=` - ${P.message}`)}catch{b&&(k+=` - ${b}`)}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=b,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=b,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=b,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=b,P}const $=new Error(k);throw $.status=h.status,$.code="API_ERROR",$.content=b,$}const y=await h.json(),g=Date.now()-p;W(r,o,"GitHub Models",y,c);const v=y.choices?.[0]?.message?.content?.trim();if(!v){j(r,o,"GitHub Models",{message:"No content found in GitHub Models response",result:y},c);const E=new Error("No response content received from GitHub Models");throw E.code="NO_CONTENT",E.content=JSON.stringify(y,null,2),E}return Y(r,o,"GitHub Models",g,v,c),v}catch(p){if(clearTimeout(f),p instanceof Error&&p.name==="AbortError"){const g={message:`GitHub Models request timeout after ${this.params.config.timeout}ms`,error:p};j(r,o,"GitHub Models",g,c);const v=new Error(`GitHub Models request timed out after ${this.params.config.timeout}ms`);throw v.code="REQUEST_TIMEOUT",v.originalError=p,v}if(p.code)throw p;j(r,o,"GitHub Models",{message:"GitHub Models request failed",error:p},c);const y=new Error(`GitHub Models request failed: ${p instanceof Error?p.message:String(p)}`);throw y.code="REQUEST_FAILED",y.originalError=p,y}}}class Wc extends ee{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 ts({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 L(this.generateMessage("commit")).pipe(_(e=>D(e)),O(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})),N(this.handleError$))}generateCodeReview$(){return L(this.generateMessage("review")).pipe(_(e=>D(e)),O(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),N(this.handleError$))}async generateMessage(e){const r=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:n,codeReviewPromptPath:s,logging:i,locale:l,temperature:a,generate:d,type:c,maxLength:u}=this.params.config,f=this.params.config.maxTokens,p={...J,locale:l,maxLength:u,type:c,generate:d,systemPrompt:o,systemPromptPath:n,codeReviewPromptPath:s,vcs_branch:this.params.branchName||""},h=e==="review"?re(p):te(p),y=`Here is the diff: ${r}`,v=`${this.params.config.url||"https://api.groq.com"}/openai/v1/chat/completions`,b={Authorization:`Bearer ${this.params.config.key}`,"Content-Type":"application/json"};Q(r,e,"Groq",this.params.config.model,v,b,i),Z(r,e,"Groq",h,y,i);const E={messages:[{role:"system",content:h},{role:"user",content:y}],model:this.params.config.model,max_tokens:f,top_p:this.params.config.topP,temperature:a};oe(r,e,"Groq",E,i);const k=Date.now();try{const $=await this.groq.chat.completions.create(E,{timeout:this.params.config.timeout}),P=Date.now()-k,R=$.choices[0].message.content||"";return W(r,e,"Groq",$,i),Y(r,e,"Groq",P,R,i),e==="review"?this.sanitizeResponse(R):this.parseMessage(R,c,d)}catch($){throw j(r,e,"Groq",$,i),$}}}class Yc extends ee{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 L(this.generateMessage("commit")).pipe(_(e=>D(e)),O(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})),N(this.handleError$))}generateCodeReview$(){return L(this.generateMessage("review")).pipe(_(e=>D(e)),O(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),N(this.handleError$))}async generateMessage(e){await this.initialize();const r=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:n,codeReviewPromptPath:s,logging:i,locale:l,generate:a,type:d,maxLength:c,temperature:u,maxTokens:f,topP:p,timeout:h}=this.params.config,y={...J,locale:l,maxLength:c,type:d,generate:a,systemPrompt:o,systemPromptPath:n,codeReviewPromptPath:s,vcs_branch:this.params.branchName||""},g=e==="review"?re(y):te(y),v=`Here is the diff: ${r}`,E=`${this.params.config.url||"https://huggingface.co"}/chat/conversation`,k={...this.headers,cookie:this.cookie};Q(r,e,"HuggingFace",this.params.config.model,E,k,i),Z(r,e,"HuggingFace",g,v,i);const $=Date.now();try{const P=await this.getNewChat(g),A=await(await this.sendMessage(v,P.id)).completeResponsePromise();await this.deleteConversation(P.id);const B=Date.now()-$;return W(r,e,"HuggingFace",{response:A},i),Y(r,e,"HuggingFace",B,A,i),e==="review"?this.sanitizeResponse(A):this.parseMessage(A,d,a)}catch(P){throw j(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=[],l=a=>a===-1?null:n[a];for(const a of s){const d=n[a];if(n[d.unlisted])continue;const c={id:l(d.id),name:l(d.name),displayName:l(d.displayName),preprompt:l(d.preprompt),promptExamples:[],websiteUrl:l(d.websiteUrl),description:l(d.description),datasetName:l(d.datasetName),datasetUrl:l(d.datasetUrl),modelUrl:l(d.modelUrl),parameters:{}},u=l(d.promptExamples);if(u!==null){const h=u.map(y=>l(y));c.promptExamples=h.map(y=>({title:n[y.title],prompt:n[y.prompt]}))}const f=l(d.parameters),p={};for(const[h,y]of Object.entries(f)){if(y===-1){p[h]=null;continue}if(Array.isArray(n[y])){p[h]=n[y].map(g=>n[g]);continue}p[h]=n[y]}c.parameters=p,i.push(c)}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],l=n[n[0].title],a=n[n[0].messages],d=[];for(const c of a){const u=n[c],f=new Date(n[u.createdAt][1]).getTime()/1e3,p=new Date(n[u.updatedAt][1]).getTime()/1e3;d.push({id:n[u.id],role:n[u.from],content:n[u.content],createdAt:f,updatedAt:p})}return o.id=r,o.model=s,o.systemPrompt=i,o.title=l,o.history=d,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,l=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(l);function d(y){try{const g=y.split(`
|
|
90
|
+
`),v=[];for(const b of g)b.trim()&&v.push(JSON.parse(b));return v}catch{return[{}]}}const c=new TextDecoder;let u="";const f=new TransformStream({async transform(y,g){const v=c.decode(y);try{const b=d(v);for(const E of b)E.type==="finalAnswer"?(u=E?.text||"",g.terminate()):E.type==="stream"&&g.enqueue(E?.token||"")}catch{throw new Error("Error during parsing response")}}}),p=a.body?.pipeThrough(f);async function h(){return new Promise(async(y,g)=>{try{if(!p)g("ModifiedStream undefined");else{const v=p.getReader();for(;;){const{done:b,value:E}=await v.read();if(b){y(u);break}}}}catch(v){g(v)}})}return{id:this.currentConversionID,stream:p,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 Jc extends ee{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 L(this.generateMessage("commit")).pipe(_(e=>D(e)),O(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})),N(this.handleError$))}generateCodeReview$(){return L(this.generateMessage("review")).pipe(_(e=>D(e)),O(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),N(this.handleError$))}async generateMessage(e){const r=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:n,codeReviewPromptPath:s,logging:i,locale:l,generate:a,type:d,maxLength:c}=this.params.config,u={...J,locale:l,maxLength:c,type:d,generate:a,systemPrompt:o,systemPromptPath:n,codeReviewPromptPath:s,vcs_branch:this.params.branchName||""},f=e==="review"?re(u):te(u);await this.checkAvailableModels();const p=`Here is the diff: ${r}`,y=`${this.params.config.url||"https://api.mistral.ai"}/v1/chat/completions`,g={Authorization:`Bearer ${this.apiKey}`,"content-type":"application/json"};Q(r,e,"MistralAI",this.params.config.model,y,g,i),Z(r,e,"MistralAI",f,p,i);const v=await this.createChatCompletions(f,p,e);return e==="review"?this.sanitizeResponse(v):this.parseMessage(v,d,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 ze({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:mt(10,1e3)};oe(n,o,"MistralAI",i,s);const l=Date.now();try{const a=this.params.config.url||"https://api.mistral.ai",d=await new ze({method:"POST",baseURL:`${a}/v1/chat/completions`,timeout:this.params.config.timeout}).setHeaders({Authorization:`Bearer ${this.apiKey}`,"content-type":"application/json"}).setBody(i).execute(),c=Date.now()-l,u=d.data;if(W(n,o,"MistralAI",u,s),!u.choices||u.choices.length===0||!u.choices[0].message?.content)throw j(n,o,"MistralAI",{message:"No Content on response",result:u},s),new Error("No Content on response. Please open a Bug report");const p=u.choices[0].message.content;return Y(n,o,"MistralAI",c,p,s),p}catch(a){throw j(n,o,"MistralAI",a,s),a}}}class Vc extends ee{constructor(e){super(e),this.params=e,this.host=rr,this.model="",this.key="",this.auth="",this.setupFetch=(r,o={})=>os(r,{...o,dispatcher:new ns({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(`[${dt(this.model)}]`),this.errorPrefix=C.red.bold(`[${dt(this.model)}]`),this.host=this.params.config.host||rr,this.auth=this.params.config.auth||"Bearer",this.key=this.params.config.key||"",this.ollama=new rs({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 L(this.generateMessage("commit")).pipe(_(e=>D(e)),O(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})),N(this.handleError$))}generateCodeReview$(){return L(this.generateMessage("review")).pipe(_(e=>D(e)),O(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),N(this.handleError$))}async generateMessage(e){const r=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:n,codeReviewPromptPath:s,logging:i,locale:l,generate:a,type:d,maxLength:c}=this.params.config,u={...J,locale:l,maxLength:c,type:d,generate:a,systemPrompt:o,systemPromptPath:n,codeReviewPromptPath:s,vcs_branch:this.params.branchName||""},f=e==="review"?re(u):te(u);await this.checkIsAvailableOllama();const p=`Here is the diff: ${r}`,h=`Ollama_${this.model}`,y=`${this.host}/api/chat`,g=this.key?{Authorization:`${this.auth} ${this.key}`}:{};Q(r,e,h,this.model,y,g,i),Z(r,e,h,f,p,i);const v=await this.createChatCompletions(f,p,e);return e==="review"?this.sanitizeResponse(v):this.parseMessage(v,d,a)}async checkIsAvailableOllama(){const e=new ze({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:l,timeout:a,maxTokens:d,logging:c}=this.params.config,u=n||!1,f=this.params.stagedDiff.diff,p=`Ollama_${this.model}`,h={model:this.model,messages:[{role:"system",content:e},{role:"user",content:r}],stream:u,keep_alive:a,options:{num_ctx:s,temperature:i,top_p:l,seed:mt(10,1e3),num_predict:d??-1}};oe(f,o,p,h,c);const y=Date.now();try{const g=await this.ollama.chat(h),v=Date.now()-y;let b="";if(u){if(g)for await(const E of g)b+=E.message.content}else b=g.message.content;return W(f,o,p,{response:b,fullResponse:g},c),Y(f,o,p,v,b,c),b}catch(g){throw j(f,o,p,g,c),g}}}class qc extends ee{constructor(e){super(e),this.params=e;const r=this.params.keyName||"OPENAI_COMPATIBLE";this.colors=Ta(r),this.serviceName=C.bgHex(this.colors.primary).hex(this.colors.secondary).bold(`[${dt(r)}]`),this.errorPrefix=C.red.bold(`[${dt(r)}]`),this.openAI=new Yr({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 L(this.generateMessage("commit")).pipe(_(e=>D(e)),O(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})),N(this.handleError$))}generateCodeReview$(){return L(this.generateMessage("review")).pipe(_(e=>D(e)),O(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),N(this.handleError$))}async generateMessage(e){const r=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:n,codeReviewPromptPath:s,logging:i,locale:l,temperature:a,generate:d,type:c,maxLength:u,timeout:f,stream:p=!1}=this.params.config,h=this.params.config.maxTokens,y={...J,locale:l,maxLength:u,type:c,generate:d,systemPrompt:o,systemPromptPath:n,codeReviewPromptPath:s,vcs_branch:this.params.branchName||""},g=e==="review"?re(y):te(y),v=`Here is the diff: ${r}`,b=this.params.keyName||"OpenAI-Compatible",E=`${this.params.config.url}${this.params.config.path}`,k={Authorization:`Bearer ${this.params.config.key}`,"Content-Type":"application/json"};Q(r,e,b,this.params.config.model,E,k,i),Z(r,e,b,g,v,i);const $=br(this.params.config.model),P={messages:[{role:"system",content:g},{role:"user",content:v}],model:this.params.config.model,stream:p,...$?{max_completion_tokens:h,temperature:1}:{max_tokens:h,top_p:this.params.config.topP,temperature:a}};oe(r,e,b,P,i);const R=Date.now();try{const A=await this.openAI.chat.completions.create(P,{timeout:f});let B="";if(p&&A){const K=A;for await(const De of K){const Sn=De.choices?.[0]?.delta?.content||"",xn=De.choices?.[0]?.delta?.reasoning_content||"",In=`${Sn}${xn}`;B+=In}}else B=A.choices?.[0]?.message.content||"";const S=Date.now()-R;return W(r,e,b,A,i),Y(r,e,b,S,B,i),e==="review"?this.sanitizeResponse(B):this.parseMessage(B,c,d)}catch(A){throw j(r,e,b,A,i),A}}}class Xc extends ee{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 L(this.generateMessage("commit")).pipe(_(e=>D(e)),O(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})),N(this.handleError$))}generateCodeReview$(){return L(this.generateMessage("review")).pipe(_(e=>D(e)),O(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),N(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:l,locale:a,generate:d,type:c,maxLength:u,proxy:f,maxTokens:p,timeout:h}=this.params.config,y={...J,locale:a,maxLength:u,type:c,generate:d,systemPrompt:o,systemPromptPath:n,codeReviewPromptPath:s,vcs_branch:this.params.branchName||""},g=e==="review"?re(y):te(y),v=await zc("ChatGPT",this.params.config.url,this.params.config.path,this.params.config.key,this.params.config.model,r,h,p,i,this.params.config.topP,g,l,e,f);return ft(e==="review"?v.map(b=>this.sanitizeResponse(b)):v.map(b=>this.parseMessage(b,c,d)))}}class Qc extends ee{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 L(this.generateMessage("commit")).pipe(_(e=>D(e)),O(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})),N(this.handleError$))}generateCodeReview$(){return L(this.generateMessage("review")).pipe(_(e=>D(e)),O(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),N(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:l,generate:a,type:d,maxLength:c}=this.params.config,u={...J,locale:l,maxLength:c,type:d,generate:a,systemPrompt:o,systemPromptPath:n,codeReviewPromptPath:s,vcs_branch:this.params.branchName||""},f=e==="review"?re(u):te(u),p=`Here is the diff: ${r}`,y=`${this.params.config.url||"https://api.perplexity.ai"}/chat/completions`,g={Authorization:`Bearer ${this.apiKey}`,"content-type":"application/json"};Q(r,e,"Perplexity",this.params.config.model,y,g,i),Z(r,e,"Perplexity",f,p,i);const v=await this.createChatCompletions(f,p,e);return this.parseMessage(v,d,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 l=Date.now();try{const a=this.params.config.url||"https://api.perplexity.ai",d=await new ze({method:"POST",baseURL:`${a}/chat/completions`,timeout:this.params.config.timeout}).setHeaders({Authorization:`Bearer ${this.apiKey}`,"content-type":"application/json"}).setBody(i).execute(),c=Date.now()-l,u=d.data;if(W(n,o,"Perplexity",u,s),!u.choices||u.choices.length===0||!u.choices[0].message?.content)throw j(n,o,"Perplexity",{message:"No Content on response",result:u},s),new Error("No Content on response. Please open a Bug report");const p=u.choices[0].message.content;return Y(n,o,"Perplexity",c,p,s),p}catch(a){throw j(n,o,"Perplexity",a,s),a}}}class Ct{constructor(e,r,o=""){this.config=e,this.stagedDiff=r,this.branchName=o}createCommitMsgRequests$(e){return this.createServiceRequests$(e,"commit")}createCodeReviewRequests$(e){return this.createServiceRequests$(e,"review")}createServiceRequests$(e,r){return D(e).pipe(Br(o=>{const n=this.config[o],s=Array.isArray(n.model)?n.model:[n.model];return D(s).pipe(Br(i=>{if(n.compatible){const l=X.create(qc,{config:{...n,url:n.url||"",path:n.path||"",model:i},stagedDiff:this.stagedDiff,keyName:i,branchName:this.branchName});return r==="commit"?l.generateCommitMessage$():l.generateCodeReview$()}switch(o){case"OPENAI":{const a=X.create(Xc,{config:{...this.config.OPENAI,model:i},stagedDiff:this.stagedDiff,keyName:i,branchName:this.branchName});return r==="commit"?a.generateCommitMessage$():a.generateCodeReview$()}case"GEMINI":{const a=X.create(mc,{config:{...this.config.GEMINI,model:i},stagedDiff:this.stagedDiff,keyName:i,branchName:this.branchName});return r==="commit"?a.generateCommitMessage$():a.generateCodeReview$()}case"ANTHROPIC":{const a=X.create(ic,{config:{...this.config.ANTHROPIC,model:i},stagedDiff:this.stagedDiff,keyName:i,branchName:this.branchName});return r==="commit"?a.generateCommitMessage$():a.generateCodeReview$()}case"HUGGINGFACE":{const a=X.create(Yc,{config:{...this.config.HUGGINGFACE,model:i},stagedDiff:this.stagedDiff,keyName:i,branchName:this.branchName});return r==="commit"?a.generateCommitMessage$():a.generateCodeReview$()}case"MISTRAL":{const a=X.create(Jc,{config:{...this.config.MISTRAL,model:i},stagedDiff:this.stagedDiff,keyName:i,branchName:this.branchName});return r==="commit"?a.generateCommitMessage$():a.generateCodeReview$()}case"CODESTRAL":{const a=X.create(lc,{config:{...this.config.CODESTRAL,model:i},stagedDiff:this.stagedDiff,keyName:i,branchName:this.branchName});return r==="commit"?a.generateCommitMessage$():a.generateCodeReview$()}case"OLLAMA":{const a=X.create(Vc,{config:{...this.config.OLLAMA,model:i},keyName:i,stagedDiff:this.stagedDiff,branchName:this.branchName});return r==="commit"?a.generateCommitMessage$():a.generateCodeReview$()}case"COHERE":{const a=X.create(uc,{config:{...this.config.COHERE,model:i},stagedDiff:this.stagedDiff,keyName:i,branchName:this.branchName});return r==="commit"?a.generateCommitMessage$():a.generateCodeReview$()}case"GROQ":{const a=X.create(Wc,{config:{...this.config.GROQ,model:i},stagedDiff:this.stagedDiff,keyName:i,branchName:this.branchName});return r==="commit"?a.generateCommitMessage$():a.generateCodeReview$()}case"PERPLEXITY":{const a=X.create(Qc,{config:{...this.config.PERPLEXITY,model:i},stagedDiff:this.stagedDiff,keyName:i,branchName:this.branchName});return r==="commit"?a.generateCommitMessage$():a.generateCodeReview$()}case"BEDROCK":{const a=X.create(cc,{config:{...this.config.BEDROCK,model:i},stagedDiff:this.stagedDiff,keyName:i});return r==="commit"?a.generateCommitMessage$():a.generateCodeReview$()}case"GITHUB_MODELS":{const a=X.create(Kc,{config:{...this.config.GITHUB_MODELS,model:i},stagedDiff:this.stagedDiff,keyName:i,branchName:this.branchName});return r==="commit"?a.generateCommitMessage$():a.generateCodeReview$()}case"DEEPSEEK":{const a=X.create(dc,{config:{...this.config.DEEPSEEK,model:i},stagedDiff:this.stagedDiff,keyName:i,branchName:this.branchName});return r==="commit"?a.generateCommitMessage$():a.generateCodeReview$()}default:const l=C.red.bold(`[${o}]`);return Mt({name:l+" Invalid AI type",value:"Invalid AI type",isError:!0,disabled:!0})}}))}),N(o=>{const n=C.red.bold("[UNKNOWN]");return Mt({name:n+` ${o.message||""}`,value:"Unknown error",isError:!0,disabled:!0})}))}}class Er{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 bt extends Er{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 x("git",["rev-parse","--show-toplevel"],{reject:!0});return e.trim()}catch(e){const r=e;if(r.code==="ENOENT")throw new w(`Git command not found!
|
|
91
91
|
|
|
92
|
-
Please install Git first: https://git-scm.com/downloads`);if(
|
|
92
|
+
Please install Git first: https://git-scm.com/downloads`);if(r.stderr){if(r.stderr.includes("not a git repository"))throw new w(`Not in a Git repository!
|
|
93
93
|
|
|
94
94
|
Initialize with: git init
|
|
95
|
-
Or navigate to an existing Git repository.`);if(
|
|
95
|
+
Or navigate to an existing Git repository.`);if(r.stderr.includes("permission denied"))throw new w(`Git permission denied: ${r.stderr.trim()}
|
|
96
96
|
|
|
97
|
-
Check file permissions and repository access.`)}throw new w(`Failed to verify Git repository: ${
|
|
98
|
-
`).filter(Boolean),{stdout:l}=await x("git",[...o,"--numstat",...e?e.map(this.excludeFromDiff):[],...
|
|
97
|
+
Check file permissions and repository access.`)}throw new w(`Failed to verify Git repository: ${r.message||"Unknown error"}`)}}async getStagedDiff(e,r){const o=["diff","--cached","--diff-algorithm=minimal"],{stdout:n}=await x("git",[...o,"--name-only",...this.filesToExclude,...e?e.map(this.excludeFromDiff):[],...r?r.map(this.excludeFromDiff):[]]);if(!n)return null;const{stdout:s}=await x("git",[...o,...this.filesToExclude,...e?e.map(this.excludeFromDiff):[],...r?r.map(this.excludeFromDiff):[]]),i=n.split(`
|
|
98
|
+
`).filter(Boolean),{stdout:l}=await x("git",[...o,"--numstat",...e?e.map(this.excludeFromDiff):[],...r?r.map(this.excludeFromDiff):[]]),a=[],d=l.split(`
|
|
99
99
|
`).filter(Boolean);for(const f of d){const p=f.split(" ");p[0]==="-"&&p[1]==="-"&&p[2]&&a.push(p[2])}let c=s;if(a.length>0){s.trim()||(c=""),c+=`
|
|
100
100
|
|
|
101
101
|
--- Binary Files Changed ---
|
|
102
102
|
`;for(const f of a){const{stdout:p}=await x("git",["status","--porcelain",f]),h=p.substring(0,2).trim();c+=`Binary file ${f} ${h==="A"?"added":h==="M"?"modified":h==="D"?"deleted":"changed"}
|
|
103
|
-
`}}const u=[...new Set([...i,...a])];return{files:u,diff:c||`Files changed: ${u.join(", ")}`}}async getCommitDiff(e,
|
|
103
|
+
`}}const u=[...new Set([...i,...a])];return{files:u,diff:c||`Files changed: ${u.join(", ")}`}}async getCommitDiff(e,r,o){const n=["diff-tree","-r","--no-commit-id","--name-only",e],{stdout:s}=await x("git",[...n,...this.filesToExclude,...r?r.map(this.excludeFromDiff):[],...o?o.map(this.excludeFromDiff):[]]);if(!s)return null;const{stdout:i}=await x("git",["show",e,"--",...this.filesToExclude,...r?r.map(this.excludeFromDiff):[],...o?o.map(this.excludeFromDiff):[]]),{stdout:l}=await x("git",["diff-tree","-r","--numstat",e,...r?r.map(this.excludeFromDiff):[],...o?o.map(this.excludeFromDiff):[]]),a=[],d=l.split(`
|
|
104
104
|
`).filter(Boolean);for(const f of d){const p=f.split(" ");p[0]==="-"&&p[1]==="-"&&p[2]&&a.push(p[2])}let c=i;if(a.length>0){i.trim()||(c=""),c+=`
|
|
105
105
|
|
|
106
106
|
--- Binary Files Changed ---
|
|
107
107
|
`;for(const f of a)c+=`Binary file ${f} changed
|
|
108
108
|
`}const u=[...new Set([...s.split(`
|
|
109
|
-
`).filter(Boolean),...a])];return{files:u,diff:c||`Files changed: ${u.join(", ")}`}}async commit(e,
|
|
109
|
+
`).filter(Boolean),...a])];return{files:u,diff:c||`Files changed: ${u.join(", ")}`}}async commit(e,r=[]){try{await x("git",["commit","-m",e,...r],{stdio:"inherit"})}catch(o){const n=o;throw n.stderr?n.stderr.includes("nothing to commit")?new w(`Nothing to commit.
|
|
110
110
|
|
|
111
111
|
Stage your changes with: git add <files>
|
|
112
112
|
Or use the --all flag to stage all changes.`):n.stderr.includes("Please enter the commit message")?new w(`Commit message cannot be empty.
|
|
@@ -117,20 +117,20 @@ Configure with:
|
|
|
117
117
|
git config --global user.name "Your Name"
|
|
118
118
|
git config --global user.email "your.email@example.com"`):n.stderr.includes("Permission denied")?new w(`Git permission error: ${n.stderr.trim()}
|
|
119
119
|
|
|
120
|
-
Check repository permissions and file access.`):new w(`Git commit failed: ${n.stderr.trim()}`):n.exitCode===1?new w("Git commit failed. Check your staged changes and try again."):new w(`Failed to commit with Git: ${n.message||"Unknown error"}`)}}async getCommentChar(){try{const{stdout:e}=await x("git",["config","--get","core.commentChar"]);return e}catch{return"#"}}async getBranchName(){try{const{stdout:e}=await x("git",["branch","--show-current"]),
|
|
120
|
+
Check repository permissions and file access.`):new w(`Git commit failed: ${n.stderr.trim()}`):n.exitCode===1?new w("Git commit failed. Check your staged changes and try again."):new w(`Failed to commit with Git: ${n.message||"Unknown error"}`)}}async getCommentChar(){try{const{stdout:e}=await x("git",["config","--get","core.commentChar"]);return e}catch{return"#"}}async getBranchName(){try{const{stdout:e}=await x("git",["branch","--show-current"]),r=e.trim();if(!r){const{stdout:o}=await x("git",["rev-parse","--short","HEAD"]);return`HEAD@${o.trim()}`}return r}catch{return"HEAD"}}}class Pr extends Er{constructor(){super(...arguments),this.name="jujutsu",this.excludeFromDiff=e=>e.includes("*")||e.includes("?")||e.includes("[")?`~glob:"${e}"`:`~"${e}"`,this.filesToExclude=["package-lock.json","pnpm-lock.yaml","*.lock","*.lockb"]}async assertRepo(){try{const{stdout:e}=await x("jj",["--version"],{reject:!0});process.env.DEBUG&&console.log(`Jujutsu version: ${e}`)}catch(e){const r=e;throw r.code==="ENOENT"?new w(`Jujutsu (jj) command not found!
|
|
121
121
|
|
|
122
122
|
Please install Jujutsu:
|
|
123
123
|
- macOS: brew install jj
|
|
124
124
|
- Linux: cargo install jj-cli
|
|
125
125
|
- Windows: cargo install jj-cli
|
|
126
|
-
- See: https://github.com/martinvonz/jj#installation`):new w(`Failed to execute jj command: ${
|
|
126
|
+
- See: https://github.com/martinvonz/jj#installation`):new w(`Failed to execute jj command: ${r.message}`)}try{const{stdout:e,stderr:r}=await x("jj",["workspace","root"],{reject:!0}),o=e.trim();if(!o)throw new w("jj workspace root returned empty path");const n=I.join(o,".jj");if(!q.existsSync(n))throw new w(`Jujutsu repository directory not found at ${n}
|
|
127
127
|
|
|
128
|
-
Initialize a jj repository with: jj init`);return o}catch(e){if(e instanceof w)throw e;const
|
|
128
|
+
Initialize a jj repository with: jj init`);return o}catch(e){if(e instanceof w)throw e;const r=e;throw r.stderr?r.stderr.includes("not in a jj repo")?new w(`Not in a Jujutsu repository!
|
|
129
129
|
|
|
130
130
|
Initialize with: jj init
|
|
131
|
-
Or navigate to an existing jj repository.`):
|
|
131
|
+
Or navigate to an existing jj repository.`):r.stderr.includes("No workspace found")?new w(`No Jujutsu workspace found!
|
|
132
132
|
|
|
133
|
-
This may be a bare repository. Navigate to a workspace directory.`):new w(`Jujutsu error: ${
|
|
133
|
+
This may be a bare repository. Navigate to a workspace directory.`):new w(`Jujutsu error: ${r.stderr.trim()}`):new w(`Failed to verify Jujutsu repository: ${r.message||"Unknown error"}`)}}async getStagedDiff(e,r){try{const{stdout:o}=await x("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 l="all()";i.length>0&&(l=`all() & ${i.join(" & ")}`);const a=["diff","--name-only"],d=["diff","--git"];i.length>0&&(a.push(l),d.push(l)),process.env.DEBUG&&(console.log("jj diff command with fileset:",a),console.log("fileset expression:",l));const{stdout:c}=await x("jj",a);if(process.env.DEBUG&&console.log("jj diff --name-only output:",JSON.stringify(c)),!c.trim())return null;const{stdout:u}=await x("jj",d),{stdout:f}=await x("jj",["status","--no-pager"]),p=c.split(`
|
|
134
134
|
`).filter(Boolean),h=[],y=f.split(`
|
|
135
135
|
`);for(const b of y)if(b.includes("(binary)")||b.includes("Binary file")){const E=b.match(/([^\s]+)\s*\(binary\)/);E&&E[1]&&h.push(E[1])}let g=u;if(h.length>0){g+=`
|
|
136
136
|
|
|
@@ -142,8 +142,8 @@ Try: jj status --no-pager`);if(n.stderr.includes("Invalid revision"))throw new w
|
|
|
142
142
|
|
|
143
143
|
Check if you're in a valid workspace.`)}if(n.exitCode===1&&!n.stderr)return null;if(process.env.DEBUG)throw new w(`Jujutsu diff failed: ${n.message}
|
|
144
144
|
stderr: ${n.stderr}
|
|
145
|
-
exitCode: ${n.exitCode}`);return null}}async getCommitDiff(e,
|
|
146
|
-
`).filter(Boolean);return{files:d,diff:a||`Files changed: ${d.join(", ")}`}}catch(s){if(process.env.DEBUG){const i=s;console.log("jj getCommitDiff error:",i.message,i.stderr)}return null}}async commit(e,
|
|
145
|
+
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 c=`all() & ${n.join(" & ")}`;s.push(c),i.push(c),process.env.DEBUG&&console.log("jj getCommitDiff fileset expression:",c)}const{stdout:l}=await x("jj",s);if(!l.trim())return null;const{stdout:a}=await x("jj",i),d=l.split(`
|
|
146
|
+
`).filter(Boolean);return{files:d,diff:a||`Files changed: ${d.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 x("jj",["describe","-m",e,...r],{stdio:"inherit"}),await x("jj",["new"],{stdio:"inherit"})}catch(o){const n=o;throw n.stderr?n.stderr.includes("Empty commit message")?new w(`Commit message cannot be empty.
|
|
147
147
|
|
|
148
148
|
Provide a meaningful commit message.`):n.stderr.includes("No changes to commit")?new w(`No changes to commit.
|
|
149
149
|
|
|
@@ -152,7 +152,7 @@ Make some changes first, then try again.`):n.stderr.includes("Invalid revision")
|
|
|
152
152
|
Ensure you're in a valid workspace with changes.`):n.stderr.includes("Operation not allowed")?new w(`Jujutsu operation not allowed: ${n.stderr.trim()}
|
|
153
153
|
|
|
154
154
|
Check repository state with: jj status`):new w(`Jujutsu describe failed: ${n.stderr.trim()}`):n.exitCode===1?new w("Jujutsu commit failed. Check your changes and repository state."):new w(`Failed to commit with Jujutsu: ${n.message||"Unknown error"}`)}}async getCommentChar(){try{const{stdout:e}=await x("jj",["config","get","ui.comment-char"]);return e.trim()||"#"}catch{return"#"}}async getBranchName(){try{const{stdout:e}=await x("jj",["bookmark","list","--revisions","@"]);if(e.trim()){const n=e.split(`
|
|
155
|
-
`)[0].split(":")[0].trim();if(n)return n}const{stdout:
|
|
155
|
+
`)[0].split(":")[0].trim();if(n)return n}const{stdout:r}=await x("jj",["log","-r","@","--no-graph","-T","change_id.short()"]);return r.trim()||"HEAD"}catch{return"HEAD"}}}class $r extends Er{constructor(){super(...arguments),this.name="yadm",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 x("yadm",["rev-parse","--show-toplevel"],{reject:!0}),r=e.trim(),o=process.env.HOME||process.env.USERPROFILE;if(!o)throw new w("HOME environment variable not set. Cannot determine YADM repository.");const n=await import("path"),s=n.resolve(r),i=n.resolve(o);if(s!==i)throw new w(`Not a YADM repository (work tree is not $HOME).
|
|
156
156
|
|
|
157
157
|
YADM work tree: ${s}
|
|
158
158
|
Expected: ${i}
|
|
@@ -161,26 +161,26 @@ This appears to be a regular Git repository.`);const{stdout:l}=await x("yadm",["
|
|
|
161
161
|
|
|
162
162
|
Git directory: ${a}
|
|
163
163
|
|
|
164
|
-
This appears to be a regular Git repository.`);return
|
|
164
|
+
This appears to be a regular Git repository.`);return r}catch(e){if(e instanceof w)throw e;const r=e;if(r.code==="ENOENT")throw new w(`YADM command not found!
|
|
165
165
|
|
|
166
|
-
Please install YADM first: https://yadm.io/`);if(
|
|
166
|
+
Please install YADM first: https://yadm.io/`);if(r.stderr){if(r.stderr.includes("not a git repository"))throw new w(`Not in a YADM repository!
|
|
167
167
|
|
|
168
168
|
Initialize with: yadm init
|
|
169
|
-
Or clone your dotfiles: yadm clone <url>`);if(
|
|
169
|
+
Or clone your dotfiles: yadm clone <url>`);if(r.stderr.includes("permission denied"))throw new w(`YADM permission denied: ${r.stderr.trim()}
|
|
170
170
|
|
|
171
|
-
Check file permissions and repository access.`)}throw new w(`Failed to verify YADM repository: ${
|
|
172
|
-
`).filter(Boolean),{stdout:l}=await x("yadm",[...o,"--numstat",...e?e.map(this.excludeFromDiff):[],...
|
|
171
|
+
Check file permissions and repository access.`)}throw new w(`Failed to verify YADM repository: ${r.message||"Unknown error"}`)}}async getStagedDiff(e,r){const o=["diff","--cached","--diff-algorithm=minimal"],{stdout:n}=await x("yadm",[...o,"--name-only",...this.filesToExclude,...e?e.map(this.excludeFromDiff):[],...r?r.map(this.excludeFromDiff):[]]);if(!n)return null;const{stdout:s}=await x("yadm",[...o,...this.filesToExclude,...e?e.map(this.excludeFromDiff):[],...r?r.map(this.excludeFromDiff):[]]),i=n.split(`
|
|
172
|
+
`).filter(Boolean),{stdout:l}=await x("yadm",[...o,"--numstat",...e?e.map(this.excludeFromDiff):[],...r?r.map(this.excludeFromDiff):[]]),a=[],d=l.split(`
|
|
173
173
|
`).filter(Boolean);for(const f of d){const p=f.split(" ");p[0]==="-"&&p[1]==="-"&&p[2]&&a.push(p[2])}let c=s;if(a.length>0){s.trim()||(c=""),c+=`
|
|
174
174
|
|
|
175
175
|
--- Binary Files Changed ---
|
|
176
176
|
`;for(const f of a){const{stdout:p}=await x("yadm",["status","--porcelain",f]),h=p.substring(0,2).trim();c+=`Binary file ${f} ${h==="A"?"added":h==="M"?"modified":h==="D"?"deleted":"changed"}
|
|
177
|
-
`}}const u=[...new Set([...i,...a])];return{files:u,diff:c||`Files changed: ${u.join(", ")}`}}async getCommitDiff(e,
|
|
177
|
+
`}}const u=[...new Set([...i,...a])];return{files:u,diff:c||`Files changed: ${u.join(", ")}`}}async getCommitDiff(e,r,o){const n=["diff-tree","-r","--no-commit-id","--name-only",e],{stdout:s}=await x("yadm",[...n,...this.filesToExclude,...r?r.map(this.excludeFromDiff):[],...o?o.map(this.excludeFromDiff):[]]);if(!s)return null;const{stdout:i}=await x("yadm",["show",e,"--",...this.filesToExclude,...r?r.map(this.excludeFromDiff):[],...o?o.map(this.excludeFromDiff):[]]),{stdout:l}=await x("yadm",["diff-tree","-r","--numstat",e,...r?r.map(this.excludeFromDiff):[],...o?o.map(this.excludeFromDiff):[]]),a=[],d=l.split(`
|
|
178
178
|
`).filter(Boolean);for(const f of d){const p=f.split(" ");p[0]==="-"&&p[1]==="-"&&p[2]&&a.push(p[2])}let c=i;if(a.length>0){i.trim()||(c=""),c+=`
|
|
179
179
|
|
|
180
180
|
--- Binary Files Changed ---
|
|
181
181
|
`;for(const f of a)c+=`Binary file ${f} changed
|
|
182
182
|
`}const u=[...new Set([...s.split(`
|
|
183
|
-
`).filter(Boolean),...a])];return{files:u,diff:c||`Files changed: ${u.join(", ")}`}}async commit(e,
|
|
183
|
+
`).filter(Boolean),...a])];return{files:u,diff:c||`Files changed: ${u.join(", ")}`}}async commit(e,r=[]){try{await x("yadm",["commit","-m",e,...r],{stdio:"inherit"})}catch(o){const n=o;throw n.stderr?n.stderr.includes("nothing to commit")?new w(`Nothing to commit.
|
|
184
184
|
|
|
185
185
|
Stage your changes with: yadm add <file>
|
|
186
186
|
Or stage tracked file modifications: aicommit2 --all
|
|
@@ -193,14 +193,14 @@ Configure with:
|
|
|
193
193
|
yadm config --global user.name "Your Name"
|
|
194
194
|
yadm config --global user.email "your.email@example.com"`):n.stderr.includes("Permission denied")?new w(`YADM permission error: ${n.stderr.trim()}
|
|
195
195
|
|
|
196
|
-
Check repository permissions and file access.`):new w(`YADM commit failed: ${n.stderr.trim()}`):n.exitCode===1?new w("YADM commit failed. Check your staged changes and try again."):new w(`Failed to commit with YADM: ${n.message||"Unknown error"}`)}}async getCommentChar(){try{const{stdout:e}=await x("yadm",["config","--get","core.commentChar"]);return e}catch{return"#"}}async getBranchName(){try{const{stdout:e}=await x("yadm",["branch","--show-current"]),
|
|
197
|
-
${c instanceof Error?c.message:String(c)}`)}if(e)try{const c=new
|
|
198
|
-
${c instanceof Error?c.message:String(c)}`)}if(
|
|
196
|
+
Check repository permissions and file access.`):new w(`YADM commit failed: ${n.stderr.trim()}`):n.exitCode===1?new w("YADM commit failed. Check your staged changes and try again."):new w(`Failed to commit with YADM: ${n.message||"Unknown error"}`)}}async getCommentChar(){try{const{stdout:e}=await x("yadm",["config","--get","core.commentChar"]);return e}catch{return"#"}}async getBranchName(){try{const{stdout:e}=await x("yadm",["branch","--show-current"]),r=e.trim();if(!r){const{stdout:o}=await x("yadm",["rev-parse","--short","HEAD"]);return`HEAD@${o.trim()}`}return r}catch{return"HEAD"}}}let Ar=null;async function Zc(){const t=process.argv.includes("--git"),e=process.argv.includes("--yadm"),r=process.argv.includes("--jj");if(t)try{const c=new bt;return await c.assertRepo(),c}catch(c){throw new w(`--git flag is set, but Git is not available or not in a git repository.
|
|
197
|
+
${c instanceof Error?c.message:String(c)}`)}if(e)try{const c=new $r;return await c.assertRepo(),c}catch(c){throw new w(`--yadm flag is set, but YADM is not available or not in a YADM repository.
|
|
198
|
+
${c instanceof Error?c.message:String(c)}`)}if(r)try{const c=new Pr;return await c.assertRepo(),c}catch(c){throw new w(`--jj flag is set, but Jujutsu is not available or not in a jj repository.
|
|
199
199
|
${c instanceof Error?c.message:String(c)}`)}const o=process.env.FORCE_GIT==="true",n=process.env.FORCE_YADM==="true",s=process.env.FORCE_JJ==="true";if(o)try{const c=new bt;return await c.assertRepo(),c}catch(c){throw new w(`FORCE_GIT="true" environment variable is set, but Git is not available or not in a git repository.
|
|
200
|
-
${c instanceof Error?c.message:String(c)}`)}if(n)try{const c=new
|
|
201
|
-
${c instanceof Error?c.message:String(c)}`)}if(s)try{const c=new
|
|
200
|
+
${c instanceof Error?c.message:String(c)}`)}if(n)try{const c=new $r;return await c.assertRepo(),c}catch(c){throw new w(`FORCE_YADM="true" environment variable is set, but YADM is not available or not in a YADM repository.
|
|
201
|
+
${c instanceof Error?c.message:String(c)}`)}if(s)try{const c=new Pr;return await c.assertRepo(),c}catch(c){throw new w(`FORCE_JJ="true" environment variable is set, but Jujutsu is not available or not in a jj repository.
|
|
202
202
|
${c instanceof Error?c.message:String(c)}`)}let i=!1;try{i=(await he({})).forceGit===!0}catch{i=!1}if(i)try{const c=new bt;return await c.assertRepo(),c}catch(c){throw new w(`forceGit=true is set in config, but Git is not available or not in a git repository.
|
|
203
|
-
${c instanceof Error?c.message:String(c)}`)}let l=null,a=null,d=null;try{const c=new
|
|
203
|
+
${c instanceof Error?c.message:String(c)}`)}let l=null,a=null,d=null;try{const c=new Pr;return await c.assertRepo(),c}catch(c){l=c instanceof Error?c:new Error(String(c))}try{const c=new bt;return await c.assertRepo(),c}catch(c){a=c instanceof Error?c:new Error(String(c))}try{const c=new $r;return await c.assertRepo(),c}catch(c){d=c instanceof Error?c:new Error(String(c))}if(l&&a&&d){const c=l.message.replace("KnownError: ","").trim(),u=a.message.replace("KnownError: ","").trim(),f=d.message.replace("KnownError: ","").trim();throw new w(`No supported VCS repository found.
|
|
204
204
|
|
|
205
205
|
Jujutsu Error:
|
|
206
206
|
${c}
|
|
@@ -217,7 +217,7 @@ Solutions:
|
|
|
217
217
|
\u2022 Initialize a YADM repository: yadm init (or yadm clone <url>)
|
|
218
218
|
\u2022 Navigate to an existing Jujutsu, Git, or YADM repository
|
|
219
219
|
\u2022 Set FORCE_GIT="true" environment variable to force Git detection
|
|
220
|
-
\u2022 Set forceGit=true in config file to prefer Git detection`)}throw new w("Unexpected error during VCS detection")}async function we(){return
|
|
220
|
+
\u2022 Set forceGit=true in config file to prefer Git detection`)}throw new w("Unexpected error during VCS detection")}async function we(){return Ar||(Ar=await Zc()),Ar}const kr=async()=>(await we()).assertRepo(),Sr=async(t,e)=>(await we()).getStagedDiff(t,e),el=async(t,e,r)=>{const o=await we();if(!o.getCommitDiff)throw new w(`Commit diff not supported for ${o.name}`);return o.getCommitDiff(t,e,r)},tl=async()=>(await we()).getCommentChar(),rl=t=>`Detected ${t.files.length.toLocaleString()} changed file${t.files.length>1?"s":""} (${t.diff.length.toLocaleString()} characters)`,Et=async()=>(await we()).name,ol=async(t,e)=>{await(await we()).commit(t,e||[])},Pt=async()=>(await we()).getBranchName();class ce{constructor(){this.title="aicommit2"}printTitle(){try{const e=Vr.textSync(this.title,{font:"Small Slant"}),r=ss(["#8B5CF6","#A020F0","#D946EF"]);console.log(C.bold(r.multiline(e)))}catch{console.log(C.bold(Vr.textSync(this.title,{font:"Small Slant"})))}}showLoader(e){if(this.loader){this.loader.text=e;return}this.loader=qr(e).start()}stopLoader(){this.loader?.stop(),this.loader=void 0}displaySpinner(e){return qr(e).start()}stopSpinner(e){e.stop(),e.clear()}printStagedFiles(e){console.log(C.bold.green("\u2714 ")+C.bold(`${rl(e)}:`)),console.log(`${e.files.map(r=>` ${r}`).join(`
|
|
221
221
|
`)}
|
|
222
222
|
`)}printAnalyzed(){console.log(`
|
|
223
223
|
${C.bold.green("\u2714")} ${C.bold("Changes analyzed")}`)}printCommitted(){console.log(`
|
|
@@ -229,8 +229,8 @@ ${C.bold.red("\u2716")} ${C.red(`${e}`)}`)}printWarning(e){console.log(`
|
|
|
229
229
|
${C.bold.yellow("\u26A0")} ${C.red(`${e}`)}`)}printSuccess(e){console.log(`
|
|
230
230
|
${C.bold.green("\u2714")} ${C.green(`${e}`)}`)}printInfo(e){console.log(`
|
|
231
231
|
${C.bold.blue("\u2139")} ${C.blue(`${e}`)}`)}printSetupGitEvent(e){console.log(`
|
|
232
|
-
${C.bold.green("\u2714")} ${C.bold(`Git ${e} hook has been set up`)}`)}moveCursorUp(){const e=
|
|
233
|
-
${C.bold.yellow("\u26A0")} ${C.yellow(`${
|
|
232
|
+
${C.bold.green("\u2714")} ${C.bold(`Git ${e} hook has been set up`)}`)}moveCursorUp(){const e=tt.createInterface({input:process.stdin,output:process.stdout});tt.moveCursor(process.stdout,0,-1),e.close()}moveCursorDown(){const e=tt.createInterface({input:process.stdin,output:process.stdout});tt.moveCursor(process.stdout,0,2),e.close()}print(e){console.log(e)}}const nl={isLoading:!1,startOption:{text:"AI is analyzing your changes"}},yn={isLoading:!1,startOption:{text:"AI is performing a code review"}},xr="No commit messages were generated",wn="No code reviews were generated",Ir={type:"reactiveListPrompt",name:"aicommit2Prompt",message:"Pick a commit message to use: ",emptyMessage:`\u26A0 ${xr}`,loop:!1,descPageSize:15,showDescription:!0,pickKey:"short",isDescriptionDim:!0,stopMessage:"Changes analyzed"};class Mr{constructor(e){this.choices$=new Gr([]),this.destroyed$=new zn(1),this.stopMessage="Changes analyzed",this.isDestroyed=!1,this.subscriptions=new Rt,this.inquirerInstance=null,this.loader$=new Gr(e)}addSubscription(e){if(this.isDestroyed){e.unsubscribe();return}this.subscriptions.add(e)}initPrompt(e=Ir){return this.stopMessage=e.stopMessage,Qe.registerPrompt("reactiveListPrompt",is),this.inquirerInstance=Qe.prompt({choices$:this.choices$,loader$:this.loader$,...e}),this.inquirerInstance}startLoader(){this.loader$.next({isLoading:!0})}clearLoader(){this.inquirerInstance&&this.loader$.next({isLoading:!1,clear:!0})}refreshChoices(e){this.isDestroyed||!e||!e.value||this.choices$.next([...this.currentChoices,e].sort(Na))}checkErrorOnChoices(e=!0){if(this.choices$.getValue().map(o=>o).every(o=>o?.isError||o?.disabled)){this.alertNoGeneratedMessage(),this.logEmptyCommitMessage(),e&&process.exit(1);return}this.stopLoaderOnSuccess()}completeSubject(){try{this.destroyed$.next(!0),this.destroyed$.complete(),this.choices$.closed||this.choices$.complete(),this.loader$.closed||this.loader$.complete()}catch(e){console.warn("Error completing subjects:",e)}}closeInquirerInstance(){if(!this.inquirerInstance)return;const e=this.inquirerInstance.ui;e?.rl&&!e.rl.closed&&e.close()}cancel(){this.inquirerInstance?.ui?.activePrompt&&this.inquirerInstance.ui.activePrompt.abortPrompt()}destroy(){if(!this.isDestroyed){this.isDestroyed=!0;try{this.cancel(),this.closeInquirerInstance(),this.subscriptions.unsubscribe(),this.completeSubject()}catch(e){yt()&&console.warn("Error during ReactivePromptManager destruction:",e)}finally{this.inquirerInstance=null}}}alertNoGeneratedMessage(){this.loader$.next({isLoading:!1,message:xr,stopOption:{doneFrame:"\u26A0",color:"yellow"}})}stopLoaderOnSuccess(){this.loader$.next({isLoading:!1,message:this.stopMessage})}logEmptyCommitMessage(){console.log(`
|
|
233
|
+
${C.bold.yellow("\u26A0")} ${C.yellow(`${xr}`)}`)}get currentChoices(){return this.choices$.getValue().map(e=>e)}}const V=new ce;var sl=async(t,e,r,o,n,s,i,l,a,d,c,u,f,p,h)=>(async()=>{if(V.printTitle(),await kr(),o){const S=await Et();S==="git"?await x("git",["add","."]):S==="yadm"&&await x("yadm",["add","--update"])}const y={locale:t?.toString(),generate:e?.toString(),type:n?.toString(),systemPrompt:l?.toString(),...a===!0&&{includeBody:"true"},...u===!0&&{disableLowerCase:"true"}};f&&(y.logLevel="verbose");const g=await he(y,h);(a===!0||g.includeBody===!0)&&Object.keys(g).forEach(S=>{typeof g[S]=="object"&&g[S]!==null&&"includeBody"in g[S]&&(g[S].includeBody=!0)}),u&&Object.keys(g).forEach(S=>{typeof g[S]=="object"&&g[S]!==null&&"disableLowerCase"in g[S]&&(g[S].disableLowerCase=!0)}),await rn(g);const b=V.displaySpinner("Detecting staged files"),E=await Sr(r,g.exclude);if(b.stop(),!E){const S=await Et();let K="No staged changes found.";throw S==="yadm"?(K+=`
|
|
234
234
|
|
|
235
235
|
Stage your changes with: yadm add <file>`,K+=`
|
|
236
236
|
Or stage tracked file modifications: aicommit2 --all`,K+=`
|
|
@@ -242,20 +242,20 @@ Stage your changes with: git add <file>`,K+=`
|
|
|
242
242
|
Or automatically stage all changes: aicommit2 --all`):S==="jujutsu"&&(K+=`
|
|
243
243
|
|
|
244
244
|
Jujutsu automatically tracks all changes in the working copy.`,K+=`
|
|
245
|
-
Make some changes to your files and try again.`),new w(K)}V.printStagedFiles(E);const k=
|
|
245
|
+
Make some changes to your files and try again.`),new w(K)}V.printStagedFiles(E);const k=xe(g,"commit");if(k.length===0)throw new w("Please set at least one API key via the `aicommit2 config set` command");const $=await Pt(),P=new Ct(g,E,$),R=xe(g,"review");R.length>0&&await il(P,R);let A=await al(P,k,d);if(c){if(V.printInfo("Opening editor to modify commit message..."),A=await cl(A),!A.trim())throw new w("Commit message cannot be empty");V.printSuccess("Commit message edited successfully!"),V.print(`
|
|
246
246
|
${A}
|
|
247
|
-
`)}i&&(
|
|
248
|
-
`),process.exit()),(s||d&&k.length===1)&&(await vn(A,h),process.exit());const{confirmationPrompt:
|
|
247
|
+
`)}i&&(As("copy-paste").copy(A),V.printCopied(),p||process.exit()),p&&(process.stdout.write(A+`
|
|
248
|
+
`),process.exit()),(s||d&&k.length===1)&&(await vn(A,h),process.exit());const{confirmationPrompt:B}=await Qe.prompt([{type:"confirm",name:"confirmationPrompt",message:"Use selected message?",default:!0}]);B?await vn(A,h):V.printCancelledCommit(),process.exit()})().catch(y=>{V.printError(y.message),de(y),process.exit(1)});async function il(t,e){const r=new Mr(yn);let o=null;try{const n=r.initPrompt({...Ir,name:"codeReviewPrompt",message:"Please check code reviews: ",emptyMessage:`\u26A0 ${wn}`,isDescriptionDim:!1,stopMessage:"Code review completed",descPageSize:20});if(r.startLoader(),o=t.createCodeReviewRequests$(e).subscribe({next:a=>r.refreshChoices(a),error:a=>{console.error("Code review request error:",a),r.checkErrorOnChoices()},complete:()=>r.checkErrorOnChoices()}),!(await n).codeReviewPrompt?.value)throw new w("An error occurred! No selected code review");V.moveCursorUp();const{continuePrompt:l}=await Qe.prompt([{type:"confirm",name:"continuePrompt",message:"Will you continue without changing the code?",default:!0}]);l||(V.printCancelledCommit(),process.exit())}finally{o&&o.unsubscribe(),r.destroy()}}async function al(t,e,r){const o=new Mr(nl);let n=null;try{if(r&&e.length===1){const a=[];o.startLoader(),n=t.createCommitMsgRequests$(e).subscribe({next:c=>{a.push(c),o.refreshChoices(c)},error:c=>{console.error("Commit message generation error:",c),o.checkErrorOnChoices(!1)},complete:()=>o.checkErrorOnChoices(!1)}),await new Promise(c=>{n?.add(()=>c())}),o.clearLoader(),V.moveCursorUp();const d=a.find(c=>c.value&&!c.isError&&!c.disabled);if(!d||!d.value)throw new w("No valid commit message was generated");return V.print(`
|
|
249
249
|
${d.name}
|
|
250
|
-
`),d.value}const s=o.initPrompt();o.startLoader(),n=
|
|
250
|
+
`),d.value}const s=o.initPrompt();o.startLoader(),n=t.createCommitMsgRequests$(e).subscribe({next:a=>o.refreshChoices(a),error:a=>{console.error("Commit message generation error:",a),o.checkErrorOnChoices()},complete:()=>o.checkErrorOnChoices()});const i=await s;V.moveCursorUp();const l=i.aicommit2Prompt?.value;if(!l)throw new w("An error occurred! No selected message");return l}finally{n&&n.unsubscribe(),o.destroy()}}async function cl(t){const e=process.env.VISUAL||process.env.EDITOR||(process.platform==="win32"?"notepad":"vi"),r=I.join(Oe.tmpdir(),`aicommit2-${Date.now()}-${Dn.randomBytes(4).toString("hex")}.txt`);try{q.writeFileSync(r,t,"utf8");const o=e.split(" "),[n,...s]=o;await x(n,[...s,r],{stdio:"inherit"});const i=q.readFileSync(r,"utf8").trim();if(q.unlinkSync(r),!i)throw new w("Commit cancelled - empty message");return i}catch(o){throw q.existsSync(r)&&q.unlinkSync(r),o instanceof w?o:o&&typeof o=="object"&&"exitCode"in o&&o.exitCode!==0?new w("Commit cancelled"):process.env.VISUAL||process.env.EDITOR?new w(`Failed to open editor "${e}". Please check:
|
|
251
251
|
- Editor binary exists in PATH
|
|
252
252
|
- Editor flags are correct
|
|
253
|
-
- EDITOR/VISUAL is set correctly`):new w(`Failed to open editor "${e}". Please set your EDITOR or VISUAL environment variable to a valid editor command.`)}}async function vn(
|
|
253
|
+
- EDITOR/VISUAL is set correctly`):new w(`Failed to open editor "${e}". Please set your EDITOR or VISUAL environment variable to a valid editor command.`)}}async function vn(t,e){await ol(t,e),V.printCommitted()}var ll=le({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:[le({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"]}}),le({name:"get",parameters:["[<key>","[<key> ...]]"],help:{description:"Retrieve configuration values for specified AI provider.",examples:["aic2 config get OPENAI","aic2 config get ANTHROPIC"]}}),le({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"']}}),le({name:"list",parameters:[],help:{description:"Display all configuration keys and their values.",examples:["aic2 config list"]}}),le({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"]}}),le({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 he({},[]);if(r.length===0){console.log(n);return}for(const s of r){const i=s.split(".");let l=n,a=!0;for(const d of i)if(or(l,d))l=l[d];else{a=!1;break}a?console.log(s,l):console.log(`${s} not found`)}return}if(e==="set"){await sr(r.map(n=>{const s=n.indexOf("=");if(s===-1)throw new w("Invalid format. Use: key=value");const i=n.slice(0,s),l=n.slice(s+1);return[i,l]}));return}if(e==="add"){await Wa(r.map(n=>{const s=n.indexOf("=");if(s===-1)throw new w("Invalid format. Use: key=value");const i=n.slice(0,s),l=n.slice(s+1);return[i,l]}));return}if(e==="list"){await Ya();return}if(e==="del"){if(!o)throw new w("Please provide the config name to delete.");const n=await Be(),s=o.split(".");if(s.length===2){const[i,l]=s;if(n[i]&&typeof n[i]=="object"&&or(n[i],l)){delete n[i][l],Object.keys(n[i]).length===0&&delete n[i];const a=await ke();await F.writeFile(a,Ae.stringify(n),"utf8"),console.log(`Successfully deleted config: ${o}`);const d=await F.readFile(a,"utf8");console.log("--- Updated Config Content ---"),console.log(d),console.log("----------------------------")}else throw new w(`Config not found: ${o}`)}else if(s.length===1){const i=s[0];if(or(n,i)){delete n[i];const l=await ke();await F.writeFile(l,Ae.stringify(n),"utf8"),console.log(`Successfully deleted config: ${o}`);const a=await F.readFile(l,"utf8");console.log("--- Updated Config Content ---"),console.log(a),console.log("----------------------------")}else throw new w(`Config not found: ${o}`)}else throw new w(`Invalid config name format: ${o}`);return}if(e==="path"){await Ja();return}throw new w(`Invalid mode: ${e}`)})().catch(e=>{new ce().printError(e.message),de(e),process.exit(1)})}),ul=le({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 ce;if(t.flags.token){try{await dl(t.flags.token,e)}catch(r){throw new w(`Token authentication failed: ${r.message}`)}return}try{await ml(e)}catch(r){throw new w(`Browser authentication failed: ${r.message}`)}})().catch(e=>{new ce().printError(e.message),de(e),process.exit(1)})});async function dl(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 sr([["GITHUB_MODELS.key",t]]),e.printSuccess(`Successfully authenticated as ${o.login}`)}catch(r){throw new Error(`Token validation failed: ${r.message}`)}}async function ml(t){t.printInfo("Starting GitHub browser authentication for GitHub Models...");try{try{Xe("gh --version",{stdio:"ignore"})}catch{throw new Error("GitHub CLI (gh) is not installed. Please install it first: https://cli.github.com/")}try{Xe("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{Xe("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=Xe("gh auth token",{encoding:"utf8"}).trim();e&&(await sr([["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 Re="prepare-commit-msg",fl=async()=>{const t=await Et();if(t==="git")return`.git/hooks/${Re}`;if(t==="yadm"){const e=process.env.HOME||process.env.USERPROFILE;if(!e)throw new w("HOME environment variable not set. Cannot determine YADM hook path.");try{const{execa:n}=await Promise.resolve().then(function(){return Da}),{stdout:s}=await n("yadm",["introspect","repo"]),i=s.trim();if(i)return I.join(i,"hooks",Re)}catch{}const r=I.join(e,".config/yadm/hooks"),o=I.join(e,".yadm/hooks");try{return await F.access(r),I.join(r,Re)}catch{return I.join(o,Re)}}throw t==="jujutsu"?new w("Hooks are not supported for Jujutsu repositories."):new w(`Hooks are not supported for ${t} repositories.`)},$t=Zn(new URL("cli.mjs",import.meta.url)),pl=process.argv[1].replace(/\\/g,"/").includes(`/hooks/${Re}`),Cn=process.platform==="win32",bn=`
|
|
254
254
|
#!/usr/bin/env node
|
|
255
|
-
import(${JSON.stringify(es(
|
|
256
|
-
`.trim();var hl=le({name:"hook",parameters:["<install/uninstall>"],help:{description:"Install or uninstall the Git prepare-commit-msg hook",examples:["aic2 hook install","aic2 hook uninstall"]}},
|
|
257
|
-
`);const
|
|
258
|
-
${C.green("Total:")} ${e.length} file${e.length!==1?"s":""}`)}catch(e){if(e.code==="ENOENT")console.log(`${C.yellow("Logs directory does not exist yet.")}`);else throw e}},Cl=async
|
|
255
|
+
import(${JSON.stringify(es($t))})
|
|
256
|
+
`.trim();var hl=le({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 kr(),{installUninstall:r}=t._,o=await fl(),n=I.isAbsolute(o)?o:I.join(e,o),s=await Wo(n);if(r==="install"){if(s){if(await F.realpath(n).catch(()=>{})===$t){console.warn("The hook is already installed");return}throw new w(`A different ${Re} hook seems to be installed. Please remove it before installing aicommit2.`)}await F.mkdir(I.dirname(n),{recursive:!0}),Cn?await F.writeFile(n,bn):(await F.symlink($t,n,"file"),await F.chmod(n,493)),console.log(`${C.green("\u2714")} Hook installed`);return}if(r==="uninstall"){if(!s){console.warn("Hook is not installed");return}if(Cn){if(await F.readFile(n,"utf8")!==bn){console.warn("Hook is not installed");return}}else if(await F.realpath(n)!==$t){console.warn("Hook is not installed");return}await F.rm(n),console.log(`${C.green("\u2714")} Hook uninstalled`);return}throw new w(`Invalid mode: ${r}`)})().catch(e=>{console.error(`${C.red("\u2716")} ${e.message}`),de(e),process.exit(1)})});const gl=Un(On),yl=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]},wl=t=>t.toLocaleDateString()+" "+t.toLocaleTimeString(),vl=async t=>{try{const e=await Xr(ie);if(e.length===0){console.log(`${C.yellow("No log files found.")}`);return}console.log(`${C.blue("Log files in")} ${ie}:
|
|
257
|
+
`);const r=await Promise.all(e.map(async o=>{const n=fe.join(ie,o),s=await as(n);return{name:o,size:yl(s.size),modified:wl(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}":" "} ${C.cyan(o.name)} ${C.gray(`(${o.size}, ${o.modified})`)}`)}),console.log(`
|
|
258
|
+
${C.green("Total:")} ${e.length} file${e.length!==1?"s":""}`)}catch(e){if(e.code==="ENOENT")console.log(`${C.yellow("Logs directory does not exist yet.")}`);else throw e}},Cl=async t=>{try{await Xr(ie);const e=process.platform;let r;switch(e){case"darwin":r=`open "${ie}"`;break;case"win32":r=`start "" "${ie}"`;break;default:r=`xdg-open "${ie}"`;break}await gl(r),console.log(`${C.green("\u2714")} Opened logs directory in file manager`)}catch(e){e.code==="ENOENT"?console.log(`${C.yellow("Logs directory does not exist yet.")}`):t.printError(`Failed to open logs directory: ${e.message}`)}},bl=async t=>{try{await cs(ie,{recursive:!0,force:!0}),console.log(`${C.green("\u2714")} All log files removed!`)}catch(e){t.printError(`Failed to remove log files: ${e.message}`)}};var El=le({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 ce;switch(e){case"list":await vl();break;case"path":console.log(`${C.blue("Logs directory:")} ${ie}`);break;case"open":await Cl(r);break;case"removeAll":await bl(r);break;default:throw new w(`Invalid action: ${e}. Use 'list', 'path', 'open', or 'removeAll'`)}})().catch(e=>{new ce().printError(e.message),de(e),process.exit(1)})});const Pl=process.argv.slice(2).filter(t=>!t.startsWith("--pre-commit")),[At,En]=Pl;var $l=(t=!1)=>(async()=>{if(!At)throw new w('Commit message file path is missing. This file should be called from the "pre-commit framework"');if(En){console.log(`Skipping aicommit2 message generation for ${En} commit`);return}const e=await Sr();if(!e)return;const r=new ce;r.printTitle();const o={};t&&(o.logLevel="verbose");const n=await he(o);if(n.systemPromptPath)try{await F.readFile(I.resolve(n.systemPromptPath),"utf-8")}catch{throw new w(`Error reading system prompt file: ${n.systemPromptPath}`)}const s=xe(n,"commit");if(s.length===0)throw new w("Please set at least one API key via the `aicommit2 config set` command");const l=await Pt(),a=new Ct(n,e,l);let d;try{d=await Hr(a.createCommitMsgRequests$(s).pipe(Ur(g=>!g.isError),O(g=>g.value),zr()))}finally{r.printAnalyzed()}const u=await F.readFile(At,"utf8")!=="",f=d.length>1;let p="";u&&(p=`# \u{1F916} Generated by aicommit2 (https://github.com/tak-bro/aicommit2)
|
|
259
259
|
`,p+=`# ----------------------------------------
|
|
260
260
|
`,p+=`# How to use:
|
|
261
261
|
`,f?(p+=`# 1. Remove the "#" from your chosen message
|
|
@@ -273,8 +273,8 @@ ${d.map(g=>`# ${g}`).join(`
|
|
|
273
273
|
# \u{1F4DD} Generated commit message:
|
|
274
274
|
`),p+=`
|
|
275
275
|
${d[0]}
|
|
276
|
-
`);const h=await
|
|
277
|
-
`+h;await
|
|
276
|
+
`);const h=await F.readFile(At,"utf8"),y=p+`
|
|
277
|
+
`+h;await F.writeFile(At,y),r.printSavedCommitMessage()})().catch(e=>{new ce().printError(e.message),de(e),process.exit(1)});const Rr=process.argv.slice(2),Pn=[];let Dr=!1;for(let t=0;t<Rr.length;t++){const e=Rr[t];if(Dr){Dr=!1;continue}if(e!=="--hook-mode"){if(e.startsWith("-")){const r=Rr[t+1];r&&!r.startsWith("-")&&(Dr=!0);continue}Pn.push(e)}}const[kt,$n]=Pn;var Al=(t,e,r,o,n,s,i)=>(async()=>{if(!kt)throw new w('Commit message file path is missing. This file should be called from the "prepare-commit-msg" git hook or with --hook-mode flag');if($n){console.log(`Skipping aicommit2 message generation for ${$n} commit`);return}const l=await Sr();if(!l)return;const a=new ce;a.printTitle();const d={locale:t?.toString(),generate:e?.toString(),type:o?.toString(),systemPrompt:n?.toString(),...s===!0&&{includeBody:"true"}};i&&(d.logLevel="verbose");const c=await he(d,r);if(c.systemPromptPath)try{await F.readFile(I.resolve(c.systemPromptPath),"utf-8")}catch{throw new w(`Error reading system prompt file: ${c.systemPromptPath}`)}const u=xe(c,"commit");if(u.length===0)throw new w("Please set at least one API key via the `aicommit2 config set` command");const p=await Pt(),h=new Ct(c,l,p),y=a.displaySpinner("The AI is analyzing your changes");let g;try{g=await Hr(h.createCommitMsgRequests$(u).pipe(Ur(A=>!A.isError),O(A=>A.value),zr()))}finally{y.stop(),y.clear(),a.printAnalyzed()}const b=await F.readFile(kt,"utf8")!=="",E=g.length>1,k=await tl();let $="";b&&($=`${k} \u{1F916} Generated by aicommit2 (https://github.com/tak-bro/aicommit2)
|
|
278
278
|
`,$+=`${k} ----------------------------------------
|
|
279
279
|
`,$+=`${k} How to use:
|
|
280
280
|
`,E?($+=`${k} 1. Remove the "${k}" from your chosen message
|
|
@@ -292,11 +292,11 @@ ${g.map(A=>`${k} ${A}`).join(`
|
|
|
292
292
|
${k} \u{1F4DD} Generated commit message:
|
|
293
293
|
`),$+=`
|
|
294
294
|
${g[0]}
|
|
295
|
-
`);const P=await
|
|
296
|
-
`+P;await
|
|
295
|
+
`);const P=await F.readFile(kt,"utf8"),R=$+`
|
|
296
|
+
`+P;await F.writeFile(kt,R),a.printSavedCommitMessage()})().catch(l=>{new ce().printError(l.message),de(l),process.exit(1)});class An{constructor(e="SubscriptionManager"){this.destroyed$=new Dt,this.subscriptions=new Rt,this.isDestroyed=!1,this.name=e}add(e,r){if(this.isDestroyed){console.warn(`${this.name}: Cannot add subscription - manager is destroyed`);const n=new Rt;return n.unsubscribe(),n}const o=e.pipe(Qr(this.destroyed$),Zr(()=>{process.env.NODE_ENV==="development"&&console.log(`${this.name}: Observable finalized`)})).subscribe({next:r?.next,error:n=>{console.error(`${this.name}: Observable error:`,n),r?.error?.(n)},complete:r?.complete});return this.subscriptions.add(o),o}pipe(e){return this.isDestroyed?(console.warn(`${this.name}: Cannot pipe - manager is destroyed`),e):e.pipe(Qr(this.destroyed$),Zr(()=>{process.env.NODE_ENV==="development"&&console.log(`${this.name}: Piped observable finalized`)}))}addSubscription(e){if(this.isDestroyed){console.warn(`${this.name}: Cannot add subscription - manager is destroyed`),e.unsubscribe();return}this.subscriptions.add(e)}get destroySignal$(){return this.destroyed$.asObservable()}get isActive(){return!this.isDestroyed}destroy(){this.isDestroyed||(this.isDestroyed=!0,this.subscriptions.unsubscribe(),this.destroyed$.next(),this.destroyed$.complete(),process.env.NODE_ENV==="development"&&console.log(`${this.name}: Destroyed successfully`))}}const kl=new An("Global"),qe=()=>{kl.destroy()};process.on("exit",qe),process.on("SIGINT",qe),process.on("SIGTERM",qe),process.on("uncaughtException",t=>{console.error("Uncaught exception:",t),qe(),process.exit(1)}),process.on("unhandledRejection",(t,e)=>{console.error("Unhandled rejection at:",e,"reason:",t),qe(),process.exit(1)});class Sl{constructor(){this.destroyed$=new Dt,this.consoleManager=new ce,this.subscriptionManager=new An,this.currentCodeReviewSubscription=null,this.currentCodeReviewPromptManager=null,this.watcher=null,this.lastCommitHash=null,this.isProcessingCommit=!1,this.REPO_PATH=process.cwd(),this.GIT_PATH=I.join(this.REPO_PATH,".git"),this.HEAD_PATH=I.join(this.GIT_PATH,"HEAD"),this.REFS_PATH=I.join(this.GIT_PATH,"refs","heads"),this.COMMIT_MSG_PATH=I.join(this.GIT_PATH,"COMMIT_EDITMSG"),this.setupProcessHandlers()}setupProcessHandlers(){const e=()=>{this.destroy(),process.exit(0)};process.on("SIGINT",e),process.on("SIGTERM",e),process.on("SIGQUIT",e)}async watch(e,r,o,n,s,i){this.consoleManager.printTitle(),await kr();const l=await Et();if(l!=="git")throw new w(`Watch mode is only supported for Git repositories. Current VCS: ${l}`);const a=await this.initializeConfig(e,r,n,s,i);await this.initializeCurrentCommit();try{await this.watchGitEvents(a)}catch(d){return await this.handleWatchGitError(d),this.watch(e,r,o,n,s,i)}}async initializeConfig(e,r,o,n,s){const i={locale:e?.toString(),generate:r?.toString(),systemPrompt:o?.toString()};n&&(i.logLevel="verbose");const l=await he(i,s);return await rn(l),xe(l,"watch").length===0&&(this.consoleManager.printError(`Please set at least one API key and watchMode via the config command:
|
|
297
297
|
aicommit2 config set [MODEL].key="YOUR_API_KEY"
|
|
298
|
-
aicommit2 config set [MODEL].watchMode="true"`),process.exit()),l}async handleWatchGitError(e){this.consoleManager.printError(`An error occurred: ${e.message}`),de(e),await new Promise(
|
|
298
|
+
aicommit2 config set [MODEL].watchMode="true"`),process.exit()),l}async handleWatchGitError(e){this.consoleManager.printError(`An error occurred: ${e.message}`),de(e),await new Promise(r=>setTimeout(r,3e3)),this.consoleManager.printWarning("Restarting the commit monitoring process...")}async initializeCurrentCommit(){try{const e=await this.executeGitCommand("git rev-parse HEAD");this.lastCommitHash=e.trim(),this.consoleManager.printInfo(`Starting watch from commit: ${this.lastCommitHash.substring(0,8)}`)}catch{this.consoleManager.printWarning("No commits found in repository"),this.lastCommitHash=null}}async executeGitCommand(e){const r=Gn(Fn),{stdout:o}=await r(e,{cwd:this.REPO_PATH});return o}clearTerminal(){process.stdout.write("\x1Bc")}async handleCommitEvent(e,r){try{const o=await el(r);if(!o){this.consoleManager.printWarning("No changes found in this commit");return}this.consoleManager.stopLoader(),this.consoleManager.printStagedFiles(o);const n=xe(e,"watch");if(n.length===0){this.consoleManager.printError(`Please set at least one API key and watchMode via the config command:
|
|
299
299
|
aicommit2 config set [MODEL].key="YOUR_API_KEY"
|
|
300
|
-
aicommit2 config set [MODEL].watchMode="true"`),process.exit();return}await this.performCodeReview(e,o,n)}catch(o){this.consoleManager.printError(`Error processing commit ${
|
|
300
|
+
aicommit2 config set [MODEL].watchMode="true"`),process.exit();return}await this.performCodeReview(e,o,n)}catch(o){this.consoleManager.printError(`Error processing commit ${r}: ${o.message}`)}}async performCodeReview(e,r,o){this.cleanupPreviousCodeReview();const n=await Pt(),s=new Ct(e,r,n);this.currentCodeReviewPromptManager=new Mr(yn);try{const i=this.initializeCodeReviewInquirer();this.currentCodeReviewPromptManager.startLoader(),this.currentCodeReviewSubscription=this.subscribeToCodeReviewRequests(s,o),await i}finally{this.cleanupCodeReview()}}cleanupPreviousCodeReview(){this.cleanupCurrentReviewResources(),this.destroyed$.closed||(this.destroyed$.next(),this.destroyed$.complete()),this.destroyed$=new Dt}initializeCodeReviewInquirer(){return this.currentCodeReviewPromptManager.initPrompt({...Ir,name:"codeReviewPrompt",message:"Please check code reviews: ",emptyMessage:`\u26A0 ${wn}`,isDescriptionDim:!1,stopMessage:"Code review completed",descPageSize:20})}subscribeToCodeReviewRequests(e,r){return this.subscriptionManager.add(e.createCodeReviewRequests$(r),{next:o=>{this.currentCodeReviewPromptManager?.refreshChoices(o)},error:o=>{console.error("Code review request error:",o),this.currentCodeReviewPromptManager?.checkErrorOnChoices(!1)},complete:()=>{this.currentCodeReviewPromptManager?.checkErrorOnChoices(!1)}})}cleanupCurrentReviewResources(){this.currentCodeReviewSubscription&&(this.currentCodeReviewSubscription.unsubscribe(),this.currentCodeReviewSubscription=null),this.currentCodeReviewPromptManager&&(this.currentCodeReviewPromptManager.destroy(),this.currentCodeReviewPromptManager=null)}cleanupCodeReview(){this.cleanupCurrentReviewResources(),this.clearTerminal(),this.consoleManager.showLoader("Watching for new Git commits...")}async isGitReset(e){if(!this.lastCommitHash)return!1;try{const r=await this.executeGitCommand(`git merge-base --is-ancestor ${e} ${this.lastCommitHash}`);return!0}catch{return!1}}cancelCurrentReview(){this.currentCodeReviewPromptManager&&this.currentCodeReviewPromptManager.cancel(),this.cleanupCurrentReviewResources(),this.destroyed$.next()}async watchGitEvents(e){this.consoleManager.showLoader("Watching for new Git commits...");const o=[this.HEAD_PATH,this.REFS_PATH,this.COMMIT_MSG_PATH,I.join(this.GIT_PATH,"logs","HEAD")].filter(n=>{try{return q.accessSync(n),!0}catch{return!1}});this.watcher=ls.watch(o,{persistent:!0,ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:500,pollInterval:100}}),this.watcher.on("change",async n=>{await this.handleGitChange(e,n)}),this.watcher.on("add",async n=>{await this.handleGitChange(e,n)}),this.watcher.on("error",n=>{this.consoleManager.printError(`Watcher error: ${n.message}`),setTimeout(()=>this.watchGitEvents(e),1e3)})}async handleGitChange(e,r){try{const n=(await this.executeGitCommand("git rev-parse HEAD")).trim();if(n!==this.lastCommitHash){if(await this.isGitReset(n)){this.clearTerminal(),this.consoleManager.printInfo(`\u21A9\uFE0F Git reset detected: ${n.substring(0,8)}`),this.lastCommitHash=n,this.isProcessingCommit&&(this.cancelCurrentReview(),this.isProcessingCommit=!1);return}if(this.isProcessingCommit){this.consoleManager.printInfo(`
|
|
301
301
|
\u{1F504} New commit detected, cancelling current review...`);try{this.cancelCurrentReview(),await new Promise(i=>setTimeout(i,200))}catch(i){console.warn("Error during review cancellation:",i)}}this.isProcessingCommit=!0;try{this.consoleManager.stopLoader(),this.consoleManager.printInfo(`
|
|
302
|
-
\u{1F50D} New commit detected: ${n.substring(0,8)}`);const i=this.lastCommitHash;this.lastCommitHash=n,this.clearTerminal(),await this.handleCommitEvent(e,n)}catch(i){this.consoleManager.printError(`Error processing commit ${n.substring(0,8)}: ${i.message}`)}finally{this.isProcessingCommit=!1}}}catch(o){this.isProcessingCommit=!1,o.message?.includes("fatal: not a git repository")||this.consoleManager.printError(`Error checking for new commits: ${o.message}`)}}destroy(){this.isProcessingCommit=!1,this.lastCommitHash=null;try{this.subscriptionManager.destroy(),this.cleanupCurrentReviewResources(),this.watcher&&(this.watcher.close(),this.watcher=null),this.consoleManager.stopLoader(),this.destroyed$.next(),this.destroyed$.complete()}catch(e){console.warn("Error during WatchGitManager destruction:",e)}}}const xl=new Sl,Il=async(
|
|
302
|
+
\u{1F50D} New commit detected: ${n.substring(0,8)}`);const i=this.lastCommitHash;this.lastCommitHash=n,this.clearTerminal(),await this.handleCommitEvent(e,n)}catch(i){this.consoleManager.printError(`Error processing commit ${n.substring(0,8)}: ${i.message}`)}finally{this.isProcessingCommit=!1}}}catch(o){this.isProcessingCommit=!1,o.message?.includes("fatal: not a git repository")||this.consoleManager.printError(`Error checking for new commits: ${o.message}`)}}destroy(){this.isProcessingCommit=!1,this.lastCommitHash=null;try{this.subscriptionManager.destroy(),this.cleanupCurrentReviewResources(),this.watcher&&(this.watcher.close(),this.watcher=null),this.consoleManager.stopLoader(),this.destroyed$.next(),this.destroyed$.complete()}catch(e){console.warn("Error during WatchGitManager destruction:",e)}}}const xl=new Sl,Il=async(t,e,r,o,n,s)=>xl.watch(t,e,r,o,n,s),St=process.argv.slice(2),{version:kn,description:Ml}=$s;Mn({name:"aicommit2",version:kn,flags:{locale:{type:String,description:"Locale to use for the generated commit messages (default: en)",alias:"l"},generate:{type:Number,description:"Number of messages to generate (Warning: generating multiple costs more) (default: 1)",alias:"g"},exclude:{type:[String],description:"Files to exclude from AI analysis",alias:"x"},all:{type:Boolean,description:"Automatically stage changes in tracked files for the commit",alias:"a",default:!1},type:{type:String,description:"Type of commit message to generate (default: conventional)",alias:"t"},confirm:{type:Boolean,description:"Skip confirmation when committing after message generation (default: false)",alias:"y",default:!1},clipboard:{type:Boolean,description:"Copy the selected message to the clipboard",alias:"c",default:!1},prompt:{type:String,description:"Custom prompt to let users fine-tune provided prompt",alias:"p"},"watch-commit":{type:Boolean,default:!1},"hook-mode":{type:Boolean,description:"Run in git hook mode, allowing chaining with other hooks",default:!1},"pre-commit":{type:Boolean,description:"Run in pre-commit Framework, allowing chaining with other hooks",default:!1},"include-body":{type:Boolean,description:"Force include commit body in all generated messages",alias:"i",default:!1},"auto-select":{type:Boolean,description:"Automatically select the message when only one is generated",alias:"s",default:!1},edit:{type:Boolean,description:"Open the AI-generated commit message in your default editor",alias:"e",default:!1},"disable-lowercase":{type:Boolean,description:"Disable automatic lowercase conversion of commit messages",default:!1},verbose:{type:Boolean,description:"Enable verbose logging for this run",alias:"v",default:!1},git:{type:Boolean,description:"Force use Git (overrides auto-detection)",default:!1},yadm:{type:Boolean,description:"Force use YADM (overrides auto-detection)",default:!1},jj:{type:Boolean,description:"Force use Jujutsu (overrides auto-detection)",default:!1},"dry-run":{type:Boolean,description:"Generate commit message without committing (output only)",alias:"d",default:!1}},commands:[ll,ul,hl,El],help:{description:Ml},ignoreArgv:t=>t==="unknown-flag"||t==="argument"},async t=>{const e={};t.flags.verbose&&(e.logLevel="verbose");const r=await he(e,St);if(await Za(r),Ie.info(`aicommit2 version: ${kn}`),t.flags["pre-commit"]){$l(t.flags.verbose);return}if(t.flags["hook-mode"]||pl){Al(t.flags.locale,t.flags.generate,t.flags.exclude,t.flags.type,t.flags.prompt,t.flags["include-body"],t.flags.verbose);return}if(t.flags["watch-commit"]){Il(t.flags.locale,t.flags.generate,t.flags.exclude,t.flags.prompt,t.flags.verbose,St);return}sl(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"],t.flags.verbose,t.flags["dry-run"],St)},St);
|