aicommit2 2.4.21 → 2.4.22
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.mjs +139 -138
- package/package.json +1 -1
package/dist/cli.mjs
CHANGED
|
@@ -1,26 +1,26 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{command as ce,cli as In}from"cleye";import{createRequire as Mn}from"module";import Rn from"crypto";import V from"fs";import Re from"os";import x from"path";import{Buffer as Ir}from"node:buffer";import me from"node:path";import St,{ChildProcess as Mr,exec as On}from"node:child_process";import ne from"node:process";import Dn,{execSync as Ve,exec as Fn}from"child_process";import{fileURLToPath as Rr}from"node:url";import Ln,{constants as Or}from"node:os";import Dr from"assert";import Fr from"events";import{createWriteStream as Nn,createReadStream as _n,readFileSync as Tn}from"node:fs";import jn from"buffer";import xt from"stream";import Lr,{promisify as Bn}from"util";import{debuglog as Gn,promisify as Hn}from"node:util";import qe from"inquirer";import N from"fs/promises";import C from"chalk";import{of as It,concatMap as _,from as D,map as F,catchError as L,mergeMap as Nr,BehaviorSubject as _r,ReplaySubject as Un,Subscription as Mt,lastValueFrom as Tr,filter as jr,toArray as Br,Subject as Rt}from"rxjs";import zn from"@anthropic-ai/sdk";import{fromPromise as T}from"rxjs/internal/observable/innerFrom";import{xxh64 as Gr}from"@pacote/xxhash";import H from"winston";import"winston-daily-rotate-file";import Hr from"https";import Kn from"axios";import{CohereClientV2 as Wn}from"cohere-ai";import Ur from"openai";import{GoogleGenerativeAI as Yn,HarmCategory as Xe,HarmBlockThreshold as Qe}from"@google/generative-ai";import Jn from"http";import Vn from"net";import qn from"tls";import Xn,{fileURLToPath as Qn,pathToFileURL as Zn}from"url";import zr from"tty";import es from"groq-sdk";import{Ollama as ts}from"ollama";import{fetch as rs,Agent as os}from"undici";import Ze from"readline";import Kr from"figlet";import ns from"gradient-string";import Wr from"ora";import ss from"inquirer-reactive-list-prompt";import{readdir as Yr,stat as is,rm as as}from"node:fs/promises";import cs from"chokidar";import{takeUntil as Jr,finalize as Vr}from"rxjs/operators";var ls="aicommit2",qr="2.4.21",us="A Reactive CLI that generates commit messages for Git and Jujutsu with various AI",ds=["cli","ai","git","jujutsu","jj","vcs","version-control","commit","git-commit","jujutsu-commit","command-line","commandline","aipick","aicommit","aicommits","aicommit2","openai","huggingface","anthropic","claude","claude3","gemini","gemini-pro","generative-ai","mistral","ollama","llama3","llama3.2","llama3.3","gemma","llm","chatgpt","cohere","groq","codestral","perplexity","deepseek","deepseek-r1","pre-commit"],ms="MIT",fs="tak-bro/aicommit2",ps="Hyungtak Jin(@tak-bro)",hs="module",gs=["dist"],ys={aicommit2:"./dist/cli.mjs",aic2:"./dist/cli.mjs"},ws={prepare:"simple-git-hooks",build:"pkgroll --minify",lint:"eslint --cache .","type-check":"tsc",test:"tsx tests",prepack:"pnpm build && clean-pkg-json",prettier:"prettier"},vs={"@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"},Cs={"@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"},bs={extends:["@pvtnbr","prettier"],rules:{"unicorn/no-process-exit":"off"},overrides:[{files:"./src/commands/prepare-commit-msg-hook.ts",rules:{"unicorn/prevent-abbreviations":"off"}}]},Es={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"]},Ps={name:ls,version:qr,description:us,keywords:ds,license:ms,repository:fs,author:ps,type:hs,files:gs,bin:ys,scripts:ws,"simple-git-hooks":{"pre-commit":"pnpm lint-staged"},"lint-staged":{"*.ts":["prettier --config ./.prettierrc --write","eslint --fix"]},dependencies:vs,devDependencies:Cs,eslintConfig:bs,release:Es},$s=Mn(import.meta.url),G=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function ye(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var we={exports:{}},Ot,Xr;function As(){if(Xr)return Ot;Xr=1,Ot=o,o.sync=n;var t=V;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 Dt,Qr;function ks(){if(Qr)return Dt;Qr=1,Dt=e,e.sync=r;var t=V;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(),m=parseInt("100",8),p=parseInt("010",8),h=parseInt("001",8),g=m|p,y=l&h||l&p&&d===u||l&m&&a===c||l&g&&c===0;return y}return Dt}var et;process.platform==="win32"||G.TESTING_WINDOWS?et=As():et=ks();var Ss=Ft;Ft.sync=xs;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)})})}et(t,e||{},function(o,n){o&&(o.code==="EACCES"||e&&e.ignoreErrors)&&(o=null,n=!1),r(o,n)})}function xs(t,e){try{return et.sync(t,e||{})}catch(r){if(e&&e.ignoreErrors||r.code==="EACCES")return!1;throw r}}const ve=process.platform==="win32"||process.env.OSTYPE==="cygwin"||process.env.OSTYPE==="msys",Zr=x,Is=ve?";":":",eo=Ss,to=t=>Object.assign(new Error(`not found: ${t}`),{code:"ENOENT"}),ro=(t,e)=>{const r=e.colon||Is,o=t.match(/\//)||ve&&t.match(/\\/)?[""]:[...ve?[process.cwd()]:[],...(e.path||process.env.PATH||"").split(r)],n=ve?e.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",s=ve?n.split(r):[""];return ve&&t.indexOf(".")!==-1&&s[0]!==""&&s.unshift(""),{pathEnv:o,pathExt:s,pathExtExe:n}},oo=(t,e,r)=>{typeof e=="function"&&(r=e,e={}),e||(e={});const{pathEnv:o,pathExt:n,pathExtExe:s}=ro(t,e),i=[],l=d=>new Promise((c,u)=>{if(d===o.length)return e.all&&i.length?c(i):u(to(t));const m=o[d],p=/^".*"$/.test(m)?m.slice(1,-1):m,h=Zr.join(p,t),g=!p&&/^\.[\\\/]/.test(t)?t.slice(0,2)+h:h;c(a(g,d,0))}),a=(d,c,u)=>new Promise((m,p)=>{if(u===n.length)return m(l(c+1));const h=n[u];eo(d+h,{pathExt:s},(g,y)=>{if(!g&&y)if(e.all)i.push(d+h);else return m(d+h);return m(a(d,c,u+1))})});return r?l(0).then(d=>r(null,d),r):l(0)},Ms=(t,e)=>{e=e||{};const{pathEnv:r,pathExt:o,pathExtExe:n}=ro(t,e),s=[];for(let i=0;i<r.length;i++){const l=r[i],a=/^".*"$/.test(l)?l.slice(1,-1):l,d=Zr.join(a,t),c=!a&&/^\.[\\\/]/.test(t)?t.slice(0,2)+d:d;for(let u=0;u<o.length;u++){const m=c+o[u];try{if(eo.sync(m,{pathExt:n}))if(e.all)s.push(m);else return m}catch{}}}if(e.all&&s.length)return s;if(e.nothrow)return null;throw to(t)};var Rs=oo;oo.sync=Ms;var Lt={exports:{}};const no=(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=no,Lt.exports.default=no;var Os=Lt.exports;const so=x,Ds=Rs,Fs=Os;function io(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=Ds.sync(t.command,{path:r[Fs({env:r})],pathExt:e?so.delimiter:void 0})}catch{}finally{s&&process.chdir(o)}return i&&(i=so.resolve(n?t.options.cwd:"",i)),i}function Ls(t){return io(t)||io(t,!0)}var Ns=Ls,Nt={};const _t=/([()\][%!^"`<>&|;, *?])/g;function _s(t){return t=t.replace(_t,"^$1"),t}function Ts(t,e){return t=`${t}`,t=t.replace(/(?=(\\+?)?)\1"/g,'$1$1\\"'),t=t.replace(/(?=(\\+?)?)\1$/,"$1$1"),t=`"${t}"`,t=t.replace(_t,"^$1"),e&&(t=t.replace(_t,"^$1")),t}Nt.command=_s,Nt.argument=Ts;var js=/^#!(.*)/;const Bs=js;var Gs=(t="")=>{const e=t.match(Bs);if(!e)return null;const[r,o]=e[0].replace(/#! ?/,"").split(" "),n=r.split("/").pop();return n==="env"?o:o?`${n} ${o}`:n};const Tt=V,Hs=Gs;function Us(t){const r=Buffer.alloc(150);let o;try{o=Tt.openSync(t,"r"),Tt.readSync(o,r,0,150,0),Tt.closeSync(o)}catch{}return Hs(r.toString())}var zs=Us;const Ks=x,ao=Ns,co=Nt,Ws=zs,Ys=process.platform==="win32",Js=/\.(?:com|exe)$/i,Vs=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function qs(t){t.file=ao(t);const e=t.file&&Ws(t.file);return e?(t.args.unshift(t.file),t.command=e,ao(t)):t.file}function Xs(t){if(!Ys)return t;const e=qs(t),r=!Js.test(e);if(t.options.forceShell||r){const o=Vs.test(e);t.command=Ks.normalize(t.command),t.command=co.command(t.command),t.args=t.args.map(s=>co.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 Qs(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:Xs(o)}var Zs=Qs;const jt=process.platform==="win32";function Bt(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 ei(t,e){if(!jt)return;const r=t.emit;t.emit=function(o,n){if(o==="exit"){const s=lo(n,e);if(s)return r.call(t,"error",s)}return r.apply(t,arguments)}}function lo(t,e){return jt&&t===1&&!e.file?Bt(e.original,"spawn"):null}function ti(t,e){return jt&&t===1&&!e.file?Bt(e.original,"spawnSync"):null}var ri={hookChildProcess:ei,verifyENOENT:lo,verifyENOENTSync:ti,notFoundError:Bt};const uo=Dn,Gt=Zs,Ht=ri;function mo(t,e,r){const o=Gt(t,e,r),n=uo.spawn(o.command,o.args,o.options);return Ht.hookChildProcess(n,o),n}function oi(t,e,r){const o=Gt(t,e,r),n=uo.spawnSync(o.command,o.args,o.options);return n.error=n.error||Ht.verifyENOENTSync(n.status,o),n}we.exports=mo,we.exports.spawn=mo,we.exports.sync=oi,we.exports._parse=Gt,we.exports._enoent=Ht;var ni=we.exports,si=ye(ni);function ii(t){const e=typeof t=="string"?`
|
|
2
|
+
import{command as le,cli as Mn}from"cleye";import{createRequire as Rn}from"module";import Dn from"crypto";import V from"fs";import De from"os";import I from"path";import{Buffer as Rr}from"node:buffer";import fe from"node:path";import xt,{ChildProcess as Dr,exec as On}from"node:child_process";import se from"node:process";import Nn,{execSync as qe,exec as Fn}from"child_process";import{fileURLToPath as Or}from"node:url";import Ln,{constants as Nr}from"node:os";import Fr from"assert";import Lr from"events";import{createWriteStream as _n,createReadStream as Tn,readFileSync as jn}from"node:fs";import Bn from"buffer";import It from"stream";import _r,{promisify as Gn}from"util";import{debuglog as Hn,promisify as Un}from"node:util";import Xe from"inquirer";import L from"fs/promises";import b from"chalk";import{of as Mt,concatMap as _,from as O,map as N,catchError as F,mergeMap as Tr,BehaviorSubject as jr,ReplaySubject as zn,Subscription as Rt,lastValueFrom as Br,filter as Gr,toArray as Hr,Subject as Dt}from"rxjs";import Kn from"@anthropic-ai/sdk";import{fromPromise as T}from"rxjs/internal/observable/innerFrom";import{xxh64 as Ur}from"@pacote/xxhash";import H from"winston";import"winston-daily-rotate-file";import zr from"https";import Wn from"axios";import{CohereClientV2 as Yn}from"cohere-ai";import Kr from"openai";import{GoogleGenerativeAI as Jn,HarmCategory as Qe,HarmBlockThreshold as Ze}from"@google/generative-ai";import Vn from"http";import qn from"net";import Xn from"tls";import Qn,{fileURLToPath as Zn,pathToFileURL as es}from"url";import Wr from"tty";import ts from"groq-sdk";import{Ollama as rs}from"ollama";import{fetch as os,Agent as ns}from"undici";import et from"readline";import Yr from"figlet";import ss from"gradient-string";import Jr from"ora";import is from"inquirer-reactive-list-prompt";import{readdir as Vr,stat as as,rm as cs}from"node:fs/promises";import ls from"chokidar";import{takeUntil as qr,finalize as Xr}from"rxjs/operators";var us="aicommit2",Qr="2.4.22",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"},bs={"@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"},Cs={"@pvtnbr/eslint-config":"^0.33.0","@semantic-release/changelog":"^6.0.3","@semantic-release/commit-analyzer":"^12.0.0","@semantic-release/git":"^10.0.1","@semantic-release/github":"^10.3.5","@semantic-release/npm":"^12.0.1","@semantic-release/release-notes-generator":"^13.0.0","@types/figlet":"^1.7.0","@types/ini":"^1.3.34","@types/inquirer":"^9.0.8","@types/node":"^18.19.103","@types/uuid":"^9.0.8","@typescript-eslint/eslint-plugin":"^6.21.0","@typescript-eslint/parser":"^6.21.0","clean-pkg-json":"^1.3.0","conventional-changelog-conventionalcommits":"^7.0.2","conventional-commits-parser":"^5.0.0",eslint:"^8.57.1","eslint-config-prettier":"^8.10.0","eslint-plugin-eslint-comments":"^3.2.0","eslint-plugin-import":"^2.31.0","eslint-plugin-jsonc":"^2.20.1","eslint-plugin-no-use-extend-native":"^0.5.0","eslint-plugin-promise":"^6.6.0","eslint-plugin-unicorn":"^49.0.0","eslint-plugin-unused-imports":"^3.2.0",execa:"^7.2.0","fs-fixture":"^1.2.0","https-proxy-agent":"^5.0.1",ini:"^3.0.1","lint-staged":"^13.3.0",manten:"^0.7.0",pkgroll:"^1.11.1",prettier:"^3.5.3","semantic-release":"^23.1.1","simple-git-hooks":"^2.13.0",tsx:"^3.14.0",typescript:"^4.9.5","undici-types":"^7.10.0"},Es={extends:["@pvtnbr","prettier"],rules:{"unicorn/no-process-exit":"off"},overrides:[{files:"./src/commands/prepare-commit-msg-hook.ts",rules:{"unicorn/prevent-abbreviations":"off"}}]},Ps={branches:["main"],plugins:[["@semantic-release/commit-analyzer",{preset:"conventionalcommits",releaseRules:[{type:"refactor",release:"patch"},{type:"chore",release:"patch"},{type:"feat",release:"patch"},{scope:"major",release:"major"},{scope:"minor",release:"minor"},{scope:"patch",release:"patch"}]}],"@semantic-release/release-notes-generator",["@semantic-release/changelog",{changelogFile:"CHANGELOG.md"}],"@semantic-release/github",["@semantic-release/git",{assets:["CHANGELOG.md"],message:"chore(release): ${nextRelease.version} [skip ci]\n\n${nextRelease.notes}"}],"@semantic-release/npm"]},As={name:us,version:Qr,description:ds,keywords:ms,license:fs,repository:ps,author:hs,type:gs,files:ys,bin:ws,scripts:vs,"simple-git-hooks":{"pre-commit":"pnpm lint-staged"},"lint-staged":{"*.ts":["prettier --config ./.prettierrc --write","eslint --fix"]},dependencies:bs,devDependencies:Cs,eslintConfig:Es,release:Ps},$s=Rn(import.meta.url),G=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function ve(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var be={exports:{}},Ot,Zr;function ks(){if(Zr)return Ot;Zr=1,Ot=o,o.sync=n;var t=V;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,eo;function Ss(){if(eo)return Nt;eo=1,Nt=e,e.sync=r;var t=V;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 tt;process.platform==="win32"||G.TESTING_WINDOWS?tt=ks():tt=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)})})}tt(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 tt.sync(t,e||{})}catch(r){if(e&&e.ignoreErrors||r.code==="EACCES")return!1;throw r}}const Ce=process.platform==="win32"||process.env.OSTYPE==="cygwin"||process.env.OSTYPE==="msys",to=I,Ms=Ce?";":":",ro=xs,oo=t=>Object.assign(new Error(`not found: ${t}`),{code:"ENOENT"}),no=(t,e)=>{const r=e.colon||Ms,o=t.match(/\//)||Ce&&t.match(/\\/)?[""]:[...Ce?[process.cwd()]:[],...(e.path||process.env.PATH||"").split(r)],n=Ce?e.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",s=Ce?n.split(r):[""];return Ce&&t.indexOf(".")!==-1&&s[0]!==""&&s.unshift(""),{pathEnv:o,pathExt:s,pathExtExe:n}},so=(t,e,r)=>{typeof e=="function"&&(r=e,e={}),e||(e={});const{pathEnv:o,pathExt:n,pathExtExe:s}=no(t,e),i=[],l=d=>new Promise((c,u)=>{if(d===o.length)return e.all&&i.length?c(i):u(oo(t));const f=o[d],p=/^".*"$/.test(f)?f.slice(1,-1):f,h=to.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];ro(d+h,{pathExt:s},(y,g)=>{if(!y&&g)if(e.all)i.push(d+h);else return f(d+h);return f(a(d,c,u+1))})});return r?l(0).then(d=>r(null,d),r):l(0)},Rs=(t,e)=>{e=e||{};const{pathEnv:r,pathExt:o,pathExtExe:n}=no(t,e),s=[];for(let i=0;i<r.length;i++){const l=r[i],a=/^".*"$/.test(l)?l.slice(1,-1):l,d=to.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(ro.sync(f,{pathExt:n}))if(e.all)s.push(f);else return f}catch{}}}if(e.all&&s.length)return s;if(e.nothrow)return null;throw oo(t)};var Ds=so;so.sync=Rs;var Lt={exports:{}};const io=(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=io,Lt.exports.default=io;var Os=Lt.exports;const ao=I,Ns=Ds,Fs=Os;function co(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?ao.delimiter:void 0})}catch{}finally{s&&process.chdir(o)}return i&&(i=ao.resolve(n?t.options.cwd:"",i)),i}function Ls(t){return co(t)||co(t,!0)}var _s=Ls,_t={};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}_t.command=Ts,_t.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=V,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,lo=_s,uo=_t,Ys=Ks,Js=process.platform==="win32",Vs=/\.(?:com|exe)$/i,qs=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function Xs(t){t.file=lo(t);const e=t.file&&Ys(t.file);return e?(t.args.unshift(t.file),t.command=e,lo(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=uo.command(t.command),t.args=t.args.map(s=>uo.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=mo(n,e);if(s)return r.call(t,"error",s)}return r.apply(t,arguments)}}function mo(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:mo,verifyENOENTSync:ri,notFoundError:Gt};const fo=Nn,Ht=ei,Ut=oi;function po(t,e,r){const o=Ht(t,e,r),n=fo.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=fo.spawnSync(o.command,o.args,o.options);return n.error=n.error||Ut.verifyENOENTSync(n.status,o),n}be.exports=po,be.exports.spawn=po,be.exports.sync=ni,be.exports._parse=Ht,be.exports._enoent=Ut;var si=be.exports,ii=ve(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}`,
|
|
6
|
-
${o.message}`:
|
|
7
|
-
`);return v?(o.originalMessage=o.message,o.message=
|
|
8
|
-
`)},$a=1e3*1e3*100,
|
|
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 ho(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[ho()],preferLocal:r=!0,execPath:o=se.execPath,addExecPath:n=!0}={})=>{const s=t instanceof URL?Or(t):t,i=fe.resolve(s),l=[];return r&&li(l,i),n&&ui(l,o,i),[...l,e].join(fe.delimiter)},li=(t,e)=>{let r;for(;r!==e;)t.push(fe.join(e,"node_modules/.bin")),r=e,e=fe.resolve(e,"..")},ui=(t,e,r)=>{const o=e instanceof URL?Or(e):e;t.push(fe.resolve(r,o,".."))},di=({env:t=se.env,...e}={})=>{t={...t};const r=ho({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 rt=new WeakMap,go=(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(rt.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),rt.set(s,o),s};go.callCount=t=>{if(!rt.has(t))throw new Error(`The given function \`${t.name}\` is not wrapped by the \`onetime\` package`);return rt.get(t)};const bi=()=>{const t=wo-yo+1;return Array.from({length:t},Ci)},Ci=(t,e)=>({name:`SIGRT${e+1}`,number:yo+e,action:"terminate",description:"Application-specific signal (realtime)",standard:"posix"}),yo=34,wo=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"}],vo=()=>{const t=bi();return[...Ei,...t].map(Pi)},Pi=({name:t,number:e,description:r,action:o,forced:n=!1,standard:s})=>{const{signals:{[t]:i}}=Nr,l=i!==void 0;return{name:t,number:l?i:e,description:r,supported:l,action:o,forced:n,standard:s}},Ai=()=>{const t=vo();return Object.fromEntries(t.map($i))},$i=({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=Ai(),Si=()=>{const t=vo(),e=wo+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})=>Nr.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",ot=({stdout:t,stderr:e,all:r,error:o,signal:n,exitCode:s,command:i,escapedCommand:l,timedOut:a,isCanceled:d,killed:c,parsed:{options:{timeout:u,cwd:f=se.cwd()}}})=>{s=s===null?void 0:s,n=n===null?void 0:n;const p=n===void 0?void 0:ki[n].description,h=o&&o.code,g=`Command ${Mi({timedOut:a,timeout:u,errorCode:h,signal:n,signalDescription:p,exitCode:s,isCanceled:d})}: ${i}`,v=Object.prototype.toString.call(o)==="[object Error]",C=v?`${g}
|
|
6
|
+
${o.message}`:g,E=[C,e,t].filter(Boolean).join(`
|
|
7
|
+
`);return v?(o.originalMessage=o.message,o.message=E):o=new Error(E),o.shortMessage=C,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},nt=["stdin","stdout","stderr"],Ri=t=>nt.some(e=>t[e]!==void 0),bo=t=>{if(!t)return;const{stdio:e}=t;if(e===void 0)return nt.map(o=>t[o]);if(Ri(t))throw new Error(`It's not possible to provide \`stdio\` in combination with one of ${nt.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,nt.length);return Array.from({length:r},(o,n)=>e[n])},Di=t=>{const e=bo(t);return e==="ipc"?"ipc":e===void 0||typeof e=="string"?[e,e,e,"ipc"]:e.includes("ipc")?e:[...e,"ipc"]};var Ee={exports:{}},st={exports:{}};st.exports;var Co;function Oi(){return Co||(Co=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")}(st)),st.exports}var j=G.process;const pe=function(t){return t&&typeof t=="object"&&typeof t.removeListener=="function"&&typeof t.emit=="function"&&typeof t.reallyExit=="function"&&typeof t.listeners=="function"&&typeof t.kill=="function"&&typeof t.pid=="number"&&typeof t.on=="function"};if(!pe(j))Ee.exports=function(){return function(){}};else{var Ni=Fr,Oe=Oi(),Fi=/^win/i.test(j.platform),it=Lr;typeof it!="function"&&(it=it.EventEmitter);var U;j.__signal_exit_emitter__?U=j.__signal_exit_emitter__:(U=j.__signal_exit_emitter__=new it,U.count=0,U.emitted={}),U.infinite||(U.setMaxListeners(1/0),U.infinite=!0),Ee.exports=function(t,e){if(!pe(G.process))return function(){};Ni.equal(typeof t,"function","a callback must be provided for exit handler"),Ne===!1&&Eo();var r="exit";e&&e.alwaysLast&&(r="afterexit");var o=function(){U.removeListener(r,t),U.listeners("exit").length===0&&U.listeners("afterexit").length===0&&zt()};return U.on(r,t),o};var zt=function(){!Ne||!pe(G.process)||(Ne=!1,Oe.forEach(function(e){try{j.removeListener(e,Kt[e])}catch{}}),j.emit=Wt,j.reallyExit=Po,U.count-=1)};Ee.exports.unload=zt;var Pe=function(e,r,o){U.emitted[e]||(U.emitted[e]=!0,U.emit(e,r,o))},Kt={};Oe.forEach(function(t){Kt[t]=function(){if(pe(G.process)){var r=j.listeners(t);r.length===U.count&&(zt(),Pe("exit",null,t),Pe("afterexit",null,t),Fi&&t==="SIGHUP"&&(t="SIGINT"),j.kill(j.pid,t))}}}),Ee.exports.signals=function(){return Oe};var Ne=!1,Eo=function(){Ne||!pe(G.process)||(Ne=!0,U.count+=1,Oe=Oe.filter(function(e){try{return j.on(e,Kt[e]),!0}catch{return!1}}),j.emit=_i,j.reallyExit=Li)};Ee.exports.load=Eo;var Po=j.reallyExit,Li=function(e){pe(G.process)&&(j.exitCode=e||0,Pe("exit",j.exitCode,null),Pe("afterexit",j.exitCode,null),Po.call(j,j.exitCode))},Wt=j.emit,_i=function(e,r){if(e==="exit"&&pe(G.process)){r!==void 0&&(j.exitCode=r);var o=Wt.apply(this,arguments);return Pe("exit",j.exitCode,null),Pe("afterexit",j.exitCode,null),o}else return Wt.apply(this,arguments)}}var Ti=Ee.exports,ji=ve(Ti);const Bi=1e3*5,Gi=(t,e="SIGTERM",r={})=>{const o=t(e);return Hi(t,e,r,o),o},Hi=(t,e,r,o)=>{if(!Ui(e,r,o))return;const n=Ki(r),s=setTimeout(()=>{t("SIGKILL")},n);s.unref&&s.unref()},Ui=(t,{forceKillAfterTimeout:e},r)=>zi(t)&&e!==!1&&r,zi=t=>t===Ln.constants.signals.SIGTERM||typeof t=="string"&&t.toUpperCase()==="SIGTERM",Ki=({forceKillAfterTimeout:t=!0})=>{if(t===!0)return Bi;if(!Number.isFinite(t)||t<0)throw new TypeError(`Expected the \`forceKillAfterTimeout\` option to be a non-negative integer, got \`${t}\` (${typeof t})`);return t},Wi=(t,e)=>{t.kill()&&(e.isCanceled=!0)},Yi=(t,e,r)=>{t.kill(e),r(Object.assign(new Error("Timed out"),{timedOut:!0,signal:e}))},Ji=(t,{timeout:e,killSignal:r="SIGTERM"},o)=>{if(e===0||e===void 0)return o;let n;const s=new Promise((l,a)=>{n=setTimeout(()=>{Yi(t,r,a)},e)}),i=o.finally(()=>{clearTimeout(n)});return Promise.race([s,i])},Vi=({timeout:t})=>{if(t!==void 0&&(!Number.isFinite(t)||t<0))throw new TypeError(`Expected the \`timeout\` option to be a non-negative integer, got \`${t}\` (${typeof t})`)},qi=async(t,{cleanup:e,detached:r},o)=>{if(!e||r)return o;const n=ji(()=>{t.kill()});return o.finally(()=>{n()})};function Yt(t){return t!==null&&typeof t=="object"&&typeof t.pipe=="function"}function Ao(t){return Yt(t)&&t.writable!==!1&&typeof t._write=="function"&&typeof t._writableState=="object"}const Xi=t=>t instanceof Dr&&typeof t.then=="function",Jt=(t,e,r)=>{if(typeof r=="string")return t[e].pipe(_n(r)),t;if(Ao(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(!Ao(r.stdin))throw new TypeError("The target child process's stdin must be available.");return t[e].pipe(r.stdin),r},Qi=t=>{t.stdout!==null&&(t.pipeStdout=Jt.bind(void 0,t,"stdout")),t.stderr!==null&&(t.pipeStderr=Jt.bind(void 0,t,"stderr")),t.all!==void 0&&(t.pipeAll=Jt.bind(void 0,t,"all"))};var Fe={exports:{}};const{PassThrough:Zi}=It;var ea=t=>{t={...t};const{array:e}=t;let{encoding:r}=t;const o=r==="buffer";let n=!1;e?n=!(r||o):r=r||"utf8",o&&(r=null);const s=new Zi({objectMode:n});r&&s.setEncoding(r);let i=0;const l=[];return s.on("data",a=>{l.push(a),n?i=l.length:i+=a.length}),s.getBufferedValue=()=>e?l:o?Buffer.concat(l,i):l.join(""),s.getBufferedLength=()=>i,s};const{constants:ta}=Bn,ra=It,{promisify:oa}=_r,na=ea,sa=oa(ra.pipeline);class $o extends Error{constructor(){super("maxBuffer exceeded"),this.name="MaxBufferError"}}async function Vt(t,e){if(!t)throw new Error("Expected a stream");e={maxBuffer:1/0,...e};const{maxBuffer:r}=e,o=na(e);return await new Promise((n,s)=>{const i=l=>{l&&o.getBufferedLength()<=ta.MAX_LENGTH&&(l.bufferedData=o.getBufferedValue()),s(l)};(async()=>{try{await sa(t,o),n()}catch(l){i(l)}})(),o.on("data",()=>{o.getBufferedLength()>r&&i(new $o)})}),o.getBufferedValue()}Fe.exports=Vt,Fe.exports.buffer=(t,e)=>Vt(t,{...e,encoding:"buffer"}),Fe.exports.array=(t,e)=>Vt(t,{...e,array:!0}),Fe.exports.MaxBufferError=$o;var ia=Fe.exports,ko=ve(ia);const{PassThrough:aa}=It;var ca=function(){var t=[],e=new aa({objectMode:!0});return e.setMaxListeners(0),e.add=r,e.isEmpty=o,e.on("unpipe",n),Array.prototype.slice.call(arguments).forEach(r),e;function r(s){return Array.isArray(s)?(s.forEach(r),this):(t.push(s),s.once("end",n.bind(null,s)),s.once("error",e.emit.bind(e,"error")),s.pipe(e,{end:!1}),this)}function o(){return t.length==0}function n(s){t=t.filter(function(i){return i!==s}),!t.length&&e.readable&&e.end()}},la=ve(ca);const So=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:(So(t),jn(e)),da=t=>{const e=ua(t);if(Yt(e))throw new TypeError("The `input` option cannot be a stream in sync mode");return e},ma=({input:t,inputFile:e})=>typeof e!="string"?t:(So(t),Tn(e)),fa=(t,e)=>{const r=ma(e);r!==void 0&&(Yt(r)?r.pipe(t.stdin):t.stdin.end(r))},pa=(t,{all:e})=>{if(!e||!t.stdout&&!t.stderr)return;const r=la();return t.stdout&&r.add(t.stdout),t.stderr&&r.add(t.stderr),r},qt=async(t,e)=>{if(!(!t||e===void 0)){t.destroy();try{return await e}catch(r){return r.bufferedData}}},Xt=(t,{encoding:e,buffer:r,maxBuffer:o})=>{if(!(!t||!r))return e?ko(t,{encoding:e,maxBuffer:o}):ko.buffer(t,{maxBuffer:o})},ha=async({stdout:t,stderr:e,all:r},{encoding:o,buffer:n,maxBuffer:s},i)=>{const l=Xt(t,{encoding:o,buffer:n,maxBuffer:s}),a=Xt(e,{encoding:o,buffer:n,maxBuffer:s}),d=Xt(r,{encoding:o,buffer:n,maxBuffer:s*2});try{return await Promise.all([i,l,a,d])}catch(c){return Promise.all([{error:c,signal:c.signal,timedOut:c.timedOut},qt(t,l),qt(e,a),qt(r,d)])}},ga=(async()=>{})().constructor.prototype,ya=["then","catch","finally"].map(t=>[t,Reflect.getOwnPropertyDescriptor(ga,t)]),xo=(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)})}),Io=(t,e=[])=>Array.isArray(e)?[t,...e]:[t],va=/^[\w.-]+$/,ba=/"/g,Ca=t=>typeof t!="string"||va.test(t)?t:`"${t.replace(ba,'\\"')}"`,Mo=(t,e)=>Io(t,e).join(" "),Ro=(t,e)=>Io(t,e).map(r=>Ca(r)).join(" "),Do=/ +/g,Oo=t=>{const e=[];for(const r of t.trim().split(Do)){const o=e[e.length-1];o&&o.endsWith("\\")?e[e.length-1]=`${o.slice(0,-1)} ${r}`:e.push(r)}return e},No=t=>{const e=typeof t;if(e==="string")return t;if(e==="number")return String(t);if(e==="object"&&t!==null&&!(t instanceof Dr)&&"stdout"in t){const r=typeof t.stdout;if(r==="string")return t.stdout;if(Rr.isBuffer(t.stdout))return t.stdout.toString();throw new TypeError(`Unexpected "${r}" stdout in template expression`)}throw new TypeError(`Unexpected "${e}" in template expression`)},Fo=(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(Do).filter(Boolean),l=Fo(r,i,s.startsWith(" "));if(o===e.length)return l;const a=e[o],d=Array.isArray(a)?a.map(c=>No(c)):[No(a)];return Fo(l,d,s.endsWith(" "))},Lo=(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,at=(t,e)=>String(t).padStart(e,"0"),Aa=()=>{const t=new Date;return`${at(t.getHours(),2)}:${at(t.getMinutes(),2)}:${at(t.getSeconds(),2)}.${at(t.getMilliseconds(),3)}`},_o=(t,{verbose:e})=>{e&&se.stderr.write(`[${Aa()}] ${t}
|
|
8
|
+
`)},$a=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},To=(t,e,r={})=>{const o=ii._parse(t,e,r);return t=o.command,e=o.args,r=o.options,r={maxBuffer:$a,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=bo(r),se.platform==="win32"&&fe.basename(t,".exe")==="cmd"&&e.unshift("/q"),{file:t,args:e,options:r,parsed:o}},Le=(t,e,r)=>typeof e!="string"&&!Rr.isBuffer(e)?r===void 0?void 0:"":t.stripFinalNewline?ai(e):e;function S(t,e,r){const o=To(t,e,r),n=Mo(t,e),s=Ro(t,e);_o(s,o.options),Vi(o.options);let i;try{i=xt.spawn(o.file,o.args,o.options)}catch(p){const h=new xt.ChildProcess,y=Promise.reject(ot({error:p,stdout:"",stderr:"",all:"",command:n,escapedCommand:s,parsed:o,timedOut:!1,isCanceled:!1,killed:!1}));return xo(h,y),h}const l=wa(i),a=Ji(i,o.options,l),d=qi(i,o.options,a),c={isCanceled:!1};i.kill=Gi.bind(null,i.kill.bind(i)),i.cancel=Wi.bind(null,i,c);const f=go(async()=>{const[{error:p,exitCode:h,signal:y,timedOut:g},v,C,E]=await ha(i,o.options,d),k=Le(o.options,v),P=Le(o.options,C),A=Le(o.options,E);if(p||h!==0||y!==null){const M=ot({error:p,exitCode:h,signal:y,stdout:k,stderr:P,all:A,command:n,escapedCommand:s,parsed:o,timedOut:g,isCanceled:c.isCanceled||(o.options.signal?o.options.signal.aborted:!1),killed:i.killed});if(!o.options.reject)return M;throw M}return{command:n,escapedCommand:s,exitCode:0,stdout:k,stderr:P,all:A,failed:!1,timedOut:!1,isCanceled:!1,killed:!1}});return fa(i,o.options),i.all=pa(i,o.options),Qi(i),xo(i,f),i}function Qt(t,e,r){const o=To(t,e,r),n=Mo(t,e),s=Ro(t,e);_o(s,o.options);const i=da(o.options);let l;try{l=xt.spawnSync(o.file,o.args,{...o.options,input:i})}catch(c){throw ot({error:c,stdout:"",stderr:"",all:"",command:n,escapedCommand:s,parsed:o,timedOut:!1,isCanceled:!1,killed:!1})}const a=Le(o.options,l.stdout,l.error),d=Le(o.options,l.stderr,l.error);if(l.error||l.status!==0||l.signal!==null){const c=ot({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"}:{},jo=(t={})=>({preferLocal:!0,...Sa(t),...t});function Bo(t){function e(r,...o){if(!Array.isArray(r))return Bo({...t,...r});const[n,...s]=Lo(r,o);return S(n,s,jo(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]=Lo(r,o);return Qt(n,s,jo(t))},e}const xa=Bo();function Ia(t,e){const[r,...o]=Oo(t);return S(r,o,e)}function Ma(t,e){const[r,...o]=Oo(t);return Qt(r,o,e)}function Ra(t,e,r={}){e&&!Array.isArray(e)&&typeof e=="object"&&(r=e,e=[]);const o=Di(r),n=se.execArgv.filter(l=>!l.startsWith("--inspect")),{nodePath:s=se.execPath,nodeOptions:i=n}=r;return 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:Qt,$:xa,execaCommand:Ia,execaCommandSync:Ma,execaNode:Ra});const{hasOwnProperty:Zt}=Object.prototype,ct=typeof process<"u"&&process.platform==="win32"?`\r
|
|
9
9
|
`:`
|
|
10
|
-
`,
|
|
10
|
+
`,er=(t,e)=>{const r=[];let o="";typeof e=="string"?e={section:e,whitespace:!1}:(e=e||Object.create(null),e.whitespace=e.whitespace===!0);const n=e.whitespace?" = ":"=";for(const s of Object.keys(t)){const i=t[s];if(i&&Array.isArray(i))for(const l of i)o+=Ae(s+"[]")+n+Ae(l)+ct;else i&&typeof i=="object"?r.push(s):o+=Ae(s)+n+Ae(i)+ct}e.section&&o.length&&(o="["+Ae(e.section)+"]"+ct+o);for(const s of r){const i=Go(s).join("\\."),l=(e.section?e.section+".":"")+i,{whitespace:a}=e,d=er(t[s],{section:l,whitespace:a});o.length&&d.length&&(o+=ct),o+=d}return o},Go=t=>t.replace(/\1/g,"LITERAL\\1LITERAL").replace(/\\\./g,"").split(/\./).map(e=>e.replace(/\1/g,"\\.").replace(/\2LITERAL\\1LITERAL\2/g,"")),Ho=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=lt(a[1]),o==="__proto__"){r=Object.create(null);continue}r=e[o]=e[o]||Object.create(null);continue}const d=lt(a[2]),c=d.length>2&&d.slice(-2)==="[]",u=c?d.slice(0,-2):d;if(u==="__proto__")continue;const f=a[3]?lt(a[4]):!0,p=f==="true"||f==="false"||f==="null"?JSON.parse(f):f;c&&(Zt.call(r,u)?Array.isArray(r[u])||(r[u]=[r[u]]):r[u]=[]),Array.isArray(r[u])?r[u].push(p):r[u]=p}const i=[];for(const l of Object.keys(e)){if(!Zt.call(e,l)||typeof e[l]!="object"||Array.isArray(e[l]))continue;const a=Go(l);r=e;const d=a.pop(),c=d.replace(/\\\./g,".");for(const u of a)u!=="__proto__"&&((!Zt.call(r,u)||typeof r[u]!="object")&&(r[u]=Object.create(null)),r=r[u]);r===e&&c===d||(r[c]=e[l],i.push(l))}for(const l of i)delete e[l];return e},Uo=t=>t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'"),Ae=t=>typeof t!="string"||t.match(/[=\r\n]/)||t.match(/^\[/)||t.length>1&&Uo(t)||t!==t.trim()?JSON.stringify(t):t.split(";").join("\\;").split("#").join("\\#"),lt=(t,e)=>{if(t=(t||"").trim(),Uo(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:Ho,decode:Ho,stringify:er,encode:er,safe:Ae,unsafe:lt},$e=ve(Oa);class w extends Error{}const tr=" ",de=t=>{t instanceof Error&&(t instanceof w||(t.stack&&console.error(b.dim(t.stack.split(`
|
|
11
11
|
`).slice(1).join(`
|
|
12
12
|
`))),console.error(`
|
|
13
|
-
${
|
|
14
|
-
${er}Please open a Bug report with the information above:`),console.error(`${er}https://github.com/tak-bro/aicommit2/issues/new/choose`)))},Ho=t=>N.lstat(t).then(()=>!0,()=>!1),Uo=async t=>{try{await N.mkdir(t,{recursive:!0})}catch(e){if(e.code!=="EEXIST")throw e}},lt=t=>t&&`${t[0].toUpperCase()}${t.slice(1)}`,ut=(t,e)=>{const r=Math.ceil(t),o=Math.floor(e);return Math.floor(Math.random()*(o-r+1))+r},Da=(t,e)=>t.disabled&&!e.disabled?1:!t.disabled&&e.disabled?-1:0,dt=t=>t.reduce((e,r)=>Array.isArray(r)?e.concat(dt(r)):e.concat(r),[]),zo=(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)},La=t=>{const e=t%360,r=65+t%15,o=45+t%10;return`hsl(${e}, ${r}%, ${o}%)`},Na=t=>{const[e,r,o]=t.match(/\d+/g).map((u,m)=>m===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 m=Math.round((u+i)*255).toString(16);return m.length===1?"0"+m:m};return`#${c(l)}${c(a)}${c(d)}`},_a=t=>{const e=Fa(t),r=La(e);return{primary:Na(r),secondary:"#FFFFFF"}},Ko=t=>{try{return{ok:!0,data:JSON.parse(t)}}catch(e){return{ok:!1,error:e}}},mt=t=>{if(!t||typeof t!="string")return"";if(x.isAbsolute(t))return x.resolve(t);if(_e){const e=x.dirname(_e),r=x.join(e,t);return x.resolve(r)}else return""},Ta=["","conventional","gitmoji"],tr="http://localhost:11434",{hasOwnProperty:ja}=Object.prototype,rr=(t,e)=>ja.call(t,e),$e=["OPENAI","OLLAMA","HUGGINGFACE","GEMINI","ANTHROPIC","MISTRAL","CODESTRAL","COHERE","GROQ","PERPLEXITY","DEEPSEEK","GITHUB_MODELS","BEDROCK"],Wo=t=>{const e=Re.platform(),r=Re.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},Ba=x.join(Wo("config"),"aicommit2"),se=x.join(Wo("state"),"aicommit2","logs"),Yo=x.join(Ba,"config.ini"),Jo=x.join(se,"aicommit2-%DATE%.log"),Vo=x.join(se,"exceptions-%DATE%.log"),Ga=t=>{const e=Object.keys(t),r=new Set([...$e,...e.filter(o=>/^[A-Z][A-Z0-9_]*$/.test(o))]);return Array.from(r)},O=(t,e,r)=>{if(!e)throw new w(`Invalid config property ${t}: ${r}`)},le=(t,e=!1)=>r=>typeof r=="boolean"?r:r==null?e:(O(t,/^(?:true|false)$/.test(r),"Must be a boolean(true or false)"),r==="true"),f={systemPrompt(t){return t||""},systemPromptPath(t){return t||""},codeReviewPromptPath(t){return t||""},timeout(t){if(!t)return 6e4;O("timeout",/^\d+$/.test(t),"Must be an integer");const e=Number(t);return O("timeout",e>=500,"Must be greater than 500ms"),e},temperature(t){if(!t)return .7;O("temperature",/^(2|\d)(\.\d{1,2})?$/.test(t),"Must be decimal between 0 and 2");const e=Number(t);return O("temperature",e>0,"Must be greater than 0"),O("temperature",e<=2,"Must be less than or equal to 2"),e},maxTokens(t){return t?(O("maxTokens",/^\d+$/.test(t),"Must be an integer"),Number(t)):8192},logLevel(t){return t?(O("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||Jo},exceptionLogFilePath(t){return t||Vo},locale(t){return t?(O("locale",t,"Cannot be empty"),O("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;O("generate",/^\d+$/.test(t),"Must be an integer");const e=Number(t);return O("generate",e>0,"Must be greater than 0"),O("generate",e<=5,"Must be less or equal to 5"),e},type(t){return t?(O("type",Ta.includes(t),"Invalid commit type"),t):"conventional"},maxLength(t){if(!t)return 50;O("maxLength",/^\d+$/.test(t),"Must be an integer");const e=Number(t);return O("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;O("topP",/^(1|\d)(\.\d{1,2})?$/.test(t),"Must be decimal between 0 and 1");const e=Number(t);return O("topP",e>0,"Must be greater than 0"),O("topP",e<=1,"Must be less than or equal to 1"),e},logging:le("logging",!0),includeBody:le("includeBody"),codeReview:le("codeReview"),disabled:le("disabled"),watchMode:le("watchMode"),forceGit:le("forceGit"),disableLowerCase:le("disableLowerCase")},Ne={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?(O("OPENAI.url",/^https?:\/\//.test(t),"Must be a valid URL"),t):"https://api.openai.com",path:t=>t||"/v1/chat/completions",proxy:t=>t||"",topP:f.topP,systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,timeout:f.timeout,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode,disableLowerCase:f.disableLowerCase},HUGGINGFACE:{cookie:t=>t||"",model:t=>t?(typeof t=="string"?t?.split(","):t).map(r=>r.trim()).filter(r=>!!r&&r.length>0):["CohereForAI/c4ai-command-r-plus"],systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,timeout:f.timeout,temperature:f.temperature,maxTokens:f.maxTokens,topP:f.topP,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode,disableLowerCase:f.disableLowerCase},GEMINI:{key:t=>t||"",envKey:t=>t||"",model:t=>t?(typeof t=="string"?t?.split(","):t).map(r=>r.trim()).filter(r=>!!r&&r.length>0):["gemini-2.5-flash"],systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,timeout:f.timeout,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,topP:f.topP,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode,disableLowerCase:f.disableLowerCase},ANTHROPIC:{key:t=>t||"",envKey:t=>t||"",model:t=>t?(typeof t=="string"?t?.split(","):t).map(r=>r.trim()).filter(r=>!!r&&r.length>0):["claude-3-5-haiku-20241022"],systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,timeout:f.timeout,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,topP:f.topP,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode,disableLowerCase:f.disableLowerCase},MISTRAL:{key:t=>t||"",envKey:t=>t||"",model:t=>t?(typeof t=="string"?t?.split(","):t).map(r=>r.trim()).filter(r=>!!r&&r.length>0):["mistral-small-latest"],systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,timeout:f.timeout,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,topP:f.topP,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode,disableLowerCase:f.disableLowerCase},CODESTRAL:{key:t=>t||"",envKey:t=>t||"",model:t=>t?(typeof t=="string"?t?.split(","):t).map(r=>r.trim()).filter(r=>!!r&&r.length>0):["codestral-latest"],topP:f.topP,systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,timeout:f.timeout,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode,disableLowerCase:f.disableLowerCase},OLLAMA:{model:t=>t?(typeof t=="string"?t?.split(","):t).map(r=>r.trim()).filter(r=>!!r&&r.length>0):[],host:t=>t?(O("OLLAMA.host",/^https?:\/\//.test(t),"Must be a valid URL"),t):tr,timeout:t=>{if(!t)return 1e5;O("OLLAMA.timeout",/^\d+$/.test(t),"Must be an integer");const e=Number(t);return O("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;O("OLLAMA.numCtx",/^\d+$/.test(t),"Must be an integer");const e=Number(t);return O("OLLAMA.numCtx",e>=2048,"Must be greater than 2048"),e},systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,topP:f.topP,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode,disableLowerCase:f.disableLowerCase},COHERE:{key:t=>t||"",envKey:t=>t||"",url:t=>t?(O("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:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,timeout:f.timeout,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,topP:f.topP,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode,disableLowerCase:f.disableLowerCase},GROQ:{key:t=>t||"",envKey:t=>t||"",model:t=>t?(typeof t=="string"?t?.split(","):t).map(r=>r.trim()).filter(r=>!!r&&r.length>0):["llama-3.3-70b-versatile"],systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,timeout:f.timeout,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,topP:f.topP,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode,disableLowerCase:f.disableLowerCase},PERPLEXITY:{key:t=>t||"",envKey:t=>t||"",model:t=>t?(typeof t=="string"?t?.split(","):t).map(r=>r.trim()).filter(r=>!!r&&r.length>0):["sonar"],topP:f.topP,systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,timeout:f.timeout,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode,disableLowerCase:f.disableLowerCase},DEEPSEEK:{key:t=>t||"",envKey:t=>t||"",model:t=>t?(typeof t=="string"?t?.split(","):t).map(r=>r.trim()).filter(r=>!!r&&r.length>0):["deepseek-coder"],topP:f.topP,systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,timeout:f.timeout,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode,disableLowerCase:f.disableLowerCase},GITHUB_MODELS:{key:t=>t||"",envKey:t=>t||"",model:t=>t?(typeof t=="string"?t?.split(","):t).map(r=>r.trim()).filter(r=>!!r&&r.length>0):["gpt-4o-mini"],systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,timeout:f.timeout,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,topP:f.topP,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode,disableLowerCase:f.disableLowerCase},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
|
+
${tr}${b.dim(`aicommit2 v${Qr}`)}`),console.error(`
|
|
14
|
+
${tr}Please open a Bug report with the information above:`),console.error(`${tr}https://github.com/tak-bro/aicommit2/issues/new/choose`)))},zo=t=>L.lstat(t).then(()=>!0,()=>!1),Ko=async t=>{try{await L.mkdir(t,{recursive:!0})}catch(e){if(e.code!=="EEXIST")throw e}},ut=t=>t&&`${t[0].toUpperCase()}${t.slice(1)}`,dt=(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,mt=t=>t.reduce((e,r)=>Array.isArray(r)?e.concat(mt(r)):e.concat(r),[]),Wo=(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)},La=t=>{const e=t%360,r=65+t%15,o=45+t%10;return`hsl(${e}, ${r}%, ${o}%)`},_a=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=La(e);return{primary:_a(r),secondary:"#FFFFFF"}},Yo=t=>{try{return{ok:!0,data:JSON.parse(t)}}catch(e){return{ok:!1,error:e}}},ft=t=>{if(!t||typeof t!="string")return"";if(I.isAbsolute(t))return I.resolve(t);if(Te){const e=I.dirname(Te),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),ke=["OPENAI","OLLAMA","HUGGINGFACE","GEMINI","ANTHROPIC","MISTRAL","CODESTRAL","COHERE","GROQ","PERPLEXITY","DEEPSEEK","GITHUB_MODELS","BEDROCK"],Jo=t=>{const e=De.platform(),r=De.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(Jo("config"),"aicommit2"),ie=I.join(Jo("state"),"aicommit2","logs"),Vo=I.join(Ga,"config.ini"),qo=I.join(ie,"aicommit2-%DATE%.log"),Xo=I.join(ie,"exceptions-%DATE%.log"),Ha=t=>{const e=Object.keys(t),r=new Set([...ke,...e.filter(o=>/^[A-Z][A-Z0-9_]*$/.test(o))]);return Array.from(r)},R=(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:(R(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;R("timeout",/^\d+$/.test(t),"Must be an integer");const e=Number(t);return R("timeout",e>=500,"Must be greater than 500ms"),e},temperature(t){if(!t)return .7;R("temperature",/^(2|\d)(\.\d{1,2})?$/.test(t),"Must be decimal between 0 and 2");const e=Number(t);return R("temperature",e>0,"Must be greater than 0"),R("temperature",e<=2,"Must be less than or equal to 2"),e},maxTokens(t){return t?(R("maxTokens",/^\d+$/.test(t),"Must be an integer"),Number(t)):8192},logLevel(t){return t?(R("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||Xo},locale(t){return t?(R("locale",t,"Cannot be empty"),R("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;R("generate",/^\d+$/.test(t),"Must be an integer");const e=Number(t);return R("generate",e>0,"Must be greater than 0"),R("generate",e<=5,"Must be less or equal to 5"),e},type(t){return t?(R("type",ja.includes(t),"Invalid commit type"),t):"conventional"},maxLength(t){if(!t)return 50;R("maxLength",/^\d+$/.test(t),"Must be an integer");const e=Number(t);return R("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;R("topP",/^(1|\d)(\.\d{1,2})?$/.test(t),"Must be decimal between 0 and 1");const e=Number(t);return R("topP",e>0,"Must be greater than 0"),R("topP",e<=1,"Must be less than or equal to 1"),e},logging:ue("logging",!0),includeBody:ue("includeBody"),codeReview:ue("codeReview"),disabled:ue("disabled"),watchMode:ue("watchMode"),forceGit:ue("forceGit"),disableLowerCase:ue("disableLowerCase")},_e={OPENAI:{key: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?(R("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?(R("OLLAMA.host",/^https?:\/\//.test(t),"Must be a valid URL"),t):rr,timeout:t=>{if(!t)return 1e5;R("OLLAMA.timeout",/^\d+$/.test(t),"Must be an integer");const e=Number(t);return R("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;R("OLLAMA.numCtx",/^\d+$/.test(t),"Must be an integer");const e=Number(t);return R("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?(R("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:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,timeout:f.timeout,temperature:t=>{if(!t)return;O("temperature",/^(2|\d)(\.\d{1,2})?$/.test(t),"Must be decimal between 0 and 2");const e=Number(t);return O("temperature",e>0,"Must be greater than 0"),O("temperature",e<=2,"Must be less than or equal to 2"),e},maxTokens:t=>{if(t)return O("maxTokens",/^\d+$/.test(t),"Must be an integer"),Number(t)},logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,topP:t=>{if(!t)return;O("topP",/^(1|\d)(\.\d{1,2})?$/.test(t),"Must be decimal between 0 and 1");const e=Number(t);return O("topP",e>0,"Must be greater than 0"),O("topP",e<=1,"Must be less than or equal to 1"),e},codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode,disableLowerCase:f.disableLowerCase,inferenceParameters:t=>{if(!t)return{};if(typeof t=="object")return t;try{const e=JSON.parse(t);return O("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 _e;const Ha=(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 Ne?(e[s]||(e[s]={}),e[s][i]=n):e[o]=n}return e},Ua=()=>{const t=Re.homedir(),e=process.env.AICOMMIT_CONFIG_PATH,r=Yo,o=x.join(t,".aicommit2");return[e,r,o].filter(n=>!!n)},Ae=async()=>{const t=Ua();for(const e of t)if(await Ho(e))return e;return Yo},Te=async()=>{const t=await Ae();_e=t;try{const e=await N.readFile(t,"utf8");return Pe.parse(e)}catch(e){return e.code==="ENOENT"?(_e=void 0,{}):(console.error(`Error reading config file ${t}:`,e),_e=void 0,{})}},pe=async(t,e=[])=>{const r=await Te(),o=Ha(e),n={...t,...o},s={},i=Ga(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 m=u.map(p=>p?process.env[p]:void 0).find(p=>typeof p=="string"&&p.length>0);m&&(l[d]={key:m})}const a=(d,c)=>{const u=n[`${d}.${c}`]??n[d]?.[c],m=l[d]?.[c],p=r[d]?.[c],h=n[c]??r[c];return u!==void 0?u:m!==void 0?m:p!==void 0?p:h};for(const[d,c]of Object.entries(f)){const u=n[d]??r[d];s[d]=c(u)}for(const d of i){s[d]={};const c=Ne[d]||ft(d);for(const[u,m]of Object.entries(c)){const p=a(d,u);s[d][u]=m(p)}}return s},or=async t=>{const e=await Te();for(const[n,s]of t){const[i,l]=n.split(".");if(!l){const c=f[n];if(!c)throw new w(`Invalid config property: ${n}`);e[n]=c(s);continue}if(e[i]||(e[i]={}),$e.includes(i)){const c=Ne[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=ft(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 Ae(),o=x.dirname(r);await N.mkdir(o,{recursive:!0}),await N.writeFile(r,Pe.stringify(e),"utf8")},za=async t=>{const e=await Te();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(m=>m.trim()).filter(m=>!!m):s;e[i][l]=dt([...c,...u]);continue}if(a&&a.compatible===!0){a||(e[i]={});const c=ft(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 Ne){a||(e[i]={});const c=Ne[i][l];if(!c)throw new w(`Invalid config property: ${n}`);e[i][l]=c(s)}else{const c=ft(i);if(!c[l])throw new w(`Invalid config property: ${n}`);e[i]||(e[i]={}),e[i][l]=c[l](s)}}const r=await Ae(),o=x.dirname(r);await N.mkdir(o,{recursive:!0}),await N.writeFile(r,Pe.stringify(e),"utf8")},Ka=async()=>{const t=await Te();console.log(Pe.stringify(t))},Wa=async()=>{console.log(await Ae())},ft=t=>({compatible:le("compatible"),stream:le("stream"),url:e=>e?(O(`${t}.url`,/^https?:\/\//.test(e),"Must be a valid URL"),e):"",path:e=>e||"",key:e=>e||"",envKey:e=>e||"",model:e=>e?(typeof e=="string"?e?.split(","):e).map(o=>o.trim()).filter(o=>!!o&&o.length>0):[],systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,timeout:f.timeout,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,topP:f.topP,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode,disableLowerCase:f.disableLowerCase}),ie=t=>typeof t=="string"&&t.trim().length>0,pt=t=>(Array.isArray(t.model)?t.model:ie(t.model)?[t.model.trim()]:[]).length>0,qo=t=>{const e=ie(t.key),r=ie(t.region)||ie(process.env.AWS_REGION)||ie(process.env.AWS_DEFAULT_REGION),o=ie(t.profile)||ie(process.env.AWS_PROFILE),n=ie(t.accessKeyId)&&ie(t.secretAccessKey)||ie(process.env.AWS_ACCESS_KEY_ID)&&ie(process.env.AWS_SECRET_ACCESS_KEY);return r&&(e||o||n)},Xo=(t,e)=>Object.entries(t).map(([r,o])=>[r,o]).filter(([r,o])=>!o.disabled).filter(([r,o])=>$e.includes(r)||o.compatible===!0).filter(([r,o])=>{switch(e){case"commit":return r==="OLLAMA"?!!o&&pt(o):r==="HUGGINGFACE"?!!o&&!!o.cookie:r==="BEDROCK"?pt(o)&&qo(o):!!o.key&&o.key.length>0;case"review":const n=t.codeReview||o.codeReview;return r==="OLLAMA"?!!o&&pt(o)&&n:r==="HUGGINGFACE"?!!o&&!!o.cookie&&n:r==="BEDROCK"?pt(o)&&qo(o)&&n:!!o.key&&o.key.length>0&&n}}).map(([r])=>r);class q{static create(e,r){return new e(r)}}const je=new Map,he=(t,e,r)=>{const o=Gr(0).update(e).digest("hex").substring(0,8),n=`${t}_${o}_${r}`;if(je.has(n))return je.get(n);const s=new Date,i=Va(s,t,e,r),l=`${se}/${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,...m})=>m&&Object.keys(m).length>0?`[${d}] ${c}: ${u} ${JSON.stringify(m,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(""),je.set(n,a),a},Ya=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},X=(t,e,r,o,n,s,i=!0)=>{if(!i)return;const l=he(r,t,e);l.info(`Making request to ${r} API with model: ${o}`),l.info(`Request URL: ${n}`),l.info("Request headers:",Ya(s))},re=(t,e,r,o,n=!0)=>{if(!n)return;he(r,t,e).info("Request payload:",o)},Q=(t,e,r,o,n,s=!0)=>{if(!s)return;const i=he(r,t,e);i.info("System prompt:",{prompt:o}),i.info("User prompt:",{prompt:n})},K=(t,e,r,o,n=!0)=>{if(!n)return;he(r,t,e).info("Response received:",o)},B=(t,e,r,o,n=!0)=>{if(!n)return;he(r,t,e).error("API request failed:",o)},W=(t,e,r,o,n,s=!0)=>{if(!s)return;const i=he(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 ===")},Ja=(t,e,r,o,n,s,i,l=!0)=>{if(!l)return;const a=he(r,t,e);i?a.error(`Request failed after ${s}ms:`,{error:i}):(a.info(`Request completed in ${s}ms`),a.info("Response:",{response:n})),W(t,e,r,s,n,l)},Va=(t,e,r,o)=>{const{year:n,month:s,day:i,hours:l,minutes:a,seconds:d}=qa(t),u=Gr(0).update(r).digest("hex").substring(0,8),m=e.toLowerCase().replace(/[^a-z0-9]/g,"").substring(0,20);return o==="review"?`${n}-${s}-${i}_${l}-${a}-${d}_${u}_${m}_review.log`:`${n}-${s}-${i}_${l}-${a}-${d}_${u}_${m}_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}},nr=()=>{for(const[t,e]of je.entries())try{e.close()}catch(r){console.error(`Failed to close logger ${t}:`,r)}je.clear()};process.on("exit",nr),process.on("SIGINT",()=>{nr(),process.exit(0)}),process.on("SIGTERM",()=>{nr(),process.exit(0)});let ht,Qo="info";async function Xa(t){if(ht){console.warn("Logger already initialized. Skipping re-initialization.");return}const e=t?.logLevel||"info";Qo=e;const r=t?.logFilePath||Jo,o=t?.exceptionLogFilePath||Vo,n=t?.logging??!0;await Uo(x.dirname(r)),await Uo(x.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})),ht=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 ke=new Proxy({},{get:(t,e,r)=>{if(!ht)throw new Error("Logger not initialized. Call initializeLogger() first.");return Reflect.get(ht,e,r)}});function gt(){const t=H.config.npm.levels;return(t[Qo]??t.info)>=t.verbose}class Z{constructor(e){this.handleError$=r=>{const o=this.getDetailedErrorMessage(r),n=r.status?`HTTP ${r.status}: ${o}`:o;if(this.params.config.logging){const s=this.params.stagedDiff.diff,i=this.serviceName.replace(/\[|\]/g,"").trim();Ja(s,"commit",i,"Error occurred","",void 0,n)}return ke.error(`${this.errorPrefix} ${n}`),r.stack&&ke.error(` ${r.stack}`),r.content&&ke.error(` Problematic content: ${r.content}`),r.originalError&&ke.error(` Original error: ${r.originalError}`),It({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=Ko(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;R("temperature",/^(2|\d)(\.\d{1,2})?$/.test(t),"Must be decimal between 0 and 2");const e=Number(t);return R("temperature",e>0,"Must be greater than 0"),R("temperature",e<=2,"Must be less than or equal to 2"),e},maxTokens:t=>{if(t)return R("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;R("topP",/^(1|\d)(\.\d{1,2})?$/.test(t),"Must be decimal between 0 and 1");const e=Number(t);return R("topP",e>0,"Must be greater than 0"),R("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 R("BEDROCK.inferenceParameters",typeof e=="object"&&e!==null&&!Array.isArray(e),"Must be a valid JSON object"),e}catch(e){throw new w(`Invalid BEDROCK.inferenceParameters: Must be valid JSON. Error: ${e.message}`)}}}};let Te;const Ua=(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 _e?(e[s]||(e[s]={}),e[s][i]=n):e[o]=n}return e},za=()=>{const t=De.homedir(),e=process.env.AICOMMIT_CONFIG_PATH,r=Vo,o=I.join(t,".aicommit2");return[e,r,o].filter(n=>!!n)},Se=async()=>{const t=za();for(const e of t)if(await zo(e))return e;return Vo},je=async()=>{const t=await Se();Te=t;try{const e=await L.readFile(t,"utf8");return $e.parse(e)}catch(e){return e.code==="ENOENT"?(Te=void 0,{}):(console.error(`Error reading config file ${t}:`,e),Te=void 0,{})}},he=async(t,e=[])=>{const r=await je(),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=_e[d]||pt(d);for(const[u,f]of Object.entries(c)){const p=a(d,u);s[d][u]=f(p)}}return s},nr=async t=>{const e=await je();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]={}),ke.includes(i)){const c=_e[i][l];if(!c)throw new w(`Invalid config property: ${n}`);e[i][l]=c(s);continue}if(!/^[A-Z][A-Z0-9_]*$/.test(i))throw new w(`Invalid service name: ${i}. Service names must be uppercase letters, numbers, and underscores.`);const d=pt(i);if(!d[l])throw new w(`Invalid config property for custom service: ${n}`);try{e[i][l]=d[l](s)}catch(c){throw c instanceof w?c:new w(`Invalid value for ${n}: ${c.message}`)}}const r=await Se(),o=I.dirname(r);await L.mkdir(o,{recursive:!0}),await L.writeFile(r,$e.stringify(e),"utf8")},Ka=async t=>{const e=await je();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]=mt([...c,...u]);continue}if(a&&a.compatible===!0){a||(e[i]={});const c=pt(i);if(!c[l])throw new w(`Invalid config property: ${n}`);try{e[i][l]=c[l](s)}catch(u){throw u instanceof w?u:new w(`Invalid value for ${n}: ${u.message}`)}continue}if(i in _e){a||(e[i]={});const c=_e[i][l];if(!c)throw new w(`Invalid config property: ${n}`);e[i][l]=c(s)}else{const c=pt(i);if(!c[l])throw new w(`Invalid config property: ${n}`);e[i]||(e[i]={}),e[i][l]=c[l](s)}}const r=await Se(),o=I.dirname(r);await L.mkdir(o,{recursive:!0}),await L.writeFile(r,$e.stringify(e),"utf8")},Wa=async()=>{const t=await je();console.log($e.stringify(t))},Ya=async()=>{console.log(await Se())},pt=t=>({compatible:ue("compatible"),stream:ue("stream"),url:e=>e?(R(`${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,ht=t=>(Array.isArray(t.model)?t.model:ae(t.model)?[t.model.trim()]:[]).length>0,Qo=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)},Zo=(t,e)=>Object.entries(t).map(([r,o])=>[r,o]).filter(([r,o])=>!o.disabled).filter(([r,o])=>ke.includes(r)||o.compatible===!0).filter(([r,o])=>{switch(e){case"commit":return r==="OLLAMA"?!!o&&ht(o):r==="HUGGINGFACE"?!!o&&!!o.cookie:r==="BEDROCK"?ht(o)&&Qo(o):!!o.key&&o.key.length>0;case"review":const n=t.codeReview||o.codeReview;return r==="OLLAMA"?!!o&&ht(o)&&n:r==="HUGGINGFACE"?!!o&&!!o.cookie&&n:r==="BEDROCK"?ht(o)&&Qo(o)&&n:!!o.key&&o.key.length>0&&n}}).map(([r])=>r);class q{static create(e,r){return new e(r)}}const Be=new Map,ge=(t,e,r)=>{const o=Ur(0).update(e).digest("hex").substring(0,8),n=`${t}_${o}_${r}`;if(Be.has(n))return Be.get(n);const s=new Date,i=qa(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(""),Be.set(n,a),a},Ja=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},X=(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:",Ja(s))},oe=(t,e,r,o,n=!0)=>{if(!n)return;ge(r,t,e).info("Request payload:",o)},Q=(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})},K=(t,e,r,o,n=!0)=>{if(!n)return;ge(r,t,e).info("Response received:",o)},B=(t,e,r,o,n=!0)=>{if(!n)return;ge(r,t,e).error("API request failed:",o)},W=(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 ===")},Va=(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})),W(t,e,r,s,n,l)},qa=(t,e,r,o)=>{const{year:n,month:s,day:i,hours:l,minutes:a,seconds:d}=Xa(t),u=Ur(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`},Xa=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}},sr=()=>{for(const[t,e]of Be.entries())try{e.close()}catch(r){console.error(`Failed to close logger ${t}:`,r)}Be.clear()};process.on("exit",sr),process.on("SIGINT",()=>{sr(),process.exit(0)}),process.on("SIGTERM",()=>{sr(),process.exit(0)});let gt,en="info";async function Qa(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||Xo,n=t?.logging??!0;await Ko(I.dirname(r)),await Ko(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 xe=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 Z{constructor(e){this.handleError$=r=>{const o=this.getDetailedErrorMessage(r),n=r.status?`HTTP ${r.status}: ${o}`:o;if(this.params.config.logging){const s=this.params.stagedDiff.diff,i=this.serviceName.replace(/\[|\]/g,"").trim();Va(s,"commit",i,"Error occurred","",void 0,n)}return xe.error(`${this.errorPrefix} ${n}`),r.stack&&xe.error(` ${r.stack}`),r.content&&xe.error(` Problematic content: ${r.content}`),r.originalError&&xe.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=Yo(s);if(!i.ok){const u=new Error("Failed to parse AI response as JSON");throw u.name="JsonParseError",u.content=s,u.originalError=i.error,u}const l=i.data,a=Array.isArray(l)?l:[l];if(!a.length||!a.every(u=>typeof u.subject=="string")){const u=new Error("AI response contained malformed commit message data.");throw u.name="MalformedCommitMessage",u.content=e,u}const c=a.map(u=>this.extractMessageAsType(u,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(
|
|
23
|
+
${u.footer}`:""}`})).slice(0,o);if(this.isLoggingEnabled()){const u=c.map(f=>f.title).join(", ");xe.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:`${Wo(e)}...`,value:e}]}catch{return[]}return e.map(r=>{try{return{title:`${Wo(r)}...`,value:r}}catch{return{title:"",value:""}}})}isLoggingEnabled(){return this.params.config.logging&&!!this.logSessionId}}const Y={locale:"en",maxLength:50,type:"conventional",generate:1,systemPrompt:"",systemPromptPath:"",codeReviewPromptPath:"",vcs_branch:""},Za={"":"<commit message>",conventional:`<type>(<optional scope>): <description>
|
|
24
24
|
|
|
25
25
|
[optional body]
|
|
26
26
|
|
|
@@ -28,13 +28,13 @@ ${u.footer}`:""}`})).slice(0,o);if(this.isLoggingEnabled()){const u=c.map(m=>m.t
|
|
|
28
28
|
|
|
29
29
|
[optional body]
|
|
30
30
|
|
|
31
|
-
[optional footer(s)]`},
|
|
31
|
+
[optional footer(s)]`},ec={"":"",gitmoji:`
|
|
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
|
+
`)}`},ir=(t,e)=>t.replace(/{(\w+)}/g,(r,o)=>e[o]?.toString()||Y[o]?.toString()),tc=(t,e)=>{const r=e.split("-")[0].toLowerCase(),o={conventional:{en:{subject:"fix(auth): fix bug in user authentication process",body:"- Update login function to handle edge cases\\n- Add additional error logging for debugging"},zh:{subject:"fix(auth): \u4FEE\u590D\u7528\u6237\u8BA4\u8BC1\u8FC7\u7A0B\u4E2D\u7684\u9519\u8BEF",body:"- \u66F4\u65B0\u767B\u5F55\u51FD\u6570\u4EE5\u5904\u7406\u8FB9\u7F18\u60C5\u51B5\\n- \u6DFB\u52A0\u989D\u5916\u7684\u9519\u8BEF\u65E5\u5FD7\u7528\u4E8E\u8C03\u8BD5"},ja:{subject:"fix(auth): \u30E6\u30FC\u30B6\u30FC\u8A8D\u8A3C\u30D7\u30ED\u30BB\u30B9\u306E\u30D0\u30B0\u3092\u4FEE\u6B63",body:"- \u30A8\u30C3\u30B8\u30B1\u30FC\u30B9\u3092\u51E6\u7406\u3059\u308B\u305F\u3081\u306B\u30ED\u30B0\u30A4\u30F3\u6A5F\u80FD\u3092\u66F4\u65B0\\n- \u30C7\u30D0\u30C3\u30B0\u7528\u306E\u8FFD\u52A0\u30A8\u30E9\u30FC\u30ED\u30B0\u3092\u8FFD\u52A0"},ko:{subject:"fix(auth): \uC0AC\uC6A9\uC790 \uC778\uC99D \uD504\uB85C\uC138\uC2A4\uC758 \uBC84\uADF8 \uC218\uC815",body:"- \uC5E3\uC9C0 \uCF00\uC774\uC2A4\uB97C \uCC98\uB9AC\uD558\uB3C4\uB85D \uB85C\uADF8\uC778 \uD568\uC218 \uC5C5\uB370\uC774\uD2B8\\n- \uB514\uBC84\uAE45\uC744 \uC704\uD55C \uCD94\uAC00 \uC624\uB958 \uB85C\uAE45 \uCD94\uAC00"},es:{subject:"fix(auth): corregir error en el proceso de autenticaci\xF3n",body:"- Actualizar funci\xF3n de inicio de sesi\xF3n para manejar casos extremos\\n- Agregar registro de errores adicional para depuraci\xF3n"},fr:{subject:"fix(auth): corriger un bug dans le processus d'authentification",body:"- Mettre \xE0 jour la fonction de connexion pour g\xE9rer les cas limites\\n- Ajouter une journalisation d'erreurs suppl\xE9mentaire pour le d\xE9bogage"},de:{subject:"fix(auth): Fehler im Benutzerauthentifizierungsprozess beheben",body:"- Login-Funktion aktualisiert, um Randf\xE4lle zu behandeln\\n- Zus\xE4tzliche Fehlerprotokollierung f\xFCr Debugging hinzugef\xFCgt"}},gitmoji:{en:{subject:":sparkles: Add real-time chat feature",body:"- Implement WebSocket connection\\n- Add message encryption\\n- Include typing indicators"},zh:{subject:":sparkles: \u6DFB\u52A0\u5B9E\u65F6\u804A\u5929\u529F\u80FD",body:"- \u5B9E\u73B0WebSocket\u8FDE\u63A5\\n- \u6DFB\u52A0\u6D88\u606F\u52A0\u5BC6\\n- \u5305\u542B\u8F93\u5165\u6307\u793A\u5668"},ja:{subject:":sparkles: \u30EA\u30A2\u30EB\u30BF\u30A4\u30E0\u30C1\u30E3\u30C3\u30C8\u6A5F\u80FD\u3092\u8FFD\u52A0",body:"- WebSocket\u63A5\u7D9A\u3092\u5B9F\u88C5\\n- \u30E1\u30C3\u30BB\u30FC\u30B8\u6697\u53F7\u5316\u3092\u8FFD\u52A0\\n- \u5165\u529B\u30A4\u30F3\u30B8\u30B1\u30FC\u30BF\u30FC\u3092\u542B\u3080"},ko:{subject:":sparkles: \uC2E4\uC2DC\uAC04 \uCC44\uD305 \uAE30\uB2A5 \uCD94\uAC00",body:"- WebSocket \uC5F0\uACB0 \uAD6C\uD604\\n- \uBA54\uC2DC\uC9C0 \uC554\uD638\uD654 \uCD94\uAC00\\n- \uC785\uB825 \uD45C\uC2DC\uAE30 \uD3EC\uD568"},es:{subject:":sparkles: Agregar funci\xF3n de chat en tiempo real",body:"- Implementar conexi\xF3n WebSocket\\n- Agregar cifrado de mensajes\\n- Incluir indicadores de escritura"},fr:{subject:":sparkles: Ajouter une fonctionnalit\xE9 de chat en temps r\xE9el",body:"- Impl\xE9menter une connexion WebSocket\\n- Ajouter le chiffrement des messages\\n- Inclure des indicateurs de saisie"},de:{subject:":sparkles: Echtzeit-Chat-Funktion hinzuf\xFCgen",body:"- WebSocket-Verbindung implementieren\\n- Nachrichtenverschl\xFCsselung hinzuf\xFCgen\\n- Tippindikatoren einschlie\xDFen"}},"":{en:{subject:"",body:""}}},n=o[t]||o[""];return n[r]||n.en},tn=t=>{const{type:e,maxLength:r,generate:o,locale:n}=t,s="You are an expert Git commit message writer specializing in analyzing code changes and creating precise, meaningful commit messages.",i=`Your task is to generate exactly ${o} ${e} style commit message${o!==1?"s":""} based on the provided git diff.`;return[s,i,"",["## Requirements:",`1. Language: Write all messages in ${n}`,`2. Format: Strictly follow the ${e} commit format:`,`${Za[e]}`,`3. Allowed Types:${ec[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
|
+
`)},wt=(t,e,r)=>{const o=n=>{const s=tc(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
|
-
`)},ee=t=>{const{systemPrompt:e,systemPromptPath:r,type:o,generate:n,locale:s}=t;if(e)return`${e}
|
|
47
|
-
${
|
|
48
|
-
${
|
|
49
|
-
${
|
|
50
|
-
${
|
|
46
|
+
`)},ee=t=>{const{systemPrompt:e,systemPromptPath:r,type:o,generate:n,locale:s}=t;if(e)return`${ir(e,t)}
|
|
47
|
+
${wt(o,n,s)}`;if(!r)return`${tn(t)}
|
|
48
|
+
${wt(o,n,s)}`;try{const i=V.readFileSync(ft(r),"utf-8");return`${ir(i,t)}
|
|
49
|
+
${wt(o,n,s)}`}catch{return`${tn(t)}
|
|
50
|
+
${wt(o,n,s)}`}},te=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 @@ ${yt(o,n,s)}`}},te=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=V.readFileSync(
|
|
58
|
+
Please structure your response with appropriate Markdown headings, code blocks, and bullet points.`;if(!e)return o;try{const n=V.readFileSync(ft(e),"utf-8");return`${ir(n,t)}`}catch{return o}},rn=async t=>{if(t.systemPromptPath)try{V.readFileSync(ft(t.systemPromptPath),"utf-8")}catch(e){throw new w(`Error reading system prompt file: ${t.systemPromptPath}, ${e}`)}if(t.codeReview&&t.codeReviewPromptPath)try{V.readFileSync(ft(t.codeReviewPromptPath),"utf-8")}catch(e){throw new w(`Error reading code review prompt file: ${t.codeReviewPromptPath}, ${e}`)}},ye=(t,e="commit")=>e==="review"?`Please analyze the following diff and provide a comprehensive code review:
|
|
59
59
|
|
|
60
60
|
\`\`\`diff
|
|
61
61
|
${t}
|
|
@@ -67,46 +67,46 @@ 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).`,tc=10*60*1e3;class rc extends Z{constructor(e){super(e),this.params=e,this.colors={primary:"#AE5630",secondary:"#fff"},this.serviceName=C.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[Anthropic]"),this.errorPrefix=C.red.bold("[Anthropic]"),this.anthropic=new zn({apiKey:this.params.config.key,...this.params.config.timeout>tc&&{timeout:this.params.config.timeout}})}getServiceSpecificErrorMessage(e){const r=e.message||"";return r.includes("API key")||r.includes("api_key")?"Invalid API key. Check your Anthropic API key in configuration":r.includes("quota")||r.includes("usage")?"API quota exceeded. Check your Anthropic usage limits":r.includes("model")||r.includes("Model")?"Model not found or not accessible. Check if the Claude model name is correct":r.includes("403")||r.includes("Forbidden")?"Access denied. Your API key may not have permission for this Claude model":r.includes("404")||r.includes("Not Found")?"Model or endpoint not found. Check your Claude model configuration":r.includes("500")||r.includes("Internal Server Error")?"Anthropic server error. Try again later":null}generateCommitMessage$(){return T(this.generateMessage("commit")).pipe(_(e=>D(e)),F(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})),L(this.handleError$))}generateCodeReview$(){return T(this.generateMessage("review")).pipe(_(e=>D(e)),F(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),L(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:m,topP:p,model:h}=this.params.config,g={...Y,locale:a,maxLength:u,type:c,generate:d,systemPrompt:o,systemPromptPath:n,codeReviewPromptPath:s},y=e==="review"?te(g):ee(g),v=ge(r,e),b=`${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"};X(r,e,"Anthropic",h,b,A,i),Q(r,e,"Anthropic",y,v,i);const k={max_tokens:m,temperature:l,system:y,messages:[{role:"user",content:v}],top_p:p,model:h};re(r,e,"Anthropic",k,i);const P=Date.now();try{const $=await this.anthropic.messages.create(k),S=Date.now()-P;K(r,e,"Anthropic",$,i);const M=$.content.map(({text:R})=>R).join("");return W(r,e,"Anthropic",S,M,i),e==="review"?this.sanitizeResponse(M):this.parseMessage(M,c,d)}catch($){throw B(r,e,"Anthropic",$,i),$}}}const oe="Bedrock",de={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 Be=null,Ge=null;const rn=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=de.MISSING_DEPENDENCY,e.originalError=t,e},oc=async()=>{if(Be)return Be;try{return Be=await import("@aws-sdk/client-bedrock-runtime"),Be}catch(t){throw Be=null,rn(t)}},on=async()=>{if(Ge)return Ge;try{return Ge=await import("@aws-sdk/credential-providers"),Ge}catch(t){throw Ge=null,rn(t)}};class nc extends Z{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(`[${oe}]`),this.errorPrefix=C.red.bold(`[${oe}]`),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=de.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=de.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=de.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=de.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 T(this.generateMessage("commit")).pipe(_(e=>D(e)),F(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})),L(this.handleError$))}generateCodeReview$(){return T(this.generateMessage("review")).pipe(_(e=>D(e)),F(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),L(this.handleError$))}async generateMessage(e){const r=this.params.stagedDiff.diff,o=this.bedrockConfig,n=o.model,{logging:s,inferenceParameters:i}=o,l={...Y,locale:o.locale,maxLength:o.maxLength,type:o.type,generate:o.generate,systemPrompt:o.systemPrompt,systemPromptPath:o.systemPromptPath,codeReviewPromptPath:o.codeReviewPromptPath},a=e==="review"?te(l):ee(l),d=ge(r,e),c={region:this.getRegion(),profile:o.profile,modelId:n},u=`https://bedrock-runtime.${this.getRegion()||"unknown"}.amazonaws.com/model/${encodeURIComponent(n)}/converse`;X(r,e,oe,n,u,c,s),Q(r,e,oe,a,d,s);const m={modelId:n,systemPrompt:a,userPrompt:d,...i&&Object.keys(i).length>0&&{inferenceConfig:i}};re(r,e,oe,m,s);const p=Date.now();try{const h=this.determineAuthMethod();gt()&&(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 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 W(r,e,oe,y,g,s),e==="review"?this.sanitizeResponse(g):this.parseMessage(g,o.type,o.generate)}catch(h){throw B(r,e,oe,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 oc(),m=this.bedrockConfig,p={region:r,requestHandler:{requestTimeout:m.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}});gt()&&console.log(C.cyan(`[Bedrock] Sending ConverseCommand with modelId: ${o}`));let v;try{v=await g.send(y),K(d,a,oe,v,l)}catch(b){throw gt()&&(console.error(C.red(`[Bedrock] AWS SDK Error: ${b.name}`)),console.error(C.red(`[Bedrock] Error message: ${b.message}`)),b.$metadata&&(console.error(C.red(`[Bedrock] Request ID: ${b.$metadata.requestId}`)),console.error(C.red(`[Bedrock] HTTP Status: ${b.$metadata.httpStatusCode}`))),b.$fault&&console.error(C.red(`[Bedrock] Fault: ${b.$fault}`))),b}const E=v.output?.message?.content?.[0]?.text||"";if(!E){const b=new Error("No text content found in Bedrock response.");throw b.name=de.EMPTY_RESPONSE,b.content=v,b}return E}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),m=d.applicationBaseUrl||`https://bedrock-runtime.${c}.amazonaws.com/model/${u}/converse`,p=new URL(m),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 z(d.key)&&(y.Authorization=`Bearer ${d.key}`),z(d.applicationInferenceProfileArn)&&(y["x-amzn-bedrock-inference-profile-arn"]=d.applicationInferenceProfileArn),z(d.applicationEndpointId)&&(y["x-amzn-bedrock-endpoint-id"]=d.applicationEndpointId),new Promise((v,E)=>{const b=Hr.request({method:"POST",protocol:p.protocol,hostname:p.hostname,port:p.port,path:p.pathname+p.search,headers:y,timeout:d.timeout},A=>{const k=[];A.on("data",P=>k.push(P)),A.on("end",()=>{const P=Buffer.concat(k).toString("utf8");if(A.statusCode&&A.statusCode>=400){const R=new Error(`Bedrock application endpoint responded with status ${A.statusCode}.`);return R.status=A.statusCode,R.content=P,B(a,l,oe,R,i),E(R)}const $=Ko(P);if(!$.ok){const R=new Error("Failed to parse Bedrock application response as JSON. The Bedrock Converse API should always return valid JSON.");return R.name=de.INVALID_RESPONSE,R.content=P,B(a,l,oe,R,i),E(R)}const S=$.data;K(a,l,oe,S,i);const M=S.output?.message?.content?.[0]?.text||"";if(!M){const R=new Error("No text content found in Bedrock response.");return R.name=de.EMPTY_RESPONSE,R.content=S,B(a,l,oe,R,i),E(R)}v(M)})});b.on("error",A=>{const k=A;B(a,l,oe,k,i),E(k)}),b.write(g),b.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 on();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 on();l=a({profile:process.env.AWS_PROFILE})}return l&&(this.credentialCache=l,this.credentialCacheTimestamp=e),l}}class He{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=Kn.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 sc extends Z{constructor(e){super(e),this.params=e,this.apiKey="",this.colors={primary:"#e28c58",secondary:"#fff"},this.serviceName=C.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[Codestral]"),this.errorPrefix=C.red.bold("[Codestral]"),this.apiKey=this.params.config.key}getServiceSpecificErrorMessage(e){const r=e.message||"";return r.includes("API key")||r.includes("api_key")?"Invalid API key. Check your Codestral API key in configuration":r.includes("rate_limit")||r.includes("Rate limit")?"Rate limit exceeded. Wait a moment and try again, or upgrade your Codestral plan":r.includes("model")||r.includes("Model")?"Model not found or not accessible. Check if the Codestral model name is correct":r.includes("Invalid model type")?"Invalid model type. Use supported models: codestral-latest, codestral-2501":r.includes("overloaded")||r.includes("capacity")?"Codestral service is overloaded. Try again in a few minutes":r.includes("403")||r.includes("Forbidden")?"Access denied. Your API key may not have permission for this Codestral model":r.includes("404")||r.includes("Not Found")?"Model or endpoint not found. Check your Codestral model configuration":r.includes("500")||r.includes("Internal Server Error")?"Codestral server error. Try again later":null}generateCommitMessage$(){return T(this.generateMessage("commit")).pipe(_(e=>D(e)),F(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})),L(this.handleError$))}generateCodeReview$(){return T(this.generateMessage("review")).pipe(_(e=>D(e)),F(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),L(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={...Y,locale:l,maxLength:c,type:d,generate:a,systemPrompt:o,systemPromptPath:n,codeReviewPromptPath:s},m=e==="review"?te(u):ee(u);this.checkAvailableModels();const p=ge(r,e),g=`${this.params.config.url||"https://codestral.mistral.ai"}/v1/chat/completions`,y={Authorization:`Bearer ${this.apiKey}`,"content-type":"application/json"};X(r,e,"Codestral",this.params.config.model,g,y,i),Q(r,e,"Codestral",m,p,i);const v=await this.createChatCompletions(m,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:ge(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:ut(10,1e3)};r==="commit"&&(i.response_format={type:"json_object"}),re(o,r,"Codestral",i,n);const l=Date.now();try{const d=await new He({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(K(o,r,"Codestral",u,n),!u.choices||u.choices.length===0||!u.choices[0].message?.content)throw B(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 W(o,r,"Codestral",c,p,n),p}catch(a){throw B(o,r,"Codestral",a,n),a}}}class ic extends Z{constructor(e){super(e),this.params=e,this.colors={primary:"#D18EE2",secondary:"#fff"},this.serviceName=C.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[Cohere]"),this.errorPrefix=C.red.bold("[Cohere]"),this.cohere=new Wn({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 T(this.generateMessage("commit")).pipe(_(e=>D(e)),F(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})),L(this.handleError$))}generateCodeReview$(){return T(this.generateMessage("review")).pipe(_(e=>D(e)),F(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),L(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:m}=this.params.config,p={...Y,locale:a,maxLength:u,type:c,generate:d,systemPrompt:o,systemPromptPath:n,codeReviewPromptPath:s},h=e==="review"?te(p):ee(p),g=`Here is the diff: ${r}`,y=[...h?[{role:"system",content:h}]:[],{role:"user",content:g}],E=`${this.params.config.url}/v2/chat`;X(r,e,"Cohere",this.params.config.model,E,{},i),Q(r,e,"Cohere",h,g,i);const b={model:this.params.config.model,messages:y,max_tokens:m,temperature:l,seed:ut(10,1e3),p:this.params.config.topP};re(r,e,"Cohere",b,i);const A=Date.now();try{const k=await this.cohere.chat(b,{timeoutInSeconds:Math.floor(this.params.config.timeout/1e3)}),P=Date.now()-A;if(!this.isValidCohereV2Response(k))throw new Error("Invalid response structure from Cohere v2 API");const $=k.message.content[0].text;return K(r,e,"Cohere",k,i),W(r,e,"Cohere",P,$,i),e==="review"?this.sanitizeResponse($):this.parseMessage($,c,d)}catch(k){throw B(r,e,"Cohere",k,i),k}}}class ac extends Z{constructor(e){super(e),this.params=e,this.colors={primary:"#53a3f9",secondary:"#fff"},this.serviceName=C.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[DeepSeek]"),this.errorPrefix=C.red.bold("[DeepSeek]");const r=this.params.config.url||"https://api.deepseek.com";this.deepSeek=new Ur({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 T(this.generateMessage("commit")).pipe(_(e=>D(e)),F(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})),L(this.handleError$))}generateCodeReview$(){return T(this.generateMessage("review")).pipe(_(e=>D(e)),F(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),L(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={...Y,locale:l,maxLength:c,type:d,generate:a,systemPrompt:o,systemPromptPath:n,codeReviewPromptPath:s},m=e==="review"?te(u):ee(u);this.checkAvailableModels();const p=ge(r,e),g=`${this.params.config.url||"https://api.deepseek.com"}/chat/completions`,y={Authorization:`Bearer ${this.params.config.key}`,"Content-Type":"application/json"};X(r,e,"DeepSeek",this.params.config.model,g,y,i),Q(r,e,"DeepSeek",m,p,i);const v=await this.createChatCompletions(m,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};re(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 K(n,o,"DeepSeek",a,s),W(n,o,"DeepSeek",d,u,s),u}catch(a){throw B(n,o,"DeepSeek",a,s),a}}}class cc extends Z{constructor(e){super(e),this.params=e,this.colors={primary:"#0077FF",secondary:"#fff"},this.serviceName=C.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[Gemini]"),this.errorPrefix=C.red.bold("[Gemini]"),this.genAI=new Yn(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 T(this.generateMessage("commit")).pipe(_(e=>D(e)),F(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})),L(this.handleError$))}generateCodeReview$(){return T(this.generateMessage("review")).pipe(_(e=>D(e)),F(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),L(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,m={...Y,locale:i,maxLength:c,type:d,generate:a,systemPrompt:o,systemPromptPath:n,codeReviewPromptPath:l},p=e==="review"?te(m):ee(m),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:Xe.HARM_CATEGORY_HATE_SPEECH,threshold:Qe.BLOCK_LOW_AND_ABOVE},{category:Xe.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:Qe.BLOCK_LOW_AND_ABOVE},{category:Xe.HARM_CATEGORY_HARASSMENT,threshold:Qe.BLOCK_LOW_AND_ABOVE},{category:Xe.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:Qe.BLOCK_LOW_AND_ABOVE}]}),y=ge(r,e),E=`${this.params.config.url||"https://generativelanguage.googleapis.com"}/v1beta/models/${this.params.config.model}:generateContent`,b={"Content-Type":"application/json","x-goog-api-key":this.params.config.key};X(r,e,"Gemini",this.params.config.model,E,b,s),Q(r,e,"Gemini",p,y,s),re(r,e,"Gemini",{systemInstruction:{parts:[{text:p}]},contents:[{parts:[{text:y}]}],generationConfig:h},s);const k=Date.now();try{const P=this.params.config.timeout>1e4?{request:{timeout:this.params.config.timeout}}:void 0,$=await g.generateContent(y,P),S=$.response;if(S.candidates?.[0]?.finishReason==="MAX_TOKENS"){const Me=S.usageMetadata;throw new Error(`Response truncated: maxOutputTokens exceeded. Thinking tokens: ${Me?.thoughtsTokenCount??"N/A"}, Output tokens: ${Me?.candidatesTokenCount??"N/A"}. Increase maxTokens config for Gemini 2.5+ thinking models.`)}const R=S.text(),kt=Date.now()-k;return K(r,e,"Gemini",{response:R,candidates:$.response.candidates,usageMetadata:$.response.usageMetadata},s),W(r,e,"Gemini",kt,R,s),e==="review"?this.sanitizeResponse(R):this.parseMessage(R,d,a)}catch(P){throw B(r,e,"Gemini",P,s),P}}}var sr={},ir={exports:{}},Ue={exports:{}},ar,nn;function lc(){if(nn)return ar;nn=1;var t=1e3,e=t*60,r=e*60,o=r*24,n=o*7,s=o*365.25;ar=function(c,u){u=u||{};var m=typeof c;if(m==="string"&&c.length>0)return i(c);if(m==="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 m=parseFloat(u[1]),p=(u[2]||"ms").toLowerCase();switch(p){case"years":case"year":case"yrs":case"yr":case"y":return m*s;case"weeks":case"week":case"w":return m*n;case"days":case"day":case"d":return m*o;case"hours":case"hour":case"hrs":case"hr":case"h":return m*r;case"minutes":case"minute":case"mins":case"min":case"m":return m*e;case"seconds":case"second":case"secs":case"sec":case"s":return m*t;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return m;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,m,p){var h=u>=m*1.5;return Math.round(c/m)+" "+p+(h?"s":"")}return ar}var cr,sn;function an(){if(sn)return cr;sn=1;function t(e){o.debug=o,o.default=o,o.coerce=d,o.disable=l,o.enable=s,o.enabled=a,o.humanize=lc(),o.destroy=c,Object.keys(e).forEach(u=>{o[u]=e[u]}),o.names=[],o.skips=[],o.formatters={};function r(u){let m=0;for(let p=0;p<u.length;p++)m=(m<<5)-m+u.charCodeAt(p),m|=0;return o.colors[Math.abs(m)%o.colors.length]}o.selectColor=r;function o(u){let m,p=null,h,g;function y(...v){if(!y.enabled)return;const E=y,b=Number(new Date),A=b-(m||b);E.diff=A,E.prev=m,E.curr=b,m=b,v[0]=o.coerce(v[0]),typeof v[0]!="string"&&v.unshift("%O");let k=0;v[0]=v[0].replace(/%([a-zA-Z%])/g,($,S)=>{if($==="%%")return"%";k++;const M=o.formatters[S];if(typeof M=="function"){const R=v[k];$=M.call(E,R),v.splice(k,1),k--}return $}),o.formatArgs.call(E,v),(E.log||o.log).apply(E,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,m){const p=o(this.namespace+(typeof m>"u"?":":m)+u);return p.log=this.log,p}function s(u){o.save(u),o.namespaces=u,o.names=[],o.skips=[];const m=(typeof u=="string"?u:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(const p of m)p[0]==="-"?o.skips.push(p.slice(1)):o.names.push(p)}function i(u,m){let p=0,h=0,g=-1,y=0;for(;p<u.length;)if(h<m.length&&(m[h]===u[p]||m[h]==="*"))m[h]==="*"?(g=h,y=p,h++):(p++,h++);else if(g!==-1)h=g+1,y++,p=y;else return!1;for(;h<m.length&&m[h]==="*";)h++;return h===m.length}function l(){const u=[...o.names,...o.skips.map(m=>"-"+m)].join(",");return o.enable(""),u}function a(u){for(const m of o.skips)if(i(u,m))return!1;for(const m of o.names)if(i(u,m))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 cr=t,cr}Ue.exports;var cn;function uc(){return cn||(cn=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,m=>{m!=="%%"&&(c++,m==="%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=an()(e);const{formatters:l}=t.exports;l.j=function(a){try{return JSON.stringify(a)}catch(d){return"[UnexpectedJSONParseError]: "+d.message}}}(Ue,Ue.exports)),Ue.exports}var ze={exports:{}},lr,ln;function dc(){return ln||(ln=1,lr=(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)}),lr}var ur,un;function mc(){if(un)return ur;un=1;const t=Re,e=zr,r=dc(),{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 ur={supportsColor:l,stdout:s(i(!0,e.isatty(1))),stderr:s(i(!0,e.isatty(2)))},ur}ze.exports;var dn;function fc(){return dn||(dn=1,function(t,e){const r=zr,o=Lr;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 m=mc();m&&(m.stderr||m).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(m=>/^debug_/i.test(m)).reduce((m,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),m[h]=g,m},{});function n(){return"colors"in e.inspectOpts?!!e.inspectOpts.colors:r.isatty(process.stderr.fd)}function s(m){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`;m[0]=v+m[0].split(`
|
|
70
|
+
Focus on understanding the purpose and impact of these changes to create meaningful commit message(s).`,rc=10*60*1e3;class oc extends Z{constructor(e){super(e),this.params=e,this.colors={primary:"#AE5630",secondary:"#fff"},this.serviceName=b.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[Anthropic]"),this.errorPrefix=b.red.bold("[Anthropic]"),this.anthropic=new Kn({apiKey:this.params.config.key,...this.params.config.timeout>rc&&{timeout:this.params.config.timeout}})}getServiceSpecificErrorMessage(e){const r=e.message||"";return r.includes("API key")||r.includes("api_key")?"Invalid API key. Check your Anthropic API key in configuration":r.includes("quota")||r.includes("usage")?"API quota exceeded. Check your Anthropic usage limits":r.includes("model")||r.includes("Model")?"Model not found or not accessible. Check if the Claude model name is correct":r.includes("403")||r.includes("Forbidden")?"Access denied. Your API key may not have permission for this Claude model":r.includes("404")||r.includes("Not Found")?"Model or endpoint not found. Check your Claude model configuration":r.includes("500")||r.includes("Internal Server Error")?"Anthropic server error. Try again later":null}generateCommitMessage$(){return T(this.generateMessage("commit")).pipe(_(e=>O(e)),N(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:this.params.config.includeBody?e.value:e.title,description:this.params.config.includeBody?e.value:"",isError:!1})),F(this.handleError$))}generateCodeReview$(){return T(this.generateMessage("review")).pipe(_(e=>O(e)),N(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),F(this.handleError$))}async generateMessage(e){const 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={...Y,locale:a,maxLength:u,type:c,generate:d,systemPrompt:o,systemPromptPath:n,codeReviewPromptPath:s,vcs_branch:this.params.branchName||""},g=e==="review"?te(y):ee(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"};X(r,e,"Anthropic",h,E,k,i),Q(r,e,"Anthropic",g,v,i);const P={max_tokens:f,temperature:l,system:g,messages:[{role:"user",content:v}],top_p:p,model:h};oe(r,e,"Anthropic",P,i);const A=Date.now();try{const M=await this.anthropic.messages.create(P),$=Date.now()-A;K(r,e,"Anthropic",M,i);const D=M.content.map(({text:x})=>x).join("");return W(r,e,"Anthropic",$,D,i),e==="review"?this.sanitizeResponse(D):this.parseMessage(D,c,d)}catch(M){throw B(r,e,"Anthropic",M,i),M}}}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 Ge=null,He=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},nc=async()=>{if(Ge)return Ge;try{return Ge=await import("@aws-sdk/client-bedrock-runtime"),Ge}catch(t){throw Ge=null,on(t)}},nn=async()=>{if(He)return He;try{return He=await import("@aws-sdk/credential-providers"),He}catch(t){throw He=null,on(t)}};class sc extends Z{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=b.bgHex(this.colors.primary).hex(this.colors.secondary).bold(`[${ne}]`),this.errorPrefix=b.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 T(this.generateMessage("commit")).pipe(_(e=>O(e)),N(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:this.params.config.includeBody?e.value:e.title,description:this.params.config.includeBody?e.value:"",isError:!1})),F(this.handleError$))}generateCodeReview$(){return T(this.generateMessage("review")).pipe(_(e=>O(e)),N(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),F(this.handleError$))}async generateMessage(e){const r=this.params.stagedDiff.diff,o=this.bedrockConfig,n=o.model,{logging:s,inferenceParameters:i}=o,l={...Y,locale:o.locale,maxLength:o.maxLength,type:o.type,generate:o.generate,systemPrompt:o.systemPrompt,systemPromptPath:o.systemPromptPath,codeReviewPromptPath:o.codeReviewPromptPath},a=e==="review"?te(l):ee(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`;X(r,e,ne,n,u,c,s),Q(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(b.cyan(`[Bedrock] Authentication method: ${h}`)),console.log(b.cyan(`[Bedrock] Model ID: ${n}`)),console.log(b.cyan(`[Bedrock] Region: ${this.getRegion()}`)),console.log(b.cyan(`[Bedrock] Has AWS credentials: ${this.canUseAwsSdk()}`)),console.log(b.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 W(r,e,ne,g,y,s),e==="review"?this.sanitizeResponse(y):this.parseMessage(y,o.type,o.generate)}catch(h){throw B(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 nc(),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(b.cyan(`[Bedrock] Sending ConverseCommand with modelId: ${o}`));let v;try{v=await y.send(g),K(d,a,ne,v,l)}catch(E){throw yt()&&(console.error(b.red(`[Bedrock] AWS SDK Error: ${E.name}`)),console.error(b.red(`[Bedrock] Error message: ${E.message}`)),E.$metadata&&(console.error(b.red(`[Bedrock] Request ID: ${E.$metadata.requestId}`)),console.error(b.red(`[Bedrock] HTTP Status: ${E.$metadata.httpStatusCode}`))),E.$fault&&console.error(b.red(`[Bedrock] Fault: ${E.$fault}`))),E}const C=v.output?.message?.content?.[0]?.text||"";if(!C){const E=new Error("No text content found in Bedrock response.");throw E.name=me.EMPTY_RESPONSE,E.content=v,E}return C}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,C)=>{const E=zr.request({method:"POST",protocol:p.protocol,hostname:p.hostname,port:p.port,path:p.pathname+p.search,headers:g,timeout:d.timeout},k=>{const P=[];k.on("data",A=>P.push(A)),k.on("end",()=>{const A=Buffer.concat(P).toString("utf8");if(k.statusCode&&k.statusCode>=400){const x=new Error(`Bedrock application endpoint responded with status ${k.statusCode}.`);return x.status=k.statusCode,x.content=A,B(a,l,ne,x,i),C(x)}const M=Yo(A);if(!M.ok){const x=new Error("Failed to parse Bedrock application response as JSON. The Bedrock Converse API should always return valid JSON.");return x.name=me.INVALID_RESPONSE,x.content=A,B(a,l,ne,x,i),C(x)}const $=M.data;K(a,l,ne,$,i);const D=$.output?.message?.content?.[0]?.text||"";if(!D){const x=new Error("No text content found in Bedrock response.");return x.name=me.EMPTY_RESPONSE,x.content=$,B(a,l,ne,x,i),C(x)}v(D)})});E.on("error",k=>{const P=k;B(a,l,ne,P,i),C(P)}),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 Ue{constructor(e={}){if(!e.method)throw new Error("method should be defined!");if(!e.baseURL)throw new Error("baseURL should be defined!");this.config={...e},this.axiosInstance=Wn.create(this.config)}setHeaders(e){return this.config.headers=e,this}setParams(e){return this.config.params=e,this}setBody(e){return this.config.data=e,this}addBody(e){return this.config.data={...this.config.data,...e},this}setMethod(e){return this.config.method=e,this}async execute(){try{return await this.axiosInstance.request(this.config)}catch(e){throw e}}}class ic extends Z{constructor(e){super(e),this.params=e,this.apiKey="",this.colors={primary:"#e28c58",secondary:"#fff"},this.serviceName=b.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[Codestral]"),this.errorPrefix=b.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 T(this.generateMessage("commit")).pipe(_(e=>O(e)),N(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:this.params.config.includeBody?e.value:e.title,description:this.params.config.includeBody?e.value:"",isError:!1})),F(this.handleError$))}generateCodeReview$(){return T(this.generateMessage("review")).pipe(_(e=>O(e)),N(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),F(this.handleError$))}async generateMessage(e){const 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={...Y,locale:l,maxLength:c,type:d,generate:a,systemPrompt:o,systemPromptPath:n,codeReviewPromptPath:s,vcs_branch:this.params.branchName||""},f=e==="review"?te(u):ee(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"};X(r,e,"Codestral",this.params.config.model,y,g,i),Q(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:dt(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 Ue({method:"POST",baseURL:`${s}/v1/chat/completions`,timeout:this.params.config.timeout}).setHeaders({Authorization:`Bearer ${this.apiKey}`,"content-type":"application/json"}).setBody(i).execute(),c=Date.now()-l,u=d.data;if(K(o,r,"Codestral",u,n),!u.choices||u.choices.length===0||!u.choices[0].message?.content)throw B(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 W(o,r,"Codestral",c,p,n),p}catch(a){throw B(o,r,"Codestral",a,n),a}}}class ac extends Z{constructor(e){super(e),this.params=e,this.colors={primary:"#D18EE2",secondary:"#fff"},this.serviceName=b.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[Cohere]"),this.errorPrefix=b.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 T(this.generateMessage("commit")).pipe(_(e=>O(e)),N(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:this.params.config.includeBody?e.value:e.title,description:this.params.config.includeBody?e.value:"",isError:!1})),F(this.handleError$))}generateCodeReview$(){return T(this.generateMessage("review")).pipe(_(e=>O(e)),N(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),F(this.handleError$))}async generateMessage(e){const 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={...Y,locale:a,maxLength:u,type:c,generate:d,systemPrompt:o,systemPromptPath:n,codeReviewPromptPath:s,vcs_branch:this.params.branchName||""},h=e==="review"?te(p):ee(p),y=`Here is the diff: ${r}`,g=[...h?[{role:"system",content:h}]:[],{role:"user",content:y}],C=`${this.params.config.url}/v2/chat`;X(r,e,"Cohere",this.params.config.model,C,{},i),Q(r,e,"Cohere",h,y,i);const E={model:this.params.config.model,messages:g,max_tokens:f,temperature:l,seed:dt(10,1e3),p:this.params.config.topP};oe(r,e,"Cohere",E,i);const k=Date.now();try{const P=await this.cohere.chat(E,{timeoutInSeconds:Math.floor(this.params.config.timeout/1e3)}),A=Date.now()-k;if(!this.isValidCohereV2Response(P))throw new Error("Invalid response structure from Cohere v2 API");const M=P.message.content[0].text;return K(r,e,"Cohere",P,i),W(r,e,"Cohere",A,M,i),e==="review"?this.sanitizeResponse(M):this.parseMessage(M,c,d)}catch(P){throw B(r,e,"Cohere",P,i),P}}}class cc extends Z{constructor(e){super(e),this.params=e,this.colors={primary:"#53a3f9",secondary:"#fff"},this.serviceName=b.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[DeepSeek]"),this.errorPrefix=b.red.bold("[DeepSeek]");const r=this.params.config.url||"https://api.deepseek.com";this.deepSeek=new Kr({baseURL:r,apiKey:this.params.config.key})}getServiceSpecificErrorMessage(e){const r=e.message||"";return r.includes("API key")||r.includes("api_key")?"Invalid API key. Check your DeepSeek API key in configuration":r.includes("rate_limit")||r.includes("Rate limit")?"Rate limit exceeded. Wait a moment and try again, or upgrade your DeepSeek plan":r.includes("model")||r.includes("Model")?"Model not found or not accessible. Check if the DeepSeek model name is correct":r.includes("Invalid model type")?"Invalid model type. Use supported models: deepseek-reasoner, deepseek-chat":r.includes("overloaded")||r.includes("capacity")?"DeepSeek service is overloaded. Try again in a few minutes":r.includes("403")||r.includes("Forbidden")?"Access denied. Your API key may not have permission for this DeepSeek model":r.includes("404")||r.includes("Not Found")?"Model or endpoint not found. Check your DeepSeek model configuration":r.includes("500")||r.includes("Internal Server Error")?"DeepSeek server error. Try again later":null}generateCommitMessage$(){return T(this.generateMessage("commit")).pipe(_(e=>O(e)),N(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:this.params.config.includeBody?e.value:e.title,description:this.params.config.includeBody?e.value:"",isError:!1})),F(this.handleError$))}generateCodeReview$(){return T(this.generateMessage("review")).pipe(_(e=>O(e)),N(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),F(this.handleError$))}async generateMessage(e){const 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={...Y,locale:l,maxLength:c,type:d,generate:a,systemPrompt:o,systemPromptPath:n,codeReviewPromptPath:s,vcs_branch:this.params.branchName||""},f=e==="review"?te(u):ee(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"};X(r,e,"DeepSeek",this.params.config.model,y,g,i),Q(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 K(n,o,"DeepSeek",a,s),W(n,o,"DeepSeek",d,u,s),u}catch(a){throw B(n,o,"DeepSeek",a,s),a}}}class lc extends Z{constructor(e){super(e),this.params=e,this.colors={primary:"#0077FF",secondary:"#fff"},this.serviceName=b.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[Gemini]"),this.errorPrefix=b.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 T(this.generateMessage("commit")).pipe(_(e=>O(e)),N(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:this.params.config.includeBody?e.value:e.title,description:this.params.config.includeBody?e.value:"",isError:!1})),F(this.handleError$))}generateCodeReview$(){return T(this.generateMessage("review")).pipe(_(e=>O(e)),N(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),F(this.handleError$))}async generateMessage(e){const 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={...Y,locale:i,maxLength:c,type:d,generate:a,systemPrompt:o,systemPromptPath:n,codeReviewPromptPath:l,vcs_branch:this.params.branchName||""},p=e==="review"?te(f):ee(f),h={maxOutputTokens:u,temperature:this.params.config.temperature,topP:this.params.config.topP},y=this.genAI.getGenerativeModel({model:this.params.config.model,systemInstruction:p,generationConfig:h,safetySettings:[{category:Qe.HARM_CATEGORY_HATE_SPEECH,threshold:Ze.BLOCK_LOW_AND_ABOVE},{category:Qe.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:Ze.BLOCK_LOW_AND_ABOVE},{category:Qe.HARM_CATEGORY_HARASSMENT,threshold:Ze.BLOCK_LOW_AND_ABOVE},{category:Qe.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:Ze.BLOCK_LOW_AND_ABOVE}]}),g=ye(r,e),C=`${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};X(r,e,"Gemini",this.params.config.model,C,E,s),Q(r,e,"Gemini",p,g,s),oe(r,e,"Gemini",{systemInstruction:{parts:[{text:p}]},contents:[{parts:[{text:g}]}],generationConfig:h},s);const P=Date.now();try{const A=this.params.config.timeout>1e4?{request:{timeout:this.params.config.timeout}}:void 0,M=await y.generateContent(g,A),$=M.response;if($.candidates?.[0]?.finishReason==="MAX_TOKENS"){const Re=$.usageMetadata;throw new Error(`Response truncated: maxOutputTokens exceeded. Thinking tokens: ${Re?.thoughtsTokenCount??"N/A"}, Output tokens: ${Re?.candidatesTokenCount??"N/A"}. Increase maxTokens config for Gemini 2.5+ thinking models.`)}const x=$.text(),re=Date.now()-P;return K(r,e,"Gemini",{response:x,candidates:M.response.candidates,usageMetadata:M.response.usageMetadata},s),W(r,e,"Gemini",re,x,s),e==="review"?this.sanitizeResponse(x):this.parseMessage(x,d,a)}catch(A){throw B(r,e,"Gemini",A,s),A}}}var ar={},cr={exports:{}},ze={exports:{}},lr,sn;function uc(){if(sn)return lr;sn=1;var t=1e3,e=t*60,r=e*60,o=r*24,n=o*7,s=o*365.25;lr=function(c,u){u=u||{};var f=typeof c;if(f==="string"&&c.length>0)return i(c);if(f==="number"&&isFinite(c))return u.long?a(c):l(c);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(c))};function i(c){if(c=String(c),!(c.length>100)){var u=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(c);if(u){var f=parseFloat(u[1]),p=(u[2]||"ms").toLowerCase();switch(p){case"years":case"year":case"yrs":case"yr":case"y":return f*s;case"weeks":case"week":case"w":return f*n;case"days":case"day":case"d":return f*o;case"hours":case"hour":case"hrs":case"hr":case"h":return f*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 lr}var ur,an;function cn(){if(an)return ur;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=uc(),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 C=g,E=Number(new Date),k=E-(f||E);C.diff=k,C.prev=f,C.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,(M,$)=>{if(M==="%%")return"%";P++;const D=o.formatters[$];if(typeof D=="function"){const x=v[P];M=D.call(C,x),v.splice(P,1),P--}return M}),o.formatArgs.call(C,v),(C.log||o.log).apply(C,v)}return g.namespace=u,g.useColors=o.useColors(),g.color=o.selectColor(u),g.extend=n,g.destroy=o.destroy,Object.defineProperty(g,"enabled",{enumerable:!0,configurable:!1,get:()=>p!==null?p:(h!==o.namespaces&&(h=o.namespaces,y=o.enabled(u)),y),set:v=>{p=v}}),typeof o.init=="function"&&o.init(g),g}function n(u,f){const p=o(this.namespace+(typeof f>"u"?":":f)+u);return p.log=this.log,p}function s(u){o.save(u),o.namespaces=u,o.names=[],o.skips=[];const f=(typeof u=="string"?u:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(const p of f)p[0]==="-"?o.skips.push(p.slice(1)):o.names.push(p)}function i(u,f){let p=0,h=0,y=-1,g=0;for(;p<u.length;)if(h<f.length&&(f[h]===u[p]||f[h]==="*"))f[h]==="*"?(y=h,g=p,h++):(p++,h++);else if(y!==-1)h=y+1,g++,p=g;else return!1;for(;h<f.length&&f[h]==="*";)h++;return h===f.length}function l(){const u=[...o.names,...o.skips.map(f=>"-"+f)].join(",");return o.enable(""),u}function a(u){for(const f of o.skips)if(i(u,f))return!1;for(const f of o.names)if(i(u,f))return!0;return!1}function d(u){return u instanceof Error?u.stack||u.message:u}function c(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return o.enable(o.load()),o}return ur=t,ur}ze.exports;var ln;function dc(){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}}}(ze,ze.exports)),ze.exports}var Ke={exports:{}},dr,un;function mc(){return un||(un=1,dr=(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)}),dr}var mr,dn;function fc(){if(dn)return mr;dn=1;const t=De,e=Wr,r=mc(),{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 mr={supportsColor:l,stdout:s(i(!0,e.isatty(1))),stderr:s(i(!0,e.isatty(2)))},mr}Ke.exports;var mn;function pc(){return mn||(mn=1,function(t,e){const r=Wr,o=_r;e.init=c,e.log=l,e.formatArgs=s,e.save=a,e.load=d,e.useColors=n,e.destroy=o.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."),e.colors=[6,2,3,4,5,1];try{const f=fc();f&&(f.stderr||f).level>=2&&(e.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221])}catch{}e.inspectOpts=Object.keys(process.env).filter(f=>/^debug_/i.test(f)).reduce((f,p)=>{const h=p.substring(6).toLowerCase().replace(/_([a-z])/g,(g,v)=>v.toUpperCase());let y=process.env[p];return/^(yes|on|true|enabled)$/i.test(y)?y=!0:/^(no|off|false|disabled)$/i.test(y)?y=!1:y==="null"?y=null:y=Number(y),f[h]=y,f},{});function n(){return"colors"in e.inspectOpts?!!e.inspectOpts.colors:r.isatty(process.stderr.fd)}function s(f){const{namespace:p,useColors:h}=this;if(h){const y=this.color,g="\x1B[3"+(y<8?y:"8;5;"+y),v=` ${g};1m${p} \x1B[0m`;f[0]=v+f[0].split(`
|
|
71
71
|
`).join(`
|
|
72
|
-
`+v),
|
|
73
|
-
`)}function a(
|
|
74
|
-
`).map(p=>p.trim()).join(" ")},u.O=function(
|
|
75
|
-
`).some(e=>e.indexOf("(https.js:")!==-1||e.indexOf("node:https:")!==-1)}function
|
|
72
|
+
`+v),f.push(g+"m+"+t.exports.humanize(this.diff)+"\x1B[0m")}else f[0]=i()+p+" "+f[0]}function i(){return e.inspectOpts.hideDate?"":new Date().toISOString()+" "}function l(...f){return process.stderr.write(o.formatWithOptions(e.inspectOpts,...f)+`
|
|
73
|
+
`)}function a(f){f?process.env.DEBUG=f:delete process.env.DEBUG}function d(){return process.env.DEBUG}function c(f){f.inspectOpts={};const p=Object.keys(e.inspectOpts);for(let h=0;h<p.length;h++)f.inspectOpts[p[h]]=e.inspectOpts[p[h]]}t.exports=cn()(e);const{formatters:u}=t.exports;u.o=function(f){return this.inspectOpts.colors=this.useColors,o.inspect(f,this.inspectOpts).split(`
|
|
74
|
+
`).map(p=>p.trim()).join(" ")},u.O=function(f){return this.inspectOpts.colors=this.useColors,o.inspect(f,this.inspectOpts)}}(Ke,Ke.exports)),Ke.exports}typeof process>"u"||process.type==="renderer"||process.browser===!0||process.__nwjs?cr.exports=dc():cr.exports=pc();var fr=cr.exports,pr={};Object.defineProperty(pr,"__esModule",{value:!0});function hc(t){return function(e,r){return new Promise((o,n)=>{t.call(this,e,r,(s,i)=>{s?n(s):o(i)})})}}pr.default=hc;var fn=G&&G.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};const gc=Lr,yc=fn(fr),wc=fn(pr),We=yc.default("agent-base");function vc(t){return!!t&&typeof t.addRequest=="function"}function hr(){const{stack:t}=new Error;return typeof t!="string"?!1:t.split(`
|
|
75
|
+
`).some(e=>e.indexOf("(https.js:")!==-1||e.indexOf("node:https:")!==-1)}function vt(t,e){return new vt.Agent(t,e)}(function(t){class e extends gc.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:hr()?443:80}set defaultPort(o){this.explicitDefaultPort=o}get protocol(){return typeof this.explicitProtocol=="string"?this.explicitProtocol:hr()?"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=hr()),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),vc(p)){We("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?(We("Converting legacy callback function to promise"),this.promisifiedCallback=wc.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{We("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){We("Freeing socket %o %o",o.constructor.name,n),o.destroy()}destroy(){We("Destroying agent %o",this.constructor.name)}}t.Agent=e,t.prototype=t.Agent.prototype})(vt||(vt={}));var bc=vt,gr={},Cc=G&&G.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(gr,"__esModule",{value:!0});const Ec=Cc(fr),Ye=Ec.default("https-proxy-agent:parse-proxy-response");function Pc(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){Ye("onclose had error %o",u)}function a(){Ye("onend")}function d(u){i(),Ye("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;
|
|
80
|
-
`;const
|
|
81
|
-
`);const{statusCode:p,buffered:h}=yield
|
|
77
|
+
`)===-1){Ye("have not received end of HTTP headers yet..."),s();return}const h=f.toString("ascii",0,f.indexOf(`\r
|
|
78
|
+
`)),y=+h.split(" ")[1];Ye("got proxy server response: %o",h),e({statusCode:y,buffered:f})}t.on("error",d),t.on("close",l),t.on("end",a),s()})}gr.default=Pc;var Ac=G&&G.__awaiter||function(t,e,r,o){function n(s){return s instanceof r?s:new r(function(i){i(s)})}return new(r||(r=Promise))(function(s,i){function l(c){try{d(o.next(c))}catch(u){i(u)}}function a(c){try{d(o.throw(c))}catch(u){i(u)}}function d(c){c.done?s(c.value):n(c.value).then(l,a)}d((o=o.apply(t,e||[])).next())})},Ie=G&&G.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(ar,"__esModule",{value:!0});const pn=Ie(qn),hn=Ie(Xn),$c=Ie(Qn),kc=Ie(Fr),Sc=Ie(fr),xc=bc,Ic=Ie(gr),Je=Sc.default("https-proxy-agent:agent");class Mc extends xc.Agent{constructor(e){let r;if(typeof e=="string"?r=$c.default.parse(e):r=e,!r)throw new Error("an HTTP(S) proxy server `host` and `port` must be specified!");Je("creating new HttpsProxyAgent instance: %o",r),super(r);const o=Object.assign({},r);this.secureProxy=r.secureProxy||Oc(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 Ac(this,void 0,void 0,function*(){const{proxy:o,secureProxy:n}=this;let s;n?(Je("Creating `tls.Socket`: %o",o),s=hn.default.connect(o)):(Je("Creating `net.Socket`: %o",o),s=pn.default.connect(o));const i=Object.assign({},o.headers);let a=`CONNECT ${`${r.host}:${r.port}`} HTTP/1.1\r
|
|
79
|
+
`;o.auth&&(i["Proxy-Authorization"]=`Basic ${Buffer.from(o.auth).toString("base64")}`);let{host:d,port:c,secureEndpoint:u}=r;Dc(c,u)||(d+=`:${c}`),i.Host=d,i.Connection="close";for(const g of Object.keys(i))a+=`${g}: ${i[g]}\r
|
|
80
|
+
`;const f=Ic.default(s);s.write(`${a}\r
|
|
81
|
+
`);const{statusCode:p,buffered:h}=yield f;if(p===200){if(e.once("socket",Rc),r.secureEndpoint){Je("Upgrading socket connection to TLS");const g=r.servername||r.host;return hn.default.connect(Object.assign(Object.assign({},Nc(r,"host","hostname","path","port")),{socket:s,servername:g}))}return s}s.destroy();const y=new pn.default.Socket({writable:!1});return y.readable=!0,e.once("socket",g=>{Je("replaying proxy buffer for failed request"),kc.default(g.listenerCount("data")>0),g.push(h),g.push(null)}),y})}}ar.default=Mc;function Rc(t){t.resume()}function Dc(t,e){return!!(!e&&t===80||e&&t===443)}function Oc(t){return typeof t=="string"?/^https:?$/i.test(t):!1}function Nc(t,...e){const r={};let o;for(o in t)e.includes(o)||(r[o]=t[o]);return r}var Fc=G&&G.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};const yr=Fc(ar);function wr(t){return new yr.default(t)}(function(t){t.HttpsProxyAgent=yr.default,t.prototype=yr.default.prototype})(wr||(wr={}));var Lc=wr,_c=ve(Lc);const Tc=async(t,e,r,o,n,s,i)=>new Promise((l,a)=>{const d=JSON.stringify(o),u=(t.protocol.includes("https")?zr: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?_c(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()}),jc=async(t,e,r,o,n,s)=>{const i=new URL(t),{response:l,data:a}=await Tc(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)},gn=t=>t.trim(),Bc=["gpt-5","gpt-5-mini","gpt-5-nano","gpt-5-codex","o1","o1-mini","o1-pro","o3","o3-mini","o3-pro","o4-mini"],vr=t=>{const e=t.toLowerCase();return Bc.some(r=>e===r||e.startsWith(`${r}-`)||e.startsWith(`${r}.`))},Gc=async(t,e,r,o,n,s,i,l,a,d,c,u,f,p)=>{try{const h=ye(s,f),y=vr(n),g={model:n,messages:[{role:"system",content:c},{role:"user",content:h}],stream:!1,n:1,frequency_penalty:0,presence_penalty:0,...y?{max_completion_tokens:l,temperature:1}:{max_tokens:l,top_p:d,temperature:a}},v=new URL(e),C=`${v.protocol}//${v.host}${r}`,E={Authorization:`Bearer ${o}`,"Content-Type":"application/json"};X(s,f,t,n,C,E,u),Q(s,f,t,c,h,u),oe(s,f,t,g,u);const k=Date.now(),P=await jc(e,r,o,g,i,p),A=Date.now()-k;K(s,f,t,P,u);const M=P.choices.filter($=>$.message?.content).map($=>gn($.message.content)).join();return W(s,f,t,A,M,u),P.choices.filter($=>$.message?.content).map($=>gn($.message.content))}catch(h){B(s,f,t,h,u);const y=h;throw y.code==="ENOTFOUND"?new w(`Error connecting to ${y.hostname} (${y.syscall})`):y}};class Hc extends Z{constructor(e){super(e),this.params=e,this.baseURL="https://models.github.ai",this.colors={primary:"#24292e",secondary:"#FFF"},this.serviceName=b.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[GitHub Models]"),this.errorPrefix=b.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 T(this.generateMessage("commit")).pipe(_(e=>O(e)),N(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:this.params.config.includeBody?e.value:e.title,description:this.params.config.includeBody?e.value:"",isError:!1})),F(this.handleError$))}generateCodeReview$(){return T(this.generateMessage("review")).pipe(_(e=>O(e)),N(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),F(this.handleError$))}async generateMessage(e){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={...Y,locale:i,maxLength:d,type:a,generate:l,systemPrompt:o,systemPromptPath:n,codeReviewPromptPath:s,vcs_branch:this.params.branchName||""},u=e==="review"?te(c):ee(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=vr(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;X(r,o,"GitHub Models",n,a,d,c),Q(r,o,"GitHub Models",e,o==="review"?r:`Here's the diff:
|
|
88
88
|
|
|
89
|
-
${r}`,c),re(r,o,"GitHub Models",l,c);const u=new AbortController,m=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(m),!h.ok){const E=await h.text(),b={status:h.status,statusText:h.statusText,url:a,headers:Object.fromEntries(h.headers),body:E};B(r,o,"GitHub Models",b,c);let A=`GitHub API request failed: ${h.status} ${h.statusText}`;try{const P=JSON.parse(E);P.error?.message?A+=` - ${P.error.message}`:P.message&&(A+=` - ${P.message}`)}catch{E&&(A+=` - ${E}`)}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=E,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=E,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=E,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=E,P}const k=new Error(A);throw k.status=h.status,k.code="API_ERROR",k.content=E,k}const g=await h.json(),y=Date.now()-p;K(r,o,"GitHub Models",g,c);const v=g.choices?.[0]?.message?.content?.trim();if(!v){B(r,o,"GitHub Models",{message:"No content found in GitHub Models response",result:g},c);const b=new Error("No response content received from GitHub Models");throw b.code="NO_CONTENT",b.content=JSON.stringify(g,null,2),b}return W(r,o,"GitHub Models",y,v,c),v}catch(p){if(clearTimeout(m),p instanceof Error&&p.name==="AbortError"){const y={message:`GitHub Models request timeout after ${this.params.config.timeout}ms`,error:p};B(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;B(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 Hc extends Z{constructor(e){super(e),this.params=e,this.colors={primary:"#f55036",secondary:"#fff"},this.serviceName=C.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[Groq]"),this.errorPrefix=C.red.bold("[Groq]"),this.groq=new es({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 T(this.generateMessage("commit")).pipe(_(e=>D(e)),F(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})),L(this.handleError$))}generateCodeReview$(){return T(this.generateMessage("review")).pipe(_(e=>D(e)),F(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),L(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,m=this.params.config.maxTokens,p={...Y,locale:l,maxLength:u,type:c,generate:d,systemPrompt:o,systemPromptPath:n,codeReviewPromptPath:s},h=e==="review"?te(p):ee(p),g=`Here is the diff: ${r}`,v=`${this.params.config.url||"https://api.groq.com"}/openai/v1/chat/completions`,E={Authorization:`Bearer ${this.params.config.key}`,"Content-Type":"application/json"};X(r,e,"Groq",this.params.config.model,v,E,i),Q(r,e,"Groq",h,g,i);const b={messages:[{role:"system",content:h},{role:"user",content:g}],model:this.params.config.model,max_tokens:m,top_p:this.params.config.topP,temperature:a};re(r,e,"Groq",b,i);const A=Date.now();try{const k=await this.groq.chat.completions.create(b,{timeout:this.params.config.timeout}),P=Date.now()-A,$=k.choices[0].message.content||"";return K(r,e,"Groq",k,i),W(r,e,"Groq",P,$,i),e==="review"?this.sanitizeResponse($):this.parseMessage($,c,d)}catch(k){throw B(r,e,"Groq",k,i),k}}}class Uc extends Z{constructor(e){super(e),this.params=e,this.headers={},this.models=[],this.currentModelId=null,this.currentConversation=void 0,this.currentConversionID=void 0,this.cookie="",this.colors={primary:"#FED21F",secondary:"#000"},this.serviceName=C.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[HuggingFace]"),this.errorPrefix=C.red.bold("[HuggingFace]"),this.cookie=this.params.config.cookie;const r=this.params.config.url||"https://huggingface.co";this.headers={accept:"*/*","accept-language":"en-US,en;q=0.9","sec-ch-ua":'"Chromium";v="116", "Not)A;Brand";v="24", "Google Chrome";v="116"',"sec-ch-ua-mobile":"?0","sec-ch-ua-platform":'"Windows"',"sec-fetch-dest":"empty","sec-fetch-mode":"cors","sec-fetch-site":"same-origin",origin:r,"Referrer-Policy":"strict-origin-when-cross-origin"}}getServiceSpecificErrorMessage(e){const r=e.message||"";return r.includes("cookie")||r.includes("Cookie")?"Invalid cookie. Check your Hugging Face session cookie in configuration":r.includes("model")||r.includes("Model")?"Model not found or not accessible. Check if the Hugging Face model name is correct":r.includes("conversation")||r.includes("conversion")?"Failed to create conversation. Try again or check your session":r.includes("401")||r.includes("Unauthorized")?"Authentication failed. Your Hugging Face session may have expired":r.includes("403")||r.includes("Forbidden")?"Access denied. You may not have permission to access this model":r.includes("404")||r.includes("Not Found")?"Model not found. Check your Hugging Face model configuration":r.includes("500")||r.includes("Internal Server Error")?"Hugging Face server error. Try again later":r.includes("overloaded")||r.includes("capacity")?"Hugging Face service is overloaded. Try again in a few minutes":null}generateCommitMessage$(){return T(this.generateMessage("commit")).pipe(_(e=>D(e)),F(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})),L(this.handleError$))}generateCodeReview$(){return T(this.generateMessage("review")).pipe(_(e=>D(e)),F(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),L(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:m,topP:p,timeout:h}=this.params.config,g={...Y,locale:l,maxLength:c,type:d,generate:a,systemPrompt:o,systemPromptPath:n,codeReviewPromptPath:s},y=e==="review"?te(g):ee(g),v=`Here is the diff: ${r}`,b=`${this.params.config.url||"https://huggingface.co"}/chat/conversation`,A={...this.headers,cookie:this.cookie};X(r,e,"HuggingFace",this.params.config.model,b,A,i),Q(r,e,"HuggingFace",y,v,i);const k=Date.now();try{const P=await this.getNewChat(y),S=await(await this.sendMessage(v,P.id)).completeResponsePromise();await this.deleteConversation(P.id);const M=Date.now()-k;return K(r,e,"HuggingFace",{response:S},i),W(r,e,"HuggingFace",M,S,i),e==="review"?this.sanitizeResponse(S):this.parseMessage(S,d,a)}catch(P){throw B(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(g=>l(g));c.promptExamples=h.map(g=>({title:n[g.title],prompt:n[g.prompt]}))}const m=l(d.parameters),p={};for(const[h,g]of Object.entries(m)){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],m=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:m,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 E of y)E.trim()&&v.push(JSON.parse(E));return v}catch{return[{}]}}const c=new TextDecoder;let u="";const m=new TransformStream({async transform(g,y){const v=c.decode(g);try{const E=d(v);for(const b of E)b.type==="finalAnswer"?(u=b?.text||"",y.terminate()):b.type==="stream"&&y.enqueue(b?.token||"")}catch{throw new Error("Error during parsing response")}}}),p=a.body?.pipeThrough(m);async function h(){return new Promise(async(g,y)=>{try{if(!p)y("ModifiedStream undefined");else{const v=p.getReader();for(;;){const{done:E,value:b}=await v.read();if(E){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 zc extends Z{constructor(e){super(e),this.params=e,this.apiKey="",this.colors={primary:"#ff7000",secondary:"#fff"},this.serviceName=C.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[MistralAI]"),this.errorPrefix=C.red.bold("[MistralAI]"),this.apiKey=this.params.config.key}getServiceSpecificErrorMessage(e){const r=e.message||"";return r.includes("API key")||r.includes("api_key")?"Invalid API key. Check your Mistral AI API key in configuration":r.includes("quota")||r.includes("usage")?"API quota exceeded. Check your Mistral AI usage limits":r.includes("model")||r.includes("Model")?"Model not found or not accessible. Check if the Mistral model name is correct":r.includes("403")||r.includes("Forbidden")?"Access denied. Your API key may not have permission for this Mistral model":r.includes("404")||r.includes("Not Found")?"Model or endpoint not found. Check your Mistral model configuration":r.includes("500")||r.includes("Internal Server Error")?"Mistral AI server error. Try again later":null}generateCommitMessage$(){return T(this.generateMessage("commit")).pipe(_(e=>D(e)),F(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})),L(this.handleError$))}generateCodeReview$(){return T(this.generateMessage("review")).pipe(_(e=>D(e)),F(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),L(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={...Y,locale:l,maxLength:c,type:d,generate:a,systemPrompt:o,systemPromptPath:n,codeReviewPromptPath:s},m=e==="review"?te(u):ee(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"};X(r,e,"MistralAI",this.params.config.model,g,y,i),Q(r,e,"MistralAI",m,p,i);const v=await this.createChatCompletions(m,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 He({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:ut(10,1e3)};re(n,o,"MistralAI",i,s);const l=Date.now();try{const a=this.params.config.url||"https://api.mistral.ai",d=await new He({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(K(n,o,"MistralAI",u,s),!u.choices||u.choices.length===0||!u.choices[0].message?.content)throw B(n,o,"MistralAI",{message:"No Content on response",result:u},s),new Error("No Content on response. Please open a Bug report");const p=u.choices[0].message.content;return W(n,o,"MistralAI",c,p,s),p}catch(a){throw B(n,o,"MistralAI",a,s),a}}}class Kc extends Z{constructor(e){super(e),this.params=e,this.host=tr,this.model="",this.key="",this.auth="",this.setupFetch=(r,o={})=>rs(r,{...o,dispatcher:new os({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(`[${lt(this.model)}]`),this.errorPrefix=C.red.bold(`[${lt(this.model)}]`),this.host=this.params.config.host||tr,this.auth=this.params.config.auth||"Bearer",this.key=this.params.config.key||"",this.ollama=new ts({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 T(this.generateMessage("commit")).pipe(_(e=>D(e)),F(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})),L(this.handleError$))}generateCodeReview$(){return T(this.generateMessage("review")).pipe(_(e=>D(e)),F(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),L(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={...Y,locale:l,maxLength:c,type:d,generate:a,systemPrompt:o,systemPromptPath:n,codeReviewPromptPath:s},m=e==="review"?te(u):ee(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}`}:{};X(r,e,h,this.model,g,y,i),Q(r,e,h,m,p,i);const v=await this.createChatCompletions(m,p,e);return e==="review"?this.sanitizeResponse(v):this.parseMessage(v,d,a)}async checkIsAvailableOllama(){const e=new He({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,m=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:ut(10,1e3),num_predict:d??-1}};re(m,o,p,h,c);const g=Date.now();try{const y=await this.ollama.chat(h),v=Date.now()-g;let E="";if(u){if(y)for await(const b of y)E+=b.message.content}else E=y.message.content;return K(m,o,p,{response:E,fullResponse:y},c),W(m,o,p,v,E,c),E}catch(y){throw B(m,o,p,y,c),y}}}class Wc extends Z{constructor(e){super(e),this.params=e;const r=this.params.keyName||"OPENAI_COMPATIBLE";this.colors=_a(r),this.serviceName=C.bgHex(this.colors.primary).hex(this.colors.secondary).bold(`[${lt(r)}]`),this.errorPrefix=C.red.bold(`[${lt(r)}]`),this.openAI=new Ur({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 T(this.generateMessage("commit")).pipe(_(e=>D(e)),F(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})),L(this.handleError$))}generateCodeReview$(){return T(this.generateMessage("review")).pipe(_(e=>D(e)),F(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),L(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:m,stream:p=!1}=this.params.config,h=this.params.config.maxTokens,g={...Y,locale:l,maxLength:u,type:c,generate:d,systemPrompt:o,systemPromptPath:n,codeReviewPromptPath:s},y=e==="review"?te(g):ee(g),v=`Here is the diff: ${r}`,E=this.params.keyName||"OpenAI-Compatible",b=`${this.params.config.url}${this.params.config.path}`,A={Authorization:`Bearer ${this.params.config.key}`,"Content-Type":"application/json"};X(r,e,E,this.params.config.model,b,A,i),Q(r,e,E,y,v,i);const k=yr(this.params.config.model),P={messages:[{role:"system",content:y},{role:"user",content:v}],model:this.params.config.model,stream:p,...k?{max_completion_tokens:h,temperature:1}:{max_tokens:h,top_p:this.params.config.topP,temperature:a}};re(r,e,E,P,i);const $=Date.now();try{const S=await this.openAI.chat.completions.create(P,{timeout:m});let M="";if(p&&S){const kt=S;for await(const Me of kt){const kn=Me.choices?.[0]?.delta?.content||"",Sn=Me.choices?.[0]?.delta?.reasoning_content||"",xn=`${kn}${Sn}`;M+=xn}}else M=S.choices?.[0]?.message.content||"";const R=Date.now()-$;return K(r,e,E,S,i),W(r,e,E,R,M,i),e==="review"?this.sanitizeResponse(M):this.parseMessage(M,c,d)}catch(S){throw B(r,e,E,S,i),S}}}class Yc extends Z{constructor(e){super(e),this.params=e,this.colors={primary:"#74AA9C",secondary:"#FFF"},this.serviceName=C.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[ChatGPT]"),this.errorPrefix=C.red.bold("[ChatGPT]")}getServiceSpecificErrorMessage(e){const r=e.message||"";return r.includes("API key")?"Invalid API key. Check your OpenAI API key in configuration":r.includes("quota")?"API quota exceeded. Check your OpenAI usage limits":r.includes("500")?"OpenAI server error. Try again later":null}generateCommitMessage$(){return T(this.generateMessage("commit")).pipe(_(e=>D(e)),F(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})),L(this.handleError$))}generateCodeReview$(){return T(this.generateMessage("review")).pipe(_(e=>D(e)),F(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),L(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:m,maxTokens:p,timeout:h}=this.params.config,g={...Y,locale:a,maxLength:u,type:c,generate:d,systemPrompt:o,systemPromptPath:n,codeReviewPromptPath:s},y=e==="review"?te(g):ee(g),v=await Bc("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,m);return dt(e==="review"?v.map(E=>this.sanitizeResponse(E)):v.map(E=>this.parseMessage(E,c,d)))}}class Jc extends Z{constructor(e){super(e),this.params=e,this.apiKey="",this.colors={primary:"#20808D",secondary:"#FFF"},this.serviceName=C.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[Perplexity]"),this.errorPrefix=C.red.bold("[Perplexity]"),this.apiKey=this.params.config.key}getServiceSpecificErrorMessage(e){const r=e.message||"";return r.includes("API key")||r.includes("api_key")?"Invalid API key. Check your Perplexity API key in configuration":r.includes("rate_limit")||r.includes("Rate limit")?"Rate limit exceeded. Wait a moment and try again, or upgrade your Perplexity plan":r.includes("model")||r.includes("Model")?"Model not found or not accessible. Check if the Perplexity model name is correct":r.includes("overloaded")||r.includes("capacity")?"Perplexity service is overloaded. Try again in a few minutes":r.includes("403")||r.includes("Forbidden")?"Access denied. Your API key may not have permission for this Perplexity model":r.includes("404")||r.includes("Not Found")?"Model or endpoint not found. Check your Perplexity model configuration":r.includes("500")||r.includes("Internal Server Error")?"Perplexity server error. Try again later":null}generateCommitMessage$(){return T(this.generateMessage("commit")).pipe(_(e=>D(e)),F(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})),L(this.handleError$))}generateCodeReview$(){return T(this.generateMessage("review")).pipe(_(e=>D(e)),F(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),L(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={...Y,locale:l,maxLength:c,type:d,generate:a,systemPrompt:o,systemPromptPath:n,codeReviewPromptPath:s},m=e==="review"?te(u):ee(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"};X(r,e,"Perplexity",this.params.config.model,g,y,i),Q(r,e,"Perplexity",m,p,i);const v=await this.createChatCompletions(m,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};re(n,o,"Perplexity",i,s);const l=Date.now();try{const a=this.params.config.url||"https://api.perplexity.ai",d=await new He({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(K(n,o,"Perplexity",u,s),!u.choices||u.choices.length===0||!u.choices[0].message?.content)throw B(n,o,"Perplexity",{message:"No Content on response",result:u},s),new Error("No Content on response. Please open a Bug report");const p=u.choices[0].message.content;return W(n,o,"Perplexity",c,p,s),p}catch(a){throw B(n,o,"Perplexity",a,s),a}}}class vt{constructor(e,r){this.config=e,this.stagedDiff=r}createCommitMsgRequests$(e){return this.createServiceRequests$(e,"commit")}createCodeReviewRequests$(e){return this.createServiceRequests$(e,"review")}createServiceRequests$(e,r){return D(e).pipe(Nr(o=>{const n=this.config[o],s=Array.isArray(n.model)?n.model:[n.model];return D(s).pipe(Nr(i=>{if(n.compatible){const l=q.create(Wc,{config:{...n,url:n.url||"",path:n.path||"",model:i},stagedDiff:this.stagedDiff,keyName:i});return r==="commit"?l.generateCommitMessage$():l.generateCodeReview$()}switch(o){case"OPENAI":{const a=q.create(Yc,{config:{...this.config.OPENAI,model:i},stagedDiff:this.stagedDiff,keyName:i});return r==="commit"?a.generateCommitMessage$():a.generateCodeReview$()}case"GEMINI":{const a=q.create(cc,{config:{...this.config.GEMINI,model:i},stagedDiff:this.stagedDiff,keyName:i});return r==="commit"?a.generateCommitMessage$():a.generateCodeReview$()}case"ANTHROPIC":{const a=q.create(rc,{config:{...this.config.ANTHROPIC,model:i},stagedDiff:this.stagedDiff,keyName:i});return r==="commit"?a.generateCommitMessage$():a.generateCodeReview$()}case"HUGGINGFACE":{const a=q.create(Uc,{config:{...this.config.HUGGINGFACE,model:i},stagedDiff:this.stagedDiff,keyName:i});return r==="commit"?a.generateCommitMessage$():a.generateCodeReview$()}case"MISTRAL":{const a=q.create(zc,{config:{...this.config.MISTRAL,model:i},stagedDiff:this.stagedDiff,keyName:i});return r==="commit"?a.generateCommitMessage$():a.generateCodeReview$()}case"CODESTRAL":{const a=q.create(sc,{config:{...this.config.CODESTRAL,model:i},stagedDiff:this.stagedDiff,keyName:i});return r==="commit"?a.generateCommitMessage$():a.generateCodeReview$()}case"OLLAMA":{const a=q.create(Kc,{config:{...this.config.OLLAMA,model:i},keyName:i,stagedDiff:this.stagedDiff});return r==="commit"?a.generateCommitMessage$():a.generateCodeReview$()}case"COHERE":{const a=q.create(ic,{config:{...this.config.COHERE,model:i},stagedDiff:this.stagedDiff,keyName:i});return r==="commit"?a.generateCommitMessage$():a.generateCodeReview$()}case"GROQ":{const a=q.create(Hc,{config:{...this.config.GROQ,model:i},stagedDiff:this.stagedDiff,keyName:i});return r==="commit"?a.generateCommitMessage$():a.generateCodeReview$()}case"PERPLEXITY":{const a=q.create(Jc,{config:{...this.config.PERPLEXITY,model:i},stagedDiff:this.stagedDiff,keyName:i});return r==="commit"?a.generateCommitMessage$():a.generateCodeReview$()}case"BEDROCK":{const a=q.create(nc,{config:{...this.config.BEDROCK,model:i},stagedDiff:this.stagedDiff,keyName:i});return r==="commit"?a.generateCommitMessage$():a.generateCodeReview$()}case"GITHUB_MODELS":{const a=q.create(Gc,{config:{...this.config.GITHUB_MODELS,model:i},stagedDiff:this.stagedDiff,keyName:i});return r==="commit"?a.generateCommitMessage$():a.generateCodeReview$()}case"DEEPSEEK":{const a=q.create(ac,{config:{...this.config.DEEPSEEK,model:i},stagedDiff:this.stagedDiff,keyName:i});return r==="commit"?a.generateCommitMessage$():a.generateCodeReview$()}default:const l=C.red.bold(`[${o}]`);return It({name:l+" Invalid AI type",value:"Invalid AI type",isError:!0,disabled:!0})}}))}),L(o=>{const n=C.red.bold("[UNKNOWN]");return It({name:n+` ${o.message||""}`,value:"Unknown error",isError:!0,disabled:!0})}))}}class wr{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 Ct extends wr{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 I("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 C=await h.text(),E={status:h.status,statusText:h.statusText,url:a,headers:Object.fromEntries(h.headers),body:C};B(r,o,"GitHub Models",E,c);let k=`GitHub API request failed: ${h.status} ${h.statusText}`;try{const A=JSON.parse(C);A.error?.message?k+=` - ${A.error.message}`:A.message&&(k+=` - ${A.message}`)}catch{C&&(k+=` - ${C}`)}if(h.status===401){const A=new Error("GitHub authentication failed. Please run: aicommit2 github-login");throw A.status=h.status,A.code="AUTHENTICATION_FAILED",A.content=C,A}else if(h.status===403){const A=new Error('GitHub Models access denied. Make sure your token has "Models" permission.');throw A.status=h.status,A.code="ACCESS_DENIED",A.content=C,A}else if(h.status===404){const A=new Error(`Model "${n}" not found. Please check the model name.`);throw A.status=h.status,A.code="MODEL_NOT_FOUND",A.content=C,A}else if(h.status===429){const A=new Error("Rate limit exceeded. Please try again later.");throw A.status=h.status,A.code="RATE_LIMIT_EXCEEDED",A.content=C,A}const P=new Error(k);throw P.status=h.status,P.code="API_ERROR",P.content=C,P}const y=await h.json(),g=Date.now()-p;K(r,o,"GitHub Models",y,c);const v=y.choices?.[0]?.message?.content?.trim();if(!v){B(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 W(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};B(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;B(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 Uc extends Z{constructor(e){super(e),this.params=e,this.colors={primary:"#f55036",secondary:"#fff"},this.serviceName=b.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[Groq]"),this.errorPrefix=b.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 T(this.generateMessage("commit")).pipe(_(e=>O(e)),N(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:this.params.config.includeBody?e.value:e.title,description:this.params.config.includeBody?e.value:"",isError:!1})),F(this.handleError$))}generateCodeReview$(){return T(this.generateMessage("review")).pipe(_(e=>O(e)),N(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),F(this.handleError$))}async generateMessage(e){const 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={...Y,locale:l,maxLength:u,type:c,generate:d,systemPrompt:o,systemPromptPath:n,codeReviewPromptPath:s,vcs_branch:this.params.branchName||""},h=e==="review"?te(p):ee(p),y=`Here is the diff: ${r}`,v=`${this.params.config.url||"https://api.groq.com"}/openai/v1/chat/completions`,C={Authorization:`Bearer ${this.params.config.key}`,"Content-Type":"application/json"};X(r,e,"Groq",this.params.config.model,v,C,i),Q(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 P=await this.groq.chat.completions.create(E,{timeout:this.params.config.timeout}),A=Date.now()-k,M=P.choices[0].message.content||"";return K(r,e,"Groq",P,i),W(r,e,"Groq",A,M,i),e==="review"?this.sanitizeResponse(M):this.parseMessage(M,c,d)}catch(P){throw B(r,e,"Groq",P,i),P}}}class zc extends Z{constructor(e){super(e),this.params=e,this.headers={},this.models=[],this.currentModelId=null,this.currentConversation=void 0,this.currentConversionID=void 0,this.cookie="",this.colors={primary:"#FED21F",secondary:"#000"},this.serviceName=b.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[HuggingFace]"),this.errorPrefix=b.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 T(this.generateMessage("commit")).pipe(_(e=>O(e)),N(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:this.params.config.includeBody?e.value:e.title,description:this.params.config.includeBody?e.value:"",isError:!1})),F(this.handleError$))}generateCodeReview$(){return T(this.generateMessage("review")).pipe(_(e=>O(e)),N(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),F(this.handleError$))}async generateMessage(e){await this.initialize();const 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={...Y,locale:l,maxLength:c,type:d,generate:a,systemPrompt:o,systemPromptPath:n,codeReviewPromptPath:s,vcs_branch:this.params.branchName||""},g=e==="review"?te(y):ee(y),v=`Here is the diff: ${r}`,E=`${this.params.config.url||"https://huggingface.co"}/chat/conversation`,k={...this.headers,cookie:this.cookie};X(r,e,"HuggingFace",this.params.config.model,E,k,i),Q(r,e,"HuggingFace",g,v,i);const P=Date.now();try{const A=await this.getNewChat(g),$=await(await this.sendMessage(v,A.id)).completeResponsePromise();await this.deleteConversation(A.id);const D=Date.now()-P;return K(r,e,"HuggingFace",{response:$},i),W(r,e,"HuggingFace",D,$,i),e==="review"?this.sanitizeResponse($):this.parseMessage($,d,a)}catch(A){throw B(r,e,"HuggingFace",A,i),A}}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 C of g)C.trim()&&v.push(JSON.parse(C));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 C=d(v);for(const E of C)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:C,value:E}=await v.read();if(C){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 Kc extends Z{constructor(e){super(e),this.params=e,this.apiKey="",this.colors={primary:"#ff7000",secondary:"#fff"},this.serviceName=b.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[MistralAI]"),this.errorPrefix=b.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 T(this.generateMessage("commit")).pipe(_(e=>O(e)),N(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:this.params.config.includeBody?e.value:e.title,description:this.params.config.includeBody?e.value:"",isError:!1})),F(this.handleError$))}generateCodeReview$(){return T(this.generateMessage("review")).pipe(_(e=>O(e)),N(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),F(this.handleError$))}async generateMessage(e){const 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={...Y,locale:l,maxLength:c,type:d,generate:a,systemPrompt:o,systemPromptPath:n,codeReviewPromptPath:s,vcs_branch:this.params.branchName||""},f=e==="review"?te(u):ee(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"};X(r,e,"MistralAI",this.params.config.model,y,g,i),Q(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 Ue({method:"GET",baseURL:`${e}/v1/models`,timeout:this.params.config.timeout}).setHeaders({Authorization:`Bearer ${this.apiKey}`,"content-type":"application/json"}).execute()).data.data.filter(o=>o.object==="model").map(o=>o.id)}async createChatCompletions(e,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:dt(10,1e3)};oe(n,o,"MistralAI",i,s);const l=Date.now();try{const a=this.params.config.url||"https://api.mistral.ai",d=await new Ue({method:"POST",baseURL:`${a}/v1/chat/completions`,timeout:this.params.config.timeout}).setHeaders({Authorization:`Bearer ${this.apiKey}`,"content-type":"application/json"}).setBody(i).execute(),c=Date.now()-l,u=d.data;if(K(n,o,"MistralAI",u,s),!u.choices||u.choices.length===0||!u.choices[0].message?.content)throw B(n,o,"MistralAI",{message:"No Content on response",result:u},s),new Error("No Content on response. Please open a Bug report");const p=u.choices[0].message.content;return W(n,o,"MistralAI",c,p,s),p}catch(a){throw B(n,o,"MistralAI",a,s),a}}}class Wc extends Z{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=b.bgHex(this.colors.primary).hex(this.colors.secondary).bold(`[${ut(this.model)}]`),this.errorPrefix=b.red.bold(`[${ut(this.model)}]`),this.host=this.params.config.host||rr,this.auth=this.params.config.auth||"Bearer",this.key=this.params.config.key||"",this.ollama=new rs({host:this.host,fetch:this.setupFetch,...this.key&&{headers:{Authorization:`${this.auth} ${this.key}`}}})}getServiceSpecificErrorMessage(e){const 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 T(this.generateMessage("commit")).pipe(_(e=>O(e)),N(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:this.params.config.includeBody?e.value:e.title,description:this.params.config.includeBody?e.value:"",isError:!1})),F(this.handleError$))}generateCodeReview$(){return T(this.generateMessage("review")).pipe(_(e=>O(e)),N(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),F(this.handleError$))}async generateMessage(e){const 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={...Y,locale:l,maxLength:c,type:d,generate:a,systemPrompt:o,systemPromptPath:n,codeReviewPromptPath:s,vcs_branch:this.params.branchName||""},f=e==="review"?te(u):ee(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}`}:{};X(r,e,h,this.model,y,g,i),Q(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 Ue({method:"GET",baseURL:`${this.host}`,timeout:this.params.config.timeout});return this.key&&e.setHeaders({Authorization:`${this.auth} ${this.key}`}),(await e.execute()).data}async createChatCompletions(e,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:dt(10,1e3),num_predict:d??-1}};oe(f,o,p,h,c);const y=Date.now();try{const g=await this.ollama.chat(h),v=Date.now()-y;let C="";if(u){if(g)for await(const E of g)C+=E.message.content}else C=g.message.content;return K(f,o,p,{response:C,fullResponse:g},c),W(f,o,p,v,C,c),C}catch(g){throw B(f,o,p,g,c),g}}}class Yc extends Z{constructor(e){super(e),this.params=e;const r=this.params.keyName||"OPENAI_COMPATIBLE";this.colors=Ta(r),this.serviceName=b.bgHex(this.colors.primary).hex(this.colors.secondary).bold(`[${ut(r)}]`),this.errorPrefix=b.red.bold(`[${ut(r)}]`),this.openAI=new Kr({apiKey:this.params.config.key,baseURL:`${this.params.config.url}${this.params.config.path}`})}getServiceSpecificErrorMessage(e){const r=e.message||"";return r.includes("API key")||r.includes("api_key")?"Invalid API key. Check your OpenAI-compatible API key in configuration":r.includes("rate_limit")||r.includes("Rate limit")?"Rate limit exceeded. Wait a moment and try again, or check your service limits":r.includes("model")||r.includes("Model")?"Model not found or not accessible. Check if the model name is correct":r.includes("network")||r.includes("connection")?"Network error. Check your internet connection and API endpoint":r.includes("quota")||r.includes("usage")?"API quota exceeded. Check your usage limits":r.includes("403")||r.includes("Forbidden")?"Access denied. Your API key may not have permission for this model":r.includes("404")||r.includes("Not Found")?"Model or endpoint not found. Check your API configuration":r.includes("500")||r.includes("Internal Server Error")?"Server error. Try again later":r.includes("overloaded")||r.includes("capacity")?"Service is overloaded. Try again in a few minutes":null}generateCommitMessage$(){return T(this.generateMessage("commit")).pipe(_(e=>O(e)),N(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:this.params.config.includeBody?e.value:e.title,description:this.params.config.includeBody?e.value:"",isError:!1})),F(this.handleError$))}generateCodeReview$(){return T(this.generateMessage("review")).pipe(_(e=>O(e)),N(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),F(this.handleError$))}async generateMessage(e){const 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={...Y,locale:l,maxLength:u,type:c,generate:d,systemPrompt:o,systemPromptPath:n,codeReviewPromptPath:s,vcs_branch:this.params.branchName||""},g=e==="review"?te(y):ee(y),v=`Here is the diff: ${r}`,C=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"};X(r,e,C,this.params.config.model,E,k,i),Q(r,e,C,g,v,i);const P=vr(this.params.config.model),A={messages:[{role:"system",content:g},{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,C,A,i);const M=Date.now();try{const $=await this.openAI.chat.completions.create(A,{timeout:f});let D="";if(p&&$){const re=$;for await(const Re of re){const Sn=Re.choices?.[0]?.delta?.content||"",xn=Re.choices?.[0]?.delta?.reasoning_content||"",In=`${Sn}${xn}`;D+=In}}else D=$.choices?.[0]?.message.content||"";const x=Date.now()-M;return K(r,e,C,$,i),W(r,e,C,x,D,i),e==="review"?this.sanitizeResponse(D):this.parseMessage(D,c,d)}catch($){throw B(r,e,C,$,i),$}}}class Jc extends Z{constructor(e){super(e),this.params=e,this.colors={primary:"#74AA9C",secondary:"#FFF"},this.serviceName=b.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[ChatGPT]"),this.errorPrefix=b.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 T(this.generateMessage("commit")).pipe(_(e=>O(e)),N(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:this.params.config.includeBody?e.value:e.title,description:this.params.config.includeBody?e.value:"",isError:!1})),F(this.handleError$))}generateCodeReview$(){return T(this.generateMessage("review")).pipe(_(e=>O(e)),N(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),F(this.handleError$))}extractJSONFromError(e){const 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={...Y,locale:a,maxLength:u,type:c,generate:d,systemPrompt:o,systemPromptPath:n,codeReviewPromptPath:s,vcs_branch:this.params.branchName||""},g=e==="review"?te(y):ee(y),v=await Gc("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 mt(e==="review"?v.map(C=>this.sanitizeResponse(C)):v.map(C=>this.parseMessage(C,c,d)))}}class Vc extends Z{constructor(e){super(e),this.params=e,this.apiKey="",this.colors={primary:"#20808D",secondary:"#FFF"},this.serviceName=b.bgHex(this.colors.primary).hex(this.colors.secondary).bold("[Perplexity]"),this.errorPrefix=b.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 T(this.generateMessage("commit")).pipe(_(e=>O(e)),N(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:this.params.config.includeBody?e.value:e.title,description:this.params.config.includeBody?e.value:"",isError:!1})),F(this.handleError$))}generateCodeReview$(){return T(this.generateMessage("review")).pipe(_(e=>O(e)),N(e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1})),F(this.handleError$))}extractJSONFromError(e){const 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={...Y,locale:l,maxLength:c,type:d,generate:a,systemPrompt:o,systemPromptPath:n,codeReviewPromptPath:s,vcs_branch:this.params.branchName||""},f=e==="review"?te(u):ee(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"};X(r,e,"Perplexity",this.params.config.model,y,g,i),Q(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 Ue({method:"POST",baseURL:`${a}/chat/completions`,timeout:this.params.config.timeout}).setHeaders({Authorization:`Bearer ${this.apiKey}`,"content-type":"application/json"}).setBody(i).execute(),c=Date.now()-l,u=d.data;if(K(n,o,"Perplexity",u,s),!u.choices||u.choices.length===0||!u.choices[0].message?.content)throw B(n,o,"Perplexity",{message:"No Content on response",result:u},s),new Error("No Content on response. Please open a Bug report");const p=u.choices[0].message.content;return W(n,o,"Perplexity",c,p,s),p}catch(a){throw B(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 O(e).pipe(Tr(o=>{const n=this.config[o],s=Array.isArray(n.model)?n.model:[n.model];return O(s).pipe(Tr(i=>{if(n.compatible){const l=q.create(Yc,{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=q.create(Jc,{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=q.create(lc,{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=q.create(oc,{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=q.create(zc,{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=q.create(Kc,{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=q.create(ic,{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=q.create(Wc,{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=q.create(ac,{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=q.create(Uc,{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=q.create(Vc,{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=q.create(sc,{config:{...this.config.BEDROCK,model:i},stagedDiff:this.stagedDiff,keyName:i});return r==="commit"?a.generateCommitMessage$():a.generateCodeReview$()}case"GITHUB_MODELS":{const a=q.create(Hc,{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=q.create(cc,{config:{...this.config.DEEPSEEK,model:i},stagedDiff:this.stagedDiff,keyName:i,branchName:this.branchName});return r==="commit"?a.generateCommitMessage$():a.generateCodeReview$()}default:const l=b.red.bold(`[${o}]`);return Mt({name:l+" Invalid AI type",value:"Invalid AI type",isError:!0,disabled:!0})}}))}),F(o=>{const n=b.red.bold("[UNKNOWN]");return Mt({name:n+` ${o.message||""}`,value:"Unknown error",isError:!0,disabled:!0})}))}}class br{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 Ct extends br{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
|
|
99
|
-
`).filter(Boolean);for(const
|
|
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
|
+
`).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
|
|
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
|
|
104
|
-
`).filter(Boolean);for(const
|
|
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
|
+
`).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
|
-
`;for(const
|
|
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=[]){try{await S("git",["commit","-m",e,...r],{stdio:"inherit"})}catch(o){const n=o;throw n.stderr?n.stderr.includes("nothing to commit")?new w(`Nothing to commit.
|
|
110
110
|
|
|
111
111
|
Stage your changes with: git add <files>
|
|
112
112
|
Or use the --all flag to stage all changes.`):n.stderr.includes("Please enter the commit message")?new w(`Commit message cannot be empty.
|
|
@@ -117,33 +117,33 @@ Configure with:
|
|
|
117
117
|
git config --global user.name "Your Name"
|
|
118
118
|
git config --global user.email "your.email@example.com"`):n.stderr.includes("Permission denied")?new w(`Git permission error: ${n.stderr.trim()}
|
|
119
119
|
|
|
120
|
-
Check repository permissions and file access.`):new w(`Git commit failed: ${n.stderr.trim()}`):n.exitCode===1?new w("Git commit failed. Check your staged changes and try again."):new w(`Failed to commit with Git: ${n.message||"Unknown error"}`)}}async getCommentChar(){try{const{stdout:e}=await
|
|
120
|
+
Check repository permissions and file access.`):new w(`Git commit failed: ${n.stderr.trim()}`):n.exitCode===1?new w("Git commit failed. Check your staged changes and try again."):new w(`Failed to commit with Git: ${n.message||"Unknown error"}`)}}async getCommentChar(){try{const{stdout:e}=await 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 Cr extends br{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=I.join(o,".jj");if(!V.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
|
|
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=[],y=f.split(`
|
|
135
|
+
`);for(const C of y)if(C.includes("(binary)")||C.includes("Binary file")){const E=C.match(/([^\s]+)\s*\(binary\)/);E&&E[1]&&h.push(E[1])}let g=u;if(h.length>0){g+=`
|
|
136
136
|
|
|
137
137
|
--- Binary Files Changed ---
|
|
138
|
-
`;for(const
|
|
139
|
-
`}const v=[...new Set([...p,...h])];return{files:v,diff:
|
|
138
|
+
`;for(const C of h)g+=`Binary file ${C} changed
|
|
139
|
+
`}const v=[...new Set([...p,...h])];return{files:v,diff:g||`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=[]){try{await S("jj",["describe","-m",e,...r],{stdio:"inherit"}),await S("jj",["new"],{stdio:"inherit"})}catch(o){const n=o;throw n.stderr?n.stderr.includes("Empty commit message")?new w(`Commit message cannot be empty.
|
|
147
147
|
|
|
148
148
|
Provide a meaningful commit message.`):n.stderr.includes("No changes to commit")?new w(`No changes to commit.
|
|
149
149
|
|
|
@@ -151,12 +151,13 @@ Make some changes first, then try again.`):n.stderr.includes("Invalid revision")
|
|
|
151
151
|
|
|
152
152
|
Ensure you're in a valid workspace with changes.`):n.stderr.includes("Operation not allowed")?new w(`Jujutsu operation not allowed: ${n.stderr.trim()}
|
|
153
153
|
|
|
154
|
-
Check repository state with: jj status`):new w(`Jujutsu describe failed: ${n.stderr.trim()}`):n.exitCode===1?new w("Jujutsu commit failed. Check your changes and repository state."):new w(`Failed to commit with Jujutsu: ${n.message||"Unknown error"}`)}}async getCommentChar(){try{const{stdout:e}=await
|
|
154
|
+
Check repository state with: jj status`):new w(`Jujutsu describe failed: ${n.stderr.trim()}`):n.exitCode===1?new w("Jujutsu commit failed. Check your changes and repository state."):new w(`Failed to commit with Jujutsu: ${n.message||"Unknown error"}`)}}async getCommentChar(){try{const{stdout:e}=await 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 Er extends br{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).
|
|
155
156
|
|
|
156
157
|
YADM work tree: ${s}
|
|
157
158
|
Expected: ${i}
|
|
158
159
|
|
|
159
|
-
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").
|
|
160
161
|
|
|
161
162
|
Git directory: ${a}
|
|
162
163
|
|
|
@@ -167,19 +168,19 @@ Please install YADM first: https://yadm.io/`);if(r.stderr){if(r.stderr.includes(
|
|
|
167
168
|
Initialize with: yadm init
|
|
168
169
|
Or clone your dotfiles: yadm clone <url>`);if(r.stderr.includes("permission denied"))throw new w(`YADM permission denied: ${r.stderr.trim()}
|
|
169
170
|
|
|
170
|
-
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
|
|
171
|
-
`).filter(Boolean),{stdout:l}=await
|
|
172
|
-
`).filter(Boolean);for(const
|
|
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
|
+
`).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+=`
|
|
173
174
|
|
|
174
175
|
--- Binary Files Changed ---
|
|
175
|
-
`;for(const
|
|
176
|
-
`}}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
|
|
177
|
-
`).filter(Boolean);for(const
|
|
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
|
+
`).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+=`
|
|
178
179
|
|
|
179
180
|
--- Binary Files Changed ---
|
|
180
|
-
`;for(const
|
|
181
|
+
`;for(const f of a)c+=`Binary file ${f} changed
|
|
181
182
|
`}const u=[...new Set([...s.split(`
|
|
182
|
-
`).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=[]){try{await S("yadm",["commit","-m",e,...r],{stdio:"inherit"})}catch(o){const n=o;throw n.stderr?n.stderr.includes("nothing to commit")?new w(`Nothing to commit.
|
|
183
184
|
|
|
184
185
|
Stage your changes with: yadm add <file>
|
|
185
186
|
Or stage tracked file modifications: aicommit2 --all
|
|
@@ -192,14 +193,14 @@ Configure with:
|
|
|
192
193
|
yadm config --global user.name "Your Name"
|
|
193
194
|
yadm config --global user.email "your.email@example.com"`):n.stderr.includes("Permission denied")?new w(`YADM permission error: ${n.stderr.trim()}
|
|
194
195
|
|
|
195
|
-
Check repository permissions and file access.`):new w(`YADM commit failed: ${n.stderr.trim()}`):n.exitCode===1?new w("YADM commit failed. Check your staged changes and try again."):new w(`Failed to commit with YADM: ${n.message||"Unknown error"}`)}}async getCommentChar(){try{const{stdout:e}=await
|
|
196
|
-
${c instanceof Error?c.message:String(c)}`)}if(e)try{const c=new
|
|
197
|
-
${c instanceof Error?c.message:String(c)}`)}if(r)try{const c=new
|
|
196
|
+
Check repository permissions and file access.`):new w(`YADM commit failed: ${n.stderr.trim()}`):n.exitCode===1?new w("YADM commit failed. Check your staged changes and try again."):new w(`Failed to commit with YADM: ${n.message||"Unknown error"}`)}}async getCommentChar(){try{const{stdout:e}=await 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 Pr=null;async function qc(){const t=process.argv.includes("--git"),e=process.argv.includes("--yadm"),r=process.argv.includes("--jj");if(t)try{const c=new Ct;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 Er;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 Cr;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.
|
|
198
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 Ct;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.
|
|
199
|
-
${c instanceof Error?c.message:String(c)}`)}if(n)try{const c=new
|
|
200
|
-
${c instanceof Error?c.message:String(c)}`)}if(s)try{const c=new
|
|
201
|
-
${c instanceof Error?c.message:String(c)}`)}let i=!1;try{i=(await
|
|
202
|
-
${c instanceof Error?c.message:String(c)}`)}let l=null,a=null,d=null;try{const c=new
|
|
200
|
+
${c instanceof Error?c.message:String(c)}`)}if(n)try{const c=new Er;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 Cr;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 he({})).forceGit===!0}catch{i=!1}if(i)try{const c=new Ct;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 Cr;return await c.assertRepo(),c}catch(c){l=c instanceof Error?c:new Error(String(c))}try{const c=new Ct;return await c.assertRepo(),c}catch(c){a=c instanceof Error?c:new Error(String(c))}try{const c=new Er;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.
|
|
203
204
|
|
|
204
205
|
Jujutsu Error:
|
|
205
206
|
${c}
|
|
@@ -208,7 +209,7 @@ Git Error:
|
|
|
208
209
|
${u}
|
|
209
210
|
|
|
210
211
|
YADM Error:
|
|
211
|
-
${
|
|
212
|
+
${f}
|
|
212
213
|
|
|
213
214
|
Solutions:
|
|
214
215
|
\u2022 Initialize a Jujutsu repository: jj init
|
|
@@ -216,86 +217,86 @@ Solutions:
|
|
|
216
217
|
\u2022 Initialize a YADM repository: yadm init (or yadm clone <url>)
|
|
217
218
|
\u2022 Navigate to an existing Jujutsu, Git, or YADM repository
|
|
218
219
|
\u2022 Set FORCE_GIT="true" environment variable to force Git detection
|
|
219
|
-
\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 we(){return Pr||(Pr=await qc()),Pr}const Ar=async()=>(await we()).assertRepo(),$r=async(t,e)=>(await we()).getStagedDiff(t,e),Xc=async(t,e,r)=>{const o=await we();if(!o.getCommitDiff)throw new w(`Commit diff not supported for ${o.name}`);return o.getCommitDiff(t,e,r)},Qc=async()=>(await we()).getCommentChar(),Zc=t=>`Detected ${t.files.length.toLocaleString()} changed file${t.files.length>1?"s":""} (${t.diff.length.toLocaleString()} characters)`,Et=async()=>(await we()).name,el=async(t,e)=>{await(await we()).commit(t,e||[])},Pt=async()=>(await we()).getBranchName();class ce{constructor(){this.title="aicommit2"}printTitle(){try{const e=Yr.textSync(this.title,{font:"Small Slant"}),r=ss(["#8B5CF6","#A020F0","#D946EF"]);console.log(b.bold(r.multiline(e)))}catch{console.log(b.bold(Yr.textSync(this.title,{font:"Small Slant"})))}}showLoader(e){if(this.loader){this.loader.text=e;return}this.loader=Jr(e).start()}stopLoader(){this.loader?.stop(),this.loader=void 0}displaySpinner(e){return Jr(e).start()}stopSpinner(e){e.stop(),e.clear()}printStagedFiles(e){console.log(b.bold.green("\u2714 ")+b.bold(`${Zc(e)}:`)),console.log(`${e.files.map(r=>` ${r}`).join(`
|
|
220
221
|
`)}
|
|
221
222
|
`)}printAnalyzed(){console.log(`
|
|
222
|
-
${
|
|
223
|
-
${
|
|
224
|
-
${
|
|
225
|
-
${
|
|
226
|
-
${
|
|
227
|
-
${
|
|
228
|
-
${
|
|
229
|
-
${
|
|
230
|
-
${
|
|
231
|
-
${
|
|
232
|
-
${
|
|
233
|
-
|
|
234
|
-
Stage your changes with: yadm add <file>`,
|
|
235
|
-
Or stage tracked file modifications: aicommit2 --all`,
|
|
236
|
-
|
|
237
|
-
Note: The --all flag only stages already-tracked files (YADM best practice).`,
|
|
238
|
-
To track new dotfiles, explicitly add them first: yadm add <file>`):
|
|
239
|
-
|
|
240
|
-
Stage your changes with: git add <file>`,
|
|
241
|
-
Or automatically stage all changes: aicommit2 --all`):
|
|
242
|
-
|
|
243
|
-
Jujutsu automatically tracks all changes in the working copy.`,
|
|
244
|
-
Make some changes to your files and try again.`),new w(
|
|
223
|
+
${b.bold.green("\u2714")} ${b.bold("Changes analyzed")}`)}printCommitted(){console.log(`
|
|
224
|
+
${b.bold.green("\u2714")} ${b.bold("Successfully committed!")}`)}printCopied(){console.log(`
|
|
225
|
+
${b.bold.green("\u2714")} ${b.bold("Successfully copied! Press 'Ctrl + V' to paste")}`)}printSavedCommitMessage(){console.log(`
|
|
226
|
+
${b.bold.green("\u2714")} ${b.bold("Saved commit message")}`)}printCancelledCommit(){console.log(`
|
|
227
|
+
${b.bold.yellow("\u26A0")} ${b.yellow("Commit cancelled")}`)}printError(e){console.log(`
|
|
228
|
+
${b.bold.red("\u2716")} ${b.red(`${e}`)}`)}printWarning(e){console.log(`
|
|
229
|
+
${b.bold.yellow("\u26A0")} ${b.red(`${e}`)}`)}printSuccess(e){console.log(`
|
|
230
|
+
${b.bold.green("\u2714")} ${b.green(`${e}`)}`)}printInfo(e){console.log(`
|
|
231
|
+
${b.bold.blue("\u2139")} ${b.blue(`${e}`)}`)}printSetupGitEvent(e){console.log(`
|
|
232
|
+
${b.bold.green("\u2714")} ${b.bold(`Git ${e} hook has been set up`)}`)}moveCursorUp(){const e=et.createInterface({input:process.stdin,output:process.stdout});et.moveCursor(process.stdout,0,-1),e.close()}moveCursorDown(){const e=et.createInterface({input:process.stdin,output:process.stdout});et.moveCursor(process.stdout,0,2),e.close()}print(e){console.log(e)}}const tl={isLoading:!1,startOption:{text:"AI is analyzing your changes"}},yn={isLoading:!1,startOption:{text:"AI is performing a code review"}},kr="No commit messages were generated",wn="No code reviews were generated",Sr={type:"reactiveListPrompt",name:"aicommit2Prompt",message:"Pick a commit message to use: ",emptyMessage:`\u26A0 ${kr}`,loop:!1,descPageSize:15,showDescription:!0,pickKey:"short",isDescriptionDim:!0,stopMessage:"Changes analyzed"};class xr{constructor(e){this.choices$=new jr([]),this.destroyed$=new zn(1),this.stopMessage="Changes analyzed",this.isDestroyed=!1,this.subscriptions=new Rt,this.inquirerInstance=null,this.loader$=new jr(e)}addSubscription(e){if(this.isDestroyed){e.unsubscribe();return}this.subscriptions.add(e)}initPrompt(e=Sr){return this.stopMessage=e.stopMessage,Xe.registerPrompt("reactiveListPrompt",is),this.inquirerInstance=Xe.prompt({choices$:this.choices$,loader$:this.loader$,...e}),this.inquirerInstance}startLoader(){this.loader$.next({isLoading:!0})}clearLoader(){this.inquirerInstance&&this.loader$.next({isLoading:!1,clear:!0})}refreshChoices(e){this.isDestroyed||!e||!e.value||this.choices$.next([...this.currentChoices,e].sort(Na))}checkErrorOnChoices(e=!0){if(this.choices$.getValue().map(o=>o).every(o=>o?.isError||o?.disabled)){this.alertNoGeneratedMessage(),this.logEmptyCommitMessage(),e&&process.exit(1);return}this.stopLoaderOnSuccess()}completeSubject(){try{this.destroyed$.next(!0),this.destroyed$.complete(),this.choices$.closed||this.choices$.complete(),this.loader$.closed||this.loader$.complete()}catch(e){console.warn("Error completing subjects:",e)}}closeInquirerInstance(){if(!this.inquirerInstance)return;const e=this.inquirerInstance.ui;e?.rl&&!e.rl.closed&&e.close()}cancel(){this.inquirerInstance?.ui?.activePrompt&&this.inquirerInstance.ui.activePrompt.abortPrompt()}destroy(){if(!this.isDestroyed){this.isDestroyed=!0;try{this.cancel(),this.closeInquirerInstance(),this.subscriptions.unsubscribe(),this.completeSubject()}catch(e){yt()&&console.warn("Error during ReactivePromptManager destruction:",e)}finally{this.inquirerInstance=null}}}alertNoGeneratedMessage(){this.loader$.next({isLoading:!1,message:kr,stopOption:{doneFrame:"\u26A0",color:"yellow"}})}stopLoaderOnSuccess(){this.loader$.next({isLoading:!1,message:this.stopMessage})}logEmptyCommitMessage(){console.log(`
|
|
233
|
+
${b.bold.yellow("\u26A0")} ${b.yellow(`${kr}`)}`)}get currentChoices(){return this.choices$.getValue().map(e=>e)}}const J=new ce;var rl=async(t,e,r,o,n,s,i,l,a,d,c,u,f,p,h)=>(async()=>{if(J.printTitle(),await Ar(),o){const x=await Et();x==="git"?await S("git",["add","."]):x==="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 g=await he(y,h);(a===!0||g.includeBody===!0)&&Object.keys(g).forEach(x=>{typeof g[x]=="object"&&g[x]!==null&&"includeBody"in g[x]&&(g[x].includeBody=!0)}),u&&Object.keys(g).forEach(x=>{typeof g[x]=="object"&&g[x]!==null&&"disableLowerCase"in g[x]&&(g[x].disableLowerCase=!0)}),await rn(g);const C=J.displaySpinner("Detecting staged files"),E=await $r(r,g.exclude);if(C.stop(),!E){const x=await Et();let re="No staged changes found.";throw x==="yadm"?(re+=`
|
|
234
|
+
|
|
235
|
+
Stage your changes with: yadm add <file>`,re+=`
|
|
236
|
+
Or stage tracked file modifications: aicommit2 --all`,re+=`
|
|
237
|
+
|
|
238
|
+
Note: The --all flag only stages already-tracked files (YADM best practice).`,re+=`
|
|
239
|
+
To track new dotfiles, explicitly add them first: yadm add <file>`):x==="git"?(re+=`
|
|
240
|
+
|
|
241
|
+
Stage your changes with: git add <file>`,re+=`
|
|
242
|
+
Or automatically stage all changes: aicommit2 --all`):x==="jujutsu"&&(re+=`
|
|
243
|
+
|
|
244
|
+
Jujutsu automatically tracks all changes in the working copy.`,re+=`
|
|
245
|
+
Make some changes to your files and try again.`),new w(re)}J.printStagedFiles(E);const k=Zo(g,"commit");if(k.length===0)throw new w("Please set at least one API key via the `aicommit2 config set` command");const P=await Pt(),A=new bt(g,E,P),M=Zo(g,"review");M.length>0&&await ol(A,M);let $=await nl(A,k,d);if(c){if(J.printInfo("Opening editor to modify commit message..."),$=await sl($),!$.trim())throw new w("Commit message cannot be empty");J.printSuccess("Commit message edited successfully!"),J.print(`
|
|
245
246
|
${$}
|
|
246
247
|
`)}i&&($s("copy-paste").copy($),J.printCopied(),p||process.exit()),p&&(process.stdout.write($+`
|
|
247
|
-
`),process.exit()),(s||d&&
|
|
248
|
+
`),process.exit()),(s||d&&k.length===1)&&(await vn($,h),process.exit());const{confirmationPrompt:D}=await Xe.prompt([{type:"confirm",name:"confirmationPrompt",message:"Use selected message?",default:!0}]);D?await vn($,h):J.printCancelledCommit(),process.exit()})().catch(y=>{J.printError(y.message),de(y),process.exit(1)});async function ol(t,e){const r=new xr(yn);let o=null;try{const n=r.initPrompt({...Sr,name:"codeReviewPrompt",message:"Please check code reviews: ",emptyMessage:`\u26A0 ${wn}`,isDescriptionDim:!1,stopMessage:"Code review completed",descPageSize:20});if(r.startLoader(),o=t.createCodeReviewRequests$(e).subscribe({next:a=>r.refreshChoices(a),error:a=>{console.error("Code review request error:",a),r.checkErrorOnChoices()},complete:()=>r.checkErrorOnChoices()}),!(await n).codeReviewPrompt?.value)throw new w("An error occurred! No selected code review");J.moveCursorUp();const{continuePrompt:l}=await Xe.prompt([{type:"confirm",name:"continuePrompt",message:"Will you continue without changing the code?",default:!0}]);l||(J.printCancelledCommit(),process.exit())}finally{o&&o.unsubscribe(),r.destroy()}}async function nl(t,e,r){const o=new xr(tl);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(),J.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 J.print(`
|
|
248
249
|
${d.name}
|
|
249
|
-
`),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;J.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
|
|
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;J.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 sl(t){const e=process.env.VISUAL||process.env.EDITOR||(process.platform==="win32"?"notepad":"vi"),r=I.join(De.tmpdir(),`aicommit2-${Date.now()}-${Dn.randomBytes(4).toString("hex")}.txt`);try{V.writeFileSync(r,t,"utf8");const o=e.split(" "),[n,...s]=o;await S(n,[...s,r],{stdio:"inherit"});const i=V.readFileSync(r,"utf8").trim();if(V.unlinkSync(r),!i)throw new w("Commit cancelled - empty message");return i}catch(o){throw V.existsSync(r)&&V.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:
|
|
250
251
|
- Editor binary exists in PATH
|
|
251
252
|
- Editor flags are correct
|
|
252
|
-
- EDITOR/VISUAL is set correctly`):new w(`Failed to open editor "${e}". Please set your EDITOR or VISUAL environment variable to a valid editor command.`)}}async function
|
|
253
|
+
- EDITOR/VISUAL is set correctly`):new w(`Failed to open editor "${e}". Please set your EDITOR or VISUAL environment variable to a valid editor command.`)}}async function vn(t,e){await el(t,e),J.printCommitted()}var il=le({name:"config",parameters:["<mode>","[key=value...]"],help:{description:"Manage configuration settings",examples:["aic2 config set <key>=<value> [<key>=<value> ...]","aic2 config get [<key> [<key> ...]]","aic2 config add <key>=<value> [<key>=<value> ...]","aic2 config del <key>","aic2 config list"]},commands:[le({name:"set",parameters:["<key>=<value>","[<key>=<value> ...]"],help:{description:"Set configuration values. Multiple key-value pairs can be set at once.",examples:["aic2 config set OPENAI.key=<your key>","aic2 config set ANTHROPIC.topP=0.8 ANTHROPIC.generate=2"]}}),le({name:"get",parameters:["[<key>","[<key> ...]]"],help:{description:"Retrieve configuration values for specified AI provider.",examples:["aic2 config get OPENAI","aic2 config get ANTHROPIC"]}}),le({name:"add",parameters:["<key>=<value>","[<key>=<value> ...]"],help:{description:"Add new model to existing configuration. Only Ollama.model can be added.",examples:['aic2 config add OLLAMA.model="gemma2"']}}),le({name:"list",parameters:[],help:{description:"Display all configuration keys and their values.",examples:["aic2 config list"]}}),le({name:"del",parameters:["<config-name>"],help:{description:"Delete a configuration setting or section.",examples:["aic2 config del <config-name>","aic2 config del OPENAI.key","aic2 config del OPENAI"]}}),le({name:"path",parameters:[],help:{description:"Display the path of the loaded configuration file.",examples:["aic2 config path"]}})]},t=>{(async()=>{const{mode:e,keyValue:r}=t._,o=t._[1];if(e==="get"){const n=await he({},[]);if(r.length===0){console.log(n);return}for(const s of r){const i=s.split(".");let l=n,a=!0;for(const d of i)if(or(l,d))l=l[d];else{a=!1;break}a?console.log(s,l):console.log(`${s} not found`)}return}if(e==="set"){await nr(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 Ka(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 Wa();return}if(e==="del"){if(!o)throw new w("Please provide the config name to delete.");const n=await je(),s=o.split(".");if(s.length===2){const[i,l]=s;if(n[i]&&typeof n[i]=="object"&&or(n[i],l)){delete n[i][l],Object.keys(n[i]).length===0&&delete n[i];const a=await Se();await L.writeFile(a,$e.stringify(n),"utf8"),console.log(`Successfully deleted config: ${o}`);const d=await L.readFile(a,"utf8");console.log("--- Updated Config Content ---"),console.log(d),console.log("----------------------------")}else throw new w(`Config not found: ${o}`)}else if(s.length===1){const i=s[0];if(or(n,i)){delete n[i];const l=await Se();await L.writeFile(l,$e.stringify(n),"utf8"),console.log(`Successfully deleted config: ${o}`);const a=await L.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 Ya();return}throw new w(`Invalid mode: ${e}`)})().catch(e=>{new ce().printError(e.message),de(e),process.exit(1)})}),al=le({name:"github-login",parameters:[],flags:{token:{type:String,description:"Manually provide a GitHub token for authentication",alias:"t"}},help:{description:"Login to GitHub and setup access to GitHub Models",examples:["aic2 github-login","aic2 github-login --token ghp_xxxxxxxxxxxxxxxxxxxx"]}},t=>{(async()=>{const e=new ce;if(t.flags.token){try{await cl(t.flags.token,e)}catch(r){throw new w(`Token authentication failed: ${r.message}`)}return}try{await ll(e)}catch(r){throw new w(`Browser authentication failed: ${r.message}`)}})().catch(e=>{new ce().printError(e.message),de(e),process.exit(1)})});async function cl(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 nr([["GITHUB_MODELS.key",t]]),e.printSuccess(`Successfully authenticated as ${o.login}`)}catch(r){throw new Error(`Token validation failed: ${r.message}`)}}async function ll(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 nr([["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 Me="prepare-commit-msg",ul=async()=>{const t=await Et();if(t==="git")return`.git/hooks/${Me}`;if(t==="yadm"){const e=process.env.HOME||process.env.USERPROFILE;if(!e)throw new w("HOME environment variable not set. Cannot determine YADM hook path.");try{const{execa:n}=await Promise.resolve().then(function(){return Da}),{stdout:s}=await n("yadm",["introspect","repo"]),i=s.trim();if(i)return I.join(i,"hooks",Me)}catch{}const r=I.join(e,".config/yadm/hooks"),o=I.join(e,".yadm/hooks");try{return await L.access(r),I.join(r,Me)}catch{return I.join(o,Me)}}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)),dl=process.argv[1].replace(/\\/g,"/").includes(`/hooks/${Me}`),bn=process.platform==="win32",Cn=`
|
|
253
254
|
#!/usr/bin/env node
|
|
254
|
-
import(${JSON.stringify(
|
|
255
|
-
`.trim();var
|
|
256
|
-
`);const r=await Promise.all(e.map(async o=>{const n=
|
|
257
|
-
${
|
|
258
|
-
`,
|
|
259
|
-
`,
|
|
260
|
-
`,
|
|
261
|
-
`,
|
|
262
|
-
`,
|
|
263
|
-
`):(
|
|
264
|
-
`,
|
|
265
|
-
`,
|
|
266
|
-
`),
|
|
267
|
-
`),
|
|
255
|
+
import(${JSON.stringify(es(At))})
|
|
256
|
+
`.trim();var ml=le({name:"hook",parameters:["<install/uninstall>"],help:{description:"Install or uninstall the Git prepare-commit-msg hook",examples:["aic2 hook install","aic2 hook uninstall"]}},t=>{(async()=>{const e=await Ar(),{installUninstall:r}=t._,o=await ul(),n=I.isAbsolute(o)?o:I.join(e,o),s=await zo(n);if(r==="install"){if(s){if(await L.realpath(n).catch(()=>{})===At){console.warn("The hook is already installed");return}throw new w(`A different ${Me} hook seems to be installed. Please remove it before installing aicommit2.`)}await L.mkdir(I.dirname(n),{recursive:!0}),bn?await L.writeFile(n,Cn):(await L.symlink(At,n,"file"),await L.chmod(n,493)),console.log(`${b.green("\u2714")} Hook installed`);return}if(r==="uninstall"){if(!s){console.warn("Hook is not installed");return}if(bn){if(await L.readFile(n,"utf8")!==Cn){console.warn("Hook is not installed");return}}else if(await L.realpath(n)!==At){console.warn("Hook is not installed");return}await L.rm(n),console.log(`${b.green("\u2714")} Hook uninstalled`);return}throw new w(`Invalid mode: ${r}`)})().catch(e=>{console.error(`${b.red("\u2716")} ${e.message}`),de(e),process.exit(1)})});const fl=Un(On),pl=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]},hl=t=>t.toLocaleDateString()+" "+t.toLocaleTimeString(),gl=async t=>{try{const e=await Vr(ie);if(e.length===0){console.log(`${b.yellow("No log files found.")}`);return}console.log(`${b.blue("Log files in")} ${ie}:
|
|
257
|
+
`);const r=await Promise.all(e.map(async o=>{const n=fe.join(ie,o),s=await as(n);return{name:o,size:pl(s.size),modified:hl(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}":" "} ${b.cyan(o.name)} ${b.gray(`(${o.size}, ${o.modified})`)}`)}),console.log(`
|
|
258
|
+
${b.green("Total:")} ${e.length} file${e.length!==1?"s":""}`)}catch(e){if(e.code==="ENOENT")console.log(`${b.yellow("Logs directory does not exist yet.")}`);else throw e}},yl=async t=>{try{await Vr(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 fl(r),console.log(`${b.green("\u2714")} Opened logs directory in file manager`)}catch(e){e.code==="ENOENT"?console.log(`${b.yellow("Logs directory does not exist yet.")}`):t.printError(`Failed to open logs directory: ${e.message}`)}},wl=async t=>{try{await cs(ie,{recursive:!0,force:!0}),console.log(`${b.green("\u2714")} All log files removed!`)}catch(e){t.printError(`Failed to remove log files: ${e.message}`)}};var vl=le({name:"log",parameters:["<action>"],help:{description:"Manage log files generated by the application",examples:["aic2 log list # List all log files","aic2 log path # Show logs directory path","aic2 log open # Open logs directory","aic2 log removeAll # Remove all log files"]}},t=>{(async()=>{const{action:e}=t._,r=new ce;switch(e){case"list":await gl();break;case"path":console.log(`${b.blue("Logs directory:")} ${ie}`);break;case"open":await yl(r);break;case"removeAll":await wl(r);break;default:throw new w(`Invalid action: ${e}. Use 'list', 'path', 'open', or 'removeAll'`)}})().catch(e=>{new ce().printError(e.message),de(e),process.exit(1)})});const bl=process.argv.slice(2).filter(t=>!t.startsWith("--pre-commit")),[$t,En]=bl;var Cl=(t=!1)=>(async()=>{if(!$t)throw new w('Commit message file path is missing. This file should be called from the "pre-commit framework"');if(En){console.log(`Skipping aicommit2 message generation for ${En} commit`);return}const e=await $r();if(!e)return;const r=new ce;r.printTitle();const o={};t&&(o.logLevel="verbose");const n=await he(o);if(n.systemPromptPath)try{await L.readFile(I.resolve(n.systemPromptPath),"utf-8")}catch{throw new w(`Error reading system prompt file: ${n.systemPromptPath}`)}const s=Object.entries(n).filter(([g])=>ke.includes(g)).map(([g,v])=>[g,v]).filter(([g,v])=>!v.disabled).filter(([g,v])=>g==="OLLAMA"?!!v&&!!v.model&&v.model.length>0:g==="HUGGINGFACE"?!!v&&!!v.cookie:!!v.key&&v.key.length>0).map(([g])=>g);if(s.length===0)throw new w("Please set at least one API key via the `aicommit2 config set` command");const l=await Pt(),a=new bt(n,e,l);let d;try{d=await Br(a.createCommitMsgRequests$(s).pipe(Gr(g=>!g.isError),N(g=>g.value),Hr()))}finally{r.printAnalyzed()}const u=await L.readFile($t,"utf8")!=="",f=d.length>1;let p="";u&&(p=`# \u{1F916} Generated by aicommit2 (https://github.com/tak-bro/aicommit2)
|
|
259
|
+
`,p+=`# ----------------------------------------
|
|
260
|
+
`,p+=`# How to use:
|
|
261
|
+
`,f?(p+=`# 1. Remove the "#" from your chosen message
|
|
262
|
+
`,p+=`# 2. Edit the message if needed
|
|
263
|
+
`,p+=`# 3. Save and close the editor
|
|
264
|
+
`):(p+=`# 1. The message below will be used
|
|
265
|
+
`,p+=`# 2. Edit the message if needed
|
|
266
|
+
`,p+=`# 3. Save and close the editor
|
|
267
|
+
`),p+=`# ----------------------------------------
|
|
268
|
+
`),f?(u&&(p+=`
|
|
268
269
|
# \u{1F4DD} Choose one of these messages:
|
|
269
|
-
`),
|
|
270
|
-
${
|
|
271
|
-
`)}`):(
|
|
270
|
+
`),p+=`
|
|
271
|
+
${d.map(g=>`# ${g}`).join(`
|
|
272
|
+
`)}`):(u&&(p+=`
|
|
272
273
|
# \u{1F4DD} Generated commit message:
|
|
273
|
-
`),
|
|
274
|
-
${
|
|
275
|
-
`);const
|
|
276
|
-
`+
|
|
277
|
-
`,
|
|
278
|
-
`,
|
|
279
|
-
`,E?(
|
|
280
|
-
`,
|
|
281
|
-
`,
|
|
282
|
-
`):(
|
|
283
|
-
`,
|
|
284
|
-
`,
|
|
285
|
-
`),
|
|
286
|
-
`),E?(
|
|
287
|
-
${
|
|
288
|
-
`),
|
|
289
|
-
${g.map($=>`${
|
|
290
|
-
`)}`):(
|
|
291
|
-
${
|
|
292
|
-
`),
|
|
274
|
+
`),p+=`
|
|
275
|
+
${d[0]}
|
|
276
|
+
`);const h=await L.readFile($t,"utf8"),y=p+`
|
|
277
|
+
`+h;await L.writeFile($t,y),r.printSavedCommitMessage()})().catch(e=>{new ce().printError(e.message),de(e),process.exit(1)});const Ir=process.argv.slice(2),Pn=[];let Mr=!1;for(let t=0;t<Ir.length;t++){const e=Ir[t];if(Mr){Mr=!1;continue}if(e!=="--hook-mode"){if(e.startsWith("-")){const r=Ir[t+1];r&&!r.startsWith("-")&&(Mr=!0);continue}Pn.push(e)}}const[kt,An]=Pn;var El=(t,e,r,o,n,s,i)=>(async()=>{if(!kt)throw new w('Commit message file path is missing. This file should be called from the "prepare-commit-msg" git hook or with --hook-mode flag');if(An){console.log(`Skipping aicommit2 message generation for ${An} commit`);return}const l=await $r();if(!l)return;const a=new ce;a.printTitle();const d={locale:t?.toString(),generate:e?.toString(),type:o?.toString(),systemPrompt:n?.toString(),...s===!0&&{includeBody:"true"}};i&&(d.logLevel="verbose");const c=await he(d,r);if(c.systemPromptPath)try{await L.readFile(I.resolve(c.systemPromptPath),"utf-8")}catch{throw new w(`Error reading system prompt file: ${c.systemPromptPath}`)}const u=Object.entries(c).filter(([$])=>ke.includes($)).map(([$,D])=>[$,D]).filter(([$,D])=>!D.disabled).filter(([$,D])=>$==="OLLAMA"?!!D&&!!D.model&&D.model.length>0:$==="HUGGINGFACE"?!!D&&!!D.cookie:!!D.key&&D.key.length>0).map(([$])=>$);if(u.length===0)throw new w("Please set at least one API key via the `aicommit2 config set` command");const p=await Pt(),h=new bt(c,l,p),y=a.displaySpinner("The AI is analyzing your changes");let g;try{g=await Br(h.createCommitMsgRequests$(u).pipe(Gr($=>!$.isError),N($=>$.value),Hr()))}finally{y.stop(),y.clear(),a.printAnalyzed()}const C=await L.readFile(kt,"utf8")!=="",E=g.length>1,k=await Qc();let P="";C&&(P=`${k} \u{1F916} Generated by aicommit2 (https://github.com/tak-bro/aicommit2)
|
|
278
|
+
`,P+=`${k} ----------------------------------------
|
|
279
|
+
`,P+=`${k} How to use:
|
|
280
|
+
`,E?(P+=`${k} 1. Remove the "${k}" from your chosen message
|
|
281
|
+
`,P+=`${k} 2. Edit the message if needed
|
|
282
|
+
`,P+=`${k} 3. Save and close the editor
|
|
283
|
+
`):(P+=`${k} 1. The message below will be used
|
|
284
|
+
`,P+=`${k} 2. Edit the message if needed
|
|
285
|
+
`,P+=`${k} 3. Save and close the editor
|
|
286
|
+
`),P+=`${k} ----------------------------------------
|
|
287
|
+
`),E?(C&&(P+=`
|
|
288
|
+
${k} \u{1F4DD} Choose one of these messages:
|
|
289
|
+
`),P+=`
|
|
290
|
+
${g.map($=>`${k} ${$}`).join(`
|
|
291
|
+
`)}`):(C&&(P+=`
|
|
292
|
+
${k} \u{1F4DD} Generated commit message:
|
|
293
|
+
`),P+=`
|
|
293
294
|
${g[0]}
|
|
294
|
-
`);const
|
|
295
|
-
`+
|
|
295
|
+
`);const A=await L.readFile(kt,"utf8"),M=P+`
|
|
296
|
+
`+A;await L.writeFile(kt,M),a.printSavedCommitMessage()})().catch(l=>{new ce().printError(l.message),de(l),process.exit(1)});class $n{constructor(e="SubscriptionManager"){this.destroyed$=new Dt,this.subscriptions=new Rt,this.isDestroyed=!1,this.name=e}add(e,r){if(this.isDestroyed){console.warn(`${this.name}: Cannot add subscription - manager is destroyed`);const n=new Rt;return n.unsubscribe(),n}const o=e.pipe(qr(this.destroyed$),Xr(()=>{process.env.NODE_ENV==="development"&&console.log(`${this.name}: Observable finalized`)})).subscribe({next:r?.next,error:n=>{console.error(`${this.name}: Observable error:`,n),r?.error?.(n)},complete:r?.complete});return this.subscriptions.add(o),o}pipe(e){return this.isDestroyed?(console.warn(`${this.name}: Cannot pipe - manager is destroyed`),e):e.pipe(qr(this.destroyed$),Xr(()=>{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 Pl=new $n("Global"),Ve=()=>{Pl.destroy()};process.on("exit",Ve),process.on("SIGINT",Ve),process.on("SIGTERM",Ve),process.on("uncaughtException",t=>{console.error("Uncaught exception:",t),Ve(),process.exit(1)}),process.on("unhandledRejection",(t,e)=>{console.error("Unhandled rejection at:",e,"reason:",t),Ve(),process.exit(1)});class Al{constructor(){this.destroyed$=new Dt,this.consoleManager=new ce,this.subscriptionManager=new $n,this.currentCodeReviewSubscription=null,this.currentCodeReviewPromptManager=null,this.watcher=null,this.lastCommitHash=null,this.isProcessingCommit=!1,this.REPO_PATH=process.cwd(),this.GIT_PATH=I.join(this.REPO_PATH,".git"),this.HEAD_PATH=I.join(this.GIT_PATH,"HEAD"),this.REFS_PATH=I.join(this.GIT_PATH,"refs","heads"),this.COMMIT_MSG_PATH=I.join(this.GIT_PATH,"COMMIT_EDITMSG"),this.setupProcessHandlers()}setupProcessHandlers(){const e=()=>{this.destroy(),process.exit(0)};process.on("SIGINT",e),process.on("SIGTERM",e),process.on("SIGQUIT",e)}async watch(e,r,o,n,s,i){this.consoleManager.printTitle(),await Ar();const l=await Et();if(l!=="git")throw new w(`Watch mode is only supported for Git repositories. Current VCS: ${l}`);const a=await this.initializeConfig(e,r,n,s,i);await this.initializeCurrentCommit();try{await this.watchGitEvents(a)}catch(d){return await this.handleWatchGitError(d),this.watch(e,r,o,n,s,i)}}async initializeConfig(e,r,o,n,s){const i={locale:e?.toString(),generate:r?.toString(),systemPrompt:o?.toString()};n&&(i.logLevel="verbose");const l=await he(i,s);return await rn(l),this.getAvailableAIs(l).length===0&&(this.consoleManager.printError(`Please set at least one API key and watchMode via the config command:
|
|
296
297
|
aicommit2 config set [MODEL].key="YOUR_API_KEY"
|
|
297
|
-
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}`),de(e),await new Promise(r=>setTimeout(r,3e3)),this.consoleManager.printWarning("Restarting the commit monitoring process...")}async initializeCurrentCommit(){try{const e=await this.executeGitCommand("git rev-parse HEAD");this.lastCommitHash=e.trim(),this.consoleManager.printInfo(`Starting watch from commit: ${this.lastCommitHash.substring(0,8)}`)}catch{this.consoleManager.printWarning("No commits found in repository"),this.lastCommitHash=null}}async executeGitCommand(e){const r=Gn(Fn),{stdout:o}=await r(e,{cwd:this.REPO_PATH});return o}getAvailableAIs(e){return Object.entries(e).filter(([r,o])=>ke.includes(r)||o.compatible===!0).map(([r,o])=>[r,o]).filter(([r,o])=>!o.disabled).filter(([r,o])=>this.isAIAvailable(r,o,e)).map(([r])=>r)}isAIAvailable(e,r,o){const n=o.watchMode||r.watchMode;return e==="OLLAMA"?!!r&&!!r.model&&r.model.length>0&&n:e==="HUGGINGFACE"?!!r&&!!r.cookie&&n:r.compatible?!!r.url&&!!r.key&&n:!!r.key&&r.key.length>0&&n}clearTerminal(){process.stdout.write("\x1Bc")}async handleCommitEvent(e,r){try{const o=await Xc(r);if(!o){this.consoleManager.printWarning("No changes found in this commit");return}this.consoleManager.stopLoader(),this.consoleManager.printStagedFiles(o);const n=this.getAvailableAIs(e);if(n.length===0){this.consoleManager.printError(`Please set at least one API key and watchMode via the config command:
|
|
298
299
|
aicommit2 config set [MODEL].key="YOUR_API_KEY"
|
|
299
|
-
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=new
|
|
300
|
+
aicommit2 config set [MODEL].watchMode="true"`),process.exit();return}await this.performCodeReview(e,o,n)}catch(o){this.consoleManager.printError(`Error processing commit ${r}: ${o.message}`)}}async performCodeReview(e,r,o){this.cleanupPreviousCodeReview();const n=await Pt(),s=new bt(e,r,n);this.currentCodeReviewPromptManager=new xr(yn);try{const i=this.initializeCodeReviewInquirer();this.currentCodeReviewPromptManager.startLoader(),this.currentCodeReviewSubscription=this.subscribeToCodeReviewRequests(s,o),await i}finally{this.cleanupCodeReview()}}cleanupPreviousCodeReview(){this.cleanupCurrentReviewResources(),this.destroyed$.closed||(this.destroyed$.next(),this.destroyed$.complete()),this.destroyed$=new Dt}initializeCodeReviewInquirer(){return this.currentCodeReviewPromptManager.initPrompt({...Sr,name:"codeReviewPrompt",message:"Please check code reviews: ",emptyMessage:`\u26A0 ${wn}`,isDescriptionDim:!1,stopMessage:"Code review completed",descPageSize:20})}subscribeToCodeReviewRequests(e,r){return this.subscriptionManager.add(e.createCodeReviewRequests$(r),{next:o=>{this.currentCodeReviewPromptManager?.refreshChoices(o)},error:o=>{console.error("Code review request error:",o),this.currentCodeReviewPromptManager?.checkErrorOnChoices(!1)},complete:()=>{this.currentCodeReviewPromptManager?.checkErrorOnChoices(!1)}})}cleanupCurrentReviewResources(){this.currentCodeReviewSubscription&&(this.currentCodeReviewSubscription.unsubscribe(),this.currentCodeReviewSubscription=null),this.currentCodeReviewPromptManager&&(this.currentCodeReviewPromptManager.destroy(),this.currentCodeReviewPromptManager=null)}cleanupCodeReview(){this.cleanupCurrentReviewResources(),this.clearTerminal(),this.consoleManager.showLoader("Watching for new Git commits...")}async isGitReset(e){if(!this.lastCommitHash)return!1;try{const r=await this.executeGitCommand(`git merge-base --is-ancestor ${e} ${this.lastCommitHash}`);return!0}catch{return!1}}cancelCurrentReview(){this.currentCodeReviewPromptManager&&this.currentCodeReviewPromptManager.cancel(),this.cleanupCurrentReviewResources(),this.destroyed$.next()}async watchGitEvents(e){this.consoleManager.showLoader("Watching for new Git commits...");const o=[this.HEAD_PATH,this.REFS_PATH,this.COMMIT_MSG_PATH,I.join(this.GIT_PATH,"logs","HEAD")].filter(n=>{try{return V.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(`
|
|
300
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(`
|
|
301
|
-
\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 $l=new
|
|
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 $l=new Al,kl=async(t,e,r,o,n,s)=>$l.watch(t,e,r,o,n,s),St=process.argv.slice(2),{version:kn,description:Sl}=As;Mn({name:"aicommit2",version:kn,flags:{locale:{type:String,description:"Locale to use for the generated commit messages (default: en)",alias:"l"},generate:{type:Number,description:"Number of messages to generate (Warning: generating multiple costs more) (default: 1)",alias:"g"},exclude:{type:[String],description:"Files to exclude from AI analysis",alias:"x"},all:{type:Boolean,description:"Automatically stage changes in tracked files for the commit",alias:"a",default:!1},type:{type:String,description:"Type of commit message to generate (default: conventional)",alias:"t"},confirm:{type:Boolean,description:"Skip confirmation when committing after message generation (default: false)",alias:"y",default:!1},clipboard:{type:Boolean,description:"Copy the selected message to the clipboard",alias:"c",default:!1},prompt:{type:String,description:"Custom prompt to let users fine-tune provided prompt",alias:"p"},"watch-commit":{type:Boolean,default:!1},"hook-mode":{type:Boolean,description:"Run in git hook mode, allowing chaining with other hooks",default:!1},"pre-commit":{type:Boolean,description:"Run in pre-commit Framework, allowing chaining with other hooks",default:!1},"include-body":{type:Boolean,description:"Force include commit body in all generated messages",alias:"i",default:!1},"auto-select":{type:Boolean,description:"Automatically select the message when only one is generated",alias:"s",default:!1},edit:{type:Boolean,description:"Open the AI-generated commit message in your default editor",alias:"e",default:!1},"disable-lowercase":{type:Boolean,description:"Disable automatic lowercase conversion of commit messages",default:!1},verbose:{type:Boolean,description:"Enable verbose logging for this run",alias:"v",default:!1},git:{type:Boolean,description:"Force use Git (overrides auto-detection)",default:!1},yadm:{type:Boolean,description:"Force use YADM (overrides auto-detection)",default:!1},jj:{type:Boolean,description:"Force use Jujutsu (overrides auto-detection)",default:!1},"dry-run":{type:Boolean,description:"Generate commit message without committing (output only)",alias:"d",default:!1}},commands:[il,al,ml,vl],help:{description:Sl},ignoreArgv:t=>t==="unknown-flag"||t==="argument"},async t=>{const e={};t.flags.verbose&&(e.logLevel="verbose");const r=await he(e,St);if(await Qa(r),xe.info(`aicommit2 version: ${kn}`),t.flags["pre-commit"]){Cl(t.flags.verbose);return}if(t.flags["hook-mode"]||dl){El(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"]){kl(t.flags.locale,t.flags.generate,t.flags.exclude,t.flags.prompt,t.flags.verbose,St);return}rl(t.flags.locale,t.flags.generate,t.flags.exclude,t.flags.all,t.flags.type,t.flags.confirm,t.flags.clipboard,t.flags.prompt,t.flags["include-body"],t.flags["auto-select"],t.flags.edit,t.flags["disable-lowercase"],t.flags.verbose,t.flags["dry-run"],St)},St);
|