aicommit2
Version:
A Reactive CLI that generates git commit messages with various AI
14 lines • 162 kB
JavaScript
#!/usr/bin/env node
import{command as ie,cli as ln}from"cleye";import{createRequire as un}from"module";import{Buffer as dn}from"node:buffer";import ue from"node:path";import dr,{ChildProcess as mn,exec as fn}from"node:child_process";import ae from"node:process";import pn,{execSync as je}from"child_process";import S from"path";import oe from"fs";import{fileURLToPath as mr}from"node:url";import hn,{constants as fr}from"node:os";import pr from"assert";import hr from"events";import{createWriteStream as gn,createReadStream as yn}from"node:fs";import wn from"buffer";import gt from"stream";import gr from"util";import{debuglog as vn,promisify as bn}from"node:util";import Be from"inquirer";import C from"chalk";import{of as Ae,concatMap as L,from as I,map as M,catchError as R,mergeMap as Ue,BehaviorSubject as yr,ReplaySubject as Cn,lastValueFrom as wr,filter as vr,toArray as br,Subject as Cr}from"rxjs";import Pn from"@anthropic-ai/sdk";import{fromPromise as N}from"rxjs/internal/observable/innerFrom";import{xxh64 as Pr}from"@pacote/xxhash";import U from"winston";import O from"fs/promises";import ze from"os";import"winston-daily-rotate-file";import $n from"axios";import{CohereClient as En}from"cohere-ai";import $r from"openai";import{GoogleGenerativeAI as kn,HarmCategory as Ke,HarmBlockThreshold as We}from"@google/generative-ai";import An from"groq-sdk";import{Ollama as xn}from"ollama";import{fetch as Sn,Agent as In}from"undici";import Mn from"http";import Rn from"https";import On from"net";import Ln from"tls";import Nn,{fileURLToPath as Tn,pathToFileURL as Dn}from"url";import Er from"tty";import Ye from"readline";import _n from"figlet";import kr from"ora";import Fn from"inquirer-reactive-list-prompt";import{readdir as Ar,stat as Gn,rm as Hn}from"node:fs/promises";import jn from"chokidar";import{takeUntil as Bn}from"rxjs/operators";var Un="aicommit2",xr="2.3.5",zn="A Reactive CLI that generates git commit messages with various AI",Kn=["cli","ai","git","commit","git-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"],Wn="MIT",Yn="tak-bro/aicommit2",qn="Hyungtak Jin(@tak-bro)",Jn="module",Vn=["dist"],Xn={aicommit2:"./dist/cli.mjs",aic2:"./dist/cli.mjs"},Qn={prepare:"simple-git-hooks",build:"pkgroll --minify",lint:"eslint --cache .","type-check":"tsc",test:"tsx tests",prepack:"pnpm build && clean-pkg-json",prettier:"prettier"},Zn={"@anthropic-ai/sdk":"^0.39.0","@dqbd/tiktoken":"^1.0.21","@google/generative-ai":"^0.24.1","@inquirer/prompts":"^3.3.2","@pacote/xxhash":"^0.3.2","@types/winston":"^2.4.4",axios:"^1.9.0",chalk:"^5.4.1",chokidar:"^4.0.3",cleye:"^1.3.4","cohere-ai":"^7.17.1","copy-paste":"^1.5.3",figlet:"^1.8.1","formdata-node":"^6.0.3","groq-sdk":"^0.7.0",inquirer:"9.2.8","inquirer-reactive-list-prompt":"^1.0.15",ollama:"^0.5.15",openai:"^5.0.1",ora:"^8.2.0",readline:"^1.3.0",rxjs:"^7.8.2",undici:"^7.10.0",uuid:"^9.0.1",winston:"^3.17.0","winston-daily-rotate-file":"^5.0.0"},es={"@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"},ts={extends:["@pvtnbr","prettier"],rules:{"unicorn/no-process-exit":"off"},overrides:[{files:"./src/commands/prepare-commit-msg-hook.ts",rules:{"unicorn/prevent-abbreviations":"off"}}]},rs={branches:["main"],plugins:[["@semantic-release/commit-analyzer",{preset:"conventionalcommits",releaseRules:[{type:"refactor",release:"patch"},{type:"chore",release:"patch"},{type:"feat",release:"patch"},{scope:"major",release:"major"},{scope:"minor",release:"minor"},{scope:"patch",release:"patch"}]}],"@semantic-release/release-notes-generator",["@semantic-release/changelog",{changelogFile:"CHANGELOG.md"}],"@semantic-release/github",["@semantic-release/git",{assets:["CHANGELOG.md"],message:"chore(release): ${nextRelease.version} [skip ci]\n\n${nextRelease.notes}"}],"@semantic-release/npm"]},os={name:Un,version:xr,description:zn,keywords:Kn,license:Wn,repository:Yn,author:qn,type:Jn,files:Vn,bin:Xn,scripts:Qn,"simple-git-hooks":{"pre-commit":"pnpm lint-staged"},"lint-staged":{"*.ts":["prettier --config ./.prettierrc --write","eslint --fix"]},dependencies:Zn,devDependencies:es,eslintConfig:ts,release:rs},ns=un(import.meta.url),F=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function fe(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var pe={exports:{}},yt,Sr;function ss(){if(Sr)return yt;Sr=1,yt=o,o.sync=s;var t=oe;function e(n,i){var c=i.pathExt!==void 0?i.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&&n.substr(-u.length).toLowerCase()===u)return!0}return!1}function r(n,i,c){return!n.isSymbolicLink()&&!n.isFile()?!1:e(i,c)}function o(n,i,c){t.stat(n,function(l,u){c(l,l?!1:r(u,n,i))})}function s(n,i){return r(t.statSync(n),n,i)}return yt}var wt,Ir;function is(){if(Ir)return wt;Ir=1,wt=e,e.sync=r;var t=oe;function e(n,i,c){t.stat(n,function(l,u){c(l,l?!1:o(u,i))})}function r(n,i){return o(t.statSync(n),i)}function o(n,i){return n.isFile()&&s(n,i)}function s(n,i){var c=n.mode,l=n.uid,u=n.gid,m=i.uid!==void 0?i.uid:process.getuid&&process.getuid(),a=i.gid!==void 0?i.gid:process.getgid&&process.getgid(),d=parseInt("100",8),f=parseInt("010",8),h=parseInt("001",8),g=d|f,y=c&h||c&f&&u===a||c&d&&l===m||c&g&&m===0;return y}return wt}var qe;process.platform==="win32"||F.TESTING_WINDOWS?qe=ss():qe=is();var as=vt;vt.sync=cs;function vt(t,e,r){if(typeof e=="function"&&(r=e,e={}),!r){if(typeof Promise!="function")throw new TypeError("callback not provided");return new Promise(function(o,s){vt(t,e||{},function(n,i){n?s(n):o(i)})})}qe(t,e||{},function(o,s){o&&(o.code==="EACCES"||e&&e.ignoreErrors)&&(o=null,s=!1),r(o,s)})}function cs(t,e){try{return qe.sync(t,e||{})}catch(r){if(e&&e.ignoreErrors||r.code==="EACCES")return!1;throw r}}const he=process.platform==="win32"||process.env.OSTYPE==="cygwin"||process.env.OSTYPE==="msys",Mr=S,ls=he?";":":",Rr=as,Or=t=>Object.assign(new Error(`not found: ${t}`),{code:"ENOENT"}),Lr=(t,e)=>{const r=e.colon||ls,o=t.match(/\//)||he&&t.match(/\\/)?[""]:[...he?[process.cwd()]:[],...(e.path||process.env.PATH||"").split(r)],s=he?e.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",n=he?s.split(r):[""];return he&&t.indexOf(".")!==-1&&n[0]!==""&&n.unshift(""),{pathEnv:o,pathExt:n,pathExtExe:s}},Nr=(t,e,r)=>{typeof e=="function"&&(r=e,e={}),e||(e={});const{pathEnv:o,pathExt:s,pathExtExe:n}=Lr(t,e),i=[],c=u=>new Promise((m,a)=>{if(u===o.length)return e.all&&i.length?m(i):a(Or(t));const d=o[u],f=/^".*"$/.test(d)?d.slice(1,-1):d,h=Mr.join(f,t),g=!f&&/^\.[\\\/]/.test(t)?t.slice(0,2)+h:h;m(l(g,u,0))}),l=(u,m,a)=>new Promise((d,f)=>{if(a===s.length)return d(c(m+1));const h=s[a];Rr(u+h,{pathExt:n},(g,y)=>{if(!g&&y)if(e.all)i.push(u+h);else return d(u+h);return d(l(u,m,a+1))})});return r?c(0).then(u=>r(null,u),r):c(0)},us=(t,e)=>{e=e||{};const{pathEnv:r,pathExt:o,pathExtExe:s}=Lr(t,e),n=[];for(let i=0;i<r.length;i++){const c=r[i],l=/^".*"$/.test(c)?c.slice(1,-1):c,u=Mr.join(l,t),m=!l&&/^\.[\\\/]/.test(t)?t.slice(0,2)+u:u;for(let a=0;a<o.length;a++){const d=m+o[a];try{if(Rr.sync(d,{pathExt:s}))if(e.all)n.push(d);else return d}catch{}}}if(e.all&&n.length)return n;if(e.nothrow)return null;throw Or(t)};var ds=Nr;Nr.sync=us;var bt={exports:{}};const Tr=(t={})=>{const e=t.env||process.env;return(t.platform||process.platform)!=="win32"?"PATH":Object.keys(e).reverse().find(o=>o.toUpperCase()==="PATH")||"Path"};bt.exports=Tr,bt.exports.default=Tr;var ms=bt.exports;const Dr=S,fs=ds,ps=ms;function _r(t,e){const r=t.options.env||process.env,o=process.cwd(),s=t.options.cwd!=null,n=s&&process.chdir!==void 0&&!process.chdir.disabled;if(n)try{process.chdir(t.options.cwd)}catch{}let i;try{i=fs.sync(t.command,{path:r[ps({env:r})],pathExt:e?Dr.delimiter:void 0})}catch{}finally{n&&process.chdir(o)}return i&&(i=Dr.resolve(s?t.options.cwd:"",i)),i}function hs(t){return _r(t)||_r(t,!0)}var gs=hs,Ct={};const Pt=/([()\][%!^"`<>&|;, *?])/g;function ys(t){return t=t.replace(Pt,"^$1"),t}function ws(t,e){return t=`${t}`,t=t.replace(/(?=(\\+?)?)\1"/g,'$1$1\\"'),t=t.replace(/(?=(\\+?)?)\1$/,"$1$1"),t=`"${t}"`,t=t.replace(Pt,"^$1"),e&&(t=t.replace(Pt,"^$1")),t}Ct.command=ys,Ct.argument=ws;var vs=/^#!(.*)/;const bs=vs;var Cs=(t="")=>{const e=t.match(bs);if(!e)return null;const[r,o]=e[0].replace(/#! ?/,"").split(" "),s=r.split("/").pop();return s==="env"?o:o?`${s} ${o}`:s};const $t=oe,Ps=Cs;function $s(t){const r=Buffer.alloc(150);let o;try{o=$t.openSync(t,"r"),$t.readSync(o,r,0,150,0),$t.closeSync(o)}catch{}return Ps(r.toString())}var Es=$s;const ks=S,Fr=gs,Gr=Ct,As=Es,xs=process.platform==="win32",Ss=/\.(?:com|exe)$/i,Is=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function Ms(t){t.file=Fr(t);const e=t.file&&As(t.file);return e?(t.args.unshift(t.file),t.command=e,Fr(t)):t.file}function Rs(t){if(!xs)return t;const e=Ms(t),r=!Ss.test(e);if(t.options.forceShell||r){const o=Is.test(e);t.command=ks.normalize(t.command),t.command=Gr.command(t.command),t.args=t.args.map(n=>Gr.argument(n,o));const s=[t.command].concat(t.args).join(" ");t.args=["/d","/s","/c",`"${s}"`],t.command=process.env.comspec||"cmd.exe",t.options.windowsVerbatimArguments=!0}return t}function Os(t,e,r){e&&!Array.isArray(e)&&(r=e,e=null),e=e?e.slice(0):[],r=Object.assign({},r);const o={command:t,args:e,options:r,file:void 0,original:{command:t,args:e}};return r.shell?o:Rs(o)}var Ls=Os;const Et=process.platform==="win32";function kt(t,e){return Object.assign(new Error(`${e} ${t.command} ENOENT`),{code:"ENOENT",errno:"ENOENT",syscall:`${e} ${t.command}`,path:t.command,spawnargs:t.args})}function Ns(t,e){if(!Et)return;const r=t.emit;t.emit=function(o,s){if(o==="exit"){const n=Hr(s,e);if(n)return r.call(t,"error",n)}return r.apply(t,arguments)}}function Hr(t,e){return Et&&t===1&&!e.file?kt(e.original,"spawn"):null}function Ts(t,e){return Et&&t===1&&!e.file?kt(e.original,"spawnSync"):null}var Ds={hookChildProcess:Ns,verifyENOENT:Hr,verifyENOENTSync:Ts,notFoundError:kt};const jr=pn,At=Ls,xt=Ds;function Br(t,e,r){const o=At(t,e,r),s=jr.spawn(o.command,o.args,o.options);return xt.hookChildProcess(s,o),s}function _s(t,e,r){const o=At(t,e,r),s=jr.spawnSync(o.command,o.args,o.options);return s.error=s.error||xt.verifyENOENTSync(s.status,o),s}pe.exports=Br,pe.exports.spawn=Br,pe.exports.sync=_s,pe.exports._parse=At,pe.exports._enoent=xt;var Fs=pe.exports,Gs=fe(Fs);function Hs(t){const e=typeof t=="string"?`
`:`
`.charCodeAt(),r=typeof t=="string"?"\r":"\r".charCodeAt();return t[t.length-1]===e&&(t=t.slice(0,-1)),t[t.length-1]===r&&(t=t.slice(0,-1)),t}function Ur(t={}){const{env:e=process.env,platform:r=process.platform}=t;return r!=="win32"?"PATH":Object.keys(e).reverse().find(o=>o.toUpperCase()==="PATH")||"Path"}const js=({cwd:t=ae.cwd(),path:e=ae.env[Ur()],preferLocal:r=!0,execPath:o=ae.execPath,addExecPath:s=!0}={})=>{const n=t instanceof URL?mr(t):t,i=ue.resolve(n),c=[];return r&&Bs(c,i),s&&Us(c,o,i),[...c,e].join(ue.delimiter)},Bs=(t,e)=>{let r;for(;r!==e;)t.push(ue.join(e,"node_modules/.bin")),r=e,e=ue.resolve(e,"..")},Us=(t,e,r)=>{const o=e instanceof URL?mr(e):e;t.push(ue.resolve(r,o,".."))},zs=({env:t=ae.env,...e}={})=>{t={...t};const r=Ur({env:t});return e.path=t[r],t[r]=js(e),t},Ks=(t,e,r,o)=>{if(r==="length"||r==="prototype"||r==="arguments"||r==="caller")return;const s=Object.getOwnPropertyDescriptor(t,r),n=Object.getOwnPropertyDescriptor(e,r);!Ws(s,n)&&o||Object.defineProperty(t,r,n)},Ws=function(t,e){return t===void 0||t.configurable||t.writable===e.writable&&t.enumerable===e.enumerable&&t.configurable===e.configurable&&(t.writable||t.value===e.value)},Ys=(t,e)=>{const r=Object.getPrototypeOf(e);r!==Object.getPrototypeOf(t)&&Object.setPrototypeOf(t,r)},qs=(t,e)=>`/* Wrapped ${t}*/
${e}`,Js=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),Vs=Object.getOwnPropertyDescriptor(Function.prototype.toString,"name"),Xs=(t,e,r)=>{const o=r===""?"":`with ${r.trim()}() `,s=qs.bind(null,o,e.toString());Object.defineProperty(s,"name",Vs),Object.defineProperty(t,"toString",{...Js,value:s})};function Qs(t,e,{ignoreNonConfigurable:r=!1}={}){const{name:o}=t;for(const s of Reflect.ownKeys(e))Ks(t,e,s,r);return Ys(t,e),Xs(t,e,o),t}const Je=new WeakMap,zr=(t,e={})=>{if(typeof t!="function")throw new TypeError("Expected a function");let r,o=0;const s=t.displayName||t.name||"<anonymous>",n=function(...i){if(Je.set(n,++o),o===1)r=t.apply(this,i),t=null;else if(e.throw===!0)throw new Error(`Function \`${s}\` can only be called once`);return r};return Qs(n,t),Je.set(n,o),n};zr.callCount=t=>{if(!Je.has(t))throw new Error(`The given function \`${t.name}\` is not wrapped by the \`onetime\` package`);return Je.get(t)};const Zs=()=>{const t=Wr-Kr+1;return Array.from({length:t},ei)},ei=(t,e)=>({name:`SIGRT${e+1}`,number:Kr+e,action:"terminate",description:"Application-specific signal (realtime)",standard:"posix"}),Kr=34,Wr=64,ti=[{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"}],Yr=()=>{const t=Zs();return[...ti,...t].map(ri)},ri=({name:t,number:e,description:r,action:o,forced:s=!1,standard:n})=>{const{signals:{[t]:i}}=fr,c=i!==void 0;return{name:t,number:c?i:e,description:r,supported:c,action:o,forced:s,standard:n}},oi=()=>{const t=Yr();return Object.fromEntries(t.map(ni))},ni=({name:t,number:e,description:r,supported:o,action:s,forced:n,standard:i})=>[t,{name:t,number:e,description:r,supported:o,action:s,forced:n,standard:i}],si=oi(),ii=()=>{const t=Yr(),e=Wr+1,r=Array.from({length:e},(o,s)=>ai(s,t));return Object.assign({},...r)},ai=(t,e)=>{const r=ci(t,e);if(r===void 0)return{};const{name:o,description:s,supported:n,action:i,forced:c,standard:l}=r;return{[t]:{name:o,number:t,description:s,supported:n,action:i,forced:c,standard:l}}},ci=(t,e)=>{const r=e.find(({name:o})=>fr.signals[o]===t);return r!==void 0?r:e.find(o=>o.number===t)};ii();const li=({timedOut:t,timeout:e,errorCode:r,signal:o,signalDescription:s,exitCode:n,isCanceled:i})=>t?`timed out after ${e} milliseconds`:i?"was canceled":r!==void 0?`failed with ${r}`:o!==void 0?`was killed with ${o} (${s})`:n!==void 0?`failed with exit code ${n}`:"failed",qr=({stdout:t,stderr:e,all:r,error:o,signal:s,exitCode:n,command:i,escapedCommand:c,timedOut:l,isCanceled:u,killed:m,parsed:{options:{timeout:a,cwd:d=ae.cwd()}}})=>{n=n===null?void 0:n,s=s===null?void 0:s;const f=s===void 0?void 0:si[s].description,h=o&&o.code,y=`Command ${li({timedOut:l,timeout:a,errorCode:h,signal:s,signalDescription:f,exitCode:n,isCanceled:u})}: ${i}`,w=Object.prototype.toString.call(o)==="[object Error]",v=w?`${y}
${o.message}`:y,P=[v,e,t].filter(Boolean).join(`
`);return w?(o.originalMessage=o.message,o.message=P):o=new Error(P),o.shortMessage=v,o.command=i,o.escapedCommand=c,o.exitCode=n,o.signal=s,o.signalDescription=f,o.stdout=t,o.stderr=e,o.cwd=d,r!==void 0&&(o.all=r),"bufferedData"in o&&delete o.bufferedData,o.failed=!0,o.timedOut=!!l,o.isCanceled=u,o.killed=m&&!l,o},Ve=["stdin","stdout","stderr"],ui=t=>Ve.some(e=>t[e]!==void 0),di=t=>{if(!t)return;const{stdio:e}=t;if(e===void 0)return Ve.map(o=>t[o]);if(ui(t))throw new Error(`It's not possible to provide \`stdio\` in combination with one of ${Ve.map(o=>`\`${o}\``).join(", ")}`);if(typeof e=="string")return e;if(!Array.isArray(e))throw new TypeError(`Expected \`stdio\` to be of type \`string\` or \`Array\`, got \`${typeof e}\``);const r=Math.max(e.length,Ve.length);return Array.from({length:r},(o,s)=>e[s])};var ge={exports:{}},Xe={exports:{}};Xe.exports;var Jr;function mi(){return Jr||(Jr=1,function(t){t.exports=["SIGABRT","SIGALRM","SIGHUP","SIGINT","SIGTERM"],process.platform!=="win32"&&t.exports.push("SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT"),process.platform==="linux"&&t.exports.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT","SIGUNUSED")}(Xe)),Xe.exports}var D=F.process;const de=function(t){return t&&typeof t=="object"&&typeof t.removeListener=="function"&&typeof t.emit=="function"&&typeof t.reallyExit=="function"&&typeof t.listeners=="function"&&typeof t.kill=="function"&&typeof t.pid=="number"&&typeof t.on=="function"};if(!de(D))ge.exports=function(){return function(){}};else{var fi=pr,xe=mi(),pi=/^win/i.test(D.platform),Qe=hr;typeof Qe!="function"&&(Qe=Qe.EventEmitter);var G;D.__signal_exit_emitter__?G=D.__signal_exit_emitter__:(G=D.__signal_exit_emitter__=new Qe,G.count=0,G.emitted={}),G.infinite||(G.setMaxListeners(1/0),G.infinite=!0),ge.exports=function(t,e){if(!de(F.process))return function(){};fi.equal(typeof t,"function","a callback must be provided for exit handler"),Se===!1&&Vr();var r="exit";e&&e.alwaysLast&&(r="afterexit");var o=function(){G.removeListener(r,t),G.listeners("exit").length===0&&G.listeners("afterexit").length===0&&St()};return G.on(r,t),o};var St=function(){!Se||!de(F.process)||(Se=!1,xe.forEach(function(e){try{D.removeListener(e,It[e])}catch{}}),D.emit=Mt,D.reallyExit=Xr,G.count-=1)};ge.exports.unload=St;var ye=function(e,r,o){G.emitted[e]||(G.emitted[e]=!0,G.emit(e,r,o))},It={};xe.forEach(function(t){It[t]=function(){if(de(F.process)){var r=D.listeners(t);r.length===G.count&&(St(),ye("exit",null,t),ye("afterexit",null,t),pi&&t==="SIGHUP"&&(t="SIGINT"),D.kill(D.pid,t))}}}),ge.exports.signals=function(){return xe};var Se=!1,Vr=function(){Se||!de(F.process)||(Se=!0,G.count+=1,xe=xe.filter(function(e){try{return D.on(e,It[e]),!0}catch{return!1}}),D.emit=gi,D.reallyExit=hi)};ge.exports.load=Vr;var Xr=D.reallyExit,hi=function(e){de(F.process)&&(D.exitCode=e||0,ye("exit",D.exitCode,null),ye("afterexit",D.exitCode,null),Xr.call(D,D.exitCode))},Mt=D.emit,gi=function(e,r){if(e==="exit"&&de(F.process)){r!==void 0&&(D.exitCode=r);var o=Mt.apply(this,arguments);return ye("exit",D.exitCode,null),ye("afterexit",D.exitCode,null),o}else return Mt.apply(this,arguments)}}var yi=ge.exports,wi=fe(yi);const vi=1e3*5,bi=(t,e="SIGTERM",r={})=>{const o=t(e);return Ci(t,e,r,o),o},Ci=(t,e,r,o)=>{if(!Pi(e,r,o))return;const s=Ei(r),n=setTimeout(()=>{t("SIGKILL")},s);n.unref&&n.unref()},Pi=(t,{forceKillAfterTimeout:e},r)=>$i(t)&&e!==!1&&r,$i=t=>t===hn.constants.signals.SIGTERM||typeof t=="string"&&t.toUpperCase()==="SIGTERM",Ei=({forceKillAfterTimeout:t=!0})=>{if(t===!0)return vi;if(!Number.isFinite(t)||t<0)throw new TypeError(`Expected the \`forceKillAfterTimeout\` option to be a non-negative integer, got \`${t}\` (${typeof t})`);return t},ki=(t,e)=>{t.kill()&&(e.isCanceled=!0)},Ai=(t,e,r)=>{t.kill(e),r(Object.assign(new Error("Timed out"),{timedOut:!0,signal:e}))},xi=(t,{timeout:e,killSignal:r="SIGTERM"},o)=>{if(e===0||e===void 0)return o;let s;const n=new Promise((c,l)=>{s=setTimeout(()=>{Ai(t,r,l)},e)}),i=o.finally(()=>{clearTimeout(s)});return Promise.race([n,i])},Si=({timeout:t})=>{if(t!==void 0&&(!Number.isFinite(t)||t<0))throw new TypeError(`Expected the \`timeout\` option to be a non-negative integer, got \`${t}\` (${typeof t})`)},Ii=async(t,{cleanup:e,detached:r},o)=>{if(!e||r)return o;const s=wi(()=>{t.kill()});return o.finally(()=>{s()})};function Qr(t){return t!==null&&typeof t=="object"&&typeof t.pipe=="function"}function Zr(t){return Qr(t)&&t.writable!==!1&&typeof t._write=="function"&&typeof t._writableState=="object"}const Mi=t=>t instanceof mn&&typeof t.then=="function",Rt=(t,e,r)=>{if(typeof r=="string")return t[e].pipe(gn(r)),t;if(Zr(r))return t[e].pipe(r),t;if(!Mi(r))throw new TypeError("The second argument must be a string, a stream or an Execa child process.");if(!Zr(r.stdin))throw new TypeError("The target child process's stdin must be available.");return t[e].pipe(r.stdin),r},Ri=t=>{t.stdout!==null&&(t.pipeStdout=Rt.bind(void 0,t,"stdout")),t.stderr!==null&&(t.pipeStderr=Rt.bind(void 0,t,"stderr")),t.all!==void 0&&(t.pipeAll=Rt.bind(void 0,t,"all"))};var Ie={exports:{}};const{PassThrough:Oi}=gt;var Li=t=>{t={...t};const{array:e}=t;let{encoding:r}=t;const o=r==="buffer";let s=!1;e?s=!(r||o):r=r||"utf8",o&&(r=null);const n=new Oi({objectMode:s});r&&n.setEncoding(r);let i=0;const c=[];return n.on("data",l=>{c.push(l),s?i=c.length:i+=l.length}),n.getBufferedValue=()=>e?c:o?Buffer.concat(c,i):c.join(""),n.getBufferedLength=()=>i,n};const{constants:Ni}=wn,Ti=gt,{promisify:Di}=gr,_i=Li,Fi=Di(Ti.pipeline);class eo extends Error{constructor(){super("maxBuffer exceeded"),this.name="MaxBufferError"}}async function Ot(t,e){if(!t)throw new Error("Expected a stream");e={maxBuffer:1/0,...e};const{maxBuffer:r}=e,o=_i(e);return await new Promise((s,n)=>{const i=c=>{c&&o.getBufferedLength()<=Ni.MAX_LENGTH&&(c.bufferedData=o.getBufferedValue()),n(c)};(async()=>{try{await Fi(t,o),s()}catch(c){i(c)}})(),o.on("data",()=>{o.getBufferedLength()>r&&i(new eo)})}),o.getBufferedValue()}Ie.exports=Ot,Ie.exports.buffer=(t,e)=>Ot(t,{...e,encoding:"buffer"}),Ie.exports.array=(t,e)=>Ot(t,{...e,array:!0}),Ie.exports.MaxBufferError=eo;var Gi=Ie.exports,to=fe(Gi);const{PassThrough:Hi}=gt;var ji=function(){var t=[],e=new Hi({objectMode:!0});return e.setMaxListeners(0),e.add=r,e.isEmpty=o,e.on("unpipe",s),Array.prototype.slice.call(arguments).forEach(r),e;function r(n){return Array.isArray(n)?(n.forEach(r),this):(t.push(n),n.once("end",s.bind(null,n)),n.once("error",e.emit.bind(e,"error")),n.pipe(e,{end:!1}),this)}function o(){return t.length==0}function s(n){t=t.filter(function(i){return i!==n}),!t.length&&e.readable&&e.end()}},Bi=fe(ji);const Ui=t=>{if(t!==void 0)throw new TypeError("The `input` and `inputFile` options cannot be both set.")},zi=({input:t,inputFile:e})=>typeof e!="string"?t:(Ui(t),yn(e)),Ki=(t,e)=>{const r=zi(e);r!==void 0&&(Qr(r)?r.pipe(t.stdin):t.stdin.end(r))},Wi=(t,{all:e})=>{if(!e||!t.stdout&&!t.stderr)return;const r=Bi();return t.stdout&&r.add(t.stdout),t.stderr&&r.add(t.stderr),r},Lt=async(t,e)=>{if(!(!t||e===void 0)){t.destroy();try{return await e}catch(r){return r.bufferedData}}},Nt=(t,{encoding:e,buffer:r,maxBuffer:o})=>{if(!(!t||!r))return e?to(t,{encoding:e,maxBuffer:o}):to.buffer(t,{maxBuffer:o})},Yi=async({stdout:t,stderr:e,all:r},{encoding:o,buffer:s,maxBuffer:n},i)=>{const c=Nt(t,{encoding:o,buffer:s,maxBuffer:n}),l=Nt(e,{encoding:o,buffer:s,maxBuffer:n}),u=Nt(r,{encoding:o,buffer:s,maxBuffer:n*2});try{return await Promise.all([i,c,l,u])}catch(m){return Promise.all([{error:m,signal:m.signal,timedOut:m.timedOut},Lt(t,c),Lt(e,l),Lt(r,u)])}},qi=(async()=>{})().constructor.prototype,Ji=["then","catch","finally"].map(t=>[t,Reflect.getOwnPropertyDescriptor(qi,t)]),ro=(t,e)=>{for(const[r,o]of Ji){const s=typeof e=="function"?(...n)=>Reflect.apply(o.value,e(),n):o.value.bind(e);Reflect.defineProperty(t,r,{...o,value:s})}},Vi=t=>new Promise((e,r)=>{t.on("exit",(o,s)=>{e({exitCode:o,signal:s})}),t.on("error",o=>{r(o)}),t.stdin&&t.stdin.on("error",o=>{r(o)})}),oo=(t,e=[])=>Array.isArray(e)?[t,...e]:[t],Xi=/^[\w.-]+$/,Qi=/"/g,Zi=t=>typeof t!="string"||Xi.test(t)?t:`"${t.replace(Qi,'\\"')}"`,ea=(t,e)=>oo(t,e).join(" "),ta=(t,e)=>oo(t,e).map(r=>Zi(r)).join(" "),ra=vn("execa").enabled,Ze=(t,e)=>String(t).padStart(e,"0"),oa=()=>{const t=new Date;return`${Ze(t.getHours(),2)}:${Ze(t.getMinutes(),2)}:${Ze(t.getSeconds(),2)}.${Ze(t.getMilliseconds(),3)}`},na=(t,{verbose:e})=>{e&&ae.stderr.write(`[${oa()}] ${t}
`)},sa=1e3*1e3*100,ia=({env:t,extendEnv:e,preferLocal:r,localDir:o,execPath:s})=>{const n=e?{...ae.env,...t}:t;return r?zs({env:n,cwd:o,execPath:s}):n},aa=(t,e,r={})=>{const o=Gs._parse(t,e,r);return t=o.command,e=o.args,r=o.options,r={maxBuffer:sa,buffer:!0,stripFinalNewline:!0,extendEnv:!0,preferLocal:!1,localDir:r.cwd||ae.cwd(),execPath:ae.execPath,encoding:"utf8",reject:!0,cleanup:!0,all:!1,windowsHide:!0,verbose:ra,...r},r.env=ia(r),r.stdio=di(r),ae.platform==="win32"&&ue.basename(t,".exe")==="cmd"&&e.unshift("/q"),{file:t,args:e,options:r,parsed:o}},Tt=(t,e,r)=>typeof e!="string"&&!dn.isBuffer(e)?r===void 0?void 0:"":t.stripFinalNewline?Hs(e):e;function ne(t,e,r){const o=aa(t,e,r),s=ea(t,e),n=ta(t,e);na(n,o.options),Si(o.options);let i;try{i=dr.spawn(o.file,o.args,o.options)}catch(f){const h=new dr.ChildProcess,g=Promise.reject(qr({error:f,stdout:"",stderr:"",all:"",command:s,escapedCommand:n,parsed:o,timedOut:!1,isCanceled:!1,killed:!1}));return ro(h,g),h}const c=Vi(i),l=xi(i,o.options,c),u=Ii(i,o.options,l),m={isCanceled:!1};i.kill=bi.bind(null,i.kill.bind(i)),i.cancel=ki.bind(null,i,m);const d=zr(async()=>{const[{error:f,exitCode:h,signal:g,timedOut:y},w,v,P]=await Yi(i,o.options,u),A=Tt(o.options,w),b=Tt(o.options,v),k=Tt(o.options,P);if(f||h!==0||g!==null){const E=qr({error:f,exitCode:h,signal:g,stdout:A,stderr:b,all:k,command:s,escapedCommand:n,parsed:o,timedOut:y,isCanceled:m.isCanceled||(o.options.signal?o.options.signal.aborted:!1),killed:i.killed});if(!o.options.reject)return E;throw E}return{command:s,escapedCommand:n,exitCode:0,stdout:A,stderr:b,all:k,failed:!1,timedOut:!1,isCanceled:!1,killed:!1}});return Ki(i,o.options),i.all=Wi(i,o.options),Ri(i),ro(i,d),i}class T{static create(e,r){return new e(r)}}const{hasOwnProperty:Dt}=Object.prototype,et=typeof process<"u"&&process.platform==="win32"?`\r
`:`
`,_t=(t,e)=>{const r=[];let o="";typeof e=="string"?e={section:e,whitespace:!1}:(e=e||Object.create(null),e.whitespace=e.whitespace===!0);const s=e.whitespace?" = ":"=";for(const n of Object.keys(t)){const i=t[n];if(i&&Array.isArray(i))for(const c of i)o+=we(n+"[]")+s+we(c)+et;else i&&typeof i=="object"?r.push(n):o+=we(n)+s+we(i)+et}e.section&&o.length&&(o="["+we(e.section)+"]"+et+o);for(const n of r){const i=no(n).join("\\."),c=(e.section?e.section+".":"")+i,{whitespace:l}=e,u=_t(t[n],{section:c,whitespace:l});o.length&&u.length&&(o+=et),o+=u}return o},no=t=>t.replace(/\1/g,"LITERAL\\1LITERAL").replace(/\\\./g,"").split(/\./).map(e=>e.replace(/\1/g,"\\.").replace(/\2LITERAL\\1LITERAL\2/g,"")),so=t=>{const e=Object.create(null);let r=e,o=null;const s=/^\[([^\]]*)\]$|^([^=]+)(=(.*))?$/i,n=t.split(/[\r\n]+/g);for(const c of n){if(!c||c.match(/^\s*[;#]/))continue;const l=c.match(s);if(!l)continue;if(l[1]!==void 0){if(o=tt(l[1]),o==="__proto__"){r=Object.create(null);continue}r=e[o]=e[o]||Object.create(null);continue}const u=tt(l[2]),m=u.length>2&&u.slice(-2)==="[]",a=m?u.slice(0,-2):u;if(a==="__proto__")continue;const d=l[3]?tt(l[4]):!0,f=d==="true"||d==="false"||d==="null"?JSON.parse(d):d;m&&(Dt.call(r,a)?Array.isArray(r[a])||(r[a]=[r[a]]):r[a]=[]),Array.isArray(r[a])?r[a].push(f):r[a]=f}const i=[];for(const c of Object.keys(e)){if(!Dt.call(e,c)||typeof e[c]!="object"||Array.isArray(e[c]))continue;const l=no(c);r=e;const u=l.pop(),m=u.replace(/\\\./g,".");for(const a of l)a!=="__proto__"&&((!Dt.call(r,a)||typeof r[a]!="object")&&(r[a]=Object.create(null)),r=r[a]);r===e&&m===u||(r[m]=e[c],i.push(c))}for(const c of i)delete e[c];return e},io=t=>t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'"),we=t=>typeof t!="string"||t.match(/[=\r\n]/)||t.match(/^\[/)||t.length>1&&io(t)||t!==t.trim()?JSON.stringify(t):t.split(";").join("\\;").split("#").join("\\#"),tt=(t,e)=>{if(t=(t||"").trim(),io(t)){t.charAt(0)==="'"&&(t=t.slice(1,-1));try{t=JSON.parse(t)}catch{}}else{let r=!1,o="";for(let s=0,n=t.length;s<n;s++){const i=t.charAt(s);if(r)"\\;#".indexOf(i)!==-1?o+=i:o+="\\"+i,r=!1;else{if(";#".indexOf(i)!==-1)break;i==="\\"?r=!0:o+=i}}return r&&(o+="\\"),o.trim()}return t};var ca={parse:so,decode:so,stringify:_t,encode:_t,safe:we,unsafe:tt},ve=fe(ca);class $ extends Error{}const Ft=" ",ce=t=>{t instanceof Error&&(t instanceof $||(t.stack&&console.error(C.dim(t.stack.split(`
`).slice(1).join(`
`))),console.error(`
${Ft}${C.dim(`aicommit2 v${xr}`)}`),console.error(`
${Ft}Please open a Bug report with the information above:`),console.error(`${Ft}https://github.com/tak-bro/aicommit2/issues/new/choose`)))},ao=t=>O.lstat(t).then(()=>!0,()=>!1),co=async t=>{try{await O.mkdir(t,{recursive:!0})}catch(e){if(e.code!=="EEXIST")throw e}},rt=t=>t&&`${t[0].toUpperCase()}${t.slice(1)}`,ot=(t,e)=>{const r=Math.ceil(t),o=Math.floor(e);return Math.floor(Math.random()*(o-r+1))+r},la=(t,e)=>t.disabled&&!e.disabled?1:!t.disabled&&e.disabled?-1:0,nt=t=>t.reduce((e,r)=>Array.isArray(r)?e.concat(nt(r)):e.concat(r),[]),lo=(t,e=5)=>t.replace(/[\n\r]/g,"").split(" ").slice(0,e).join(" "),ua=t=>{let e=0;for(let r=0;r<t.length;r++){const o=t.charCodeAt(r);e=(e<<5)-e+o,e=e&e}return Math.abs(e)},da=t=>{const e=t%360,r=65+t%15,o=45+t%10;return`hsl(${e}, ${r}%, ${o}%)`},ma=t=>{const[e,r,o]=t.match(/\d+/g).map((a,d)=>d===0?Number(a):Number(a)/100),s=(1-Math.abs(2*o-1))*r,n=s*(1-Math.abs(e/60%2-1)),i=o-s/2;let c,l,u;e<60?[c,l,u]=[s,n,0]:e<120?[c,l,u]=[n,s,0]:e<180?[c,l,u]=[0,s,n]:e<240?[c,l,u]=[0,n,s]:e<300?[c,l,u]=[n,0,s]:[c,l,u]=[s,0,n];const m=a=>{const d=Math.round((a+i)*255).toString(16);return d.length===1?"0"+d:d};return`#${m(c)}${m(l)}${m(u)}`},fa=t=>{const e=ua(t),r=da(e);return{primary:ma(r),secondary:"#FFFFFF"}},pa=t=>{try{return{ok:!0,data:JSON.parse(t)}}catch(e){return{ok:!1,error:e}}},st=t=>{if(!t||typeof t!="string")return"";if(S.isAbsolute(t))return S.resolve(t);if(Re){const e=S.dirname(Re),r=S.join(e,t);return S.resolve(r)}else return""},ha=["","conventional","gitmoji"],Gt="http://localhost:11434",{hasOwnProperty:ga}=Object.prototype,Ht=(t,e)=>ga.call(t,e),be=["OPENAI","OLLAMA","HUGGINGFACE","GEMINI","ANTHROPIC","MISTRAL","CODESTRAL","COHERE","GROQ","PERPLEXITY","DEEPSEEK","GITHUB_MODELS"],uo=t=>{const e=ze.platform(),r=ze.homedir();let o,s;switch(t){case"config":o=process.env.XDG_CONFIG_HOME;break;case"data":o=process.env.XDG_DATA_HOME;break;case"cache":o=process.env.XDG_CACHE_HOME;break;case"state":o=process.env.XDG_STATE_HOME;break;default:o=void 0}if(e==="darwin")t==="cache"?s=S.join(r,"Library","Caches"):s=S.join(r,"Application Support");else if(e==="win32")s=process.env.LOCALAPPDATA||r;else switch(t){case"config":s=S.join(r,".config");break;case"data":s=S.join(r,".local","share");break;case"cache":s=S.join(r,".cache");break;case"state":s=S.join(r,".local","state");break;default:s=r}return o||s},ya=S.join(uo("config"),"aicommit2"),ee=S.join(uo("state"),"aicommit2","logs"),mo=S.join(ya,"config.ini"),fo=S.join(ee,"aicommit2-%DATE%.log"),po=S.join(ee,"exceptions-%DATE%.log"),wa=t=>{const e=Object.keys(t),r=new Set([...be,...e.filter(o=>/^[A-Z][A-Z0-9_]*$/.test(o))]);return Array.from(r)},x=(t,e,r)=>{if(!e)throw new $(`Invalid config property ${t}: ${r}`)},p={systemPrompt(t){return t||""},systemPromptPath(t){return t||""},codeReviewPromptPath(t){return t||""},timeout(t){if(!t)return 1e4;x("timeout",/^\d+$/.test(t),"Must be an integer");const e=Number(t);return x("timeout",e>=500,"Must be greater than 500ms"),e},temperature(t){if(!t)return .7;x("temperature",/^(2|\d)(\.\d{1,2})?$/.test(t),"Must be decimal between 0 and 2");const e=Number(t);return x("temperature",e>0,"Must be greater than 0"),x("temperature",e<=2,"Must be less than or equal to 2"),e},maxTokens(t){return t?(x("maxTokens",/^\d+$/.test(t),"Must be an integer"),Number(t)):1024},logging(t){return typeof t=="boolean"?t:t==null?!0:(x("logging",/^(?:true|false)$/.test(t),"Must be a boolean(true or false)"),t==="true")},logLevel(t){return t?(x("logLevel",/^(?:error|warn|info|http|verbose|debug|silly)$/.test(t),"Must be a valid log level (error, warn, info, http, verbose, debug, silly)"),t):"info"},logFilePath(t){return t||fo},exceptionLogFilePath(t){return t||po},locale(t){return t?(x("locale",t,"Cannot be empty"),x("locale",/^[a-z-]+$/i.test(t),"Must be a valid locale (letters and dashes/underscores). You can consult the list of codes in: https://wikipedia.org/wiki/List_of_ISO_639-1_codes"),t):"en"},generate(t){if(!t)return 1;x("generate",/^\d+$/.test(t),"Must be an integer");const e=Number(t);return x("generate",e>0,"Must be greater than 0"),x("generate",e<=5,"Must be less or equal to 5"),e},type(t){return t?(x("type",ha.includes(t),"Invalid commit type"),t):"conventional"},maxLength(t){if(!t)return 50;x("maxLength",/^\d+$/.test(t),"Must be an integer");const e=Number(t);return x("maxLength",e>=20,"Must be greater than 20 characters"),e},includeBody(t){return typeof t=="boolean"?t:t==null?!1:(x("includeBody",/^(?:true|false)$/.test(t),"Must be a boolean(true or false)"),t==="true")},exclude:t=>t?(typeof t=="string"?t?.split(","):t).map(r=>r.trim()).filter(r=>!!r&&r.length>0):[],topP:t=>{if(!t)return .9;x("topP",/^(1|\d)(\.\d{1,2})?$/.test(t),"Must be decimal between 0 and 1");const e=Number(t);return x("topP",e>0,"Must be greater than 0"),x("topP",e<=1,"Must be less than or equal to 1"),e},codeReview(t){return typeof t=="boolean"?t:t==null?!1:(x("codeReview",/^(?:true|false)$/.test(t),"Must be a boolean(true or false)"),t==="true")},disabled(t){return typeof t=="boolean"?t:t==null?!1:(x("disabled",/^(?:true|false)$/.test(t),"Must be a boolean(true or false)"),t==="true")},watchMode(t){return typeof t=="boolean"?t:t==null?!1:(x("watchMode",/^(?:true|false)$/.test(t),"Must be a boolean(true or false)"),t==="true")}},Me={OPENAI:{key:t=>t||"",envKey:t=>t||"",model:t=>t?(typeof t=="string"?t?.split(","):t).map(r=>r.trim()).filter(r=>!!r&&r.length>0):["gpt-4o-mini"],url:t=>t?(x("OPENAI.url",/^https?:\/\//.test(t),"Must be a valid URL"),t):"https://api.openai.com",path:t=>t||"/v1/chat/completions",proxy:t=>t||"",topP:p.topP,systemPrompt:p.systemPrompt,systemPromptPath:p.systemPromptPath,codeReviewPromptPath:p.codeReviewPromptPath,timeout:p.timeout,temperature:p.temperature,maxTokens:p.maxTokens,logging:p.logging,locale:p.locale,generate:p.generate,type:p.type,maxLength:p.maxLength,includeBody:p.includeBody,codeReview:p.codeReview,disabled:p.disabled,watchMode:p.watchMode},HUGGINGFACE:{cookie:t=>t||"",model:t=>t?(typeof t=="string"?t?.split(","):t).map(r=>r.trim()).filter(r=>!!r&&r.length>0):["CohereForAI/c4ai-command-r-plus"],systemPrompt:p.systemPrompt,systemPromptPath:p.systemPromptPath,codeReviewPromptPath:p.codeReviewPromptPath,timeout:p.timeout,temperature:p.temperature,maxTokens:p.maxTokens,topP:p.topP,logging:p.logging,locale:p.locale,generate:p.generate,type:p.type,maxLength:p.maxLength,includeBody:p.includeBody,codeReview:p.codeReview,disabled:p.disabled,watchMode:p.watchMode},GEMINI:{key:t=>t||"",envKey:t=>t||"",model:t=>t?(typeof t=="string"?t?.split(","):t).map(r=>r.trim()).filter(r=>!!r&&r.length>0):["gemini-2.0-flash"],systemPrompt:p.systemPrompt,systemPromptPath:p.systemPromptPath,codeReviewPromptPath:p.codeReviewPromptPath,temperature:p.temperature,maxTokens:p.maxTokens,logging:p.logging,locale:p.locale,generate:p.generate,type:p.type,maxLength:p.maxLength,includeBody:p.includeBody,topP:p.topP,codeReview:p.codeReview,disabled:p.disabled,watchMode:p.watchMode},ANTHROPIC:{key:t=>t||"",envKey:t=>t||"",model:t=>t?(typeof t=="string"?t?.split(","):t).map(r=>r.trim()).filter(r=>!!r&&r.length>0):["claude-3-5-haiku-20241022"],systemPrompt:p.systemPrompt,systemPromptPath:p.systemPromptPath,codeReviewPromptPath:p.codeReviewPromptPath,temperature:p.temperature,maxTokens:p.maxTokens,logging:p.logging,locale:p.locale,generate:p.generate,type:p.type,maxLength:p.maxLength,includeBody:p.includeBody,topP:p.topP,codeReview:p.codeReview,disabled:p.disabled,watchMode:p.watchMode},MISTRAL:{key:t=>t||"",envKey:t=>t||"",model:t=>t?(typeof t=="string"?t?.split(","):t).map(r=>r.trim()).filter(r=>!!r&&r.length>0):["mistral-small-latest"],systemPrompt:p.systemPrompt,systemPromptPath:p.systemPromptPath,codeReviewPromptPath:p.codeReviewPromptPath,timeout:p.timeout,temperature:p.temperature,maxTokens:p.maxTokens,logging:p.logging,locale:p.locale,generate:p.generate,type:p.type,maxLength:p.maxLength,includeBody:p.includeBody,topP:p.topP,codeReview:p.codeReview,disabled:p.disabled,watchMode:p.watchMode},CODESTRAL:{key:t=>t||"",envKey:t=>t||"",model:t=>t?(typeof t=="string"?t?.split(","):t).map(r=>r.trim()).filter(r=>!!r&&r.length>0):["codestral-latest"],topP:p.topP,systemPrompt:p.systemPrompt,systemPromptPath:p.systemPromptPath,codeReviewPromptPath:p.codeReviewPromptPath,timeout:p.timeout,temperature:p.temperature,maxTokens:p.maxTokens,logging:p.logging,locale:p.locale,generate:p.generate,type:p.type,maxLength:p.maxLength,includeBody:p.includeBody,codeReview:p.codeReview,disabled:p.disabled,watchMode:p.watchMode},OLLAMA:{model:t=>t?(typeof t=="string"?t?.split(","):t).map(r=>r.trim()).filter(r=>!!r&&r.length>0):[],host:t=>t?(x("OLLAMA.host",/^https?:\/\//.test(t),"Must be a valid URL"),t):Gt,timeout:t=>{if(!t)return 1e5;x("OLLAMA.timeout",/^\d+$/.test(t),"Must be an integer");const e=Number(t);return x("OLLAMA.timeout",e>=500,"Must be greater than 500ms"),e},auth:t=>t||"",key:t=>t||"",envKey:t=>t||"",numCtx:t=>{if(!t)return 2048;x("OLLAMA.numCtx",/^\d+$/.test(t),"Must be an integer");const e=Number(t);return x("OLLAMA.numCtx",e>=2048,"Must be greater than 2048"),e},systemPrompt:p.systemPrompt,systemPromptPath:p.systemPromptPath,codeReviewPromptPath:p.codeReviewPromptPath,temperature:p.temperature,maxTokens:p.maxTokens,logging:p.logging,locale:p.locale,generate:p.generate,type:p.type,maxLength:p.maxLength,includeBody:p.includeBody,topP:p.topP,codeReview:p.codeReview,disabled:p.disabled,watchMode:p.watchMode},COHERE:{key:t=>t||"",envKey:t=>t||"",model:t=>t?(typeof t=="string"?t?.split(","):t).map(r=>r.trim()).filter(r=>!!r&&r.length>0):["command-r"],systemPrompt:p.systemPrompt,systemPromptPath:p.systemPromptPath,codeReviewPromptPath:p.codeReviewPromptPath,temperature:p.temperature,maxTokens:p.maxTokens,logging:p.logging,locale:p.locale,generate:p.generate,type:p.type,maxLength:p.maxLength,includeBody:p.includeBody,topP:p.topP,codeReview:p.codeReview,disabled:p.disabled,watchMode:p.watchMode},GROQ:{key:t=>t||"",envKey:t=>t||"",model:t=>t?(typeof t=="string"?t?.split(","):t).map(r=>r.trim()).filter(r=>!!r&&r.length>0):["llama-3.3-70b-versatile"],systemPrompt:p.systemPrompt,systemPromptPath:p.systemPromptPath,codeReviewPromptPath:p.codeReviewPromptPath,timeout:p.timeout,temperature:p.temperature,maxTokens:p.maxTokens,logging:p.logging,locale:p.locale,generate:p.generate,type:p.type,maxLength:p.maxLength,includeBody:p.includeBody,topP:p.topP,codeReview:p.codeReview,disabled:p.disabled,watchMode:p.watchMode},PERPLEXITY:{key:t=>t||"",envKey:t=>t||"",model:t=>t?(typeof t=="string"?t?.split(","):t).map(r=>r.trim()).filter(r=>!!r&&r.length>0):["sonar"],topP:p.topP,systemPrompt:p.systemPrompt,systemPromptPath:p.systemPromptPath,codeReviewPromptPath:p.codeReviewPromptPath,timeout:p.timeout,temperature:p.temperature,maxTokens:p.maxTokens,logging:p.logging,locale:p.locale,generate:p.generate,type:p.type,maxLength:p.maxLength,includeBody:p.includeBody,codeReview:p.codeReview,disabled:p.disabled,watchMode:p.watchMode},DEEPSEEK:{key:t=>t||"",envKey:t=>t||"",model:t=>t?(typeof t=="string"?t?.split(","):t).map(r=>r.trim()).filter(r=>!!r&&r.length>0):["deepseek-coder"],topP:p.topP,systemPrompt:p.systemPrompt,systemPromptPath:p.systemPromptPath,codeReviewPromptPath:p.codeReviewPromptPath,timeout:p.timeout,temperature:p.temperature,maxTokens:p.maxTokens,logging:p.logging,locale:p.locale,generate:p.generate,type:p.type,maxLength:p.maxLength,includeBody:p.includeBody,codeReview:p.codeReview,disabled:p.disabled,watchMode:p.watchMode},GITHUB_MODELS:{key:t=>t||"",envKey:t=>t||"",model:t=>t?(typeof t=="string"?t?.split(","):t).map(r=>r.trim()).filter(r=>!!r&&r.length>0):["gpt-4o-mini"],systemPrompt:p.systemPrompt,systemPromptPath:p.systemPromptPath,codeReviewPromptPath:p.codeReviewPromptPath,timeout:p.timeout,temperature:p.temperature,maxTokens:p.maxTokens,logging:p.logging,locale:p.locale,generate:p.generate,type:p.type,maxLength:p.maxLength,includeBody:p.includeBody,topP:p.topP,codeReview:p.codeReview,disabled:p.disabled,watchMode:p.watchMode}};let Re;const va=(t=[])=>{const e={};for(const r of t)if(r.startsWith("--")){const[o,s]=r.slice(2).split("="),[n,i]=o.split(".");n&&i&&n in Me?(e[n]||(e[n]={}),e[n][i]=s):e[o]=s}return e},ba=()=>{const t=ze.homedir(),e=process.env.AICOMMIT_CONFIG_PATH,r=mo,o=S.join(t,".aicommit2");return[e,r,o].filter(s=>!!s)},Ce=async()=>{const t=ba();for(const e of t)if(await ao(e))return e;return mo},Oe=async()=>{const t=await Ce();Re=t;try{const e=await O.readFile(t,"utf8");return ve.parse(e)}catch(e){return e.code==="ENOENT"?(Re=void 0,{}):(console.error(`Error reading config file ${t}:`,e),Re=void 0,{})}},Pe=async(t,e=[])=>{const r=await Oe(),o=va(e),s={...t,...o},n={},i=wa(r),c={};for(const u of i){const a=r[u]?.envKey||`${u}_API_KEY`,d=process.env[a];d&&(c[u]={key:d})}const l=(u,m)=>{const a=s[`${u}.${m}`]??s[u]?.[m],d=c[u]?.[m],f=r[u]?.[m],h=s[m]??r[m];return a!==void 0?a:d!==void 0?d:f!==void 0?f:h};for(const[u,m]of Object.entries(p)){const a=s[u]??r[u];n[u]=m(a)}for(const u of i){n[u]={};const m=Me[u]||it(u);for(const[a,d]of Object.entries(m)){const f=l(u,a);n[u][a]=d(f)}}return n},jt=async t=>{const e=await Oe();for(const[s,n]of t){const[i,c]=s.split(".");if(!c){const m=p[s];if(!m)throw new $(`Invalid config property: ${s}`);e[s]=m(n);continue}if(e[i]||(e[i]={}),be.includes(i)){const m=Me[i][c];if(!m)throw new $(`Invalid config property: ${s}`);e[i][c]=m(n);continue}if(!/^[A-Z][A-Z0-9_]*$/.test(i))throw new $(`Invalid service name: ${i}. Service names must be uppercase letters, numbers, and underscores.`);const u=it(i);if(!u[c])throw new $(`Invalid config property for custom service: ${s}`);try{e[i][c]=u[c](n)}catch(m){throw m instanceof $?m:new $(`Invalid value for ${s}: ${m.message}`)}}const r=await Ce(),o=S.dirname(r);await O.mkdir(o,{recursive:!0}),await O.writeFile(r,ve.stringify(e),"utf8")},Ca=async t=>{const e=await Oe();for(const[s,n]of t){const[i,c]=s.split("."),l=e[i];if(c==="model"){l||(e[i]={});const m=e[i][c]||[],a=typeof n=="string"?n.split(",").map(d=>d.trim()).filter(d=>!!d):n;e[i][c]=nt([...m,...a]);continue}if(l&&l.compatible===!0){l||(e[i]={});const m=it(i);if(!m[c])throw new $(`Invalid config property: ${s}`);try{e[i][c]=m[c](n)}catch(a){throw a instanceof $?a:new $(`Invalid value for ${s}: ${a.message}`)}continue}if(i in Me){l||(e[i]={});const m=Me[i][c];if(!m)throw new $(`Invalid config property: ${s}`);e[i][c]=m(n)}else{const m=it(i);if(!m[c])throw new $(`Invalid config property: ${s}`);e[i]||(e[i]={}),e[i][c]=m[c](n)}}const r=await Ce(),o=S.dirname(r);await O.mkdir(o,{recursive:!0}),await O.writeFile(r,ve.stringify(e),"utf8")},Pa=async()=>{const t=await Oe();console.log(ve.stringify(t))},$a=async()=>{console.log(await Ce())},it=t=>({compatible:e=>typeof e=="boolean"?e:e==null?!1:(x("compatible",/^(?:true|false)$/.test(e),"Must be a boolean(true or false)"),e==="true"),stream:e=>typeof e=="boolean"?e:e==null?!1:(x("stream",/^(?:true|false)$/.test(e),"Must be a boolean(true or false)"),e==="true"),url:e=>e?(x(`${t}.url`,/^https?:\/\//.test(e),"Must be a valid URL"),e):"",path:e=>e||"",key:e=>e||"",envKey:e=>e||"",model:e=>e?(typeof e=="string"?e?.split(","):e).map(o=>o.trim()).filter(o=>!!o&&o.length>0):[],systemPrompt:p.systemPrompt,systemPromptPath:p.systemPromptPath,codeReviewPromptPath:p.codeReviewPromptPath,timeout:p.timeout,temperature:p.temperature,maxTokens:p.maxTokens,logging:p.logging,locale:p.locale,generate:p.generate,type:p.type,maxLength:p.maxLength,includeBody:p.includeBody,topP:p.topP,codeReview:p.codeReview,disabled:p.disabled,watchMode:p.watchMode}),Le=new Map,me=(t,e,r)=>{const o=Pr(0).update(e).digest("hex").substring(0,8),s=`${t}_${o}_${r}`;if(Le.has(s))return Le.get(s);const n=new Date,i=Aa(n,t,e,r),c=`${ee}/${i}`,l=U.createLogger({level:"info",format:U.format.combine(U.format.timestamp({format:"YYYY-MM-DDTHH:mm:ss.SSSZ"}),U.format.printf(({timestamp:u,level:m,message:a,...d})=>d&&Object.keys(d).length>0?`[${u}] ${m}: ${a} ${JSON.stringify(d,null,2)}`:`[${u}] ${m}: ${a}`)),transports:[new U.transports.File({filename:c})]});return l.info(`=== ${t.toUpperCase()} AI SERVICE LOG ===`),l.info(`Diff Hash: ${o}`),l.info(`Request Type: ${r.toUpperCase()}`),l.info(`Start Time: ${n.toISOString()}`),l.info("=".repeat(50)),l.info(""),Le.set(s,l),l},Ea=t=>{const e={...t},r=["authorization","x-api-key","x-goog-api-key","api-key"];for(const o of r){const s=o.toLowerCase(),n=Object.keys(e).find(i=>i.toLowerCase()===s);n&&e[n]&&typeof e[n]=="string"&&(e[n].startsWith("Bearer ")?e[n]="Bearer [MASKED]":e[n]="[MASKED]")}return e},Y=(t,e,r,o,s,n,i=!0)=>{if(!i)return;const c=me(r,t,e);c.info(`Making request to ${r} API with model: ${o}`),c.info(`Request URL: ${s}`),c.info("Request headers:",Ea(n))},te=(t,e,r,o,s=!0)=>{if(!s)return;me(r,t,e).info("Request payload:",o)},q=(t,e,r,o,s,n=!0)=>{if(!n)return;const i=me(r,t,e);i.info("System prompt:",{prompt:o}),i.info("User prompt:",{prompt:s})},J=(t,e,r,o,s=!0)=>{if(!s)return;me(r,t,e).info("Response received:",o)},_=(t,e,r,o,s=!0)=>{if(!s)return;me(r,t,e).error("API request failed:",o)},K=(t,e,r,o,s,n=!0)=>{if(!n)return;const i=me(r,t,e);o?i.info(`Request completed successfully in ${o}ms`):i.info("Request completed successfully"),s&&i.info("Final processed response:",{response:s}),i.info(""),i.info("=".repeat(50)),i.info(`End Time: ${new Date().toISOString()}`),i.info("=== REQUEST C