aicommit2 2.4.25 → 2.4.26
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +15 -1
- package/dist/cli.mjs +116 -116
- 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 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"?`
|
|
2
|
+
import{command as ue,cli as Mn}from"cleye";import{createRequire as Rn}from"module";import Dn from"crypto";import q from"fs";import Ne from"os";import x from"path";import{Buffer as Nr}from"node:buffer";import he from"node:path";import It,{ChildProcess as Fr,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 _r}from"node:url";import _n,{constants as Lr}from"node:os";import Tr from"assert";import jr from"events";import{createWriteStream as Ln,createReadStream as Tn,readFileSync as jn}from"node:fs";import Bn from"buffer";import Mt from"stream";import Br,{promisify as Gn}from"util";import{debuglog as Hn,promisify as Un}from"node:util";import Ze from"inquirer";import F from"fs/promises";import C from"chalk";import{of as Rt,concatMap as _,from as D,map as O,catchError as N,mergeMap as Gr,BehaviorSubject as Hr,ReplaySubject as zn,Subscription as Dt,lastValueFrom as Ur,filter as zr,toArray as Kr,Subject as Ot}from"rxjs";import Kn from"@anthropic-ai/sdk";import{fromPromise as L}from"rxjs/internal/observable/innerFrom";import{xxh64 as Wr}from"@pacote/xxhash";import U from"winston";import"winston-daily-rotate-file";import Yr from"https";import Wn from"axios";import{CohereClientV2 as Yn}from"cohere-ai";import Jr from"openai";import{GoogleGenerativeAI as Jn,HarmCategory as et,HarmBlockThreshold as tt}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 Vr from"tty";import ts from"groq-sdk";import{Ollama as rs}from"ollama";import{fetch as os,Agent as ns}from"undici";import rt from"readline";import qr from"figlet";import ss from"gradient-string";import Xr from"ora";import is from"inquirer-reactive-list-prompt";import{readdir as Qr,stat as as,rm as cs}from"node:fs/promises";import ls from"chokidar";import{takeUntil as Zr,finalize as eo}from"rxjs/operators";var us="aicommit2",to="2.4.26",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:to,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),H=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function be(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Ee={exports:{}},Nt,ro;function ks(){if(ro)return Nt;ro=1,Nt=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 Nt}var Ft,oo;function Ss(){if(oo)return Ft;oo=1,Ft=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),g=f|p,y=l&h||l&p&&d===u||l&f&&a===c||l&g&&c===0;return y}return Ft}var ot;process.platform==="win32"||H.TESTING_WINDOWS?ot=ks():ot=Ss();var xs=_t;_t.sync=Is;function _t(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){_t(t,e||{},function(s,i){s?n(s):o(i)})})}ot(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 ot.sync(t,e||{})}catch(r){if(e&&e.ignoreErrors||r.code==="EACCES")return!1;throw r}}const Pe=process.platform==="win32"||process.env.OSTYPE==="cygwin"||process.env.OSTYPE==="msys",no=x,Ms=Pe?";":":",so=xs,io=t=>Object.assign(new Error(`not found: ${t}`),{code:"ENOENT"}),ao=(t,e)=>{const r=e.colon||Ms,o=t.match(/\//)||Pe&&t.match(/\\/)?[""]:[...Pe?[process.cwd()]:[],...(e.path||process.env.PATH||"").split(r)],n=Pe?e.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",s=Pe?n.split(r):[""];return Pe&&t.indexOf(".")!==-1&&s[0]!==""&&s.unshift(""),{pathEnv:o,pathExt:s,pathExtExe:n}},co=(t,e,r)=>{typeof e=="function"&&(r=e,e={}),e||(e={});const{pathEnv:o,pathExt:n,pathExtExe:s}=ao(t,e),i=[],l=d=>new Promise((c,u)=>{if(d===o.length)return e.all&&i.length?c(i):u(io(t));const f=o[d],p=/^".*"$/.test(f)?f.slice(1,-1):f,h=no.join(p,t),g=!p&&/^\.[\\\/]/.test(t)?t.slice(0,2)+h:h;c(a(g,d,0))}),a=(d,c,u)=>new Promise((f,p)=>{if(u===n.length)return f(l(c+1));const h=n[u];so(d+h,{pathExt:s},(g,y)=>{if(!g&&y)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}=ao(t,e),s=[];for(let i=0;i<r.length;i++){const l=r[i],a=/^".*"$/.test(l)?l.slice(1,-1):l,d=no.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(so.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 io(t)};var Ds=co;co.sync=Rs;var Lt={exports:{}};const lo=(t={})=>{const e=t.env||process.env;return(t.platform||process.platform)!=="win32"?"PATH":Object.keys(e).reverse().find(o=>o.toUpperCase()==="PATH")||"Path"};Lt.exports=lo,Lt.exports.default=lo;var Os=Lt.exports;const uo=x,Ns=Ds,Fs=Os;function mo(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?uo.delimiter:void 0})}catch{}finally{s&&process.chdir(o)}return i&&(i=uo.resolve(n?t.options.cwd:"",i)),i}function _s(t){return mo(t)||mo(t,!0)}var Ls=_s,Tt={};const jt=/([()\][%!^"`<>&|;, *?])/g;function Ts(t){return t=t.replace(jt,"^$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(jt,"^$1"),e&&(t=t.replace(jt,"^$1")),t}Tt.command=Ts,Tt.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 Bt=q,Us=Hs;function zs(t){const r=Buffer.alloc(150);let o;try{o=Bt.openSync(t,"r"),Bt.readSync(o,r,0,150,0),Bt.closeSync(o)}catch{}return Us(r.toString())}var Ks=zs;const Ws=x,fo=Ls,po=Tt,Ys=Ks,Js=process.platform==="win32",Vs=/\.(?:com|exe)$/i,qs=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function Xs(t){t.file=fo(t);const e=t.file&&Ys(t.file);return e?(t.args.unshift(t.file),t.command=e,fo(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=po.command(t.command),t.args=t.args.map(s=>po.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 Gt=process.platform==="win32";function Ht(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(!Gt)return;const r=t.emit;t.emit=function(o,n){if(o==="exit"){const s=ho(n,e);if(s)return r.call(t,"error",s)}return r.apply(t,arguments)}}function ho(t,e){return Gt&&t===1&&!e.file?Ht(e.original,"spawn"):null}function ri(t,e){return Gt&&t===1&&!e.file?Ht(e.original,"spawnSync"):null}var oi={hookChildProcess:ti,verifyENOENT:ho,verifyENOENTSync:ri,notFoundError:Ht};const go=Nn,Ut=ei,zt=oi;function yo(t,e,r){const o=Ut(t,e,r),n=go.spawn(o.command,o.args,o.options);return zt.hookChildProcess(n,o),n}function ni(t,e,r){const o=Ut(t,e,r),n=go.spawnSync(o.command,o.args,o.options);return n.error=n.error||zt.verifyENOENTSync(n.status,o),n}Ee.exports=yo,Ee.exports.spawn=yo,Ee.exports.sync=ni,Ee.exports._parse=Ut,Ee.exports._enoent=zt;var si=Ee.exports,ii=be(si);function ai(t){const e=typeof t=="string"?`
|
|
3
3
|
`:`
|
|
4
|
-
`.charCodeAt(),r=typeof t=="string"?"\r":"\r".charCodeAt();return t[t.length-1]===e&&(t=t.slice(0,-1)),t[t.length-1]===r&&(t=t.slice(0,-1)),t}function
|
|
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
|
|
6
|
-
${o.message}`:
|
|
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},
|
|
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},
|
|
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 wo(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[wo()],preferLocal:r=!0,execPath:o=se.execPath,addExecPath:n=!0}={})=>{const s=t instanceof URL?_r(t):t,i=he.resolve(s),l=[];return r&&li(l,i),n&&ui(l,o,i),[...l,e].join(he.delimiter)},li=(t,e)=>{let r;for(;r!==e;)t.push(he.join(e,"node_modules/.bin")),r=e,e=he.resolve(e,"..")},ui=(t,e,r)=>{const o=e instanceof URL?_r(e):e;t.push(he.resolve(r,o,".."))},di=({env:t=se.env,...e}={})=>{t={...t};const r=wo({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 nt=new WeakMap,vo=(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(nt.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),nt.set(s,o),s};vo.callCount=t=>{if(!nt.has(t))throw new Error(`The given function \`${t.name}\` is not wrapped by the \`onetime\` package`);return nt.get(t)};const Ci=()=>{const t=bo-Co+1;return Array.from({length:t},bi)},bi=(t,e)=>({name:`SIGRT${e+1}`,number:Co+e,action:"terminate",description:"Application-specific signal (realtime)",standard:"posix"}),Co=34,bo=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"}],Eo=()=>{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}}=Lr,l=i!==void 0;return{name:t,number:l?i:e,description:r,supported:l,action:o,forced:n,standard:s}},$i=()=>{const t=Eo();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=Eo(),e=bo+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})=>Lr.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",st=({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,y=`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?`${y}
|
|
6
|
+
${o.message}`:y,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},it=["stdin","stdout","stderr"],Ri=t=>it.some(e=>t[e]!==void 0),Po=t=>{if(!t)return;const{stdio:e}=t;if(e===void 0)return it.map(o=>t[o]);if(Ri(t))throw new Error(`It's not possible to provide \`stdio\` in combination with one of ${it.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,it.length);return Array.from({length:r},(o,n)=>e[n])},Di=t=>{const e=Po(t);return e==="ipc"?"ipc":e===void 0||typeof e=="string"?[e,e,e,"ipc"]:e.includes("ipc")?e:[...e,"ipc"]};var $e={exports:{}},at={exports:{}};at.exports;var $o;function Oi(){return $o||($o=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")}(at)),at.exports}var T=H.process;const ge=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(!ge(T))$e.exports=function(){return function(){}};else{var Ni=Tr,Fe=Oi(),Fi=/^win/i.test(T.platform),ct=jr;typeof ct!="function"&&(ct=ct.EventEmitter);var z;T.__signal_exit_emitter__?z=T.__signal_exit_emitter__:(z=T.__signal_exit_emitter__=new ct,z.count=0,z.emitted={}),z.infinite||(z.setMaxListeners(1/0),z.infinite=!0),$e.exports=function(t,e){if(!ge(H.process))return function(){};Ni.equal(typeof t,"function","a callback must be provided for exit handler"),_e===!1&&Ao();var r="exit";e&&e.alwaysLast&&(r="afterexit");var o=function(){z.removeListener(r,t),z.listeners("exit").length===0&&z.listeners("afterexit").length===0&&Kt()};return z.on(r,t),o};var Kt=function(){!_e||!ge(H.process)||(_e=!1,Fe.forEach(function(e){try{T.removeListener(e,Wt[e])}catch{}}),T.emit=Yt,T.reallyExit=ko,z.count-=1)};$e.exports.unload=Kt;var Ae=function(e,r,o){z.emitted[e]||(z.emitted[e]=!0,z.emit(e,r,o))},Wt={};Fe.forEach(function(t){Wt[t]=function(){if(ge(H.process)){var r=T.listeners(t);r.length===z.count&&(Kt(),Ae("exit",null,t),Ae("afterexit",null,t),Fi&&t==="SIGHUP"&&(t="SIGINT"),T.kill(T.pid,t))}}}),$e.exports.signals=function(){return Fe};var _e=!1,Ao=function(){_e||!ge(H.process)||(_e=!0,z.count+=1,Fe=Fe.filter(function(e){try{return T.on(e,Wt[e]),!0}catch{return!1}}),T.emit=Li,T.reallyExit=_i)};$e.exports.load=Ao;var ko=T.reallyExit,_i=function(e){ge(H.process)&&(T.exitCode=e||0,Ae("exit",T.exitCode,null),Ae("afterexit",T.exitCode,null),ko.call(T,T.exitCode))},Yt=T.emit,Li=function(e,r){if(e==="exit"&&ge(H.process)){r!==void 0&&(T.exitCode=r);var o=Yt.apply(this,arguments);return Ae("exit",T.exitCode,null),Ae("afterexit",T.exitCode,null),o}else return Yt.apply(this,arguments)}}var Ti=$e.exports,ji=be(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 Jt(t){return t!==null&&typeof t=="object"&&typeof t.pipe=="function"}function So(t){return Jt(t)&&t.writable!==!1&&typeof t._write=="function"&&typeof t._writableState=="object"}const Xi=t=>t instanceof Fr&&typeof t.then=="function",Vt=(t,e,r)=>{if(typeof r=="string")return t[e].pipe(Ln(r)),t;if(So(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(!So(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=Vt.bind(void 0,t,"stdout")),t.stderr!==null&&(t.pipeStderr=Vt.bind(void 0,t,"stderr")),t.all!==void 0&&(t.pipeAll=Vt.bind(void 0,t,"all"))};var Le={exports:{}};const{PassThrough:Zi}=Mt;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=Mt,{promisify:oa}=Br,na=ea,sa=oa(ra.pipeline);class xo extends Error{constructor(){super("maxBuffer exceeded"),this.name="MaxBufferError"}}async function qt(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 xo)})}),o.getBufferedValue()}Le.exports=qt,Le.exports.buffer=(t,e)=>qt(t,{...e,encoding:"buffer"}),Le.exports.array=(t,e)=>qt(t,{...e,array:!0}),Le.exports.MaxBufferError=xo;var ia=Le.exports,Io=be(ia);const{PassThrough:aa}=Mt;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=be(ca);const Mo=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:(Mo(t),jn(e)),da=t=>{const e=ua(t);if(Jt(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:(Mo(t),Tn(e)),fa=(t,e)=>{const r=ma(e);r!==void 0&&(Jt(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},Xt=async(t,e)=>{if(!(!t||e===void 0)){t.destroy();try{return await e}catch(r){return r.bufferedData}}},Qt=(t,{encoding:e,buffer:r,maxBuffer:o})=>{if(!(!t||!r))return e?Io(t,{encoding:e,maxBuffer:o}):Io.buffer(t,{maxBuffer:o})},ha=async({stdout:t,stderr:e,all:r},{encoding:o,buffer:n,maxBuffer:s},i)=>{const l=Qt(t,{encoding:o,buffer:n,maxBuffer:s}),a=Qt(e,{encoding:o,buffer:n,maxBuffer:s}),d=Qt(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},Xt(t,l),Xt(e,a),Xt(r,d)])}},ga=(async()=>{})().constructor.prototype,ya=["then","catch","finally"].map(t=>[t,Reflect.getOwnPropertyDescriptor(ga,t)]),Ro=(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)})}),Do=(t,e=[])=>Array.isArray(e)?[t,...e]:[t],va=/^[\w.-]+$/,Ca=/"/g,ba=t=>typeof t!="string"||va.test(t)?t:`"${t.replace(Ca,'\\"')}"`,Oo=(t,e)=>Do(t,e).join(" "),No=(t,e)=>Do(t,e).map(r=>ba(r)).join(" "),Fo=/ +/g,_o=t=>{const e=[];for(const r of t.trim().split(Fo)){const o=e[e.length-1];o&&o.endsWith("\\")?e[e.length-1]=`${o.slice(0,-1)} ${r}`:e.push(r)}return e},Lo=t=>{const e=typeof t;if(e==="string")return t;if(e==="number")return String(t);if(e==="object"&&t!==null&&!(t instanceof Fr)&&"stdout"in t){const r=typeof t.stdout;if(r==="string")return t.stdout;if(Nr.isBuffer(t.stdout))return t.stdout.toString();throw new TypeError(`Unexpected "${r}" stdout in template expression`)}throw new TypeError(`Unexpected "${e}" in template expression`)},To=(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(Fo).filter(Boolean),l=To(r,i,s.startsWith(" "));if(o===e.length)return l;const a=e[o],d=Array.isArray(a)?a.map(c=>Lo(c)):[Lo(a)];return To(l,d,s.endsWith(" "))},jo=(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,lt=(t,e)=>String(t).padStart(e,"0"),$a=()=>{const t=new Date;return`${lt(t.getHours(),2)}:${lt(t.getMinutes(),2)}:${lt(t.getSeconds(),2)}.${lt(t.getMilliseconds(),3)}`},Bo=(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},Go=(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=Po(r),se.platform==="win32"&&he.basename(t,".exe")==="cmd"&&e.unshift("/q"),{file:t,args:e,options:r,parsed:o}},Te=(t,e,r)=>typeof e!="string"&&!Nr.isBuffer(e)?r===void 0?void 0:"":t.stripFinalNewline?ai(e):e;function S(t,e,r){const o=Go(t,e,r),n=Oo(t,e),s=No(t,e);Bo(s,o.options),Vi(o.options);let i;try{i=It.spawn(o.file,o.args,o.options)}catch(p){const h=new It.ChildProcess,g=Promise.reject(st({error:p,stdout:"",stderr:"",all:"",command:n,escapedCommand:s,parsed:o,timedOut:!1,isCanceled:!1,killed:!1}));return Ro(h,g),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=vo(async()=>{const[{error:p,exitCode:h,signal:g,timedOut:y},v,b,E]=await ha(i,o.options,d),A=Te(o.options,v),P=Te(o.options,b),$=Te(o.options,E);if(p||h!==0||g!==null){const R=st({error:p,exitCode:h,signal:g,stdout:A,stderr:P,all:$,command:n,escapedCommand:s,parsed:o,timedOut:y,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:A,stderr:P,all:$,failed:!1,timedOut:!1,isCanceled:!1,killed:!1}});return fa(i,o.options),i.all=pa(i,o.options),Qi(i),Ro(i,f),i}function Zt(t,e,r){const o=Go(t,e,r),n=Oo(t,e),s=No(t,e);Bo(s,o.options);const i=da(o.options);let l;try{l=It.spawnSync(o.file,o.args,{...o.options,input:i})}catch(c){throw st({error:c,stdout:"",stderr:"",all:"",command:n,escapedCommand:s,parsed:o,timedOut:!1,isCanceled:!1,killed:!1})}const a=Te(o.options,l.stdout,l.error),d=Te(o.options,l.stderr,l.error);if(l.error||l.status!==0||l.signal!==null){const c=st({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"}:{},Ho=(t={})=>({preferLocal:!0,...Sa(t),...t});function Uo(t){function e(r,...o){if(!Array.isArray(r))return Uo({...t,...r});const[n,...s]=jo(r,o);return S(n,s,Ho(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]=jo(r,o);return Zt(n,s,Ho(t))},e}const xa=Uo();function Ia(t,e){const[r,...o]=_o(t);return S(r,o,e)}function Ma(t,e){const[r,...o]=_o(t);return Zt(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 S(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:S,execaSync:Zt,$:xa,execaCommand:Ia,execaCommandSync:Ma,execaNode:Ra});const{hasOwnProperty:er}=Object.prototype,ut=typeof process<"u"&&process.platform==="win32"?`\r
|
|
9
9
|
`:`
|
|
10
|
-
`,
|
|
10
|
+
`,tr=(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+=ke(s+"[]")+n+ke(l)+ut;else i&&typeof i=="object"?r.push(s):o+=ke(s)+n+ke(i)+ut}e.section&&o.length&&(o="["+ke(e.section)+"]"+ut+o);for(const s of r){const i=zo(s).join("\\."),l=(e.section?e.section+".":"")+i,{whitespace:a}=e,d=tr(t[s],{section:l,whitespace:a});o.length&&d.length&&(o+=ut),o+=d}return o},zo=t=>t.replace(/\1/g,"LITERAL\\1LITERAL").replace(/\\\./g,"").split(/\./).map(e=>e.replace(/\1/g,"\\.").replace(/\2LITERAL\\1LITERAL\2/g,"")),Ko=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=dt(a[1]),o==="__proto__"){r=Object.create(null);continue}r=e[o]=e[o]||Object.create(null);continue}const d=dt(a[2]),c=d.length>2&&d.slice(-2)==="[]",u=c?d.slice(0,-2):d;if(u==="__proto__")continue;const f=a[3]?dt(a[4]):!0,p=f==="true"||f==="false"||f==="null"?JSON.parse(f):f;c&&(er.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(!er.call(e,l)||typeof e[l]!="object"||Array.isArray(e[l]))continue;const a=zo(l);r=e;const d=a.pop(),c=d.replace(/\\\./g,".");for(const u of a)u!=="__proto__"&&((!er.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},Wo=t=>t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'"),ke=t=>typeof t!="string"||t.match(/[=\r\n]/)||t.match(/^\[/)||t.length>1&&Wo(t)||t!==t.trim()?JSON.stringify(t):t.split(";").join("\\;").split("#").join("\\#"),dt=(t,e)=>{if(t=(t||"").trim(),Wo(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:Ko,decode:Ko,stringify:tr,encode:tr,safe:ke,unsafe:dt},Se=be(Oa);class w extends Error{}const rr=" ",me=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
|
-
${
|
|
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.
|
|
13
|
+
${rr}${C.dim(`aicommit2 v${to}`)}`),console.error(`
|
|
14
|
+
${rr}Please open a Bug report with the information above:`),console.error(`${rr}https://github.com/tak-bro/aicommit2/issues/new/choose`)))},Yo=t=>F.lstat(t).then(()=>!0,()=>!1),Jo=async t=>{try{await F.mkdir(t,{recursive:!0})}catch(e){if(e.code!=="EEXIST")throw e}},mt=t=>t&&`${t[0].toUpperCase()}${t.slice(1)}`,ft=(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,pt=t=>t.reduce((e,r)=>Array.isArray(r)?e.concat(pt(r)):e.concat(r),[]),Vo=(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"}},qo=t=>{try{return{ok:!0,data:JSON.parse(t)}}catch(e){return{ok:!1,error:e}}},ht=t=>{if(!t||typeof t!="string")return"";if(x.isAbsolute(t))return x.resolve(t);if(Be){const e=x.dirname(Be),r=x.join(e,t);return x.resolve(r)}else return""},ja=["","conventional","gitmoji"],or="http://localhost:11434",{hasOwnProperty:Ba}=Object.prototype,nr=(t,e)=>Ba.call(t,e),sr=["OPENAI","OLLAMA","HUGGINGFACE","GEMINI","ANTHROPIC","MISTRAL","CODESTRAL","COHERE","GROQ","PERPLEXITY","DEEPSEEK","GITHUB_MODELS","BEDROCK"],Xo=t=>{const e=Ne.platform(),r=Ne.homedir();let o,n;switch(t){case"config":o=process.env.XDG_CONFIG_HOME;break;case"data":o=process.env.XDG_DATA_HOME;break;case"cache":o=process.env.XDG_CACHE_HOME;break;case"state":o=process.env.XDG_STATE_HOME;break;default:o=void 0}if(e==="darwin")t==="cache"?n=x.join(r,"Library","Caches"):n=x.join(r,"Library","Application Support");else if(e==="win32")n=process.env.LOCALAPPDATA||r;else switch(t){case"config":n=x.join(r,".config");break;case"data":n=x.join(r,".local","share");break;case"cache":n=x.join(r,".cache");break;case"state":n=x.join(r,".local","state");break;default:n=r}return o||n},Ga=x.join(Xo("config"),"aicommit2"),ie=x.join(Xo("state"),"aicommit2","logs"),Qo=x.join(Ga,"config.ini"),Zo=x.join(ie,"aicommit2-%DATE%.log"),en=x.join(ie,"exceptions-%DATE%.log"),Ha=t=>{const e=Object.keys(t),r=new Set([...sr,...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}`)},de=(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||Zo},exceptionLogFilePath(t){return t||en},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:de("logging",!0),includeBody:de("includeBody"),codeReview:de("codeReview"),disabled:de("disabled"),watchMode:de("watchMode"),forceGit:de("forceGit"),disableLowerCase:de("disableLowerCase"),jjAutoNew:de("jjAutoNew")},je={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):or,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(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?`
|
|
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 Be;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 je?(e[s]||(e[s]={}),e[s][i]=n):e[o]=n}return e},za=()=>{const t=Ne.homedir(),e=process.env.AICOMMIT_CONFIG_PATH,r=Qo,o=x.join(t,".aicommit2");return[e,r,o].filter(n=>!!n)},xe=async()=>{const t=za();for(const e of t)if(await Yo(e))return e;return Qo},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]??""}),Ge=async()=>{const t=await xe();Be=t;try{const e=await F.readFile(t,"utf8"),r=Ka(e);return Se.parse(r)}catch(e){return e.code==="ENOENT"?(Be=void 0,{}):(console.error(`Error reading config file ${t}:`,e),Be=void 0,{})}},ye=async(t,e=[])=>{const r=await Ge(),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=je[d]||gt(d);for(const[u,f]of Object.entries(c)){const p=a(d,u);s[d][u]=f(p)}}return s},ir=async t=>{const e=await Ge();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]={}),sr.includes(i)){const c=je[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=gt(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 xe(),o=x.dirname(r);await F.mkdir(o,{recursive:!0}),await F.writeFile(r,Se.stringify(e),"utf8")},Wa=async t=>{const e=await Ge();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]=pt([...c,...u]);continue}if(a&&a.compatible===!0){a||(e[i]={});const c=gt(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 je){a||(e[i]={});const c=je[i][l];if(!c)throw new w(`Invalid config property: ${n}`);e[i][l]=c(s)}else{const c=gt(i);if(!c[l])throw new w(`Invalid config property: ${n}`);e[i]||(e[i]={}),e[i][l]=c[l](s)}}const r=await xe(),o=x.dirname(r);await F.mkdir(o,{recursive:!0}),await F.writeFile(r,Se.stringify(e),"utf8")},Ya=async()=>{const t=await Ge();console.log(Se.stringify(t))},Ja=async()=>{console.log(await xe())},gt=t=>({compatible:de("compatible"),stream:de("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}),ce=t=>typeof t=="string"&&t.trim().length>0,Ie=t=>(Array.isArray(t.model)?t.model:ce(t.model)?[t.model.trim()]:[]).length>0,ar=t=>{const e=ce(t.key),r=ce(t.region)||ce(process.env.AWS_REGION)||ce(process.env.AWS_DEFAULT_REGION),o=ce(t.profile)||ce(process.env.AWS_PROFILE),n=ce(t.accessKeyId)&&ce(t.secretAccessKey)||ce(process.env.AWS_ACCESS_KEY_ID)&&ce(process.env.AWS_SECRET_ACCESS_KEY);return r&&(e||o||n)},Me=(t,e)=>Object.entries(t).map(([r,o])=>[r,o]).filter(([r,o])=>!o.disabled).filter(([r,o])=>sr.includes(r)||o.compatible===!0).filter(([r,o])=>{switch(e){case"commit":return r==="OLLAMA"?!!o&&Ie(o):r==="HUGGINGFACE"?!!o&&!!o.cookie:r==="BEDROCK"?Ie(o)&&ar(o):!!o.key&&o.key.length>0;case"review":const n=t.codeReview||o.codeReview;return r==="OLLAMA"?!!o&&Ie(o)&&n:r==="HUGGINGFACE"?!!o&&!!o.cookie&&n:r==="BEDROCK"?Ie(o)&&ar(o)&&n:!!o.key&&o.key.length>0&&n;case"watch":const s=t.watchMode||o.watchMode;return r==="OLLAMA"?!!o&&Ie(o)&&s:r==="HUGGINGFACE"?!!o&&!!o.cookie&&s:r==="BEDROCK"?Ie(o)&&ar(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 He=new Map,we=(t,e,r)=>{const o=Wr(0).update(e).digest("hex").substring(0,8),n=`${t}_${o}_${r}`;if(He.has(n))return He.get(n);const s=new Date,i=Xa(s,t,e,r),l=`${ie}/${i}`,a=U.createLogger({level:"info",format:U.format.combine(U.format.timestamp({format:"YYYY-MM-DDTHH:mm:ss.SSSZ"}),U.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 U.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(""),He.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=we(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;we(r,t,e).info("Request payload:",o)},Z=(t,e,r,o,n,s=!0)=>{if(!s)return;const i=we(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;we(r,t,e).info("Response received:",o)},j=(t,e,r,o,n=!0)=>{if(!n)return;we(r,t,e).error("API request failed:",o)},Y=(t,e,r,o,n,s=!0)=>{if(!s)return;const i=we(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=we(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=Wr(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}},cr=()=>{for(const[t,e]of He.entries())try{e.close()}catch(r){console.error(`Failed to close logger ${t}:`,r)}He.clear()};process.on("exit",cr),process.on("SIGINT",()=>{cr(),process.exit(0)}),process.on("SIGTERM",()=>{cr(),process.exit(0)});let yt,tn="info";async function Za(t){if(yt){console.warn("Logger already initialized. Skipping re-initialization.");return}const e=t?.logLevel||"info";tn=e;const r=t?.logFilePath||Zo,o=t?.exceptionLogFilePath||en,n=t?.logging??!0;await Jo(x.dirname(r)),await Jo(x.dirname(o));const s=[];n?s.push(new U.transports.DailyRotateFile({filename:r,datePattern:"YYYY-MM-DD",zippedArchive:!0,maxSize:"20m",maxFiles:"14d",level:e,format:U.format.combine(U.format.timestamp(),U.format.printf(({level:i,message:l,timestamp:a})=>`[${a}] ${i}: ${l}`))})):s.push(new U.transports.Console({silent:!0})),yt=U.createLogger({level:e,format:U.format.json(),transports:s,exceptionHandlers:n?[new U.transports.DailyRotateFile({filename:o,datePattern:"YYYY-MM-DD",zippedArchive:!0,maxSize:"20m",maxFiles:"14d",format:U.format.combine(U.format.timestamp(),U.format.json())})]:[],exitOnError:!1,silent:!n})}const Re=new Proxy({},{get:(t,e,r)=>{if(!yt)throw new Error("Logger not initialized. Call initializeLogger() first.");return Reflect.get(yt,e,r)}});function wt(){const t=U.config.npm.levels;return(t[tn]??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 Re.error(`${this.errorPrefix} ${n}`),r.stack&&Re.error(` ${r.stack}`),r.content&&Re.error(` Problematic content: ${r.content}`),r.originalError&&Re.error(` Original error: ${r.originalError}`),Rt({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=qo(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(", ");Re.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:`${Vo(e)}...`,value:e}]}catch{return[]}return e.map(r=>{try{return{title:`${Vo(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
|
|
|
@@ -32,9 +32,9 @@ ${u.footer}`:""}`})).slice(0,o);if(this.isLoggingEnabled()){const u=c.map(f=>f.t
|
|
|
32
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
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
|
-
`)}`},
|
|
35
|
+
`)}`},lr=(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},rn=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
|
-
`)},
|
|
37
|
+
`)},vt=(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}",
|
|
@@ -43,11 +43,11 @@ ${Object.entries({docs:"Documentation only changes",style:"Changes that do not a
|
|
|
43
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
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=t=>{const{systemPrompt:e,systemPromptPath:r,type:o,generate:n,locale:s}=t;if(e)return`${
|
|
47
|
-
${
|
|
48
|
-
${
|
|
49
|
-
${
|
|
50
|
-
${
|
|
46
|
+
`)},te=t=>{const{systemPrompt:e,systemPromptPath:r,type:o,generate:n,locale:s}=t;if(e)return`${lr(e,t)}
|
|
47
|
+
${vt(o,n,s)}`;if(!r)return`${rn(t)}
|
|
48
|
+
${vt(o,n,s)}`;try{const i=q.readFileSync(ht(r),"utf-8");return`${lr(i,t)}
|
|
49
|
+
${vt(o,n,s)}`}catch{return`${rn(t)}
|
|
50
|
+
${vt(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
52
|
1. Language: ${r}
|
|
53
53
|
2. Code quality and best practices
|
|
@@ -55,7 +55,7 @@ ${wt(o,n,s)}`}},re=t=>{const{codeReviewPromptPath:e,locale:r}=t,o=`I'll give you
|
|
|
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(ht(e),"utf-8");return`${lr(n,t)}`}catch{return o}},on=async t=>{if(t.systemPromptPath)try{q.readFileSync(ht(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(ht(t.codeReviewPromptPath),"utf-8")}catch(e){throw new w(`Error reading code review prompt file: ${t.codeReviewPromptPath}, ${e}`)}},ve=(t,e="commit")=>e==="review"?`Please analyze the following diff and provide a comprehensive code review:
|
|
59
59
|
|
|
60
60
|
\`\`\`diff
|
|
61
61
|
${t}
|
|
@@ -67,97 +67,97 @@ Focus on code quality, potential issues, and improvement suggestions.`:`Please a
|
|
|
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 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(`
|
|
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,g={...J,locale:a,maxLength:u,type:c,generate:d,systemPrompt:o,systemPromptPath:n,codeReviewPromptPath:s,vcs_branch:this.params.branchName||""},y=e==="review"?re(g):te(g),v=ve(r,e),E=`${this.params.config.url||"https://api.anthropic.com"}/v1/messages`,A={"Content-Type":"application/json","x-api-key":this.params.config.key,"anthropic-version":"2023-06-01"};Q(r,e,"Anthropic",h,E,A,i),Z(r,e,"Anthropic",y,v,i);const P=tc(h),$={max_tokens:f,temperature:l,system:y,messages:[{role:"user",content:v}],model:h,...P?{}:{top_p:p}};oe(r,e,"Anthropic",$,i);const R=Date.now();try{const k=await this.anthropic.messages.create($),G=Date.now()-R;W(r,e,"Anthropic",k,i);const I=k.content.map(({text:pe})=>pe).join("");return Y(r,e,"Anthropic",G,I,i),e==="review"?this.sanitizeResponse(I):this.parseMessage(I,c,d)}catch(k){throw j(r,e,"Anthropic",k,i),k}}}const ne="Bedrock",fe={MISSING_DEPENDENCY:"MissingDependencyError",MISSING_REGION:"MissingRegionError",MISSING_MODEL_ID:"MissingModelIdError",MISSING_API_KEY:"MissingApiKeyError",MISSING_APPLICATION_KEY:"MissingApplicationKeyError",INVALID_RESPONSE:"InvalidResponseError",EMPTY_RESPONSE:"EmptyResponseError"},K=t=>typeof t=="string"&&t.length>0;let Ue=null,ze=null;const nn=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=fe.MISSING_DEPENDENCY,e.originalError=t,e},ac=async()=>{if(Ue)return Ue;try{return Ue=await import("@aws-sdk/client-bedrock-runtime"),Ue}catch(t){throw Ue=null,nn(t)}},sn=async()=>{if(ze)return ze;try{return ze=await import("@aws-sdk/credential-providers"),ze}catch(t){throw ze=null,nn(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(!K(e.model)){const n=new Error("Model ID or inference profile ARN is required.");throw n.name=fe.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=fe.MISSING_REGION,n}const r=K(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=fe.MISSING_API_KEY,n}if(r&&!o&&!this.getRegion()&&!K(e.applicationBaseUrl)){const n=new Error("Bearer token authentication requires region or applicationBaseUrl to construct endpoint.");throw n.name=fe.MISSING_REGION,n}}canUseAwsSdk(){const e=this.bedrockConfig,r=K(e.profile)||K(process.env.AWS_PROFILE),o=K(e.accessKeyId)&&K(e.secretAccessKey)||K(process.env.AWS_ACCESS_KEY_ID)&&K(process.env.AWS_SECRET_ACCESS_KEY);return r||o}determineAuthMethod(){const e=K(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=ve(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();wt()&&(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: ${K(o.key)}`)));const g=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}),y=Date.now()-p;return Y(r,e,ne,y,g,s),e==="review"?this.sanitizeResponse(g):this.parseMessage(g,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 g=new c(p),y=new u({modelId:o,messages:[{role:"user",content:[{text:s}]}],...n?{system:[{text:n}]}:{},...i&&Object.keys(i).length>0&&{inferenceConfig:i}});wt()&&console.log(C.cyan(`[Bedrock] Sending ConverseCommand with modelId: ${o}`));let v;try{v=await g.send(y),W(d,a,ne,v,l)}catch(E){throw wt()&&(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=fe.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 g=JSON.stringify(h),y={"Content-Type":"application/json","Content-Length":Buffer.byteLength(g).toString()};return K(d.key)&&(y.Authorization=`Bearer ${d.key}`),K(d.applicationInferenceProfileArn)&&(y["x-amzn-bedrock-inference-profile-arn"]=d.applicationInferenceProfileArn),K(d.applicationEndpointId)&&(y["x-amzn-bedrock-endpoint-id"]=d.applicationEndpointId),new Promise((v,b)=>{const E=Yr.request({method:"POST",protocol:p.protocol,hostname:p.hostname,port:p.port,path:p.pathname+p.search,headers:y,timeout:d.timeout},A=>{const P=[];A.on("data",$=>P.push($)),A.on("end",()=>{const $=Buffer.concat(P).toString("utf8");if(A.statusCode&&A.statusCode>=400){const I=new Error(`Bedrock application endpoint responded with status ${A.statusCode}.`);return I.status=A.statusCode,I.content=$,j(a,l,ne,I,i),b(I)}const R=qo($);if(!R.ok){const I=new Error("Failed to parse Bedrock application response as JSON. The Bedrock Converse API should always return valid JSON.");return I.name=fe.INVALID_RESPONSE,I.content=$,j(a,l,ne,I,i),b(I)}const k=R.data;W(a,l,ne,k,i);const G=k.output?.message?.content?.[0]?.text||"";if(!G){const I=new Error("No text content found in Bedrock response.");return I.name=fe.EMPTY_RESPONSE,I.content=k,j(a,l,ne,I,i),b(I)}v(G)})});E.on("error",A=>{const P=A;j(a,l,ne,P,i),b(P)}),E.write(g),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(K(o)){const{fromIni:a}=await sn();l=a({profile:o})}else if(K(n)&&K(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 sn();l=a({profile:process.env.AWS_PROFILE})}return l&&(this.credentialCache=l,this.credentialCacheTimestamp=e),l}}class Ke{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=ve(r,e),g=`${this.params.config.url||"https://codestral.mistral.ai"}/v1/chat/completions`,y={Authorization:`Bearer ${this.apiKey}`,"content-type":"application/json"};Q(r,e,"Codestral",this.params.config.model,g,y,i),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:ve(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:ft(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 Ke({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),g=`Here is the diff: ${r}`,y=[...h?[{role:"system",content:h}]:[],{role:"user",content:g}],b=`${this.params.config.url}/v2/chat`;Q(r,e,"Cohere",this.params.config.model,b,{},i),Z(r,e,"Cohere",h,g,i);const E={model:this.params.config.model,messages:y,max_tokens:f,temperature:l,seed:ft(10,1e3),p:this.params.config.topP};oe(r,e,"Cohere",E,i);const A=Date.now();try{const P=await this.cohere.chat(E,{timeoutInSeconds:Math.floor(this.params.config.timeout/1e3)}),$=Date.now()-A;if(!this.isValidCohereV2Response(P))throw new Error("Invalid response structure from Cohere v2 API");const R=P.message.content[0].text;return W(r,e,"Cohere",P,i),Y(r,e,"Cohere",$,R,i),e==="review"?this.sanitizeResponse(R):this.parseMessage(R,c,d)}catch(P){throw j(r,e,"Cohere",P,i),P}}}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 Jr({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=ve(r,e),g=`${this.params.config.url||"https://api.deepseek.com"}/chat/completions`,y={Authorization:`Bearer ${this.params.config.key}`,"Content-Type":"application/json"};Q(r,e,"DeepSeek",this.params.config.model,g,y,i),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},g=this.genAI.getGenerativeModel({model:this.params.config.model,systemInstruction:p,generationConfig:h,safetySettings:[{category:et.HARM_CATEGORY_HATE_SPEECH,threshold:tt.BLOCK_LOW_AND_ABOVE},{category:et.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:tt.BLOCK_LOW_AND_ABOVE},{category:et.HARM_CATEGORY_HARASSMENT,threshold:tt.BLOCK_LOW_AND_ABOVE},{category:et.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:tt.BLOCK_LOW_AND_ABOVE}]}),y=ve(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,y,s),oe(r,e,"Gemini",{systemInstruction:{parts:[{text:p}]},contents:[{parts:[{text:y}]}],generationConfig:h},s);const P=Date.now();try{const $=this.params.config.timeout>1e4?{request:{timeout:this.params.config.timeout}}:void 0,R=await g.generateContent(y,$),k=R.response;if(k.candidates?.[0]?.finishReason==="MAX_TOKENS"){const B=k.usageMetadata;throw new Error(`Response truncated: maxOutputTokens exceeded. Thinking tokens: ${B?.thoughtsTokenCount??"N/A"}, Output tokens: ${B?.candidatesTokenCount??"N/A"}. Increase maxTokens config for Gemini 2.5+ thinking models.`)}const I=k.text(),pe=Date.now()-P;return W(r,e,"Gemini",{response:I,candidates:R.response.candidates,usageMetadata:R.response.usageMetadata},s),Y(r,e,"Gemini",pe,I,s),e==="review"?this.sanitizeResponse(I):this.parseMessage(I,d,a)}catch($){throw j(r,e,"Gemini",$,s),$}}}var ur={},dr={exports:{}},We={exports:{}},mr,an;function fc(){if(an)return mr;an=1;var t=1e3,e=t*60,r=e*60,o=r*24,n=o*7,s=o*365.25;mr=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 mr}var fr,cn;function ln(){if(cn)return fr;cn=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,g;function y(...v){if(!y.enabled)return;const b=y,E=Number(new Date),A=E-(f||E);b.diff=A,b.prev=f,b.curr=E,f=E,v[0]=o.coerce(v[0]),typeof v[0]!="string"&&v.unshift("%O");let P=0;v[0]=v[0].replace(/%([a-zA-Z%])/g,(R,k)=>{if(R==="%%")return"%";P++;const G=o.formatters[k];if(typeof G=="function"){const I=v[P];R=G.call(b,I),v.splice(P,1),P--}return R}),o.formatArgs.call(b,v),(b.log||o.log).apply(b,v)}return y.namespace=u,y.useColors=o.useColors(),y.color=o.selectColor(u),y.extend=n,y.destroy=o.destroy,Object.defineProperty(y,"enabled",{enumerable:!0,configurable:!1,get:()=>p!==null?p:(h!==o.namespaces&&(h=o.namespaces,g=o.enabled(u)),g),set:v=>{p=v}}),typeof o.init=="function"&&o.init(y),y}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,g=-1,y=0;for(;p<u.length;)if(h<f.length&&(f[h]===u[p]||f[h]==="*"))f[h]==="*"?(g=h,y=p,h++):(p++,h++);else if(g!==-1)h=g+1,y++,p=y;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 fr=t,fr}We.exports;var un;function pc(){return un||(un=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=ln()(e);const{formatters:l}=t.exports;l.j=function(a){try{return JSON.stringify(a)}catch(d){return"[UnexpectedJSONParseError]: "+d.message}}}(We,We.exports)),We.exports}var Ye={exports:{}},pr,dn;function hc(){return dn||(dn=1,pr=(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)}),pr}var hr,mn;function gc(){if(mn)return hr;mn=1;const t=Ne,e=Vr,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 hr={supportsColor:l,stdout:s(i(!0,e.isatty(1))),stderr:s(i(!0,e.isatty(2)))},hr}Ye.exports;var fn;function yc(){return fn||(fn=1,function(t,e){const r=Vr,o=Br;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,(y,v)=>v.toUpperCase());let g=process.env[p];return/^(yes|on|true|enabled)$/i.test(g)?g=!0:/^(no|off|false|disabled)$/i.test(g)?g=!1:g==="null"?g=null:g=Number(g),f[h]=g,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 g=this.color,y="\x1B[3"+(g<8?g:"8;5;"+g),v=` ${y};1m${p} \x1B[0m`;f[0]=v+f[0].split(`
|
|
71
71
|
`).join(`
|
|
72
|
-
`+v),f.push(
|
|
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=
|
|
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
|
|
72
|
+
`+v),f.push(y+"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=ln()(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)}}(Ye,Ye.exports)),Ye.exports}typeof process>"u"||process.type==="renderer"||process.browser===!0||process.__nwjs?dr.exports=pc():dr.exports=yc();var gr=dr.exports,yr={};Object.defineProperty(yr,"__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)})})}}yr.default=wc;var pn=H&&H.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};const vc=jr,Cc=pn(gr),bc=pn(yr),Je=Cc.default("agent-base");function Ec(t){return!!t&&typeof t.addRequest=="function"}function wr(){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 Ct(t,e){return new Ct.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:wr()?443:80}set defaultPort(o){this.explicitDefaultPort=o}get protocol(){return typeof this.explicitProtocol=="string"?this.explicitProtocol:wr()?"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=wr()),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)){Je("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?(Je("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{Je("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){Je("Freeing socket %o %o",o.constructor.name,n),o.destroy()}destroy(){Je("Destroying agent %o",this.constructor.name)}}t.Agent=e,t.prototype=t.Agent.prototype})(Ct||(Ct={}));var Pc=Ct,vr={},$c=H&&H.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(vr,"__esModule",{value:!0});const Ac=$c(gr),Ve=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){Ve("onclose had error %o",u)}function a(){Ve("onend")}function d(u){i(),Ve("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
|
-
`)),
|
|
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
|
|
77
|
+
`)===-1){Ve("have not received end of HTTP headers yet..."),s();return}const h=f.toString("ascii",0,f.indexOf(`\r
|
|
78
|
+
`)),g=+h.split(" ")[1];Ve("got proxy server response: %o",h),e({statusCode:g,buffered:f})}t.on("error",d),t.on("close",l),t.on("end",a),s()})}vr.default=kc;var Sc=H&&H.__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())})},De=H&&H.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(ur,"__esModule",{value:!0});const hn=De(qn),gn=De(Xn),xc=De(Qn),Ic=De(Tr),Mc=De(gr),Rc=Pc,Dc=De(vr),qe=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!");qe("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?(qe("Creating `tls.Socket`: %o",o),s=gn.default.connect(o)):(qe("Creating `net.Socket`: %o",o),s=hn.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 y of Object.keys(i))a+=`${y}: ${i[y]}\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),r.secureEndpoint){
|
|
81
|
+
`);const{statusCode:p,buffered:h}=yield f;if(p===200){if(e.once("socket",Nc),r.secureEndpoint){qe("Upgrading socket connection to TLS");const y=r.servername||r.host;return gn.default.connect(Object.assign(Object.assign({},Lc(r,"host","hostname","path","port")),{socket:s,servername:y}))}return s}s.destroy();const g=new hn.default.Socket({writable:!1});return g.readable=!0,e.once("socket",y=>{qe("replaying proxy buffer for failed request"),Ic.default(y.listenerCount("data")>0),y.push(h),y.push(null)}),g})}}ur.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=H&&H.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};const Cr=Tc(ur);function br(t){return new Cr.default(t)}(function(t){t.HttpsProxyAgent=Cr.default,t.prototype=Cr.default.prototype})(br||(br={}));var jc=br,Bc=be(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")?Yr: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: ${t}`),new w(d)}return JSON.parse(a)},
|
|
85
|
+
Check the API status: ${t}`),new w(d)}return JSON.parse(a)},yn=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"],Er=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=ve(s,f),g=Er(n),y={model:n,messages:[{role:"system",content:c},{role:"user",content:h}],stream:!1,n:1,frequency_penalty:0,presence_penalty:0,...g?{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,y,u);const A=Date.now(),P=await Hc(e,r,o,y,i,p),$=Date.now()-A;W(s,f,t,P,u);const R=P.choices.filter(k=>k.message?.content).map(k=>yn(k.message.content)).join();return Y(s,f,t,$,R,u),P.choices.filter(k=>k.message?.content).map(k=>yn(k.message.content))}catch(h){j(s,f,t,h,u);const g=h;throw g.code==="ENOTFOUND"?new w(`Error connecting to ${g.hostname} (${g.syscall})`):g}};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
|
-
${r}`}],i=
|
|
87
|
+
${r}`}],i=Er(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
|
-
${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!
|
|
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 A=`GitHub API request failed: ${h.status} ${h.statusText}`;try{const $=JSON.parse(b);$.error?.message?A+=` - ${$.error.message}`:$.message&&(A+=` - ${$.message}`)}catch{b&&(A+=` - ${b}`)}if(h.status===401){const $=new Error("GitHub authentication failed. Please run: aicommit2 github-login");throw $.status=h.status,$.code="AUTHENTICATION_FAILED",$.content=b,$}else if(h.status===403){const $=new Error('GitHub Models access denied. Make sure your token has "Models" permission.');throw $.status=h.status,$.code="ACCESS_DENIED",$.content=b,$}else if(h.status===404){const $=new Error(`Model "${n}" not found. Please check the model name.`);throw $.status=h.status,$.code="MODEL_NOT_FOUND",$.content=b,$}else if(h.status===429){const $=new Error("Rate limit exceeded. Please try again later.");throw $.status=h.status,$.code="RATE_LIMIT_EXCEEDED",$.content=b,$}const P=new Error(A);throw P.status=h.status,P.code="API_ERROR",P.content=b,P}const g=await h.json(),y=Date.now()-p;W(r,o,"GitHub Models",g,c);const v=g.choices?.[0]?.message?.content?.trim();if(!v){j(r,o,"GitHub Models",{message:"No content found in GitHub Models response",result:g},c);const E=new Error("No response content received from GitHub Models");throw E.code="NO_CONTENT",E.content=JSON.stringify(g,null,2),E}return Y(r,o,"GitHub Models",y,v,c),v}catch(p){if(clearTimeout(f),p instanceof Error&&p.name==="AbortError"){const y={message:`GitHub Models request timeout after ${this.params.config.timeout}ms`,error:p};j(r,o,"GitHub Models",y,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 g=new Error(`GitHub Models request failed: ${p instanceof Error?p.message:String(p)}`);throw g.code="REQUEST_FAILED",g.originalError=p,g}}}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),g=`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,g,i);const E={messages:[{role:"system",content:h},{role:"user",content:g}],model:this.params.config.model,max_tokens:f,top_p:this.params.config.topP,temperature:a};oe(r,e,"Groq",E,i);const A=Date.now();try{const P=await this.groq.chat.completions.create(E,{timeout:this.params.config.timeout}),$=Date.now()-A,R=P.choices[0].message.content||"";return W(r,e,"Groq",P,i),Y(r,e,"Groq",$,R,i),e==="review"?this.sanitizeResponse(R):this.parseMessage(R,c,d)}catch(P){throw j(r,e,"Groq",P,i),P}}}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,g={...J,locale:l,maxLength:c,type:d,generate:a,systemPrompt:o,systemPromptPath:n,codeReviewPromptPath:s,vcs_branch:this.params.branchName||""},y=e==="review"?re(g):te(g),v=`Here is the diff: ${r}`,E=`${this.params.config.url||"https://huggingface.co"}/chat/conversation`,A={...this.headers,cookie:this.cookie};Q(r,e,"HuggingFace",this.params.config.model,E,A,i),Z(r,e,"HuggingFace",y,v,i);const P=Date.now();try{const $=await this.getNewChat(y),k=await(await this.sendMessage(v,$.id)).completeResponsePromise();await this.deleteConversation($.id);const G=Date.now()-P;return W(r,e,"HuggingFace",{response:k},i),Y(r,e,"HuggingFace",G,k,i),e==="review"?this.sanitizeResponse(k):this.parseMessage(k,d,a)}catch($){throw j(r,e,"HuggingFace",$,i),$}}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(g=>l(g));c.promptExamples=h.map(g=>({title:n[g.title],prompt:n[g.prompt]}))}const f=l(d.parameters),p={};for(const[h,g]of Object.entries(f)){if(g===-1){p[h]=null;continue}if(Array.isArray(n[g])){p[h]=n[g].map(y=>n[y]);continue}p[h]=n[g]}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(g){try{const y=g.split(`
|
|
90
|
+
`),v=[];for(const b of y)b.trim()&&v.push(JSON.parse(b));return v}catch{return[{}]}}const c=new TextDecoder;let u="";const f=new TransformStream({async transform(g,y){const v=c.decode(g);try{const b=d(v);for(const E of b)E.type==="finalAnswer"?(u=E?.text||"",y.terminate()):E.type==="stream"&&y.enqueue(E?.token||"")}catch{throw new Error("Error during parsing response")}}}),p=a.body?.pipeThrough(f);async function h(){return new Promise(async(g,y)=>{try{if(!p)y("ModifiedStream undefined");else{const v=p.getReader();for(;;){const{done:b,value:E}=await v.read();if(b){g(u);break}}}}catch(v){y(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}`,g=`${this.params.config.url||"https://api.mistral.ai"}/v1/chat/completions`,y={Authorization:`Bearer ${this.apiKey}`,"content-type":"application/json"};Q(r,e,"MistralAI",this.params.config.model,g,y,i),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 Ke({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:ft(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 Ke({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=or,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(`[${mt(this.model)}]`),this.errorPrefix=C.red.bold(`[${mt(this.model)}]`),this.host=this.params.config.host||or,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}`,g=`${this.host}/api/chat`,y=this.key?{Authorization:`${this.auth} ${this.key}`}:{};Q(r,e,h,this.model,g,y,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 Ke({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:ft(10,1e3),num_predict:d??-1}};oe(f,o,p,h,c);const g=Date.now();try{const y=await this.ollama.chat(h),v=Date.now()-g;let b="";if(u){if(y)for await(const E of y)b+=E.message.content}else b=y.message.content;return W(f,o,p,{response:b,fullResponse:y},c),Y(f,o,p,v,b,c),b}catch(y){throw j(f,o,p,y,c),y}}}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(`[${mt(r)}]`),this.errorPrefix=C.red.bold(`[${mt(r)}]`),this.openAI=new Jr({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,g={...J,locale:l,maxLength:u,type:c,generate:d,systemPrompt:o,systemPromptPath:n,codeReviewPromptPath:s,vcs_branch:this.params.branchName||""},y=e==="review"?re(g):te(g),v=`Here is the diff: ${r}`,b=this.params.keyName||"OpenAI-Compatible",E=`${this.params.config.url}${this.params.config.path}`,A={Authorization:`Bearer ${this.params.config.key}`,"Content-Type":"application/json"};Q(r,e,b,this.params.config.model,E,A,i),Z(r,e,b,y,v,i);const P=Er(this.params.config.model),$={messages:[{role:"system",content:y},{role:"user",content:v}],model:this.params.config.model,stream:p,...P?{max_completion_tokens:h,temperature:1}:{max_tokens:h,top_p:this.params.config.topP,temperature:a}};oe(r,e,b,$,i);const R=Date.now();try{const k=await this.openAI.chat.completions.create($,{timeout:f});let G="";if(p&&k){const pe=k;for await(const B of pe){const ae=B.choices?.[0]?.delta?.content||"",xn=B.choices?.[0]?.delta?.reasoning_content||"",In=`${ae}${xn}`;G+=In}}else G=k.choices?.[0]?.message.content||"";const I=Date.now()-R;return W(r,e,b,k,i),Y(r,e,b,I,G,i),e==="review"?this.sanitizeResponse(G):this.parseMessage(G,c,d)}catch(k){throw j(r,e,b,k,i),k}}}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,g={...J,locale:a,maxLength:u,type:c,generate:d,systemPrompt:o,systemPromptPath:n,codeReviewPromptPath:s,vcs_branch:this.params.branchName||""},y=e==="review"?re(g):te(g),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,y,l,e,f);return pt(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}`,g=`${this.params.config.url||"https://api.perplexity.ai"}/chat/completions`,y={Authorization:`Bearer ${this.apiKey}`,"content-type":"application/json"};Q(r,e,"Perplexity",this.params.config.model,g,y,i),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 Ke({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 bt{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(Gr(o=>{const n=this.config[o],s=Array.isArray(n.model)?n.model:[n.model];return D(s).pipe(Gr(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 Rt({name:l+" Invalid AI type",value:"Invalid AI type",isError:!0,disabled:!0})}}))}),N(o=>{const n=C.red.bold("[UNKNOWN]");return Rt({name:n+` ${o.message||""}`,value:"Unknown error",isError:!0,disabled:!0})}))}}class Pr{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 Et extends Pr{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 S("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
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
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: ${r.message||"Unknown error"}`)}}async getStagedDiff(e,r){const o=["diff","--cached","--diff-algorithm=minimal"],{stdout:n}=await
|
|
98
|
-
`).filter(Boolean),{stdout:l}=await
|
|
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 S("git",[...o,"--name-only",...this.filesToExclude,...e?e.map(this.excludeFromDiff):[],...r?r.map(this.excludeFromDiff):[]]);if(!n)return null;const{stdout:s}=await S("git",[...o,...this.filesToExclude,...e?e.map(this.excludeFromDiff):[],...r?r.map(this.excludeFromDiff):[]]),i=n.split(`
|
|
98
|
+
`).filter(Boolean),{stdout:l}=await S("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
|
-
`;for(const f of a){const{stdout:p}=await
|
|
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
|
|
102
|
+
`;for(const f of a){const{stdout:p}=await S("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,r,o){const n=["diff-tree","-r","--no-commit-id","--name-only",e],{stdout:s}=await S("git",[...n,...this.filesToExclude,...r?r.map(this.excludeFromDiff):[],...o?o.map(this.excludeFromDiff):[]]);if(!s)return null;const{stdout:i}=await S("git",["show",e,"--",...this.filesToExclude,...r?r.map(this.excludeFromDiff):[],...o?o.map(this.excludeFromDiff):[]]),{stdout:l}=await S("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,r=[]){try{await
|
|
109
|
+
`).filter(Boolean),...a])];return{files:u,diff:c||`Files changed: ${u.join(", ")}`}}async commit(e,r=[],o={}){try{await S("git",["commit","-m",e,...r],{stdio:"inherit"})}catch(n){const s=n;throw s.stderr?s.stderr.includes("nothing to commit")?new w(`Nothing to commit.
|
|
110
110
|
|
|
111
111
|
Stage your changes with: git add <files>
|
|
112
|
-
Or use the --all flag to stage all changes.`):
|
|
112
|
+
Or use the --all flag to stage all changes.`):s.stderr.includes("Please enter the commit message")?new w(`Commit message cannot be empty.
|
|
113
113
|
|
|
114
|
-
Provide a meaningful commit message.`):
|
|
114
|
+
Provide a meaningful commit message.`):s.stderr.includes("Author identity unknown")?new w(`Git author identity not configured.
|
|
115
115
|
|
|
116
116
|
Configure with:
|
|
117
117
|
git config --global user.name "Your Name"
|
|
118
|
-
git config --global user.email "your.email@example.com"`):
|
|
118
|
+
git config --global user.email "your.email@example.com"`):s.stderr.includes("Permission denied")?new w(`Git permission error: ${s.stderr.trim()}
|
|
119
119
|
|
|
120
|
-
Check repository permissions and file access.`):new w(`Git commit failed: ${
|
|
120
|
+
Check repository permissions and file access.`):new w(`Git commit failed: ${s.stderr.trim()}`):s.exitCode===1?new w("Git commit failed. Check your staged changes and try again."):new w(`Failed to commit with Git: ${s.message||"Unknown error"}`)}}async getCommentChar(){try{const{stdout:e}=await S("git",["config","--get","core.commentChar"]);return e}catch{return"#"}}async getBranchName(){try{const{stdout:e}=await S("git",["branch","--show-current"]),r=e.trim();if(!r){const{stdout:o}=await S("git",["rev-parse","--short","HEAD"]);return`HEAD@${o.trim()}`}return r}catch{return"HEAD"}}}class $r extends Pr{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 S("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: ${r.message}`)}try{const{stdout:e,stderr:r}=await
|
|
126
|
+
- See: https://github.com/martinvonz/jj#installation`):new w(`Failed to execute jj command: ${r.message}`)}try{const{stdout:e,stderr:r}=await S("jj",["workspace","root"],{reject:!0}),o=e.trim();if(!o)throw new w("jj workspace root returned empty path");const n=x.join(o,".jj");if(!q.existsSync(n))throw new w(`Jujutsu repository directory not found at ${n}
|
|
127
127
|
|
|
128
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
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: ${r.stderr.trim()}`):new w(`Failed to verify Jujutsu repository: ${r.message||"Unknown error"}`)}}async getStagedDiff(e,r){try{const{stdout:o}=await
|
|
134
|
-
`).filter(Boolean),h=[],
|
|
135
|
-
`);for(const b of
|
|
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 S("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 S("jj",a);if(process.env.DEBUG&&console.log("jj diff --name-only output:",JSON.stringify(c)),!c.trim())return null;const{stdout:u}=await S("jj",d),{stdout:f}=await S("jj",["status","--no-pager"]),p=c.split(`
|
|
134
|
+
`).filter(Boolean),h=[],g=f.split(`
|
|
135
|
+
`);for(const b of g)if(b.includes("(binary)")||b.includes("Binary file")){const E=b.match(/([^\s]+)\s*\(binary\)/);E&&E[1]&&h.push(E[1])}let y=u;if(h.length>0){y+=`
|
|
136
136
|
|
|
137
137
|
--- Binary Files Changed ---
|
|
138
|
-
`;for(const b of h)
|
|
139
|
-
`}const v=[...new Set([...p,...h])];return{files:v,diff:
|
|
138
|
+
`;for(const b of h)y+=`Binary file ${b} changed
|
|
139
|
+
`}const v=[...new Set([...p,...h])];return{files:v,diff:y||`Files changed: ${v.join(", ")}`}}catch(o){const n=o;if(n.stderr){if(n.stderr.includes("No changes to show"))return null;if(n.stderr.includes("Operation not allowed"))throw new w(`Jujutsu diff failed: ${n.stderr.trim()}
|
|
140
140
|
|
|
141
141
|
Try: jj status --no-pager`);if(n.stderr.includes("Invalid revision"))throw new w(`Jujutsu revision error: ${n.stderr.trim()}
|
|
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,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
|
|
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
|
|
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 S("jj",s);if(!l.trim())return null;const{stdout:a}=await S("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=[],o={}){try{await S("jj",["describe","-m",e,...r],{stdio:"inherit"}),o.autoNew&&await S("jj",["new"],{stdio:"inherit"})}catch(n){const s=n;throw s.stderr?s.stderr.includes("Empty commit message")?new w(`Commit message cannot be empty.
|
|
147
147
|
|
|
148
|
-
Provide a meaningful commit message.`):
|
|
148
|
+
Provide a meaningful commit message.`):s.stderr.includes("No changes to commit")?new w(`No changes to commit.
|
|
149
149
|
|
|
150
|
-
Make some changes first, then try again.`):
|
|
150
|
+
Make some changes first, then try again.`):s.stderr.includes("Invalid revision")?new w(`Jujutsu commit error: ${s.stderr.trim()}
|
|
151
151
|
|
|
152
|
-
Ensure you're in a valid workspace with changes.`):
|
|
152
|
+
Ensure you're in a valid workspace with changes.`):s.stderr.includes("Operation not allowed")?new w(`Jujutsu operation not allowed: ${s.stderr.trim()}
|
|
153
153
|
|
|
154
|
-
Check repository state with: jj status`):new w(`Jujutsu describe failed: ${
|
|
155
|
-
`)[0].split(":")[0].trim();if(n)return n}const{stdout:r}=await
|
|
154
|
+
Check repository state with: jj status`):new w(`Jujutsu describe failed: ${s.stderr.trim()}`):s.exitCode===1?new w("Jujutsu commit failed. Check your changes and repository state."):new w(`Failed to commit with Jujutsu: ${s.message||"Unknown error"}`)}}async getCommentChar(){try{const{stdout:e}=await S("jj",["config","get","ui.comment-char"]);return e.trim()||"#"}catch{return"#"}}async getBranchName(){try{const{stdout:e}=await S("jj",["bookmark","list","--revisions","@"]);if(e.trim()){const n=e.split(`
|
|
155
|
+
`)[0].split(":")[0].trim();if(n)return n}const{stdout:r}=await S("jj",["log","-r","@","--no-graph","-T","change_id.short()"]);return r.trim()||"HEAD"}catch{return"HEAD"}}}class Ar extends Pr{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 S("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}
|
|
159
159
|
|
|
160
|
-
This appears to be a regular Git repository.`);const{stdout:l}=await
|
|
160
|
+
This appears to be a regular Git repository.`);const{stdout:l}=await S("yadm",["rev-parse","--git-dir"],{reject:!0}),a=l.trim();if(!a.includes("yadm"))throw new w(`Not a YADM repository (git-dir does not contain "yadm").
|
|
161
161
|
|
|
162
162
|
Git directory: ${a}
|
|
163
163
|
|
|
@@ -168,39 +168,39 @@ Please install YADM first: https://yadm.io/`);if(r.stderr){if(r.stderr.includes(
|
|
|
168
168
|
Initialize with: yadm init
|
|
169
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: ${r.message||"Unknown error"}`)}}async getStagedDiff(e,r){const o=["diff","--cached","--diff-algorithm=minimal"],{stdout:n}=await
|
|
172
|
-
`).filter(Boolean),{stdout:l}=await
|
|
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 S("yadm",[...o,"--name-only",...this.filesToExclude,...e?e.map(this.excludeFromDiff):[],...r?r.map(this.excludeFromDiff):[]]);if(!n)return null;const{stdout:s}=await S("yadm",[...o,...this.filesToExclude,...e?e.map(this.excludeFromDiff):[],...r?r.map(this.excludeFromDiff):[]]),i=n.split(`
|
|
172
|
+
`).filter(Boolean),{stdout:l}=await S("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
|
-
`;for(const f of a){const{stdout:p}=await
|
|
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
|
|
176
|
+
`;for(const f of a){const{stdout:p}=await S("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,r,o){const n=["diff-tree","-r","--no-commit-id","--name-only",e],{stdout:s}=await S("yadm",[...n,...this.filesToExclude,...r?r.map(this.excludeFromDiff):[],...o?o.map(this.excludeFromDiff):[]]);if(!s)return null;const{stdout:i}=await S("yadm",["show",e,"--",...this.filesToExclude,...r?r.map(this.excludeFromDiff):[],...o?o.map(this.excludeFromDiff):[]]),{stdout:l}=await S("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,r=[]){try{await
|
|
183
|
+
`).filter(Boolean),...a])];return{files:u,diff:c||`Files changed: ${u.join(", ")}`}}async commit(e,r=[],o={}){try{await S("yadm",["commit","-m",e,...r],{stdio:"inherit"})}catch(n){const s=n;throw s.stderr?s.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
|
|
187
187
|
|
|
188
|
-
Note: The --all flag only stages already-tracked files (YADM best practice).`):
|
|
188
|
+
Note: The --all flag only stages already-tracked files (YADM best practice).`):s.stderr.includes("Please enter the commit message")?new w(`Commit message cannot be empty.
|
|
189
189
|
|
|
190
|
-
Provide a meaningful commit message.`):
|
|
190
|
+
Provide a meaningful commit message.`):s.stderr.includes("Author identity unknown")?new w(`YADM author identity not configured.
|
|
191
191
|
|
|
192
192
|
Configure with:
|
|
193
193
|
yadm config --global user.name "Your Name"
|
|
194
|
-
yadm config --global user.email "your.email@example.com"`):
|
|
194
|
+
yadm config --global user.email "your.email@example.com"`):s.stderr.includes("Permission denied")?new w(`YADM permission error: ${s.stderr.trim()}
|
|
195
195
|
|
|
196
|
-
Check repository permissions and file access.`):new w(`YADM commit failed: ${
|
|
197
|
-
${c instanceof Error?c.message:String(c)}`)}if(e)try{const c=new
|
|
198
|
-
${c instanceof Error?c.message:String(c)}`)}if(r)try{const c=new
|
|
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
|
|
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
|
|
202
|
-
${c instanceof Error?c.message:String(c)}`)}let i=!1;try{i=(await
|
|
203
|
-
${c instanceof Error?c.message:String(c)}`)}let l=null,a=null,d=null;try{const c=new
|
|
196
|
+
Check repository permissions and file access.`):new w(`YADM commit failed: ${s.stderr.trim()}`):s.exitCode===1?new w("YADM commit failed. Check your staged changes and try again."):new w(`Failed to commit with YADM: ${s.message||"Unknown error"}`)}}async getCommentChar(){try{const{stdout:e}=await S("yadm",["config","--get","core.commentChar"]);return e}catch{return"#"}}async getBranchName(){try{const{stdout:e}=await S("yadm",["branch","--show-current"]),r=e.trim();if(!r){const{stdout:o}=await S("yadm",["rev-parse","--short","HEAD"]);return`HEAD@${o.trim()}`}return r}catch{return"HEAD"}}}let kr=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 Et;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 Ar;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 $r;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
|
+
${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 Et;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 Ar;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 $r;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
|
+
${c instanceof Error?c.message:String(c)}`)}let i=!1;try{i=(await ye({})).forceGit===!0}catch{i=!1}if(i)try{const c=new Et;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 $r;return await c.assertRepo(),c}catch(c){l=c instanceof Error?c:new Error(String(c))}try{const c=new Et;return await c.assertRepo(),c}catch(c){a=c instanceof Error?c:new Error(String(c))}try{const c=new Ar;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
|
|
220
|
+
\u2022 Set forceGit=true in config file to prefer Git detection`)}throw new w("Unexpected error during VCS detection")}async function Ce(){return kr||(kr=await Zc()),kr}const Sr=async()=>(await Ce()).assertRepo(),xr=async(t,e)=>(await Ce()).getStagedDiff(t,e),el=async(t,e,r)=>{const o=await Ce();if(!o.getCommitDiff)throw new w(`Commit diff not supported for ${o.name}`);return o.getCommitDiff(t,e,r)},tl=async()=>(await Ce()).getCommentChar(),rl=t=>`Detected ${t.files.length.toLocaleString()} changed file${t.files.length>1?"s":""} (${t.diff.length.toLocaleString()} characters)`,Pt=async()=>(await Ce()).name,ol=async(t,e,r)=>{await(await Ce()).commit(t,e||[],r)},$t=async()=>(await Ce()).getBranchName();class le{constructor(){this.title="aicommit2"}printTitle(){try{const e=qr.textSync(this.title,{font:"Small Slant"}),r=ss(["#8B5CF6","#A020F0","#D946EF"]);console.log(C.bold(r.multiline(e)))}catch{console.log(C.bold(qr.textSync(this.title,{font:"Small Slant"})))}}showLoader(e){if(this.loader){this.loader.text=e;return}this.loader=Xr(e).start()}stopLoader(){this.loader?.stop(),this.loader=void 0}displaySpinner(e){return Xr(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,33 +229,33 @@ ${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=rt.createInterface({input:process.stdin,output:process.stdout});rt.moveCursor(process.stdout,0,-1),e.close()}moveCursorDown(){const e=rt.createInterface({input:process.stdin,output:process.stdout});rt.moveCursor(process.stdout,0,2),e.close()}print(e){console.log(e)}}const nl={isLoading:!1,startOption:{text:"AI is analyzing your changes"}},wn={isLoading:!1,startOption:{text:"AI is performing a code review"}},Ir="No commit messages were generated",vn="No code reviews were generated",Mr={type:"reactiveListPrompt",name:"aicommit2Prompt",message:"Pick a commit message to use: ",emptyMessage:`\u26A0 ${Ir}`,loop:!1,descPageSize:15,showDescription:!0,pickKey:"short",isDescriptionDim:!0,stopMessage:"Changes analyzed"};class Rr{constructor(e){this.choices$=new Hr([]),this.destroyed$=new zn(1),this.stopMessage="Changes analyzed",this.isDestroyed=!1,this.subscriptions=new Dt,this.inquirerInstance=null,this.loader$=new Hr(e)}addSubscription(e){if(this.isDestroyed){e.unsubscribe();return}this.subscriptions.add(e)}initPrompt(e=Mr){return this.stopMessage=e.stopMessage,Ze.registerPrompt("reactiveListPrompt",is),this.inquirerInstance=Ze.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){wt()&&console.warn("Error during ReactivePromptManager destruction:",e)}finally{this.inquirerInstance=null}}}alertNoGeneratedMessage(){this.loader$.next({isLoading:!1,message:Ir,stopOption:{doneFrame:"\u26A0",color:"yellow"}})}stopLoaderOnSuccess(){this.loader$.next({isLoading:!1,message:this.stopMessage})}logEmptyCommitMessage(){console.log(`
|
|
233
|
+
${C.bold.yellow("\u26A0")} ${C.yellow(`${Ir}`)}`)}get currentChoices(){return this.choices$.getValue().map(e=>e)}}const V=new le;var sl=async(t,e,r,o,n,s,i,l,a,d,c,u,f,p,h,g)=>(async()=>{if(V.printTitle(),await Sr(),o){const B=await Pt();B==="git"?await S("git",["add","."]):B==="yadm"&&await S("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 v=await ye(y,g);(a===!0||v.includeBody===!0)&&Object.keys(v).forEach(B=>{typeof v[B]=="object"&&v[B]!==null&&"includeBody"in v[B]&&(v[B].includeBody=!0)}),u&&Object.keys(v).forEach(B=>{typeof v[B]=="object"&&v[B]!==null&&"disableLowerCase"in v[B]&&(v[B].disableLowerCase=!0)}),await on(v);const E={autoNew:h||v.jjAutoNew},A=V.displaySpinner("Detecting staged files"),P=await xr(r,v.exclude);if(A.stop(),!P){const B=await Pt();let ae="No staged changes found.";throw B==="yadm"?(ae+=`
|
|
234
234
|
|
|
235
|
-
Stage your changes with: yadm add <file>`,
|
|
236
|
-
Or stage tracked file modifications: aicommit2 --all`,
|
|
235
|
+
Stage your changes with: yadm add <file>`,ae+=`
|
|
236
|
+
Or stage tracked file modifications: aicommit2 --all`,ae+=`
|
|
237
237
|
|
|
238
|
-
Note: The --all flag only stages already-tracked files (YADM best practice).`,
|
|
239
|
-
To track new dotfiles, explicitly add them first: yadm add <file>`):
|
|
238
|
+
Note: The --all flag only stages already-tracked files (YADM best practice).`,ae+=`
|
|
239
|
+
To track new dotfiles, explicitly add them first: yadm add <file>`):B==="git"?(ae+=`
|
|
240
240
|
|
|
241
|
-
Stage your changes with: git add <file>`,
|
|
242
|
-
Or automatically stage all changes: aicommit2 --all`):
|
|
241
|
+
Stage your changes with: git add <file>`,ae+=`
|
|
242
|
+
Or automatically stage all changes: aicommit2 --all`):B==="jujutsu"&&(ae+=`
|
|
243
243
|
|
|
244
|
-
Jujutsu automatically tracks all changes in the working copy.`,
|
|
245
|
-
Make some changes to your files and try again.`),new w(
|
|
246
|
-
${
|
|
247
|
-
`)}i&&(As("copy-paste").copy(
|
|
248
|
-
`),process.exit()),(s||d
|
|
244
|
+
Jujutsu automatically tracks all changes in the working copy.`,ae+=`
|
|
245
|
+
Make some changes to your files and try again.`),new w(ae)}V.printStagedFiles(P);const $=Me(v,"commit");if($.length===0)throw new w("Please set at least one API key via the `aicommit2 config set` command");const R=await $t(),k=new bt(v,P,R),G=Me(v,"review");G.length>0&&await il(k,G);let I=await al(k,$,d);if(c){if(V.printInfo("Opening editor to modify commit message..."),I=await cl(I),!I.trim())throw new w("Commit message cannot be empty");V.printSuccess("Commit message edited successfully!"),V.print(`
|
|
246
|
+
${I}
|
|
247
|
+
`)}i&&(As("copy-paste").copy(I),V.printCopied(),p||process.exit()),p&&(process.stdout.write(I+`
|
|
248
|
+
`),process.exit()),(s||d&&$.length===1)&&(await Cn(I,g,E),process.exit());const{confirmationPrompt:pe}=await Ze.prompt([{type:"confirm",name:"confirmationPrompt",message:"Use selected message?",default:!0}]);pe?await Cn(I,g,E):V.printCancelledCommit(),process.exit()})().catch(y=>{V.printError(y.message),me(y),process.exit(1)});async function il(t,e){const r=new Rr(wn);let o=null;try{const n=r.initPrompt({...Mr,name:"codeReviewPrompt",message:"Please check code reviews: ",emptyMessage:`\u26A0 ${vn}`,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 Ze.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 Rr(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=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=
|
|
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=x.join(Ne.tmpdir(),`aicommit2-${Date.now()}-${Dn.randomBytes(4).toString("hex")}.txt`);try{q.writeFileSync(r,t,"utf8");const o=e.split(" "),[n,...s]=o;await S(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
|
|
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.`)}}const Cn=async(t,e,r)=>{await ol(t,e,r),V.printCommitted()};var ll=ue({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:[ue({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"]}}),ue({name:"get",parameters:["[<key>","[<key> ...]]"],help:{description:"Retrieve configuration values for specified AI provider.",examples:["aic2 config get OPENAI","aic2 config get ANTHROPIC"]}}),ue({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"']}}),ue({name:"list",parameters:[],help:{description:"Display all configuration keys and their values.",examples:["aic2 config list"]}}),ue({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"]}}),ue({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 ye({},[]);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(nr(l,d))l=l[d];else{a=!1;break}a?console.log(s,l):console.log(`${s} not found`)}return}if(e==="set"){await ir(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 Ge(),s=o.split(".");if(s.length===2){const[i,l]=s;if(n[i]&&typeof n[i]=="object"&&nr(n[i],l)){delete n[i][l],Object.keys(n[i]).length===0&&delete n[i];const a=await xe();await F.writeFile(a,Se.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(nr(n,i)){delete n[i];const l=await xe();await F.writeFile(l,Se.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 le().printError(e.message),me(e),process.exit(1)})}),ul=ue({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 le;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 le().printError(e.message),me(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 ir([["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{Qe("gh --version",{stdio:"ignore"})}catch{throw new Error("GitHub CLI (gh) is not installed. Please install it first: https://cli.github.com/")}try{Qe("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{Qe("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=Qe("gh auth token",{encoding:"utf8"}).trim();e&&(await ir([["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 Oe="prepare-commit-msg",fl=async()=>{const t=await Pt();if(t==="git")return`.git/hooks/${Oe}`;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 x.join(i,"hooks",Oe)}catch{}const r=x.join(e,".config/yadm/hooks"),o=x.join(e,".yadm/hooks");try{return await F.access(r),x.join(r,Oe)}catch{return x.join(o,Oe)}}throw t==="jujutsu"?new w("Hooks are not supported for Jujutsu repositories."):new w(`Hooks are not supported for ${t} repositories.`)},At=Zn(new URL("cli.mjs",import.meta.url)),pl=process.argv[1].replace(/\\/g,"/").includes(`/hooks/${Oe}`),bn=process.platform==="win32",En=`
|
|
254
254
|
#!/usr/bin/env node
|
|
255
|
-
import(${JSON.stringify(es(
|
|
256
|
-
`.trim();var hl=
|
|
257
|
-
`);const r=await Promise.all(e.map(async o=>{const n=
|
|
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
|
|
255
|
+
import(${JSON.stringify(es(At))})
|
|
256
|
+
`.trim();var hl=ue({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 Sr(),{installUninstall:r}=t._,o=await fl(),n=x.isAbsolute(o)?o:x.join(e,o),s=await Yo(n);if(r==="install"){if(s){if(await F.realpath(n).catch(()=>{})===At){console.warn("The hook is already installed");return}throw new w(`A different ${Oe} hook seems to be installed. Please remove it before installing aicommit2.`)}await F.mkdir(x.dirname(n),{recursive:!0}),bn?await F.writeFile(n,En):(await F.symlink(At,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(bn){if(await F.readFile(n,"utf8")!==En){console.warn("Hook is not installed");return}}else if(await F.realpath(n)!==At){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}`),me(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 Qr(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=he.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 Qr(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=ue({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 le;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 le().printError(e.message),me(e),process.exit(1)})});const Pl=process.argv.slice(2).filter(t=>!t.startsWith("--pre-commit")),[kt,Pn]=Pl;var $l=(t=!1)=>(async()=>{if(!kt)throw new w('Commit message file path is missing. This file should be called from the "pre-commit framework"');if(Pn){console.log(`Skipping aicommit2 message generation for ${Pn} commit`);return}const e=await xr();if(!e)return;const r=new le;r.printTitle();const o={};t&&(o.logLevel="verbose");const n=await ye(o);if(n.systemPromptPath)try{await F.readFile(x.resolve(n.systemPromptPath),"utf-8")}catch{throw new w(`Error reading system prompt file: ${n.systemPromptPath}`)}const s=Me(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 $t(),a=new bt(n,e,l);let d;try{d=await Ur(a.createCommitMsgRequests$(s).pipe(zr(y=>!y.isError),O(y=>y.value),Kr()))}finally{r.printAnalyzed()}const u=await F.readFile(kt,"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
|
|
@@ -268,35 +268,35 @@ ${C.green("Total:")} ${e.length} file${e.length!==1?"s":""}`)}catch(e){if(e.code
|
|
|
268
268
|
`),f?(u&&(p+=`
|
|
269
269
|
# \u{1F4DD} Choose one of these messages:
|
|
270
270
|
`),p+=`
|
|
271
|
-
${d.map(
|
|
271
|
+
${d.map(y=>`# ${y}`).join(`
|
|
272
272
|
`)}`):(u&&(p+=`
|
|
273
273
|
# \u{1F4DD} Generated commit message:
|
|
274
274
|
`),p+=`
|
|
275
275
|
${d[0]}
|
|
276
|
-
`);const h=await F.readFile(
|
|
277
|
-
`+h;await F.writeFile(
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
`,E?(
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
`):(
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
`)
|
|
287
|
-
`),E?(b&&(
|
|
288
|
-
${
|
|
289
|
-
`)
|
|
290
|
-
${
|
|
291
|
-
`)}`):(b&&(
|
|
292
|
-
${
|
|
293
|
-
`)
|
|
294
|
-
${
|
|
295
|
-
`);const
|
|
296
|
-
|
|
276
|
+
`);const h=await F.readFile(kt,"utf8"),g=p+`
|
|
277
|
+
`+h;await F.writeFile(kt,g),r.printSavedCommitMessage()})().catch(e=>{new le().printError(e.message),me(e),process.exit(1)});const Dr=process.argv.slice(2),$n=[];let Or=!1;for(let t=0;t<Dr.length;t++){const e=Dr[t];if(Or){Or=!1;continue}if(e!=="--hook-mode"){if(e.startsWith("-")){const r=Dr[t+1];r&&!r.startsWith("-")&&(Or=!0);continue}$n.push(e)}}const[St,An]=$n;var Al=(t,e,r,o,n,s,i)=>(async()=>{if(!St)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(An){console.log(`Skipping aicommit2 message generation for ${An} commit`);return}const l=await xr();if(!l)return;const a=new le;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 ye(d,r);if(c.systemPromptPath)try{await F.readFile(x.resolve(c.systemPromptPath),"utf-8")}catch{throw new w(`Error reading system prompt file: ${c.systemPromptPath}`)}const u=Me(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 $t(),h=new bt(c,l,p),g=a.displaySpinner("The AI is analyzing your changes");let y;try{y=await Ur(h.createCommitMsgRequests$(u).pipe(zr(k=>!k.isError),O(k=>k.value),Kr()))}finally{g.stop(),g.clear(),a.printAnalyzed()}const b=await F.readFile(St,"utf8")!=="",E=y.length>1,A=await tl();let P="";b&&(P=`${A} \u{1F916} Generated by aicommit2 (https://github.com/tak-bro/aicommit2)
|
|
278
|
+
`,P+=`${A} ----------------------------------------
|
|
279
|
+
`,P+=`${A} How to use:
|
|
280
|
+
`,E?(P+=`${A} 1. Remove the "${A}" from your chosen message
|
|
281
|
+
`,P+=`${A} 2. Edit the message if needed
|
|
282
|
+
`,P+=`${A} 3. Save and close the editor
|
|
283
|
+
`):(P+=`${A} 1. The message below will be used
|
|
284
|
+
`,P+=`${A} 2. Edit the message if needed
|
|
285
|
+
`,P+=`${A} 3. Save and close the editor
|
|
286
|
+
`),P+=`${A} ----------------------------------------
|
|
287
|
+
`),E?(b&&(P+=`
|
|
288
|
+
${A} \u{1F4DD} Choose one of these messages:
|
|
289
|
+
`),P+=`
|
|
290
|
+
${y.map(k=>`${A} ${k}`).join(`
|
|
291
|
+
`)}`):(b&&(P+=`
|
|
292
|
+
${A} \u{1F4DD} Generated commit message:
|
|
293
|
+
`),P+=`
|
|
294
|
+
${y[0]}
|
|
295
|
+
`);const $=await F.readFile(St,"utf8"),R=P+`
|
|
296
|
+
`+$;await F.writeFile(St,R),a.printSavedCommitMessage()})().catch(l=>{new le().printError(l.message),me(l),process.exit(1)});class kn{constructor(e="SubscriptionManager"){this.destroyed$=new Ot,this.subscriptions=new Dt,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 Dt;return n.unsubscribe(),n}const o=e.pipe(Zr(this.destroyed$),eo(()=>{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(Zr(this.destroyed$),eo(()=>{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 kn("Global"),Xe=()=>{kl.destroy()};process.on("exit",Xe),process.on("SIGINT",Xe),process.on("SIGTERM",Xe),process.on("uncaughtException",t=>{console.error("Uncaught exception:",t),Xe(),process.exit(1)}),process.on("unhandledRejection",(t,e)=>{console.error("Unhandled rejection at:",e,"reason:",t),Xe(),process.exit(1)});class Sl{constructor(){this.destroyed$=new Ot,this.consoleManager=new le,this.subscriptionManager=new kn,this.currentCodeReviewSubscription=null,this.currentCodeReviewPromptManager=null,this.watcher=null,this.lastCommitHash=null,this.isProcessingCommit=!1,this.REPO_PATH=process.cwd(),this.GIT_PATH=x.join(this.REPO_PATH,".git"),this.HEAD_PATH=x.join(this.GIT_PATH,"HEAD"),this.REFS_PATH=x.join(this.GIT_PATH,"refs","heads"),this.COMMIT_MSG_PATH=x.join(this.GIT_PATH,"COMMIT_EDITMSG"),this.setupProcessHandlers()}setupProcessHandlers(){const e=()=>{this.destroy(),process.exit(0)};process.on("SIGINT",e),process.on("SIGTERM",e),process.on("SIGQUIT",e)}async watch(e,r,o,n,s,i){this.consoleManager.printTitle(),await Sr();const l=await Pt();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 ye(i,s);return await on(l),Me(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}`),
|
|
298
|
+
aicommit2 config set [MODEL].watchMode="true"`),process.exit()),l}async handleWatchGitError(e){this.consoleManager.printError(`An error occurred: ${e.message}`),me(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=Me(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 ${r}: ${o.message}`)}}async performCodeReview(e,r,o){this.cleanupPreviousCodeReview();const n=await
|
|
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 $t(),s=new bt(e,r,n);this.currentCodeReviewPromptManager=new Rr(wn);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 Ot}initializeCodeReviewInquirer(){return this.currentCodeReviewPromptManager.initPrompt({...Mr,name:"codeReviewPrompt",message:"Please check code reviews: ",emptyMessage:`\u26A0 ${vn}`,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,x.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(t,e,r,o,n,s)=>xl.watch(t,e,r,o,n,s),
|
|
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),xt=process.argv.slice(2),{version:Sn,description:Ml}=$s;Mn({name:"aicommit2",version:Sn,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},"jj-auto-new":{type:Boolean,description:"Run jj new after jj describe (default: false, only describe)",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 ye(e,xt);if(await Za(r),Re.info(`aicommit2 version: ${Sn}`),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,xt);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"],t.flags["jj-auto-new"],xt)},xt);
|