aicommit2
Version:
A Reactive CLI that generates git commit messages with various AI
14 lines • 131 kB
JavaScript
#!/usr/bin/env node
import{command as Y,cli as Ho}from"cleye";import{createRequire as Uo}from"module";import{Buffer as qo}from"node:buffer";import te from"node:path";import Xt,{ChildProcess as zo}from"node:child_process";import U from"node:process";import Ko from"child_process";import P from"path";import _ from"fs";import{fileURLToPath as Jt}from"node:url";import Wo,{constants as Qt}from"node:os";import Zt from"assert";import er from"events";import{createWriteStream as Yo,createReadStream as Vo}from"node:fs";import Xo from"buffer";import st from"stream";import tr from"util";import{debuglog as Jo}from"node:util";import Me from"inquirer";import nt from"ora";import w from"chalk";import{of as de,concatMap as k,from as $,map as A,catchError as S,mergeMap as Ie,BehaviorSubject as rr,ReplaySubject as Qo,lastValueFrom as or,filter as sr,toArray as nr,Subject as ir}from"rxjs";import Zo from"@anthropic-ai/sdk";import{fromPromise as M}from"rxjs/internal/observable/innerFrom";import q from"winston";import"winston-daily-rotate-file";import x from"fs/promises";import Re from"os";import{xxh64 as es}from"@pacote/xxhash";import ts from"axios";import{CohereClient as rs}from"cohere-ai";import ar from"openai";import{GoogleGenerativeAI as os,HarmCategory as Oe,HarmBlockThreshold as Le}from"@google/generative-ai";import ss from"groq-sdk";import{Ollama as ns}from"ollama";import{fetch as is,Agent as as}from"undici";import cs from"http";import ls from"https";import ms from"net";import us from"tls";import ps,{fileURLToPath as fs,pathToFileURL as ds}from"url";import cr from"tty";import Te from"readline";import hs from"figlet";import gs from"inquirer-reactive-list-prompt";import{rm as ys}from"node:fs/promises";import ws from"chokidar";import{takeUntil as vs}from"rxjs/operators";var bs="aicommit2",lr="2.2.21",Cs="A Reactive CLI that generates git commit messages with various AI",Ps=["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"],$s="MIT",Es="tak-bro/aicommit2",xs="Hyungtak Jin(@tak-bro)",As="module",Ss=["dist"],ks={aicommit2:"./dist/cli.mjs",aic2:"./dist/cli.mjs"},Ms={prepare:"simple-git-hooks",build:"pkgroll --minify",lint:"eslint --cache .","type-check":"tsc",test:"tsx tests",prepack:"pnpm build && clean-pkg-json",prettier:"prettier"},Is={"@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"},Rs={"@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"},Os={extends:["@pvtnbr","prettier"],rules:{"unicorn/no-process-exit":"off"},overrides:[{files:"./src/commands/prepare-commit-msg-hook.ts",rules:{"unicorn/prevent-abbreviations":"off"}}]},Ls={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"]},Ts={name:bs,version:lr,description:Cs,keywords:Ps,license:$s,repository:Es,author:xs,type:As,files:Ss,bin:ks,scripts:Ms,"simple-git-hooks":{"pre-commit":"pnpm lint-staged"},"lint-staged":{"*.ts":["prettier --config ./.prettierrc --write","eslint --fix"]},dependencies:Is,devDependencies:Rs,eslintConfig:Os,release:Ls},Ns=Uo(import.meta.url),O=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function re(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var oe={exports:{}},it,mr;function _s(){if(mr)return it;mr=1,it=r,r.sync=n;var t=_;function e(s,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&&s.substr(-u.length).toLowerCase()===u)return!0}return!1}function o(s,i,c){return!s.isSymbolicLink()&&!s.isFile()?!1:e(i,c)}function r(s,i,c){t.stat(s,function(l,u){c(l,l?!1:o(u,s,i))})}function n(s,i){return o(t.statSync(s),s,i)}return it}var at,ur;function Fs(){if(ur)return at;ur=1,at=e,e.sync=o;var t=_;function e(s,i,c){t.stat(s,function(l,u){c(l,l?!1:r(u,i))})}function o(s,i){return r(t.statSync(s),i)}function r(s,i){return s.isFile()&&n(s,i)}function n(s,i){var c=s.mode,l=s.uid,u=s.gid,p=i.uid!==void 0?i.uid:process.getuid&&process.getuid(),a=i.gid!==void 0?i.gid:process.getgid&&process.getgid(),m=parseInt("100",8),d=parseInt("010",8),h=parseInt("001",8),g=m|d,y=c&h||c&d&&u===a||c&m&&l===p||c&g&&p===0;return y}return at}var Ne;process.platform==="win32"||O.TESTING_WINDOWS?Ne=_s():Ne=Fs();var Ds=ct;ct.sync=Gs;function ct(t,e,o){if(typeof e=="function"&&(o=e,e={}),!o){if(typeof Promise!="function")throw new TypeError("callback not provided");return new Promise(function(r,n){ct(t,e||{},function(s,i){s?n(s):r(i)})})}Ne(t,e||{},function(r,n){r&&(r.code==="EACCES"||e&&e.ignoreErrors)&&(r=null,n=!1),o(r,n)})}function Gs(t,e){try{return Ne.sync(t,e||{})}catch(o){if(e&&e.ignoreErrors||o.code==="EACCES")return!1;throw o}}const se=process.platform==="win32"||process.env.OSTYPE==="cygwin"||process.env.OSTYPE==="msys",pr=P,js=se?";":":",fr=Ds,dr=t=>Object.assign(new Error(`not found: ${t}`),{code:"ENOENT"}),hr=(t,e)=>{const o=e.colon||js,r=t.match(/\//)||se&&t.match(/\\/)?[""]:[...se?[process.cwd()]:[],...(e.path||process.env.PATH||"").split(o)],n=se?e.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",s=se?n.split(o):[""];return se&&t.indexOf(".")!==-1&&s[0]!==""&&s.unshift(""),{pathEnv:r,pathExt:s,pathExtExe:n}},gr=(t,e,o)=>{typeof e=="function"&&(o=e,e={}),e||(e={});const{pathEnv:r,pathExt:n,pathExtExe:s}=hr(t,e),i=[],c=u=>new Promise((p,a)=>{if(u===r.length)return e.all&&i.length?p(i):a(dr(t));const m=r[u],d=/^".*"$/.test(m)?m.slice(1,-1):m,h=pr.join(d,t),g=!d&&/^\.[\\\/]/.test(t)?t.slice(0,2)+h:h;p(l(g,u,0))}),l=(u,p,a)=>new Promise((m,d)=>{if(a===n.length)return m(c(p+1));const h=n[a];fr(u+h,{pathExt:s},(g,y)=>{if(!g&&y)if(e.all)i.push(u+h);else return m(u+h);return m(l(u,p,a+1))})});return o?c(0).then(u=>o(null,u),o):c(0)},Bs=(t,e)=>{e=e||{};const{pathEnv:o,pathExt:r,pathExtExe:n}=hr(t,e),s=[];for(let i=0;i<o.length;i++){const c=o[i],l=/^".*"$/.test(c)?c.slice(1,-1):c,u=pr.join(l,t),p=!l&&/^\.[\\\/]/.test(t)?t.slice(0,2)+u:u;for(let a=0;a<r.length;a++){const m=p+r[a];try{if(fr.sync(m,{pathExt:n}))if(e.all)s.push(m);else return m}catch{}}}if(e.all&&s.length)return s;if(e.nothrow)return null;throw dr(t)};var Hs=gr;gr.sync=Bs;var lt={exports:{}};const yr=(t={})=>{const e=t.env||process.env;return(t.platform||process.platform)!=="win32"?"PATH":Object.keys(e).reverse().find(r=>r.toUpperCase()==="PATH")||"Path"};lt.exports=yr,lt.exports.default=yr;var Us=lt.exports;const wr=P,qs=Hs,zs=Us;function vr(t,e){const o=t.options.env||process.env,r=process.cwd(),n=t.options.cwd!=null,s=n&&process.chdir!==void 0&&!process.chdir.disabled;if(s)try{process.chdir(t.options.cwd)}catch{}let i;try{i=qs.sync(t.command,{path:o[zs({env:o})],pathExt:e?wr.delimiter:void 0})}catch{}finally{s&&process.chdir(r)}return i&&(i=wr.resolve(n?t.options.cwd:"",i)),i}function Ks(t){return vr(t)||vr(t,!0)}var Ws=Ks,mt={};const ut=/([()\][%!^"`<>&|;, *?])/g;function Ys(t){return t=t.replace(ut,"^$1"),t}function Vs(t,e){return t=`${t}`,t=t.replace(/(?=(\\+?)?)\1"/g,'$1$1\\"'),t=t.replace(/(?=(\\+?)?)\1$/,"$1$1"),t=`"${t}"`,t=t.replace(ut,"^$1"),e&&(t=t.replace(ut,"^$1")),t}mt.command=Ys,mt.argument=Vs;var Xs=/^#!(.*)/;const Js=Xs;var Qs=(t="")=>{const e=t.match(Js);if(!e)return null;const[o,r]=e[0].replace(/#! ?/,"").split(" "),n=o.split("/").pop();return n==="env"?r:r?`${n} ${r}`:n};const pt=_,Zs=Qs;function en(t){const o=Buffer.alloc(150);let r;try{r=pt.openSync(t,"r"),pt.readSync(r,o,0,150,0),pt.closeSync(r)}catch{}return Zs(o.toString())}var tn=en;const rn=P,br=Ws,Cr=mt,on=tn,sn=process.platform==="win32",nn=/\.(?:com|exe)$/i,an=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function cn(t){t.file=br(t);const e=t.file&&on(t.file);return e?(t.args.unshift(t.file),t.command=e,br(t)):t.file}function ln(t){if(!sn)return t;const e=cn(t),o=!nn.test(e);if(t.options.forceShell||o){const r=an.test(e);t.command=rn.normalize(t.command),t.command=Cr.command(t.command),t.args=t.args.map(s=>Cr.argument(s,r));const n=[t.command].concat(t.args).join(" ");t.args=["/d","/s","/c",`"${n}"`],t.command=process.env.comspec||"cmd.exe",t.options.windowsVerbatimArguments=!0}return t}function mn(t,e,o){e&&!Array.isArray(e)&&(o=e,e=null),e=e?e.slice(0):[],o=Object.assign({},o);const r={command:t,args:e,options:o,file:void 0,original:{command:t,args:e}};return o.shell?r:ln(r)}var un=mn;const ft=process.platform==="win32";function dt(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 pn(t,e){if(!ft)return;const o=t.emit;t.emit=function(r,n){if(r==="exit"){const s=Pr(n,e);if(s)return o.call(t,"error",s)}return o.apply(t,arguments)}}function Pr(t,e){return ft&&t===1&&!e.file?dt(e.original,"spawn"):null}function fn(t,e){return ft&&t===1&&!e.file?dt(e.original,"spawnSync"):null}var dn={hookChildProcess:pn,verifyENOENT:Pr,verifyENOENTSync:fn,notFoundError:dt};const $r=Ko,ht=un,gt=dn;function Er(t,e,o){const r=ht(t,e,o),n=$r.spawn(r.command,r.args,r.options);return gt.hookChildProcess(n,r),n}function hn(t,e,o){const r=ht(t,e,o),n=$r.spawnSync(r.command,r.args,r.options);return n.error=n.error||gt.verifyENOENTSync(n.status,r),n}oe.exports=Er,oe.exports.spawn=Er,oe.exports.sync=hn,oe.exports._parse=ht,oe.exports._enoent=gt;var gn=oe.exports,yn=re(gn);function wn(t){const e=typeof t=="string"?`
`:`
`.charCodeAt(),o=typeof t=="string"?"\r":"\r".charCodeAt();return t[t.length-1]===e&&(t=t.slice(0,-1)),t[t.length-1]===o&&(t=t.slice(0,-1)),t}function xr(t={}){const{env:e=process.env,platform:o=process.platform}=t;return o!=="win32"?"PATH":Object.keys(e).reverse().find(r=>r.toUpperCase()==="PATH")||"Path"}const vn=({cwd:t=U.cwd(),path:e=U.env[xr()],preferLocal:o=!0,execPath:r=U.execPath,addExecPath:n=!0}={})=>{const s=t instanceof URL?Jt(t):t,i=te.resolve(s),c=[];return o&&bn(c,i),n&&Cn(c,r,i),[...c,e].join(te.delimiter)},bn=(t,e)=>{let o;for(;o!==e;)t.push(te.join(e,"node_modules/.bin")),o=e,e=te.resolve(e,"..")},Cn=(t,e,o)=>{const r=e instanceof URL?Jt(e):e;t.push(te.resolve(o,r,".."))},Pn=({env:t=U.env,...e}={})=>{t={...t};const o=xr({env:t});return e.path=t[o],t[o]=vn(e),t},$n=(t,e,o,r)=>{if(o==="length"||o==="prototype"||o==="arguments"||o==="caller")return;const n=Object.getOwnPropertyDescriptor(t,o),s=Object.getOwnPropertyDescriptor(e,o);!En(n,s)&&r||Object.defineProperty(t,o,s)},En=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)},xn=(t,e)=>{const o=Object.getPrototypeOf(e);o!==Object.getPrototypeOf(t)&&Object.setPrototypeOf(t,o)},An=(t,e)=>`/* Wrapped ${t}*/
${e}`,Sn=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),kn=Object.getOwnPropertyDescriptor(Function.prototype.toString,"name"),Mn=(t,e,o)=>{const r=o===""?"":`with ${o.trim()}() `,n=An.bind(null,r,e.toString());Object.defineProperty(n,"name",kn),Object.defineProperty(t,"toString",{...Sn,value:n})};function In(t,e,{ignoreNonConfigurable:o=!1}={}){const{name:r}=t;for(const n of Reflect.ownKeys(e))$n(t,e,n,o);return xn(t,e),Mn(t,e,r),t}const _e=new WeakMap,Ar=(t,e={})=>{if(typeof t!="function")throw new TypeError("Expected a function");let o,r=0;const n=t.displayName||t.name||"<anonymous>",s=function(...i){if(_e.set(s,++r),r===1)o=t.apply(this,i),t=null;else if(e.throw===!0)throw new Error(`Function \`${n}\` can only be called once`);return o};return In(s,t),_e.set(s,r),s};Ar.callCount=t=>{if(!_e.has(t))throw new Error(`The given function \`${t.name}\` is not wrapped by the \`onetime\` package`);return _e.get(t)};const Rn=()=>{const t=kr-Sr+1;return Array.from({length:t},On)},On=(t,e)=>({name:`SIGRT${e+1}`,number:Sr+e,action:"terminate",description:"Application-specific signal (realtime)",standard:"posix"}),Sr=34,kr=64,Ln=[{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"}],Mr=()=>{const t=Rn();return[...Ln,...t].map(Tn)},Tn=({name:t,number:e,description:o,action:r,forced:n=!1,standard:s})=>{const{signals:{[t]:i}}=Qt,c=i!==void 0;return{name:t,number:c?i:e,description:o,supported:c,action:r,forced:n,standard:s}},Nn=()=>{const t=Mr();return Object.fromEntries(t.map(_n))},_n=({name:t,number:e,description:o,supported:r,action:n,forced:s,standard:i})=>[t,{name:t,number:e,description:o,supported:r,action:n,forced:s,standard:i}],Fn=Nn(),Dn=()=>{const t=Mr(),e=kr+1,o=Array.from({length:e},(r,n)=>Gn(n,t));return Object.assign({},...o)},Gn=(t,e)=>{const o=jn(t,e);if(o===void 0)return{};const{name:r,description:n,supported:s,action:i,forced:c,standard:l}=o;return{[t]:{name:r,number:t,description:n,supported:s,action:i,forced:c,standard:l}}},jn=(t,e)=>{const o=e.find(({name:r})=>Qt.signals[r]===t);return o!==void 0?o:e.find(r=>r.number===t)};Dn();const Bn=({timedOut:t,timeout:e,errorCode:o,signal:r,signalDescription:n,exitCode:s,isCanceled:i})=>t?`timed out after ${e} milliseconds`:i?"was canceled":o!==void 0?`failed with ${o}`:r!==void 0?`was killed with ${r} (${n})`:s!==void 0?`failed with exit code ${s}`:"failed",Ir=({stdout:t,stderr:e,all:o,error:r,signal:n,exitCode:s,command:i,escapedCommand:c,timedOut:l,isCanceled:u,killed:p,parsed:{options:{timeout:a,cwd:m=U.cwd()}}})=>{s=s===null?void 0:s,n=n===null?void 0:n;const d=n===void 0?void 0:Fn[n].description,h=r&&r.code,y=`Command ${Bn({timedOut:l,timeout:a,errorCode:h,signal:n,signalDescription:d,exitCode:s,isCanceled:u})}: ${i}`,v=Object.prototype.toString.call(r)==="[object Error]",E=v?`${y}
${r.message}`:y,N=[E,e,t].filter(Boolean).join(`
`);return v?(r.originalMessage=r.message,r.message=N):r=new Error(N),r.shortMessage=E,r.command=i,r.escapedCommand=c,r.exitCode=s,r.signal=n,r.signalDescription=d,r.stdout=t,r.stderr=e,r.cwd=m,o!==void 0&&(r.all=o),"bufferedData"in r&&delete r.bufferedData,r.failed=!0,r.timedOut=!!l,r.isCanceled=u,r.killed=p&&!l,r},Fe=["stdin","stdout","stderr"],Hn=t=>Fe.some(e=>t[e]!==void 0),Un=t=>{if(!t)return;const{stdio:e}=t;if(e===void 0)return Fe.map(r=>t[r]);if(Hn(t))throw new Error(`It's not possible to provide \`stdio\` in combination with one of ${Fe.map(r=>`\`${r}\``).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 o=Math.max(e.length,Fe.length);return Array.from({length:o},(r,n)=>e[n])};var ne={exports:{}},De={exports:{}};De.exports;var Rr;function qn(){return Rr||(Rr=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")}(De)),De.exports}var I=O.process;const Z=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(!Z(I))ne.exports=function(){return function(){}};else{var zn=Zt,he=qn(),Kn=/^win/i.test(I.platform),Ge=er;typeof Ge!="function"&&(Ge=Ge.EventEmitter);var L;I.__signal_exit_emitter__?L=I.__signal_exit_emitter__:(L=I.__signal_exit_emitter__=new Ge,L.count=0,L.emitted={}),L.infinite||(L.setMaxListeners(1/0),L.infinite=!0),ne.exports=function(t,e){if(!Z(O.process))return function(){};zn.equal(typeof t,"function","a callback must be provided for exit handler"),ge===!1&&Or();var o="exit";e&&e.alwaysLast&&(o="afterexit");var r=function(){L.removeListener(o,t),L.listeners("exit").length===0&&L.listeners("afterexit").length===0&&yt()};return L.on(o,t),r};var yt=function(){!ge||!Z(O.process)||(ge=!1,he.forEach(function(e){try{I.removeListener(e,wt[e])}catch{}}),I.emit=vt,I.reallyExit=Lr,L.count-=1)};ne.exports.unload=yt;var ie=function(e,o,r){L.emitted[e]||(L.emitted[e]=!0,L.emit(e,o,r))},wt={};he.forEach(function(t){wt[t]=function(){if(Z(O.process)){var o=I.listeners(t);o.length===L.count&&(yt(),ie("exit",null,t),ie("afterexit",null,t),Kn&&t==="SIGHUP"&&(t="SIGINT"),I.kill(I.pid,t))}}}),ne.exports.signals=function(){return he};var ge=!1,Or=function(){ge||!Z(O.process)||(ge=!0,L.count+=1,he=he.filter(function(e){try{return I.on(e,wt[e]),!0}catch{return!1}}),I.emit=Yn,I.reallyExit=Wn)};ne.exports.load=Or;var Lr=I.reallyExit,Wn=function(e){Z(O.process)&&(I.exitCode=e||0,ie("exit",I.exitCode,null),ie("afterexit",I.exitCode,null),Lr.call(I,I.exitCode))},vt=I.emit,Yn=function(e,o){if(e==="exit"&&Z(O.process)){o!==void 0&&(I.exitCode=o);var r=vt.apply(this,arguments);return ie("exit",I.exitCode,null),ie("afterexit",I.exitCode,null),r}else return vt.apply(this,arguments)}}var Vn=ne.exports,Xn=re(Vn);const Jn=1e3*5,Qn=(t,e="SIGTERM",o={})=>{const r=t(e);return Zn(t,e,o,r),r},Zn=(t,e,o,r)=>{if(!ei(e,o,r))return;const n=ri(o),s=setTimeout(()=>{t("SIGKILL")},n);s.unref&&s.unref()},ei=(t,{forceKillAfterTimeout:e},o)=>ti(t)&&e!==!1&&o,ti=t=>t===Wo.constants.signals.SIGTERM||typeof t=="string"&&t.toUpperCase()==="SIGTERM",ri=({forceKillAfterTimeout:t=!0})=>{if(t===!0)return Jn;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},oi=(t,e)=>{t.kill()&&(e.isCanceled=!0)},si=(t,e,o)=>{t.kill(e),o(Object.assign(new Error("Timed out"),{timedOut:!0,signal:e}))},ni=(t,{timeout:e,killSignal:o="SIGTERM"},r)=>{if(e===0||e===void 0)return r;let n;const s=new Promise((c,l)=>{n=setTimeout(()=>{si(t,o,l)},e)}),i=r.finally(()=>{clearTimeout(n)});return Promise.race([s,i])},ii=({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})`)},ai=async(t,{cleanup:e,detached:o},r)=>{if(!e||o)return r;const n=Xn(()=>{t.kill()});return r.finally(()=>{n()})};function Tr(t){return t!==null&&typeof t=="object"&&typeof t.pipe=="function"}function Nr(t){return Tr(t)&&t.writable!==!1&&typeof t._write=="function"&&typeof t._writableState=="object"}const ci=t=>t instanceof zo&&typeof t.then=="function",bt=(t,e,o)=>{if(typeof o=="string")return t[e].pipe(Yo(o)),t;if(Nr(o))return t[e].pipe(o),t;if(!ci(o))throw new TypeError("The second argument must be a string, a stream or an Execa child process.");if(!Nr(o.stdin))throw new TypeError("The target child process's stdin must be available.");return t[e].pipe(o.stdin),o},li=t=>{t.stdout!==null&&(t.pipeStdout=bt.bind(void 0,t,"stdout")),t.stderr!==null&&(t.pipeStderr=bt.bind(void 0,t,"stderr")),t.all!==void 0&&(t.pipeAll=bt.bind(void 0,t,"all"))};var ye={exports:{}};const{PassThrough:mi}=st;var ui=t=>{t={...t};const{array:e}=t;let{encoding:o}=t;const r=o==="buffer";let n=!1;e?n=!(o||r):o=o||"utf8",r&&(o=null);const s=new mi({objectMode:n});o&&s.setEncoding(o);let i=0;const c=[];return s.on("data",l=>{c.push(l),n?i=c.length:i+=l.length}),s.getBufferedValue=()=>e?c:r?Buffer.concat(c,i):c.join(""),s.getBufferedLength=()=>i,s};const{constants:pi}=Xo,fi=st,{promisify:di}=tr,hi=ui,gi=di(fi.pipeline);class _r extends Error{constructor(){super("maxBuffer exceeded"),this.name="MaxBufferError"}}async function Ct(t,e){if(!t)throw new Error("Expected a stream");e={maxBuffer:1/0,...e};const{maxBuffer:o}=e,r=hi(e);return await new Promise((n,s)=>{const i=c=>{c&&r.getBufferedLength()<=pi.MAX_LENGTH&&(c.bufferedData=r.getBufferedValue()),s(c)};(async()=>{try{await gi(t,r),n()}catch(c){i(c)}})(),r.on("data",()=>{r.getBufferedLength()>o&&i(new _r)})}),r.getBufferedValue()}ye.exports=Ct,ye.exports.buffer=(t,e)=>Ct(t,{...e,encoding:"buffer"}),ye.exports.array=(t,e)=>Ct(t,{...e,array:!0}),ye.exports.MaxBufferError=_r;var yi=ye.exports,Fr=re(yi);const{PassThrough:wi}=st;var vi=function(){var t=[],e=new wi({objectMode:!0});return e.setMaxListeners(0),e.add=o,e.isEmpty=r,e.on("unpipe",n),Array.prototype.slice.call(arguments).forEach(o),e;function o(s){return Array.isArray(s)?(s.forEach(o),this):(t.push(s),s.once("end",n.bind(null,s)),s.once("error",e.emit.bind(e,"error")),s.pipe(e,{end:!1}),this)}function r(){return t.length==0}function n(s){t=t.filter(function(i){return i!==s}),!t.length&&e.readable&&e.end()}},bi=re(vi);const Ci=t=>{if(t!==void 0)throw new TypeError("The `input` and `inputFile` options cannot be both set.")},Pi=({input:t,inputFile:e})=>typeof e!="string"?t:(Ci(t),Vo(e)),$i=(t,e)=>{const o=Pi(e);o!==void 0&&(Tr(o)?o.pipe(t.stdin):t.stdin.end(o))},Ei=(t,{all:e})=>{if(!e||!t.stdout&&!t.stderr)return;const o=bi();return t.stdout&&o.add(t.stdout),t.stderr&&o.add(t.stderr),o},Pt=async(t,e)=>{if(!(!t||e===void 0)){t.destroy();try{return await e}catch(o){return o.bufferedData}}},$t=(t,{encoding:e,buffer:o,maxBuffer:r})=>{if(!(!t||!o))return e?Fr(t,{encoding:e,maxBuffer:r}):Fr.buffer(t,{maxBuffer:r})},xi=async({stdout:t,stderr:e,all:o},{encoding:r,buffer:n,maxBuffer:s},i)=>{const c=$t(t,{encoding:r,buffer:n,maxBuffer:s}),l=$t(e,{encoding:r,buffer:n,maxBuffer:s}),u=$t(o,{encoding:r,buffer:n,maxBuffer:s*2});try{return await Promise.all([i,c,l,u])}catch(p){return Promise.all([{error:p,signal:p.signal,timedOut:p.timedOut},Pt(t,c),Pt(e,l),Pt(o,u)])}},Ai=(async()=>{})().constructor.prototype,Si=["then","catch","finally"].map(t=>[t,Reflect.getOwnPropertyDescriptor(Ai,t)]),Dr=(t,e)=>{for(const[o,r]of Si){const n=typeof e=="function"?(...s)=>Reflect.apply(r.value,e(),s):r.value.bind(e);Reflect.defineProperty(t,o,{...r,value:n})}},ki=t=>new Promise((e,o)=>{t.on("exit",(r,n)=>{e({exitCode:r,signal:n})}),t.on("error",r=>{o(r)}),t.stdin&&t.stdin.on("error",r=>{o(r)})}),Gr=(t,e=[])=>Array.isArray(e)?[t,...e]:[t],Mi=/^[\w.-]+$/,Ii=/"/g,Ri=t=>typeof t!="string"||Mi.test(t)?t:`"${t.replace(Ii,'\\"')}"`,Oi=(t,e)=>Gr(t,e).join(" "),Li=(t,e)=>Gr(t,e).map(o=>Ri(o)).join(" "),Ti=Jo("execa").enabled,je=(t,e)=>String(t).padStart(e,"0"),Ni=()=>{const t=new Date;return`${je(t.getHours(),2)}:${je(t.getMinutes(),2)}:${je(t.getSeconds(),2)}.${je(t.getMilliseconds(),3)}`},_i=(t,{verbose:e})=>{e&&U.stderr.write(`[${Ni()}] ${t}
`)},Fi=1e3*1e3*100,Di=({env:t,extendEnv:e,preferLocal:o,localDir:r,execPath:n})=>{const s=e?{...U.env,...t}:t;return o?Pn({env:s,cwd:r,execPath:n}):s},Gi=(t,e,o={})=>{const r=yn._parse(t,e,o);return t=r.command,e=r.args,o=r.options,o={maxBuffer:Fi,buffer:!0,stripFinalNewline:!0,extendEnv:!0,preferLocal:!1,localDir:o.cwd||U.cwd(),execPath:U.execPath,encoding:"utf8",reject:!0,cleanup:!0,all:!1,windowsHide:!0,verbose:Ti,...o},o.env=Di(o),o.stdio=Un(o),U.platform==="win32"&&te.basename(t,".exe")==="cmd"&&e.unshift("/q"),{file:t,args:e,options:o,parsed:r}},Et=(t,e,o)=>typeof e!="string"&&!qo.isBuffer(e)?o===void 0?void 0:"":t.stripFinalNewline?wn(e):e;function X(t,e,o){const r=Gi(t,e,o),n=Oi(t,e),s=Li(t,e);_i(s,r.options),ii(r.options);let i;try{i=Xt.spawn(r.file,r.args,r.options)}catch(d){const h=new Xt.ChildProcess,g=Promise.reject(Ir({error:d,stdout:"",stderr:"",all:"",command:n,escapedCommand:s,parsed:r,timedOut:!1,isCanceled:!1,killed:!1}));return Dr(h,g),h}const c=ki(i),l=ni(i,r.options,c),u=ai(i,r.options,l),p={isCanceled:!1};i.kill=Qn.bind(null,i.kill.bind(i)),i.cancel=oi.bind(null,i,p);const m=Ar(async()=>{const[{error:d,exitCode:h,signal:g,timedOut:y},v,E,N]=await xi(i,r.options,u),K=Et(r.options,v),W=Et(r.options,E),fe=Et(r.options,N);if(d||h!==0||g!==null){const V=Ir({error:d,exitCode:h,signal:g,stdout:K,stderr:W,all:fe,command:n,escapedCommand:s,parsed:r,timedOut:y,isCanceled:p.isCanceled||(r.options.signal?r.options.signal.aborted:!1),killed:i.killed});if(!r.options.reject)return V;throw V}return{command:n,escapedCommand:s,exitCode:0,stdout:K,stderr:W,all:fe,failed:!1,timedOut:!1,isCanceled:!1,killed:!1}});return $i(i,r.options),i.all=Ei(i,r.options),li(i),Dr(i,m),i}class R{static create(e,o){return new e(o)}}const{hasOwnProperty:xt}=Object.prototype,Be=typeof process<"u"&&process.platform==="win32"?`\r
`:`
`,At=(t,e)=>{const o=[];let r="";typeof e=="string"?e={section:e,whitespace:!1}:(e=e||Object.create(null),e.whitespace=e.whitespace===!0);const n=e.whitespace?" = ":"=";for(const s of Object.keys(t)){const i=t[s];if(i&&Array.isArray(i))for(const c of i)r+=ae(s+"[]")+n+ae(c)+Be;else i&&typeof i=="object"?o.push(s):r+=ae(s)+n+ae(i)+Be}e.section&&r.length&&(r="["+ae(e.section)+"]"+Be+r);for(const s of o){const i=jr(s).join("\\."),c=(e.section?e.section+".":"")+i,{whitespace:l}=e,u=At(t[s],{section:c,whitespace:l});r.length&&u.length&&(r+=Be),r+=u}return r},jr=t=>t.replace(/\1/g,"LITERAL\\1LITERAL").replace(/\\\./g,"").split(/\./).map(e=>e.replace(/\1/g,"\\.").replace(/\2LITERAL\\1LITERAL\2/g,"")),Br=t=>{const e=Object.create(null);let o=e,r=null;const n=/^\[([^\]]*)\]$|^([^=]+)(=(.*))?$/i,s=t.split(/[\r\n]+/g);for(const c of s){if(!c||c.match(/^\s*[;#]/))continue;const l=c.match(n);if(!l)continue;if(l[1]!==void 0){if(r=He(l[1]),r==="__proto__"){o=Object.create(null);continue}o=e[r]=e[r]||Object.create(null);continue}const u=He(l[2]),p=u.length>2&&u.slice(-2)==="[]",a=p?u.slice(0,-2):u;if(a==="__proto__")continue;const m=l[3]?He(l[4]):!0,d=m==="true"||m==="false"||m==="null"?JSON.parse(m):m;p&&(xt.call(o,a)?Array.isArray(o[a])||(o[a]=[o[a]]):o[a]=[]),Array.isArray(o[a])?o[a].push(d):o[a]=d}const i=[];for(const c of Object.keys(e)){if(!xt.call(e,c)||typeof e[c]!="object"||Array.isArray(e[c]))continue;const l=jr(c);o=e;const u=l.pop(),p=u.replace(/\\\./g,".");for(const a of l)a!=="__proto__"&&((!xt.call(o,a)||typeof o[a]!="object")&&(o[a]=Object.create(null)),o=o[a]);o===e&&p===u||(o[p]=e[c],i.push(c))}for(const c of i)delete e[c];return e},Hr=t=>t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'"),ae=t=>typeof t!="string"||t.match(/[=\r\n]/)||t.match(/^\[/)||t.length>1&&Hr(t)||t!==t.trim()?JSON.stringify(t):t.split(";").join("\\;").split("#").join("\\#"),He=(t,e)=>{if(t=(t||"").trim(),Hr(t)){t.charAt(0)==="'"&&(t=t.slice(1,-1));try{t=JSON.parse(t)}catch{}}else{let o=!1,r="";for(let n=0,s=t.length;n<s;n++){const i=t.charAt(n);if(o)"\\;#".indexOf(i)!==-1?r+=i:r+="\\"+i,o=!1;else{if(";#".indexOf(i)!==-1)break;i==="\\"?o=!0:r+=i}}return o&&(r+="\\"),r.trim()}return t};var ji={parse:Br,decode:Br,stringify:At,encode:At,safe:ae,unsafe:He},ce=re(ji);class C extends Error{}const St=" ",ee=t=>{t instanceof Error&&(t instanceof C||(t.stack&&console.error(w.dim(t.stack.split(`
`).slice(1).join(`
`))),console.error(`
${St}${w.dim(`aicommit2 v${lr}`)}`),console.error(`
${St}Please open a Bug report with the information above:`),console.error(`${St}https://github.com/tak-bro/aicommit2/issues/new/choose`)))},Ur=t=>x.lstat(t).then(()=>!0,()=>!1),qr=async t=>{try{await x.mkdir(t,{recursive:!0})}catch(e){if(e.code!=="EEXIST")throw e}},Ue=t=>t&&`${t[0].toUpperCase()}${t.slice(1)}`,qe=(t,e)=>{const o=Math.ceil(t),r=Math.floor(e);return Math.floor(Math.random()*(r-o+1))+o},Bi=(t,e)=>t.disabled&&!e.disabled?1:!t.disabled&&e.disabled?-1:0,ze=t=>t.reduce((e,o)=>Array.isArray(o)?e.concat(ze(o)):e.concat(o),[]),zr=(t,e=5)=>t.replace(/[\n\r]/g,"").split(" ").slice(0,e).join(" "),Hi=t=>{let e=0;for(let o=0;o<t.length;o++){const r=t.charCodeAt(o);e=(e<<5)-e+r,e=e&e}return Math.abs(e)},Ui=t=>{const e=t%360,o=65+t%15,r=45+t%10;return`hsl(${e}, ${o}%, ${r}%)`},qi=t=>{const[e,o,r]=t.match(/\d+/g).map((a,m)=>m===0?Number(a):Number(a)/100),n=(1-Math.abs(2*r-1))*o,s=n*(1-Math.abs(e/60%2-1)),i=r-n/2;let c,l,u;e<60?[c,l,u]=[n,s,0]:e<120?[c,l,u]=[s,n,0]:e<180?[c,l,u]=[0,n,s]:e<240?[c,l,u]=[0,s,n]:e<300?[c,l,u]=[s,0,n]:[c,l,u]=[n,0,s];const p=a=>{const m=Math.round((a+i)*255).toString(16);return m.length===1?"0"+m:m};return`#${p(c)}${p(l)}${p(u)}`},zi=t=>{const e=Hi(t),o=Ui(e);return{primary:qi(o),secondary:"#FFFFFF"}},Ki=t=>{try{return{ok:!0,data:JSON.parse(t)}}catch(e){return{ok:!1,error:e}}},Ke=t=>{if(!t||typeof t!="string")return"";if(P.isAbsolute(t))return P.resolve(t);if(ve){const e=P.dirname(ve),o=P.join(e,t);return P.resolve(o)}else return""},Wi=["","conventional","gitmoji"],kt="http://localhost:11434",{hasOwnProperty:Yi}=Object.prototype,Mt=(t,e)=>Yi.call(t,e),le=["OPENAI","OLLAMA","HUGGINGFACE","GEMINI","ANTHROPIC","MISTRAL","CODESTRAL","COHERE","GROQ","PERPLEXITY","DEEPSEEK"],Kr=t=>{const e=Re.platform(),o=Re.homedir();let r,n;switch(t){case"config":r=process.env.XDG_CONFIG_HOME;break;case"data":r=process.env.XDG_DATA_HOME;break;case"cache":r=process.env.XDG_CACHE_HOME;break;case"state":r=process.env.XDG_STATE_HOME;break;default:r=void 0}if(e==="darwin")t==="cache"?n=P.join(o,"Library","Caches"):n=P.join(o,"Application Support");else if(e==="win32")n=process.env.LOCALAPPDATA||o;else switch(t){case"config":n=P.join(o,".config");break;case"data":n=P.join(o,".local","share");break;case"cache":n=P.join(o,".cache");break;case"state":n=P.join(o,".local","state");break;default:n=o}return r||n},Vi=P.join(Kr("config"),"aicommit2"),We=P.join(Kr("state"),"aicommit2","logs"),Wr=P.join(Vi,"config.ini"),Yr=P.join(We,"aicommit2-%DATE%.log"),Vr=P.join(We,"exceptions-%DATE%.log"),Xi=t=>{const e=Object.keys(t),o=new Set([...le,...e.filter(r=>/^[A-Z][A-Z0-9_]*$/.test(r))]);return Array.from(o)},b=(t,e,o)=>{if(!e)throw new C(`Invalid config property ${t}: ${o}`)},f={systemPrompt(t){return t||""},systemPromptPath(t){return t||""},codeReviewPromptPath(t){return t||""},timeout(t){if(!t)return 1e4;b("timeout",/^\d+$/.test(t),"Must be an integer");const e=Number(t);return b("timeout",e>=500,"Must be greater than 500ms"),e},temperature(t){if(!t)return .7;b("temperature",/^(2|\d)(\.\d{1,2})?$/.test(t),"Must be decimal between 0 and 2");const e=Number(t);return b("temperature",e>0,"Must be greater than 0"),b("temperature",e<=2,"Must be less than or equal to 2"),e},maxTokens(t){return t?(b("maxTokens",/^\d+$/.test(t),"Must be an integer"),Number(t)):1024},logging(t){return typeof t=="boolean"?t:t==null?!0:(b("logging",/^(?:true|false)$/.test(t),"Must be a boolean(true or false)"),t==="true")},logLevel(t){return t?(b("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||Yr},exceptionLogFilePath(t){return t||Vr},locale(t){return t?(b("locale",t,"Cannot be empty"),b("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;b("generate",/^\d+$/.test(t),"Must be an integer");const e=Number(t);return b("generate",e>0,"Must be greater than 0"),b("generate",e<=5,"Must be less or equal to 5"),e},type(t){return t?(b("type",Wi.includes(t),"Invalid commit type"),t):"conventional"},maxLength(t){if(!t)return 50;b("maxLength",/^\d+$/.test(t),"Must be an integer");const e=Number(t);return b("maxLength",e>=20,"Must be greater than 20 characters"),e},includeBody(t){return typeof t=="boolean"?t:t==null?!1:(b("includeBody",/^(?:true|false)$/.test(t),"Must be a boolean(true or false)"),t==="true")},exclude:t=>t?(typeof t=="string"?t?.split(","):t).map(o=>o.trim()).filter(o=>!!o&&o.length>0):[],topP:t=>{if(!t)return .9;b("topP",/^(1|\d)(\.\d{1,2})?$/.test(t),"Must be decimal between 0 and 1");const e=Number(t);return b("topP",e>0,"Must be greater than 0"),b("topP",e<=1,"Must be less than or equal to 1"),e},codeReview(t){return typeof t=="boolean"?t:t==null?!1:(b("codeReview",/^(?:true|false)$/.test(t),"Must be a boolean(true or false)"),t==="true")},disabled(t){return typeof t=="boolean"?t:t==null?!1:(b("disabled",/^(?:true|false)$/.test(t),"Must be a boolean(true or false)"),t==="true")},watchMode(t){return typeof t=="boolean"?t:t==null?!1:(b("watchMode",/^(?:true|false)$/.test(t),"Must be a boolean(true or false)"),t==="true")}},we={OPENAI:{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):["gpt-4o-mini"],url:t=>t?(b("OPENAI.url",/^https?:\/\//.test(t),"Must be a valid URL"),t):"https://api.openai.com",path:t=>t||"/v1/chat/completions",proxy:t=>t||"",topP:f.topP,systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,timeout:f.timeout,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode},HUGGINGFACE:{cookie:t=>t||"",model:t=>{if(!t)return["CohereForAI/c4ai-command-r-plus"];const e=typeof t=="string"?t?.split(","):t,o=["CohereForAI/c4ai-command-r-plus","meta-llama/Meta-Llama-3-70B-Instruct","HuggingFaceH4/zephyr-orpo-141b-A35b-v0.1","mistralai/Mixtral-8x7B-Instruct-v0.1","NousResearch/Nous-Hermes-2-Mixtral-8x7B-DPO","01-ai/Yi-1.5-34B-Chat","mistralai/Mistral-7B-Instruct-v0.2","microsoft/Phi-3-mini-4k-instruct"];for(const r of e)b("HUGGINGFACE.model",o.includes(r.trim()),`Invalid model type of HuggingFace chat: ${r.trim()}`);return e.map(r=>r.trim()).filter(r=>!!r&&r.length>0)},systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode},GEMINI:{key:t=>t||"",envKey:t=>t||"",model:t=>{if(!t)return["gemini-2.0-flash"];const e=typeof t=="string"?t?.split(","):t,o=["gemini-2.5-flash-preview-04-17","gemini-2.5-flash-preview-05-20","gemini-2.5-pro-preview-05-06","gemini-2.0-flash","gemini-2.0-flash-lite","gemini-2.0-flash-preview-image-generation","gemini-1.5-pro","gemini-1.5-flash","gemini-1.5-flash-8b"];for(const r of e)b("GEMINI.model",o.includes(r.trim()),`Invalid model type of Gemini: ${r.trim()}`);return e.map(r=>r.trim()).filter(r=>!!r&&r.length>0)},systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,topP:f.topP,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode},ANTHROPIC:{key:t=>t||"",envKey:t=>t||"",model:t=>{if(!t)return["claude-3-5-haiku-20241022"];const e=typeof t=="string"?t?.split(","):t,o=["claude-opus-4-20250514","claude-sonnet-4-20250514","claude-3-7-sonnet-20250219","claude-3-5-sonnet-20241022","claude-3-5-haiku-20241022","claude-3-opus-20240229","claude-3-sonnet-20240229","claude-3-haiku-20240307"];for(const r of e)b("ANTHROPIC.model",o.includes(r.trim()),`Invalid model type of Anthropic: ${r.trim()}`);return e.map(r=>r.trim()).filter(r=>!!r&&r.length>0)},systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,topP:f.topP,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode},MISTRAL:{key:t=>t||"",envKey:t=>t||"",model:t=>{if(!t)return["pixtral-12b-2409"];const e=typeof t=="string"?t?.split(","):t,o=["codestral-latest","mistral-large-latest","pixtral-large-latest","ministral-8b-latest","mistral-small-latest","mistral-embed","mistral-moderation-latest"];for(const r of e)b("MISTRAL.model",o.includes(r.trim()),`Invalid model type of Mistral AI: ${r.trim()}`);return e.map(r=>r.trim()).filter(r=>!!r&&r.length>0)},systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,timeout:f.timeout,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,topP:f.topP,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode},CODESTRAL:{key:t=>t||"",envKey:t=>t||"",model:t=>{if(!t)return["codestral-latest"];const e=typeof t=="string"?t?.split(","):t,o=["codestral-latest","codestral-2501"];for(const r of e)b("CODESTRAL.model",o.includes(r.trim()),`Invalid model type of Codestral: ${r.trim()}`);return e.map(r=>r.trim()).filter(r=>!!r&&r.length>0)},topP:f.topP,systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,timeout:f.timeout,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode},OLLAMA:{model:t=>t?(typeof t=="string"?t?.split(","):t).map(o=>o.trim()).filter(o=>!!o&&o.length>0):[],host:t=>t?(b("OLLAMA.host",/^https?:\/\//.test(t),"Must be a valid URL"),t):kt,timeout:t=>{if(!t)return 1e5;b("OLLAMA.timeout",/^\d+$/.test(t),"Must be an integer");const e=Number(t);return b("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;b("OLLAMA.numCtx",/^\d+$/.test(t),"Must be an integer");const e=Number(t);return b("OLLAMA.numCtx",e>=2048,"Must be greater than 2048"),e},systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,topP:f.topP,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode},COHERE:{key:t=>t||"",envKey:t=>t||"",model:t=>{if(!t)return["command"];const e=typeof t=="string"?t?.split(","):t,o=["command-r7b-12-2024","command-r-plus-08-2024","command-r-plus-04-2024","command-r-plus","command-r-08-2024","command-r-03-2024","command-r","command","command-nightly","command-light","command-light-nightly","c4ai-aya-expanse-8b","c4ai-aya-expanse-32b"];for(const r of e)b("COHERE.model",o.includes(r.trim()),`Invalid model type of Cohere: ${r.trim()}`);return e.map(r=>r.trim()).filter(r=>!!r&&r.length>0)},systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,topP:f.topP,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode},GROQ:{key:t=>t||"",envKey:t=>t||"",model:t=>{if(!t)return["llama-3.3-70b-versatile"];const e=typeof t=="string"?t?.split(","):t,o=["allam-2-7b","compound-beta","compound-beta-mini","deepseek-r1-distill-llama-70b","distil-whisper-large-v3-en","gemma2-9b-it","llama-3.1-8b-instant","llama-3.3-70b-versatile","llama-guard-3-8b","llama3-70b-8192","llama3-8b-8192","meta-llama/llama-4-maverick-17b-128e-instruct","meta-llama/llama-4-scout-17b-16e-instruct","mistral-saba-24b","playai-tts","playai-tts-arabic","qwen-qwq-32b","whisper-large-v3","whisper-large-v3-turbo"];for(const r of e)b("GROQ.model",o.includes(r.trim()),`Invalid model type of Groq: ${r.trim()}`);return e.map(r=>r.trim()).filter(r=>!!r&&r.length>0)},systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,timeout:f.timeout,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,topP:f.topP,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode},PERPLEXITY:{key:t=>t||"",model:t=>{if(!t)return["sonar"];const e=typeof t=="string"?t?.split(","):t,o=["sonar-pro","sonar","llama-3.1-sonar-small-128k-online","llama-3.1-sonar-large-128k-online","llama-3.1-sonar-huge-128k-online"];for(const r of e)b("PERPLEXITY.model",o.includes(r.trim()),`Invalid model type of Perplexity: ${r.trim()}`);return e.map(r=>r.trim()).filter(r=>!!r&&r.length>0)},topP:f.topP,systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,timeout:f.timeout,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode},DEEPSEEK:{key:t=>t||"",envKey:t=>t||"",model:t=>{if(!t)return["deepseek-chat"];const e=typeof t=="string"?t?.split(","):t,o=["deepseek-reasoner","deepseek-chat"];for(const r of e)b("DEEPSEEK.model",o.includes(r.trim()),`Invalid model type of DeepSeek: ${r.trim()}`);return e.map(r=>r.trim()).filter(r=>!!r&&r.length>0)},topP:f.topP,systemPrompt:f.systemPrompt,systemPromptPath:f.systemPromptPath,codeReviewPromptPath:f.codeReviewPromptPath,timeout:f.timeout,temperature:f.temperature,maxTokens:f.maxTokens,logging:f.logging,locale:f.locale,generate:f.generate,type:f.type,maxLength:f.maxLength,includeBody:f.includeBody,codeReview:f.codeReview,disabled:f.disabled,watchMode:f.watchMode}};let ve;const Ji=(t=[])=>{const e={};for(const o of t)if(o.startsWith("--")){const[r,n]=o.slice(2).split("="),[s,i]=r.split(".");s&&i&&s in we?(e[s]||(e[s]={}),e[s][i]=n):e[r]=n}return e},Qi=()=>{const t=Re.homedir(),e=process.env.AICOMMIT_CONFIG_PATH,o=Wr,r=P.join(t,".aicommit2");return[e,o,r].filter(n=>!!n)},me=async()=>{const t=Qi();for(const e of t)if(await Ur(e))return e;return Wr},be=async()=>{const t=await me();ve=t;try{const e=await x.readFile(t,"utf8");return ce.parse(e)}catch(e){return e.code==="ENOENT"?(ve=void 0,{}):(console.error(`Error reading config file ${t}:`,e),ve=void 0,{})}},ue=async(t,e=[])=>{const o=await be(),r=Ji(e),n={...t,...r},s={},i=Xi(o),c={};for(const u of i){const a=o[u]?.envKey||`${u}_API_KEY`,m=process.env[a];m&&(c[u]={key:m})}const l=(u,p)=>{const a=n[`${u}.${p}`]??n[u]?.[p],m=c[u]?.[p],d=o[u]?.[p],h=n[p]??o[p];return a!==void 0?a:m!==void 0?m:d!==void 0?d:h};for(const[u,p]of Object.entries(f)){const a=n[u]??o[u];s[u]=p(a)}for(const u of i){s[u]={};const p=we[u]||Ye(u);for(const[a,m]of Object.entries(p)){const d=l(u,a);s[u][a]=m(d)}}return s},Zi=async t=>{const e=await be();for(const[n,s]of t){const[i,c]=n.split(".");if(!c){const p=f[n];if(!p)throw new C(`Invalid config property: ${n}`);e[n]=p(s);continue}if(e[i]||(e[i]={}),le.includes(i)){const p=we[i][c];if(!p)throw new C(`Invalid config property: ${n}`);e[i][c]=p(s);continue}if(!/^[A-Z][A-Z0-9_]*$/.test(i))throw new C(`Invalid service name: ${i}. Service names must be uppercase letters, numbers, and underscores.`);const u=Ye(i);if(!u[c])throw new C(`Invalid config property for custom service: ${n}`);try{e[i][c]=u[c](s)}catch(p){throw p instanceof C?p:new C(`Invalid value for ${n}: ${p.message}`)}}const o=await me(),r=P.dirname(o);await x.mkdir(r,{recursive:!0}),await x.writeFile(o,ce.stringify(e),"utf8")},ea=async t=>{const e=await be();for(const[n,s]of t){const[i,c]=n.split("."),l=e[i];if(c==="model"){l||(e[i]={});const p=e[i][c]||[],a=typeof s=="string"?s.split(",").map(m=>m.trim()).filter(m=>!!m):s;e[i][c]=ze([...p,...a]);continue}if(l&&l.compatible===!0){l||(e[i]={});const p=Ye(i);if(!p[c])throw new C(`Invalid config property: ${n}`);try{e[i][c]=p[c](s)}catch(a){throw a instanceof C?a:new C(`Invalid value for ${n}: ${a.message}`)}continue}if(i in we){l||(e[i]={});const p=we[i][c];if(!p)throw new C(`Invalid config property: ${n}`);e[i][c]=p(s)}else{const p=Ye(i);if(!p[c])throw new C(`Invalid config property: ${n}`);e[i]||(e[i]={}),e[i][c]=p[c](s)}}const o=await me(),r=P.dirname(o);await x.mkdir(r,{recursive:!0}),await x.writeFile(o,ce.stringify(e),"utf8")},ta=async()=>{const t=await be();console.log(ce.stringify(t))},ra=async()=>{console.log(await me())},Ye=t=>({compatible:e=>typeof e=="boolean"?e:e==null?!1:(b("compatible",/^(?:true|false)$/.test(e),"Must be a boolean(true or false)"),e==="true"),stream:e=>typeof e=="boolean"?e:e==null?!1:(b("stream",/^(?:true|false)$/.test(e),"Must be a boolean(true or false)"),e==="true"),url:e=>e?(b(`${t}.url`,/^https?:\/\//.test(e),"Must be a valid URL"),e):"",path:e=>e||""