aicommit2 2.5.11 → 2.5.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +36 -0
- package/dist/ai.service-f59388bb.mjs +17 -0
- package/dist/anthropic.service-fb44d54e.mjs +1 -0
- package/dist/bedrock.service-40cbd1e5.mjs +1 -0
- package/dist/cli-d193cf90.mjs +273 -0
- package/dist/cli.mjs +1 -1
- package/dist/codestral.service-f6ae65a5.mjs +1 -0
- package/dist/cohere.service-af885cf7.mjs +1 -0
- package/dist/copilot-sdk.service-f1cc1873.mjs +5 -0
- package/dist/deep-seek.service-de8b4395.mjs +1 -0
- package/dist/gemini.service-c9b02d26.mjs +1 -0
- package/dist/{github-models.service-7c104b0a.mjs → github-models.service-becd2e94.mjs} +3 -3
- package/dist/groq.service-180e7478.mjs +1 -0
- package/dist/hugging-face.service-2c8f4576.mjs +2 -0
- package/dist/mistral.service-7a553113.mjs +1 -0
- package/dist/ollama.service-31b2908b.mjs +1 -0
- package/dist/{openai-compatible.service-987d206d.mjs → openai-compatible.service-2bea7313.mjs} +1 -1
- package/dist/{openai-22ac0386.mjs → openai-dc366083.mjs} +1 -1
- package/dist/{openai.service-fb8b0aec.mjs → openai.service-ca071f6c.mjs} +1 -1
- package/dist/openrouter.service-2e239655.mjs +1 -0
- package/dist/perplexity.service-fe8bfcd5.mjs +1 -0
- package/package.json +4 -2
- package/dist/ai.service-1ba3c081.mjs +0 -17
- package/dist/anthropic.service-7842f514.mjs +0 -1
- package/dist/bedrock.service-65bb3c73.mjs +0 -1
- package/dist/cli-e0859d73.mjs +0 -273
- package/dist/codestral.service-cd9177f4.mjs +0 -1
- package/dist/cohere.service-03179c4c.mjs +0 -1
- package/dist/copilot-sdk.service-5c240291.mjs +0 -5
- package/dist/deep-seek.service-0c494b66.mjs +0 -1
- package/dist/gemini.service-ef22fdae.mjs +0 -1
- package/dist/groq.service-ecd1e518.mjs +0 -1
- package/dist/hugging-face.service-e6a0100a.mjs +0 -2
- package/dist/mistral.service-902039e1.mjs +0 -1
- package/dist/ollama.service-d60eeaa2.mjs +0 -1
- package/dist/openrouter.service-16a86909.mjs +0 -1
- package/dist/perplexity.service-6a36f05d.mjs +0 -1
|
@@ -0,0 +1,273 @@
|
|
|
1
|
+
import{command as j,cli as ss}from"cleye";import{createRequire as rs}from"module";import is from"crypto";import _ from"fs";import Ie from"os";import P from"path";import{Buffer as cn}from"node:buffer";import ee from"node:path";import lt,{ChildProcess as ln,exec as as}from"node:child_process";import G from"node:process";import cs,{execSync as ge,exec as ls}from"child_process";import{fileURLToPath as un}from"node:url";import us,{constants as dn}from"node:os";import ds from"assert";import ms from"events";import{createWriteStream as fs,createReadStream as ps,readFileSync as hs}from"node:fs";import gs from"buffer";import ut from"stream";import ys,{promisify as ws}from"util";import{debuglog as Cs,promisify as bs}from"node:util";import M from"inquirer";import{from as ke,switchMap as mn,of as Es,tap as vs,mergeMap as fn,catchError as Ps,BehaviorSubject as pn,ReplaySubject as As,Subscription as dt,lastValueFrom as mt,toArray as ft,filter as hn,map as gn,Subject as xs}from"rxjs";import I from"fs/promises";import h from"chalk";import Le from"readline";import yn from"figlet";import Ss from"gradient-string";import wn from"ora";import $s from"inquirer-reactive-list-prompt";import B from"winston";import"winston-daily-rotate-file";import Rs from"axios";import{fileURLToPath as Is,pathToFileURL as ks}from"url";import{readdir as Cn,stat as Ls,rm as Ms}from"node:fs/promises";import Ts from"chokidar";import{takeUntil as bn,finalize as En}from"rxjs/operators";var Os="aicommit2",vn="2.5.13",Ds="A Reactive CLI that generates commit messages for Git and Jujutsu with various AI",Ns=["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"],_s="MIT",js="tak-bro/aicommit2",Fs="Hyungtak Jin(@tak-bro)",Gs="module",Bs=["dist"],Hs={aicommit2:"./dist/cli.mjs",aic2:"./dist/cli.mjs"},Us={prepare:"simple-git-hooks",build:"pkgroll --minify",lint:"eslint --cache .","type-check":"tsc",test:"tsx tests",prepack:"pnpm build && clean-pkg-json",prettier:"prettier"},Ks={"@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"},Ws={"@github/copilot-sdk":"0.2.0"},qs={"@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"},zs={extends:["@pvtnbr","prettier"],rules:{"unicorn/no-process-exit":"off"},overrides:[{files:"./src/commands/prepare-commit-msg-hook.ts",rules:{"unicorn/prevent-abbreviations":"off"}}]},Ys={branches:["main"],plugins:[["@semantic-release/commit-analyzer",{preset:"conventionalcommits",releaseRules:[{type:"docs",release:!1},{type:"style",release:!1},{type:"test",release:!1},{type:"ci",release:!1},{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"]},Vs={name:Os,version:vn,description:Ds,keywords:Ns,license:_s,repository:js,author:Fs,type:Gs,files:Bs,bin:Hs,scripts:Us,"simple-git-hooks":{"pre-commit":"pnpm lint-staged"},"lint-staged":{"*.ts":["prettier --config ./.prettierrc --write","eslint --fix"]},dependencies:Ks,optionalDependencies:Ws,devDependencies:qs,eslintConfig:zs,release:Ys},pt=rs(import.meta.url),J=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function oe(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var se={exports:{}},ht,Pn;function Js(){if(Pn)return ht;Pn=1,ht=o,o.sync=s;var e=_;function t(r,a){var c=a.pathExt!==void 0?a.pathExt:process.env.PATHEXT;if(!c||(c=c.split(";"),c.indexOf("")!==-1))return!0;for(var l=0;l<c.length;l++){var u=c[l].toLowerCase();if(u&&r.substr(-u.length).toLowerCase()===u)return!0}return!1}function n(r,a,c){return!r.isSymbolicLink()&&!r.isFile()?!1:t(a,c)}function o(r,a,c){e.stat(r,function(l,u){c(l,l?!1:n(u,r,a))})}function s(r,a){return n(e.statSync(r),r,a)}return ht}var gt,An;function Xs(){if(An)return gt;An=1,gt=t,t.sync=n;var e=_;function t(r,a,c){e.stat(r,function(l,u){c(l,l?!1:o(u,a))})}function n(r,a){return o(e.statSync(r),a)}function o(r,a){return r.isFile()&&s(r,a)}function s(r,a){var c=r.mode,l=r.uid,u=r.gid,d=a.uid!==void 0?a.uid:process.getuid&&process.getuid(),m=a.gid!==void 0?a.gid:process.getgid&&process.getgid(),g=parseInt("100",8),y=parseInt("010",8),f=parseInt("001",8),A=g|y,R=c&f||c&y&&u===m||c&g&&l===d||c&A&&d===0;return R}return gt}var Me;process.platform==="win32"||J.TESTING_WINDOWS?Me=Js():Me=Xs();var Qs=yt;yt.sync=Zs;function yt(e,t,n){if(typeof t=="function"&&(n=t,t={}),!n){if(typeof Promise!="function")throw new TypeError("callback not provided");return new Promise(function(o,s){yt(e,t||{},function(r,a){r?s(r):o(a)})})}Me(e,t||{},function(o,s){o&&(o.code==="EACCES"||t&&t.ignoreErrors)&&(o=null,s=!1),n(o,s)})}function Zs(e,t){try{return Me.sync(e,t||{})}catch(n){if(t&&t.ignoreErrors||n.code==="EACCES")return!1;throw n}}const re=process.platform==="win32"||process.env.OSTYPE==="cygwin"||process.env.OSTYPE==="msys",xn=P,er=re?";":":",Sn=Qs,$n=e=>Object.assign(new Error(`not found: ${e}`),{code:"ENOENT"}),Rn=(e,t)=>{const n=t.colon||er,o=e.match(/\//)||re&&e.match(/\\/)?[""]:[...re?[process.cwd()]:[],...(t.path||process.env.PATH||"").split(n)],s=re?t.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",r=re?s.split(n):[""];return re&&e.indexOf(".")!==-1&&r[0]!==""&&r.unshift(""),{pathEnv:o,pathExt:r,pathExtExe:s}},In=(e,t,n)=>{typeof t=="function"&&(n=t,t={}),t||(t={});const{pathEnv:o,pathExt:s,pathExtExe:r}=Rn(e,t),a=[],c=u=>new Promise((d,m)=>{if(u===o.length)return t.all&&a.length?d(a):m($n(e));const g=o[u],y=/^".*"$/.test(g)?g.slice(1,-1):g,f=xn.join(y,e),A=!y&&/^\.[\\\/]/.test(e)?e.slice(0,2)+f:f;d(l(A,u,0))}),l=(u,d,m)=>new Promise((g,y)=>{if(m===s.length)return g(c(d+1));const f=s[m];Sn(u+f,{pathExt:r},(A,R)=>{if(!A&&R)if(t.all)a.push(u+f);else return g(u+f);return g(l(u,d,m+1))})});return n?c(0).then(u=>n(null,u),n):c(0)},tr=(e,t)=>{t=t||{};const{pathEnv:n,pathExt:o,pathExtExe:s}=Rn(e,t),r=[];for(let a=0;a<n.length;a++){const c=n[a],l=/^".*"$/.test(c)?c.slice(1,-1):c,u=xn.join(l,e),d=!l&&/^\.[\\\/]/.test(e)?e.slice(0,2)+u:u;for(let m=0;m<o.length;m++){const g=d+o[m];try{if(Sn.sync(g,{pathExt:s}))if(t.all)r.push(g);else return g}catch{}}}if(t.all&&r.length)return r;if(t.nothrow)return null;throw $n(e)};var nr=In;In.sync=tr;var wt={exports:{}};const kn=(e={})=>{const t=e.env||process.env;return(e.platform||process.platform)!=="win32"?"PATH":Object.keys(t).reverse().find(o=>o.toUpperCase()==="PATH")||"Path"};wt.exports=kn,wt.exports.default=kn;var or=wt.exports;const Ln=P,sr=nr,rr=or;function Mn(e,t){const n=e.options.env||process.env,o=process.cwd(),s=e.options.cwd!=null,r=s&&process.chdir!==void 0&&!process.chdir.disabled;if(r)try{process.chdir(e.options.cwd)}catch{}let a;try{a=sr.sync(e.command,{path:n[rr({env:n})],pathExt:t?Ln.delimiter:void 0})}catch{}finally{r&&process.chdir(o)}return a&&(a=Ln.resolve(s?e.options.cwd:"",a)),a}function ir(e){return Mn(e)||Mn(e,!0)}var ar=ir,Ct={};const bt=/([()\][%!^"`<>&|;, *?])/g;function cr(e){return e=e.replace(bt,"^$1"),e}function lr(e,t){return e=`${e}`,e=e.replace(/(?=(\\+?)?)\1"/g,'$1$1\\"'),e=e.replace(/(?=(\\+?)?)\1$/,"$1$1"),e=`"${e}"`,e=e.replace(bt,"^$1"),t&&(e=e.replace(bt,"^$1")),e}Ct.command=cr,Ct.argument=lr;var ur=/^#!(.*)/;const dr=ur;var mr=(e="")=>{const t=e.match(dr);if(!t)return null;const[n,o]=t[0].replace(/#! ?/,"").split(" "),s=n.split("/").pop();return s==="env"?o:o?`${s} ${o}`:s};const Et=_,fr=mr;function pr(e){const n=Buffer.alloc(150);let o;try{o=Et.openSync(e,"r"),Et.readSync(o,n,0,150,0),Et.closeSync(o)}catch{}return fr(n.toString())}var hr=pr;const gr=P,Tn=ar,On=Ct,yr=hr,wr=process.platform==="win32",Cr=/\.(?:com|exe)$/i,br=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function Er(e){e.file=Tn(e);const t=e.file&&yr(e.file);return t?(e.args.unshift(e.file),e.command=t,Tn(e)):e.file}function vr(e){if(!wr)return e;const t=Er(e),n=!Cr.test(t);if(e.options.forceShell||n){const o=br.test(t);e.command=gr.normalize(e.command),e.command=On.command(e.command),e.args=e.args.map(r=>On.argument(r,o));const s=[e.command].concat(e.args).join(" ");e.args=["/d","/s","/c",`"${s}"`],e.command=process.env.comspec||"cmd.exe",e.options.windowsVerbatimArguments=!0}return e}function Pr(e,t,n){t&&!Array.isArray(t)&&(n=t,t=null),t=t?t.slice(0):[],n=Object.assign({},n);const o={command:e,args:t,options:n,file:void 0,original:{command:e,args:t}};return n.shell?o:vr(o)}var Ar=Pr;const vt=process.platform==="win32";function Pt(e,t){return Object.assign(new Error(`${t} ${e.command} ENOENT`),{code:"ENOENT",errno:"ENOENT",syscall:`${t} ${e.command}`,path:e.command,spawnargs:e.args})}function xr(e,t){if(!vt)return;const n=e.emit;e.emit=function(o,s){if(o==="exit"){const r=Dn(s,t);if(r)return n.call(e,"error",r)}return n.apply(e,arguments)}}function Dn(e,t){return vt&&e===1&&!t.file?Pt(t.original,"spawn"):null}function Sr(e,t){return vt&&e===1&&!t.file?Pt(t.original,"spawnSync"):null}var $r={hookChildProcess:xr,verifyENOENT:Dn,verifyENOENTSync:Sr,notFoundError:Pt};const Nn=cs,At=Ar,xt=$r;function _n(e,t,n){const o=At(e,t,n),s=Nn.spawn(o.command,o.args,o.options);return xt.hookChildProcess(s,o),s}function Rr(e,t,n){const o=At(e,t,n),s=Nn.spawnSync(o.command,o.args,o.options);return s.error=s.error||xt.verifyENOENTSync(s.status,o),s}se.exports=_n,se.exports.spawn=_n,se.exports.sync=Rr,se.exports._parse=At,se.exports._enoent=xt;var Ir=se.exports,kr=oe(Ir);function Lr(e){const t=typeof e=="string"?`
|
|
2
|
+
`:`
|
|
3
|
+
`.charCodeAt(),n=typeof e=="string"?"\r":"\r".charCodeAt();return e[e.length-1]===t&&(e=e.slice(0,-1)),e[e.length-1]===n&&(e=e.slice(0,-1)),e}function jn(e={}){const{env:t=process.env,platform:n=process.platform}=e;return n!=="win32"?"PATH":Object.keys(t).reverse().find(o=>o.toUpperCase()==="PATH")||"Path"}const Mr=({cwd:e=G.cwd(),path:t=G.env[jn()],preferLocal:n=!0,execPath:o=G.execPath,addExecPath:s=!0}={})=>{const r=e instanceof URL?un(e):e,a=ee.resolve(r),c=[];return n&&Tr(c,a),s&&Or(c,o,a),[...c,t].join(ee.delimiter)},Tr=(e,t)=>{let n;for(;n!==t;)e.push(ee.join(t,"node_modules/.bin")),n=t,t=ee.resolve(t,"..")},Or=(e,t,n)=>{const o=t instanceof URL?un(t):t;e.push(ee.resolve(n,o,".."))},Dr=({env:e=G.env,...t}={})=>{e={...e};const n=jn({env:e});return t.path=e[n],e[n]=Mr(t),e},Nr=(e,t,n,o)=>{if(n==="length"||n==="prototype"||n==="arguments"||n==="caller")return;const s=Object.getOwnPropertyDescriptor(e,n),r=Object.getOwnPropertyDescriptor(t,n);!_r(s,r)&&o||Object.defineProperty(e,n,r)},_r=function(e,t){return e===void 0||e.configurable||e.writable===t.writable&&e.enumerable===t.enumerable&&e.configurable===t.configurable&&(e.writable||e.value===t.value)},jr=(e,t)=>{const n=Object.getPrototypeOf(t);n!==Object.getPrototypeOf(e)&&Object.setPrototypeOf(e,n)},Fr=(e,t)=>`/* Wrapped ${e}*/
|
|
4
|
+
${t}`,Gr=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),Br=Object.getOwnPropertyDescriptor(Function.prototype.toString,"name"),Hr=(e,t,n)=>{const o=n===""?"":`with ${n.trim()}() `,s=Fr.bind(null,o,t.toString());Object.defineProperty(s,"name",Br),Object.defineProperty(e,"toString",{...Gr,value:s})};function Ur(e,t,{ignoreNonConfigurable:n=!1}={}){const{name:o}=e;for(const s of Reflect.ownKeys(t))Nr(e,t,s,n);return jr(e,t),Hr(e,t,o),e}const Te=new WeakMap,Fn=(e,t={})=>{if(typeof e!="function")throw new TypeError("Expected a function");let n,o=0;const s=e.displayName||e.name||"<anonymous>",r=function(...a){if(Te.set(r,++o),o===1)n=e.apply(this,a),e=null;else if(t.throw===!0)throw new Error(`Function \`${s}\` can only be called once`);return n};return Ur(r,e),Te.set(r,o),r};Fn.callCount=e=>{if(!Te.has(e))throw new Error(`The given function \`${e.name}\` is not wrapped by the \`onetime\` package`);return Te.get(e)};const Kr=()=>{const e=Bn-Gn+1;return Array.from({length:e},Wr)},Wr=(e,t)=>({name:`SIGRT${t+1}`,number:Gn+t,action:"terminate",description:"Application-specific signal (realtime)",standard:"posix"}),Gn=34,Bn=64,qr=[{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"}],Hn=()=>{const e=Kr();return[...qr,...e].map(zr)},zr=({name:e,number:t,description:n,action:o,forced:s=!1,standard:r})=>{const{signals:{[e]:a}}=dn,c=a!==void 0;return{name:e,number:c?a:t,description:n,supported:c,action:o,forced:s,standard:r}},Yr=()=>{const e=Hn();return Object.fromEntries(e.map(Vr))},Vr=({name:e,number:t,description:n,supported:o,action:s,forced:r,standard:a})=>[e,{name:e,number:t,description:n,supported:o,action:s,forced:r,standard:a}],Jr=Yr(),Xr=()=>{const e=Hn(),t=Bn+1,n=Array.from({length:t},(o,s)=>Qr(s,e));return Object.assign({},...n)},Qr=(e,t)=>{const n=Zr(e,t);if(n===void 0)return{};const{name:o,description:s,supported:r,action:a,forced:c,standard:l}=n;return{[e]:{name:o,number:e,description:s,supported:r,action:a,forced:c,standard:l}}},Zr=(e,t)=>{const n=t.find(({name:o})=>dn.signals[o]===e);return n!==void 0?n:t.find(o=>o.number===e)};Xr();const ei=({timedOut:e,timeout:t,errorCode:n,signal:o,signalDescription:s,exitCode:r,isCanceled:a})=>e?`timed out after ${t} milliseconds`:a?"was canceled":n!==void 0?`failed with ${n}`:o!==void 0?`was killed with ${o} (${s})`:r!==void 0?`failed with exit code ${r}`:"failed",Oe=({stdout:e,stderr:t,all:n,error:o,signal:s,exitCode:r,command:a,escapedCommand:c,timedOut:l,isCanceled:u,killed:d,parsed:{options:{timeout:m,cwd:g=G.cwd()}}})=>{r=r===null?void 0:r,s=s===null?void 0:s;const y=s===void 0?void 0:Jr[s].description,f=o&&o.code,R=`Command ${ei({timedOut:l,timeout:m,errorCode:f,signal:s,signalDescription:y,exitCode:r,isCanceled:u})}: ${a}`,x=Object.prototype.toString.call(o)==="[object Error]",S=x?`${R}
|
|
5
|
+
${o.message}`:R,b=[S,t,e].filter(Boolean).join(`
|
|
6
|
+
`);return x?(o.originalMessage=o.message,o.message=b):o=new Error(b),o.shortMessage=S,o.command=a,o.escapedCommand=c,o.exitCode=r,o.signal=s,o.signalDescription=y,o.stdout=e,o.stderr=t,o.cwd=g,n!==void 0&&(o.all=n),"bufferedData"in o&&delete o.bufferedData,o.failed=!0,o.timedOut=!!l,o.isCanceled=u,o.killed=d&&!l,o},De=["stdin","stdout","stderr"],ti=e=>De.some(t=>e[t]!==void 0),Un=e=>{if(!e)return;const{stdio:t}=e;if(t===void 0)return De.map(o=>e[o]);if(ti(e))throw new Error(`It's not possible to provide \`stdio\` in combination with one of ${De.map(o=>`\`${o}\``).join(", ")}`);if(typeof t=="string")return t;if(!Array.isArray(t))throw new TypeError(`Expected \`stdio\` to be of type \`string\` or \`Array\`, got \`${typeof t}\``);const n=Math.max(t.length,De.length);return Array.from({length:n},(o,s)=>t[s])},ni=e=>{const t=Un(e);return t==="ipc"?"ipc":t===void 0||typeof t=="string"?[t,t,t,"ipc"]:t.includes("ipc")?t:[...t,"ipc"]};var ie={exports:{}},Ne={exports:{}};Ne.exports;var Kn;function oi(){return Kn||(Kn=1,function(e){e.exports=["SIGABRT","SIGALRM","SIGHUP","SIGINT","SIGTERM"],process.platform!=="win32"&&e.exports.push("SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT"),process.platform==="linux"&&e.exports.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT","SIGUNUSED")}(Ne)),Ne.exports}var L=J.process;const te=function(e){return e&&typeof e=="object"&&typeof e.removeListener=="function"&&typeof e.emit=="function"&&typeof e.reallyExit=="function"&&typeof e.listeners=="function"&&typeof e.kill=="function"&&typeof e.pid=="number"&&typeof e.on=="function"};if(!te(L))ie.exports=function(){return function(){}};else{var si=ds,ye=oi(),ri=/^win/i.test(L.platform),_e=ms;typeof _e!="function"&&(_e=_e.EventEmitter);var T;L.__signal_exit_emitter__?T=L.__signal_exit_emitter__:(T=L.__signal_exit_emitter__=new _e,T.count=0,T.emitted={}),T.infinite||(T.setMaxListeners(1/0),T.infinite=!0),ie.exports=function(e,t){if(!te(J.process))return function(){};si.equal(typeof e,"function","a callback must be provided for exit handler"),we===!1&&Wn();var n="exit";t&&t.alwaysLast&&(n="afterexit");var o=function(){T.removeListener(n,e),T.listeners("exit").length===0&&T.listeners("afterexit").length===0&&St()};return T.on(n,e),o};var St=function(){!we||!te(J.process)||(we=!1,ye.forEach(function(t){try{L.removeListener(t,$t[t])}catch{}}),L.emit=Rt,L.reallyExit=qn,T.count-=1)};ie.exports.unload=St;var ae=function(t,n,o){T.emitted[t]||(T.emitted[t]=!0,T.emit(t,n,o))},$t={};ye.forEach(function(e){$t[e]=function(){if(te(J.process)){var n=L.listeners(e);n.length===T.count&&(St(),ae("exit",null,e),ae("afterexit",null,e),ri&&e==="SIGHUP"&&(e="SIGINT"),L.kill(L.pid,e))}}}),ie.exports.signals=function(){return ye};var we=!1,Wn=function(){we||!te(J.process)||(we=!0,T.count+=1,ye=ye.filter(function(t){try{return L.on(t,$t[t]),!0}catch{return!1}}),L.emit=ai,L.reallyExit=ii)};ie.exports.load=Wn;var qn=L.reallyExit,ii=function(t){te(J.process)&&(L.exitCode=t||0,ae("exit",L.exitCode,null),ae("afterexit",L.exitCode,null),qn.call(L,L.exitCode))},Rt=L.emit,ai=function(t,n){if(t==="exit"&&te(J.process)){n!==void 0&&(L.exitCode=n);var o=Rt.apply(this,arguments);return ae("exit",L.exitCode,null),ae("afterexit",L.exitCode,null),o}else return Rt.apply(this,arguments)}}var ci=ie.exports,li=oe(ci);const ui=1e3*5,di=(e,t="SIGTERM",n={})=>{const o=e(t);return mi(e,t,n,o),o},mi=(e,t,n,o)=>{if(!fi(t,n,o))return;const s=hi(n),r=setTimeout(()=>{e("SIGKILL")},s);r.unref&&r.unref()},fi=(e,{forceKillAfterTimeout:t},n)=>pi(e)&&t!==!1&&n,pi=e=>e===us.constants.signals.SIGTERM||typeof e=="string"&&e.toUpperCase()==="SIGTERM",hi=({forceKillAfterTimeout:e=!0})=>{if(e===!0)return ui;if(!Number.isFinite(e)||e<0)throw new TypeError(`Expected the \`forceKillAfterTimeout\` option to be a non-negative integer, got \`${e}\` (${typeof e})`);return e},gi=(e,t)=>{e.kill()&&(t.isCanceled=!0)},yi=(e,t,n)=>{e.kill(t),n(Object.assign(new Error("Timed out"),{timedOut:!0,signal:t}))},wi=(e,{timeout:t,killSignal:n="SIGTERM"},o)=>{if(t===0||t===void 0)return o;let s;const r=new Promise((c,l)=>{s=setTimeout(()=>{yi(e,n,l)},t)}),a=o.finally(()=>{clearTimeout(s)});return Promise.race([r,a])},Ci=({timeout:e})=>{if(e!==void 0&&(!Number.isFinite(e)||e<0))throw new TypeError(`Expected the \`timeout\` option to be a non-negative integer, got \`${e}\` (${typeof e})`)},bi=async(e,{cleanup:t,detached:n},o)=>{if(!t||n)return o;const s=li(()=>{e.kill()});return o.finally(()=>{s()})};function It(e){return e!==null&&typeof e=="object"&&typeof e.pipe=="function"}function zn(e){return It(e)&&e.writable!==!1&&typeof e._write=="function"&&typeof e._writableState=="object"}const Ei=e=>e instanceof ln&&typeof e.then=="function",kt=(e,t,n)=>{if(typeof n=="string")return e[t].pipe(fs(n)),e;if(zn(n))return e[t].pipe(n),e;if(!Ei(n))throw new TypeError("The second argument must be a string, a stream or an Execa child process.");if(!zn(n.stdin))throw new TypeError("The target child process's stdin must be available.");return e[t].pipe(n.stdin),n},vi=e=>{e.stdout!==null&&(e.pipeStdout=kt.bind(void 0,e,"stdout")),e.stderr!==null&&(e.pipeStderr=kt.bind(void 0,e,"stderr")),e.all!==void 0&&(e.pipeAll=kt.bind(void 0,e,"all"))};var Ce={exports:{}};const{PassThrough:Pi}=ut;var Ai=e=>{e={...e};const{array:t}=e;let{encoding:n}=e;const o=n==="buffer";let s=!1;t?s=!(n||o):n=n||"utf8",o&&(n=null);const r=new Pi({objectMode:s});n&&r.setEncoding(n);let a=0;const c=[];return r.on("data",l=>{c.push(l),s?a=c.length:a+=l.length}),r.getBufferedValue=()=>t?c:o?Buffer.concat(c,a):c.join(""),r.getBufferedLength=()=>a,r};const{constants:xi}=gs,Si=ut,{promisify:$i}=ys,Ri=Ai,Ii=$i(Si.pipeline);class Yn extends Error{constructor(){super("maxBuffer exceeded"),this.name="MaxBufferError"}}async function Lt(e,t){if(!e)throw new Error("Expected a stream");t={maxBuffer:1/0,...t};const{maxBuffer:n}=t,o=Ri(t);return await new Promise((s,r)=>{const a=c=>{c&&o.getBufferedLength()<=xi.MAX_LENGTH&&(c.bufferedData=o.getBufferedValue()),r(c)};(async()=>{try{await Ii(e,o),s()}catch(c){a(c)}})(),o.on("data",()=>{o.getBufferedLength()>n&&a(new Yn)})}),o.getBufferedValue()}Ce.exports=Lt,Ce.exports.buffer=(e,t)=>Lt(e,{...t,encoding:"buffer"}),Ce.exports.array=(e,t)=>Lt(e,{...t,array:!0}),Ce.exports.MaxBufferError=Yn;var ki=Ce.exports,Vn=oe(ki);const{PassThrough:Li}=ut;var Mi=function(){var e=[],t=new Li({objectMode:!0});return t.setMaxListeners(0),t.add=n,t.isEmpty=o,t.on("unpipe",s),Array.prototype.slice.call(arguments).forEach(n),t;function n(r){return Array.isArray(r)?(r.forEach(n),this):(e.push(r),r.once("end",s.bind(null,r)),r.once("error",t.emit.bind(t,"error")),r.pipe(t,{end:!1}),this)}function o(){return e.length==0}function s(r){e=e.filter(function(a){return a!==r}),!e.length&&t.readable&&t.end()}},Ti=oe(Mi);const Jn=e=>{if(e!==void 0)throw new TypeError("The `input` and `inputFile` options cannot be both set.")},Oi=({input:e,inputFile:t})=>typeof t!="string"?e:(Jn(e),hs(t)),Di=e=>{const t=Oi(e);if(It(t))throw new TypeError("The `input` option cannot be a stream in sync mode");return t},Ni=({input:e,inputFile:t})=>typeof t!="string"?e:(Jn(e),ps(t)),_i=(e,t)=>{const n=Ni(t);n!==void 0&&(It(n)?n.pipe(e.stdin):e.stdin.end(n))},ji=(e,{all:t})=>{if(!t||!e.stdout&&!e.stderr)return;const n=Ti();return e.stdout&&n.add(e.stdout),e.stderr&&n.add(e.stderr),n},Mt=async(e,t)=>{if(!(!e||t===void 0)){e.destroy();try{return await t}catch(n){return n.bufferedData}}},Tt=(e,{encoding:t,buffer:n,maxBuffer:o})=>{if(!(!e||!n))return t?Vn(e,{encoding:t,maxBuffer:o}):Vn.buffer(e,{maxBuffer:o})},Fi=async({stdout:e,stderr:t,all:n},{encoding:o,buffer:s,maxBuffer:r},a)=>{const c=Tt(e,{encoding:o,buffer:s,maxBuffer:r}),l=Tt(t,{encoding:o,buffer:s,maxBuffer:r}),u=Tt(n,{encoding:o,buffer:s,maxBuffer:r*2});try{return await Promise.all([a,c,l,u])}catch(d){return Promise.all([{error:d,signal:d.signal,timedOut:d.timedOut},Mt(e,c),Mt(t,l),Mt(n,u)])}},Gi=(async()=>{})().constructor.prototype,Bi=["then","catch","finally"].map(e=>[e,Reflect.getOwnPropertyDescriptor(Gi,e)]),Xn=(e,t)=>{for(const[n,o]of Bi){const s=typeof t=="function"?(...r)=>Reflect.apply(o.value,t(),r):o.value.bind(t);Reflect.defineProperty(e,n,{...o,value:s})}},Hi=e=>new Promise((t,n)=>{e.on("exit",(o,s)=>{t({exitCode:o,signal:s})}),e.on("error",o=>{n(o)}),e.stdin&&e.stdin.on("error",o=>{n(o)})}),Qn=(e,t=[])=>Array.isArray(t)?[e,...t]:[e],Ui=/^[\w.-]+$/,Ki=/"/g,Wi=e=>typeof e!="string"||Ui.test(e)?e:`"${e.replace(Ki,'\\"')}"`,Zn=(e,t)=>Qn(e,t).join(" "),eo=(e,t)=>Qn(e,t).map(n=>Wi(n)).join(" "),to=/ +/g,no=e=>{const t=[];for(const n of e.trim().split(to)){const o=t[t.length-1];o&&o.endsWith("\\")?t[t.length-1]=`${o.slice(0,-1)} ${n}`:t.push(n)}return t},oo=e=>{const t=typeof e;if(t==="string")return e;if(t==="number")return String(e);if(t==="object"&&e!==null&&!(e instanceof ln)&&"stdout"in e){const n=typeof e.stdout;if(n==="string")return e.stdout;if(cn.isBuffer(e.stdout))return e.stdout.toString();throw new TypeError(`Unexpected "${n}" stdout in template expression`)}throw new TypeError(`Unexpected "${t}" in template expression`)},so=(e,t,n)=>n||e.length===0||t.length===0?[...e,...t]:[...e.slice(0,-1),`${e[e.length-1]}${t[0]}`,...t.slice(1)],qi=({templates:e,expressions:t,tokens:n,index:o,template:s})=>{const r=s??e.raw[o],a=r.split(to).filter(Boolean),c=so(n,a,r.startsWith(" "));if(o===t.length)return c;const l=t[o],u=Array.isArray(l)?l.map(d=>oo(d)):[oo(l)];return so(c,u,r.endsWith(" "))},ro=(e,t)=>{let n=[];for(const[o,s]of e.entries())n=qi({templates:e,expressions:t,tokens:n,index:o,template:s});return n},zi=Cs("execa").enabled,je=(e,t)=>String(e).padStart(t,"0"),Yi=()=>{const e=new Date;return`${je(e.getHours(),2)}:${je(e.getMinutes(),2)}:${je(e.getSeconds(),2)}.${je(e.getMilliseconds(),3)}`},io=(e,{verbose:t})=>{t&&G.stderr.write(`[${Yi()}] ${e}
|
|
7
|
+
`)},Vi=1e3*1e3*100,Ji=({env:e,extendEnv:t,preferLocal:n,localDir:o,execPath:s})=>{const r=t?{...G.env,...e}:e;return n?Dr({env:r,cwd:o,execPath:s}):r},ao=(e,t,n={})=>{const o=kr._parse(e,t,n);return e=o.command,t=o.args,n=o.options,n={maxBuffer:Vi,buffer:!0,stripFinalNewline:!0,extendEnv:!0,preferLocal:!1,localDir:n.cwd||G.cwd(),execPath:G.execPath,encoding:"utf8",reject:!0,cleanup:!0,all:!1,windowsHide:!0,verbose:zi,...n},n.env=Ji(n),n.stdio=Un(n),G.platform==="win32"&&ee.basename(e,".exe")==="cmd"&&t.unshift("/q"),{file:e,args:t,options:n,parsed:o}},be=(e,t,n)=>typeof t!="string"&&!cn.isBuffer(t)?n===void 0?void 0:"":e.stripFinalNewline?Lr(t):t;function E(e,t,n){const o=ao(e,t,n),s=Zn(e,t),r=eo(e,t);io(r,o.options),Ci(o.options);let a;try{a=lt.spawn(o.file,o.args,o.options)}catch(y){const f=new lt.ChildProcess,A=Promise.reject(Oe({error:y,stdout:"",stderr:"",all:"",command:s,escapedCommand:r,parsed:o,timedOut:!1,isCanceled:!1,killed:!1}));return Xn(f,A),f}const c=Hi(a),l=wi(a,o.options,c),u=bi(a,o.options,l),d={isCanceled:!1};a.kill=di.bind(null,a.kill.bind(a)),a.cancel=gi.bind(null,a,d);const g=Fn(async()=>{const[{error:y,exitCode:f,signal:A,timedOut:R},x,S,b]=await Fi(a,o.options,u),C=be(o.options,x),k=be(o.options,S),O=be(o.options,b);if(y||f!==0||A!==null){const V=Oe({error:y,exitCode:f,signal:A,stdout:C,stderr:k,all:O,command:s,escapedCommand:r,parsed:o,timedOut:R,isCanceled:d.isCanceled||(o.options.signal?o.options.signal.aborted:!1),killed:a.killed});if(!o.options.reject)return V;throw V}return{command:s,escapedCommand:r,exitCode:0,stdout:C,stderr:k,all:O,failed:!1,timedOut:!1,isCanceled:!1,killed:!1}});return _i(a,o.options),a.all=ji(a,o.options),vi(a),Xn(a,g),a}function Ot(e,t,n){const o=ao(e,t,n),s=Zn(e,t),r=eo(e,t);io(r,o.options);const a=Di(o.options);let c;try{c=lt.spawnSync(o.file,o.args,{...o.options,input:a})}catch(d){throw Oe({error:d,stdout:"",stderr:"",all:"",command:s,escapedCommand:r,parsed:o,timedOut:!1,isCanceled:!1,killed:!1})}const l=be(o.options,c.stdout,c.error),u=be(o.options,c.stderr,c.error);if(c.error||c.status!==0||c.signal!==null){const d=Oe({stdout:l,stderr:u,error:c.error,signal:c.signal,exitCode:c.status,command:s,escapedCommand:r,parsed:o,timedOut:c.error&&c.error.code==="ETIMEDOUT",isCanceled:!1,killed:c.signal!==null});if(!o.options.reject)return d;throw d}return{command:s,escapedCommand:r,exitCode:0,stdout:l,stderr:u,failed:!1,timedOut:!1,isCanceled:!1,killed:!1}}const Xi=({input:e,inputFile:t,stdio:n})=>e===void 0&&t===void 0&&n===void 0?{stdin:"inherit"}:{},co=(e={})=>({preferLocal:!0,...Xi(e),...e});function lo(e){function t(n,...o){if(!Array.isArray(n))return lo({...e,...n});const[s,...r]=ro(n,o);return E(s,r,co(e))}return t.sync=(n,...o)=>{if(!Array.isArray(n))throw new TypeError("Please use $(options).sync`command` instead of $.sync(options)`command`.");const[s,...r]=ro(n,o);return Ot(s,r,co(e))},t}const Qi=lo();function Zi(e,t){const[n,...o]=no(e);return E(n,o,t)}function ea(e,t){const[n,...o]=no(e);return Ot(n,o,t)}function ta(e,t,n={}){t&&!Array.isArray(t)&&typeof t=="object"&&(n=t,t=[]);const o=ni(n),s=G.execArgv.filter(c=>!c.startsWith("--inspect")),{nodePath:r=G.execPath,nodeOptions:a=s}=n;return E(r,[...a,e,...Array.isArray(t)?t:[]],{...n,stdin:void 0,stdout:void 0,stderr:void 0,stdio:o,shell:!1})}var na=Object.freeze({__proto__:null,execa:E,execaSync:Ot,$:Qi,execaCommand:Zi,execaCommandSync:ea,execaNode:ta});const{hasOwnProperty:Dt}=Object.prototype,Fe=typeof process<"u"&&process.platform==="win32"?`\r
|
|
8
|
+
`:`
|
|
9
|
+
`,Nt=(e,t)=>{const n=[];let o="";typeof t=="string"?t={section:t,whitespace:!1}:(t=t||Object.create(null),t.whitespace=t.whitespace===!0);const s=t.whitespace?" = ":"=";for(const r of Object.keys(e)){const a=e[r];if(a&&Array.isArray(a))for(const c of a)o+=ce(r+"[]")+s+ce(c)+Fe;else a&&typeof a=="object"?n.push(r):o+=ce(r)+s+ce(a)+Fe}t.section&&o.length&&(o="["+ce(t.section)+"]"+Fe+o);for(const r of n){const a=uo(r).join("\\."),c=(t.section?t.section+".":"")+a,{whitespace:l}=t,u=Nt(e[r],{section:c,whitespace:l});o.length&&u.length&&(o+=Fe),o+=u}return o},uo=e=>e.replace(/\1/g,"LITERAL\\1LITERAL").replace(/\\\./g,"").split(/\./).map(t=>t.replace(/\1/g,"\\.").replace(/\2LITERAL\\1LITERAL\2/g,"")),mo=e=>{const t=Object.create(null);let n=t,o=null;const s=/^\[([^\]]*)\]$|^([^=]+)(=(.*))?$/i,r=e.split(/[\r\n]+/g);for(const c of r){if(!c||c.match(/^\s*[;#]/))continue;const l=c.match(s);if(!l)continue;if(l[1]!==void 0){if(o=Ge(l[1]),o==="__proto__"){n=Object.create(null);continue}n=t[o]=t[o]||Object.create(null);continue}const u=Ge(l[2]),d=u.length>2&&u.slice(-2)==="[]",m=d?u.slice(0,-2):u;if(m==="__proto__")continue;const g=l[3]?Ge(l[4]):!0,y=g==="true"||g==="false"||g==="null"?JSON.parse(g):g;d&&(Dt.call(n,m)?Array.isArray(n[m])||(n[m]=[n[m]]):n[m]=[]),Array.isArray(n[m])?n[m].push(y):n[m]=y}const a=[];for(const c of Object.keys(t)){if(!Dt.call(t,c)||typeof t[c]!="object"||Array.isArray(t[c]))continue;const l=uo(c);n=t;const u=l.pop(),d=u.replace(/\\\./g,".");for(const m of l)m!=="__proto__"&&((!Dt.call(n,m)||typeof n[m]!="object")&&(n[m]=Object.create(null)),n=n[m]);n===t&&d===u||(n[d]=t[c],a.push(c))}for(const c of a)delete t[c];return t},fo=e=>e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"),ce=e=>typeof e!="string"||e.match(/[=\r\n]/)||e.match(/^\[/)||e.length>1&&fo(e)||e!==e.trim()?JSON.stringify(e):e.split(";").join("\\;").split("#").join("\\#"),Ge=(e,t)=>{if(e=(e||"").trim(),fo(e)){e.charAt(0)==="'"&&(e=e.slice(1,-1));try{e=JSON.parse(e)}catch{}}else{let n=!1,o="";for(let s=0,r=e.length;s<r;s++){const a=e.charAt(s);if(n)"\\;#".indexOf(a)!==-1?o+=a:o+="\\"+a,n=!1;else{if(";#".indexOf(a)!==-1)break;a==="\\"?n=!0:o+=a}}return n&&(o+="\\"),o.trim()}return e};var oa={parse:mo,decode:mo,stringify:Nt,encode:Nt,safe:ce,unsafe:Ge},le=oe(oa);const ue=3,sa=3,po={mode:"none",maxHunkLines:0,maxDiffLines:0},ra=(e,t={})=>{const n={...po,...t},o=e.split(`
|
|
10
|
+
`).length;return n.mode==="none"||!e.trim()?{diff:e,stats:{originalLines:o,compressedLines:o,originalChars:e.length,compressedChars:e.length,truncatedHunks:0,truncatedFiles:0}}:ia(e,n,o)},ia=(e,t,n)=>{const o=aa(e),s=[];let r=0,a=0;const c=t.maxDiffLines>0?t.maxDiffLines:1/0,l=t.maxHunkLines>0?t.maxHunkLines:1/0;for(let m=0;m<o.length;m++){if(s.length>=c){a+=o.length-m;break}const{lines:g,hunksTruncated:y}=ca(o[m],l);r+=y;const f=c-s.length;if(g.length>f){s.push(...g.slice(0,f)),a+=o.length-m-1;break}s.push(...g)}if(r>0||a>0){const m=[];r>0&&m.push(`${r} hunk${r>1?"s":""} truncated`),a>0&&m.push(`${a} file${a>1?"s":""} omitted`),s.push("",`[diff compressed \u2014 ${m.join(", ")}]`)}const d=s.join(`
|
|
11
|
+
`);return{diff:d,stats:{originalLines:n,compressedLines:s.length,originalChars:e.length,compressedChars:d.length,truncatedHunks:r,truncatedFiles:a}}},aa=e=>{const t=e.split(`
|
|
12
|
+
`),n=[];let o=[];for(const s of t)s.startsWith("diff --git ")?(o.length>0&&n.push(o),o=[s]):o.push(s);return o.length>0&&n.push(o),n},ca=(e,t)=>{const o=[`=== ${ua(e)} ===`];let s=0;const r=[];let a=null;for(const c of e)if(!da(c)){if(c.startsWith("@@")){a&&r.push(a),a={header:c,lines:[]};continue}a&&a.lines.push(c)}a&&r.push(a);for(const c of r){o.push(c.header);const l=la(c.lines);if(t>0&&l.length>t){const u=l.length-t;o.push(...l.slice(0,t)),o.push(`[... ${u} lines truncated]`),s++}else o.push(...l)}return{lines:o,hunksTruncated:s}},la=e=>{if(e.length===0)return[];const t=e.map(r=>r.startsWith("+")||r.startsWith("-")),n=new Array(e.length).fill(!1);for(let r=0;r<e.length;r++)if(t[r]){n[r]=!0;for(let a=1;a<=sa;a++)r-a>=0&&(n[r-a]=!0),r+a<e.length&&(n[r+a]=!0);continue}const o=[];let s=!1;for(let r=0;r<e.length;r++)n[r]?(s&&(o.push(" ..."),s=!1),o.push(e[r])):s=!0;return o},ua=e=>{const n=(e[0]||"").match(/^diff --git a\/(.+?) b\/(.+)$/);if(!n)return"unknown";const[,o,s]=n;return o!==s?`${o} \u2192 ${s}`:s},da=e=>e.startsWith("diff --git ")||e.startsWith("index ")||e.startsWith("--- a/")||e.startsWith("--- /dev/null")||e.startsWith("+++ b/")||e.startsWith("+++ /dev/null")||e.startsWith("old mode ")||e.startsWith("new mode ")||e.startsWith("new file mode ")||e.startsWith("deleted file mode ")||e.startsWith("similarity index ")||e.startsWith("rename from ")||e.startsWith("rename to ")||e.startsWith("Binary files ");class p extends Error{constructor(t,n={}){super(t,{cause:n.cause}),this.name="KnownError",this.code=n.code,this.suggestions=n.suggestions||[]}}const Ee=" ",q=e=>{if(e instanceof Error){if(e instanceof p){e.suggestions.length>0&&(console.error(""),console.error(`${Ee}${h.yellow("Suggestions:")}`),e.suggestions.forEach(t=>{console.error(`${Ee} ${h.dim("\u2022")} ${t}`)}));return}e.stack&&console.error(h.dim(e.stack.split(`
|
|
13
|
+
`).slice(1).join(`
|
|
14
|
+
`))),console.error(`
|
|
15
|
+
${Ee}${h.dim(`aicommit2 v${vn}`)}`),console.error(`
|
|
16
|
+
${Ee}Please open a Bug report with the information above:`),console.error(`${Ee}https://github.com/tak-bro/aicommit2/issues/new/choose`)}},Be=e=>I.lstat(e).then(()=>!0,()=>!1),ho=async e=>{try{await I.mkdir(e,{recursive:!0})}catch(t){if(t.code!=="EEXIST")throw t}},ma=e=>e&&`${e[0].toUpperCase()}${e.slice(1)}`,fa=(e,t)=>{const n=Math.ceil(e),o=Math.floor(t);return Math.floor(Math.random()*(o-n+1))+n},go=(e,t)=>e.disabled&&!t.disabled?1:!e.disabled&&t.disabled?-1:0,_t=e=>e.reduce((t,n)=>Array.isArray(n)?t.concat(_t(n)):t.concat(n),[]),pa=(e,t=5)=>e.replace(/[\n\r]/g,"").split(" ").slice(0,t).join(" "),ha=e=>{let t=0;for(let n=0;n<e.length;n++){const o=e.charCodeAt(n);t=(t<<5)-t+o,t=t&t}return Math.abs(t)},ga=e=>{const t=e%360,n=65+e%15,o=45+e%10;return`hsl(${t}, ${n}%, ${o}%)`},ya=e=>{const[t,n,o]=e.match(/\d+/g).map((m,g)=>g===0?Number(m):Number(m)/100),s=(1-Math.abs(2*o-1))*n,r=s*(1-Math.abs(t/60%2-1)),a=o-s/2;let c,l,u;t<60?[c,l,u]=[s,r,0]:t<120?[c,l,u]=[r,s,0]:t<180?[c,l,u]=[0,s,r]:t<240?[c,l,u]=[0,r,s]:t<300?[c,l,u]=[r,0,s]:[c,l,u]=[s,0,r];const d=m=>{const g=Math.round((m+a)*255).toString(16);return g.length===1?"0"+g:g};return`#${d(c)}${d(l)}${d(u)}`},wa=e=>{const t=ha(e),n=ga(t);return{primary:ya(n),secondary:"#FFFFFF"}},Ca=e=>{try{return{ok:!0,data:JSON.parse(e)}}catch(t){return{ok:!1,error:t}}},He=e=>{if(!e||typeof e!="string")return"";if(P.isAbsolute(e))return P.resolve(e);if(Ae){const t=P.dirname(Ae),n=P.join(t,e);return P.resolve(n)}else return""},ba=["","conventional","gitmoji"],ve="http://localhost:11434",{hasOwnProperty:Ea}=Object.prototype,jt=(e,t)=>Ea.call(e,t),de=["OPENAI","COPILOT_SDK","OPENROUTER","OLLAMA","HUGGINGFACE","GEMINI","ANTHROPIC","MISTRAL","CODESTRAL","COHERE","GROQ","PERPLEXITY","DEEPSEEK","GITHUB_MODELS","BEDROCK"],yo=e=>{const t=Ie.platform(),n=Ie.homedir();let o,s;switch(e){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(t==="darwin")e==="cache"?s=P.join(n,"Library","Caches"):s=P.join(n,"Library","Application Support");else if(t==="win32")s=process.env.LOCALAPPDATA||n;else switch(e){case"config":s=P.join(n,".config");break;case"data":s=P.join(n,".local","share");break;case"cache":s=P.join(n,".cache");break;case"state":s=P.join(n,".local","state");break;default:s=n}return o||s},wo=P.join(yo("config"),"aicommit2"),H=P.join(yo("state"),"aicommit2","logs"),Co=P.join(wo,"config.ini"),bo=P.join(H,"aicommit2-%DATE%.log"),Eo=P.join(H,"exceptions-%DATE%.log"),va=e=>{const t=Object.keys(e),n=new Set([...de,...t.filter(o=>/^[A-Z][A-Z0-9_]*$/.test(o))]);return Array.from(n)},v=(e,t,n)=>{if(!t)throw new p(`Invalid config property ${e}: ${n}`)},F=(e,t=!1)=>n=>typeof n=="boolean"?n:n==null?t:(v(e,/^(?:true|false)$/.test(n),"Must be a boolean(true or false)"),n==="true"),Ue=e=>t=>{if(!t)return{};if(typeof t=="object")return v(e,!Array.isArray(t),"Must be a JSON object"),t;try{const n=JSON.parse(t);return v(e,typeof n=="object"&&n!==null&&!Array.isArray(n),"Must be a valid JSON object"),n}catch(n){throw new p(`Invalid ${e}: Must be valid JSON. Error: ${n.message}`)}},i={systemPrompt(e){return e||""},systemPromptPath(e){return e||""},codeReviewPromptPath(e){return e||""},timeout(e){if(!e)return 6e4;v("timeout",/^\d+$/.test(e),"Must be an integer");const t=Number(e);return v("timeout",t>=500,"Must be greater than 500ms"),t},temperature(e){if(!e)return .7;v("temperature",/^(2|\d)(\.\d{1,2})?$/.test(e),"Must be decimal between 0 and 2");const t=Number(e);return v("temperature",t>0,"Must be greater than 0"),v("temperature",t<=2,"Must be less than or equal to 2"),t},maxTokens(e){return e?(v("maxTokens",/^\d+$/.test(e),"Must be an integer"),Number(e)):8192},logLevel(e){return e?(v("logLevel",/^(?:error|warn|info|http|verbose|debug|silly)$/.test(e),"Must be a valid log level (error, warn, info, http, verbose, debug, silly)"),e):"info"},logFilePath(e){return e||bo},exceptionLogFilePath(e){return e||Eo},locale(e){return e?(v("locale",e,"Cannot be empty"),v("locale",/^[a-z-]+$/i.test(e),"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"),e):"en"},generate(e){if(!e)return 1;v("generate",/^\d+$/.test(e),"Must be an integer");const t=Number(e);return v("generate",t>0,"Must be greater than 0"),v("generate",t<=5,"Must be less or equal to 5"),t},type(e){return e?(v("type",ba.includes(e),"Invalid commit type"),e):"conventional"},maxLength(e){if(!e)return 50;v("maxLength",/^\d+$/.test(e),"Must be an integer");const t=Number(e);return v("maxLength",t>=20,"Must be greater than 20 characters"),t},exclude:e=>e?(typeof e=="string"?e?.split(","):e).map(n=>n.trim()).filter(n=>!!n&&n.length>0):[],topP:e=>{if(!e)return .9;v("topP",/^(1|\d)(\.\d{1,2})?$/.test(e),"Must be decimal between 0 and 1");const t=Number(e);return v("topP",t>0,"Must be greater than 0"),v("topP",t<=1,"Must be less than or equal to 1"),t},logging:F("logging",!0),includeBody:F("includeBody"),codeReview:F("codeReview"),disabled:F("disabled"),watchMode:F("watchMode"),forceGit:F("forceGit"),stream:F("stream"),disableLowerCase:F("disableLowerCase"),jjAutoNew:F("jjAutoNew"),autoCopy:F("autoCopy"),modelNameDisplay:e=>e?(v("modelNameDisplay",/^(?:none|short|full)$/.test(e),"Must be none, short, or full"),e):"short",diffCompression:e=>e?(v("diffCompression",/^(?:none|compact)$/.test(e),"Must be none or compact"),e):po.mode,maxHunkLines:e=>e?(v("maxHunkLines",/^\d+$/.test(e),"Must be an integer"),Number(e)):0,maxDiffLines:e=>e?(v("maxDiffLines",/^\d+$/.test(e),"Must be an integer"),Number(e)):0,diffContext:e=>{if(!e)return ue;v("diffContext",/^\d+$/.test(e),"Must be an integer");const t=Number(e);return v("diffContext",t>=0&&t<=10,"Must be between 0 and 10"),t},useStats:F("useStats",!0),statsDays:e=>{if(!e)return 30;v("statsDays",/^\d+$/.test(e),"Must be an integer");const t=Number(e);return v("statsDays",t>0,"Must be greater than 0"),t}},Pe={OPENAI:{key:e=>e||"",envKey:e=>e||"",model:e=>e?(typeof e=="string"?e?.split(","):e).map(n=>n.trim()).filter(n=>!!n&&n.length>0):["gpt-4o-mini"],url:e=>e?(v("OPENAI.url",/^https?:\/\//.test(e),"Must be a valid URL"),e):"https://api.openai.com",path:e=>e||"/v1/chat/completions",proxy:e=>e||"",topP:i.topP,systemPrompt:i.systemPrompt,systemPromptPath:i.systemPromptPath,codeReviewPromptPath:i.codeReviewPromptPath,timeout:i.timeout,temperature:i.temperature,maxTokens:i.maxTokens,logging:i.logging,locale:i.locale,generate:i.generate,type:i.type,maxLength:i.maxLength,includeBody:i.includeBody,codeReview:i.codeReview,disabled:i.disabled,stream:i.stream,watchMode:i.watchMode,disableLowerCase:i.disableLowerCase,diffCompression:i.diffCompression,maxHunkLines:i.maxHunkLines,maxDiffLines:i.maxDiffLines,diffContext:i.diffContext},OPENROUTER:{key:e=>e||"",envKey:e=>e||"",model:e=>e?(typeof e=="string"?e?.split(","):e).map(n=>n.trim()).filter(n=>!!n&&n.length>0):["openrouter/auto"],url:e=>e?(v("OPENROUTER.url",/^https?:\/\//.test(e),"Must be a valid URL"),e):"https://openrouter.ai",path:e=>e||"/api/v1/chat/completions",responseFormat:Ue("OPENROUTER.responseFormat"),provider:Ue("OPENROUTER.provider"),reasoning:Ue("OPENROUTER.reasoning"),topP:i.topP,systemPrompt:i.systemPrompt,systemPromptPath:i.systemPromptPath,codeReviewPromptPath:i.codeReviewPromptPath,timeout:i.timeout,temperature:i.temperature,maxTokens:i.maxTokens,logging:i.logging,locale:i.locale,generate:i.generate,type:i.type,maxLength:i.maxLength,includeBody:i.includeBody,codeReview:i.codeReview,disabled:i.disabled,stream:i.stream,watchMode:i.watchMode,disableLowerCase:i.disableLowerCase,diffCompression:i.diffCompression,maxHunkLines:i.maxHunkLines,maxDiffLines:i.maxDiffLines,diffContext:i.diffContext},HUGGINGFACE:{cookie:e=>e||"",model:e=>e?(typeof e=="string"?e?.split(","):e).map(n=>n.trim()).filter(n=>!!n&&n.length>0):["CohereForAI/c4ai-command-r-plus"],systemPrompt:i.systemPrompt,systemPromptPath:i.systemPromptPath,codeReviewPromptPath:i.codeReviewPromptPath,timeout:i.timeout,temperature:i.temperature,maxTokens:i.maxTokens,topP:i.topP,logging:i.logging,locale:i.locale,generate:i.generate,type:i.type,maxLength:i.maxLength,includeBody:i.includeBody,codeReview:i.codeReview,disabled:i.disabled,stream:i.stream,watchMode:i.watchMode,disableLowerCase:i.disableLowerCase,diffCompression:i.diffCompression,maxHunkLines:i.maxHunkLines,maxDiffLines:i.maxDiffLines,diffContext:i.diffContext},GEMINI:{key:e=>e||"",envKey:e=>e||"",model:e=>e?(typeof e=="string"?e?.split(","):e).map(n=>n.trim()).filter(n=>!!n&&n.length>0):["gemini-3-flash-preview"],systemPrompt:i.systemPrompt,systemPromptPath:i.systemPromptPath,codeReviewPromptPath:i.codeReviewPromptPath,timeout:i.timeout,temperature:i.temperature,maxTokens:i.maxTokens,logging:i.logging,locale:i.locale,generate:i.generate,type:i.type,maxLength:i.maxLength,includeBody:i.includeBody,topP:i.topP,codeReview:i.codeReview,disabled:i.disabled,stream:i.stream,watchMode:i.watchMode,disableLowerCase:i.disableLowerCase,diffCompression:i.diffCompression,maxHunkLines:i.maxHunkLines,maxDiffLines:i.maxDiffLines,diffContext:i.diffContext},ANTHROPIC:{key:e=>e||"",envKey:e=>e||"",model:e=>e?(typeof e=="string"?e?.split(","):e).map(n=>n.trim()).filter(n=>!!n&&n.length>0):["claude-sonnet-4-20250514"],systemPrompt:i.systemPrompt,systemPromptPath:i.systemPromptPath,codeReviewPromptPath:i.codeReviewPromptPath,timeout:i.timeout,temperature:i.temperature,maxTokens:i.maxTokens,logging:i.logging,locale:i.locale,generate:i.generate,type:i.type,maxLength:i.maxLength,includeBody:i.includeBody,topP:i.topP,codeReview:i.codeReview,disabled:i.disabled,stream:i.stream,watchMode:i.watchMode,disableLowerCase:i.disableLowerCase,diffCompression:i.diffCompression,maxHunkLines:i.maxHunkLines,maxDiffLines:i.maxDiffLines,diffContext:i.diffContext},MISTRAL:{key:e=>e||"",envKey:e=>e||"",model:e=>e?(typeof e=="string"?e?.split(","):e).map(n=>n.trim()).filter(n=>!!n&&n.length>0):["mistral-small-latest"],systemPrompt:i.systemPrompt,systemPromptPath:i.systemPromptPath,codeReviewPromptPath:i.codeReviewPromptPath,timeout:i.timeout,temperature:i.temperature,maxTokens:i.maxTokens,logging:i.logging,locale:i.locale,generate:i.generate,type:i.type,maxLength:i.maxLength,includeBody:i.includeBody,topP:i.topP,codeReview:i.codeReview,disabled:i.disabled,stream:i.stream,watchMode:i.watchMode,disableLowerCase:i.disableLowerCase,diffCompression:i.diffCompression,maxHunkLines:i.maxHunkLines,maxDiffLines:i.maxDiffLines,diffContext:i.diffContext},CODESTRAL:{key:e=>e||"",envKey:e=>e||"",model:e=>e?(typeof e=="string"?e?.split(","):e).map(n=>n.trim()).filter(n=>!!n&&n.length>0):["codestral-latest"],topP:i.topP,systemPrompt:i.systemPrompt,systemPromptPath:i.systemPromptPath,codeReviewPromptPath:i.codeReviewPromptPath,timeout:i.timeout,temperature:i.temperature,maxTokens:i.maxTokens,logging:i.logging,locale:i.locale,generate:i.generate,type:i.type,maxLength:i.maxLength,includeBody:i.includeBody,codeReview:i.codeReview,disabled:i.disabled,stream:i.stream,watchMode:i.watchMode,disableLowerCase:i.disableLowerCase,diffCompression:i.diffCompression,maxHunkLines:i.maxHunkLines,maxDiffLines:i.maxDiffLines,diffContext:i.diffContext},OLLAMA:{model:e=>e?(typeof e=="string"?e?.split(","):e).map(n=>n.trim()).filter(n=>!!n&&n.length>0):[],host:e=>e?(v("OLLAMA.host",/^https?:\/\//.test(e),"Must be a valid URL"),e):ve,timeout:e=>{if(!e)return 1e5;v("OLLAMA.timeout",/^\d+$/.test(e),"Must be an integer");const t=Number(e);return v("OLLAMA.timeout",t>=500,"Must be greater than 500ms"),t},auth:e=>e||"",key:e=>e||"",envKey:e=>e||"",numCtx:e=>{if(!e)return 2048;v("OLLAMA.numCtx",/^\d+$/.test(e),"Must be an integer");const t=Number(e);return v("OLLAMA.numCtx",t>=2048,"Must be greater than 2048"),t},systemPrompt:i.systemPrompt,systemPromptPath:i.systemPromptPath,codeReviewPromptPath:i.codeReviewPromptPath,temperature:i.temperature,maxTokens:i.maxTokens,logging:i.logging,locale:i.locale,generate:i.generate,type:i.type,maxLength:i.maxLength,includeBody:i.includeBody,topP:i.topP,codeReview:i.codeReview,disabled:i.disabled,stream:i.stream,watchMode:i.watchMode,disableLowerCase:i.disableLowerCase,diffCompression:i.diffCompression,maxHunkLines:i.maxHunkLines,maxDiffLines:i.maxDiffLines,diffContext:i.diffContext},COHERE:{key:e=>e||"",envKey:e=>e||"",url:e=>e?(v("COHERE.url",/^https?:\/\//.test(e),"Must be a valid URL"),e):"https://api.cohere.ai",model:e=>e?(typeof e=="string"?e?.split(","):e).map(n=>n.trim()).filter(n=>!!n&&n.length>0):["command-a-03-2025"],systemPrompt:i.systemPrompt,systemPromptPath:i.systemPromptPath,codeReviewPromptPath:i.codeReviewPromptPath,temperature:i.temperature,maxTokens:i.maxTokens,logging:i.logging,locale:i.locale,timeout:i.timeout,generate:i.generate,type:i.type,maxLength:i.maxLength,includeBody:i.includeBody,topP:i.topP,codeReview:i.codeReview,disabled:i.disabled,stream:i.stream,watchMode:i.watchMode,disableLowerCase:i.disableLowerCase,diffCompression:i.diffCompression,maxHunkLines:i.maxHunkLines,maxDiffLines:i.maxDiffLines,diffContext:i.diffContext},GROQ:{key:e=>e||"",envKey:e=>e||"",model:e=>e?(typeof e=="string"?e?.split(","):e).map(n=>n.trim()).filter(n=>!!n&&n.length>0):["llama-3.3-70b-versatile"],systemPrompt:i.systemPrompt,systemPromptPath:i.systemPromptPath,codeReviewPromptPath:i.codeReviewPromptPath,timeout:i.timeout,temperature:i.temperature,maxTokens:i.maxTokens,logging:i.logging,locale:i.locale,generate:i.generate,type:i.type,maxLength:i.maxLength,includeBody:i.includeBody,topP:i.topP,codeReview:i.codeReview,disabled:i.disabled,stream:i.stream,watchMode:i.watchMode,disableLowerCase:i.disableLowerCase,diffCompression:i.diffCompression,maxHunkLines:i.maxHunkLines,maxDiffLines:i.maxDiffLines,diffContext:i.diffContext},PERPLEXITY:{key:e=>e||"",envKey:e=>e||"",model:e=>e?(typeof e=="string"?e?.split(","):e).map(n=>n.trim()).filter(n=>!!n&&n.length>0):["sonar"],topP:i.topP,systemPrompt:i.systemPrompt,systemPromptPath:i.systemPromptPath,codeReviewPromptPath:i.codeReviewPromptPath,timeout:i.timeout,temperature:i.temperature,maxTokens:i.maxTokens,logging:i.logging,locale:i.locale,generate:i.generate,type:i.type,maxLength:i.maxLength,includeBody:i.includeBody,codeReview:i.codeReview,disabled:i.disabled,stream:i.stream,watchMode:i.watchMode,disableLowerCase:i.disableLowerCase,diffCompression:i.diffCompression,maxHunkLines:i.maxHunkLines,maxDiffLines:i.maxDiffLines,diffContext:i.diffContext},DEEPSEEK:{key:e=>e||"",envKey:e=>e||"",model:e=>e?(typeof e=="string"?e?.split(","):e).map(n=>n.trim()).filter(n=>!!n&&n.length>0):["deepseek-chat"],topP:i.topP,systemPrompt:i.systemPrompt,systemPromptPath:i.systemPromptPath,codeReviewPromptPath:i.codeReviewPromptPath,timeout:i.timeout,temperature:i.temperature,maxTokens:i.maxTokens,logging:i.logging,locale:i.locale,generate:i.generate,type:i.type,maxLength:i.maxLength,includeBody:i.includeBody,codeReview:i.codeReview,disabled:i.disabled,stream:i.stream,watchMode:i.watchMode,disableLowerCase:i.disableLowerCase,diffCompression:i.diffCompression,maxHunkLines:i.maxHunkLines,maxDiffLines:i.maxDiffLines,diffContext:i.diffContext},GITHUB_MODELS:{key:e=>e||"",envKey:e=>e||"",model:e=>e?(typeof e=="string"?e?.split(","):e).map(n=>n.trim()).filter(n=>!!n&&n.length>0):["openai/gpt-4o-mini"],systemPrompt:i.systemPrompt,systemPromptPath:i.systemPromptPath,codeReviewPromptPath:i.codeReviewPromptPath,timeout:i.timeout,temperature:i.temperature,maxTokens:i.maxTokens,logging:i.logging,locale:i.locale,generate:i.generate,type:i.type,maxLength:i.maxLength,includeBody:i.includeBody,topP:i.topP,codeReview:i.codeReview,disabled:i.disabled,stream:i.stream,watchMode:i.watchMode,disableLowerCase:i.disableLowerCase,diffCompression:i.diffCompression,maxHunkLines:i.maxHunkLines,maxDiffLines:i.maxDiffLines,diffContext:i.diffContext},COPILOT_SDK:{key:e=>e||"",envKey:e=>e||"",model:e=>e?(typeof e=="string"?e?.split(","):e).map(n=>n.trim()).filter(n=>!!n&&n.length>0):["gpt-4.1"],systemPrompt:i.systemPrompt,systemPromptPath:i.systemPromptPath,codeReviewPromptPath:i.codeReviewPromptPath,timeout:i.timeout,temperature:i.temperature,maxTokens:i.maxTokens,logging:i.logging,locale:i.locale,generate:i.generate,type:i.type,maxLength:i.maxLength,includeBody:i.includeBody,topP:i.topP,codeReview:i.codeReview,disabled:i.disabled,stream:i.stream,watchMode:i.watchMode,disableLowerCase:i.disableLowerCase,diffCompression:i.diffCompression,maxHunkLines:i.maxHunkLines,maxDiffLines:i.maxDiffLines,diffContext:i.diffContext},BEDROCK:{key:e=>e||"",envKey:e=>e&&e.length>0?e:"BEDROCK_API_KEY",model:e=>e?(typeof e=="string"?e?.split(","):e).map(n=>{const o=n.trim();return o&&!o.includes(".")&&!o.includes(":")&&console.warn(`[Bedrock] Model ID "${o}" may be invalid.
|
|
17
|
+
Expected formats:
|
|
18
|
+
- Foundation model: "provider.model-name-version" (e.g., "anthropic.claude-haiku-4-5-20251001-v1:0")
|
|
19
|
+
- Inference profile: "prefix.provider.model-name-version" (e.g., "us.anthropic.claude-haiku-4-5-20251001-v1:0")
|
|
20
|
+
- ARN: Full Amazon Resource Name
|
|
21
|
+
See https://docs.aws.amazon.com/bedrock/latest/userguide/inference-profiles.html`),o}).filter(n=>!!n&&n.length>0):["anthropic.claude-haiku-4-5-20251001-v1:0"],runtimeMode:e=>{e&&console.warn("[Bedrock] DEPRECATION: runtimeMode is no longer used. Authentication method is now auto-detected from configured credentials.")},region:e=>e||process.env.AWS_REGION||process.env.AWS_DEFAULT_REGION||"",profile:e=>e||process.env.AWS_PROFILE||"",accessKeyId:e=>e||process.env.AWS_ACCESS_KEY_ID||"",secretAccessKey:e=>e||process.env.AWS_SECRET_ACCESS_KEY||"",sessionToken:e=>e||process.env.AWS_SESSION_TOKEN||"",applicationEndpointId:e=>e||process.env.BEDROCK_APPLICATION_ENDPOINT_ID||"",applicationInferenceProfileArn:e=>e||process.env.BEDROCK_APPLICATION_INFERENCE_PROFILE_ARN||process.env.BEDROCK_INFERENCE_PROFILE_ARN||"",applicationBaseUrl:e=>e||process.env.BEDROCK_APPLICATION_BASE_URL||"",systemPrompt:i.systemPrompt,systemPromptPath:i.systemPromptPath,codeReviewPromptPath:i.codeReviewPromptPath,timeout:i.timeout,temperature:e=>{if(!e)return;v("temperature",/^(2|\d)(\.\d{1,2})?$/.test(e),"Must be decimal between 0 and 2");const t=Number(e);return v("temperature",t>0,"Must be greater than 0"),v("temperature",t<=2,"Must be less than or equal to 2"),t},maxTokens:e=>{if(e)return v("maxTokens",/^\d+$/.test(e),"Must be an integer"),Number(e)},logging:i.logging,locale:i.locale,generate:i.generate,type:i.type,maxLength:i.maxLength,includeBody:i.includeBody,topP:e=>{if(!e)return;v("topP",/^(1|\d)(\.\d{1,2})?$/.test(e),"Must be decimal between 0 and 1");const t=Number(e);return v("topP",t>0,"Must be greater than 0"),v("topP",t<=1,"Must be less than or equal to 1"),t},codeReview:i.codeReview,disabled:i.disabled,stream:i.stream,watchMode:i.watchMode,disableLowerCase:i.disableLowerCase,inferenceParameters:Ue("BEDROCK.inferenceParameters"),diffCompression:i.diffCompression,maxHunkLines:i.maxHunkLines,maxDiffLines:i.maxDiffLines,diffContext:i.diffContext}},Pa=e=>typeof e=="object"&&e!==null,vo=(e,t)=>{Object.keys(e).forEach(n=>{const o=e[n];Pa(o)&&t in o&&(o[t]=!0)})},Aa=e=>{vo(e,"includeBody")},xa=e=>{vo(e,"disableLowerCase")};let Ae,xe=null,Ft=null;const Sa=(e=[])=>{const t={};for(const n of e)if(n.startsWith("--")){const[o,s]=n.slice(2).split("="),[r,a]=o.split(".");r&&a&&r in Pe?(t[r]||(t[r]={}),t[r][a]=s):t[o]=s}return t},$a=()=>{const e=Ie.homedir(),t=process.env.AICOMMIT_CONFIG_PATH,n=Co,o=P.join(e,".aicommit2");return[t,n,o].filter(s=>!!s)},me=async()=>{const e=$a();for(const t of e)if(await Be(t))return t;return Co},Ra=e=>e.replace(/\$\{([a-zA-Z_][a-zA-Z0-9_]*)\}|\$([a-zA-Z_][a-zA-Z0-9_]*)/g,(t,n,o)=>{const s=n||o;return process.env[s]??""}),Po=e=>{if(Array.isArray(e)||e===null||typeof e!="object")return e;const t={};for(const[n,o]of Object.entries(e)){const s=Po(o);if(!n.includes(".")){t[n]=s;continue}const r=n.split(".");let a=t;for(const c of r.slice(0,-1)){const l=a[c];(!l||typeof l!="object"||Array.isArray(l))&&(a[c]={}),a=a[c]}a[r[r.length-1]]=s}return t},Se=async()=>{const e=await me();if(xe&&Ft===e)return xe;Ae=e;try{const t=await I.readFile(e,"utf8"),n=Ra(t);return xe=Po(le.parse(n)),Ft=e,xe}catch(t){return t.code==="ENOENT"?(Ae=void 0,{}):(console.error(`Error reading config file ${e}:`,t),Ae=void 0,{})}},Ao=()=>{xe=null,Ft=null},X=async(e,t=[])=>{const n=await Se(),o=Sa(t),s={...e,...o},r={},a=va(n),c={};for(const u of a){const d=n[u]?.envKey;let m;d?(m=[d],u==="BEDROCK"&&d!=="BEDROCK_APPLICATION_API_KEY"&&m.push("BEDROCK_APPLICATION_API_KEY")):u==="BEDROCK"?m=["BEDROCK_API_KEY","BEDROCK_APPLICATION_API_KEY"]:m=[`${u}_API_KEY`];const g=m.map(y=>y?process.env[y]:void 0).find(y=>typeof y=="string"&&y.length>0);g&&(c[u]={key:g})}const l=(u,d)=>{const m=s[`${u}.${d}`]??s[u]?.[d],g=c[u]?.[d],y=n[u]?.[d],f=s[d]??n[d];return m!==void 0?m:g!==void 0?g:y!==void 0?y:f};for(const[u,d]of Object.entries(i)){const m=s[u]??n[u];r[u]=d(m)}for(const u of a){r[u]={};const d=Pe[u]||We(u);for(const[m,g]of Object.entries(d)){const y=l(u,m);r[u][m]=g(y)}}return r},Ke=async e=>{const t=await Se();for(const[s,r]of e){const[a,c]=s.split(".");if(!c){const d=i[s];if(!d)throw new p(`Invalid config property: ${s}`);t[s]=d(r);continue}if(t[a]||(t[a]={}),de.includes(a)){const d=Pe[a][c];if(!d)throw new p(`Invalid config property: ${s}`);t[a][c]=d(r);continue}if(!/^[A-Z][A-Z0-9_]*$/.test(a))throw new p(`Invalid service name: ${a}. Service names must be uppercase letters, numbers, and underscores.`);const u=We(a);if(!u[c])throw new p(`Invalid config property for custom service: ${s}`);try{t[a][c]=u[c](r)}catch(d){throw d instanceof p?d:new p(`Invalid value for ${s}: ${d.message}`)}}const n=await me(),o=P.dirname(n);await I.mkdir(o,{recursive:!0}),await I.writeFile(n,le.stringify(t),"utf8"),Ao()},Ia=async e=>{const t=await Se();for(const[s,r]of e){const[a,c]=s.split("."),l=t[a];if(c==="model"){l||(t[a]={});const d=t[a][c]||[],m=typeof r=="string"?r.split(",").map(g=>g.trim()).filter(g=>!!g):r;t[a][c]=_t([...d,...m]);continue}if(l&&l.compatible===!0){l||(t[a]={});const d=We(a);if(!d[c])throw new p(`Invalid config property: ${s}`);try{t[a][c]=d[c](r)}catch(m){throw m instanceof p?m:new p(`Invalid value for ${s}: ${m.message}`)}continue}if(a in Pe){l||(t[a]={});const d=Pe[a][c];if(!d)throw new p(`Invalid config property: ${s}`);t[a][c]=d(r)}else{const d=We(a);if(!d[c])throw new p(`Invalid config property: ${s}`);t[a]||(t[a]={}),t[a][c]=d[c](r)}}const n=await me(),o=P.dirname(n);await I.mkdir(o,{recursive:!0}),await I.writeFile(n,le.stringify(t),"utf8"),Ao()},ka=async()=>{const e=await Se();console.log(le.stringify(e))},La=async()=>{console.log(await me())},We=e=>({compatible:F("compatible"),stream:F("stream"),url:t=>t?(v(`${e}.url`,/^https?:\/\//.test(t),"Must be a valid URL"),t):"",path:t=>t||"",key:t=>t||"",envKey:t=>t||"",model:t=>t?(typeof t=="string"?t?.split(","):t).map(o=>o.trim()).filter(o=>!!o&&o.length>0):[],systemPrompt:i.systemPrompt,systemPromptPath:i.systemPromptPath,codeReviewPromptPath:i.codeReviewPromptPath,timeout:i.timeout,temperature:i.temperature,maxTokens:i.maxTokens,logging:i.logging,locale:i.locale,generate:i.generate,type:i.type,maxLength:i.maxLength,includeBody:i.includeBody,topP:i.topP,codeReview:i.codeReview,disabled:i.disabled,watchMode:i.watchMode,disableLowerCase:i.disableLowerCase,autoCopy:i.autoCopy,diffCompression:i.diffCompression,maxHunkLines:i.maxHunkLines,maxDiffLines:i.maxDiffLines,diffContext:i.diffContext}),D=e=>typeof e=="string"&&e.trim().length>0,Ma=()=>{try{const e=typeof pt<"u"?pt.resolve:void 0;return e?(e("@github/copilot-sdk"),!0):typeof import.meta.resolve=="function"?(import.meta.resolve("@github/copilot-sdk"),!0):!1}catch{return!1}};let Gt;const Ta=e=>Y(e)?(Gt===void 0&&(Gt=Ma()),Gt):!1,Y=e=>(Array.isArray(e.model)?e.model:D(e.model)?[e.model.trim()]:[]).length>0,qe=e=>{const t=D(e.key),n=D(e.region)||D(process.env.AWS_REGION)||D(process.env.AWS_DEFAULT_REGION),o=D(e.profile)||D(process.env.AWS_PROFILE),s=D(e.accessKeyId)&&D(e.secretAccessKey)||D(process.env.AWS_ACCESS_KEY_ID)&&D(process.env.AWS_SECRET_ACCESS_KEY),r=D(e.applicationBaseUrl)||D(process.env.BEDROCK_APPLICATION_BASE_URL),a=D(e.applicationEndpointId)||D(process.env.BEDROCK_APPLICATION_ENDPOINT_ID),c=D(process.env.BEDROCK_APPLICATION_API_KEY);return n&&(t||o||s)||(r&&t||a&&c)},fe=(e,t)=>Object.entries(e).map(([n,o])=>[n,o]).filter(([n,o])=>!o.disabled).filter(([n,o])=>de.includes(n)||o.compatible===!0).filter(([n,o])=>{switch(t){case"commit":return n==="OLLAMA"?!!o&&Y(o):n==="COPILOT_SDK"?!!o&&Ta(o):n==="HUGGINGFACE"?!!o&&!!o.cookie:n==="BEDROCK"?Y(o)&&qe(o):!!o.key&&o.key.length>0;case"review":const s=e.codeReview||o.codeReview;return n==="OLLAMA"||n==="COPILOT_SDK"?!!o&&Y(o)&&s:n==="HUGGINGFACE"?!!o&&!!o.cookie&&s:n==="BEDROCK"?Y(o)&&qe(o)&&s:!!o.key&&o.key.length>0&&s;case"watch":const r=e.watchMode||o.watchMode;return n==="OLLAMA"||n==="COPILOT_SDK"?!!o&&Y(o)&&r:n==="HUGGINGFACE"?!!o&&!!o.cookie&&r:n==="BEDROCK"?Y(o)&&qe(o)&&r:o.compatible?!!o.url&&!!o.key&&r:!!o.key&&o.key.length>0&&r}}).map(([n])=>n);class Oa{static create(t,n){return new t(n)}}const Da="stats.json",ze=2,Na=30,Bt=()=>P.join(wo,Da),Ye=async()=>{const e=Bt();if(!await Be(e))return{version:ze,metrics:[],selections:[]};try{const t=await I.readFile(e,"utf-8"),n=JSON.parse(t);return!n.version||n.version<ze?{version:ze,metrics:n.metrics||[],selections:n.selections||[]}:n}catch{return{version:ze,metrics:[],selections:[]}}},_a=(e,t)=>{const n=Date.now()-t*24*60*60*1e3;return{version:e.version,metrics:e.metrics.filter(o=>o.timestamp>=n),selections:e.selections.filter(o=>o.timestamp>=n)}},xo=async(e,t)=>{const n=Bt(),o=P.dirname(n),s=t?_a(e,t):e;await I.mkdir(o,{recursive:!0}),await I.writeFile(n,JSON.stringify(s,null,2),"utf-8")},ja=async e=>{const t={timestamp:Date.now(),provider:e.provider,model:e.model,responseTimeMs:e.responseTimeMs,success:e.success,errorCode:e.errorCode,tokensUsed:e.tokensUsed},n=await Ye();n.metrics.push(t),await xo(n,e.statsDays)},Fa=async e=>{const t={timestamp:Date.now(),provider:e.provider,model:e.model},n=await Ye();n.selections.push(t),await xo(n,e.statsDays)},Ga=(e,t,n)=>{const o=t.filter(u=>u.provider===e),s=n.filter(u=>u.provider===e);if(o.length===0)return{provider:e,totalRequests:0,successCount:0,failureCount:0,selectedCount:s.length,selectionRate:0,avgResponseTimeMs:0,minResponseTimeMs:0,maxResponseTimeMs:0};const r=o.filter(u=>u.success),a=o.map(u=>u.responseTimeMs),c=s.length,l=r.length>0?Math.min(100,Math.round(c/r.length*1e3)/10):0;return{provider:e,totalRequests:o.length,successCount:r.length,failureCount:o.length-r.length,selectedCount:c,selectionRate:l,avgResponseTimeMs:Math.round(a.reduce((u,d)=>u+d,0)/a.length),minResponseTimeMs:Math.min(...a),maxResponseTimeMs:Math.max(...a)}},Ba=async(e=Na)=>{const t=await Ye(),n=Date.now()-e*24*60*60*1e3,o=t.metrics.filter(u=>u.timestamp>=n),s=t.selections.filter(u=>u.timestamp>=n);if(o.length===0)return{totalRequests:0,successRate:0,avgResponseTimeMs:0,providerStats:[],periodStart:n,periodEnd:Date.now()};const a=[...new Set(o.map(u=>u.provider))].map(u=>Ga(u,o,s)).sort((u,d)=>d.totalRequests-u.totalRequests),c=o.filter(u=>u.success).length,l=o.reduce((u,d)=>u+d.responseTimeMs,0);return{totalRequests:o.length,successRate:Math.round(c/o.length*1e3)/10,avgResponseTimeMs:Math.round(l/o.length),providerStats:a,periodStart:Math.min(...o.map(u=>u.timestamp)),periodEnd:Math.max(...o.map(u=>u.timestamp))}},Ha=async()=>{const e=Bt();await Be(e)&&await I.unlink(e)},Ua=async()=>(await Ye()).metrics.length>0,So=(e,t)=>{const n=h.red.bold(`[${e}]`);return Es({name:`${n} ${t}`,value:t,isError:!0,disabled:!0})},$o=e=>{let t=!1;return vs({next:n=>{if(Object.assign(n,{provider:e.provider,model:e.model}),e.statsEnabled===!1||t)return;t=!0;const o=n.isError===!0,s={provider:e.provider,model:e.model,responseTimeMs:Date.now()-e.startTime,success:!o,errorCode:o?"REQUEST_ERROR":void 0,statsDays:e.statsDays};ja(s).catch(()=>{})}})};class Ka{constructor(){this.loaders=new Map,this.cache=new Map,this.loadService=async t=>{const n=this.cache.get(t);if(n)return n;const o=this.loaders.get(t);if(!o)return null;const s=await o();return this.cache.set(t,s),s},this.createService=async(t,n)=>{const o=await this.loadService(t);return o?new o(n):null},this.createRequest$=(t,n,o)=>{const s=Date.now(),r=Array.isArray(n.config.model)?n.config.model[0]:n.config.model;return ke(this.createService(t,n)).pipe(mn(a=>a?(o==="commit"?a.generateCommitMessage$():a.generateCodeReview$()).pipe($o({provider:t,model:r||"unknown",startTime:s,statsEnabled:n.statsEnabled,statsDays:n.statsDays})):So(t,"Invalid AI type")))},this.registerBuiltinProviders=()=>{this.loaders.set("OPENAI",()=>import("./openai.service-ca071f6c.mjs").then(t=>t.OpenAIService)),this.loaders.set("COPILOT_SDK",()=>import("./copilot-sdk.service-f1cc1873.mjs").then(t=>t.CopilotSdkService)),this.loaders.set("OPENROUTER",()=>import("./openrouter.service-2e239655.mjs").then(t=>t.OpenRouterService)),this.loaders.set("GEMINI",()=>import("./gemini.service-c9b02d26.mjs").then(t=>t.GeminiService)),this.loaders.set("ANTHROPIC",()=>import("./anthropic.service-fb44d54e.mjs").then(t=>t.AnthropicService)),this.loaders.set("HUGGINGFACE",()=>import("./hugging-face.service-2c8f4576.mjs").then(t=>t.HuggingFaceService)),this.loaders.set("MISTRAL",()=>import("./mistral.service-7a553113.mjs").then(t=>t.MistralService)),this.loaders.set("CODESTRAL",()=>import("./codestral.service-f6ae65a5.mjs").then(t=>t.CodestralService)),this.loaders.set("OLLAMA",()=>import("./ollama.service-31b2908b.mjs").then(t=>t.OllamaService)),this.loaders.set("COHERE",()=>import("./cohere.service-af885cf7.mjs").then(t=>t.CohereService)),this.loaders.set("GROQ",()=>import("./groq.service-180e7478.mjs").then(t=>t.GroqService)),this.loaders.set("PERPLEXITY",()=>import("./perplexity.service-fe8bfcd5.mjs").then(t=>t.PerplexityService)),this.loaders.set("BEDROCK",()=>import("./bedrock.service-40cbd1e5.mjs").then(t=>t.BedrockService)),this.loaders.set("GITHUB_MODELS",()=>import("./github-models.service-becd2e94.mjs").then(t=>t.GitHubModelsService)),this.loaders.set("DEEPSEEK",()=>import("./deep-seek.service-de8b4395.mjs").then(t=>t.DeepSeekService))},this.registerBuiltinProviders()}}const Wa=new Ka;class Ht{getDetectedMessage(t){return`Detected ${t.files.length.toLocaleString()} changed file${t.files.length>1?"s":""} (${t.diff.length.toLocaleString()} characters)`}getDetectedFiles(t){return`Detected ${t.length.toLocaleString()} changed file${t.length>1?"s":""}`}}class Ve extends Ht{constructor(){super(...arguments),this.name="git",this.excludeFromDiff=t=>`:(exclude)${t}`,this.filesToExclude=["package-lock.json","pnpm-lock.yaml","*.lock","*.lockb"].map(this.excludeFromDiff)}async assertRepo(){try{const{stdout:t}=await E("git",["rev-parse","--show-toplevel"],{reject:!0});return t.trim()}catch(t){const n=t;if(n.code==="ENOENT")throw new p(`Git command not found!
|
|
22
|
+
|
|
23
|
+
Please install Git first: https://git-scm.com/downloads`);if(n.stderr){if(n.stderr.includes("not a git repository"))throw new p(`Not in a Git repository!
|
|
24
|
+
|
|
25
|
+
Initialize with: git init
|
|
26
|
+
Or navigate to an existing Git repository.`);if(n.stderr.includes("permission denied"))throw new p(`Git permission denied: ${n.stderr.trim()}
|
|
27
|
+
|
|
28
|
+
Check file permissions and repository access.`)}throw new p(`Failed to verify Git repository: ${n.message||"Unknown error"}`)}}async getStagedDiff(t,n,o){const r=["diff","--cached","--diff-algorithm=minimal",o?.diffContext!==void 0?`-U${o.diffContext}`:`-U${ue}`],a=[...t?t.map(this.excludeFromDiff):[],...n?n.map(this.excludeFromDiff):[]],c=[...this.filesToExclude,...a],[l,u,d]=await Promise.all([E("git",[...r,"--name-only",...c]),E("git",[...r,...c]),E("git",[...r,"--numstat",...a])]),m=l.stdout;if(!m)return null;const g=u.stdout,y=m.split(`
|
|
29
|
+
`).filter(Boolean),f=d.stdout,A=[],R=f.split(`
|
|
30
|
+
`).filter(Boolean);for(const b of R){const C=b.split(" ");C[0]==="-"&&C[1]==="-"&&C[2]&&A.push(C[2])}let x=g;if(A.length>0){g.trim()||(x=""),x+=`
|
|
31
|
+
|
|
32
|
+
--- Binary Files Changed ---
|
|
33
|
+
`;for(const b of A){const{stdout:C}=await E("git",["status","--porcelain",b]),k=C.substring(0,2).trim();x+=`Binary file ${b} ${k==="A"?"added":k==="M"?"modified":k==="D"?"deleted":"changed"}
|
|
34
|
+
`}}const S=[...new Set([...y,...A])];return{files:S,diff:x||`Files changed: ${S.join(", ")}`}}async getCommitDiff(t,n,o,s){const r=s?.diffContext!==void 0?`-U${s.diffContext}`:`-U${ue}`,a=[...n?n.map(this.excludeFromDiff):[],...o?o.map(this.excludeFromDiff):[]],c=[...this.filesToExclude,...a],[l,u,d]=await Promise.all([E("git",["diff-tree","-r","--no-commit-id","--name-only",t,...c]),E("git",["show",r,t,"--",...c]),E("git",["diff-tree","-r","--numstat",t,...a])]),m=l.stdout;if(!m)return null;const g=u.stdout,y=d.stdout,f=[],A=y.split(`
|
|
35
|
+
`).filter(Boolean);for(const S of A){const b=S.split(" ");b[0]==="-"&&b[1]==="-"&&b[2]&&f.push(b[2])}let R=g;if(f.length>0){g.trim()||(R=""),R+=`
|
|
36
|
+
|
|
37
|
+
--- Binary Files Changed ---
|
|
38
|
+
`;for(const S of f)R+=`Binary file ${S} changed
|
|
39
|
+
`}const x=[...new Set([...m.split(`
|
|
40
|
+
`).filter(Boolean),...f])];return{files:x,diff:R||`Files changed: ${x.join(", ")}`}}async commit(t,n=[],o={}){try{await E("git",["commit","-m",t,...n],{stdio:"inherit"})}catch(s){const r=s;throw r.stderr?r.stderr.includes("nothing to commit")?new p(`Nothing to commit.
|
|
41
|
+
|
|
42
|
+
Stage your changes with: git add <files>
|
|
43
|
+
Or use the --all flag to stage all changes.`):r.stderr.includes("Please enter the commit message")?new p(`Commit message cannot be empty.
|
|
44
|
+
|
|
45
|
+
Provide a meaningful commit message.`):r.stderr.includes("Author identity unknown")?new p(`Git author identity not configured.
|
|
46
|
+
|
|
47
|
+
Configure with:
|
|
48
|
+
git config --global user.name "Your Name"
|
|
49
|
+
git config --global user.email "your.email@example.com"`):r.stderr.includes("Permission denied")?new p(`Git permission error: ${r.stderr.trim()}
|
|
50
|
+
|
|
51
|
+
Check repository permissions and file access.`):new p(`Git commit failed: ${r.stderr.trim()}`):r.exitCode===1?new p("Git commit failed. Check your staged changes and try again."):new p(`Failed to commit with Git: ${r.message||"Unknown error"}`)}}async getCommentChar(){try{const{stdout:t}=await E("git",["config","--get","core.commentChar"]);return t}catch{return"#"}}async getBranchName(){try{const{stdout:t}=await E("git",["branch","--show-current"]),n=t.trim();if(!n){const{stdout:o}=await E("git",["rev-parse","--short","HEAD"]);return`HEAD@${o.trim()}`}return n}catch{return"HEAD"}}}class Ut extends Ht{constructor(){super(...arguments),this.name="jujutsu",this.excludeFromDiff=t=>t.includes("*")||t.includes("?")||t.includes("[")?`~glob:"${t}"`:`~"${t}"`,this.filesToExclude=["package-lock.json","pnpm-lock.yaml","*.lock","*.lockb"]}async assertRepo(){try{const{stdout:t}=await E("jj",["--version"],{reject:!0});process.env.DEBUG&&console.log(`Jujutsu version: ${t}`)}catch(t){const n=t;throw n.code==="ENOENT"?new p(`Jujutsu (jj) command not found!
|
|
52
|
+
|
|
53
|
+
Please install Jujutsu:
|
|
54
|
+
- macOS: brew install jj
|
|
55
|
+
- Linux: cargo install jj-cli
|
|
56
|
+
- Windows: cargo install jj-cli
|
|
57
|
+
- See: https://github.com/jj-vcs/jj#installation`):new p(`Failed to execute jj command: ${n.message}`)}try{const{stdout:t,stderr:n}=await E("jj",["workspace","root"],{reject:!0}),o=t.trim();if(!o)throw new p("jj workspace root returned empty path");const s=P.join(o,".jj");if(!_.existsSync(s))throw new p(`Jujutsu repository directory not found at ${s}
|
|
58
|
+
|
|
59
|
+
Initialize a jj repository with: jj init`);return o}catch(t){if(t instanceof p)throw t;const n=t;throw n.stderr?n.stderr.includes("not in a jj repo")?new p(`Not in a Jujutsu repository!
|
|
60
|
+
|
|
61
|
+
Initialize with: jj init
|
|
62
|
+
Or navigate to an existing jj repository.`):n.stderr.includes("No workspace found")?new p(`No Jujutsu workspace found!
|
|
63
|
+
|
|
64
|
+
This may be a bare repository. Navigate to a workspace directory.`):new p(`Jujutsu error: ${n.stderr.trim()}`):new p(`Failed to verify Jujutsu repository: ${n.message||"Unknown error"}`)}}async getStagedDiff(t,n,o){try{const{stdout:s}=await E("jj",["status","--no-pager"]);if(process.env.DEBUG&&(console.log("jj status output:",JSON.stringify(s)),console.log("excludeFiles:",t),console.log("exclude:",n)),s.includes("No changes.")||s.includes("The working copy is clean"))return null;const r=this.filesToExclude.map(this.excludeFromDiff),a=[...t?t.map(this.excludeFromDiff):[],...n?n.map(this.excludeFromDiff):[]],c=[...r,...a];let l="all()";c.length>0&&(l=`all() & ${c.join(" & ")}`);const u=["diff","--name-only"],d=["diff","--git"];c.length>0&&(u.push(l),d.push(l)),process.env.DEBUG&&(console.log("jj diff command with fileset:",u),console.log("fileset expression:",l));const{stdout:m}=await E("jj",u);if(process.env.DEBUG&&console.log("jj diff --name-only output:",JSON.stringify(m)),!m.trim())return null;const{stdout:g}=await E("jj",d),{stdout:y}=await E("jj",["status","--no-pager"]),f=m.split(`
|
|
65
|
+
`).filter(Boolean),A=[],R=y.split(`
|
|
66
|
+
`);for(const b of R)if(b.includes("(binary)")||b.includes("Binary file")){const C=b.match(/([^\s]+)\s*\(binary\)/);C&&C[1]&&A.push(C[1])}let x=g;if(A.length>0){x+=`
|
|
67
|
+
|
|
68
|
+
--- Binary Files Changed ---
|
|
69
|
+
`;for(const b of A)x+=`Binary file ${b} changed
|
|
70
|
+
`}const S=[...new Set([...f,...A])];return{files:S,diff:x||`Files changed: ${S.join(", ")}`}}catch(s){const r=s;if(r.stderr){if(r.stderr.includes("No changes to show"))return null;if(r.stderr.includes("Operation not allowed"))throw new p(`Jujutsu diff failed: ${r.stderr.trim()}
|
|
71
|
+
|
|
72
|
+
Try: jj status --no-pager`);if(r.stderr.includes("Invalid revision"))throw new p(`Jujutsu revision error: ${r.stderr.trim()}
|
|
73
|
+
|
|
74
|
+
Check if you're in a valid workspace.`)}if(r.exitCode===1&&!r.stderr)return null;if(process.env.DEBUG)throw new p(`Jujutsu diff failed: ${r.message}
|
|
75
|
+
stderr: ${r.stderr}
|
|
76
|
+
exitCode: ${r.exitCode}`);return null}}async getCommitDiff(t,n,o,s){const r=[...n?n.map(this.excludeFromDiff):[],...o?o.map(this.excludeFromDiff):[]];try{const a=["diff","--name-only","--revision",t],c=["diff","--git","--revision",t];if(r.length>0){const m=`all() & ${r.join(" & ")}`;a.push(m),c.push(m),process.env.DEBUG&&console.log("jj getCommitDiff fileset expression:",m)}const{stdout:l}=await E("jj",a);if(!l.trim())return null;const{stdout:u}=await E("jj",c),d=l.split(`
|
|
77
|
+
`).filter(Boolean);return{files:d,diff:u||`Files changed: ${d.join(", ")}`}}catch(a){if(process.env.DEBUG){const c=a;console.log("jj getCommitDiff error:",c.message,c.stderr)}return null}}async commit(t,n=[],o={}){try{await E("jj",["describe","-m",t,...n],{stdio:"inherit"}),o.autoNew&&await E("jj",["new"],{stdio:"inherit"})}catch(s){const r=s;throw r.stderr?r.stderr.includes("Empty commit message")?new p(`Commit message cannot be empty.
|
|
78
|
+
|
|
79
|
+
Provide a meaningful commit message.`):r.stderr.includes("No changes to commit")?new p(`No changes to commit.
|
|
80
|
+
|
|
81
|
+
Make some changes first, then try again.`):r.stderr.includes("Invalid revision")?new p(`Jujutsu commit error: ${r.stderr.trim()}
|
|
82
|
+
|
|
83
|
+
Ensure you're in a valid workspace with changes.`):r.stderr.includes("Operation not allowed")?new p(`Jujutsu operation not allowed: ${r.stderr.trim()}
|
|
84
|
+
|
|
85
|
+
Check repository state with: jj status`):new p(`Jujutsu describe failed: ${r.stderr.trim()}`):r.exitCode===1?new p("Jujutsu commit failed. Check your changes and repository state."):new p(`Failed to commit with Jujutsu: ${r.message||"Unknown error"}`)}}async getCommentChar(){try{const{stdout:t}=await E("jj",["config","get","ui.comment-char"]);return t.trim()||"#"}catch{return"#"}}async getBranchName(){try{const{stdout:t}=await E("jj",["bookmark","list","--revisions","@"]);if(t.trim()){const s=t.split(`
|
|
86
|
+
`)[0].split(":")[0].trim();if(s)return s}const{stdout:n}=await E("jj",["log","-r","@","--no-graph","-T","change_id.short()"]);return n.trim()||"HEAD"}catch{return"HEAD"}}}class Kt extends Ht{constructor(){super(...arguments),this.name="yadm",this.excludeFromDiff=t=>`:(exclude)${t}`,this.filesToExclude=["package-lock.json","pnpm-lock.yaml","*.lock","*.lockb"].map(this.excludeFromDiff)}async assertRepo(){try{const{stdout:t}=await E("yadm",["rev-parse","--show-toplevel"],{reject:!0}),n=t.trim(),o=process.env.HOME||process.env.USERPROFILE;if(!o)throw new p("HOME environment variable not set. Cannot determine YADM repository.");const s=await import("path"),r=s.resolve(n),a=s.resolve(o);if(r!==a)throw new p(`Not a YADM repository (work tree is not $HOME).
|
|
87
|
+
|
|
88
|
+
YADM work tree: ${r}
|
|
89
|
+
Expected: ${a}
|
|
90
|
+
|
|
91
|
+
This appears to be a regular Git repository.`);const{stdout:c}=await E("yadm",["rev-parse","--git-dir"],{reject:!0}),l=c.trim();if(!l.includes("yadm"))throw new p(`Not a YADM repository (git-dir does not contain "yadm").
|
|
92
|
+
|
|
93
|
+
Git directory: ${l}
|
|
94
|
+
|
|
95
|
+
This appears to be a regular Git repository.`);return n}catch(t){if(t instanceof p)throw t;const n=t;if(n.code==="ENOENT")throw new p(`YADM command not found!
|
|
96
|
+
|
|
97
|
+
Please install YADM first: https://yadm.io/`);if(n.stderr){if(n.stderr.includes("not a git repository"))throw new p(`Not in a YADM repository!
|
|
98
|
+
|
|
99
|
+
Initialize with: yadm init
|
|
100
|
+
Or clone your dotfiles: yadm clone <url>`);if(n.stderr.includes("permission denied"))throw new p(`YADM permission denied: ${n.stderr.trim()}
|
|
101
|
+
|
|
102
|
+
Check file permissions and repository access.`)}throw new p(`Failed to verify YADM repository: ${n.message||"Unknown error"}`)}}async getStagedDiff(t,n,o){const r=["diff","--cached","--diff-algorithm=minimal",o?.diffContext!==void 0?`-U${o.diffContext}`:`-U${ue}`],a=[...t?t.map(this.excludeFromDiff):[],...n?n.map(this.excludeFromDiff):[]],c=[...this.filesToExclude,...a],[l,u,d]=await Promise.all([E("yadm",[...r,"--name-only",...c]),E("yadm",[...r,...c]),E("yadm",[...r,"--numstat",...a])]),m=l.stdout;if(!m)return null;const g=u.stdout,y=m.split(`
|
|
103
|
+
`).filter(Boolean),f=d.stdout,A=[],R=f.split(`
|
|
104
|
+
`).filter(Boolean);for(const b of R){const C=b.split(" ");C[0]==="-"&&C[1]==="-"&&C[2]&&A.push(C[2])}let x=g;if(A.length>0){g.trim()||(x=""),x+=`
|
|
105
|
+
|
|
106
|
+
--- Binary Files Changed ---
|
|
107
|
+
`;for(const b of A){const{stdout:C}=await E("yadm",["status","--porcelain",b]),k=C.substring(0,2).trim();x+=`Binary file ${b} ${k==="A"?"added":k==="M"?"modified":k==="D"?"deleted":"changed"}
|
|
108
|
+
`}}const S=[...new Set([...y,...A])];return{files:S,diff:x||`Files changed: ${S.join(", ")}`}}async getCommitDiff(t,n,o,s){const r=s?.diffContext!==void 0?`-U${s.diffContext}`:`-U${ue}`,a=[...n?n.map(this.excludeFromDiff):[],...o?o.map(this.excludeFromDiff):[]],c=[...this.filesToExclude,...a],[l,u,d]=await Promise.all([E("yadm",["diff-tree","-r","--no-commit-id","--name-only",t,...c]),E("yadm",["show",r,t,"--",...c]),E("yadm",["diff-tree","-r","--numstat",t,...a])]),m=l.stdout;if(!m)return null;const g=u.stdout,y=d.stdout,f=[],A=y.split(`
|
|
109
|
+
`).filter(Boolean);for(const S of A){const b=S.split(" ");b[0]==="-"&&b[1]==="-"&&b[2]&&f.push(b[2])}let R=g;if(f.length>0){g.trim()||(R=""),R+=`
|
|
110
|
+
|
|
111
|
+
--- Binary Files Changed ---
|
|
112
|
+
`;for(const S of f)R+=`Binary file ${S} changed
|
|
113
|
+
`}const x=[...new Set([...m.split(`
|
|
114
|
+
`).filter(Boolean),...f])];return{files:x,diff:R||`Files changed: ${x.join(", ")}`}}async commit(t,n=[],o={}){try{await E("yadm",["commit","-m",t,...n],{stdio:"inherit"})}catch(s){const r=s;throw r.stderr?r.stderr.includes("nothing to commit")?new p(`Nothing to commit.
|
|
115
|
+
|
|
116
|
+
Stage your changes with: yadm add <file>
|
|
117
|
+
Or stage tracked file modifications: aicommit2 --all
|
|
118
|
+
|
|
119
|
+
Note: The --all flag only stages already-tracked files (YADM best practice).`):r.stderr.includes("Please enter the commit message")?new p(`Commit message cannot be empty.
|
|
120
|
+
|
|
121
|
+
Provide a meaningful commit message.`):r.stderr.includes("Author identity unknown")?new p(`YADM author identity not configured.
|
|
122
|
+
|
|
123
|
+
Configure with:
|
|
124
|
+
yadm config --global user.name "Your Name"
|
|
125
|
+
yadm config --global user.email "your.email@example.com"`):r.stderr.includes("Permission denied")?new p(`YADM permission error: ${r.stderr.trim()}
|
|
126
|
+
|
|
127
|
+
Check repository permissions and file access.`):new p(`YADM commit failed: ${r.stderr.trim()}`):r.exitCode===1?new p("YADM commit failed. Check your staged changes and try again."):new p(`Failed to commit with YADM: ${r.message||"Unknown error"}`)}}async getCommentChar(){try{const{stdout:t}=await E("yadm",["config","--get","core.commentChar"]);return t}catch{return"#"}}async getBranchName(){try{const{stdout:t}=await E("yadm",["branch","--show-current"]),n=t.trim();if(!n){const{stdout:o}=await E("yadm",["rev-parse","--short","HEAD"]);return`HEAD@${o.trim()}`}return n}catch{return"HEAD"}}}let Wt=null;const qa=async()=>{const e=process.argv.includes("--git"),t=process.argv.includes("--yadm"),n=process.argv.includes("--jj");if(e)try{const f=new Ve;return await f.assertRepo(),f}catch(f){throw new p(`--git flag is set, but Git is not available or not in a git repository.
|
|
128
|
+
${f instanceof Error?f.message:String(f)}`)}if(t)try{const f=new Kt;return await f.assertRepo(),f}catch(f){throw new p(`--yadm flag is set, but YADM is not available or not in a YADM repository.
|
|
129
|
+
${f instanceof Error?f.message:String(f)}`)}if(n)try{const f=new Ut;return await f.assertRepo(),f}catch(f){throw new p(`--jj flag is set, but Jujutsu is not available or not in a jj repository.
|
|
130
|
+
${f instanceof Error?f.message:String(f)}`)}const o=process.env.FORCE_GIT==="true",s=process.env.FORCE_YADM==="true",r=process.env.FORCE_JJ==="true";if(o)try{const f=new Ve;return await f.assertRepo(),f}catch(f){throw new p(`FORCE_GIT="true" environment variable is set, but Git is not available or not in a git repository.
|
|
131
|
+
${f instanceof Error?f.message:String(f)}`)}if(s)try{const f=new Kt;return await f.assertRepo(),f}catch(f){throw new p(`FORCE_YADM="true" environment variable is set, but YADM is not available or not in a YADM repository.
|
|
132
|
+
${f instanceof Error?f.message:String(f)}`)}if(r)try{const f=new Ut;return await f.assertRepo(),f}catch(f){throw new p(`FORCE_JJ="true" environment variable is set, but Jujutsu is not available or not in a jj repository.
|
|
133
|
+
${f instanceof Error?f.message:String(f)}`)}let a=!1;try{a=(await X({})).forceGit===!0}catch{a=!1}if(a)try{const f=new Ve;return await f.assertRepo(),f}catch(f){throw new p(`forceGit=true is set in config, but Git is not available or not in a git repository.
|
|
134
|
+
${f instanceof Error?f.message:String(f)}`)}const[c,l,u]=await Promise.allSettled([(async()=>{const f=new Ut;return await f.assertRepo(),f})(),(async()=>{const f=new Ve;return await f.assertRepo(),f})(),(async()=>{const f=new Kt;return await f.assertRepo(),f})()]);if(c.status==="fulfilled")return c.value;if(l.status==="fulfilled")return l.value;if(u.status==="fulfilled")return u.value;const d=f=>f.status==="fulfilled"?"unexpected success":String(f.reason?.message??f.reason).replace("KnownError: ","").trim(),m=d(c),g=d(l),y=d(u);throw new p(`No supported VCS repository found.
|
|
135
|
+
|
|
136
|
+
Jujutsu Error:
|
|
137
|
+
${m}
|
|
138
|
+
|
|
139
|
+
Git Error:
|
|
140
|
+
${g}
|
|
141
|
+
|
|
142
|
+
YADM Error:
|
|
143
|
+
${y}
|
|
144
|
+
|
|
145
|
+
Solutions:
|
|
146
|
+
\u2022 Initialize a Jujutsu repository: jj init
|
|
147
|
+
\u2022 Initialize a Git repository: git init
|
|
148
|
+
\u2022 Initialize a YADM repository: yadm init (or yadm clone <url>)
|
|
149
|
+
\u2022 Navigate to an existing Jujutsu, Git, or YADM repository
|
|
150
|
+
\u2022 Set FORCE_GIT="true" environment variable to force Git detection
|
|
151
|
+
\u2022 Set forceGit=true in config file to prefer Git detection`)},ne=async()=>(Wt||(Wt=await qa()),Wt);let $e=null;const Ro=async()=>{if($e!==null)return $e;try{$e=(await X({})).diffContext}catch{$e=ue}return $e},Io=(e,t)=>{const{diff:n,stats:o}=ra(e.diff,t);return n===e.diff?e:{...e,diff:n,compression:o}},qt=async()=>(await ne()).assertRepo(),zt=async(e,t)=>{const n=await ne(),o=await Ro(),s=await n.getStagedDiff(e,t,{diffContext:o});return s||null},za=async(e,t,n)=>{const o=await ne();if(!o.getCommitDiff)throw new p(`Commit diff not supported for ${o.name}`);const s=await Ro(),r=await o.getCommitDiff(e,t,n,{diffContext:s});return r||null},Ya=async()=>(await ne()).getCommentChar(),Va=e=>{const t=e.files.length.toLocaleString(),n=e.files.length>1?"s":"",o=e.diff.length.toLocaleString();return`Detected ${t} changed file${n} (${o} characters)`},Je=async()=>(await ne()).name,Ja=async(e,t,n)=>{await(await ne()).commit(e,t||[],n)},Xe=async()=>(await ne()).getBranchName();class Qe{constructor(t,n,o=""){this.config=t,this.stagedDiff=n,this.branchName=o,this.getDiffForModel=s=>{const r={mode:s.diffCompression||"none",maxHunkLines:s.maxHunkLines||0,maxDiffLines:s.maxDiffLines||0};return Io(this.stagedDiff,r)},this.extractProviderName=s=>{if(!s)return"compatible";try{return new URL(s).hostname}catch{return"compatible"}},this.createCommitMsgRequests$=s=>this.createServiceRequests$(s,"commit"),this.createCodeReviewRequests$=s=>this.createServiceRequests$(s,"review"),this.createServiceRequests$=(s,r)=>ke(s).pipe(fn(a=>this.createProviderRequests$(a,r)),Ps(a=>So("UNKNOWN",a.message||"Unknown error"))),this.createProviderRequests$=(s,r)=>{const a=this.config[s],c=Array.isArray(a.model)?a.model:[a.model];return ke(c).pipe(fn(l=>this.createModelRequest$(s,l,r)))},this.createModelRequest$=(s,r,a)=>{const c=this.config[s];if(c.compatible)return this.createCompatibleServiceRequest$(c,r,a);const l=this.getDiffForModel(c);return Wa.createRequest$(s,{config:{...c,model:r},stagedDiff:l,keyName:r,branchName:this.branchName,statsEnabled:this.config.useStats,statsDays:this.config.statsDays,modelNameDisplay:this.config.modelNameDisplay},a)},this.createCompatibleServiceRequest$=(s,r,a)=>{const c=Date.now(),l=this.extractProviderName(s.url),u=this.getDiffForModel(s);return ke(import("./openai-compatible.service-2bea7313.mjs")).pipe(mn(({OpenAICompatibleService:d})=>{const m=Oa.create(d,{config:{...s,url:s.url||"",path:s.path||"",model:r},stagedDiff:u,keyName:r,branchName:this.branchName,modelNameDisplay:this.config.modelNameDisplay});return(a==="commit"?m.generateCommitMessage$():m.generateCodeReview$()).pipe($o({provider:l,model:r,startTime:c,statsEnabled:this.config.useStats,statsDays:this.config.statsDays}))}))}}}const Xa=1e5;class U{constructor(){this.title="aicommit2",this.formatCompressionStats=t=>{if(!t||t.originalChars===t.compressedChars)return null;const n=Math.round((1-t.compressedChars/t.originalChars)*100);return`[compact: ${t.originalChars.toLocaleString()} \u2192 ${t.compressedChars.toLocaleString()} chars, ${n}% saved]`},this.formatBytes=t=>t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:`${(t/(1024*1024)).toFixed(1)} MB`}printTitle(){try{const t=yn.textSync(this.title,{font:"Small Slant"}),n=Ss(["#8B5CF6","#A020F0","#D946EF"]);console.log(h.bold(n.multiline(t)))}catch{console.log(h.bold(yn.textSync(this.title,{font:"Small Slant"})))}}showLoader(t){if(this.loader){this.loader.text=t;return}this.loader=wn(t).start()}stopLoader(){this.loader?.stop(),this.loader=void 0}displaySpinner(t){return wn(t).start()}stopSpinner(t){t.stop(),t.clear()}printStagedFiles(t,n){const o=Buffer.byteLength(t.diff,"utf8"),s=this.formatBytes(o),r=Va(t),a=this.formatCompressionStats(n);console.log(h.bold.green("\u2714 ")+h.bold(r)+h.dim(` (${s})`)+(a?h.cyan(` ${a}`):"")+h.bold(":")),console.log(`${t.files.map(l=>` ${l}`).join(`
|
|
152
|
+
`)}
|
|
153
|
+
`),o>Xa&&!n&&(console.log(h.yellow(`\u26A0 Large diff detected (${s}). This may increase processing time and costs.`)),console.log(h.dim(` Consider using --exclude to filter large files or diffCompression=compact.
|
|
154
|
+
`)))}printAnalyzed(){console.log(`
|
|
155
|
+
${h.bold.green("\u2714")} ${h.bold("Changes analyzed")}`)}printCommitted(){console.log(`
|
|
156
|
+
${h.bold.green("\u2714")} ${h.bold("Successfully committed!")}`)}printCopied(){console.log(`
|
|
157
|
+
${h.bold.green("\u2714")} ${h.bold("Successfully copied! Press 'Ctrl + V' to paste")}`)}printSavedCommitMessage(){console.log(`
|
|
158
|
+
${h.bold.green("\u2714")} ${h.bold("Saved commit message")}`)}printCancelledCommit(){console.log(`
|
|
159
|
+
${h.bold.yellow("\u26A0")} ${h.yellow("Commit cancelled")}`)}printError(t){console.log(`
|
|
160
|
+
${h.bold.red("\u2716")} ${h.red(`${t}`)}`)}printWarning(t){console.log(`
|
|
161
|
+
${h.bold.yellow("\u26A0")} ${h.yellow(`${t}`)}`)}printSuccess(t){console.log(`
|
|
162
|
+
${h.bold.green("\u2714")} ${h.green(`${t}`)}`)}printInfo(t){console.log(`
|
|
163
|
+
${h.bold.blue("\u2139")} ${h.blue(`${t}`)}`)}printSetupGitEvent(t){console.log(`
|
|
164
|
+
${h.bold.green("\u2714")} ${h.bold(`Git ${t} hook has been set up`)}`)}moveCursorUp(){const t=Le.createInterface({input:process.stdin,output:process.stdout});Le.moveCursor(process.stdout,0,-1),t.close()}moveCursorDown(){const t=Le.createInterface({input:process.stdin,output:process.stdout});Le.moveCursor(process.stdout,0,2),t.close()}print(t){console.log(t)}}let Ze,ko="info";async function Qa(e){if(Ze){console.warn("Logger already initialized. Skipping re-initialization.");return}const t=e?.logLevel||"info";ko=t;const n=e?.logFilePath||bo,o=e?.exceptionLogFilePath||Eo,s=e?.logging??!0;await ho(P.dirname(n)),await ho(P.dirname(o));const r=[];s?r.push(new B.transports.DailyRotateFile({filename:n,datePattern:"YYYY-MM-DD",zippedArchive:!0,maxSize:"20m",maxFiles:"14d",level:t,format:B.format.combine(B.format.timestamp(),B.format.printf(({level:a,message:c,timestamp:l})=>`[${l}] ${a}: ${c}`))})):r.push(new B.transports.Console({silent:!0})),Ze=B.createLogger({level:t,format:B.format.json(),transports:r,exceptionHandlers:s?[new B.transports.DailyRotateFile({filename:o,datePattern:"YYYY-MM-DD",zippedArchive:!0,maxSize:"20m",maxFiles:"14d",format:B.format.combine(B.format.timestamp(),B.format.json())})]:[],exitOnError:!1,silent:!s})}const pe=new Proxy({},{get:(e,t,n)=>{if(!Ze)throw new Error("Logger not initialized. Call initializeLogger() first.");return Reflect.get(Ze,t,n)}});function Lo(){const e=B.config.npm.levels;return(e[ko]??e.info)>=e.verbose}const Za={isLoading:!1,startOption:{text:"AI is analyzing your changes"}},Mo={isLoading:!1,startOption:{text:"AI is performing a code review"}},Yt="No commit messages were generated",To="No code reviews were generated",Vt={type:"reactiveListPrompt",name:"aicommit2Prompt",message:"Pick a commit message to use: ",emptyMessage:`\u26A0 ${Yt}`,loop:!1,descPageSize:15,showDescription:!0,pickKey:"short",isDescriptionDim:!0,stopMessage:"Changes analyzed"};class Jt{constructor(t){this.choices$=new pn([]),this.destroyed$=new As(1),this.stopMessage="Changes analyzed",this.isDestroyed=!1,this.subscriptions=new dt,this.inquirerInstance=null,this.loader$=new pn(t)}addSubscription(t){if(this.isDestroyed){t.unsubscribe();return}this.subscriptions.add(t)}initPrompt(t=Vt){return this.stopMessage=t.stopMessage,M.registerPrompt("reactiveListPrompt",$s),this.inquirerInstance=M.prompt({choices$:this.choices$,loader$:this.loader$,...t}),this.inquirerInstance}startLoader(){this.loader$.next({isLoading:!0})}updateLoaderText(t){this.isDestroyed||this.loader$.next({isLoading:!0,startOption:{text:t}})}clearLoader(){this.inquirerInstance&&this.loader$.next({isLoading:!1,clear:!0})}refreshChoices(t){if(this.isDestroyed||!t)return;const n=t.streamKey;if(n){if(!t.value){this.removeStreamingChoice(n);return}const o=[...this.currentChoices],s=o.findIndex(r=>r.streamKey===n);if(s>=0){o[s]=t,this.choices$.next(o);return}this.choices$.next([...this.currentChoices,t].sort(go));return}t.value&&this.choices$.next([...this.currentChoices,t].sort(go))}removeStreamingChoice(t){if(this.isDestroyed)return;const n=this.currentChoices.filter(o=>o.streamKey!==t);this.choices$.next(n)}checkErrorOnChoices(t=!0){if(this.choices$.getValue().map(s=>s).filter(s=>!s.streamKey).every(s=>s?.isError||s?.disabled)){this.alertNoGeneratedMessage(),this.logEmptyCommitMessage(),t&&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(t){console.warn("Error completing subjects:",t)}}closeInquirerInstance(){if(!this.inquirerInstance)return;const t=this.inquirerInstance.ui;t?.rl&&!t.rl.closed&&t.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(t){Lo()&&console.warn("Error during ReactivePromptManager destruction:",t)}finally{this.inquirerInstance=null}}}alertNoGeneratedMessage(){this.loader$.next({isLoading:!1,message:Yt,stopOption:{doneFrame:"\u26A0",color:"yellow"}})}stopLoaderOnSuccess(){this.loader$.next({isLoading:!1,message:this.stopMessage})}logEmptyCommitMessage(){console.log(`
|
|
165
|
+
${h.bold.yellow("\u26A0")} ${h.yellow(`${Yt}`)}`)}get currentChoices(){return this.choices$.getValue().map(t=>t)}}const w={label:h.bold.green,command:h.bold.white,hint:h.gray,highlight:h.bold.magenta,dim:h.dim},$={MISSING_API_KEY:"MISSING_API_KEY",INVALID_API_KEY:"INVALID_API_KEY",AUTH_FAILED:"AUTH_FAILED",RATE_LIMITED:"RATE_LIMITED",QUOTA_EXCEEDED:"QUOTA_EXCEEDED",MODEL_NOT_FOUND:"MODEL_NOT_FOUND",MODEL_ACCESS_DENIED:"MODEL_ACCESS_DENIED",NETWORK_ERROR:"NETWORK_ERROR",TIMEOUT:"TIMEOUT",SERVICE_UNAVAILABLE:"SERVICE_UNAVAILABLE",NO_STAGED_CHANGES:"NO_STAGED_CHANGES",EMPTY_COMMIT_MESSAGE:"EMPTY_COMMIT_MESSAGE",VCS_NOT_FOUND:"VCS_NOT_FOUND",INVALID_CONFIG:"INVALID_CONFIG",CONFIG_NOT_FOUND:"CONFIG_NOT_FOUND",SERVER_ERROR:"SERVER_ERROR",UNKNOWN:"UNKNOWN"},Xt={missingApiKey:e=>{const t=e.toUpperCase();return[`Missing API key for ${w.highlight(t)}.`,"",`${w.label("\u2192")} Run: ${w.command(`aicommit2 config set ${t}.key=YOUR_API_KEY`)}`].join(`
|
|
166
|
+
`)},invalidApiKey:e=>{const t=e.toUpperCase();return[`Invalid or expired API key for ${w.highlight(t)}.`,"",`${w.label("\u2192")} Update: ${w.command(`aicommit2 config set ${t}.key=YOUR_NEW_KEY`)}`].join(`
|
|
167
|
+
`)},noApiKeysConfigured:()=>["No AI provider API keys configured.","",`${w.label("\u2192")} Please set at least one API key:`,` ${w.command("aicommit2 config set OPENAI.key=sk-...")}`,` ${w.command("aicommit2 config set ANTHROPIC.key=sk-ant-...")}`,` ${w.command("aicommit2 config set OLLAMA.model=llama3.2")} ${w.dim("(no key needed)")}`,"",`${w.hint("Tip:")} ${w.command("aicommit2 config get")} ${w.hint("to see current config")}`].join(`
|
|
168
|
+
`),rateLimited:e=>[`Rate limit exceeded${e?` for ${w.highlight(e)}`:""}.`,"",`${w.label("\u2192")} Wait a moment and try again`,`${w.label("\u2192")} Or use a different AI provider`].join(`
|
|
169
|
+
`),quotaExceeded:e=>[`API quota exceeded${e?` for ${w.highlight(e)}`:""}.`,"",`${w.label("\u2192")} Upgrade your API plan or wait for reset`].join(`
|
|
170
|
+
`),modelNotFound:(e,t)=>{const n=t.toUpperCase();return[`Model ${w.highlight(`"${e}"`)} not found for ${w.highlight(n)}.`,"",`${w.label("\u2192")} Update: ${w.command(`aicommit2 config set ${n}.model=VALID_MODEL`)}`].join(`
|
|
171
|
+
`)},modelAccessDenied:(e,t)=>[`Access denied to model ${w.highlight(`"${e}"`)} on ${w.highlight(t)}.`,"",`${w.label("\u2192")} Check API access or upgrade your plan`].join(`
|
|
172
|
+
`),networkError:e=>[`Network connection failed${e?` to ${w.highlight(e)}`:""}.`,"",`${w.label("\u2192")} Check internet connectivity and try again`].join(`
|
|
173
|
+
`),timeout:(e,t)=>{const n=t?` from ${w.highlight(t)}`:"",o=Math.round(e*1.5);return[`Request timed out${n} after ${e}ms.`,"",`${w.label("\u2192")} Increase: ${w.command(`aicommit2 config set timeout=${o}`)}`].join(`
|
|
174
|
+
`)},serviceUnavailable:e=>[`${w.highlight(e)} service is temporarily unavailable.`,"",`${w.label("\u2192")} Try again in a few minutes`].join(`
|
|
175
|
+
`),noStagedChanges:e=>{const t=e.toLowerCase()==="jujutsu"?"jj":e.toLowerCase()==="yadm"?"yadm add":"git add";return[`No staged changes found in ${w.highlight(e)} repository.`,"",`${w.label("\u2192")} Stage: ${w.command(`${t} <files>`)}`,`${w.label("\u2192")} Or use: ${w.command("aicommit2 --all")}`].join(`
|
|
176
|
+
`)},emptyCommitMessage:()=>"Commit message cannot be empty.",vcsNotFound:e=>{const n={git:"https://git-scm.com/downloads",yadm:"https://yadm.io/docs/install",jujutsu:"https://github.com/jj-vcs/jj#installation"}[e.toLowerCase()]||"";return[`${w.highlight(e)} is not installed or not found in PATH.`,"",n?`${w.label("\u2192")} Install: ${w.command(n)}`:""].filter(Boolean).join(`
|
|
177
|
+
`)},notInRepository:e=>[`Not in a ${w.highlight(e)} repository.`,"",`${w.label("\u2192")} Init: ${w.command(`${e.toLowerCase()} init`)}`].join(`
|
|
178
|
+
`),invalidConfigFormat:e=>[`Invalid configuration format for ${w.highlight(`"${e}"`)}`,"",`${w.label("\u2192")} Use: ${w.command("aicommit2 config set PROVIDER.key=value")}`].join(`
|
|
179
|
+
`),invalidConfigValue:(e,t)=>[`Invalid value for ${w.highlight(`"${e}"`)}`,"",`${w.label("\u2192")} Expected: ${w.dim(t)}`].join(`
|
|
180
|
+
`),serverError:(e,t)=>{const n=t?` ${w.dim(`(HTTP ${t})`)}`:"";return`${w.highlight(e)} server error${n}. Try again later.`},ollamaNotRunning:()=>[`${w.highlight("Ollama")} is not running or not accessible.`,"",`${w.label("\u2192")} Start: ${w.command("ollama serve")}`].join(`
|
|
181
|
+
`),ollamaModelNotPulled:e=>[`Ollama model ${w.highlight(`"${e}"`)} is not available locally.`,"",`${w.label("\u2192")} Pull: ${w.command(`ollama pull ${e}`)}`].join(`
|
|
182
|
+
`)},ec=e=>({401:$.INVALID_API_KEY,403:$.MODEL_ACCESS_DENIED,404:$.MODEL_NOT_FOUND,429:$.RATE_LIMITED,500:$.SERVER_ERROR,502:$.SERVICE_UNAVAILABLE,503:$.SERVICE_UNAVAILABLE,504:$.TIMEOUT})[e]||$.UNKNOWN,tc=e=>{const t=e.toLowerCase();return t.includes("api key")||t.includes("api_key")||t.includes("apikey")?t.includes("missing")?$.MISSING_API_KEY:$.INVALID_API_KEY:t.includes("401")||t.includes("unauthorized")||t.includes("authentication")?$.AUTH_FAILED:t.includes("rate")||t.includes("429")||t.includes("too many")?$.RATE_LIMITED:t.includes("quota")||t.includes("usage")||t.includes("limit exceeded")?$.QUOTA_EXCEEDED:t.includes("model")&&(t.includes("not found")||t.includes("404"))?$.MODEL_NOT_FOUND:t.includes("403")||t.includes("forbidden")||t.includes("access denied")?$.MODEL_ACCESS_DENIED:t.includes("econnrefused")||t.includes("network")||t.includes("connection")?$.NETWORK_ERROR:t.includes("timeout")||t.includes("timed out")||t.includes("504")?$.TIMEOUT:t.includes("unavailable")||t.includes("overloaded")||t.includes("503")||t.includes("502")?$.SERVICE_UNAVAILABLE:t.includes("500")||t.includes("internal server error")?$.SERVER_ERROR:$.UNKNOWN},K={missingApiKey:e=>`Missing API key for ${e.toUpperCase()}`,invalidApiKey:e=>`Invalid API key for ${e.toUpperCase()}`,rateLimited:e=>`Rate limit exceeded${e?` for ${e}`:""}`,quotaExceeded:e=>`API quota exceeded${e?` for ${e}`:""}`,modelNotFound:(e,t)=>`Model "${e}" not found for ${t.toUpperCase()}`,modelAccessDenied:(e,t)=>`Access denied to model "${e}" on ${t}`,networkError:e=>`Network connection failed${e?` to ${e}`:""}`,timeout:(e,t)=>`Request timed out${t?` from ${t}`:""} after ${e}ms`,serviceUnavailable:e=>`${e} service is temporarily unavailable`,serverError:(e,t)=>`${e} server error${t?` (HTTP ${t})`:""}`,unknown:e=>`An error occurred with ${e}. Please try again.`,ollamaNotRunning:()=>"Ollama is not running. Start with: ollama serve",ollamaModelNotPulled:e=>`Ollama model "${e}" not found. Pull with: ollama pull ${e}`},nc=(e,t={})=>{const{provider:n="AI",model:o,timeout:s}=t;switch(e){case $.MISSING_API_KEY:return K.missingApiKey(n);case $.INVALID_API_KEY:case $.AUTH_FAILED:return K.invalidApiKey(n);case $.RATE_LIMITED:return K.rateLimited(n);case $.QUOTA_EXCEEDED:return K.quotaExceeded(n);case $.MODEL_NOT_FOUND:return K.modelNotFound(o||"unknown",n);case $.MODEL_ACCESS_DENIED:return K.modelAccessDenied(o||"unknown",n);case $.NETWORK_ERROR:return K.networkError(n);case $.TIMEOUT:return K.timeout(s||1e4,n);case $.SERVICE_UNAVAILABLE:return K.serviceUnavailable(n);case $.SERVER_ERROR:return K.serverError(n);default:return K.unknown(n)}},Oo={locale:"en",maxLength:50,type:"conventional",generate:1,systemPrompt:"",systemPromptPath:"",codeReviewPromptPath:"",vcs_branch:""},oc={"":"<commit message>",conventional:`<type>(<optional scope>): <description>
|
|
183
|
+
|
|
184
|
+
[optional body]
|
|
185
|
+
|
|
186
|
+
[optional footer(s)]`,gitmoji:`:<emoji>:(<optional scope>): <description>
|
|
187
|
+
|
|
188
|
+
[optional body]
|
|
189
|
+
|
|
190
|
+
[optional footer(s)]`},sc={"":"",gitmoji:`
|
|
191
|
+
${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(([e,t])=>` - ${e}: ${t}`).join(`
|
|
192
|
+
`)}`,conventional:`
|
|
193
|
+
${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(([e,t])=>` - ${e}: ${t}`).join(`
|
|
194
|
+
`)}`},Qt=(e,t)=>e.replace(/{(\w+)}/g,(n,o)=>t[o]?.toString()||Oo[o]?.toString()),rc=(e,t)=>{const n=t.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:""}}},s=o[e]||o[""];return s[n]||s.en},Do=e=>{const{type:t,maxLength:n,generate:o,locale:s}=e;return[`Generate exactly ${o} ${t} commit message${o!==1?"s":""} from the provided git diff.`,"",`Language: ${s}`,`Subject: max ${n} chars, imperative mood, no period`,"Format:",`${oc[t]}`,`Allowed types:${sc[t]}`,"","Rules:","- Extract scope from file paths or logical grouping (e.g., auth, api, ui)","- Focus on WHY the change was made, not just WHAT changed","- Body: only for complex changes (motivation, behavior comparison, breaking changes)","- Footer: issue references or BREAKING CHANGE if applicable"].filter(Boolean).join(`
|
|
195
|
+
`)},et=(e,t,n)=>{const o=rc(e,n),r=e==="conventional"||e==="gitmoji"?`
|
|
196
|
+
[
|
|
197
|
+
{"subject": "${o.subject}", "body": "${o.body}", "footer": ""}
|
|
198
|
+
]`:"";return[`
|
|
199
|
+
Respond with a JSON array of exactly ${t} object${t!==1?"s":""}:`,`- "subject": ${e} style commit message`,'- "body": detailed explanation (empty string if not needed)','- "footer": BREAKING CHANGE or issue refs (empty string if not needed)',r?`
|
|
200
|
+
Example:${r}`:"",`
|
|
201
|
+
Return valid JSON only.`].filter(Boolean).join(`
|
|
202
|
+
`)},ic=e=>{const{systemPrompt:t,systemPromptPath:n,type:o,generate:s,locale:r}=e;if(t)return`${Qt(t,e)}
|
|
203
|
+
${et(o,s,r)}`;if(!n)return`${Do(e)}
|
|
204
|
+
${et(o,s,r)}`;try{const a=_.readFileSync(He(n),"utf-8");return`${Qt(a,e)}
|
|
205
|
+
${et(o,s,r)}`}catch{return`${Do(e)}
|
|
206
|
+
${et(o,s,r)}`}},ac=e=>{const{codeReviewPromptPath:t,locale:n}=e;if(t)try{const o=_.readFileSync(He(t),"utf-8");return`${Qt(o,e)}`}catch{}return cc(n)},cc=e=>["Review the git diff and provide structured feedback as JSON.","",`Language: ${e}`,"Severity: critical (must fix) | warning (should fix) | suggestion (nice to have) | praise (good practice)","Category: bug | security | performance | style | maintainability | other","","Rules:","- Reference specific code and file paths from the diff","- Include a concrete suggestion for every issue","- Prioritize: critical > warning > suggestion","","Respond with this JSON structure:",'{"summary": "1-2 sentence assessment", "items": [{"severity": "...", "category": "...", "file": "path (optional)", "line": "number (optional)", "title": "max 80 chars", "description": "why it matters", "suggestion": "how to fix (empty string if N/A)"}]}',"","Return valid JSON only. Empty items array if no issues found."].join(`
|
|
207
|
+
`),No=async e=>{if(e.systemPromptPath)try{_.readFileSync(He(e.systemPromptPath),"utf-8")}catch(t){throw new p(`Error reading system prompt file: ${e.systemPromptPath}, ${t}`)}if(e.codeReview&&e.codeReviewPromptPath)try{_.readFileSync(He(e.codeReviewPromptPath),"utf-8")}catch(t){throw new p(`Error reading code review prompt file: ${e.codeReviewPromptPath}, ${t}`)}},lc=(e,t="commit")=>`\`\`\`diff
|
|
208
|
+
${e}
|
|
209
|
+
\`\`\``,N=new U;var uc=async(e,t,n,o,s,r,a,c,l,u,d,m,g,y,f,A,R)=>(async()=>{const x=A==="json";x||N.printTitle();const S=x?null:N.displaySpinner("Detecting repository...");if(await qt(),o){S&&(S.text="Staging changes...");const Z=await Je();Z==="git"?await E("git",["add","."]):Z==="yadm"&&await E("yadm",["add","--update"])}S&&(S.text="Loading configuration...");const b={locale:e?.toString(),generate:t?.toString(),type:s?.toString(),systemPrompt:c?.toString(),...l===!0&&{includeBody:"true"},...m===!0&&{disableLowerCase:"true"}};g&&(b.logLevel="verbose");const C=await X(b,R);(l===!0||C.includeBody===!0)&&Aa(C),m&&xa(C),await No(C);const O={autoNew:f||C.jjAutoNew};S&&(S.text="Detecting staged files...");const V=await zt(n,C.exclude);if(S?.stop(),!V){const Z=await Je();throw new p(Xt.noStagedChanges(Z),{code:$.NO_STAGED_CHANGES})}if(!x){const Z=Io(V,{mode:C.diffCompression,maxHunkLines:C.maxHunkLines,maxDiffLines:C.maxDiffLines});N.printStagedFiles(V,Z.compression)}const W=fe(C,"commit");if(W.length===0)throw new p(Xt.noApiKeysConfigured(),{code:$.MISSING_API_KEY});const ts=await Xe(),at=new Qe(C,V,ts);x&&((await pc(at,W)).forEach(os=>{process.stdout.write(JSON.stringify(os)+`
|
|
210
|
+
`)}),process.exit(0));const an=fe(C,"review");an.length>0&&await dc(at,an);const ct=await mc(at,W,u);C.useStats!==!1&&Fa({provider:ct.provider,model:ct.model,statsDays:C.statsDays}).catch(()=>{});let Q=ct.value;if(d){if(N.printInfo("Opening editor to modify commit message..."),Q=await fc(Q),!Q.trim())throw new p(Xt.emptyCommitMessage(),{code:$.EMPTY_COMMIT_MESSAGE});N.printSuccess("Commit message edited successfully!"),N.print(`
|
|
211
|
+
${Q}
|
|
212
|
+
`)}(a||C.autoCopy)&&(pt("copy-paste").copy(Q),a&&N.printCopied()),a&&!y&&process.exit(),y&&(process.stdout.write(Q+`
|
|
213
|
+
`),process.exit()),(r||u&&W.length===1)&&(await _o(Q,R,O),process.exit());const{confirmationPrompt:ns}=await M.prompt([{type:"confirm",name:"confirmationPrompt",message:"Use selected message?",default:!0}]);ns?await _o(Q,R,O):N.printCancelledCommit(),process.exit()})().catch(x=>{if(A==="json"){const S={error:x.message||"Unknown error occurred"};process.stderr.write(JSON.stringify(S)+`
|
|
214
|
+
`),process.exit(1)}N.printError(x.message),q(x),process.exit(1)});async function dc(e,t){const n=new Jt(Mo);let o=null;try{const s=n.initPrompt({...Vt,name:"codeReviewPrompt",message:"Please check code reviews: ",emptyMessage:`\u26A0 ${To}`,isDescriptionDim:!1,stopMessage:"Code review completed",descPageSize:20});n.startLoader(),o=e.createCodeReviewRequests$(t).subscribe({next:d=>n.refreshChoices(d),error:d=>{console.error("Code review request error:",d),n.checkErrorOnChoices()},complete:()=>n.checkErrorOnChoices()});const a=(await s).codeReviewPrompt?.value;if(!a)throw new p("An error occurred! No selected code review");N.moveCursorUp();const c=a.includes("<!-- HAS_CRITICAL_ISSUES -->"),l=c?"Critical issues found in code review. Continue without fixing?":"Will you continue without changing the code?",{continuePrompt:u}=await M.prompt([{type:"confirm",name:"continuePrompt",message:l,default:!c}]);u||(N.printCancelledCommit(),process.exit())}finally{o&&o.unsubscribe(),n.destroy()}}const mc=async(e,t,n)=>{const o=new Jt(Za);let s=null;try{if(n&&t.length===1){const m=[];o.startLoader(),s=e.createCommitMsgRequests$(t).subscribe({next:y=>{"streamKey"in y||m.push(y),o.refreshChoices(y)},error:y=>{console.error("Commit message generation error:",y),o.checkErrorOnChoices(!1)},complete:()=>o.checkErrorOnChoices(!1)}),await new Promise(y=>{s?.add(()=>y())}),o.clearLoader(),N.moveCursorUp();const g=m.find(y=>y.value&&!y.isError&&!y.disabled);if(!g||!g.value)throw new p("No valid commit message was generated");return N.print(`
|
|
215
|
+
${g.name}
|
|
216
|
+
`),{value:g.value,provider:g.provider||"unknown",model:g.model||"unknown"}}const r=new Map,a=o.initPrompt();o.startLoader();let c=0;s=e.createCommitMsgRequests$(t).subscribe({next:m=>{const g=m;g.value&&r.set(g.value,g),m.value&&!m.isError&&!m.disabled&&(c++,o.updateLoaderText(`AI is analyzing your changes (${c} message${c>1?"s":""} generated)`)),o.refreshChoices(m)},error:m=>{console.error("Commit message generation error:",m),o.checkErrorOnChoices()},complete:()=>o.checkErrorOnChoices()});const l=await a;N.moveCursorUp();const u=l.aicommit2Prompt?.value;if(!u)throw new p("An error occurred! No selected message");const d=r.get(u);return{value:u,provider:d?.provider||"unknown",model:d?.model||"unknown"}}finally{s&&s.unsubscribe(),o.destroy()}};async function fc(e){const t=process.env.VISUAL||process.env.EDITOR||(process.platform==="win32"?"notepad":"vi"),n=P.join(Ie.tmpdir(),`aicommit2-${Date.now()}-${is.randomBytes(4).toString("hex")}.txt`);try{_.writeFileSync(n,e,"utf8");const o=t.split(" "),[s,...r]=o;await E(s,[...r,n],{stdio:"inherit"});const a=_.readFileSync(n,"utf8").trim();if(_.unlinkSync(n),!a)throw new p("Commit cancelled - empty message");return a}catch(o){throw _.existsSync(n)&&_.unlinkSync(n),o instanceof p?o:o&&typeof o=="object"&&"exitCode"in o&&o.exitCode!==0?new p("Commit cancelled"):process.env.VISUAL||process.env.EDITOR?new p(`Failed to open editor "${t}". Please check:
|
|
217
|
+
- Editor binary exists in PATH
|
|
218
|
+
- Editor flags are correct
|
|
219
|
+
- EDITOR/VISUAL is set correctly`):new p(`Failed to open editor "${t}". Please set your EDITOR or VISUAL environment variable to a valid editor command.`)}}const _o=async(e,t,n)=>{await Ja(e,t,n),N.printCommitted()},pc=async(e,t)=>{const o=(await mt(e.createCommitMsgRequests$(t).pipe(ft()),{defaultValue:[]})).filter(s=>s.value&&!s.isError&&!s.disabled);if(o.length===0)throw new p("No valid commit messages were generated");return o.map(({value:s=""})=>{const[r="",...a]=s.split(`
|
|
220
|
+
`);return{subject:r,body:a.join(`
|
|
221
|
+
`).trim()}})};var hc=j({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:[j({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"]}}),j({name:"get",parameters:["[<key>","[<key> ...]]"],help:{description:"Retrieve configuration values for specified AI provider.",examples:["aic2 config get OPENAI","aic2 config get ANTHROPIC"]}}),j({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"']}}),j({name:"list",parameters:[],help:{description:"Display all configuration keys and their values.",examples:["aic2 config list"]}}),j({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"]}}),j({name:"path",parameters:[],help:{description:"Display the path of the loaded configuration file.",examples:["aic2 config path"]}})]},e=>{(async()=>{const{mode:t,keyValue:n}=e._,o=e._[1];if(t==="get"){const s=await X({},[]);if(n.length===0){console.log(s);return}for(const r of n){const a=r.split(".");let c=s,l=!0;for(const u of a)if(jt(c,u))c=c[u];else{l=!1;break}l?console.log(r,c):console.log(`${r} not found`)}return}if(t==="set"){await Ke(n.map(s=>{const r=s.indexOf("=");if(r===-1)throw new p("Invalid format. Use: key=value");const a=s.slice(0,r),c=s.slice(r+1);return[a,c]}));return}if(t==="add"){await Ia(n.map(s=>{const r=s.indexOf("=");if(r===-1)throw new p("Invalid format. Use: key=value");const a=s.slice(0,r),c=s.slice(r+1);return[a,c]}));return}if(t==="list"){await ka();return}if(t==="del"){if(!o)throw new p("Please provide the config name to delete.");const s=await Se(),r=o.split(".");if(r.length===2){const[a,c]=r;if(s[a]&&typeof s[a]=="object"&&jt(s[a],c)){delete s[a][c],Object.keys(s[a]).length===0&&delete s[a];const l=await me();await I.writeFile(l,le.stringify(s),"utf8"),console.log(`Successfully deleted config: ${o}`);const u=await I.readFile(l,"utf8");console.log("--- Updated Config Content ---"),console.log(u),console.log("----------------------------")}else throw new p(`Config not found: ${o}`)}else if(r.length===1){const a=r[0];if(jt(s,a)){delete s[a];const c=await me();await I.writeFile(c,le.stringify(s),"utf8"),console.log(`Successfully deleted config: ${o}`);const l=await I.readFile(c,"utf8");console.log("--- Updated Config Content ---"),console.log(l),console.log("----------------------------")}else throw new p(`Config not found: ${o}`)}else throw new p(`Invalid config name format: ${o}`);return}if(t==="path"){await La();return}throw new p(`Invalid mode: ${t}`)})().catch(t=>{new U().printError(t.message),q(t),process.exit(1)})});const tt="https://models.github.ai",Zt="/inference/chat/completions",en="2026-03-10",tn="openai/gpt-4o-mini",gc=/^([A-Za-z0-9][A-Za-z0-9._-]*)\/([A-Za-z0-9][A-Za-z0-9._:-]*)$/,jo=e=>(e||"").trim(),Fo=e=>{const t=jo(e);return t.length>0&&gc.test(t)},yc=e=>{const t=jo(e);if(!Fo(t))throw new Error(`Invalid GitHub Models model ID "${t||"(empty)"}". Expected format: "publisher/model" (example: "openai/gpt-4o-mini").`);return t},wc=e=>{const t=(e||"").trim();return t?["ghp_","gho_","ghu_","ghs_","ghr_","github_pat_"].some(o=>t.startsWith(o)):!1};class nt{constructor(t={}){if(!t.method)throw new Error("method should be defined!");if(!t.baseURL)throw new Error("baseURL should be defined!");this.config={...t},this.axiosInstance=Rs.create(this.config)}setHeaders(t){return this.config.headers=t,this}setParams(t){return this.config.params=t,this}setBody(t){return this.config.data=t,this}addBody(t){return this.config.data={...this.config.data,...t},this}setMethod(t){return this.config.method=t,this}async execute(){try{return await this.axiosInstance.request(this.config)}catch(t){throw t}}}const Cc={healthy:h.green("\u2705"),error:h.red("\u274C"),warning:h.yellow("\u26A0\uFE0F"),skipped:h.gray("\u23ED\uFE0F")},bc={healthy:h.green,error:h.red,warning:h.yellow,skipped:h.gray},nn=e=>typeof e.key=="string"&&e.key.trim().length>0,Go=e=>(Array.isArray(e.model)?e.model:typeof e.model=="string"&&e.model.trim().length>0?[e.model.trim()]:[]).length>0,Ec=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)&&Object.keys(e).length>0,vc=e=>typeof e=="string"&&e.trim()?e.replace(/\/$/,""):"https://openrouter.ai",Pc=e=>`${vc(e.url)}/api/v1`,Ac=e=>({Authorization:`Bearer ${e}`,"Content-Type":"application/json","HTTP-Referer":"https://github.com/tak-bro/aicommit2","X-OpenRouter-Title":"aicommit2","X-OpenRouter-Categories":"cli-agent"}),xc=(e,t)=>{const n=e.trim();return t.find(o=>[o.id,o.canonical_slug,o.name].filter(r=>!!r).some(r=>r===n))},Sc=(e,t)=>e.supported_parameters?.includes(t)??!1,$c=[{configKey:"OPENROUTER.responseFormat",configProperty:"responseFormat",parameters:["response_format"]},{configKey:"OPENROUTER.reasoning",configProperty:"reasoning",parameters:["reasoning","include_reasoning"]}],Rc=e=>{const t=e.supported_parameters||[];return t.length>0?`supports: ${t.join(", ")}`:"no supported parameters listed"},Ic=(e,t)=>{const n=[];for(const o of $c){if(!Ec(e[o.configProperty]))continue;o.parameters.some(r=>Sc(t,r))||n.push(o.configKey)}return n},kc=(e,t,n)=>{const o=n.context_length||n.top_provider?.context_length,s=Rc(n),r=Ic(t,n),a=o?`${o} ctx`:"";if(r.length>0){const u=[`consider removing ${r.join(", ")}`,a,s].filter(Boolean);return`${e}: ${u.join("; ")}`}const c=[a,s].filter(Boolean);return c.length>0?`${e} (${c.join("; ")})`:e},Bo=(e,t)=>{const n=[],o=Array.isArray(e.model)?e.model:typeof e.model=="string"?[e.model]:[];for(const s of o){if(s==="openrouter/auto"){n.push("Auto routing enabled");continue}const r=xc(s,t);if(!r){n.push(`Model not found in catalog: ${s}`);continue}n.push(kc(s,e,r))}return n},Lc=async(e,t)=>{try{return await new nt({method:"GET",baseURL:e,timeout:t}).execute(),{ok:!0}}catch(n){const o=n instanceof Error?n.message:String(n);return o.includes("ECONNREFUSED")?{ok:!1,error:"Not running"}:{ok:!1,error:o}}},Mc=async(e,t)=>{const n=typeof e.key=="string"?e.key.trim():"";if(!n)return{ok:!1,error:"No API key configured"};try{const o=Pc(e),s=Ac(n),r=["/models/user","/models"];let a,c;for(const y of r)try{a=await new nt({method:"GET",baseURL:`${o}${y}`,timeout:t}).setHeaders(s).execute();break}catch(f){if(c=f,!(f instanceof Error?f.message:String(f)).includes("404"))throw f}if(!a)throw c instanceof Error?c:new Error(String(c));const l=a.data?.data??[],u=Go(e)?Array.isArray(e.model)?e.model:[e.model]:[];if(u.length===0)return{ok:!0,details:`Catalog reachable (${l.length} models)`};if(u.includes("openrouter/auto")){const y=Bo(e,l);return{ok:!0,details:y.length>0?y.join("; "):`Auto routing enabled (${l.length} models)`}}const m=Bo(e,l);return m.some(y=>y.startsWith("Model not found in catalog:"))?{ok:!1,error:"Selected model not found in OpenRouter catalog",details:m.join("; ")}:{ok:!0,details:m.join("; ")}}catch(o){const s=o instanceof Error?o.message:String(o);return s.includes("401")||s.includes("403")?{ok:!1,error:"Unauthorized or forbidden when reading OpenRouter catalog"}:s.includes("404")?{ok:!1,error:"OpenRouter catalog endpoint not found"}:{ok:!1,error:s}}},Tc=e=>Array.isArray(e.model)&&e.model.length>0?String(e.model[0]).trim():typeof e.model=="string"&&e.model.trim().length>0?e.model.trim():tn,Oc=async(e,t)=>{const n=typeof e.key=="string"?e.key.trim():"";if(!n)return{ok:!1,error:"No API key configured"};const o=Tc(e);if(!Fo(o))return{ok:!1,error:"Invalid model ID format",details:`Expected "publisher/model", got "${o||"(empty)"}"`};try{const s=`${tt}${Zt}`;return await new nt({method:"POST",baseURL:s,timeout:t}).setHeaders({"Content-Type":"application/json",Accept:"application/vnd.github+json","X-GitHub-Api-Version":en,Authorization:`Bearer ${n}`}).setBody({model:o,messages:[{role:"user",content:"health-check"}],max_tokens:1,stream:!1}).execute(),{ok:!0,details:`Model: ${o}`}}catch(s){const r=s instanceof Error?s.message:String(s);return r.includes("401")?{ok:!1,error:"Authentication failed (401)"}:r.includes("403")?{ok:!1,error:"Access denied (403). Check token permission: models: read"}:r.includes("404")?{ok:!1,error:`Model not found (404): ${o}`}:r.includes("422")?{ok:!1,error:`Request validation failed (422) for model: ${o}`}:{ok:!1,error:r}}},Dc=e=>{const t=Array.isArray(e.model)?String(e.model[0]||"").trim():String(e.model||"").trim();if(!t)return{ok:!1,error:"No model configured"};try{if((process.env.COPILOT_GITHUB_TOKEN||"").trim().startsWith("ghp_"))return{ok:!1,error:"Unsupported classic PAT in COPILOT_GITHUB_TOKEN",details:"Copilot CLI requires Fine-Grained PAT (github_pat_...) or Copilot login flow"};const o=process.versions.node,s=Number(o.split(".")[0]||"0");if(Number.isFinite(s)&&s<22)return{ok:!1,error:`Node.js ${o} is too old for Copilot SDK`,details:"Copilot SDK v0.2.0 requires node:sqlite support (Node.js 22+ recommended)"};const r=ge("copilot --version",{stdio:["ignore","pipe","pipe"]}).toString().trim();return{ok:!0,details:r?`CLI: ${r}; Model: ${t}; Node: ${o}`:`Model: ${t}; Node: ${o}`}}catch{return{ok:!1,error:"Copilot CLI not found",details:"Install and authenticate Copilot CLI before using COPILOT_SDK provider"}}},Nc=async(e,t,n)=>{if(e==="OLLAMA"){if(!Y(t))return{provider:e,status:"skipped",message:"No models configured"};const o=typeof t.host=="string"&&t.host.trim()?t.host:ve,s=await Lc(o,n);return s.ok?{provider:e,status:"healthy",message:"Running",details:`Host: ${o}`}:{provider:e,status:"warning",message:s.error||"Connection failed",details:`Host: ${o}`}}if(e==="HUGGINGFACE")return t.cookie?{provider:e,status:"healthy",message:"Cookie configured"}:{provider:e,status:"skipped",message:"No cookie configured"};if(e==="BEDROCK")return qe(t)?{provider:e,status:"healthy",message:"Credentials configured"}:{provider:e,status:"skipped",message:"Not configured"};if(e==="OPENROUTER"){if(!nn(t))return{provider:e,status:"skipped",message:"Not configured"};const o=await Mc(t,n);return o.ok?{provider:e,status:"healthy",message:"Catalog reachable",details:o.details}:{provider:e,status:"warning",message:o.error||"Catalog check failed",details:o.details}}if(e==="GITHUB_MODELS"){if(!nn(t))return{provider:e,status:"skipped",message:"Not configured"};const o=await Oc(t,n);return o.ok?{provider:e,status:"healthy",message:"Models API reachable",details:o.details}:{provider:e,status:"warning",message:o.error||"Connection check failed",details:o.details}}if(e==="COPILOT_SDK"){if(!Go(t))return{provider:e,status:"skipped",message:"No models configured"};const o=Dc(t);return o.ok?{provider:e,status:"healthy",message:"SDK environment ready",details:o.details}:{provider:e,status:"warning",message:o.error||"Environment check failed",details:o.details}}return nn(t)?{provider:e,status:"healthy",message:"API key configured"}:{provider:e,status:"skipped",message:"Not configured"}},_c=async e=>{const t=[],n=e.timeout||1e4;for(const o of de){const s=e[o];if(!s||typeof s!="object"){t.push({provider:o,status:"skipped",message:"Not configured"});continue}if(s.disabled){t.push({provider:o,status:"skipped",message:"Disabled"});continue}const r=await Nc(o,s,n);t.push(r)}return t},jc=Math.max(...de.map(e=>e.length)),Fc=e=>e.padEnd(jc),Gc=e=>{console.log(""),console.log(h.bold("\u{1FA7A} aicommit2 Health Check")),console.log(""),console.log(h.bold("Providers:"));for(const n of e){const o=Cc[n.status],s=Fc(n.provider),r=bc[n.status](n.message),a=n.details?h.gray(` (${n.details})`):"";console.log(` ${o} ${s} ${r}${a}`)}const t={healthy:e.filter(n=>n.status==="healthy").length,error:e.filter(n=>n.status==="error").length,warning:e.filter(n=>n.status==="warning").length,skipped:e.filter(n=>n.status==="skipped").length};console.log(""),console.log(h.bold("Summary: ")+h.green(`${t.healthy} healthy`)+", "+h.red(`${t.error} error`)+", "+h.yellow(`${t.warning} warning`)+", "+h.gray(`${t.skipped} skipped`)),console.log(""),t.error>0&&(process.exitCode=1)},Bc=j({name:"doctor",parameters:[],help:{description:"Check health status of configured AI providers",examples:["aicommit2 doctor"]}},()=>{(async()=>{const e=await X({},[]),t=await _c(e);Gc(t)})().catch(e=>{console.error(h.red(e.message)),q(e),process.exit(1)})});var Hc=j({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 github_pat_xxxxxxxxxxxxxxxxxxxx"]}},e=>{(async()=>{const t=new U;if(e.flags.token){try{await Uc(e.flags.token,t)}catch(n){throw new p(`Token authentication failed: ${n.message}`)}return}try{await Kc(t)}catch(n){throw new p(`Browser authentication failed: ${n.message}`)}})().catch(t=>{new U().printError(t.message),q(t),process.exit(1)})});async function Uc(e,t){if(t.printWarning("Authenticating with provided token..."),!wc(e))throw new Error("Invalid token format. Expected GitHub token prefix like ghp_, gho_, ghu_, ghs_, ghr_, or github_pat_");try{const n=await fetch("https://api.github.com/user",{headers:{Authorization:`Bearer ${e}`,Accept:"application/vnd.github.v3+json","User-Agent":"aicommit2-github-models"}});if(!n.ok)throw new Error(`GitHub API request failed: ${n.status} ${n.statusText}`);const o=await n.json();try{(await fetch(`${tt}${Zt}`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/vnd.github+json","X-GitHub-Api-Version":en,Authorization:`Bearer ${e}`,"User-Agent":"aicommit2-github-models"},body:JSON.stringify({messages:[{role:"user",content:"test"}],model:tn,max_tokens:1})})).ok?t.printSuccess("GitHub Models access verified!"):t.printWarning("Could not verify GitHub Models access, but proceeding with authentication...")}catch{t.printWarning("Could not verify GitHub Models access, but proceeding with authentication...")}await Ke([["GITHUB_MODELS.key",e]]),t.printSuccess(`Successfully authenticated as ${o.login}`)}catch(n){throw new Error(`Token validation failed: ${n.message}`)}}async function Kc(e){e.printInfo("Starting GitHub browser authentication for GitHub Models...");try{try{ge("gh --version",{stdio:"ignore"})}catch{throw new Error("GitHub CLI (gh) is not installed. Please install it first: https://cli.github.com/")}try{ge("gh auth status",{encoding:"utf8",stdio:"pipe"}).includes("Logged in to github.com")&&e.printInfo("Already authenticated with GitHub CLI")}catch{e.printInfo("Authenticating with GitHub CLI..."),e.printInfo("Please follow the instructions in your browser to complete authentication.");try{ge("gh auth login --web -h github.com",{stdio:"inherit"})}catch{throw new Error("GitHub CLI authentication failed")}}e.printInfo("Verifying GitHub Models access...");try{const t=ge("gh auth token",{encoding:"utf8"}).trim();t&&(await Ke([["GITHUB_MODELS.key",t]]),e.printSuccess("GitHub token stored for GitHub Models access"))}catch{e.printWarning("Could not extract token from GitHub CLI, but authentication completed")}e.printSuccess("GitHub authentication completed and GitHub Models access verified!"),e.printInfo("See usage guide: https://github.com/tak-bro/aicommit2/blob/main/docs/providers/github-models.md"),e.printInfo("Use `gh models list` to view the latest available models."),e.printInfo(`Using GitHub Models API: ${tt}`)}catch(t){throw t}}const he="prepare-commit-msg",Wc=async()=>{const e=await Je();if(e==="git")return`.git/hooks/${he}`;if(e==="yadm"){const t=process.env.HOME||process.env.USERPROFILE;if(!t)throw new p("HOME environment variable not set. Cannot determine YADM hook path.");try{const{execa:s}=await Promise.resolve().then(function(){return na}),{stdout:r}=await s("yadm",["introspect","repo"]),a=r.trim();if(a)return P.join(a,"hooks",he)}catch{}const n=P.join(t,".config/yadm/hooks"),o=P.join(t,".yadm/hooks");try{return await I.access(n),P.join(n,he)}catch{return P.join(o,he)}}throw e==="jujutsu"?new p("Hooks are not supported for Jujutsu repositories."):new p(`Hooks are not supported for ${e} repositories.`)},ot=Is(new URL("cli.mjs",import.meta.url)),qc=process.argv[1].replace(/\\/g,"/").includes(`/hooks/${he}`),Ho=process.platform==="win32",Uo=`
|
|
222
|
+
#!/usr/bin/env node
|
|
223
|
+
import(${JSON.stringify(ks(ot))})
|
|
224
|
+
`.trim();var zc=j({name:"hook",parameters:["<install/uninstall>"],help:{description:"Install or uninstall the Git prepare-commit-msg hook",examples:["aic2 hook install","aic2 hook uninstall"]}},e=>{(async()=>{const t=await qt(),{installUninstall:n}=e._,o=await Wc(),s=P.isAbsolute(o)?o:P.join(t,o),r=await Be(s);if(n==="install"){if(r){if(await I.realpath(s).catch(()=>{})===ot){console.warn("The hook is already installed");return}throw new p(`A different ${he} hook seems to be installed. Please remove it before installing aicommit2.`)}await I.mkdir(P.dirname(s),{recursive:!0}),Ho?await I.writeFile(s,Uo):(await I.symlink(ot,s,"file"),await I.chmod(s,493)),console.log(`${h.green("\u2714")} Hook installed`);return}if(n==="uninstall"){if(!r){console.warn("Hook is not installed");return}if(Ho){if(await I.readFile(s,"utf8")!==Uo){console.warn("Hook is not installed");return}}else if(await I.realpath(s)!==ot){console.warn("Hook is not installed");return}await I.rm(s),console.log(`${h.green("\u2714")} Hook uninstalled`);return}throw new p(`Invalid mode: ${n}`)})().catch(t=>{console.error(`${h.red("\u2716")} ${t.message}`),q(t),process.exit(1)})});const Yc=bs(as),Vc=e=>{const t=["B","KB","MB","GB"];if(e===0)return"0 B";const n=Math.floor(Math.log(e)/Math.log(1024));return Math.round(e/Math.pow(1024,n)*100)/100+" "+t[n]},Jc=e=>e.toLocaleDateString()+" "+e.toLocaleTimeString(),Xc=async e=>{try{const t=await Cn(H);if(t.length===0){console.log(`${h.yellow("No log files found.")}`);return}console.log(`${h.blue("Log files in")} ${H}:
|
|
225
|
+
`);const n=await Promise.all(t.map(async o=>{const s=ee.join(H,o),r=await Ls(s);return{name:o,size:Vc(r.size),modified:Jc(r.mtime)}}));n.sort((o,s)=>new Date(s.modified).getTime()-new Date(o.modified).getTime()),n.forEach((o,s)=>{console.log(`${s===0?"\u{1F4C4}":" "} ${h.cyan(o.name)} ${h.gray(`(${o.size}, ${o.modified})`)}`)}),console.log(`
|
|
226
|
+
${h.green("Total:")} ${t.length} file${t.length!==1?"s":""}`)}catch(t){if(t.code==="ENOENT")console.log(`${h.yellow("Logs directory does not exist yet.")}`);else throw t}},Qc=async e=>{try{await Cn(H);const t=process.platform;let n;switch(t){case"darwin":n=`open "${H}"`;break;case"win32":n=`start "" "${H}"`;break;default:n=`xdg-open "${H}"`;break}await Yc(n),console.log(`${h.green("\u2714")} Opened logs directory in file manager`)}catch(t){t.code==="ENOENT"?console.log(`${h.yellow("Logs directory does not exist yet.")}`):e.printError(`Failed to open logs directory: ${t.message}`)}},Zc=async e=>{try{await Ms(H,{recursive:!0,force:!0}),console.log(`${h.green("\u2714")} All log files removed!`)}catch(t){e.printError(`Failed to remove log files: ${t.message}`)}};var el=j({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"]}},e=>{(async()=>{const{action:t}=e._,n=new U;switch(t){case"list":await Xc();break;case"path":console.log(`${h.blue("Logs directory:")} ${H}`);break;case"open":await Qc(n);break;case"removeAll":await Zc(n);break;default:throw new p(`Invalid action: ${t}. Use 'list', 'path', 'open', or 'removeAll'`)}})().catch(t=>{new U().printError(t.message),q(t),process.exit(1)})});const tl=process.argv.slice(2).filter(e=>!e.startsWith("--pre-commit")),[st,Ko]=tl;var nl=(e,t,n,o,s,r,a)=>(async()=>{if(!st)throw new p('Commit message file path is missing. This file should be called from the "pre-commit framework"');if(Ko){console.log(`Skipping aicommit2 message generation for ${Ko} commit`);return}const c=await zt();if(!c)return;const l=new U;l.printTitle();const u={...e&&{locale:e},...t!=null&&{generate:t.toString()},...o&&{type:o},...s&&{systemPrompt:s},...r===!0&&{includeBody:"true"}};a&&(u.logLevel="verbose");const d=await X(u,n);if(d.systemPromptPath)try{await I.readFile(P.resolve(d.systemPromptPath),"utf-8")}catch{throw new p(`Error reading system prompt file: ${d.systemPromptPath}`)}const m=fe(d,"commit");if(m.length===0)throw new p("Please set at least one API key via the `aicommit2 config set` command");const y=await Xe(),f=new Qe(d,c,y);let A;try{A=await mt(f.createCommitMsgRequests$(m).pipe(hn(O=>!O.isError),gn(O=>O.value),ft()))}finally{l.printAnalyzed()}const x=await I.readFile(st,"utf8")!=="",S=A.length>1;let b="";x&&(b=`# \u{1F916} Generated by aicommit2 (https://github.com/tak-bro/aicommit2)
|
|
227
|
+
`,b+=`# ----------------------------------------
|
|
228
|
+
`,b+=`# How to use:
|
|
229
|
+
`,S?(b+=`# 1. Remove the "#" from your chosen message
|
|
230
|
+
`,b+=`# 2. Edit the message if needed
|
|
231
|
+
`,b+=`# 3. Save and close the editor
|
|
232
|
+
`):(b+=`# 1. The message below will be used
|
|
233
|
+
`,b+=`# 2. Edit the message if needed
|
|
234
|
+
`,b+=`# 3. Save and close the editor
|
|
235
|
+
`),b+=`# ----------------------------------------
|
|
236
|
+
`),S?(x&&(b+=`
|
|
237
|
+
# \u{1F4DD} Choose one of these messages:
|
|
238
|
+
`),b+=`
|
|
239
|
+
${A.map(O=>`# ${O}`).join(`
|
|
240
|
+
`)}`):(x&&(b+=`
|
|
241
|
+
# \u{1F4DD} Generated commit message:
|
|
242
|
+
`),b+=`
|
|
243
|
+
${A[0]}
|
|
244
|
+
`);const C=await I.readFile(st,"utf8"),k=b+`
|
|
245
|
+
`+C;await I.writeFile(st,k),l.printSavedCommitMessage()})().catch(c=>{new U().printError(c.message),q(c),process.exit(1)});const on=process.argv.slice(2),Wo=[];let sn=!1;for(let e=0;e<on.length;e++){const t=on[e];if(sn){sn=!1;continue}if(t!=="--hook-mode"){if(t.startsWith("-")){const n=on[e+1];n&&!n.startsWith("-")&&(sn=!0);continue}Wo.push(t)}}const[rt,qo]=Wo;var ol=(e,t,n,o,s,r,a)=>(async()=>{if(!rt)throw new p('Commit message file path is missing. This file should be called from the "prepare-commit-msg" git hook or with --hook-mode flag');if(qo){console.log(`Skipping aicommit2 message generation for ${qo} commit`);return}const c=await zt();if(!c)return;const l=new U;l.printTitle();const u={locale:e?.toString(),generate:t?.toString(),type:o?.toString(),systemPrompt:s?.toString(),...r===!0&&{includeBody:"true"}};a&&(u.logLevel="verbose");const d=await X(u,n);if(d.systemPromptPath)try{await I.readFile(P.resolve(d.systemPromptPath),"utf-8")}catch{throw new p(`Error reading system prompt file: ${d.systemPromptPath}`)}const m=fe(d,"commit");if(m.length===0)throw new p("Please set at least one API key via the `aicommit2 config set` command");const y=await Xe(),f=new Qe(d,c,y),A=l.displaySpinner("The AI is analyzing your changes");let R;try{R=await mt(f.createCommitMsgRequests$(m).pipe(hn(W=>!W.isError),gn(W=>W.value),ft()))}finally{A.stop(),A.clear(),l.printAnalyzed()}const S=await I.readFile(rt,"utf8")!=="",b=R.length>1,C=await Ya();let k="";S&&(k=`${C} \u{1F916} Generated by aicommit2 (https://github.com/tak-bro/aicommit2)
|
|
246
|
+
`,k+=`${C} ----------------------------------------
|
|
247
|
+
`,k+=`${C} How to use:
|
|
248
|
+
`,b?(k+=`${C} 1. Remove the "${C}" from your chosen message
|
|
249
|
+
`,k+=`${C} 2. Edit the message if needed
|
|
250
|
+
`,k+=`${C} 3. Save and close the editor
|
|
251
|
+
`):(k+=`${C} 1. The message below will be used
|
|
252
|
+
`,k+=`${C} 2. Edit the message if needed
|
|
253
|
+
`,k+=`${C} 3. Save and close the editor
|
|
254
|
+
`),k+=`${C} ----------------------------------------
|
|
255
|
+
`),b?(S&&(k+=`
|
|
256
|
+
${C} \u{1F4DD} Choose one of these messages:
|
|
257
|
+
`),k+=`
|
|
258
|
+
${R.map(W=>`${C} ${W}`).join(`
|
|
259
|
+
`)}`):(S&&(k+=`
|
|
260
|
+
${C} \u{1F4DD} Generated commit message:
|
|
261
|
+
`),k+=`
|
|
262
|
+
${R[0]}
|
|
263
|
+
`);const O=await I.readFile(rt,"utf8"),V=k+`
|
|
264
|
+
`+O;await I.writeFile(rt,V),l.printSavedCommitMessage()})().catch(c=>{new U().printError(c.message),q(c),process.exit(1)});const z=new U,rn={OPENAI:{displayName:"OpenAI (ChatGPT)",authType:"api-key",envKeyHint:"OPENAI_API_KEY",defaultModel:"gpt-4o-mini"},COPILOT_SDK:{displayName:"GitHub Copilot SDK (Preview)",authType:"none",defaultModel:"gpt-4.1",setupNotes:"Uses local Copilot SDK auth flow (via Copilot CLI session), not GitHub Models API keys. Install/authenticate Copilot CLI first."},OPENROUTER:{displayName:"OpenRouter",authType:"api-key",envKeyHint:"OPENROUTER_API_KEY",defaultModel:"openrouter/auto",setupNotes:"OpenRouter supports many upstream models. You can keep openrouter/auto or choose a specific model slug."},ANTHROPIC:{displayName:"Anthropic (Claude)",authType:"api-key",envKeyHint:"ANTHROPIC_API_KEY",defaultModel:"claude-sonnet-4-20250514"},GEMINI:{displayName:"Google Gemini",authType:"api-key",envKeyHint:"GEMINI_API_KEY",defaultModel:"gemini-1.5-flash"},OLLAMA:{displayName:"Ollama (Local)",authType:"none",defaultModel:"llama3.2",setupNotes:"Ollama runs locally \u2014 no API key needed. Make sure Ollama is running."},GROQ:{displayName:"Groq",authType:"api-key",envKeyHint:"GROQ_API_KEY",defaultModel:"llama-3.3-70b-versatile"},DEEPSEEK:{displayName:"DeepSeek",authType:"api-key",envKeyHint:"DEEPSEEK_API_KEY",defaultModel:"deepseek-chat"},MISTRAL:{displayName:"Mistral AI",authType:"api-key",envKeyHint:"MISTRAL_API_KEY",defaultModel:"mistral-small-latest"},CODESTRAL:{displayName:"Codestral",authType:"api-key",envKeyHint:"CODESTRAL_API_KEY",defaultModel:"codestral-latest"},COHERE:{displayName:"Cohere",authType:"api-key",envKeyHint:"COHERE_API_KEY",defaultModel:"command-r-plus"},PERPLEXITY:{displayName:"Perplexity",authType:"api-key",envKeyHint:"PERPLEXITY_API_KEY",defaultModel:"sonar"},GITHUB_MODELS:{displayName:"GitHub Models",authType:"api-key",envKeyHint:"GITHUB_MODELS_API_KEY",defaultModel:"openai/gpt-4o-mini",setupNotes:"Use a GitHub personal access token (including github_pat_...). Run `aic2 github-login` for browser-based auth."},HUGGINGFACE:{displayName:"Hugging Face",authType:"cookie",defaultModel:"CohereForAI/c4ai-command-r-plus",setupNotes:"Requires a Hugging Face cookie for authentication."},BEDROCK:{displayName:"AWS Bedrock",authType:"complex",setupNotes:"Requires AWS credentials. Configure via AWS CLI or set region + access keys."}},zo=["OPENAI","OPENROUTER","ANTHROPIC","GEMINI","OLLAMA","GROQ","DEEPSEEK"];var sl=j({name:"setup",parameters:[],help:{description:"Interactive setup wizard for configuring AI providers",examples:["aic2 setup"]}},e=>{(async()=>{for(z.printTitle(),console.log(),z.printInfo(`Welcome to aicommit2 setup! Let's configure your AI providers.
|
|
265
|
+
`);;){const t=await rl();if(!t)break;await il(t.key,t.info);const{addMore:n}=await M.prompt([{type:"confirm",name:"addMore",message:"Would you like to configure another provider?",default:!1}]);if(!n)break;console.log()}z.printSuccess("Setup complete! Run `aic2` to generate commit messages.")})().catch(t=>{z.printError(t.message),q(t),process.exit(1)})});const rl=async()=>{const e=zo.map(r=>({name:rn[r].displayName,value:r})),n=de.filter(r=>!zo.includes(r)).map(r=>({name:rn[r]?.displayName||r,value:r})),{provider:o}=await M.prompt([{type:"list",name:"provider",message:"Select an AI provider to configure:",choices:[new M.Separator("\u2500\u2500 Popular \u2500\u2500"),...e,new M.Separator("\u2500\u2500 Other \u2500\u2500"),...n,new M.Separator,{name:"Done (exit setup)",value:null}]}]);if(!o)return null;const s=rn[o]||{displayName:o,authType:"api-key"};return{key:o,info:s}},il=async(e,t)=>{console.log(),t.setupNotes&&(z.printInfo(t.setupNotes),console.log());const n=[];switch(t.authType){case"api-key":{const{apiKey:r}=await M.prompt([{type:"password",name:"apiKey",message:`Enter your ${t.displayName} API key:`,mask:"*",validate:a=>a.trim()?!0:"API key is required"}]);n.push([`${e}.key`,r.trim()]);break}case"cookie":{const{cookie:r}=await M.prompt([{type:"password",name:"cookie",message:`Enter your ${t.displayName} cookie:`,mask:"*",validate:a=>a.trim()?!0:"Cookie is required"}]);n.push([`${e}.cookie`,r.trim()]);break}case"none":{if(e==="OLLAMA"){const{host:r}=await M.prompt([{type:"input",name:"host",message:"Ollama host URL:",default:ve}]);r&&r!==ve&&n.push([`${e}.host`,r.trim()])}break}case"complex":{z.printInfo("AWS Bedrock requires region and credentials."),console.log();const{region:r}=await M.prompt([{type:"input",name:"region",message:"AWS Region (e.g., us-east-1):",validate:c=>c.trim()?!0:"Region is required"}]);n.push([`${e}.region`,r.trim()]);const{authMethod:a}=await M.prompt([{type:"list",name:"authMethod",message:"Authentication method:",choices:[{name:"AWS Profile (from ~/.aws/credentials)",value:"profile"},{name:"Access Key + Secret Key",value:"keys"},{name:"Environment variables (already set)",value:"env"}]}]);if(a==="profile"){const{profile:c}=await M.prompt([{type:"input",name:"profile",message:"AWS Profile name:",default:"default"}]);n.push([`${e}.profile`,c.trim()])}else if(a==="keys"){const{accessKeyId:c,secretAccessKey:l}=await M.prompt([{type:"password",name:"accessKeyId",message:"AWS Access Key ID:",mask:"*"},{type:"password",name:"secretAccessKey",message:"AWS Secret Access Key:",mask:"*"}]);n.push([`${e}.accessKeyId`,c.trim()]),n.push([`${e}.secretAccessKey`,l.trim()])}break}}const{model:o}=await M.prompt([{type:"input",name:"model",message:"Model to use (comma-separated for multiple):",default:t.defaultModel||"",validate:r=>r.trim()?!0:"At least one model is required"}]);n.push([`${e}.model`,o.trim()]);const s=z.displaySpinner("Saving configuration...");try{await Ke(n),z.stopSpinner(s),z.printSuccess(`${t.displayName} configured successfully!`),t.envKeyHint&&console.log(` Tip: You can also set the ${t.envKeyHint} environment variable instead.`)}catch(r){z.stopSpinner(s),z.printError(`Failed to save configuration: ${r.message}`)}},Yo=20,Vo=e=>e<1e3?`${e}ms`:`${(e/1e3).toFixed(1)}s`,Jo=e=>new Date(e).toLocaleDateString(),al=e=>{const t=Math.round(e/100*Yo),n=Yo-t;return(e>=80?h.green:e>=50?h.yellow:h.red)("\u2588".repeat(t))+h.gray("\u2591".repeat(n))},cl=e=>{const t=e.totalRequests>0?Math.round(e.successCount/e.totalRequests*100):0,n=al(t),o=e.provider.padEnd(14),s=`${t}%`.padStart(4),r=`${e.totalRequests}`.padStart(4),a=`${e.selectedCount}`.padStart(4),c=e.selectionRate>0?`(${e.selectionRate}%)`.padStart(7):"".padStart(7),l=Vo(e.avgResponseTimeMs).padStart(6);console.log(` ${h.bold(o)} ${s} ${n} ${r} ${h.cyan(a)} ${h.gray(c)} ${l}`)},ll=async e=>{if(!await Ua()){console.log(h.yellow(`
|
|
266
|
+
No statistics recorded yet.`)),console.log(h.gray(`Statistics will be collected as you generate commit messages.
|
|
267
|
+
`));return}const n=await Ba(e);if(n.totalRequests===0){console.log(h.yellow(`
|
|
268
|
+
No statistics in the last ${e} days.
|
|
269
|
+
`));return}if(console.log(""),console.log(h.bold("\u{1F4CA} aicommit2 Statistics")),console.log(h.gray(` Period: ${Jo(n.periodStart)} - ${Jo(n.periodEnd)}`)),console.log(""),console.log(h.bold("Overview:")),console.log(` Total requests: ${h.cyan(n.totalRequests)}`),console.log(` Success rate: ${h.green(n.successRate+"%")}`),console.log(` Avg response time: ${h.yellow(Vo(n.avgResponseTimeMs))}`),console.log(""),n.providerStats.length>0){console.log(h.bold("Provider Usage:")),console.log(h.gray(" Provider Rate Bar Cnt Selected Time"));for(const o of n.providerStats)cl(o);console.log("")}},ul=async()=>{await Ha(),console.log(h.green(`
|
|
270
|
+
Statistics cleared successfully.
|
|
271
|
+
`))},dl=j({name:"stats",parameters:["[action]"],flags:{days:{type:Number,description:"Number of days to include in statistics (default: 30)",alias:"d",default:30}},help:{description:"View AI request statistics and performance metrics",examples:["aicommit2 stats Show statistics for last 30 days","aicommit2 stats -d 7 Show statistics for last 7 days","aicommit2 stats clear Clear all statistics"]}},e=>{(async()=>{const t=e._[0],{days:n}=e.flags;switch(t){case"clear":await ul();break;default:await ll(n);break}})().catch(t=>{console.error(h.red(t.message)),q(t),process.exit(1)})});class Xo{constructor(t="SubscriptionManager"){this.destroyed$=new xs,this.subscriptions=new dt,this.isDestroyed=!1,this.name=t}add(t,n){if(this.isDestroyed){console.warn(`${this.name}: Cannot add subscription - manager is destroyed`);const s=new dt;return s.unsubscribe(),s}const o=t.pipe(bn(this.destroyed$),En(()=>{process.env.NODE_ENV==="development"&&console.log(`${this.name}: Observable finalized`)})).subscribe({next:n?.next,error:s=>{console.error(`${this.name}: Observable error:`,s),n?.error?.(s)},complete:n?.complete});return this.subscriptions.add(o),o}pipe(t){return this.isDestroyed?(console.warn(`${this.name}: Cannot pipe - manager is destroyed`),t):t.pipe(bn(this.destroyed$),En(()=>{process.env.NODE_ENV==="development"&&console.log(`${this.name}: Piped observable finalized`)}))}addSubscription(t){if(this.isDestroyed){console.warn(`${this.name}: Cannot add subscription - manager is destroyed`),t.unsubscribe();return}this.subscriptions.add(t)}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 ml=new Xo("Global"),Re=()=>{ml.destroy()};process.on("exit",Re),process.on("SIGINT",Re),process.on("SIGTERM",Re),process.on("uncaughtException",e=>{console.error("Uncaught exception:",e),Re(),process.exit(1)}),process.on("unhandledRejection",(e,t)=>{console.error("Unhandled rejection at:",t,"reason:",e),Re(),process.exit(1)});const fl=ws(ls),Qo=5,pl=3e3,hl=500,gl=100,yl=1e3,wl=200;class Cl{constructor(){this.consoleManager=new U,this.subscriptionManager=new Xo,this.currentCodeReviewSubscription=null,this.currentCodeReviewPromptManager=null,this.watcher=null,this.lastCommitHash=null,this.isProcessingCommit=!1,this.retryCount=0,this.processingLock=!1,this.pendingCommitHash=null,this.excludeFiles=[],this.configExclude=[],this.REPO_PATH=process.cwd(),this.GIT_PATH=P.join(this.REPO_PATH,".git"),this.HEAD_PATH=P.join(this.GIT_PATH,"HEAD"),this.REFS_PATH=P.join(this.GIT_PATH,"refs","heads"),this.COMMIT_MSG_PATH=P.join(this.GIT_PATH,"COMMIT_EDITMSG"),this.setupProcessHandlers=()=>{const t=()=>{this.destroy(),process.exit(0)};process.on("SIGINT",t),process.on("SIGTERM",t),process.on("SIGQUIT",t)},this.watch=async(t,n,o,s,r,a)=>{this.consoleManager.printTitle(),await qt();const c=await Je();if(c!=="git")throw new p(`Watch mode is only supported for Git repositories. Current VCS: ${c}`);this.excludeFiles=o;const l=await this.initializeConfig(t,n,s,r,a);this.configExclude=l.exclude||[],await this.initializeCurrentCommit(),await this.startWatchLoop(l)},this.startWatchLoop=async t=>{try{await this.watchGitEvents(t)}catch(n){this.retryCount<Qo||(this.consoleManager.printError("Watch mode failed after maximum retries. Exiting."),this.destroy(),process.exit(1)),this.retryCount++;const s=pl*Math.pow(2,this.retryCount-1);return await this.handleWatchGitError(n,s),this.startWatchLoop(t)}},this.initializeConfig=async(t,n,o,s,r)=>{const a={locale:t?.toString(),generate:n?.toString(),systemPrompt:o?.toString()};s&&(a.logLevel="verbose");const c=await X(a,r);return await No(c),fe(c,"watch").length===0&&(this.consoleManager.printError(`Please set at least one API key and watchMode via the config command:
|
|
272
|
+
aicommit2 config set [MODEL].key="YOUR_API_KEY"
|
|
273
|
+
aicommit2 config set [MODEL].watchMode="true"`),process.exit()),c},this.handleWatchGitError=async(t,n)=>{this.consoleManager.printError(`An error occurred: ${t.message}`),q(t),await new Promise(o=>setTimeout(o,n)),this.consoleManager.printWarning(`Restarting the commit monitoring process... (retry ${this.retryCount}/${Qo})`)},this.initializeCurrentCommit=async()=>{try{const t=await this.executeGitCommand("git rev-parse HEAD");this.lastCommitHash=t.trim();const n=this.lastCommitHash.substring(0,8);this.consoleManager.printInfo(`Starting watch from commit: ${n}`)}catch{this.consoleManager.printWarning("No commits found in repository"),this.lastCommitHash=null}},this.executeGitCommand=async t=>{const{stdout:n}=await fl(t,{cwd:this.REPO_PATH});return n},this.clearTerminal=()=>{process.stdout.write("\x1Bc")},this.handleCommitEvent=async(t,n)=>{try{const o=await za(n,this.excludeFiles,this.configExclude);if(!o){this.consoleManager.printWarning("No changes found in this commit");return}this.consoleManager.stopLoader(),this.consoleManager.printStagedFiles(o);const s=fe(t,"watch");await this.performCodeReview(t,o,s)}catch(o){this.consoleManager.printError(`Error processing commit ${n.substring(0,8)}: ${o.message}`)}},this.performCodeReview=async(t,n,o)=>{this.cleanupPreviousCodeReview();const s=await Xe(),r=new Qe(t,n,s),a=[];let c=!1;this.currentCodeReviewSubscription=this.subscriptionManager.add(r.createCodeReviewRequests$(o),{next:l=>{a.push(l),this.currentCodeReviewPromptManager?.refreshChoices(l)},error:l=>{pe.error(`Code review request error: ${l}`),c=!0,this.currentCodeReviewPromptManager?.checkErrorOnChoices(!1)},complete:()=>{c=!0,this.currentCodeReviewPromptManager?.checkErrorOnChoices(!1)}});try{let l=!0;for(;l;){this.currentCodeReviewPromptManager=new Jt(Mo);const u=this.initializeCodeReviewInquirer();this.currentCodeReviewPromptManager.startLoader();for(const y of a)this.currentCodeReviewPromptManager.refreshChoices(y);c&&this.currentCodeReviewPromptManager.checkErrorOnChoices(!1);const m=!!(await u)?.codeReviewPrompt?.value,g=!this.currentCodeReviewPromptManager;m||c||g?l=!1:(this.currentCodeReviewPromptManager.destroy(),this.currentCodeReviewPromptManager=null)}}finally{this.cleanupCodeReview()}},this.cleanupPreviousCodeReview=()=>{this.cleanupCurrentReviewResources()},this.initializeCodeReviewInquirer=()=>this.currentCodeReviewPromptManager.initPrompt({...Vt,name:"codeReviewPrompt",message:"Please check code reviews: ",emptyMessage:`\u26A0 ${To}`,isDescriptionDim:!1,stopMessage:"Code review completed",descPageSize:20}),this.cleanupCurrentReviewResources=()=>{this.currentCodeReviewSubscription&&(this.currentCodeReviewSubscription.unsubscribe(),this.currentCodeReviewSubscription=null),this.currentCodeReviewPromptManager&&(this.currentCodeReviewPromptManager.destroy(),this.currentCodeReviewPromptManager=null)},this.cleanupCodeReview=()=>{this.cleanupCurrentReviewResources()},this.isGitReset=async t=>{if(!this.lastCommitHash)return!1;try{return await this.executeGitCommand(`git merge-base --is-ancestor ${t} ${this.lastCommitHash}`),!0}catch{return!1}},this.cancelCurrentReview=()=>{this.currentCodeReviewPromptManager&&this.currentCodeReviewPromptManager.cancel(),this.cleanupCurrentReviewResources()},this.closeWatcher=async()=>{this.watcher&&(await this.watcher.close(),this.watcher=null)},this.watchGitEvents=async t=>{this.consoleManager.showLoader("Watching for new Git commits...");const o=[this.HEAD_PATH,this.REFS_PATH,this.COMMIT_MSG_PATH,P.join(this.GIT_PATH,"logs","HEAD")].filter(s=>{try{return _.accessSync(s),!0}catch{return!1}});this.watcher=Ts.watch(o,{persistent:!0,ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:hl,pollInterval:gl}}),this.watcher.on("change",async s=>{await this.handleGitChange(t,s)}),this.watcher.on("add",async s=>{await this.handleGitChange(t,s)}),this.watcher.on("error",async s=>{this.consoleManager.printError(`Watcher error: ${s.message}`),await this.closeWatcher(),setTimeout(()=>{this.watchGitEvents(t).catch(r=>{pe.error(`Failed to restart watcher: ${r}`)})},yl)})},this.handleGitChange=async(t,n)=>{if(this.processingLock){try{const s=(await this.executeGitCommand("git rev-parse HEAD")).trim();s!==this.lastCommitHash&&(this.pendingCommitHash=s,this.isProcessingCommit&&this.cancelCurrentReview())}catch{}return}this.processingLock=!0;try{await this.processGitChange(t),this.pendingCommitHash&&this.pendingCommitHash!==this.lastCommitHash&&(this.pendingCommitHash=null,await this.processGitChange(t)),this.pendingCommitHash=null}finally{this.processingLock=!1}},this.processGitChange=async t=>{try{const o=(await this.executeGitCommand("git rev-parse HEAD")).trim();if(o===this.lastCommitHash)return;if(this.retryCount=0,await this.isGitReset(o)){this.consoleManager.printInfo(`Git reset detected: ${o.substring(0,8)}`),this.lastCommitHash=o,this.isProcessingCommit&&(this.cancelCurrentReview(),this.isProcessingCommit=!1);return}if(this.isProcessingCommit){this.consoleManager.printInfo("New commit detected, cancelling current review...");try{this.cancelCurrentReview(),await new Promise(r=>setTimeout(r,wl))}catch(r){pe.warn(`Error during review cancellation: ${r}`)}}this.isProcessingCommit=!0;try{this.consoleManager.stopLoader(),this.consoleManager.printInfo(`New commit detected: ${o.substring(0,8)}`),this.lastCommitHash=o,this.clearTerminal(),await this.handleCommitEvent(t,o)}catch(r){this.consoleManager.printError(`Error processing commit ${o.substring(0,8)}: ${r.message}`)}finally{this.isProcessingCommit=!1}}catch(n){this.isProcessingCommit=!1;const o=n.message??"";o.includes("fatal: not a git repository")||this.consoleManager.printError(`Error checking for new commits: ${o}`)}finally{this.consoleManager.showLoader("Watching for new Git commits...")}},this.destroy=()=>{this.isProcessingCommit=!1,this.lastCommitHash=null;try{this.subscriptionManager.destroy(),this.cleanupCurrentReviewResources(),this.watcher&&(this.watcher.close(),this.watcher=null),this.consoleManager.stopLoader()}catch(t){pe.warn(`Error during WatchGitManager destruction: ${t}`)}},this.setupProcessHandlers()}}const bl=new Cl,El=async(e,t,n,o,s,r)=>bl.watch(e,t,n,o,s,r),Zo={"Message Options":["locale","generate","type","prompt","include-body"],Behavior:["all","confirm","auto-select","edit","clipboard","dry-run","output"],"VCS Selection":["git","yadm","jj","jj-auto-new"],"Hook Integration":["hook-mode","pre-commit","watch-commit"],Formatting:["disable-lowercase","exclude"],Debug:["verbose"]},vl=e=>{if(!e||typeof e!="object")return!1;const t=e;return t.data?.name!==void 0&&typeof t.data.name=="string"},Pl=e=>vl(e)?e.data.name:null,Al=e=>{for(const[t,n]of Object.entries(Zo))if(n.includes(e))return t;return null},xl=e=>e.type==="section"&&e.data?.title==="Flags:",Sl=e=>e.data?.body?.data?.tableData!==void 0,$l=e=>{const t=new Map;for(const n of Object.keys(Zo))t.set(n,[]);if(t.set("Other",[]),!Array.isArray(e))return t;for(const n of e){if(!Array.isArray(n))continue;const o=Pl(n[0]),s=o&&Al(o)||"Other";t.get(s)?.push(n)}return t},Rl=(e,t,n,o,s)=>({type:"section",data:{title:s?`Flags - ${e}:`:` ${e}:`,body:{type:"table",data:{tableData:t,tableOptions:n,tableBreakpoints:o}}}}),Il=(e,t)=>{const n=[];for(const o of e){if(!xl(o)||!Sl(o)){n.push(o);continue}const{tableData:s,tableOptions:r,tableBreakpoints:a}=o.data.body.data;[...$l(s).entries()].filter(([,u])=>u.length>0).forEach(([u,d],m)=>{n.push(Rl(u,d,r,a,m===0))})}return t.render(n)};process.env.NODE_NO_WARNINGS||(process.env.NODE_NO_WARNINGS="1");const it=process.argv.slice(2),{version:es,description:kl}=Vs;ss({name:"aicommit2",version:es,flags:{locale:{type:String,description:"Locale to use for the generated commit messages (default: en)",alias:"l"},generate:{type:Number,description:"Number of messages to generate (Warning: generating multiple costs more) (default: 1)",alias:"g"},exclude:{type:[String],description:"Files to exclude from AI analysis",alias:"x"},all:{type:Boolean,description:"Automatically stage changes in tracked files for the commit",alias:"a",default:!1},type:{type:String,description:"Type of commit message to generate (default: conventional)",alias:"t"},confirm:{type:Boolean,description:"Skip confirmation when committing after message generation (default: false)",alias:"y",default:!1},clipboard:{type:Boolean,description:"Copy the selected message to the clipboard",alias:"c",default:!1},prompt:{type:String,description:"Custom prompt to let users fine-tune provided prompt",alias:"p"},"watch-commit":{type:Boolean,default:!1},"hook-mode":{type:Boolean,description:"Run in git hook mode, allowing chaining with other hooks",default:!1},"pre-commit":{type:Boolean,description:"Run in pre-commit Framework, allowing chaining with other hooks",default:!1},"include-body":{type:Boolean,description:"Force include commit body in all generated messages",alias:"i",default:!1},"auto-select":{type:Boolean,description:"Automatically select the message when only one is generated",alias:"s",default:!1},edit:{type:Boolean,description:"Open the AI-generated commit message in your default editor",alias:"e",default:!1},"disable-lowercase":{type:Boolean,description:"Disable automatic lowercase conversion of commit messages",default:!1},verbose:{type:Boolean,description:"Enable verbose logging for this run",alias:"v",default:!1},git:{type:Boolean,description:"Force use Git (overrides auto-detection)",default:!1},yadm:{type:Boolean,description:"Force use YADM (overrides auto-detection)",default:!1},jj:{type:Boolean,description:"Force use Jujutsu (overrides auto-detection)",default:!1},"jj-auto-new":{type:Boolean,description:"Run jj new after jj describe (default: false, only describe)",default:!1},"dry-run":{type:Boolean,description:"Generate commit message without committing (output only)",alias:"d",default:!1},output:{type:String,description:"Output format for non-interactive mode (json). For LazyGit integration",alias:"o"}},commands:[hc,Bc,Hc,zc,el,sl,dl],help:{description:kl,render:Il},ignoreArgv:e=>e==="unknown-flag"||e==="argument"},async e=>{const t={};e.flags.verbose&&(t.logLevel="verbose");const n=await X(t,it);if(await Qa(n),pe.info(`aicommit2 version: ${es}`),e.flags["pre-commit"]){nl(e.flags.locale,e.flags.generate,e.flags.exclude,e.flags.type,e.flags.prompt,e.flags["include-body"],e.flags.verbose);return}if(e.flags["hook-mode"]||qc){ol(e.flags.locale,e.flags.generate,e.flags.exclude,e.flags.type,e.flags.prompt,e.flags["include-body"],e.flags.verbose);return}if(e.flags["watch-commit"]){El(e.flags.locale,e.flags.generate,e.flags.exclude,e.flags.prompt,e.flags.verbose,it);return}uc(e.flags.locale,e.flags.generate,e.flags.exclude,e.flags.all,e.flags.type,e.flags.confirm,e.flags.clipboard,e.flags.prompt,e.flags["include-body"],e.flags["auto-select"],e.flags.edit,e.flags["disable-lowercase"],e.flags.verbose,e.flags["dry-run"],e.flags["jj-auto-new"],e.flags.output,it)},it);export{H as A,Oo as D,$ as E,tt as G,nt as H,p as K,K as P,wa as a,ac as b,ma as c,tc as d,nc as e,pa as f,ic as g,ec as h,J as i,oe as j,lc as k,pe as l,_t as m,fa as n,ve as o,Lo as p,tn as q,yc as r,Ca as s,Zt as t,en as u};
|