aicommit2 2.5.4 → 2.5.6

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