aicommit2 2.5.14 → 2.5.16

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 (22) hide show
  1. package/dist/{ai.service-47363f49.mjs → ai.service-8e59106d.mjs} +2 -2
  2. package/dist/{anthropic.service-07f000b2.mjs → anthropic.service-cdd97556.mjs} +1 -1
  3. package/dist/{bedrock.service-bb73b18d.mjs → bedrock.service-3487fda6.mjs} +1 -1
  4. package/dist/{cli-fd2479d5.mjs → cli-6be3c9c1.mjs} +95 -85
  5. package/dist/cli.mjs +1 -1
  6. package/dist/{codestral.service-1f018db8.mjs → codestral.service-cf085c39.mjs} +1 -1
  7. package/dist/{cohere.service-792231bd.mjs → cohere.service-2b555628.mjs} +1 -1
  8. package/dist/copilot-sdk.service-0775d505.mjs +5 -0
  9. package/dist/{deep-seek.service-18bf8bbd.mjs → deep-seek.service-f7f29cf5.mjs} +1 -1
  10. package/dist/{gemini.service-680451fb.mjs → gemini.service-25c72218.mjs} +1 -1
  11. package/dist/{github-models.service-c47a9246.mjs → github-models.service-5d43907f.mjs} +3 -3
  12. package/dist/{groq.service-b9970eb4.mjs → groq.service-f7770363.mjs} +1 -1
  13. package/dist/{hugging-face.service-370921e2.mjs → hugging-face.service-f7dcc31e.mjs} +1 -1
  14. package/dist/{mistral.service-2d118a9c.mjs → mistral.service-7a073354.mjs} +1 -1
  15. package/dist/{ollama.service-516cd32f.mjs → ollama.service-aa773594.mjs} +1 -1
  16. package/dist/{openai-compatible.service-3cda8bb5.mjs → openai-compatible.service-3da32dc7.mjs} +1 -1
  17. package/dist/{openai-c3c69b49.mjs → openai-e41e415b.mjs} +1 -1
  18. package/dist/{openai.service-41f8df31.mjs → openai.service-663ad5da.mjs} +1 -1
  19. package/dist/{openrouter.service-ac2ba1cb.mjs → openrouter.service-f6552be3.mjs} +1 -1
  20. package/dist/{perplexity.service-29e7b048.mjs → perplexity.service-f582f58e.mjs} +1 -1
  21. package/package.json +2 -2
  22. package/dist/copilot-sdk.service-3ce57b3e.mjs +0 -5
@@ -1,43 +1,43 @@
1
- import{command as F,cli as is}from"cleye";import{createRequire as as}from"module";import cs from"crypto";import j from"fs";import ke from"os";import v from"path";import{Buffer as ln}from"node:buffer";import te from"node:path";import ut,{ChildProcess as un,exec as ls}from"node:child_process";import B from"node:process";import us,{execSync as ye,exec as ds}from"child_process";import{fileURLToPath as dn}from"node:url";import ms,{constants as mn}from"node:os";import fs from"assert";import ps from"events";import{createWriteStream as hs,createReadStream as gs,readFileSync as ys}from"node:fs";import ws from"buffer";import dt from"stream";import Cs,{promisify as bs}from"util";import{debuglog as Es,promisify as vs}from"node:util";import T from"inquirer";import{from as Le,switchMap as fn,of as Ps,tap as As,mergeMap as pn,catchError as xs,BehaviorSubject as hn,ReplaySubject as $s,Subscription as mt,lastValueFrom as ft,toArray as pt,filter as gn,map as yn,Subject as Ss}from"rxjs";import I from"fs/promises";import h from"chalk";import Me from"readline";import wn from"figlet";import Rs from"gradient-string";import Cn from"ora";import Is from"inquirer-reactive-list-prompt";import H from"winston";import"winston-daily-rotate-file";import ks from"axios";import{fileURLToPath as Ls,pathToFileURL as Ms}from"url";import{readdir as bn,stat as Ts,rm as Os}from"node:fs/promises";import Ds from"chokidar";import{takeUntil as En,finalize as vn}from"rxjs/operators";var Ns="aicommit2",Pn="2.5.14",_s="A Reactive CLI that generates commit messages for Git and Jujutsu with various AI",js=["cli","ai","git","jujutsu","jj","vcs","version-control","commit","git-commit","jujutsu-commit","command-line","commandline","aipick","aicommit","aicommits","aicommit2","openai","huggingface","anthropic","claude","claude3","gemini","gemini-pro","generative-ai","mistral","ollama","llama3","llama3.2","llama3.3","gemma","llm","chatgpt","cohere","groq","codestral","perplexity","deepseek","deepseek-r1","pre-commit"],Fs="MIT",Gs="tak-bro/aicommit2",Bs="Hyungtak Jin(@tak-bro)",Hs="module",Us=["dist"],Ks={aicommit2:"./dist/cli.mjs",aic2:"./dist/cli.mjs"},Ws={prepare:"simple-git-hooks",build:"pkgroll --minify",lint:"eslint --cache .","type-check":"tsc",test:"tsx tests",prepack:"pnpm build && clean-pkg-json",prettier:"prettier"},qs={"@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"},zs={"@github/copilot-sdk":"0.2.0"},Ys={"@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"},Vs={extends:["@pvtnbr","prettier"],rules:{"unicorn/no-process-exit":"off"},overrides:[{files:"./src/commands/prepare-commit-msg-hook.ts",rules:{"unicorn/prevent-abbreviations":"off"}}]},Js={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"]},Xs={name:Ns,version:Pn,description:_s,keywords:js,license:Fs,repository:Gs,author:Bs,type:Hs,files:Us,bin:Ks,scripts:Ws,"simple-git-hooks":{"pre-commit":"pnpm lint-staged"},"lint-staged":{"*.ts":["prettier --config ./.prettierrc --write","eslint --fix"]},dependencies:qs,optionalDependencies:zs,devDependencies:Ys,eslintConfig:Vs,release:Js},ht=as(import.meta.url),V=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function se(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var re={exports:{}},gt,An;function Qs(){if(An)return gt;An=1,gt=o,o.sync=s;var e=j;function t(r,a){var c=a.pathExt!==void 0?a.pathExt:process.env.PATHEXT;if(!c||(c=c.split(";"),c.indexOf("")!==-1))return!0;for(var 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,a,c){return!r.isSymbolicLink()&&!r.isFile()?!1:t(a,c)}function o(r,a,c){e.stat(r,function(u,l){c(u,u?!1:n(l,r,a))})}function s(r,a){return n(e.statSync(r),r,a)}return gt}var yt,xn;function Zs(){if(xn)return yt;xn=1,yt=t,t.sync=n;var e=j;function t(r,a,c){e.stat(r,function(u,l){c(u,u?!1:o(l,a))})}function n(r,a){return o(e.statSync(r),a)}function o(r,a){return r.isFile()&&s(r,a)}function s(r,a){var c=r.mode,u=r.uid,l=r.gid,d=a.uid!==void 0?a.uid:process.getuid&&process.getuid(),f=a.gid!==void 0?a.gid:process.getgid&&process.getgid(),g=parseInt("100",8),y=parseInt("010",8),m=parseInt("001",8),x=g|y,$=c&m||c&y&&l===f||c&g&&u===d||c&x&&d===0;return $}return yt}var Te;process.platform==="win32"||V.TESTING_WINDOWS?Te=Qs():Te=Zs();var er=wt;wt.sync=tr;function wt(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){wt(e,t||{},function(r,a){r?s(r):o(a)})})}Te(e,t||{},function(o,s){o&&(o.code==="EACCES"||t&&t.ignoreErrors)&&(o=null,s=!1),n(o,s)})}function tr(e,t){try{return Te.sync(e,t||{})}catch(n){if(t&&t.ignoreErrors||n.code==="EACCES")return!1;throw n}}const ie=process.platform==="win32"||process.env.OSTYPE==="cygwin"||process.env.OSTYPE==="msys",$n=v,nr=ie?";":":",Sn=er,Rn=e=>Object.assign(new Error(`not found: ${e}`),{code:"ENOENT"}),In=(e,t)=>{const n=t.colon||nr,o=e.match(/\//)||ie&&e.match(/\\/)?[""]:[...ie?[process.cwd()]:[],...(t.path||process.env.PATH||"").split(n)],s=ie?t.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",r=ie?s.split(n):[""];return ie&&e.indexOf(".")!==-1&&r[0]!==""&&r.unshift(""),{pathEnv:o,pathExt:r,pathExtExe:s}},kn=(e,t,n)=>{typeof t=="function"&&(n=t,t={}),t||(t={});const{pathEnv:o,pathExt:s,pathExtExe:r}=In(e,t),a=[],c=l=>new Promise((d,f)=>{if(l===o.length)return t.all&&a.length?d(a):f(Rn(e));const g=o[l],y=/^".*"$/.test(g)?g.slice(1,-1):g,m=$n.join(y,e),x=!y&&/^\.[\\\/]/.test(e)?e.slice(0,2)+m:m;d(u(x,l,0))}),u=(l,d,f)=>new Promise((g,y)=>{if(f===s.length)return g(c(d+1));const m=s[f];Sn(l+m,{pathExt:r},(x,$)=>{if(!x&&$)if(t.all)a.push(l+m);else return g(l+m);return g(u(l,d,f+1))})});return n?c(0).then(l=>n(null,l),n):c(0)},or=(e,t)=>{t=t||{};const{pathEnv:n,pathExt:o,pathExtExe:s}=In(e,t),r=[];for(let a=0;a<n.length;a++){const c=n[a],u=/^".*"$/.test(c)?c.slice(1,-1):c,l=$n.join(u,e),d=!u&&/^\.[\\\/]/.test(e)?e.slice(0,2)+l:l;for(let f=0;f<o.length;f++){const g=d+o[f];try{if(Sn.sync(g,{pathExt:s}))if(t.all)r.push(g);else return g}catch{}}}if(t.all&&r.length)return r;if(t.nothrow)return null;throw Rn(e)};var sr=kn;kn.sync=or;var Ct={exports:{}};const Ln=(e={})=>{const t=e.env||process.env;return(e.platform||process.platform)!=="win32"?"PATH":Object.keys(t).reverse().find(o=>o.toUpperCase()==="PATH")||"Path"};Ct.exports=Ln,Ct.exports.default=Ln;var rr=Ct.exports;const Mn=v,ir=sr,ar=rr;function Tn(e,t){const n=e.options.env||process.env,o=process.cwd(),s=e.options.cwd!=null,r=s&&process.chdir!==void 0&&!process.chdir.disabled;if(r)try{process.chdir(e.options.cwd)}catch{}let a;try{a=ir.sync(e.command,{path:n[ar({env:n})],pathExt:t?Mn.delimiter:void 0})}catch{}finally{r&&process.chdir(o)}return a&&(a=Mn.resolve(s?e.options.cwd:"",a)),a}function cr(e){return Tn(e)||Tn(e,!0)}var lr=cr,bt={};const Et=/([()\][%!^"`<>&|;, *?])/g;function ur(e){return e=e.replace(Et,"^$1"),e}function dr(e,t){return e=`${e}`,e=e.replace(/(?=(\\+?)?)\1"/g,'$1$1\\"'),e=e.replace(/(?=(\\+?)?)\1$/,"$1$1"),e=`"${e}"`,e=e.replace(Et,"^$1"),t&&(e=e.replace(Et,"^$1")),e}bt.command=ur,bt.argument=dr;var mr=/^#!(.*)/;const fr=mr;var pr=(e="")=>{const t=e.match(fr);if(!t)return null;const[n,o]=t[0].replace(/#! ?/,"").split(" "),s=n.split("/").pop();return s==="env"?o:o?`${s} ${o}`:s};const vt=j,hr=pr;function gr(e){const n=Buffer.alloc(150);let o;try{o=vt.openSync(e,"r"),vt.readSync(o,n,0,150,0),vt.closeSync(o)}catch{}return hr(n.toString())}var yr=gr;const wr=v,On=lr,Dn=bt,Cr=yr,br=process.platform==="win32",Er=/\.(?:com|exe)$/i,vr=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function Pr(e){e.file=On(e);const t=e.file&&Cr(e.file);return t?(e.args.unshift(e.file),e.command=t,On(e)):e.file}function Ar(e){if(!br)return e;const t=Pr(e),n=!Er.test(t);if(e.options.forceShell||n){const o=vr.test(t);e.command=wr.normalize(e.command),e.command=Dn.command(e.command),e.args=e.args.map(r=>Dn.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 xr(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:Ar(o)}var $r=xr;const Pt=process.platform==="win32";function At(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 Sr(e,t){if(!Pt)return;const n=e.emit;e.emit=function(o,s){if(o==="exit"){const r=Nn(s,t);if(r)return n.call(e,"error",r)}return n.apply(e,arguments)}}function Nn(e,t){return Pt&&e===1&&!t.file?At(t.original,"spawn"):null}function Rr(e,t){return Pt&&e===1&&!t.file?At(t.original,"spawnSync"):null}var Ir={hookChildProcess:Sr,verifyENOENT:Nn,verifyENOENTSync:Rr,notFoundError:At};const _n=us,xt=$r,$t=Ir;function jn(e,t,n){const o=xt(e,t,n),s=_n.spawn(o.command,o.args,o.options);return $t.hookChildProcess(s,o),s}function kr(e,t,n){const o=xt(e,t,n),s=_n.spawnSync(o.command,o.args,o.options);return s.error=s.error||$t.verifyENOENTSync(s.status,o),s}re.exports=jn,re.exports.spawn=jn,re.exports.sync=kr,re.exports._parse=xt,re.exports._enoent=$t;var Lr=re.exports,Mr=se(Lr);function Tr(e){const t=typeof e=="string"?`
1
+ import{command as F,cli as ls}from"cleye";import{createRequire as us}from"module";import ds from"crypto";import j from"fs";import ke from"os";import v from"path";import{Buffer as ln}from"node:buffer";import oe from"node:path";import dt,{ChildProcess as un,exec as ms}from"node:child_process";import B from"node:process";import fs,{execSync as ye,exec as ps}from"child_process";import{fileURLToPath as dn}from"node:url";import hs,{constants as mn}from"node:os";import gs from"assert";import ys from"events";import{createWriteStream as ws,createReadStream as Cs,readFileSync as bs}from"node:fs";import Es from"buffer";import mt from"stream";import vs,{promisify as Ps}from"util";import{debuglog as As,promisify as xs}from"node:util";import M from"inquirer";import{from as Le,switchMap as fn,of as Ss,tap as $s,mergeMap as pn,catchError as Rs,BehaviorSubject as hn,ReplaySubject as Is,Subscription as ft,lastValueFrom as pt,toArray as ht,filter as gn,map as yn,Subject as ks}from"rxjs";import I from"fs/promises";import h from"chalk";import Oe from"readline";import wn from"figlet";import Ls from"gradient-string";import Cn from"ora";import Os from"inquirer-reactive-list-prompt";import H from"winston";import"winston-daily-rotate-file";import Ms from"axios";import{fileURLToPath as Ts,pathToFileURL as Ds}from"url";import{readdir as bn,stat as Ns,rm as _s}from"node:fs/promises";import js from"chokidar";import{takeUntil as En,finalize as vn}from"rxjs/operators";var Fs="aicommit2",Pn="2.5.16",Gs="A Reactive CLI that generates commit messages for Git and Jujutsu with various AI",Bs=["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"],Hs="MIT",Us="tak-bro/aicommit2",Ks="Hyungtak Jin(@tak-bro)",Ws="module",qs=["dist"],zs={aicommit2:"./dist/cli.mjs",aic2:"./dist/cli.mjs"},Ys={prepare:"simple-git-hooks",build:"pkgroll --minify",lint:"eslint --cache .","type-check":"tsc",test:"tsx tests",prepack:"pnpm build && clean-pkg-json",prettier:"prettier"},Vs={"@anthropic-ai/sdk":"^0.39.0","@aws-sdk/client-bedrock-runtime":"^3.678.0","@aws-sdk/credential-providers":"^3.678.0","@dqbd/tiktoken":"^1.0.21","@google/generative-ai":"^0.24.1","@inquirer/prompts":"^3.3.2","@pacote/xxhash":"^0.3.2","@types/winston":"^2.4.4",axios:"^1.9.0",chalk:"^5.4.1",chokidar:"^4.0.3",cleye:"^1.3.4","cohere-ai":"^7.19.0","copy-paste":"^1.5.3",figlet:"^1.8.1","formdata-node":"^6.0.3","gradient-string":"^3.0.0","groq-sdk":"^0.7.0",inquirer:"9.2.8","inquirer-reactive-list-prompt":"1.1.0",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"},Js={"@github/copilot-sdk":"0.2.0"},Xs={"@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"},Qs={extends:["@pvtnbr","prettier"],rules:{"unicorn/no-process-exit":"off"},overrides:[{files:"./src/commands/prepare-commit-msg-hook.ts",rules:{"unicorn/prevent-abbreviations":"off"}}]},Zs={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"]},er={name:Fs,version:Pn,description:Gs,keywords:Bs,license:Hs,repository:Us,author:Ks,type:Ws,files:qs,bin:zs,scripts:Ys,"simple-git-hooks":{"pre-commit":"pnpm lint-staged"},"lint-staged":{"*.ts":["prettier --config ./.prettierrc --write","eslint --fix"]},dependencies:Vs,optionalDependencies:Js,devDependencies:Xs,eslintConfig:Qs,release:Zs},gt=us(import.meta.url),V=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function re(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var ie={exports:{}},yt,An;function tr(){if(An)return yt;An=1,yt=o,o.sync=s;var e=j;function t(r,a){var c=a.pathExt!==void 0?a.pathExt:process.env.PATHEXT;if(!c||(c=c.split(";"),c.indexOf("")!==-1))return!0;for(var l=0;l<c.length;l++){var u=c[l].toLowerCase();if(u&&r.substr(-u.length).toLowerCase()===u)return!0}return!1}function n(r,a,c){return!r.isSymbolicLink()&&!r.isFile()?!1:t(a,c)}function o(r,a,c){e.stat(r,function(l,u){c(l,l?!1:n(u,r,a))})}function s(r,a){return n(e.statSync(r),r,a)}return yt}var wt,xn;function nr(){if(xn)return wt;xn=1,wt=t,t.sync=n;var e=j;function t(r,a,c){e.stat(r,function(l,u){c(l,l?!1:o(u,a))})}function n(r,a){return o(e.statSync(r),a)}function o(r,a){return r.isFile()&&s(r,a)}function s(r,a){var c=r.mode,l=r.uid,u=r.gid,d=a.uid!==void 0?a.uid:process.getuid&&process.getuid(),f=a.gid!==void 0?a.gid:process.getgid&&process.getgid(),g=parseInt("100",8),y=parseInt("010",8),m=parseInt("001",8),x=g|y,S=c&m||c&y&&u===f||c&g&&l===d||c&x&&d===0;return S}return wt}var Me;process.platform==="win32"||V.TESTING_WINDOWS?Me=tr():Me=nr();var or=Ct;Ct.sync=sr;function Ct(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){Ct(e,t||{},function(r,a){r?s(r):o(a)})})}Me(e,t||{},function(o,s){o&&(o.code==="EACCES"||t&&t.ignoreErrors)&&(o=null,s=!1),n(o,s)})}function sr(e,t){try{return Me.sync(e,t||{})}catch(n){if(t&&t.ignoreErrors||n.code==="EACCES")return!1;throw n}}const ae=process.platform==="win32"||process.env.OSTYPE==="cygwin"||process.env.OSTYPE==="msys",Sn=v,rr=ae?";":":",$n=or,Rn=e=>Object.assign(new Error(`not found: ${e}`),{code:"ENOENT"}),In=(e,t)=>{const n=t.colon||rr,o=e.match(/\//)||ae&&e.match(/\\/)?[""]:[...ae?[process.cwd()]:[],...(t.path||process.env.PATH||"").split(n)],s=ae?t.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",r=ae?s.split(n):[""];return ae&&e.indexOf(".")!==-1&&r[0]!==""&&r.unshift(""),{pathEnv:o,pathExt:r,pathExtExe:s}},kn=(e,t,n)=>{typeof t=="function"&&(n=t,t={}),t||(t={});const{pathEnv:o,pathExt:s,pathExtExe:r}=In(e,t),a=[],c=u=>new Promise((d,f)=>{if(u===o.length)return t.all&&a.length?d(a):f(Rn(e));const g=o[u],y=/^".*"$/.test(g)?g.slice(1,-1):g,m=Sn.join(y,e),x=!y&&/^\.[\\\/]/.test(e)?e.slice(0,2)+m:m;d(l(x,u,0))}),l=(u,d,f)=>new Promise((g,y)=>{if(f===s.length)return g(c(d+1));const m=s[f];$n(u+m,{pathExt:r},(x,S)=>{if(!x&&S)if(t.all)a.push(u+m);else return g(u+m);return g(l(u,d,f+1))})});return n?c(0).then(u=>n(null,u),n):c(0)},ir=(e,t)=>{t=t||{};const{pathEnv:n,pathExt:o,pathExtExe:s}=In(e,t),r=[];for(let a=0;a<n.length;a++){const c=n[a],l=/^".*"$/.test(c)?c.slice(1,-1):c,u=Sn.join(l,e),d=!l&&/^\.[\\\/]/.test(e)?e.slice(0,2)+u:u;for(let f=0;f<o.length;f++){const g=d+o[f];try{if($n.sync(g,{pathExt:s}))if(t.all)r.push(g);else return g}catch{}}}if(t.all&&r.length)return r;if(t.nothrow)return null;throw Rn(e)};var ar=kn;kn.sync=ir;var bt={exports:{}};const Ln=(e={})=>{const t=e.env||process.env;return(e.platform||process.platform)!=="win32"?"PATH":Object.keys(t).reverse().find(o=>o.toUpperCase()==="PATH")||"Path"};bt.exports=Ln,bt.exports.default=Ln;var cr=bt.exports;const On=v,lr=ar,ur=cr;function Mn(e,t){const n=e.options.env||process.env,o=process.cwd(),s=e.options.cwd!=null,r=s&&process.chdir!==void 0&&!process.chdir.disabled;if(r)try{process.chdir(e.options.cwd)}catch{}let a;try{a=lr.sync(e.command,{path:n[ur({env:n})],pathExt:t?On.delimiter:void 0})}catch{}finally{r&&process.chdir(o)}return a&&(a=On.resolve(s?e.options.cwd:"",a)),a}function dr(e){return Mn(e)||Mn(e,!0)}var mr=dr,Et={};const vt=/([()\][%!^"`<>&|;, *?])/g;function fr(e){return e=e.replace(vt,"^$1"),e}function pr(e,t){return e=`${e}`,e=e.replace(/(?=(\\+?)?)\1"/g,'$1$1\\"'),e=e.replace(/(?=(\\+?)?)\1$/,"$1$1"),e=`"${e}"`,e=e.replace(vt,"^$1"),t&&(e=e.replace(vt,"^$1")),e}Et.command=fr,Et.argument=pr;var hr=/^#!(.*)/;const gr=hr;var yr=(e="")=>{const t=e.match(gr);if(!t)return null;const[n,o]=t[0].replace(/#! ?/,"").split(" "),s=n.split("/").pop();return s==="env"?o:o?`${s} ${o}`:s};const Pt=j,wr=yr;function Cr(e){const n=Buffer.alloc(150);let o;try{o=Pt.openSync(e,"r"),Pt.readSync(o,n,0,150,0),Pt.closeSync(o)}catch{}return wr(n.toString())}var br=Cr;const Er=v,Tn=mr,Dn=Et,vr=br,Pr=process.platform==="win32",Ar=/\.(?:com|exe)$/i,xr=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function Sr(e){e.file=Tn(e);const t=e.file&&vr(e.file);return t?(e.args.unshift(e.file),e.command=t,Tn(e)):e.file}function $r(e){if(!Pr)return e;const t=Sr(e),n=!Ar.test(t);if(e.options.forceShell||n){const o=xr.test(t);e.command=Er.normalize(e.command),e.command=Dn.command(e.command),e.args=e.args.map(r=>Dn.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:$r(o)}var Ir=Rr;const At=process.platform==="win32";function xt(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 kr(e,t){if(!At)return;const n=e.emit;e.emit=function(o,s){if(o==="exit"){const r=Nn(s,t);if(r)return n.call(e,"error",r)}return n.apply(e,arguments)}}function Nn(e,t){return At&&e===1&&!t.file?xt(t.original,"spawn"):null}function Lr(e,t){return At&&e===1&&!t.file?xt(t.original,"spawnSync"):null}var Or={hookChildProcess:kr,verifyENOENT:Nn,verifyENOENTSync:Lr,notFoundError:xt};const _n=fs,St=Ir,$t=Or;function jn(e,t,n){const o=St(e,t,n),s=_n.spawn(o.command,o.args,o.options);return $t.hookChildProcess(s,o),s}function Mr(e,t,n){const o=St(e,t,n),s=_n.spawnSync(o.command,o.args,o.options);return s.error=s.error||$t.verifyENOENTSync(s.status,o),s}ie.exports=jn,ie.exports.spawn=jn,ie.exports.sync=Mr,ie.exports._parse=St,ie.exports._enoent=$t;var Tr=ie.exports,Dr=re(Tr);function Nr(e){const t=typeof e=="string"?`
2
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 Fn(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 Or=({cwd:e=B.cwd(),path:t=B.env[Fn()],preferLocal:n=!0,execPath:o=B.execPath,addExecPath:s=!0}={})=>{const r=e instanceof URL?dn(e):e,a=te.resolve(r),c=[];return n&&Dr(c,a),s&&Nr(c,o,a),[...c,t].join(te.delimiter)},Dr=(e,t)=>{let n;for(;n!==t;)e.push(te.join(t,"node_modules/.bin")),n=t,t=te.resolve(t,"..")},Nr=(e,t,n)=>{const o=t instanceof URL?dn(t):t;e.push(te.resolve(n,o,".."))},_r=({env:e=B.env,...t}={})=>{e={...e};const n=Fn({env:e});return t.path=e[n],e[n]=Or(t),e},jr=(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);!Fr(s,r)&&o||Object.defineProperty(e,n,r)},Fr=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)},Gr=(e,t)=>{const n=Object.getPrototypeOf(t);n!==Object.getPrototypeOf(e)&&Object.setPrototypeOf(e,n)},Br=(e,t)=>`/* Wrapped ${e}*/
4
- ${t}`,Hr=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),Ur=Object.getOwnPropertyDescriptor(Function.prototype.toString,"name"),Kr=(e,t,n)=>{const o=n===""?"":`with ${n.trim()}() `,s=Br.bind(null,o,t.toString());Object.defineProperty(s,"name",Ur),Object.defineProperty(e,"toString",{...Hr,value:s})};function Wr(e,t,{ignoreNonConfigurable:n=!1}={}){const{name:o}=e;for(const s of Reflect.ownKeys(t))jr(e,t,s,n);return Gr(e,t),Kr(e,t,o),e}const Oe=new WeakMap,Gn=(e,t={})=>{if(typeof e!="function")throw new TypeError("Expected a function");let n,o=0;const s=e.displayName||e.name||"<anonymous>",r=function(...a){if(Oe.set(r,++o),o===1)n=e.apply(this,a),e=null;else if(t.throw===!0)throw new Error(`Function \`${s}\` can only be called once`);return n};return Wr(r,e),Oe.set(r,o),r};Gn.callCount=e=>{if(!Oe.has(e))throw new Error(`The given function \`${e.name}\` is not wrapped by the \`onetime\` package`);return Oe.get(e)};const qr=()=>{const e=Hn-Bn+1;return Array.from({length:e},zr)},zr=(e,t)=>({name:`SIGRT${t+1}`,number:Bn+t,action:"terminate",description:"Application-specific signal (realtime)",standard:"posix"}),Bn=34,Hn=64,Yr=[{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"}],Un=()=>{const e=qr();return[...Yr,...e].map(Vr)},Vr=({name:e,number:t,description:n,action:o,forced:s=!1,standard:r})=>{const{signals:{[e]:a}}=mn,c=a!==void 0;return{name:e,number:c?a:t,description:n,supported:c,action:o,forced:s,standard:r}},Jr=()=>{const e=Un();return Object.fromEntries(e.map(Xr))},Xr=({name:e,number:t,description:n,supported:o,action:s,forced:r,standard:a})=>[e,{name:e,number:t,description:n,supported:o,action:s,forced:r,standard:a}],Qr=Jr(),Zr=()=>{const e=Un(),t=Hn+1,n=Array.from({length:t},(o,s)=>ei(s,e));return Object.assign({},...n)},ei=(e,t)=>{const n=ti(e,t);if(n===void 0)return{};const{name:o,description:s,supported:r,action:a,forced:c,standard:u}=n;return{[e]:{name:o,number:e,description:s,supported:r,action:a,forced:c,standard:u}}},ti=(e,t)=>{const n=t.find(({name:o})=>mn.signals[o]===e);return n!==void 0?n:t.find(o=>o.number===e)};Zr();const ni=({timedOut:e,timeout:t,errorCode:n,signal:o,signalDescription:s,exitCode:r,isCanceled:a})=>e?`timed out after ${t} milliseconds`:a?"was canceled":n!==void 0?`failed with ${n}`:o!==void 0?`was killed with ${o} (${s})`:r!==void 0?`failed with exit code ${r}`:"failed",De=({stdout:e,stderr:t,all:n,error:o,signal:s,exitCode:r,command:a,escapedCommand:c,timedOut:u,isCanceled:l,killed:d,parsed:{options:{timeout:f,cwd:g=B.cwd()}}})=>{r=r===null?void 0:r,s=s===null?void 0:s;const y=s===void 0?void 0:Qr[s].description,m=o&&o.code,$=`Command ${ni({timedOut:u,timeout:f,errorCode:m,signal:s,signalDescription:y,exitCode:r,isCanceled:l})}: ${a}`,A=Object.prototype.toString.call(o)==="[object Error]",S=A?`${$}
5
- ${o.message}`:$,P=[S,t,e].filter(Boolean).join(`
6
- `);return A?(o.originalMessage=o.message,o.message=P):o=new Error(P),o.shortMessage=S,o.command=a,o.escapedCommand=c,o.exitCode=r,o.signal=s,o.signalDescription=y,o.stdout=e,o.stderr=t,o.cwd=g,n!==void 0&&(o.all=n),"bufferedData"in o&&delete o.bufferedData,o.failed=!0,o.timedOut=!!u,o.isCanceled=l,o.killed=d&&!u,o},Ne=["stdin","stdout","stderr"],oi=e=>Ne.some(t=>e[t]!==void 0),Kn=e=>{if(!e)return;const{stdio:t}=e;if(t===void 0)return Ne.map(o=>e[o]);if(oi(e))throw new Error(`It's not possible to provide \`stdio\` in combination with one of ${Ne.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,Ne.length);return Array.from({length:n},(o,s)=>t[s])},si=e=>{const t=Kn(e);return t==="ipc"?"ipc":t===void 0||typeof t=="string"?[t,t,t,"ipc"]:t.includes("ipc")?t:[...t,"ipc"]};var ae={exports:{}},_e={exports:{}};_e.exports;var Wn;function ri(){return Wn||(Wn=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")}(_e)),_e.exports}var M=V.process;const ne=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(!ne(M))ae.exports=function(){return function(){}};else{var ii=fs,we=ri(),ai=/^win/i.test(M.platform),je=ps;typeof je!="function"&&(je=je.EventEmitter);var O;M.__signal_exit_emitter__?O=M.__signal_exit_emitter__:(O=M.__signal_exit_emitter__=new je,O.count=0,O.emitted={}),O.infinite||(O.setMaxListeners(1/0),O.infinite=!0),ae.exports=function(e,t){if(!ne(V.process))return function(){};ii.equal(typeof e,"function","a callback must be provided for exit handler"),Ce===!1&&qn();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&&St()};return O.on(n,e),o};var St=function(){!Ce||!ne(V.process)||(Ce=!1,we.forEach(function(t){try{M.removeListener(t,Rt[t])}catch{}}),M.emit=It,M.reallyExit=zn,O.count-=1)};ae.exports.unload=St;var ce=function(t,n,o){O.emitted[t]||(O.emitted[t]=!0,O.emit(t,n,o))},Rt={};we.forEach(function(e){Rt[e]=function(){if(ne(V.process)){var n=M.listeners(e);n.length===O.count&&(St(),ce("exit",null,e),ce("afterexit",null,e),ai&&e==="SIGHUP"&&(e="SIGINT"),M.kill(M.pid,e))}}}),ae.exports.signals=function(){return we};var Ce=!1,qn=function(){Ce||!ne(V.process)||(Ce=!0,O.count+=1,we=we.filter(function(t){try{return M.on(t,Rt[t]),!0}catch{return!1}}),M.emit=li,M.reallyExit=ci)};ae.exports.load=qn;var zn=M.reallyExit,ci=function(t){ne(V.process)&&(M.exitCode=t||0,ce("exit",M.exitCode,null),ce("afterexit",M.exitCode,null),zn.call(M,M.exitCode))},It=M.emit,li=function(t,n){if(t==="exit"&&ne(V.process)){n!==void 0&&(M.exitCode=n);var o=It.apply(this,arguments);return ce("exit",M.exitCode,null),ce("afterexit",M.exitCode,null),o}else return It.apply(this,arguments)}}var ui=ae.exports,di=se(ui);const mi=1e3*5,fi=(e,t="SIGTERM",n={})=>{const o=e(t);return pi(e,t,n,o),o},pi=(e,t,n,o)=>{if(!hi(t,n,o))return;const s=yi(n),r=setTimeout(()=>{e("SIGKILL")},s);r.unref&&r.unref()},hi=(e,{forceKillAfterTimeout:t},n)=>gi(e)&&t!==!1&&n,gi=e=>e===ms.constants.signals.SIGTERM||typeof e=="string"&&e.toUpperCase()==="SIGTERM",yi=({forceKillAfterTimeout:e=!0})=>{if(e===!0)return mi;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},wi=(e,t)=>{e.kill()&&(t.isCanceled=!0)},Ci=(e,t,n)=>{e.kill(t),n(Object.assign(new Error("Timed out"),{timedOut:!0,signal:t}))},bi=(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(()=>{Ci(e,n,u)},t)}),a=o.finally(()=>{clearTimeout(s)});return Promise.race([r,a])},Ei=({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})`)},vi=async(e,{cleanup:t,detached:n},o)=>{if(!t||n)return o;const s=di(()=>{e.kill()});return o.finally(()=>{s()})};function kt(e){return e!==null&&typeof e=="object"&&typeof e.pipe=="function"}function Yn(e){return kt(e)&&e.writable!==!1&&typeof e._write=="function"&&typeof e._writableState=="object"}const Pi=e=>e instanceof un&&typeof e.then=="function",Lt=(e,t,n)=>{if(typeof n=="string")return e[t].pipe(hs(n)),e;if(Yn(n))return e[t].pipe(n),e;if(!Pi(n))throw new TypeError("The second argument must be a string, a stream or an Execa child process.");if(!Yn(n.stdin))throw new TypeError("The target child process's stdin must be available.");return e[t].pipe(n.stdin),n},Ai=e=>{e.stdout!==null&&(e.pipeStdout=Lt.bind(void 0,e,"stdout")),e.stderr!==null&&(e.pipeStderr=Lt.bind(void 0,e,"stderr")),e.all!==void 0&&(e.pipeAll=Lt.bind(void 0,e,"all"))};var be={exports:{}};const{PassThrough:xi}=dt;var $i=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 xi({objectMode:s});n&&r.setEncoding(n);let a=0;const c=[];return r.on("data",u=>{c.push(u),s?a=c.length:a+=u.length}),r.getBufferedValue=()=>t?c:o?Buffer.concat(c,a):c.join(""),r.getBufferedLength=()=>a,r};const{constants:Si}=ws,Ri=dt,{promisify:Ii}=Cs,ki=$i,Li=Ii(Ri.pipeline);class Vn extends Error{constructor(){super("maxBuffer exceeded"),this.name="MaxBufferError"}}async function Mt(e,t){if(!e)throw new Error("Expected a stream");t={maxBuffer:1/0,...t};const{maxBuffer:n}=t,o=ki(t);return await new Promise((s,r)=>{const a=c=>{c&&o.getBufferedLength()<=Si.MAX_LENGTH&&(c.bufferedData=o.getBufferedValue()),r(c)};(async()=>{try{await Li(e,o),s()}catch(c){a(c)}})(),o.on("data",()=>{o.getBufferedLength()>n&&a(new Vn)})}),o.getBufferedValue()}be.exports=Mt,be.exports.buffer=(e,t)=>Mt(e,{...t,encoding:"buffer"}),be.exports.array=(e,t)=>Mt(e,{...t,array:!0}),be.exports.MaxBufferError=Vn;var Mi=be.exports,Jn=se(Mi);const{PassThrough:Ti}=dt;var Oi=function(){var e=[],t=new Ti({objectMode:!0});return t.setMaxListeners(0),t.add=n,t.isEmpty=o,t.on("unpipe",s),Array.prototype.slice.call(arguments).forEach(n),t;function n(r){return Array.isArray(r)?(r.forEach(n),this):(e.push(r),r.once("end",s.bind(null,r)),r.once("error",t.emit.bind(t,"error")),r.pipe(t,{end:!1}),this)}function o(){return e.length==0}function s(r){e=e.filter(function(a){return a!==r}),!e.length&&t.readable&&t.end()}},Di=se(Oi);const Xn=e=>{if(e!==void 0)throw new TypeError("The `input` and `inputFile` options cannot be both set.")},Ni=({input:e,inputFile:t})=>typeof t!="string"?e:(Xn(e),ys(t)),_i=e=>{const t=Ni(e);if(kt(t))throw new TypeError("The `input` option cannot be a stream in sync mode");return t},ji=({input:e,inputFile:t})=>typeof t!="string"?e:(Xn(e),gs(t)),Fi=(e,t)=>{const n=ji(t);n!==void 0&&(kt(n)?n.pipe(e.stdin):e.stdin.end(n))},Gi=(e,{all:t})=>{if(!t||!e.stdout&&!e.stderr)return;const n=Di();return e.stdout&&n.add(e.stdout),e.stderr&&n.add(e.stderr),n},Tt=async(e,t)=>{if(!(!e||t===void 0)){e.destroy();try{return await t}catch(n){return n.bufferedData}}},Ot=(e,{encoding:t,buffer:n,maxBuffer:o})=>{if(!(!e||!n))return t?Jn(e,{encoding:t,maxBuffer:o}):Jn.buffer(e,{maxBuffer:o})},Bi=async({stdout:e,stderr:t,all:n},{encoding:o,buffer:s,maxBuffer:r},a)=>{const c=Ot(e,{encoding:o,buffer:s,maxBuffer:r}),u=Ot(t,{encoding:o,buffer:s,maxBuffer:r}),l=Ot(n,{encoding:o,buffer:s,maxBuffer:r*2});try{return await Promise.all([a,c,u,l])}catch(d){return Promise.all([{error:d,signal:d.signal,timedOut:d.timedOut},Tt(e,c),Tt(t,u),Tt(n,l)])}},Hi=(async()=>{})().constructor.prototype,Ui=["then","catch","finally"].map(e=>[e,Reflect.getOwnPropertyDescriptor(Hi,e)]),Qn=(e,t)=>{for(const[n,o]of Ui){const s=typeof t=="function"?(...r)=>Reflect.apply(o.value,t(),r):o.value.bind(t);Reflect.defineProperty(e,n,{...o,value:s})}},Ki=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)})}),Zn=(e,t=[])=>Array.isArray(t)?[e,...t]:[e],Wi=/^[\w.-]+$/,qi=/"/g,zi=e=>typeof e!="string"||Wi.test(e)?e:`"${e.replace(qi,'\\"')}"`,eo=(e,t)=>Zn(e,t).join(" "),to=(e,t)=>Zn(e,t).map(n=>zi(n)).join(" "),no=/ +/g,oo=e=>{const t=[];for(const n of e.trim().split(no)){const o=t[t.length-1];o&&o.endsWith("\\")?t[t.length-1]=`${o.slice(0,-1)} ${n}`:t.push(n)}return t},so=e=>{const t=typeof e;if(t==="string")return e;if(t==="number")return String(e);if(t==="object"&&e!==null&&!(e instanceof un)&&"stdout"in e){const n=typeof e.stdout;if(n==="string")return e.stdout;if(ln.isBuffer(e.stdout))return e.stdout.toString();throw new TypeError(`Unexpected "${n}" stdout in template expression`)}throw new TypeError(`Unexpected "${t}" in template expression`)},ro=(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)],Yi=({templates:e,expressions:t,tokens:n,index:o,template:s})=>{const r=s??e.raw[o],a=r.split(no).filter(Boolean),c=ro(n,a,r.startsWith(" "));if(o===t.length)return c;const u=t[o],l=Array.isArray(u)?u.map(d=>so(d)):[so(u)];return ro(c,l,r.endsWith(" "))},io=(e,t)=>{let n=[];for(const[o,s]of e.entries())n=Yi({templates:e,expressions:t,tokens:n,index:o,template:s});return n},Vi=Es("execa").enabled,Fe=(e,t)=>String(e).padStart(t,"0"),Ji=()=>{const e=new Date;return`${Fe(e.getHours(),2)}:${Fe(e.getMinutes(),2)}:${Fe(e.getSeconds(),2)}.${Fe(e.getMilliseconds(),3)}`},ao=(e,{verbose:t})=>{t&&B.stderr.write(`[${Ji()}] ${e}
7
- `)},Xi=1e3*1e3*100,Qi=({env:e,extendEnv:t,preferLocal:n,localDir:o,execPath:s})=>{const r=t?{...B.env,...e}:e;return n?_r({env:r,cwd:o,execPath:s}):r},co=(e,t,n={})=>{const o=Mr._parse(e,t,n);return e=o.command,t=o.args,n=o.options,n={maxBuffer:Xi,buffer:!0,stripFinalNewline:!0,extendEnv:!0,preferLocal:!1,localDir:n.cwd||B.cwd(),execPath:B.execPath,encoding:"utf8",reject:!0,cleanup:!0,all:!1,windowsHide:!0,verbose:Vi,...n},n.env=Qi(n),n.stdio=Kn(n),B.platform==="win32"&&te.basename(e,".exe")==="cmd"&&t.unshift("/q"),{file:e,args:t,options:n,parsed:o}},Ee=(e,t,n)=>typeof t!="string"&&!ln.isBuffer(t)?n===void 0?void 0:"":e.stripFinalNewline?Tr(t):t;function b(e,t,n){const o=co(e,t,n),s=eo(e,t),r=to(e,t);ao(r,o.options),Ei(o.options);let a;try{a=ut.spawn(o.file,o.args,o.options)}catch(y){const m=new ut.ChildProcess,x=Promise.reject(De({error:y,stdout:"",stderr:"",all:"",command:s,escapedCommand:r,parsed:o,timedOut:!1,isCanceled:!1,killed:!1}));return Qn(m,x),m}const c=Ki(a),u=bi(a,o.options,c),l=vi(a,o.options,u),d={isCanceled:!1};a.kill=fi.bind(null,a.kill.bind(a)),a.cancel=wi.bind(null,a,d);const g=Gn(async()=>{const[{error:y,exitCode:m,signal:x,timedOut:$},A,S,P]=await Bi(a,o.options,l),C=Ee(o.options,A),k=Ee(o.options,S),L=Ee(o.options,P);if(y||m!==0||x!==null){const D=De({error:y,exitCode:m,signal:x,stdout:C,stderr:k,all:L,command:s,escapedCommand:r,parsed:o,timedOut:$,isCanceled:d.isCanceled||(o.options.signal?o.options.signal.aborted:!1),killed:a.killed});if(!o.options.reject)return D;throw D}return{command:s,escapedCommand:r,exitCode:0,stdout:C,stderr:k,all:L,failed:!1,timedOut:!1,isCanceled:!1,killed:!1}});return Fi(a,o.options),a.all=Gi(a,o.options),Ai(a),Qn(a,g),a}function Dt(e,t,n){const o=co(e,t,n),s=eo(e,t),r=to(e,t);ao(r,o.options);const a=_i(o.options);let c;try{c=ut.spawnSync(o.file,o.args,{...o.options,input:a})}catch(d){throw De({error:d,stdout:"",stderr:"",all:"",command:s,escapedCommand:r,parsed:o,timedOut:!1,isCanceled:!1,killed:!1})}const u=Ee(o.options,c.stdout,c.error),l=Ee(o.options,c.stderr,c.error);if(c.error||c.status!==0||c.signal!==null){const d=De({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 Zi=({input:e,inputFile:t,stdio:n})=>e===void 0&&t===void 0&&n===void 0?{stdin:"inherit"}:{},lo=(e={})=>({preferLocal:!0,...Zi(e),...e});function uo(e){function t(n,...o){if(!Array.isArray(n))return uo({...e,...n});const[s,...r]=io(n,o);return b(s,r,lo(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]=io(n,o);return Dt(s,r,lo(e))},t}const ea=uo();function ta(e,t){const[n,...o]=oo(e);return b(n,o,t)}function na(e,t){const[n,...o]=oo(e);return Dt(n,o,t)}function oa(e,t,n={}){t&&!Array.isArray(t)&&typeof t=="object"&&(n=t,t=[]);const o=si(n),s=B.execArgv.filter(c=>!c.startsWith("--inspect")),{nodePath:r=B.execPath,nodeOptions:a=s}=n;return b(r,[...a,e,...Array.isArray(t)?t:[]],{...n,stdin:void 0,stdout:void 0,stderr:void 0,stdio:o,shell:!1})}var sa=Object.freeze({__proto__:null,execa:b,execaSync:Dt,$:ea,execaCommand:ta,execaCommandSync:na,execaNode:oa});const{hasOwnProperty:Nt}=Object.prototype,Ge=typeof process<"u"&&process.platform==="win32"?`\r
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 Fn(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 _r=({cwd:e=B.cwd(),path:t=B.env[Fn()],preferLocal:n=!0,execPath:o=B.execPath,addExecPath:s=!0}={})=>{const r=e instanceof URL?dn(e):e,a=oe.resolve(r),c=[];return n&&jr(c,a),s&&Fr(c,o,a),[...c,t].join(oe.delimiter)},jr=(e,t)=>{let n;for(;n!==t;)e.push(oe.join(t,"node_modules/.bin")),n=t,t=oe.resolve(t,"..")},Fr=(e,t,n)=>{const o=t instanceof URL?dn(t):t;e.push(oe.resolve(n,o,".."))},Gr=({env:e=B.env,...t}={})=>{e={...e};const n=Fn({env:e});return t.path=e[n],e[n]=_r(t),e},Br=(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);!Hr(s,r)&&o||Object.defineProperty(e,n,r)},Hr=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)},Ur=(e,t)=>{const n=Object.getPrototypeOf(t);n!==Object.getPrototypeOf(e)&&Object.setPrototypeOf(e,n)},Kr=(e,t)=>`/* Wrapped ${e}*/
4
+ ${t}`,Wr=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),qr=Object.getOwnPropertyDescriptor(Function.prototype.toString,"name"),zr=(e,t,n)=>{const o=n===""?"":`with ${n.trim()}() `,s=Kr.bind(null,o,t.toString());Object.defineProperty(s,"name",qr),Object.defineProperty(e,"toString",{...Wr,value:s})};function Yr(e,t,{ignoreNonConfigurable:n=!1}={}){const{name:o}=e;for(const s of Reflect.ownKeys(t))Br(e,t,s,n);return Ur(e,t),zr(e,t,o),e}const Te=new WeakMap,Gn=(e,t={})=>{if(typeof e!="function")throw new TypeError("Expected a function");let n,o=0;const s=e.displayName||e.name||"<anonymous>",r=function(...a){if(Te.set(r,++o),o===1)n=e.apply(this,a),e=null;else if(t.throw===!0)throw new Error(`Function \`${s}\` can only be called once`);return n};return Yr(r,e),Te.set(r,o),r};Gn.callCount=e=>{if(!Te.has(e))throw new Error(`The given function \`${e.name}\` is not wrapped by the \`onetime\` package`);return Te.get(e)};const Vr=()=>{const e=Hn-Bn+1;return Array.from({length:e},Jr)},Jr=(e,t)=>({name:`SIGRT${t+1}`,number:Bn+t,action:"terminate",description:"Application-specific signal (realtime)",standard:"posix"}),Bn=34,Hn=64,Xr=[{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"}],Un=()=>{const e=Vr();return[...Xr,...e].map(Qr)},Qr=({name:e,number:t,description:n,action:o,forced:s=!1,standard:r})=>{const{signals:{[e]:a}}=mn,c=a!==void 0;return{name:e,number:c?a:t,description:n,supported:c,action:o,forced:s,standard:r}},Zr=()=>{const e=Un();return Object.fromEntries(e.map(ei))},ei=({name:e,number:t,description:n,supported:o,action:s,forced:r,standard:a})=>[e,{name:e,number:t,description:n,supported:o,action:s,forced:r,standard:a}],ti=Zr(),ni=()=>{const e=Un(),t=Hn+1,n=Array.from({length:t},(o,s)=>oi(s,e));return Object.assign({},...n)},oi=(e,t)=>{const n=si(e,t);if(n===void 0)return{};const{name:o,description:s,supported:r,action:a,forced:c,standard:l}=n;return{[e]:{name:o,number:e,description:s,supported:r,action:a,forced:c,standard:l}}},si=(e,t)=>{const n=t.find(({name:o})=>mn.signals[o]===e);return n!==void 0?n:t.find(o=>o.number===e)};ni();const ri=({timedOut:e,timeout:t,errorCode:n,signal:o,signalDescription:s,exitCode:r,isCanceled:a})=>e?`timed out after ${t} milliseconds`:a?"was canceled":n!==void 0?`failed with ${n}`:o!==void 0?`was killed with ${o} (${s})`:r!==void 0?`failed with exit code ${r}`:"failed",De=({stdout:e,stderr:t,all:n,error:o,signal:s,exitCode:r,command:a,escapedCommand:c,timedOut:l,isCanceled:u,killed:d,parsed:{options:{timeout:f,cwd:g=B.cwd()}}})=>{r=r===null?void 0:r,s=s===null?void 0:s;const y=s===void 0?void 0:ti[s].description,m=o&&o.code,S=`Command ${ri({timedOut:l,timeout:f,errorCode:m,signal:s,signalDescription:y,exitCode:r,isCanceled:u})}: ${a}`,A=Object.prototype.toString.call(o)==="[object Error]",$=A?`${S}
5
+ ${o.message}`:S,P=[$,t,e].filter(Boolean).join(`
6
+ `);return A?(o.originalMessage=o.message,o.message=P):o=new Error(P),o.shortMessage=$,o.command=a,o.escapedCommand=c,o.exitCode=r,o.signal=s,o.signalDescription=y,o.stdout=e,o.stderr=t,o.cwd=g,n!==void 0&&(o.all=n),"bufferedData"in o&&delete o.bufferedData,o.failed=!0,o.timedOut=!!l,o.isCanceled=u,o.killed=d&&!l,o},Ne=["stdin","stdout","stderr"],ii=e=>Ne.some(t=>e[t]!==void 0),Kn=e=>{if(!e)return;const{stdio:t}=e;if(t===void 0)return Ne.map(o=>e[o]);if(ii(e))throw new Error(`It's not possible to provide \`stdio\` in combination with one of ${Ne.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,Ne.length);return Array.from({length:n},(o,s)=>t[s])},ai=e=>{const t=Kn(e);return t==="ipc"?"ipc":t===void 0||typeof t=="string"?[t,t,t,"ipc"]:t.includes("ipc")?t:[...t,"ipc"]};var ce={exports:{}},_e={exports:{}};_e.exports;var Wn;function ci(){return Wn||(Wn=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")}(_e)),_e.exports}var O=V.process;const se=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(!se(O))ce.exports=function(){return function(){}};else{var li=gs,we=ci(),ui=/^win/i.test(O.platform),je=ys;typeof je!="function"&&(je=je.EventEmitter);var T;O.__signal_exit_emitter__?T=O.__signal_exit_emitter__:(T=O.__signal_exit_emitter__=new je,T.count=0,T.emitted={}),T.infinite||(T.setMaxListeners(1/0),T.infinite=!0),ce.exports=function(e,t){if(!se(V.process))return function(){};li.equal(typeof e,"function","a callback must be provided for exit handler"),Ce===!1&&qn();var n="exit";t&&t.alwaysLast&&(n="afterexit");var o=function(){T.removeListener(n,e),T.listeners("exit").length===0&&T.listeners("afterexit").length===0&&Rt()};return T.on(n,e),o};var Rt=function(){!Ce||!se(V.process)||(Ce=!1,we.forEach(function(t){try{O.removeListener(t,It[t])}catch{}}),O.emit=kt,O.reallyExit=zn,T.count-=1)};ce.exports.unload=Rt;var le=function(t,n,o){T.emitted[t]||(T.emitted[t]=!0,T.emit(t,n,o))},It={};we.forEach(function(e){It[e]=function(){if(se(V.process)){var n=O.listeners(e);n.length===T.count&&(Rt(),le("exit",null,e),le("afterexit",null,e),ui&&e==="SIGHUP"&&(e="SIGINT"),O.kill(O.pid,e))}}}),ce.exports.signals=function(){return we};var Ce=!1,qn=function(){Ce||!se(V.process)||(Ce=!0,T.count+=1,we=we.filter(function(t){try{return O.on(t,It[t]),!0}catch{return!1}}),O.emit=mi,O.reallyExit=di)};ce.exports.load=qn;var zn=O.reallyExit,di=function(t){se(V.process)&&(O.exitCode=t||0,le("exit",O.exitCode,null),le("afterexit",O.exitCode,null),zn.call(O,O.exitCode))},kt=O.emit,mi=function(t,n){if(t==="exit"&&se(V.process)){n!==void 0&&(O.exitCode=n);var o=kt.apply(this,arguments);return le("exit",O.exitCode,null),le("afterexit",O.exitCode,null),o}else return kt.apply(this,arguments)}}var fi=ce.exports,pi=re(fi);const hi=1e3*5,gi=(e,t="SIGTERM",n={})=>{const o=e(t);return yi(e,t,n,o),o},yi=(e,t,n,o)=>{if(!wi(t,n,o))return;const s=bi(n),r=setTimeout(()=>{e("SIGKILL")},s);r.unref&&r.unref()},wi=(e,{forceKillAfterTimeout:t},n)=>Ci(e)&&t!==!1&&n,Ci=e=>e===hs.constants.signals.SIGTERM||typeof e=="string"&&e.toUpperCase()==="SIGTERM",bi=({forceKillAfterTimeout:e=!0})=>{if(e===!0)return hi;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},Ei=(e,t)=>{e.kill()&&(t.isCanceled=!0)},vi=(e,t,n)=>{e.kill(t),n(Object.assign(new Error("Timed out"),{timedOut:!0,signal:t}))},Pi=(e,{timeout:t,killSignal:n="SIGTERM"},o)=>{if(t===0||t===void 0)return o;let s;const r=new Promise((c,l)=>{s=setTimeout(()=>{vi(e,n,l)},t)}),a=o.finally(()=>{clearTimeout(s)});return Promise.race([r,a])},Ai=({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})`)},xi=async(e,{cleanup:t,detached:n},o)=>{if(!t||n)return o;const s=pi(()=>{e.kill()});return o.finally(()=>{s()})};function Lt(e){return e!==null&&typeof e=="object"&&typeof e.pipe=="function"}function Yn(e){return Lt(e)&&e.writable!==!1&&typeof e._write=="function"&&typeof e._writableState=="object"}const Si=e=>e instanceof un&&typeof e.then=="function",Ot=(e,t,n)=>{if(typeof n=="string")return e[t].pipe(ws(n)),e;if(Yn(n))return e[t].pipe(n),e;if(!Si(n))throw new TypeError("The second argument must be a string, a stream or an Execa child process.");if(!Yn(n.stdin))throw new TypeError("The target child process's stdin must be available.");return e[t].pipe(n.stdin),n},$i=e=>{e.stdout!==null&&(e.pipeStdout=Ot.bind(void 0,e,"stdout")),e.stderr!==null&&(e.pipeStderr=Ot.bind(void 0,e,"stderr")),e.all!==void 0&&(e.pipeAll=Ot.bind(void 0,e,"all"))};var be={exports:{}};const{PassThrough:Ri}=mt;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 a=0;const c=[];return r.on("data",l=>{c.push(l),s?a=c.length:a+=l.length}),r.getBufferedValue=()=>t?c:o?Buffer.concat(c,a):c.join(""),r.getBufferedLength=()=>a,r};const{constants:ki}=Es,Li=mt,{promisify:Oi}=vs,Mi=Ii,Ti=Oi(Li.pipeline);class Vn extends Error{constructor(){super("maxBuffer exceeded"),this.name="MaxBufferError"}}async function Mt(e,t){if(!e)throw new Error("Expected a stream");t={maxBuffer:1/0,...t};const{maxBuffer:n}=t,o=Mi(t);return await new Promise((s,r)=>{const a=c=>{c&&o.getBufferedLength()<=ki.MAX_LENGTH&&(c.bufferedData=o.getBufferedValue()),r(c)};(async()=>{try{await Ti(e,o),s()}catch(c){a(c)}})(),o.on("data",()=>{o.getBufferedLength()>n&&a(new Vn)})}),o.getBufferedValue()}be.exports=Mt,be.exports.buffer=(e,t)=>Mt(e,{...t,encoding:"buffer"}),be.exports.array=(e,t)=>Mt(e,{...t,array:!0}),be.exports.MaxBufferError=Vn;var Di=be.exports,Jn=re(Di);const{PassThrough:Ni}=mt;var _i=function(){var e=[],t=new Ni({objectMode:!0});return t.setMaxListeners(0),t.add=n,t.isEmpty=o,t.on("unpipe",s),Array.prototype.slice.call(arguments).forEach(n),t;function n(r){return Array.isArray(r)?(r.forEach(n),this):(e.push(r),r.once("end",s.bind(null,r)),r.once("error",t.emit.bind(t,"error")),r.pipe(t,{end:!1}),this)}function o(){return e.length==0}function s(r){e=e.filter(function(a){return a!==r}),!e.length&&t.readable&&t.end()}},ji=re(_i);const Xn=e=>{if(e!==void 0)throw new TypeError("The `input` and `inputFile` options cannot be both set.")},Fi=({input:e,inputFile:t})=>typeof t!="string"?e:(Xn(e),bs(t)),Gi=e=>{const t=Fi(e);if(Lt(t))throw new TypeError("The `input` option cannot be a stream in sync mode");return t},Bi=({input:e,inputFile:t})=>typeof t!="string"?e:(Xn(e),Cs(t)),Hi=(e,t)=>{const n=Bi(t);n!==void 0&&(Lt(n)?n.pipe(e.stdin):e.stdin.end(n))},Ui=(e,{all:t})=>{if(!t||!e.stdout&&!e.stderr)return;const n=ji();return e.stdout&&n.add(e.stdout),e.stderr&&n.add(e.stderr),n},Tt=async(e,t)=>{if(!(!e||t===void 0)){e.destroy();try{return await t}catch(n){return n.bufferedData}}},Dt=(e,{encoding:t,buffer:n,maxBuffer:o})=>{if(!(!e||!n))return t?Jn(e,{encoding:t,maxBuffer:o}):Jn.buffer(e,{maxBuffer:o})},Ki=async({stdout:e,stderr:t,all:n},{encoding:o,buffer:s,maxBuffer:r},a)=>{const c=Dt(e,{encoding:o,buffer:s,maxBuffer:r}),l=Dt(t,{encoding:o,buffer:s,maxBuffer:r}),u=Dt(n,{encoding:o,buffer:s,maxBuffer:r*2});try{return await Promise.all([a,c,l,u])}catch(d){return Promise.all([{error:d,signal:d.signal,timedOut:d.timedOut},Tt(e,c),Tt(t,l),Tt(n,u)])}},Wi=(async()=>{})().constructor.prototype,qi=["then","catch","finally"].map(e=>[e,Reflect.getOwnPropertyDescriptor(Wi,e)]),Qn=(e,t)=>{for(const[n,o]of qi){const s=typeof t=="function"?(...r)=>Reflect.apply(o.value,t(),r):o.value.bind(t);Reflect.defineProperty(e,n,{...o,value:s})}},zi=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)})}),Zn=(e,t=[])=>Array.isArray(t)?[e,...t]:[e],Yi=/^[\w.-]+$/,Vi=/"/g,Ji=e=>typeof e!="string"||Yi.test(e)?e:`"${e.replace(Vi,'\\"')}"`,eo=(e,t)=>Zn(e,t).join(" "),to=(e,t)=>Zn(e,t).map(n=>Ji(n)).join(" "),no=/ +/g,oo=e=>{const t=[];for(const n of e.trim().split(no)){const o=t[t.length-1];o&&o.endsWith("\\")?t[t.length-1]=`${o.slice(0,-1)} ${n}`:t.push(n)}return t},so=e=>{const t=typeof e;if(t==="string")return e;if(t==="number")return String(e);if(t==="object"&&e!==null&&!(e instanceof un)&&"stdout"in e){const n=typeof e.stdout;if(n==="string")return e.stdout;if(ln.isBuffer(e.stdout))return e.stdout.toString();throw new TypeError(`Unexpected "${n}" stdout in template expression`)}throw new TypeError(`Unexpected "${t}" in template expression`)},ro=(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)],Xi=({templates:e,expressions:t,tokens:n,index:o,template:s})=>{const r=s??e.raw[o],a=r.split(no).filter(Boolean),c=ro(n,a,r.startsWith(" "));if(o===t.length)return c;const l=t[o],u=Array.isArray(l)?l.map(d=>so(d)):[so(l)];return ro(c,u,r.endsWith(" "))},io=(e,t)=>{let n=[];for(const[o,s]of e.entries())n=Xi({templates:e,expressions:t,tokens:n,index:o,template:s});return n},Qi=As("execa").enabled,Fe=(e,t)=>String(e).padStart(t,"0"),Zi=()=>{const e=new Date;return`${Fe(e.getHours(),2)}:${Fe(e.getMinutes(),2)}:${Fe(e.getSeconds(),2)}.${Fe(e.getMilliseconds(),3)}`},ao=(e,{verbose:t})=>{t&&B.stderr.write(`[${Zi()}] ${e}
7
+ `)},ea=1e3*1e3*100,ta=({env:e,extendEnv:t,preferLocal:n,localDir:o,execPath:s})=>{const r=t?{...B.env,...e}:e;return n?Gr({env:r,cwd:o,execPath:s}):r},co=(e,t,n={})=>{const o=Dr._parse(e,t,n);return e=o.command,t=o.args,n=o.options,n={maxBuffer:ea,buffer:!0,stripFinalNewline:!0,extendEnv:!0,preferLocal:!1,localDir:n.cwd||B.cwd(),execPath:B.execPath,encoding:"utf8",reject:!0,cleanup:!0,all:!1,windowsHide:!0,verbose:Qi,...n},n.env=ta(n),n.stdio=Kn(n),B.platform==="win32"&&oe.basename(e,".exe")==="cmd"&&t.unshift("/q"),{file:e,args:t,options:n,parsed:o}},Ee=(e,t,n)=>typeof t!="string"&&!ln.isBuffer(t)?n===void 0?void 0:"":e.stripFinalNewline?Nr(t):t;function b(e,t,n){const o=co(e,t,n),s=eo(e,t),r=to(e,t);ao(r,o.options),Ai(o.options);let a;try{a=dt.spawn(o.file,o.args,o.options)}catch(y){const m=new dt.ChildProcess,x=Promise.reject(De({error:y,stdout:"",stderr:"",all:"",command:s,escapedCommand:r,parsed:o,timedOut:!1,isCanceled:!1,killed:!1}));return Qn(m,x),m}const c=zi(a),l=Pi(a,o.options,c),u=xi(a,o.options,l),d={isCanceled:!1};a.kill=gi.bind(null,a.kill.bind(a)),a.cancel=Ei.bind(null,a,d);const g=Gn(async()=>{const[{error:y,exitCode:m,signal:x,timedOut:S},A,$,P]=await Ki(a,o.options,u),C=Ee(o.options,A),k=Ee(o.options,$),L=Ee(o.options,P);if(y||m!==0||x!==null){const D=De({error:y,exitCode:m,signal:x,stdout:C,stderr:k,all:L,command:s,escapedCommand:r,parsed:o,timedOut:S,isCanceled:d.isCanceled||(o.options.signal?o.options.signal.aborted:!1),killed:a.killed});if(!o.options.reject)return D;throw D}return{command:s,escapedCommand:r,exitCode:0,stdout:C,stderr:k,all:L,failed:!1,timedOut:!1,isCanceled:!1,killed:!1}});return Hi(a,o.options),a.all=Ui(a,o.options),$i(a),Qn(a,g),a}function Nt(e,t,n){const o=co(e,t,n),s=eo(e,t),r=to(e,t);ao(r,o.options);const a=Gi(o.options);let c;try{c=dt.spawnSync(o.file,o.args,{...o.options,input:a})}catch(d){throw De({error:d,stdout:"",stderr:"",all:"",command:s,escapedCommand:r,parsed:o,timedOut:!1,isCanceled:!1,killed:!1})}const l=Ee(o.options,c.stdout,c.error),u=Ee(o.options,c.stderr,c.error);if(c.error||c.status!==0||c.signal!==null){const d=De({stdout:l,stderr:u,error:c.error,signal:c.signal,exitCode:c.status,command:s,escapedCommand:r,parsed:o,timedOut:c.error&&c.error.code==="ETIMEDOUT",isCanceled:!1,killed:c.signal!==null});if(!o.options.reject)return d;throw d}return{command:s,escapedCommand:r,exitCode:0,stdout:l,stderr:u,failed:!1,timedOut:!1,isCanceled:!1,killed:!1}}const na=({input:e,inputFile:t,stdio:n})=>e===void 0&&t===void 0&&n===void 0?{stdin:"inherit"}:{},lo=(e={})=>({preferLocal:!0,...na(e),...e});function uo(e){function t(n,...o){if(!Array.isArray(n))return uo({...e,...n});const[s,...r]=io(n,o);return b(s,r,lo(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]=io(n,o);return Nt(s,r,lo(e))},t}const oa=uo();function sa(e,t){const[n,...o]=oo(e);return b(n,o,t)}function ra(e,t){const[n,...o]=oo(e);return Nt(n,o,t)}function ia(e,t,n={}){t&&!Array.isArray(t)&&typeof t=="object"&&(n=t,t=[]);const o=ai(n),s=B.execArgv.filter(c=>!c.startsWith("--inspect")),{nodePath:r=B.execPath,nodeOptions:a=s}=n;return b(r,[...a,e,...Array.isArray(t)?t:[]],{...n,stdin:void 0,stdout:void 0,stderr:void 0,stdio:o,shell:!1})}var aa=Object.freeze({__proto__:null,execa:b,execaSync:Nt,$:oa,execaCommand:sa,execaCommandSync:ra,execaNode:ia});const{hasOwnProperty:_t}=Object.prototype,Ge=typeof process<"u"&&process.platform==="win32"?`\r
8
8
  `:`
9
- `,_t=(e,t)=>{const n=[];let o="";typeof t=="string"?t={section:t,whitespace:!1}:(t=t||Object.create(null),t.whitespace=t.whitespace===!0);const s=t.whitespace?" = ":"=";for(const r of Object.keys(e)){const a=e[r];if(a&&Array.isArray(a))for(const c of a)o+=le(r+"[]")+s+le(c)+Ge;else a&&typeof a=="object"?n.push(r):o+=le(r)+s+le(a)+Ge}t.section&&o.length&&(o="["+le(t.section)+"]"+Ge+o);for(const r of n){const a=mo(r).join("\\."),c=(t.section?t.section+".":"")+a,{whitespace:u}=t,l=_t(e[r],{section:c,whitespace:u});o.length&&l.length&&(o+=Ge),o+=l}return o},mo=e=>e.replace(/\1/g,"LITERAL\\1LITERAL").replace(/\\\./g,"").split(/\./).map(t=>t.replace(/\1/g,"\\.").replace(/\2LITERAL\\1LITERAL\2/g,"")),fo=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=Be(u[1]),o==="__proto__"){n=Object.create(null);continue}n=t[o]=t[o]||Object.create(null);continue}const l=Be(u[2]),d=l.length>2&&l.slice(-2)==="[]",f=d?l.slice(0,-2):l;if(f==="__proto__")continue;const g=u[3]?Be(u[4]):!0,y=g==="true"||g==="false"||g==="null"?JSON.parse(g):g;d&&(Nt.call(n,f)?Array.isArray(n[f])||(n[f]=[n[f]]):n[f]=[]),Array.isArray(n[f])?n[f].push(y):n[f]=y}const a=[];for(const c of Object.keys(t)){if(!Nt.call(t,c)||typeof t[c]!="object"||Array.isArray(t[c]))continue;const u=mo(c);n=t;const l=u.pop(),d=l.replace(/\\\./g,".");for(const f of u)f!=="__proto__"&&((!Nt.call(n,f)||typeof n[f]!="object")&&(n[f]=Object.create(null)),n=n[f]);n===t&&d===l||(n[d]=t[c],a.push(c))}for(const c of a)delete t[c];return t},po=e=>e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"),le=e=>typeof e!="string"||e.match(/[=\r\n]/)||e.match(/^\[/)||e.length>1&&po(e)||e!==e.trim()?JSON.stringify(e):e.split(";").join("\\;").split("#").join("\\#"),Be=(e,t)=>{if(e=(e||"").trim(),po(e)){e.charAt(0)==="'"&&(e=e.slice(1,-1));try{e=JSON.parse(e)}catch{}}else{let n=!1,o="";for(let s=0,r=e.length;s<r;s++){const a=e.charAt(s);if(n)"\\;#".indexOf(a)!==-1?o+=a:o+="\\"+a,n=!1;else{if(";#".indexOf(a)!==-1)break;a==="\\"?n=!0:o+=a}}return n&&(o+="\\"),o.trim()}return e};var ra={parse:fo,decode:fo,stringify:_t,encode:_t,safe:le,unsafe:Be},ue=se(ra);const de=3,ia=3,ho={mode:"none",maxHunkLines:0,maxDiffLines:0},aa=(e,t={})=>{const n={...ho,...t},o=e.split(`
10
- `).length;return n.mode==="none"||!e.trim()?{diff:e,stats:{originalLines:o,compressedLines:o,originalChars:e.length,compressedChars:e.length,truncatedHunks:0,truncatedFiles:0}}:ca(e,n,o)},ca=(e,t,n)=>{const o=la(e),s=[];let r=0,a=0;const c=t.maxDiffLines>0?t.maxDiffLines:1/0,u=t.maxHunkLines>0?t.maxHunkLines:1/0;for(let f=0;f<o.length;f++){if(s.length>=c){a+=o.length-f;break}const{lines:g,hunksTruncated:y}=ua(o[f],u);r+=y;const m=c-s.length;if(g.length>m){s.push(...g.slice(0,m)),a+=o.length-f-1;break}s.push(...g)}if(r>0||a>0){const f=[];r>0&&f.push(`${r} hunk${r>1?"s":""} truncated`),a>0&&f.push(`${a} file${a>1?"s":""} omitted`),s.push("",`[diff compressed \u2014 ${f.join(", ")}]`)}const d=s.join(`
11
- `);return{diff:d,stats:{originalLines:n,compressedLines:s.length,originalChars:e.length,compressedChars:d.length,truncatedHunks:r,truncatedFiles:a}}},la=e=>{const t=e.split(`
12
- `),n=[];let o=[];for(const s of t)s.startsWith("diff --git ")?(o.length>0&&n.push(o),o=[s]):o.push(s);return o.length>0&&n.push(o),n},ua=(e,t)=>{const o=[`=== ${ma(e)} ===`];let s=0;const r=[];let a=null;for(const c of e)if(!fa(c)){if(c.startsWith("@@")){a&&r.push(a),a={header:c,lines:[]};continue}a&&a.lines.push(c)}a&&r.push(a);for(const c of r){o.push(c.header);const u=da(c.lines);if(t>0&&u.length>t){const l=u.length-t;o.push(...u.slice(0,t)),o.push(`[... ${l} lines truncated]`),s++}else o.push(...u)}return{lines:o,hunksTruncated:s}},da=e=>{if(e.length===0)return[];const t=e.map(r=>r.startsWith("+")||r.startsWith("-")),n=new Array(e.length).fill(!1);for(let r=0;r<e.length;r++)if(t[r]){n[r]=!0;for(let a=1;a<=ia;a++)r-a>=0&&(n[r-a]=!0),r+a<e.length&&(n[r+a]=!0);continue}const o=[];let s=!1;for(let r=0;r<e.length;r++)n[r]?(s&&(o.push(" ..."),s=!1),o.push(e[r])):s=!0;return o},ma=e=>{const n=(e[0]||"").match(/^diff --git a\/(.+?) b\/(.+)$/);if(!n)return"unknown";const[,o,s]=n;return o!==s?`${o} \u2192 ${s}`:s},fa=e=>e.startsWith("diff --git ")||e.startsWith("index ")||e.startsWith("--- a/")||e.startsWith("--- /dev/null")||e.startsWith("+++ b/")||e.startsWith("+++ /dev/null")||e.startsWith("old mode ")||e.startsWith("new mode ")||e.startsWith("new file mode ")||e.startsWith("deleted file mode ")||e.startsWith("similarity index ")||e.startsWith("rename from ")||e.startsWith("rename to ")||e.startsWith("Binary files ");class p extends Error{constructor(t,n={}){super(t,{cause:n.cause}),this.name="KnownError",this.code=n.code,this.suggestions=n.suggestions||[]}}const ve=" ",q=e=>{if(e instanceof Error){if(e instanceof p){e.suggestions.length>0&&(console.error(""),console.error(`${ve}${h.yellow("Suggestions:")}`),e.suggestions.forEach(t=>{console.error(`${ve} ${h.dim("\u2022")} ${t}`)}));return}e.stack&&console.error(h.dim(e.stack.split(`
9
+ `,jt=(e,t)=>{const n=[];let o="";typeof t=="string"?t={section:t,whitespace:!1}:(t=t||Object.create(null),t.whitespace=t.whitespace===!0);const s=t.whitespace?" = ":"=";for(const r of Object.keys(e)){const a=e[r];if(a&&Array.isArray(a))for(const c of a)o+=ue(r+"[]")+s+ue(c)+Ge;else a&&typeof a=="object"?n.push(r):o+=ue(r)+s+ue(a)+Ge}t.section&&o.length&&(o="["+ue(t.section)+"]"+Ge+o);for(const r of n){const a=mo(r).join("\\."),c=(t.section?t.section+".":"")+a,{whitespace:l}=t,u=jt(e[r],{section:c,whitespace:l});o.length&&u.length&&(o+=Ge),o+=u}return o},mo=e=>e.replace(/\1/g,"LITERAL\\1LITERAL").replace(/\\\./g,"").split(/\./).map(t=>t.replace(/\1/g,"\\.").replace(/\2LITERAL\\1LITERAL\2/g,"")),fo=e=>{const t=Object.create(null);let n=t,o=null;const s=/^\[([^\]]*)\]$|^([^=]+)(=(.*))?$/i,r=e.split(/[\r\n]+/g);for(const c of r){if(!c||c.match(/^\s*[;#]/))continue;const l=c.match(s);if(!l)continue;if(l[1]!==void 0){if(o=Be(l[1]),o==="__proto__"){n=Object.create(null);continue}n=t[o]=t[o]||Object.create(null);continue}const u=Be(l[2]),d=u.length>2&&u.slice(-2)==="[]",f=d?u.slice(0,-2):u;if(f==="__proto__")continue;const g=l[3]?Be(l[4]):!0,y=g==="true"||g==="false"||g==="null"?JSON.parse(g):g;d&&(_t.call(n,f)?Array.isArray(n[f])||(n[f]=[n[f]]):n[f]=[]),Array.isArray(n[f])?n[f].push(y):n[f]=y}const a=[];for(const c of Object.keys(t)){if(!_t.call(t,c)||typeof t[c]!="object"||Array.isArray(t[c]))continue;const l=mo(c);n=t;const u=l.pop(),d=u.replace(/\\\./g,".");for(const f of l)f!=="__proto__"&&((!_t.call(n,f)||typeof n[f]!="object")&&(n[f]=Object.create(null)),n=n[f]);n===t&&d===u||(n[d]=t[c],a.push(c))}for(const c of a)delete t[c];return t},po=e=>e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"),ue=e=>typeof e!="string"||e.match(/[=\r\n]/)||e.match(/^\[/)||e.length>1&&po(e)||e!==e.trim()?JSON.stringify(e):e.split(";").join("\\;").split("#").join("\\#"),Be=(e,t)=>{if(e=(e||"").trim(),po(e)){e.charAt(0)==="'"&&(e=e.slice(1,-1));try{e=JSON.parse(e)}catch{}}else{let n=!1,o="";for(let s=0,r=e.length;s<r;s++){const a=e.charAt(s);if(n)"\\;#".indexOf(a)!==-1?o+=a:o+="\\"+a,n=!1;else{if(";#".indexOf(a)!==-1)break;a==="\\"?n=!0:o+=a}}return n&&(o+="\\"),o.trim()}return e};var ca={parse:fo,decode:fo,stringify:jt,encode:jt,safe:ue,unsafe:Be},de=re(ca);const me=3,la=3,ho={mode:"none",maxHunkLines:0,maxDiffLines:0},ua=(e,t={})=>{const n={...ho,...t},o=e.split(`
10
+ `).length;return n.mode==="none"||!e.trim()?{diff:e,stats:{originalLines:o,compressedLines:o,originalChars:e.length,compressedChars:e.length,truncatedHunks:0,truncatedFiles:0}}:da(e,n,o)},da=(e,t,n)=>{const o=ma(e),s=[];let r=0,a=0;const c=t.maxDiffLines>0?t.maxDiffLines:1/0,l=t.maxHunkLines>0?t.maxHunkLines:1/0;for(let f=0;f<o.length;f++){if(s.length>=c){a+=o.length-f;break}const{lines:g,hunksTruncated:y}=fa(o[f],l);r+=y;const m=c-s.length;if(g.length>m){s.push(...g.slice(0,m)),a+=o.length-f-1;break}s.push(...g)}if(r>0||a>0){const f=[];r>0&&f.push(`${r} hunk${r>1?"s":""} truncated`),a>0&&f.push(`${a} file${a>1?"s":""} omitted`),s.push("",`[diff compressed \u2014 ${f.join(", ")}]`)}const d=s.join(`
11
+ `);return{diff:d,stats:{originalLines:n,compressedLines:s.length,originalChars:e.length,compressedChars:d.length,truncatedHunks:r,truncatedFiles:a}}},ma=e=>{const t=e.split(`
12
+ `),n=[];let o=[];for(const s of t)s.startsWith("diff --git ")?(o.length>0&&n.push(o),o=[s]):o.push(s);return o.length>0&&n.push(o),n},fa=(e,t)=>{const o=[`=== ${ha(e)} ===`];let s=0;const r=[];let a=null;for(const c of e)if(!ga(c)){if(c.startsWith("@@")){a&&r.push(a),a={header:c,lines:[]};continue}a&&a.lines.push(c)}a&&r.push(a);for(const c of r){o.push(c.header);const l=pa(c.lines);if(t>0&&l.length>t){const u=l.length-t;o.push(...l.slice(0,t)),o.push(`[... ${u} lines truncated]`),s++}else o.push(...l)}return{lines:o,hunksTruncated:s}},pa=e=>{if(e.length===0)return[];const t=e.map(r=>r.startsWith("+")||r.startsWith("-")),n=new Array(e.length).fill(!1);for(let r=0;r<e.length;r++)if(t[r]){n[r]=!0;for(let a=1;a<=la;a++)r-a>=0&&(n[r-a]=!0),r+a<e.length&&(n[r+a]=!0);continue}const o=[];let s=!1;for(let r=0;r<e.length;r++)n[r]?(s&&(o.push(" ..."),s=!1),o.push(e[r])):s=!0;return o},ha=e=>{const n=(e[0]||"").match(/^diff --git a\/(.+?) b\/(.+)$/);if(!n)return"unknown";const[,o,s]=n;return o!==s?`${o} \u2192 ${s}`:s},ga=e=>e.startsWith("diff --git ")||e.startsWith("index ")||e.startsWith("--- a/")||e.startsWith("--- /dev/null")||e.startsWith("+++ b/")||e.startsWith("+++ /dev/null")||e.startsWith("old mode ")||e.startsWith("new mode ")||e.startsWith("new file mode ")||e.startsWith("deleted file mode ")||e.startsWith("similarity index ")||e.startsWith("rename from ")||e.startsWith("rename to ")||e.startsWith("Binary files ");class p extends Error{constructor(t,n={}){super(t,{cause:n.cause}),this.name="KnownError",this.code=n.code,this.suggestions=n.suggestions||[]}}const ve=" ",q=e=>{if(e instanceof Error){if(e instanceof p){e.suggestions.length>0&&(console.error(""),console.error(`${ve}${h.yellow("Suggestions:")}`),e.suggestions.forEach(t=>{console.error(`${ve} ${h.dim("\u2022")} ${t}`)}));return}e.stack&&console.error(h.dim(e.stack.split(`
13
13
  `).slice(1).join(`
14
14
  `))),console.error(`
15
15
  ${ve}${h.dim(`aicommit2 v${Pn}`)}`),console.error(`
16
- ${ve}Please open a Bug report with the information above:`),console.error(`${ve}https://github.com/tak-bro/aicommit2/issues/new/choose`)}},He=e=>I.lstat(e).then(()=>!0,()=>!1),go=async e=>{try{await I.mkdir(e,{recursive:!0})}catch(t){if(t.code!=="EEXIST")throw t}},pa=e=>e&&`${e[0].toUpperCase()}${e.slice(1)}`,ha=(e,t)=>{const n=Math.ceil(e),o=Math.floor(t);return Math.floor(Math.random()*(o-n+1))+n},yo=(e,t)=>e.disabled&&!t.disabled?1:!e.disabled&&t.disabled?-1:0,jt=e=>e.reduce((t,n)=>Array.isArray(n)?t.concat(jt(n)):t.concat(n),[]),ga=(e,t=5)=>e.replace(/[\n\r]/g,"").split(" ").slice(0,t).join(" "),ya=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)},wa=e=>{const t=e%360,n=65+e%15,o=45+e%10;return`hsl(${t}, ${n}%, ${o}%)`},Ca=e=>{const[t,n,o]=e.match(/\d+/g).map((f,g)=>g===0?Number(f):Number(f)/100),s=(1-Math.abs(2*o-1))*n,r=s*(1-Math.abs(t/60%2-1)),a=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 g=Math.round((f+a)*255).toString(16);return g.length===1?"0"+g:g};return`#${d(c)}${d(u)}${d(l)}`},ba=e=>{const t=ya(e),n=wa(t);return{primary:Ca(n),secondary:"#FFFFFF"}},Ea=e=>{try{return{ok:!0,data:JSON.parse(e)}}catch(t){return{ok:!1,error:t}}},Ue=e=>{if(!e||typeof e!="string")return"";if(v.isAbsolute(e))return v.resolve(e);if(xe){const t=v.dirname(xe),n=v.join(t,e);return v.resolve(n)}else return""},va=["","conventional","gitmoji"],Pe="http://localhost:11434",{hasOwnProperty:Pa}=Object.prototype,Ft=(e,t)=>Pa.call(e,t),me=["OPENAI","COPILOT_SDK","OPENROUTER","OLLAMA","HUGGINGFACE","GEMINI","ANTHROPIC","MISTRAL","CODESTRAL","COHERE","GROQ","PERPLEXITY","DEEPSEEK","GITHUB_MODELS","BEDROCK"],wo=e=>{const t=ke.platform(),n=ke.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=v.join(n,"Library","Caches"):s=v.join(n,"Library","Application Support");else if(t==="win32")s=process.env.LOCALAPPDATA||n;else switch(e){case"config":s=v.join(n,".config");break;case"data":s=v.join(n,".local","share");break;case"cache":s=v.join(n,".cache");break;case"state":s=v.join(n,".local","state");break;default:s=n}return o||s},Co=v.join(wo("config"),"aicommit2"),U=v.join(wo("state"),"aicommit2","logs"),bo=v.join(Co,"config.ini"),Eo=v.join(U,"aicommit2-%DATE%.log"),vo=v.join(U,"exceptions-%DATE%.log"),Aa=e=>{const t=Object.keys(e),n=new Set([...me,...t.filter(o=>/^[A-Z][A-Z0-9_]*$/.test(o))]);return Array.from(n)},E=(e,t,n)=>{if(!t)throw new p(`Invalid config property ${e}: ${n}`)},G=(e,t=!1)=>n=>typeof n=="boolean"?n:n==null?t:(E(e,/^(?:true|false)$/.test(n),"Must be a boolean(true or false)"),n==="true"),Ke=e=>t=>{if(!t)return{};if(typeof t=="object")return E(e,!Array.isArray(t),"Must be a JSON object"),t;try{const n=JSON.parse(t);return E(e,typeof n=="object"&&n!==null&&!Array.isArray(n),"Must be a valid JSON object"),n}catch(n){throw new p(`Invalid ${e}: Must be valid JSON. Error: ${n.message}`)}},i={systemPrompt(e){return e||""},systemPromptPath(e){return e||""},codeReviewPromptPath(e){return e||""},timeout(e){if(!e)return 6e4;E("timeout",/^\d+$/.test(e),"Must be an integer");const t=Number(e);return E("timeout",t>=500,"Must be greater than 500ms"),t},temperature(e){if(!e)return .7;E("temperature",/^(2|\d)(\.\d{1,2})?$/.test(e),"Must be decimal between 0 and 2");const t=Number(e);return E("temperature",t>0,"Must be greater than 0"),E("temperature",t<=2,"Must be less than or equal to 2"),t},maxTokens(e){return e?(E("maxTokens",/^\d+$/.test(e),"Must be an integer"),Number(e)):8192},logLevel(e){return e?(E("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||Eo},exceptionLogFilePath(e){return e||vo},locale(e){return e?(E("locale",e,"Cannot be empty"),E("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;E("generate",/^\d+$/.test(e),"Must be an integer");const t=Number(e);return E("generate",t>0,"Must be greater than 0"),E("generate",t<=5,"Must be less or equal to 5"),t},type(e){return e?(E("type",va.includes(e),"Invalid commit type"),e):"conventional"},maxLength(e){if(!e)return 50;E("maxLength",/^\d+$/.test(e),"Must be an integer");const t=Number(e);return E("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;E("topP",/^(1|\d)(\.\d{1,2})?$/.test(e),"Must be decimal between 0 and 1");const t=Number(e);return E("topP",t>0,"Must be greater than 0"),E("topP",t<=1,"Must be less than or equal to 1"),t},logging:G("logging",!0),includeBody:G("includeBody"),codeReview:G("codeReview"),disabled:G("disabled"),watchMode:G("watchMode"),forceGit:G("forceGit"),stream:G("stream"),disableLowerCase:G("disableLowerCase"),jjAutoNew:G("jjAutoNew"),autoCopy:G("autoCopy"),modelNameDisplay:e=>e?(E("modelNameDisplay",/^(?:none|short|full)$/.test(e),"Must be none, short, or full"),e):"short",diffCompression:e=>e?(E("diffCompression",/^(?:none|compact)$/.test(e),"Must be none or compact"),e):ho.mode,maxHunkLines:e=>e?(E("maxHunkLines",/^\d+$/.test(e),"Must be an integer"),Number(e)):0,maxDiffLines:e=>e?(E("maxDiffLines",/^\d+$/.test(e),"Must be an integer"),Number(e)):0,diffContext:e=>{if(!e)return de;E("diffContext",/^\d+$/.test(e),"Must be an integer");const t=Number(e);return E("diffContext",t>=0&&t<=10,"Must be between 0 and 10"),t},useStats:G("useStats",!0),statsDays:e=>{if(!e)return 30;E("statsDays",/^\d+$/.test(e),"Must be an integer");const t=Number(e);return E("statsDays",t>0,"Must be greater than 0"),t}},Ae={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?(E("OPENAI.url",/^https?:\/\//.test(e),"Must be a valid URL"),e):"https://api.openai.com",path:e=>e||"/v1/chat/completions",proxy:e=>e||"",topP:i.topP,systemPrompt:i.systemPrompt,systemPromptPath:i.systemPromptPath,codeReviewPromptPath:i.codeReviewPromptPath,timeout:i.timeout,temperature:i.temperature,maxTokens:i.maxTokens,logging:i.logging,locale:i.locale,generate:i.generate,type:i.type,maxLength:i.maxLength,includeBody:i.includeBody,codeReview:i.codeReview,disabled:i.disabled,stream:i.stream,watchMode:i.watchMode,disableLowerCase:i.disableLowerCase,diffCompression:i.diffCompression,maxHunkLines:i.maxHunkLines,maxDiffLines:i.maxDiffLines,diffContext:i.diffContext},OPENROUTER:{key:e=>e||"",envKey:e=>e||"",model:e=>e?(typeof e=="string"?e?.split(","):e).map(n=>n.trim()).filter(n=>!!n&&n.length>0):["openrouter/auto"],url:e=>e?(E("OPENROUTER.url",/^https?:\/\//.test(e),"Must be a valid URL"),e):"https://openrouter.ai",path:e=>e||"/api/v1/chat/completions",responseFormat:Ke("OPENROUTER.responseFormat"),provider:Ke("OPENROUTER.provider"),reasoning:Ke("OPENROUTER.reasoning"),topP:i.topP,systemPrompt:i.systemPrompt,systemPromptPath:i.systemPromptPath,codeReviewPromptPath:i.codeReviewPromptPath,timeout:i.timeout,temperature:i.temperature,maxTokens:i.maxTokens,logging:i.logging,locale:i.locale,generate:i.generate,type:i.type,maxLength:i.maxLength,includeBody:i.includeBody,codeReview:i.codeReview,disabled:i.disabled,stream:i.stream,watchMode:i.watchMode,disableLowerCase:i.disableLowerCase,diffCompression:i.diffCompression,maxHunkLines:i.maxHunkLines,maxDiffLines:i.maxDiffLines,diffContext:i.diffContext},HUGGINGFACE:{cookie:e=>e||"",model:e=>e?(typeof e=="string"?e?.split(","):e).map(n=>n.trim()).filter(n=>!!n&&n.length>0):["CohereForAI/c4ai-command-r-plus"],systemPrompt:i.systemPrompt,systemPromptPath:i.systemPromptPath,codeReviewPromptPath:i.codeReviewPromptPath,timeout:i.timeout,temperature:i.temperature,maxTokens:i.maxTokens,topP:i.topP,logging:i.logging,locale:i.locale,generate:i.generate,type:i.type,maxLength:i.maxLength,includeBody:i.includeBody,codeReview:i.codeReview,disabled:i.disabled,stream:i.stream,watchMode:i.watchMode,disableLowerCase:i.disableLowerCase,diffCompression:i.diffCompression,maxHunkLines:i.maxHunkLines,maxDiffLines:i.maxDiffLines,diffContext:i.diffContext},GEMINI:{key:e=>e||"",envKey:e=>e||"",model:e=>e?(typeof e=="string"?e?.split(","):e).map(n=>n.trim()).filter(n=>!!n&&n.length>0):["gemini-3-flash-preview"],systemPrompt:i.systemPrompt,systemPromptPath:i.systemPromptPath,codeReviewPromptPath:i.codeReviewPromptPath,timeout:i.timeout,temperature:i.temperature,maxTokens:i.maxTokens,logging:i.logging,locale:i.locale,generate:i.generate,type:i.type,maxLength:i.maxLength,includeBody:i.includeBody,topP:i.topP,codeReview:i.codeReview,disabled:i.disabled,stream:i.stream,watchMode:i.watchMode,disableLowerCase:i.disableLowerCase,diffCompression:i.diffCompression,maxHunkLines:i.maxHunkLines,maxDiffLines:i.maxDiffLines,diffContext:i.diffContext},ANTHROPIC:{key:e=>e||"",envKey:e=>e||"",model:e=>e?(typeof e=="string"?e?.split(","):e).map(n=>n.trim()).filter(n=>!!n&&n.length>0):["claude-sonnet-4-20250514"],systemPrompt:i.systemPrompt,systemPromptPath:i.systemPromptPath,codeReviewPromptPath:i.codeReviewPromptPath,timeout:i.timeout,temperature:i.temperature,maxTokens:i.maxTokens,logging:i.logging,locale:i.locale,generate:i.generate,type:i.type,maxLength:i.maxLength,includeBody:i.includeBody,topP:i.topP,codeReview:i.codeReview,disabled:i.disabled,stream:i.stream,watchMode:i.watchMode,disableLowerCase:i.disableLowerCase,diffCompression:i.diffCompression,maxHunkLines:i.maxHunkLines,maxDiffLines:i.maxDiffLines,diffContext:i.diffContext},MISTRAL:{key:e=>e||"",envKey:e=>e||"",model:e=>e?(typeof e=="string"?e?.split(","):e).map(n=>n.trim()).filter(n=>!!n&&n.length>0):["mistral-small-latest"],systemPrompt:i.systemPrompt,systemPromptPath:i.systemPromptPath,codeReviewPromptPath:i.codeReviewPromptPath,timeout:i.timeout,temperature:i.temperature,maxTokens:i.maxTokens,logging:i.logging,locale:i.locale,generate:i.generate,type:i.type,maxLength:i.maxLength,includeBody:i.includeBody,topP:i.topP,codeReview:i.codeReview,disabled:i.disabled,stream:i.stream,watchMode:i.watchMode,disableLowerCase:i.disableLowerCase,diffCompression:i.diffCompression,maxHunkLines:i.maxHunkLines,maxDiffLines:i.maxDiffLines,diffContext:i.diffContext},CODESTRAL:{key:e=>e||"",envKey:e=>e||"",model:e=>e?(typeof e=="string"?e?.split(","):e).map(n=>n.trim()).filter(n=>!!n&&n.length>0):["codestral-latest"],topP:i.topP,systemPrompt:i.systemPrompt,systemPromptPath:i.systemPromptPath,codeReviewPromptPath:i.codeReviewPromptPath,timeout:i.timeout,temperature:i.temperature,maxTokens:i.maxTokens,logging:i.logging,locale:i.locale,generate:i.generate,type:i.type,maxLength:i.maxLength,includeBody:i.includeBody,codeReview:i.codeReview,disabled:i.disabled,stream:i.stream,watchMode:i.watchMode,disableLowerCase:i.disableLowerCase,diffCompression:i.diffCompression,maxHunkLines:i.maxHunkLines,maxDiffLines:i.maxDiffLines,diffContext:i.diffContext},OLLAMA:{model:e=>e?(typeof e=="string"?e?.split(","):e).map(n=>n.trim()).filter(n=>!!n&&n.length>0):[],host:e=>e?(E("OLLAMA.host",/^https?:\/\//.test(e),"Must be a valid URL"),e):Pe,timeout:e=>{if(!e)return 1e5;E("OLLAMA.timeout",/^\d+$/.test(e),"Must be an integer");const t=Number(e);return E("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;E("OLLAMA.numCtx",/^\d+$/.test(e),"Must be an integer");const t=Number(e);return E("OLLAMA.numCtx",t>=2048,"Must be greater than 2048"),t},systemPrompt:i.systemPrompt,systemPromptPath:i.systemPromptPath,codeReviewPromptPath:i.codeReviewPromptPath,temperature:i.temperature,maxTokens:i.maxTokens,logging:i.logging,locale:i.locale,generate:i.generate,type:i.type,maxLength:i.maxLength,includeBody:i.includeBody,topP:i.topP,codeReview:i.codeReview,disabled:i.disabled,stream:i.stream,watchMode:i.watchMode,disableLowerCase:i.disableLowerCase,diffCompression:i.diffCompression,maxHunkLines:i.maxHunkLines,maxDiffLines:i.maxDiffLines,diffContext:i.diffContext},COHERE:{key:e=>e||"",envKey:e=>e||"",url:e=>e?(E("COHERE.url",/^https?:\/\//.test(e),"Must be a valid URL"),e):"https://api.cohere.ai",model:e=>e?(typeof e=="string"?e?.split(","):e).map(n=>n.trim()).filter(n=>!!n&&n.length>0):["command-a-03-2025"],systemPrompt:i.systemPrompt,systemPromptPath:i.systemPromptPath,codeReviewPromptPath:i.codeReviewPromptPath,temperature:i.temperature,maxTokens:i.maxTokens,logging:i.logging,locale:i.locale,timeout:i.timeout,generate:i.generate,type:i.type,maxLength:i.maxLength,includeBody:i.includeBody,topP:i.topP,codeReview:i.codeReview,disabled:i.disabled,stream:i.stream,watchMode:i.watchMode,disableLowerCase:i.disableLowerCase,diffCompression:i.diffCompression,maxHunkLines:i.maxHunkLines,maxDiffLines:i.maxDiffLines,diffContext:i.diffContext},GROQ:{key:e=>e||"",envKey:e=>e||"",model:e=>e?(typeof e=="string"?e?.split(","):e).map(n=>n.trim()).filter(n=>!!n&&n.length>0):["llama-3.3-70b-versatile"],systemPrompt:i.systemPrompt,systemPromptPath:i.systemPromptPath,codeReviewPromptPath:i.codeReviewPromptPath,timeout:i.timeout,temperature:i.temperature,maxTokens:i.maxTokens,logging:i.logging,locale:i.locale,generate:i.generate,type:i.type,maxLength:i.maxLength,includeBody:i.includeBody,topP:i.topP,codeReview:i.codeReview,disabled:i.disabled,stream:i.stream,watchMode:i.watchMode,disableLowerCase:i.disableLowerCase,diffCompression:i.diffCompression,maxHunkLines:i.maxHunkLines,maxDiffLines:i.maxDiffLines,diffContext:i.diffContext},PERPLEXITY:{key:e=>e||"",envKey:e=>e||"",model:e=>e?(typeof e=="string"?e?.split(","):e).map(n=>n.trim()).filter(n=>!!n&&n.length>0):["sonar"],topP:i.topP,systemPrompt:i.systemPrompt,systemPromptPath:i.systemPromptPath,codeReviewPromptPath:i.codeReviewPromptPath,timeout:i.timeout,temperature:i.temperature,maxTokens:i.maxTokens,logging:i.logging,locale:i.locale,generate:i.generate,type:i.type,maxLength:i.maxLength,includeBody:i.includeBody,codeReview:i.codeReview,disabled:i.disabled,stream:i.stream,watchMode:i.watchMode,disableLowerCase:i.disableLowerCase,diffCompression:i.diffCompression,maxHunkLines:i.maxHunkLines,maxDiffLines:i.maxDiffLines,diffContext:i.diffContext},DEEPSEEK:{key:e=>e||"",envKey:e=>e||"",model:e=>e?(typeof e=="string"?e?.split(","):e).map(n=>n.trim()).filter(n=>!!n&&n.length>0):["deepseek-chat"],topP:i.topP,systemPrompt:i.systemPrompt,systemPromptPath:i.systemPromptPath,codeReviewPromptPath:i.codeReviewPromptPath,timeout:i.timeout,temperature:i.temperature,maxTokens:i.maxTokens,logging:i.logging,locale:i.locale,generate:i.generate,type:i.type,maxLength:i.maxLength,includeBody:i.includeBody,codeReview:i.codeReview,disabled:i.disabled,stream:i.stream,watchMode:i.watchMode,disableLowerCase:i.disableLowerCase,diffCompression:i.diffCompression,maxHunkLines:i.maxHunkLines,maxDiffLines:i.maxDiffLines,diffContext:i.diffContext},GITHUB_MODELS:{key:e=>e||"",envKey:e=>e||"",model:e=>e?(typeof e=="string"?e?.split(","):e).map(n=>n.trim()).filter(n=>!!n&&n.length>0):["openai/gpt-4o-mini"],systemPrompt:i.systemPrompt,systemPromptPath:i.systemPromptPath,codeReviewPromptPath:i.codeReviewPromptPath,timeout:i.timeout,temperature:i.temperature,maxTokens:i.maxTokens,logging:i.logging,locale:i.locale,generate:i.generate,type:i.type,maxLength:i.maxLength,includeBody:i.includeBody,topP:i.topP,codeReview:i.codeReview,disabled:i.disabled,stream:i.stream,watchMode:i.watchMode,disableLowerCase:i.disableLowerCase,diffCompression:i.diffCompression,maxHunkLines:i.maxHunkLines,maxDiffLines:i.maxDiffLines,diffContext:i.diffContext},COPILOT_SDK:{key:e=>e||"",envKey:e=>e||"",model:e=>e?(typeof e=="string"?e?.split(","):e).map(n=>n.trim()).filter(n=>!!n&&n.length>0):["gpt-4.1"],systemPrompt:i.systemPrompt,systemPromptPath:i.systemPromptPath,codeReviewPromptPath:i.codeReviewPromptPath,timeout:i.timeout,temperature:i.temperature,maxTokens:i.maxTokens,logging:i.logging,locale:i.locale,generate:i.generate,type:i.type,maxLength:i.maxLength,includeBody:i.includeBody,topP:i.topP,codeReview:i.codeReview,disabled:i.disabled,stream:i.stream,watchMode:i.watchMode,disableLowerCase:i.disableLowerCase,diffCompression:i.diffCompression,maxHunkLines:i.maxHunkLines,maxDiffLines:i.maxDiffLines,diffContext:i.diffContext},BEDROCK:{key:e=>e||"",envKey:e=>e&&e.length>0?e:"BEDROCK_API_KEY",model:e=>e?(typeof e=="string"?e?.split(","):e).map(n=>{const o=n.trim();return o&&!o.includes(".")&&!o.includes(":")&&console.warn(`[Bedrock] Model ID "${o}" may be invalid.
16
+ ${ve}Please open a Bug report with the information above:`),console.error(`${ve}https://github.com/tak-bro/aicommit2/issues/new/choose`)}},He=e=>I.lstat(e).then(()=>!0,()=>!1),go=async e=>{try{await I.mkdir(e,{recursive:!0})}catch(t){if(t.code!=="EEXIST")throw t}},ya=e=>e&&`${e[0].toUpperCase()}${e.slice(1)}`,wa=(e,t)=>{const n=Math.ceil(e),o=Math.floor(t);return Math.floor(Math.random()*(o-n+1))+n},yo=(e,t)=>e.disabled&&!t.disabled?1:!e.disabled&&t.disabled?-1:0,Ft=e=>e.reduce((t,n)=>Array.isArray(n)?t.concat(Ft(n)):t.concat(n),[]),Ca=(e,t=5)=>e.replace(/[\n\r]/g,"").split(" ").slice(0,t).join(" "),ba=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)},Ea=e=>{const t=e%360,n=65+e%15,o=45+e%10;return`hsl(${t}, ${n}%, ${o}%)`},va=e=>{const[t,n,o]=e.match(/\d+/g).map((f,g)=>g===0?Number(f):Number(f)/100),s=(1-Math.abs(2*o-1))*n,r=s*(1-Math.abs(t/60%2-1)),a=o-s/2;let c,l,u;t<60?[c,l,u]=[s,r,0]:t<120?[c,l,u]=[r,s,0]:t<180?[c,l,u]=[0,s,r]:t<240?[c,l,u]=[0,r,s]:t<300?[c,l,u]=[r,0,s]:[c,l,u]=[s,0,r];const d=f=>{const g=Math.round((f+a)*255).toString(16);return g.length===1?"0"+g:g};return`#${d(c)}${d(l)}${d(u)}`},Pa=e=>{const t=ba(e),n=Ea(t);return{primary:va(n),secondary:"#FFFFFF"}},Aa=e=>{try{return{ok:!0,data:JSON.parse(e)}}catch(t){return{ok:!1,error:t}}},Ue=e=>{if(!e||typeof e!="string")return"";if(v.isAbsolute(e))return v.resolve(e);if(xe){const t=v.dirname(xe),n=v.join(t,e);return v.resolve(n)}else return""},xa=["","conventional","gitmoji"],Pe="http://localhost:11434",{hasOwnProperty:Sa}=Object.prototype,Gt=(e,t)=>Sa.call(e,t),fe=["OPENAI","COPILOT_SDK","OPENROUTER","OLLAMA","HUGGINGFACE","GEMINI","ANTHROPIC","MISTRAL","CODESTRAL","COHERE","GROQ","PERPLEXITY","DEEPSEEK","GITHUB_MODELS","BEDROCK"],wo=e=>{const t=ke.platform(),n=ke.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=v.join(n,"Library","Caches"):s=v.join(n,"Library","Application Support");else if(t==="win32")s=process.env.LOCALAPPDATA||n;else switch(e){case"config":s=v.join(n,".config");break;case"data":s=v.join(n,".local","share");break;case"cache":s=v.join(n,".cache");break;case"state":s=v.join(n,".local","state");break;default:s=n}return o||s},Co=v.join(wo("config"),"aicommit2"),U=v.join(wo("state"),"aicommit2","logs"),bo=v.join(Co,"config.ini"),Eo=v.join(U,"aicommit2-%DATE%.log"),vo=v.join(U,"exceptions-%DATE%.log"),$a=e=>{const t=Object.keys(e),n=new Set([...fe,...t.filter(o=>/^[A-Z][A-Z0-9_]*$/.test(o))]);return Array.from(n)},E=(e,t,n)=>{if(!t)throw new p(`Invalid config property ${e}: ${n}`)},G=(e,t=!1)=>n=>typeof n=="boolean"?n:n==null?t:(E(e,/^(?:true|false)$/.test(n),"Must be a boolean(true or false)"),n==="true"),Ke=e=>t=>{if(!t)return{};if(typeof t=="object")return E(e,!Array.isArray(t),"Must be a JSON object"),t;try{const n=JSON.parse(t);return E(e,typeof n=="object"&&n!==null&&!Array.isArray(n),"Must be a valid JSON object"),n}catch(n){throw new p(`Invalid ${e}: Must be valid JSON. Error: ${n.message}`)}},i={systemPrompt(e){return e||""},systemPromptPath(e){return e||""},codeReviewPromptPath(e){return e||""},timeout(e){if(!e)return 6e4;E("timeout",/^\d+$/.test(e),"Must be an integer");const t=Number(e);return E("timeout",t>=500,"Must be greater than 500ms"),t},temperature(e){if(!e)return .7;E("temperature",/^(2|\d)(\.\d{1,2})?$/.test(e),"Must be decimal between 0 and 2");const t=Number(e);return E("temperature",t>0,"Must be greater than 0"),E("temperature",t<=2,"Must be less than or equal to 2"),t},maxTokens(e){return e?(E("maxTokens",/^\d+$/.test(e),"Must be an integer"),Number(e)):8192},logLevel(e){return e?(E("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||Eo},exceptionLogFilePath(e){return e||vo},locale(e){return e?(E("locale",e,"Cannot be empty"),E("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;E("generate",/^\d+$/.test(e),"Must be an integer");const t=Number(e);return E("generate",t>0,"Must be greater than 0"),E("generate",t<=5,"Must be less or equal to 5"),t},type(e){return e?(E("type",xa.includes(e),"Invalid commit type"),e):"conventional"},maxLength(e){if(!e)return 50;E("maxLength",/^\d+$/.test(e),"Must be an integer");const t=Number(e);return E("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;E("topP",/^(1|\d)(\.\d{1,2})?$/.test(e),"Must be decimal between 0 and 1");const t=Number(e);return E("topP",t>0,"Must be greater than 0"),E("topP",t<=1,"Must be less than or equal to 1"),t},logging:G("logging",!0),includeBody:G("includeBody"),codeReview:G("codeReview"),disabled:G("disabled"),watchMode:G("watchMode"),forceGit:G("forceGit"),stream:G("stream"),disableLowerCase:G("disableLowerCase"),jjAutoNew:G("jjAutoNew"),autoCopy:G("autoCopy"),modelNameDisplay:e=>e?(E("modelNameDisplay",/^(?:none|short|full)$/.test(e),"Must be none, short, or full"),e):"short",diffCompression:e=>e?(E("diffCompression",/^(?:none|compact)$/.test(e),"Must be none or compact"),e):ho.mode,maxHunkLines:e=>e?(E("maxHunkLines",/^\d+$/.test(e),"Must be an integer"),Number(e)):0,maxDiffLines:e=>e?(E("maxDiffLines",/^\d+$/.test(e),"Must be an integer"),Number(e)):0,diffContext:e=>{if(!e)return me;E("diffContext",/^\d+$/.test(e),"Must be an integer");const t=Number(e);return E("diffContext",t>=0&&t<=10,"Must be between 0 and 10"),t},useStats:G("useStats",!0),statsDays:e=>{if(!e)return 30;E("statsDays",/^\d+$/.test(e),"Must be an integer");const t=Number(e);return E("statsDays",t>0,"Must be greater than 0"),t}},Ae={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?(E("OPENAI.url",/^https?:\/\//.test(e),"Must be a valid URL"),e):"https://api.openai.com",path:e=>e||"/v1/chat/completions",proxy:e=>e||"",topP:i.topP,systemPrompt:i.systemPrompt,systemPromptPath:i.systemPromptPath,codeReviewPromptPath:i.codeReviewPromptPath,timeout:i.timeout,temperature:i.temperature,maxTokens:i.maxTokens,logging:i.logging,locale:i.locale,generate:i.generate,type:i.type,maxLength:i.maxLength,includeBody:i.includeBody,codeReview:i.codeReview,disabled:i.disabled,stream:i.stream,watchMode:i.watchMode,disableLowerCase:i.disableLowerCase,diffCompression:i.diffCompression,maxHunkLines:i.maxHunkLines,maxDiffLines:i.maxDiffLines,diffContext:i.diffContext},OPENROUTER:{key:e=>e||"",envKey:e=>e||"",model:e=>e?(typeof e=="string"?e?.split(","):e).map(n=>n.trim()).filter(n=>!!n&&n.length>0):["openrouter/auto"],url:e=>e?(E("OPENROUTER.url",/^https?:\/\//.test(e),"Must be a valid URL"),e):"https://openrouter.ai",path:e=>e||"/api/v1/chat/completions",responseFormat:Ke("OPENROUTER.responseFormat"),provider:Ke("OPENROUTER.provider"),reasoning:Ke("OPENROUTER.reasoning"),topP:i.topP,systemPrompt:i.systemPrompt,systemPromptPath:i.systemPromptPath,codeReviewPromptPath:i.codeReviewPromptPath,timeout:i.timeout,temperature:i.temperature,maxTokens:i.maxTokens,logging:i.logging,locale:i.locale,generate:i.generate,type:i.type,maxLength:i.maxLength,includeBody:i.includeBody,codeReview:i.codeReview,disabled:i.disabled,stream:i.stream,watchMode:i.watchMode,disableLowerCase:i.disableLowerCase,diffCompression:i.diffCompression,maxHunkLines:i.maxHunkLines,maxDiffLines:i.maxDiffLines,diffContext:i.diffContext},HUGGINGFACE:{cookie:e=>e||"",model:e=>e?(typeof e=="string"?e?.split(","):e).map(n=>n.trim()).filter(n=>!!n&&n.length>0):["CohereForAI/c4ai-command-r-plus"],systemPrompt:i.systemPrompt,systemPromptPath:i.systemPromptPath,codeReviewPromptPath:i.codeReviewPromptPath,timeout:i.timeout,temperature:i.temperature,maxTokens:i.maxTokens,topP:i.topP,logging:i.logging,locale:i.locale,generate:i.generate,type:i.type,maxLength:i.maxLength,includeBody:i.includeBody,codeReview:i.codeReview,disabled:i.disabled,stream:i.stream,watchMode:i.watchMode,disableLowerCase:i.disableLowerCase,diffCompression:i.diffCompression,maxHunkLines:i.maxHunkLines,maxDiffLines:i.maxDiffLines,diffContext:i.diffContext},GEMINI:{key:e=>e||"",envKey:e=>e||"",model:e=>e?(typeof e=="string"?e?.split(","):e).map(n=>n.trim()).filter(n=>!!n&&n.length>0):["gemini-3-flash-preview"],systemPrompt:i.systemPrompt,systemPromptPath:i.systemPromptPath,codeReviewPromptPath:i.codeReviewPromptPath,timeout:i.timeout,temperature:i.temperature,maxTokens:i.maxTokens,logging:i.logging,locale:i.locale,generate:i.generate,type:i.type,maxLength:i.maxLength,includeBody:i.includeBody,topP:i.topP,codeReview:i.codeReview,disabled:i.disabled,stream:i.stream,watchMode:i.watchMode,disableLowerCase:i.disableLowerCase,diffCompression:i.diffCompression,maxHunkLines:i.maxHunkLines,maxDiffLines:i.maxDiffLines,diffContext:i.diffContext},ANTHROPIC:{key:e=>e||"",envKey:e=>e||"",model:e=>e?(typeof e=="string"?e?.split(","):e).map(n=>n.trim()).filter(n=>!!n&&n.length>0):["claude-sonnet-4-20250514"],systemPrompt:i.systemPrompt,systemPromptPath:i.systemPromptPath,codeReviewPromptPath:i.codeReviewPromptPath,timeout:i.timeout,temperature:i.temperature,maxTokens:i.maxTokens,logging:i.logging,locale:i.locale,generate:i.generate,type:i.type,maxLength:i.maxLength,includeBody:i.includeBody,topP:i.topP,codeReview:i.codeReview,disabled:i.disabled,stream:i.stream,watchMode:i.watchMode,disableLowerCase:i.disableLowerCase,diffCompression:i.diffCompression,maxHunkLines:i.maxHunkLines,maxDiffLines:i.maxDiffLines,diffContext:i.diffContext},MISTRAL:{key:e=>e||"",envKey:e=>e||"",model:e=>e?(typeof e=="string"?e?.split(","):e).map(n=>n.trim()).filter(n=>!!n&&n.length>0):["mistral-small-latest"],systemPrompt:i.systemPrompt,systemPromptPath:i.systemPromptPath,codeReviewPromptPath:i.codeReviewPromptPath,timeout:i.timeout,temperature:i.temperature,maxTokens:i.maxTokens,logging:i.logging,locale:i.locale,generate:i.generate,type:i.type,maxLength:i.maxLength,includeBody:i.includeBody,topP:i.topP,codeReview:i.codeReview,disabled:i.disabled,stream:i.stream,watchMode:i.watchMode,disableLowerCase:i.disableLowerCase,diffCompression:i.diffCompression,maxHunkLines:i.maxHunkLines,maxDiffLines:i.maxDiffLines,diffContext:i.diffContext},CODESTRAL:{key:e=>e||"",envKey:e=>e||"",model:e=>e?(typeof e=="string"?e?.split(","):e).map(n=>n.trim()).filter(n=>!!n&&n.length>0):["codestral-latest"],topP:i.topP,systemPrompt:i.systemPrompt,systemPromptPath:i.systemPromptPath,codeReviewPromptPath:i.codeReviewPromptPath,timeout:i.timeout,temperature:i.temperature,maxTokens:i.maxTokens,logging:i.logging,locale:i.locale,generate:i.generate,type:i.type,maxLength:i.maxLength,includeBody:i.includeBody,codeReview:i.codeReview,disabled:i.disabled,stream:i.stream,watchMode:i.watchMode,disableLowerCase:i.disableLowerCase,diffCompression:i.diffCompression,maxHunkLines:i.maxHunkLines,maxDiffLines:i.maxDiffLines,diffContext:i.diffContext},OLLAMA:{model:e=>e?(typeof e=="string"?e?.split(","):e).map(n=>n.trim()).filter(n=>!!n&&n.length>0):[],host:e=>e?(E("OLLAMA.host",/^https?:\/\//.test(e),"Must be a valid URL"),e):Pe,timeout:e=>{if(!e)return 1e5;E("OLLAMA.timeout",/^\d+$/.test(e),"Must be an integer");const t=Number(e);return E("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;E("OLLAMA.numCtx",/^\d+$/.test(e),"Must be an integer");const t=Number(e);return E("OLLAMA.numCtx",t>=2048,"Must be greater than 2048"),t},systemPrompt:i.systemPrompt,systemPromptPath:i.systemPromptPath,codeReviewPromptPath:i.codeReviewPromptPath,temperature:i.temperature,maxTokens:i.maxTokens,logging:i.logging,locale:i.locale,generate:i.generate,type:i.type,maxLength:i.maxLength,includeBody:i.includeBody,topP:i.topP,codeReview:i.codeReview,disabled:i.disabled,stream:i.stream,watchMode:i.watchMode,disableLowerCase:i.disableLowerCase,diffCompression:i.diffCompression,maxHunkLines:i.maxHunkLines,maxDiffLines:i.maxDiffLines,diffContext:i.diffContext},COHERE:{key:e=>e||"",envKey:e=>e||"",url:e=>e?(E("COHERE.url",/^https?:\/\//.test(e),"Must be a valid URL"),e):"https://api.cohere.ai",model:e=>e?(typeof e=="string"?e?.split(","):e).map(n=>n.trim()).filter(n=>!!n&&n.length>0):["command-a-03-2025"],systemPrompt:i.systemPrompt,systemPromptPath:i.systemPromptPath,codeReviewPromptPath:i.codeReviewPromptPath,temperature:i.temperature,maxTokens:i.maxTokens,logging:i.logging,locale:i.locale,timeout:i.timeout,generate:i.generate,type:i.type,maxLength:i.maxLength,includeBody:i.includeBody,topP:i.topP,codeReview:i.codeReview,disabled:i.disabled,stream:i.stream,watchMode:i.watchMode,disableLowerCase:i.disableLowerCase,diffCompression:i.diffCompression,maxHunkLines:i.maxHunkLines,maxDiffLines:i.maxDiffLines,diffContext:i.diffContext},GROQ:{key:e=>e||"",envKey:e=>e||"",model:e=>e?(typeof e=="string"?e?.split(","):e).map(n=>n.trim()).filter(n=>!!n&&n.length>0):["llama-3.3-70b-versatile"],systemPrompt:i.systemPrompt,systemPromptPath:i.systemPromptPath,codeReviewPromptPath:i.codeReviewPromptPath,timeout:i.timeout,temperature:i.temperature,maxTokens:i.maxTokens,logging:i.logging,locale:i.locale,generate:i.generate,type:i.type,maxLength:i.maxLength,includeBody:i.includeBody,topP:i.topP,codeReview:i.codeReview,disabled:i.disabled,stream:i.stream,watchMode:i.watchMode,disableLowerCase:i.disableLowerCase,diffCompression:i.diffCompression,maxHunkLines:i.maxHunkLines,maxDiffLines:i.maxDiffLines,diffContext:i.diffContext},PERPLEXITY:{key:e=>e||"",envKey:e=>e||"",model:e=>e?(typeof e=="string"?e?.split(","):e).map(n=>n.trim()).filter(n=>!!n&&n.length>0):["sonar"],topP:i.topP,systemPrompt:i.systemPrompt,systemPromptPath:i.systemPromptPath,codeReviewPromptPath:i.codeReviewPromptPath,timeout:i.timeout,temperature:i.temperature,maxTokens:i.maxTokens,logging:i.logging,locale:i.locale,generate:i.generate,type:i.type,maxLength:i.maxLength,includeBody:i.includeBody,codeReview:i.codeReview,disabled:i.disabled,stream:i.stream,watchMode:i.watchMode,disableLowerCase:i.disableLowerCase,diffCompression:i.diffCompression,maxHunkLines:i.maxHunkLines,maxDiffLines:i.maxDiffLines,diffContext:i.diffContext},DEEPSEEK:{key:e=>e||"",envKey:e=>e||"",model:e=>e?(typeof e=="string"?e?.split(","):e).map(n=>n.trim()).filter(n=>!!n&&n.length>0):["deepseek-chat"],topP:i.topP,systemPrompt:i.systemPrompt,systemPromptPath:i.systemPromptPath,codeReviewPromptPath:i.codeReviewPromptPath,timeout:i.timeout,temperature:i.temperature,maxTokens:i.maxTokens,logging:i.logging,locale:i.locale,generate:i.generate,type:i.type,maxLength:i.maxLength,includeBody:i.includeBody,codeReview:i.codeReview,disabled:i.disabled,stream:i.stream,watchMode:i.watchMode,disableLowerCase:i.disableLowerCase,diffCompression:i.diffCompression,maxHunkLines:i.maxHunkLines,maxDiffLines:i.maxDiffLines,diffContext:i.diffContext},GITHUB_MODELS:{key:e=>e||"",envKey:e=>e||"",model:e=>e?(typeof e=="string"?e?.split(","):e).map(n=>n.trim()).filter(n=>!!n&&n.length>0):["openai/gpt-4o-mini"],systemPrompt:i.systemPrompt,systemPromptPath:i.systemPromptPath,codeReviewPromptPath:i.codeReviewPromptPath,timeout:i.timeout,temperature:i.temperature,maxTokens:i.maxTokens,logging:i.logging,locale:i.locale,generate:i.generate,type:i.type,maxLength:i.maxLength,includeBody:i.includeBody,topP:i.topP,codeReview:i.codeReview,disabled:i.disabled,stream:i.stream,watchMode:i.watchMode,disableLowerCase:i.disableLowerCase,diffCompression:i.diffCompression,maxHunkLines:i.maxHunkLines,maxDiffLines:i.maxDiffLines,diffContext:i.diffContext},COPILOT_SDK:{key:e=>e||"",envKey:e=>e||"",model:e=>e?(typeof e=="string"?e?.split(","):e).map(n=>n.trim()).filter(n=>!!n&&n.length>0):["gpt-4.1"],systemPrompt:i.systemPrompt,systemPromptPath:i.systemPromptPath,codeReviewPromptPath:i.codeReviewPromptPath,timeout:i.timeout,temperature:i.temperature,maxTokens:i.maxTokens,logging:i.logging,locale:i.locale,generate:i.generate,type:i.type,maxLength:i.maxLength,includeBody:i.includeBody,topP:i.topP,codeReview:i.codeReview,disabled:i.disabled,stream:i.stream,watchMode:i.watchMode,disableLowerCase:i.disableLowerCase,diffCompression:i.diffCompression,maxHunkLines:i.maxHunkLines,maxDiffLines:i.maxDiffLines,diffContext:i.diffContext},BEDROCK:{key:e=>e||"",envKey:e=>e&&e.length>0?e:"BEDROCK_API_KEY",model:e=>e?(typeof e=="string"?e?.split(","):e).map(n=>{const o=n.trim();return o&&!o.includes(".")&&!o.includes(":")&&console.warn(`[Bedrock] Model ID "${o}" may be invalid.
17
17
  Expected formats:
18
18
  - Foundation model: "provider.model-name-version" (e.g., "anthropic.claude-haiku-4-5-20251001-v1:0")
19
19
  - Inference profile: "prefix.provider.model-name-version" (e.g., "us.anthropic.claude-haiku-4-5-20251001-v1:0")
20
20
  - ARN: Full Amazon Resource Name
21
- See https://docs.aws.amazon.com/bedrock/latest/userguide/inference-profiles.html`),o}).filter(n=>!!n&&n.length>0):["anthropic.claude-haiku-4-5-20251001-v1:0"],runtimeMode:e=>{e&&console.warn("[Bedrock] DEPRECATION: runtimeMode is no longer used. Authentication method is now auto-detected from configured credentials.")},region:e=>e||process.env.AWS_REGION||process.env.AWS_DEFAULT_REGION||"",profile:e=>e||process.env.AWS_PROFILE||"",accessKeyId:e=>e||process.env.AWS_ACCESS_KEY_ID||"",secretAccessKey:e=>e||process.env.AWS_SECRET_ACCESS_KEY||"",sessionToken:e=>e||process.env.AWS_SESSION_TOKEN||"",applicationEndpointId:e=>e||process.env.BEDROCK_APPLICATION_ENDPOINT_ID||"",applicationInferenceProfileArn:e=>e||process.env.BEDROCK_APPLICATION_INFERENCE_PROFILE_ARN||process.env.BEDROCK_INFERENCE_PROFILE_ARN||"",applicationBaseUrl:e=>e||process.env.BEDROCK_APPLICATION_BASE_URL||"",systemPrompt:i.systemPrompt,systemPromptPath:i.systemPromptPath,codeReviewPromptPath:i.codeReviewPromptPath,timeout:i.timeout,temperature:e=>{if(!e)return;E("temperature",/^(2|\d)(\.\d{1,2})?$/.test(e),"Must be decimal between 0 and 2");const t=Number(e);return E("temperature",t>0,"Must be greater than 0"),E("temperature",t<=2,"Must be less than or equal to 2"),t},maxTokens:e=>{if(e)return E("maxTokens",/^\d+$/.test(e),"Must be an integer"),Number(e)},logging:i.logging,locale:i.locale,generate:i.generate,type:i.type,maxLength:i.maxLength,includeBody:i.includeBody,topP:e=>{if(!e)return;E("topP",/^(1|\d)(\.\d{1,2})?$/.test(e),"Must be decimal between 0 and 1");const t=Number(e);return E("topP",t>0,"Must be greater than 0"),E("topP",t<=1,"Must be less than or equal to 1"),t},codeReview:i.codeReview,disabled:i.disabled,stream:i.stream,watchMode:i.watchMode,disableLowerCase:i.disableLowerCase,inferenceParameters:Ke("BEDROCK.inferenceParameters"),diffCompression:i.diffCompression,maxHunkLines:i.maxHunkLines,maxDiffLines:i.maxDiffLines,diffContext:i.diffContext}},xa=e=>typeof e=="object"&&e!==null,Po=(e,t)=>{Object.keys(e).forEach(n=>{const o=e[n];xa(o)&&t in o&&(o[t]=!0)})},$a=e=>{Po(e,"includeBody")},Sa=e=>{Po(e,"disableLowerCase")};let xe,$e=null,Gt=null;const Ra=(e=[])=>{const t={};for(const n of e)if(n.startsWith("--")){const[o,s]=n.slice(2).split("="),[r,a]=o.split(".");r&&a&&r in Ae?(t[r]||(t[r]={}),t[r][a]=s):t[o]=s}return t},Ia=()=>{const e=ke.homedir(),t=process.env.AICOMMIT_CONFIG_PATH,n=bo,o=v.join(e,".aicommit2");return[t,n,o].filter(s=>!!s)},fe=async()=>{const e=Ia();for(const t of e)if(await He(t))return t;return bo},ka=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]??""}),Ao=e=>{if(Array.isArray(e)||e===null||typeof e!="object")return e;const t={};for(const[n,o]of Object.entries(e)){const s=Ao(o);if(!n.includes(".")){t[n]=s;continue}const r=n.split(".");let a=t;for(const c of r.slice(0,-1)){const u=a[c];(!u||typeof u!="object"||Array.isArray(u))&&(a[c]={}),a=a[c]}a[r[r.length-1]]=s}return t},Se=async()=>{const e=await fe();if($e&&Gt===e)return $e;xe=e;try{const t=await I.readFile(e,"utf8"),n=ka(t);return $e=Ao(ue.parse(n)),Gt=e,$e}catch(t){return t.code==="ENOENT"?(xe=void 0,{}):(console.error(`Error reading config file ${e}:`,t),xe=void 0,{})}},xo=()=>{$e=null,Gt=null},J=async(e,t=[])=>{const n=await Se(),o=Ra(t),s={...e,...o},r={},a=Aa(n),c={};for(const l of a){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 g=f.map(y=>y?process.env[y]:void 0).find(y=>typeof y=="string"&&y.length>0);g&&(c[l]={key:g})}const u=(l,d)=>{const f=s[`${l}.${d}`]??s[l]?.[d],g=c[l]?.[d],y=n[l]?.[d],m=s[d]??n[d];return f!==void 0?f:g!==void 0?g:y!==void 0?y:m};for(const[l,d]of Object.entries(i)){const f=s[l]??n[l];r[l]=d(f)}for(const l of a){r[l]={};const d=Ae[l]||qe(l);for(const[f,g]of Object.entries(d)){const y=u(l,f);r[l][f]=g(y)}}return r},We=async e=>{const t=await Se();for(const[s,r]of e){const[a,c]=s.split(".");if(!c){const d=i[s];if(!d)throw new p(`Invalid config property: ${s}`);t[s]=d(r);continue}if(t[a]||(t[a]={}),me.includes(a)){const d=Ae[a][c];if(!d)throw new p(`Invalid config property: ${s}`);t[a][c]=d(r);continue}if(!/^[A-Z][A-Z0-9_]*$/.test(a))throw new p(`Invalid service name: ${a}. Service names must be uppercase letters, numbers, and underscores.`);const l=qe(a);if(!l[c])throw new p(`Invalid config property for custom service: ${s}`);try{t[a][c]=l[c](r)}catch(d){throw d instanceof p?d:new p(`Invalid value for ${s}: ${d.message}`)}}const n=await fe(),o=v.dirname(n);await I.mkdir(o,{recursive:!0}),await I.writeFile(n,ue.stringify(t),"utf8"),xo()},La=async e=>{const t=await Se();for(const[s,r]of e){const[a,c]=s.split("."),u=t[a];if(c==="model"){u||(t[a]={});const d=t[a][c]||[],f=typeof r=="string"?r.split(",").map(g=>g.trim()).filter(g=>!!g):r;t[a][c]=jt([...d,...f]);continue}if(u&&u.compatible===!0){u||(t[a]={});const d=qe(a);if(!d[c])throw new p(`Invalid config property: ${s}`);try{t[a][c]=d[c](r)}catch(f){throw f instanceof p?f:new p(`Invalid value for ${s}: ${f.message}`)}continue}if(a in Ae){u||(t[a]={});const d=Ae[a][c];if(!d)throw new p(`Invalid config property: ${s}`);t[a][c]=d(r)}else{const d=qe(a);if(!d[c])throw new p(`Invalid config property: ${s}`);t[a]||(t[a]={}),t[a][c]=d[c](r)}}const n=await fe(),o=v.dirname(n);await I.mkdir(o,{recursive:!0}),await I.writeFile(n,ue.stringify(t),"utf8"),xo()},Ma=async()=>{const e=await Se();console.log(ue.stringify(e))},Ta=async()=>{console.log(await fe())},qe=e=>({compatible:G("compatible"),stream:G("stream"),url:t=>t?(E(`${e}.url`,/^https?:\/\//.test(t),"Must be a valid URL"),t):"",path:t=>t||"",key:t=>t||"",envKey:t=>t||"",model:t=>t?(typeof t=="string"?t?.split(","):t).map(o=>o.trim()).filter(o=>!!o&&o.length>0):[],systemPrompt:i.systemPrompt,systemPromptPath:i.systemPromptPath,codeReviewPromptPath:i.codeReviewPromptPath,timeout:i.timeout,temperature:i.temperature,maxTokens:i.maxTokens,logging:i.logging,locale:i.locale,generate:i.generate,type:i.type,maxLength:i.maxLength,includeBody:i.includeBody,topP:i.topP,codeReview:i.codeReview,disabled:i.disabled,watchMode:i.watchMode,disableLowerCase:i.disableLowerCase,autoCopy:i.autoCopy,diffCompression:i.diffCompression,maxHunkLines:i.maxHunkLines,maxDiffLines:i.maxDiffLines,diffContext:i.diffContext}),N=e=>typeof e=="string"&&e.trim().length>0,Oa=()=>{try{const e=typeof ht<"u"?ht.resolve:void 0;return e?(e("@github/copilot-sdk"),!0):typeof import.meta.resolve=="function"?(import.meta.resolve("@github/copilot-sdk"),!0):!1}catch{return!1}};let Bt;const Da=e=>Y(e)?(Bt===void 0&&(Bt=Oa()),Bt):!1,Y=e=>(Array.isArray(e.model)?e.model:N(e.model)?[e.model.trim()]:[]).length>0,ze=e=>{const t=N(e.key),n=N(e.region)||N(process.env.AWS_REGION)||N(process.env.AWS_DEFAULT_REGION),o=N(e.profile)||N(process.env.AWS_PROFILE),s=N(e.accessKeyId)&&N(e.secretAccessKey)||N(process.env.AWS_ACCESS_KEY_ID)&&N(process.env.AWS_SECRET_ACCESS_KEY),r=N(e.applicationBaseUrl)||N(process.env.BEDROCK_APPLICATION_BASE_URL),a=N(e.applicationEndpointId)||N(process.env.BEDROCK_APPLICATION_ENDPOINT_ID),c=N(process.env.BEDROCK_APPLICATION_API_KEY);return n&&(t||o||s)||(r&&t||a&&c)},pe=(e,t)=>Object.entries(e).map(([n,o])=>[n,o]).filter(([n,o])=>!o.disabled).filter(([n,o])=>me.includes(n)||o.compatible===!0).filter(([n,o])=>{switch(t){case"commit":return n==="OLLAMA"?!!o&&Y(o):n==="COPILOT_SDK"?!!o&&Da(o):n==="HUGGINGFACE"?!!o&&!!o.cookie:n==="BEDROCK"?Y(o)&&ze(o):!!o.key&&o.key.length>0;case"review":const s=e.codeReview||o.codeReview;return n==="OLLAMA"||n==="COPILOT_SDK"?!!o&&Y(o)&&s:n==="HUGGINGFACE"?!!o&&!!o.cookie&&s:n==="BEDROCK"?Y(o)&&ze(o)&&s:!!o.key&&o.key.length>0&&s;case"watch":const r=e.watchMode||o.watchMode;return n==="OLLAMA"||n==="COPILOT_SDK"?!!o&&Y(o)&&r:n==="HUGGINGFACE"?!!o&&!!o.cookie&&r:n==="BEDROCK"?Y(o)&&ze(o)&&r:o.compatible?!!o.url&&!!o.key&&r:!!o.key&&o.key.length>0&&r}}).map(([n])=>n);class Na{static create(t,n){return new t(n)}}const _a="stats.json",Ye=2,ja=30,Ht=()=>v.join(Co,_a),Ve=async()=>{const e=Ht();if(!await He(e))return{version:Ye,metrics:[],selections:[]};try{const t=await I.readFile(e,"utf-8"),n=JSON.parse(t);return!n.version||n.version<Ye?{version:Ye,metrics:n.metrics||[],selections:n.selections||[]}:n}catch{return{version:Ye,metrics:[],selections:[]}}},Fa=(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)}},$o=async(e,t)=>{const n=Ht(),o=v.dirname(n),s=t?Fa(e,t):e;await I.mkdir(o,{recursive:!0}),await I.writeFile(n,JSON.stringify(s,null,2),"utf-8")},Ga=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 Ve();n.metrics.push(t),await $o(n,e.statsDays)},Ba=async e=>{const t={timestamp:Date.now(),provider:e.provider,model:e.model},n=await Ve();n.selections.push(t),await $o(n,e.statsDays)},Ha=(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),a=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(a.reduce((l,d)=>l+d,0)/a.length),minResponseTimeMs:Math.min(...a),maxResponseTimeMs:Math.max(...a)}},Ua=async(e=ja)=>{const t=await Ve(),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 a=[...new Set(o.map(l=>l.provider))].map(l=>Ha(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:a,periodStart:Math.min(...o.map(l=>l.timestamp)),periodEnd:Math.max(...o.map(l=>l.timestamp))}},Ka=async()=>{const e=Ht();await He(e)&&await I.unlink(e)},Wa=async()=>(await Ve()).metrics.length>0,So=(e,t)=>{const n=h.red.bold(`[${e}]`);return Ps({name:`${n} ${t}`,value:t,isError:!0,disabled:!0})},Ro=e=>{let t=!1;return As({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};Ga(s).catch(()=>{})}})};class qa{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 Le(this.createService(t,n)).pipe(fn(a=>a?(o==="commit"?a.generateCommitMessage$():a.generateCodeReview$()).pipe(Ro({provider:t,model:r||"unknown",startTime:s,statsEnabled:n.statsEnabled,statsDays:n.statsDays})):So(t,"Invalid AI type")))},this.registerBuiltinProviders=()=>{this.loaders.set("OPENAI",()=>import("./openai.service-41f8df31.mjs").then(t=>t.OpenAIService)),this.loaders.set("COPILOT_SDK",()=>import("./copilot-sdk.service-3ce57b3e.mjs").then(t=>t.CopilotSdkService)),this.loaders.set("OPENROUTER",()=>import("./openrouter.service-ac2ba1cb.mjs").then(t=>t.OpenRouterService)),this.loaders.set("GEMINI",()=>import("./gemini.service-680451fb.mjs").then(t=>t.GeminiService)),this.loaders.set("ANTHROPIC",()=>import("./anthropic.service-07f000b2.mjs").then(t=>t.AnthropicService)),this.loaders.set("HUGGINGFACE",()=>import("./hugging-face.service-370921e2.mjs").then(t=>t.HuggingFaceService)),this.loaders.set("MISTRAL",()=>import("./mistral.service-2d118a9c.mjs").then(t=>t.MistralService)),this.loaders.set("CODESTRAL",()=>import("./codestral.service-1f018db8.mjs").then(t=>t.CodestralService)),this.loaders.set("OLLAMA",()=>import("./ollama.service-516cd32f.mjs").then(t=>t.OllamaService)),this.loaders.set("COHERE",()=>import("./cohere.service-792231bd.mjs").then(t=>t.CohereService)),this.loaders.set("GROQ",()=>import("./groq.service-b9970eb4.mjs").then(t=>t.GroqService)),this.loaders.set("PERPLEXITY",()=>import("./perplexity.service-29e7b048.mjs").then(t=>t.PerplexityService)),this.loaders.set("BEDROCK",()=>import("./bedrock.service-bb73b18d.mjs").then(t=>t.BedrockService)),this.loaders.set("GITHUB_MODELS",()=>import("./github-models.service-c47a9246.mjs").then(t=>t.GitHubModelsService)),this.loaders.set("DEEPSEEK",()=>import("./deep-seek.service-18bf8bbd.mjs").then(t=>t.DeepSeekService))},this.registerBuiltinProviders()}}const za=new qa;class Ut{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 Je extends Ut{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!
21
+ See https://docs.aws.amazon.com/bedrock/latest/userguide/inference-profiles.html`),o}).filter(n=>!!n&&n.length>0):["anthropic.claude-haiku-4-5-20251001-v1:0"],runtimeMode:e=>{e&&console.warn("[Bedrock] DEPRECATION: runtimeMode is no longer used. Authentication method is now auto-detected from configured credentials.")},region:e=>e||process.env.AWS_REGION||process.env.AWS_DEFAULT_REGION||"",profile:e=>e||process.env.AWS_PROFILE||"",accessKeyId:e=>e||process.env.AWS_ACCESS_KEY_ID||"",secretAccessKey:e=>e||process.env.AWS_SECRET_ACCESS_KEY||"",sessionToken:e=>e||process.env.AWS_SESSION_TOKEN||"",applicationEndpointId:e=>e||process.env.BEDROCK_APPLICATION_ENDPOINT_ID||"",applicationInferenceProfileArn:e=>e||process.env.BEDROCK_APPLICATION_INFERENCE_PROFILE_ARN||process.env.BEDROCK_INFERENCE_PROFILE_ARN||"",applicationBaseUrl:e=>e||process.env.BEDROCK_APPLICATION_BASE_URL||"",systemPrompt:i.systemPrompt,systemPromptPath:i.systemPromptPath,codeReviewPromptPath:i.codeReviewPromptPath,timeout:i.timeout,temperature:e=>{if(!e)return;E("temperature",/^(2|\d)(\.\d{1,2})?$/.test(e),"Must be decimal between 0 and 2");const t=Number(e);return E("temperature",t>0,"Must be greater than 0"),E("temperature",t<=2,"Must be less than or equal to 2"),t},maxTokens:e=>{if(e)return E("maxTokens",/^\d+$/.test(e),"Must be an integer"),Number(e)},logging:i.logging,locale:i.locale,generate:i.generate,type:i.type,maxLength:i.maxLength,includeBody:i.includeBody,topP:e=>{if(!e)return;E("topP",/^(1|\d)(\.\d{1,2})?$/.test(e),"Must be decimal between 0 and 1");const t=Number(e);return E("topP",t>0,"Must be greater than 0"),E("topP",t<=1,"Must be less than or equal to 1"),t},codeReview:i.codeReview,disabled:i.disabled,stream:i.stream,watchMode:i.watchMode,disableLowerCase:i.disableLowerCase,inferenceParameters:Ke("BEDROCK.inferenceParameters"),diffCompression:i.diffCompression,maxHunkLines:i.maxHunkLines,maxDiffLines:i.maxDiffLines,diffContext:i.diffContext}},Ra=e=>typeof e=="object"&&e!==null,Po=(e,t)=>{Object.keys(e).forEach(n=>{const o=e[n];Ra(o)&&t in o&&(o[t]=!0)})},Ia=e=>{Po(e,"includeBody")},ka=e=>{Po(e,"disableLowerCase")};let xe,Se=null,Bt=null;const La=(e=[])=>{const t={};for(const n of e)if(n.startsWith("--")){const[o,s]=n.slice(2).split("="),[r,a]=o.split(".");r&&a&&r in Ae?(t[r]||(t[r]={}),t[r][a]=s):t[o]=s}return t},Oa=()=>{const e=ke.homedir(),t=process.env.AICOMMIT_CONFIG_PATH,n=bo,o=v.join(e,".aicommit2");return[t,n,o].filter(s=>!!s)},pe=async()=>{const e=Oa();for(const t of e)if(await He(t))return t;return bo},Ma=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]??""}),Ao=e=>{if(Array.isArray(e)||e===null||typeof e!="object")return e;const t={};for(const[n,o]of Object.entries(e)){const s=Ao(o);if(!n.includes(".")){t[n]=s;continue}const r=n.split(".");let a=t;for(const c of r.slice(0,-1)){const l=a[c];(!l||typeof l!="object"||Array.isArray(l))&&(a[c]={}),a=a[c]}a[r[r.length-1]]=s}return t},$e=async()=>{const e=await pe();if(Se&&Bt===e)return Se;xe=e;try{const t=await I.readFile(e,"utf8"),n=Ma(t);return Se=Ao(de.parse(n)),Bt=e,Se}catch(t){return t.code==="ENOENT"?(xe=void 0,{}):(console.error(`Error reading config file ${e}:`,t),xe=void 0,{})}},xo=()=>{Se=null,Bt=null},J=async(e,t=[])=>{const n=await $e(),o=La(t),s={...e,...o},r={},a=$a(n),c={};for(const u of a){const d=n[u]?.envKey;let f;d?(f=[d],u==="BEDROCK"&&d!=="BEDROCK_APPLICATION_API_KEY"&&f.push("BEDROCK_APPLICATION_API_KEY")):u==="BEDROCK"?f=["BEDROCK_API_KEY","BEDROCK_APPLICATION_API_KEY"]:f=[`${u}_API_KEY`];const g=f.map(y=>y?process.env[y]:void 0).find(y=>typeof y=="string"&&y.length>0);g&&(c[u]={key:g})}const l=(u,d)=>{const f=s[`${u}.${d}`]??s[u]?.[d],g=c[u]?.[d],y=n[u]?.[d],m=s[d]??n[d];return f!==void 0?f:g!==void 0?g:y!==void 0?y:m};for(const[u,d]of Object.entries(i)){const f=s[u]??n[u];r[u]=d(f)}for(const u of a){r[u]={};const d=Ae[u]||qe(u);for(const[f,g]of Object.entries(d)){const y=l(u,f);r[u][f]=g(y)}}return r},We=async e=>{const t=await $e();for(const[s,r]of e){const[a,c]=s.split(".");if(!c){const d=i[s];if(!d)throw new p(`Invalid config property: ${s}`);t[s]=d(r);continue}if(t[a]||(t[a]={}),fe.includes(a)){const d=Ae[a][c];if(!d)throw new p(`Invalid config property: ${s}`);t[a][c]=d(r);continue}if(!/^[A-Z][A-Z0-9_]*$/.test(a))throw new p(`Invalid service name: ${a}. Service names must be uppercase letters, numbers, and underscores.`);const u=qe(a);if(!u[c])throw new p(`Invalid config property for custom service: ${s}`);try{t[a][c]=u[c](r)}catch(d){throw d instanceof p?d:new p(`Invalid value for ${s}: ${d.message}`)}}const n=await pe(),o=v.dirname(n);await I.mkdir(o,{recursive:!0}),await I.writeFile(n,de.stringify(t),"utf8"),xo()},Ta=async e=>{const t=await $e();for(const[s,r]of e){const[a,c]=s.split("."),l=t[a];if(c==="model"){l||(t[a]={});const d=t[a][c]||[],f=typeof r=="string"?r.split(",").map(g=>g.trim()).filter(g=>!!g):r;t[a][c]=Ft([...d,...f]);continue}if(l&&l.compatible===!0){l||(t[a]={});const d=qe(a);if(!d[c])throw new p(`Invalid config property: ${s}`);try{t[a][c]=d[c](r)}catch(f){throw f instanceof p?f:new p(`Invalid value for ${s}: ${f.message}`)}continue}if(a in Ae){l||(t[a]={});const d=Ae[a][c];if(!d)throw new p(`Invalid config property: ${s}`);t[a][c]=d(r)}else{const d=qe(a);if(!d[c])throw new p(`Invalid config property: ${s}`);t[a]||(t[a]={}),t[a][c]=d[c](r)}}const n=await pe(),o=v.dirname(n);await I.mkdir(o,{recursive:!0}),await I.writeFile(n,de.stringify(t),"utf8"),xo()},Da=async()=>{const e=await $e();console.log(de.stringify(e))},Na=async()=>{console.log(await pe())},qe=e=>({compatible:G("compatible"),stream:G("stream"),url:t=>t?(E(`${e}.url`,/^https?:\/\//.test(t),"Must be a valid URL"),t):"",path:t=>t||"",key:t=>t||"",envKey:t=>t||"",model:t=>t?(typeof t=="string"?t?.split(","):t).map(o=>o.trim()).filter(o=>!!o&&o.length>0):[],systemPrompt:i.systemPrompt,systemPromptPath:i.systemPromptPath,codeReviewPromptPath:i.codeReviewPromptPath,timeout:i.timeout,temperature:i.temperature,maxTokens:i.maxTokens,logging:i.logging,locale:i.locale,generate:i.generate,type:i.type,maxLength:i.maxLength,includeBody:i.includeBody,topP:i.topP,codeReview:i.codeReview,disabled:i.disabled,watchMode:i.watchMode,disableLowerCase:i.disableLowerCase,autoCopy:i.autoCopy,diffCompression:i.diffCompression,maxHunkLines:i.maxHunkLines,maxDiffLines:i.maxDiffLines,diffContext:i.diffContext}),N=e=>typeof e=="string"&&e.trim().length>0,_a=()=>{try{const e=typeof gt<"u"?gt.resolve:void 0;return e?(e("@github/copilot-sdk"),!0):typeof import.meta.resolve=="function"?(import.meta.resolve("@github/copilot-sdk"),!0):!1}catch{return!1}};let Ht;const ja=e=>Y(e)?(Ht===void 0&&(Ht=_a()),Ht):!1,Y=e=>(Array.isArray(e.model)?e.model:N(e.model)?[e.model.trim()]:[]).length>0,ze=e=>{const t=N(e.key),n=N(e.region)||N(process.env.AWS_REGION)||N(process.env.AWS_DEFAULT_REGION),o=N(e.profile)||N(process.env.AWS_PROFILE),s=N(e.accessKeyId)&&N(e.secretAccessKey)||N(process.env.AWS_ACCESS_KEY_ID)&&N(process.env.AWS_SECRET_ACCESS_KEY),r=N(e.applicationBaseUrl)||N(process.env.BEDROCK_APPLICATION_BASE_URL),a=N(e.applicationEndpointId)||N(process.env.BEDROCK_APPLICATION_ENDPOINT_ID),c=N(process.env.BEDROCK_APPLICATION_API_KEY);return n&&(t||o||s)||(r&&t||a&&c)},he=(e,t)=>Object.entries(e).map(([n,o])=>[n,o]).filter(([n,o])=>!o.disabled).filter(([n,o])=>fe.includes(n)||o.compatible===!0).filter(([n,o])=>{switch(t){case"commit":return n==="OLLAMA"?!!o&&Y(o):n==="COPILOT_SDK"?!!o&&ja(o):n==="HUGGINGFACE"?!!o&&!!o.cookie:n==="BEDROCK"?Y(o)&&ze(o):!!o.key&&o.key.length>0;case"review":const s=e.codeReview||o.codeReview;return n==="OLLAMA"||n==="COPILOT_SDK"?!!o&&Y(o)&&s:n==="HUGGINGFACE"?!!o&&!!o.cookie&&s:n==="BEDROCK"?Y(o)&&ze(o)&&s:!!o.key&&o.key.length>0&&s;case"watch":const r=e.watchMode||o.watchMode;return n==="OLLAMA"||n==="COPILOT_SDK"?!!o&&Y(o)&&r:n==="HUGGINGFACE"?!!o&&!!o.cookie&&r:n==="BEDROCK"?Y(o)&&ze(o)&&r:o.compatible?!!o.url&&!!o.key&&r:!!o.key&&o.key.length>0&&r}}).map(([n])=>n);class Fa{static create(t,n){return new t(n)}}const Ga="stats.json",Ye=2,Ba=30,Ut=()=>v.join(Co,Ga),Ve=async()=>{const e=Ut();if(!await He(e))return{version:Ye,metrics:[],selections:[]};try{const t=await I.readFile(e,"utf-8"),n=JSON.parse(t);return!n.version||n.version<Ye?{version:Ye,metrics:n.metrics||[],selections:n.selections||[]}:n}catch{return{version:Ye,metrics:[],selections:[]}}},Ha=(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)}},So=async(e,t)=>{const n=Ut(),o=v.dirname(n),s=t?Ha(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 Ve();n.metrics.push(t),await So(n,e.statsDays)},Ka=async e=>{const t={timestamp:Date.now(),provider:e.provider,model:e.model},n=await Ve();n.selections.push(t),await So(n,e.statsDays)},Wa=(e,t,n)=>{const o=t.filter(u=>u.provider===e),s=n.filter(u=>u.provider===e);if(o.length===0)return{provider:e,totalRequests:0,successCount:0,failureCount:0,selectedCount:s.length,selectionRate:0,avgResponseTimeMs:0,minResponseTimeMs:0,maxResponseTimeMs:0};const r=o.filter(u=>u.success),a=o.map(u=>u.responseTimeMs),c=s.length,l=r.length>0?Math.min(100,Math.round(c/r.length*1e3)/10):0;return{provider:e,totalRequests:o.length,successCount:r.length,failureCount:o.length-r.length,selectedCount:c,selectionRate:l,avgResponseTimeMs:Math.round(a.reduce((u,d)=>u+d,0)/a.length),minResponseTimeMs:Math.min(...a),maxResponseTimeMs:Math.max(...a)}},qa=async(e=Ba)=>{const t=await Ve(),n=Date.now()-e*24*60*60*1e3,o=t.metrics.filter(u=>u.timestamp>=n),s=t.selections.filter(u=>u.timestamp>=n);if(o.length===0)return{totalRequests:0,successRate:0,avgResponseTimeMs:0,providerStats:[],periodStart:n,periodEnd:Date.now()};const a=[...new Set(o.map(u=>u.provider))].map(u=>Wa(u,o,s)).sort((u,d)=>d.totalRequests-u.totalRequests),c=o.filter(u=>u.success).length,l=o.reduce((u,d)=>u+d.responseTimeMs,0);return{totalRequests:o.length,successRate:Math.round(c/o.length*1e3)/10,avgResponseTimeMs:Math.round(l/o.length),providerStats:a,periodStart:Math.min(...o.map(u=>u.timestamp)),periodEnd:Math.max(...o.map(u=>u.timestamp))}},za=async()=>{const e=Ut();await He(e)&&await I.unlink(e)},Ya=async()=>(await Ve()).metrics.length>0,$o=(e,t)=>{const n=h.red.bold(`[${e}]`);return Ss({name:`${n} ${t}`,value:t,isError:!0,disabled:!0})},Ro=e=>{let t=!1;return $s({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 Va{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 Le(this.createService(t,n)).pipe(fn(a=>a?(o==="commit"?a.generateCommitMessage$():a.generateCodeReview$()).pipe(Ro({provider:t,model:r||"unknown",startTime:s,statsEnabled:n.statsEnabled,statsDays:n.statsDays})):$o(t,"Invalid AI type")))},this.registerBuiltinProviders=()=>{this.loaders.set("OPENAI",()=>import("./openai.service-663ad5da.mjs").then(t=>t.OpenAIService)),this.loaders.set("COPILOT_SDK",()=>import("./copilot-sdk.service-0775d505.mjs").then(t=>t.CopilotSdkService)),this.loaders.set("OPENROUTER",()=>import("./openrouter.service-f6552be3.mjs").then(t=>t.OpenRouterService)),this.loaders.set("GEMINI",()=>import("./gemini.service-25c72218.mjs").then(t=>t.GeminiService)),this.loaders.set("ANTHROPIC",()=>import("./anthropic.service-cdd97556.mjs").then(t=>t.AnthropicService)),this.loaders.set("HUGGINGFACE",()=>import("./hugging-face.service-f7dcc31e.mjs").then(t=>t.HuggingFaceService)),this.loaders.set("MISTRAL",()=>import("./mistral.service-7a073354.mjs").then(t=>t.MistralService)),this.loaders.set("CODESTRAL",()=>import("./codestral.service-cf085c39.mjs").then(t=>t.CodestralService)),this.loaders.set("OLLAMA",()=>import("./ollama.service-aa773594.mjs").then(t=>t.OllamaService)),this.loaders.set("COHERE",()=>import("./cohere.service-2b555628.mjs").then(t=>t.CohereService)),this.loaders.set("GROQ",()=>import("./groq.service-f7770363.mjs").then(t=>t.GroqService)),this.loaders.set("PERPLEXITY",()=>import("./perplexity.service-f582f58e.mjs").then(t=>t.PerplexityService)),this.loaders.set("BEDROCK",()=>import("./bedrock.service-3487fda6.mjs").then(t=>t.BedrockService)),this.loaders.set("GITHUB_MODELS",()=>import("./github-models.service-5d43907f.mjs").then(t=>t.GitHubModelsService)),this.loaders.set("DEEPSEEK",()=>import("./deep-seek.service-f7f29cf5.mjs").then(t=>t.DeepSeekService))},this.registerBuiltinProviders()}}const Ja=new Va;class Kt{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 Je extends Kt{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!
22
22
 
23
23
  Please install Git first: https://git-scm.com/downloads`);if(n.stderr){if(n.stderr.includes("not a git repository"))throw new p(`Not in a Git repository!
24
24
 
25
25
  Initialize with: git init
26
26
  Or navigate to an existing Git repository.`);if(n.stderr.includes("permission denied"))throw new p(`Git permission denied: ${n.stderr.trim()}
27
27
 
28
- Check file permissions and repository access.`)}throw new p(`Failed to verify Git repository: ${n.message||"Unknown error"}`)}}async getStagedDiff(t,n,o){const r=["diff","--cached","--diff-algorithm=minimal",o?.diffContext!==void 0?`-U${o.diffContext}`:`-U${de}`],a=[...t?t.map(this.excludeFromDiff):[],...n?n.map(this.excludeFromDiff):[]],c=[...this.filesToExclude,...a],[u,l,d]=await Promise.all([b("git",[...r,"--name-only",...c]),b("git",[...r,...c]),b("git",[...r,"--numstat",...a])]),f=u.stdout;if(!f)return null;const g=l.stdout,y=f.split(`
29
- `).filter(Boolean),m=d.stdout,x=[],$=m.split(`
30
- `).filter(Boolean);for(const P of $){const C=P.split(" ");C[0]==="-"&&C[1]==="-"&&C[2]&&x.push(C[2])}let A=g;if(x.length>0){g.trim()||(A=""),A+=`
28
+ Check file permissions and repository access.`)}throw new p(`Failed to verify Git repository: ${n.message||"Unknown error"}`)}}async getStagedDiff(t,n,o){const r=["diff","--cached","--diff-algorithm=minimal",o?.diffContext!==void 0?`-U${o.diffContext}`:`-U${me}`],a=[...t?t.map(this.excludeFromDiff):[],...n?n.map(this.excludeFromDiff):[]],c=[...this.filesToExclude,...a],[l,u,d]=await Promise.all([b("git",[...r,"--name-only",...c]),b("git",[...r,...c]),b("git",[...r,"--numstat",...a])]),f=l.stdout;if(!f)return null;const g=u.stdout,y=f.split(`
29
+ `).filter(Boolean),m=d.stdout,x=[],S=m.split(`
30
+ `).filter(Boolean);for(const P of S){const C=P.split(" ");C[0]==="-"&&C[1]==="-"&&C[2]&&x.push(C[2])}let A=g;if(x.length>0){g.trim()||(A=""),A+=`
31
31
 
32
32
  --- Binary Files Changed ---
33
33
  `;for(const P of x){const{stdout:C}=await b("git",["status","--porcelain",P]),k=C.substring(0,2).trim();A+=`Binary file ${P} ${k==="A"?"added":k==="M"?"modified":k==="D"?"deleted":"changed"}
34
- `}}const S=[...new Set([...y,...x])];return{files:S,diff:A||`Files changed: ${S.join(", ")}`}}async getCommitDiff(t,n,o,s){const r=s?.diffContext!==void 0?`-U${s.diffContext}`:`-U${de}`,a=[...n?n.map(this.excludeFromDiff):[],...o?o.map(this.excludeFromDiff):[]],c=[...this.filesToExclude,...a],[u,l,d]=await Promise.all([b("git",["diff-tree","-r","--no-commit-id","--name-only",t,...c]),b("git",["show",r,t,"--",...c]),b("git",["diff-tree","-r","--numstat",t,...a])]),f=u.stdout;if(!f)return null;const g=l.stdout,y=d.stdout,m=[],x=y.split(`
35
- `).filter(Boolean);for(const S of x){const P=S.split(" ");P[0]==="-"&&P[1]==="-"&&P[2]&&m.push(P[2])}let $=g;if(m.length>0){g.trim()||($=""),$+=`
34
+ `}}const $=[...new Set([...y,...x])];return{files:$,diff:A||`Files changed: ${$.join(", ")}`}}async getCommitDiff(t,n,o,s){const r=s?.diffContext!==void 0?`-U${s.diffContext}`:`-U${me}`,a=[...n?n.map(this.excludeFromDiff):[],...o?o.map(this.excludeFromDiff):[]],c=[...this.filesToExclude,...a],[l,u,d]=await Promise.all([b("git",["diff-tree","-r","--no-commit-id","--name-only",t,...c]),b("git",["show",r,t,"--",...c]),b("git",["diff-tree","-r","--numstat",t,...a])]),f=l.stdout;if(!f)return null;const g=u.stdout,y=d.stdout,m=[],x=y.split(`
35
+ `).filter(Boolean);for(const $ of x){const P=$.split(" ");P[0]==="-"&&P[1]==="-"&&P[2]&&m.push(P[2])}let S=g;if(m.length>0){g.trim()||(S=""),S+=`
36
36
 
37
37
  --- Binary Files Changed ---
38
- `;for(const S of m)$+=`Binary file ${S} changed
38
+ `;for(const $ of m)S+=`Binary file ${$} changed
39
39
  `}const A=[...new Set([...f.split(`
40
- `).filter(Boolean),...m])];return{files:A,diff:$||`Files changed: ${A.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.
40
+ `).filter(Boolean),...m])];return{files:A,diff:S||`Files changed: ${A.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.
41
41
 
42
42
  Stage your changes with: git add <files>
43
43
  Or use the --all flag to stage all changes.`):r.stderr.includes("Please enter the commit message")?new p(`Commit message cannot be empty.
@@ -48,7 +48,7 @@ Configure with:
48
48
  git config --global user.name "Your Name"
49
49
  git config --global user.email "your.email@example.com"`):r.stderr.includes("Permission denied")?new p(`Git permission error: ${r.stderr.trim()}
50
50
 
51
- Check repository permissions and file access.`):new p(`Git commit failed: ${r.stderr.trim()}`):r.exitCode===1?new p("Git commit failed. Check your staged changes and try again."):new p(`Failed to commit with Git: ${r.message||"Unknown error"}`)}}async getCommentChar(){try{const{stdout:t}=await b("git",["config","--get","core.commentChar"]);return t}catch{return"#"}}async getRecentCommits(t=5){try{const{stdout:n}=await b("git",["log","--format=%s",`-${t}`]);return n.trim()}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 Kt extends Ut{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!
51
+ Check repository permissions and file access.`):new p(`Git commit failed: ${r.stderr.trim()}`):r.exitCode===1?new p("Git commit failed. Check your staged changes and try again."):new p(`Failed to commit with Git: ${r.message||"Unknown error"}`)}}async getCommentChar(){try{const{stdout:t}=await b("git",["config","--get","core.commentChar"]);return t}catch{return"#"}}async getRecentCommits(t=5){try{const{stdout:n}=await b("git",["log","--format=%s",`-${t}`]);return n.trim()}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 Wt extends Kt{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!
52
52
 
53
53
  Please install Jujutsu:
54
54
  - macOS: brew install jj
@@ -61,20 +61,20 @@ Initialize a jj repository with: jj init`);return o}catch(t){if(t instanceof p)t
61
61
  Initialize with: jj init
62
62
  Or navigate to an existing jj repository.`):n.stderr.includes("No workspace found")?new p(`No Jujutsu workspace found!
63
63
 
64
- This may be a bare repository. Navigate to a workspace directory.`):new p(`Jujutsu error: ${n.stderr.trim()}`):new p(`Failed to verify Jujutsu repository: ${n.message||"Unknown error"}`)}}async getStagedDiff(t,n,o){try{const{stdout:s}=await b("jj",["status","--no-pager"]);if(process.env.DEBUG&&(console.log("jj status output:",JSON.stringify(s)),console.log("excludeFiles:",t),console.log("exclude:",n)),s.includes("No changes.")||s.includes("The working copy is clean"))return null;const r=this.filesToExclude.map(this.excludeFromDiff),a=[...t?t.map(this.excludeFromDiff):[],...n?n.map(this.excludeFromDiff):[]],c=[...r,...a];let u="all()";c.length>0&&(u=`all() & ${c.join(" & ")}`);const l=["diff","--name-only"],d=["diff","--git"];c.length>0&&(l.push(u),d.push(u)),process.env.DEBUG&&(console.log("jj diff command with fileset:",l),console.log("fileset expression:",u));const{stdout:f}=await b("jj",l);if(process.env.DEBUG&&console.log("jj diff --name-only output:",JSON.stringify(f)),!f.trim())return null;const{stdout:g}=await b("jj",d),{stdout:y}=await b("jj",["status","--no-pager"]),m=f.split(`
65
- `).filter(Boolean),x=[],$=y.split(`
66
- `);for(const P of $)if(P.includes("(binary)")||P.includes("Binary file")){const C=P.match(/([^\s]+)\s*\(binary\)/);C&&C[1]&&x.push(C[1])}let A=g;if(x.length>0){A+=`
64
+ This may be a bare repository. Navigate to a workspace directory.`):new p(`Jujutsu error: ${n.stderr.trim()}`):new p(`Failed to verify Jujutsu repository: ${n.message||"Unknown error"}`)}}async getStagedDiff(t,n,o){try{const{stdout:s}=await b("jj",["status","--no-pager"]);if(process.env.DEBUG&&(console.log("jj status output:",JSON.stringify(s)),console.log("excludeFiles:",t),console.log("exclude:",n)),s.includes("No changes.")||s.includes("The working copy is clean"))return null;const r=this.filesToExclude.map(this.excludeFromDiff),a=[...t?t.map(this.excludeFromDiff):[],...n?n.map(this.excludeFromDiff):[]],c=[...r,...a];let l="all()";c.length>0&&(l=`all() & ${c.join(" & ")}`);const u=["diff","--name-only"],d=["diff","--git"];c.length>0&&(u.push(l),d.push(l)),process.env.DEBUG&&(console.log("jj diff command with fileset:",u),console.log("fileset expression:",l));const{stdout:f}=await b("jj",u);if(process.env.DEBUG&&console.log("jj diff --name-only output:",JSON.stringify(f)),!f.trim())return null;const{stdout:g}=await b("jj",d),{stdout:y}=await b("jj",["status","--no-pager"]),m=f.split(`
65
+ `).filter(Boolean),x=[],S=y.split(`
66
+ `);for(const P of S)if(P.includes("(binary)")||P.includes("Binary file")){const C=P.match(/([^\s]+)\s*\(binary\)/);C&&C[1]&&x.push(C[1])}let A=g;if(x.length>0){A+=`
67
67
 
68
68
  --- Binary Files Changed ---
69
69
  `;for(const P of x)A+=`Binary file ${P} changed
70
- `}const S=[...new Set([...m,...x])];return{files:S,diff:A||`Files changed: ${S.join(", ")}`}}catch(s){const r=s;if(r.stderr){if(r.stderr.includes("No changes to show"))return null;if(r.stderr.includes("Operation not allowed"))throw new p(`Jujutsu diff failed: ${r.stderr.trim()}
70
+ `}const $=[...new Set([...m,...x])];return{files:$,diff:A||`Files changed: ${$.join(", ")}`}}catch(s){const r=s;if(r.stderr){if(r.stderr.includes("No changes to show"))return null;if(r.stderr.includes("Operation not allowed"))throw new p(`Jujutsu diff failed: ${r.stderr.trim()}
71
71
 
72
72
  Try: jj status --no-pager`);if(r.stderr.includes("Invalid revision"))throw new p(`Jujutsu revision error: ${r.stderr.trim()}
73
73
 
74
74
  Check if you're in a valid workspace.`)}if(r.exitCode===1&&!r.stderr)return null;if(process.env.DEBUG)throw new p(`Jujutsu diff failed: ${r.message}
75
75
  stderr: ${r.stderr}
76
- exitCode: ${r.exitCode}`);return null}}async getCommitDiff(t,n,o,s){const r=[...n?n.map(this.excludeFromDiff):[],...o?o.map(this.excludeFromDiff):[]];try{const a=["diff","--name-only","--revision",t],c=["diff","--git","--revision",t];if(r.length>0){const f=`all() & ${r.join(" & ")}`;a.push(f),c.push(f),process.env.DEBUG&&console.log("jj getCommitDiff fileset expression:",f)}const{stdout:u}=await b("jj",a);if(!u.trim())return null;const{stdout:l}=await b("jj",c),d=u.split(`
77
- `).filter(Boolean);return{files:d,diff:l||`Files changed: ${d.join(", ")}`}}catch(a){if(process.env.DEBUG){const c=a;console.log("jj getCommitDiff error:",c.message,c.stderr)}return null}}async commit(t,n=[],o={}){try{await 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.
76
+ exitCode: ${r.exitCode}`);return null}}async getCommitDiff(t,n,o,s){const r=[...n?n.map(this.excludeFromDiff):[],...o?o.map(this.excludeFromDiff):[]];try{const a=["diff","--name-only","--revision",t],c=["diff","--git","--revision",t];if(r.length>0){const f=`all() & ${r.join(" & ")}`;a.push(f),c.push(f),process.env.DEBUG&&console.log("jj getCommitDiff fileset expression:",f)}const{stdout:l}=await b("jj",a);if(!l.trim())return null;const{stdout:u}=await b("jj",c),d=l.split(`
77
+ `).filter(Boolean);return{files:d,diff:u||`Files changed: ${d.join(", ")}`}}catch(a){if(process.env.DEBUG){const c=a;console.log("jj getCommitDiff error:",c.message,c.stderr)}return null}}async commit(t,n=[],o={}){try{await 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.
78
78
 
79
79
  Provide a meaningful commit message.`):r.stderr.includes("No changes to commit")?new p(`No changes to commit.
80
80
 
@@ -83,14 +83,14 @@ Make some changes first, then try again.`):r.stderr.includes("Invalid revision")
83
83
  Ensure you're in a valid workspace with changes.`):r.stderr.includes("Operation not allowed")?new p(`Jujutsu operation not allowed: ${r.stderr.trim()}
84
84
 
85
85
  Check repository state with: jj status`):new p(`Jujutsu describe failed: ${r.stderr.trim()}`):r.exitCode===1?new p("Jujutsu commit failed. Check your changes and repository state."):new p(`Failed to commit with Jujutsu: ${r.message||"Unknown error"}`)}}async getCommentChar(){try{const{stdout:t}=await b("jj",["config","get","ui.comment-char"]);return t.trim()||"#"}catch{return"#"}}async getRecentCommits(t=5){try{const{stdout:n}=await b("jj",["log","--limit",t.toString(),"--no-graph","-T",'description.first_line() ++ "\\n"']);return n.trim()}catch{return""}}async getBranchName(){try{const{stdout:t}=await b("jj",["bookmark","list","--revisions","@"]);if(t.trim()){const s=t.split(`
86
- `)[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 Wt extends Ut{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),a=s.resolve(o);if(r!==a)throw new p(`Not a YADM repository (work tree is not $HOME).
86
+ `)[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 qt extends Kt{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),a=s.resolve(o);if(r!==a)throw new p(`Not a YADM repository (work tree is not $HOME).
87
87
 
88
88
  YADM work tree: ${r}
89
89
  Expected: ${a}
90
90
 
91
- 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").
91
+ This appears to be a regular Git repository.`);const{stdout:c}=await b("yadm",["rev-parse","--git-dir"],{reject:!0}),l=c.trim();if(!l.includes("yadm"))throw new p(`Not a YADM repository (git-dir does not contain "yadm").
92
92
 
93
- Git directory: ${u}
93
+ Git directory: ${l}
94
94
 
95
95
  This appears to be a regular Git repository.`);return n}catch(t){if(t instanceof p)throw t;const n=t;if(n.code==="ENOENT")throw new p(`YADM command not found!
96
96
 
@@ -99,19 +99,19 @@ Please install YADM first: https://yadm.io/`);if(n.stderr){if(n.stderr.includes(
99
99
  Initialize with: yadm init
100
100
  Or clone your dotfiles: yadm clone <url>`);if(n.stderr.includes("permission denied"))throw new p(`YADM permission denied: ${n.stderr.trim()}
101
101
 
102
- Check file permissions and repository access.`)}throw new p(`Failed to verify YADM repository: ${n.message||"Unknown error"}`)}}async getStagedDiff(t,n,o){const r=["diff","--cached","--diff-algorithm=minimal",o?.diffContext!==void 0?`-U${o.diffContext}`:`-U${de}`],a=[...t?t.map(this.excludeFromDiff):[],...n?n.map(this.excludeFromDiff):[]],c=[...this.filesToExclude,...a],[u,l,d]=await Promise.all([b("yadm",[...r,"--name-only",...c]),b("yadm",[...r,...c]),b("yadm",[...r,"--numstat",...a])]),f=u.stdout;if(!f)return null;const g=l.stdout,y=f.split(`
103
- `).filter(Boolean),m=d.stdout,x=[],$=m.split(`
104
- `).filter(Boolean);for(const P of $){const C=P.split(" ");C[0]==="-"&&C[1]==="-"&&C[2]&&x.push(C[2])}let A=g;if(x.length>0){g.trim()||(A=""),A+=`
102
+ Check file permissions and repository access.`)}throw new p(`Failed to verify YADM repository: ${n.message||"Unknown error"}`)}}async getStagedDiff(t,n,o){const r=["diff","--cached","--diff-algorithm=minimal",o?.diffContext!==void 0?`-U${o.diffContext}`:`-U${me}`],a=[...t?t.map(this.excludeFromDiff):[],...n?n.map(this.excludeFromDiff):[]],c=[...this.filesToExclude,...a],[l,u,d]=await Promise.all([b("yadm",[...r,"--name-only",...c]),b("yadm",[...r,...c]),b("yadm",[...r,"--numstat",...a])]),f=l.stdout;if(!f)return null;const g=u.stdout,y=f.split(`
103
+ `).filter(Boolean),m=d.stdout,x=[],S=m.split(`
104
+ `).filter(Boolean);for(const P of S){const C=P.split(" ");C[0]==="-"&&C[1]==="-"&&C[2]&&x.push(C[2])}let A=g;if(x.length>0){g.trim()||(A=""),A+=`
105
105
 
106
106
  --- Binary Files Changed ---
107
107
  `;for(const P of x){const{stdout:C}=await b("yadm",["status","--porcelain",P]),k=C.substring(0,2).trim();A+=`Binary file ${P} ${k==="A"?"added":k==="M"?"modified":k==="D"?"deleted":"changed"}
108
- `}}const S=[...new Set([...y,...x])];return{files:S,diff:A||`Files changed: ${S.join(", ")}`}}async getCommitDiff(t,n,o,s){const r=s?.diffContext!==void 0?`-U${s.diffContext}`:`-U${de}`,a=[...n?n.map(this.excludeFromDiff):[],...o?o.map(this.excludeFromDiff):[]],c=[...this.filesToExclude,...a],[u,l,d]=await Promise.all([b("yadm",["diff-tree","-r","--no-commit-id","--name-only",t,...c]),b("yadm",["show",r,t,"--",...c]),b("yadm",["diff-tree","-r","--numstat",t,...a])]),f=u.stdout;if(!f)return null;const g=l.stdout,y=d.stdout,m=[],x=y.split(`
109
- `).filter(Boolean);for(const S of x){const P=S.split(" ");P[0]==="-"&&P[1]==="-"&&P[2]&&m.push(P[2])}let $=g;if(m.length>0){g.trim()||($=""),$+=`
108
+ `}}const $=[...new Set([...y,...x])];return{files:$,diff:A||`Files changed: ${$.join(", ")}`}}async getCommitDiff(t,n,o,s){const r=s?.diffContext!==void 0?`-U${s.diffContext}`:`-U${me}`,a=[...n?n.map(this.excludeFromDiff):[],...o?o.map(this.excludeFromDiff):[]],c=[...this.filesToExclude,...a],[l,u,d]=await Promise.all([b("yadm",["diff-tree","-r","--no-commit-id","--name-only",t,...c]),b("yadm",["show",r,t,"--",...c]),b("yadm",["diff-tree","-r","--numstat",t,...a])]),f=l.stdout;if(!f)return null;const g=u.stdout,y=d.stdout,m=[],x=y.split(`
109
+ `).filter(Boolean);for(const $ of x){const P=$.split(" ");P[0]==="-"&&P[1]==="-"&&P[2]&&m.push(P[2])}let S=g;if(m.length>0){g.trim()||(S=""),S+=`
110
110
 
111
111
  --- Binary Files Changed ---
112
- `;for(const S of m)$+=`Binary file ${S} changed
112
+ `;for(const $ of m)S+=`Binary file ${$} changed
113
113
  `}const A=[...new Set([...f.split(`
114
- `).filter(Boolean),...m])];return{files:A,diff:$||`Files changed: ${A.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.
114
+ `).filter(Boolean),...m])];return{files:A,diff:S||`Files changed: ${A.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.
115
115
 
116
116
  Stage your changes with: yadm add <file>
117
117
  Or stage tracked file modifications: aicommit2 --all
@@ -124,14 +124,14 @@ Configure with:
124
124
  yadm config --global user.name "Your Name"
125
125
  yadm config --global user.email "your.email@example.com"`):r.stderr.includes("Permission denied")?new p(`YADM permission error: ${r.stderr.trim()}
126
126
 
127
- Check repository permissions and file access.`):new p(`YADM commit failed: ${r.stderr.trim()}`):r.exitCode===1?new p("YADM commit failed. Check your staged changes and try again."):new p(`Failed to commit with YADM: ${r.message||"Unknown error"}`)}}async getCommentChar(){try{const{stdout:t}=await b("yadm",["config","--get","core.commentChar"]);return t}catch{return"#"}}async getRecentCommits(t=5){try{const{stdout:n}=await b("yadm",["log","--format=%s",`-${t}`]);return n.trim()}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 qt=null;const Ya=async()=>{const e=process.argv.includes("--git"),t=process.argv.includes("--yadm"),n=process.argv.includes("--jj");if(e)try{const m=new Je;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.
128
- ${m instanceof Error?m.message:String(m)}`)}if(t)try{const m=new Wt;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.
129
- ${m instanceof Error?m.message:String(m)}`)}if(n)try{const m=new Kt;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
+ 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 getRecentCommits(t=5){try{const{stdout:n}=await b("yadm",["log","--format=%s",`-${t}`]);return n.trim()}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 zt=null;const Xa=async()=>{const e=process.argv.includes("--git"),t=process.argv.includes("--yadm"),n=process.argv.includes("--jj");if(e)try{const m=new Je;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.
128
+ ${m instanceof Error?m.message:String(m)}`)}if(t)try{const m=new qt;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.
129
+ ${m instanceof Error?m.message:String(m)}`)}if(n)try{const m=new Wt;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.
130
130
  ${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 Je;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.
131
- ${m instanceof Error?m.message:String(m)}`)}if(s)try{const m=new Wt;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.
132
- ${m instanceof Error?m.message:String(m)}`)}if(r)try{const m=new Kt;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.
131
+ ${m instanceof Error?m.message:String(m)}`)}if(s)try{const m=new qt;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.
132
+ ${m instanceof Error?m.message:String(m)}`)}if(r)try{const m=new Wt;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.
133
133
  ${m instanceof Error?m.message:String(m)}`)}let a=!1;try{a=(await J({})).forceGit===!0}catch{a=!1}if(a)try{const m=new Je;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.
134
- ${m instanceof Error?m.message:String(m)}`)}const[c,u,l]=await Promise.allSettled([(async()=>{const m=new Kt;return await m.assertRepo(),m})(),(async()=>{const m=new Je;return await m.assertRepo(),m})(),(async()=>{const m=new Wt;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),g=d(u),y=d(l);throw new p(`No supported VCS repository found.
134
+ ${m instanceof Error?m.message:String(m)}`)}const[c,l,u]=await Promise.allSettled([(async()=>{const m=new Wt;return await m.assertRepo(),m})(),(async()=>{const m=new Je;return await m.assertRepo(),m})(),(async()=>{const m=new qt;return await m.assertRepo(),m})()]);if(c.status==="fulfilled")return c.value;if(l.status==="fulfilled")return l.value;if(u.status==="fulfilled")return u.value;const d=m=>m.status==="fulfilled"?"unexpected success":String(m.reason?.message??m.reason).replace("KnownError: ","").trim(),f=d(c),g=d(l),y=d(u);throw new p(`No supported VCS repository found.
135
135
 
136
136
  Jujutsu Error:
137
137
  ${f}
@@ -148,9 +148,9 @@ Solutions:
148
148
  \u2022 Initialize a YADM repository: yadm init (or yadm clone <url>)
149
149
  \u2022 Navigate to an existing Jujutsu, Git, or YADM repository
150
150
  \u2022 Set FORCE_GIT="true" environment variable to force Git detection
151
- \u2022 Set forceGit=true in config file to prefer Git detection`)},ee=async()=>(qt||(qt=await Ya()),qt);let Re=null;const Io=async()=>{if(Re!==null)return Re;try{Re=(await J({})).diffContext}catch{Re=de}return Re},ko=(e,t)=>{const{diff:n,stats:o}=aa(e.diff,t);return n===e.diff?e:{...e,diff:n,compression:o}},zt=async()=>(await ee()).assertRepo(),Yt=async(e,t)=>{const n=await ee(),o=await Io(),s=await n.getStagedDiff(e,t,{diffContext:o});return s||null},Va=async(e,t,n)=>{const o=await ee();if(!o.getCommitDiff)throw new p(`Commit diff not supported for ${o.name}`);const s=await Io(),r=await o.getCommitDiff(e,t,n,{diffContext:s});return r||null},Ja=async()=>(await ee()).getCommentChar(),Xa=e=>{const t=e.files.length.toLocaleString(),n=e.files.length>1?"s":"",o=e.diff.length.toLocaleString();return`Detected ${t} changed file${n} (${o} characters)`},Xe=async()=>(await ee()).name,Qa=async(e,t,n)=>{await(await ee()).commit(e,t||[],n)},Qe=async()=>(await ee()).getBranchName(),Ze=async(e=5)=>(await ee()).getRecentCommits(e);class et{constructor(t,n,o="",s=""){this.config=t,this.stagedDiff=n,this.branchName=o,this.recentCommits=s,this.getDiffForModel=r=>{const a={mode:r.diffCompression||"none",maxHunkLines:r.maxHunkLines||0,maxDiffLines:r.maxDiffLines||0};return ko(this.stagedDiff,a)},this.extractProviderName=r=>{if(!r)return"compatible";try{return new URL(r).hostname}catch{return"compatible"}},this.createCommitMsgRequests$=r=>this.createServiceRequests$(r,"commit"),this.createCodeReviewRequests$=r=>this.createServiceRequests$(r,"review"),this.createServiceRequests$=(r,a)=>Le(r).pipe(pn(c=>this.createProviderRequests$(c,a)),xs(c=>So("UNKNOWN",c.message||"Unknown error"))),this.createProviderRequests$=(r,a)=>{const c=this.config[r],u=Array.isArray(c.model)?c.model:[c.model];return Le(u).pipe(pn(l=>this.createModelRequest$(r,l,a)))},this.createModelRequest$=(r,a,c)=>{const u=this.config[r];if(u.compatible)return this.createCompatibleServiceRequest$(u,a,c);const l=this.getDiffForModel(u);return za.createRequest$(r,{config:{...u,model:a},stagedDiff:l,keyName:a,branchName:this.branchName,recentCommits:this.recentCommits,statsEnabled:this.config.useStats,statsDays:this.config.statsDays,modelNameDisplay:this.config.modelNameDisplay},c)},this.createCompatibleServiceRequest$=(r,a,c)=>{const u=Date.now(),l=this.extractProviderName(r.url),d=this.getDiffForModel(r);return Le(import("./openai-compatible.service-3cda8bb5.mjs")).pipe(fn(({OpenAICompatibleService:f})=>{const g=Na.create(f,{config:{...r,url:r.url||"",path:r.path||"",model:a},stagedDiff:d,keyName:a,branchName:this.branchName,recentCommits:this.recentCommits,modelNameDisplay:this.config.modelNameDisplay});return(c==="commit"?g.generateCommitMessage$():g.generateCodeReview$()).pipe(Ro({provider:l,model:a,startTime:u,statsEnabled:this.config.useStats,statsDays:this.config.statsDays}))}))}}}const Za=1e5;class K{constructor(){this.title="aicommit2",this.formatCompressionStats=t=>{if(!t||t.originalChars===t.compressedChars)return null;const n=Math.round((1-t.compressedChars/t.originalChars)*100);return`[compact: ${t.originalChars.toLocaleString()} \u2192 ${t.compressedChars.toLocaleString()} chars, ${n}% saved]`},this.formatBytes=t=>t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:`${(t/(1024*1024)).toFixed(1)} MB`}printTitle(){try{const t=wn.textSync(this.title,{font:"Small Slant"}),n=Rs(["#8B5CF6","#A020F0","#D946EF"]);console.log(h.bold(n.multiline(t)))}catch{console.log(h.bold(wn.textSync(this.title,{font:"Small Slant"})))}}showLoader(t){if(this.loader){this.loader.text=t;return}this.loader=Cn(t).start()}stopLoader(){this.loader?.stop(),this.loader=void 0}displaySpinner(t){return Cn(t).start()}stopSpinner(t){t.stop(),t.clear()}printStagedFiles(t,n){const o=Buffer.byteLength(t.diff,"utf8"),s=this.formatBytes(o),r=Xa(t),a=this.formatCompressionStats(n);console.log(h.bold.green("\u2714 ")+h.bold(r)+h.dim(` (${s})`)+(a?h.cyan(` ${a}`):"")+h.bold(":")),console.log(`${t.files.map(u=>` ${u}`).join(`
151
+ \u2022 Set forceGit=true in config file to prefer Git detection`)},te=async()=>(zt||(zt=await Xa()),zt);let Re=null;const Io=async()=>{if(Re!==null)return Re;try{Re=(await J({})).diffContext}catch{Re=me}return Re},ko=(e,t)=>{const{diff:n,stats:o}=ua(e.diff,t);return n===e.diff?e:{...e,diff:n,compression:o}},Yt=async()=>(await te()).assertRepo(),Vt=async(e,t)=>{const n=await te(),o=await Io(),s=await n.getStagedDiff(e,t,{diffContext:o});return s||null},Qa=async(e,t,n)=>{const o=await te();if(!o.getCommitDiff)throw new p(`Commit diff not supported for ${o.name}`);const s=await Io(),r=await o.getCommitDiff(e,t,n,{diffContext:s});return r||null},Za=async()=>(await te()).getCommentChar(),ec=e=>{const t=e.files.length.toLocaleString(),n=e.files.length>1?"s":"",o=e.diff.length.toLocaleString();return`Detected ${t} changed file${n} (${o} characters)`},Xe=async()=>(await te()).name,tc=async(e,t,n)=>{await(await te()).commit(e,t||[],n)},Qe=async()=>(await te()).getBranchName(),Ze=async(e=5)=>(await te()).getRecentCommits(e);class et{constructor(t,n,o="",s=""){this.config=t,this.stagedDiff=n,this.branchName=o,this.recentCommits=s,this.getDiffForModel=r=>{const a={mode:r.diffCompression||"none",maxHunkLines:r.maxHunkLines||0,maxDiffLines:r.maxDiffLines||0};return ko(this.stagedDiff,a)},this.extractProviderName=r=>{if(!r)return"compatible";try{return new URL(r).hostname}catch{return"compatible"}},this.createCommitMsgRequests$=r=>this.createServiceRequests$(r,"commit"),this.createCodeReviewRequests$=r=>this.createServiceRequests$(r,"review"),this.createServiceRequests$=(r,a)=>Le(r).pipe(pn(c=>this.createProviderRequests$(c,a)),Rs(c=>$o("UNKNOWN",c.message||"Unknown error"))),this.createProviderRequests$=(r,a)=>{const c=this.config[r],l=Array.isArray(c.model)?c.model:[c.model];return Le(l).pipe(pn(u=>this.createModelRequest$(r,u,a)))},this.createModelRequest$=(r,a,c)=>{const l=this.config[r];if(l.compatible)return this.createCompatibleServiceRequest$(l,a,c);const u=this.getDiffForModel(l);return Ja.createRequest$(r,{config:{...l,model:a},stagedDiff:u,keyName:a,branchName:this.branchName,recentCommits:this.recentCommits,statsEnabled:this.config.useStats,statsDays:this.config.statsDays,modelNameDisplay:this.config.modelNameDisplay},c)},this.createCompatibleServiceRequest$=(r,a,c)=>{const l=Date.now(),u=this.extractProviderName(r.url),d=this.getDiffForModel(r);return Le(import("./openai-compatible.service-3da32dc7.mjs")).pipe(fn(({OpenAICompatibleService:f})=>{const g=Fa.create(f,{config:{...r,url:r.url||"",path:r.path||"",model:a},stagedDiff:d,keyName:a,branchName:this.branchName,recentCommits:this.recentCommits,modelNameDisplay:this.config.modelNameDisplay});return(c==="commit"?g.generateCommitMessage$():g.generateCodeReview$()).pipe(Ro({provider:u,model:a,startTime:l,statsEnabled:this.config.useStats,statsDays:this.config.statsDays}))}))}}}const nc=1e5;class K{constructor(){this.title="aicommit2",this.formatCompressionStats=t=>{if(!t||t.originalChars===t.compressedChars)return null;const n=Math.round((1-t.compressedChars/t.originalChars)*100);return`[compact: ${t.originalChars.toLocaleString()} \u2192 ${t.compressedChars.toLocaleString()} chars, ${n}% saved]`},this.formatBytes=t=>t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:`${(t/(1024*1024)).toFixed(1)} MB`}printTitle(){try{const t=wn.textSync(this.title,{font:"Small Slant"}),n=Ls(["#8B5CF6","#A020F0","#D946EF"]);console.log(h.bold(n.multiline(t)))}catch{console.log(h.bold(wn.textSync(this.title,{font:"Small Slant"})))}}showLoader(t){if(this.loader){this.loader.text=t;return}this.loader=Cn(t).start()}stopLoader(){this.loader?.stop(),this.loader=void 0}displaySpinner(t){return Cn(t).start()}stopSpinner(t){t.stop(),t.clear()}printStagedFiles(t,n){const o=Buffer.byteLength(t.diff,"utf8"),s=this.formatBytes(o),r=ec(t),a=this.formatCompressionStats(n);console.log(h.bold.green("\u2714 ")+h.bold(r)+h.dim(` (${s})`)+(a?h.cyan(` ${a}`):"")+h.bold(":")),console.log(`${t.files.map(l=>` ${l}`).join(`
152
152
  `)}
153
- `),o>Za&&!n&&(console.log(h.yellow(`\u26A0 Large diff detected (${s}). This may increase processing time and costs.`)),console.log(h.dim(` Consider using --exclude to filter large files or diffCompression=compact.
153
+ `),o>nc&&!n&&(console.log(h.yellow(`\u26A0 Large diff detected (${s}). This may increase processing time and costs.`)),console.log(h.dim(` Consider using --exclude to filter large files or diffCompression=compact.
154
154
  `)))}printAnalyzed(){console.log(`
155
155
  ${h.bold.green("\u2714")} ${h.bold("Changes analyzed")}`)}printCommitted(){console.log(`
156
156
  ${h.bold.green("\u2714")} ${h.bold("Successfully committed!")}`)}printCopied(){console.log(`
@@ -161,8 +161,8 @@ ${h.bold.red("\u2716")} ${h.red(`${t}`)}`)}printWarning(t){console.log(`
161
161
  ${h.bold.yellow("\u26A0")} ${h.yellow(`${t}`)}`)}printSuccess(t){console.log(`
162
162
  ${h.bold.green("\u2714")} ${h.green(`${t}`)}`)}printInfo(t){console.log(`
163
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=Me.createInterface({input:process.stdin,output:process.stdout});Me.moveCursor(process.stdout,0,-1),t.close()}moveCursorDown(){const t=Me.createInterface({input:process.stdin,output:process.stdout});Me.moveCursor(process.stdout,0,2),t.close()}print(t){console.log(t)}}let tt,Lo="info";async function ec(e){if(tt){console.warn("Logger already initialized. Skipping re-initialization.");return}const t=e?.logLevel||"info";Lo=t;const n=e?.logFilePath||Eo,o=e?.exceptionLogFilePath||vo,s=e?.logging??!0;await go(v.dirname(n)),await go(v.dirname(o));const r=[];s?r.push(new H.transports.DailyRotateFile({filename:n,datePattern:"YYYY-MM-DD",zippedArchive:!0,maxSize:"20m",maxFiles:"14d",level:t,format:H.format.combine(H.format.timestamp(),H.format.printf(({level:a,message:c,timestamp:u})=>`[${u}] ${a}: ${c}`))})):r.push(new H.transports.Console({silent:!0})),tt=H.createLogger({level:t,format:H.format.json(),transports:r,exceptionHandlers:s?[new H.transports.DailyRotateFile({filename:o,datePattern:"YYYY-MM-DD",zippedArchive:!0,maxSize:"20m",maxFiles:"14d",format:H.format.combine(H.format.timestamp(),H.format.json())})]:[],exitOnError:!1,silent:!s})}const he=new Proxy({},{get:(e,t,n)=>{if(!tt)throw new Error("Logger not initialized. Call initializeLogger() first.");return Reflect.get(tt,t,n)}});function Mo(){const e=H.config.npm.levels;return(e[Lo]??e.info)>=e.verbose}const tc={isLoading:!1,startOption:{text:"AI is analyzing your changes"}},To={isLoading:!1,startOption:{text:"AI is performing a code review"}},Vt="No commit messages were generated",Oo="No code reviews were generated",Jt={type:"reactiveListPrompt",name:"aicommit2Prompt",message:"Pick a commit message to use: ",emptyMessage:`\u26A0 ${Vt}`,loop:!1,descPageSize:15,showDescription:!0,pickKey:"short",isDescriptionDim:!0,stopMessage:"Changes analyzed"};class Xt{constructor(t){this.choices$=new hn([]),this.destroyed$=new $s(1),this.stopMessage="Changes analyzed",this.isDestroyed=!1,this.subscriptions=new mt,this.inquirerInstance=null,this.loader$=new hn(t)}addSubscription(t){if(this.isDestroyed){t.unsubscribe();return}this.subscriptions.add(t)}initPrompt(t=Jt){return this.stopMessage=t.stopMessage,T.registerPrompt("reactiveListPrompt",Is),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(yo));return}t.value&&this.choices$.next([...this.currentChoices,t].sort(yo))}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){Mo()&&console.warn("Error during ReactivePromptManager destruction:",t)}finally{this.inquirerInstance=null}}}alertNoGeneratedMessage(){this.loader$.next({isLoading:!1,message:Vt,stopOption:{doneFrame:"\u26A0",color:"yellow"}})}stopLoaderOnSuccess(){this.loader$.next({isLoading:!1,message:this.stopMessage})}logEmptyCommitMessage(){console.log(`
165
- ${h.bold.yellow("\u26A0")} ${h.yellow(`${Vt}`)}`)}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},R={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"},Qt={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(`
164
+ ${h.bold.green("\u2714")} ${h.bold(`Git ${t} hook has been set up`)}`)}moveCursorUp(){const t=Oe.createInterface({input:process.stdin,output:process.stdout});Oe.moveCursor(process.stdout,0,-1),t.close()}moveCursorDown(){const t=Oe.createInterface({input:process.stdin,output:process.stdout});Oe.moveCursor(process.stdout,0,2),t.close()}print(t){console.log(t)}}let tt,Lo="info";async function Jt(e){if(tt){console.warn("Logger already initialized. Skipping re-initialization.");return}const t=e?.logLevel||"info";Lo=t;const n=e?.logFilePath||Eo,o=e?.exceptionLogFilePath||vo,s=e?.logging??!0;await go(v.dirname(n)),await go(v.dirname(o));const r=[];s?r.push(new H.transports.DailyRotateFile({filename:n,datePattern:"YYYY-MM-DD",zippedArchive:!0,maxSize:"20m",maxFiles:"14d",level:t,format:H.format.combine(H.format.timestamp(),H.format.printf(({level:a,message:c,timestamp:l})=>`[${l}] ${a}: ${c}`))})):r.push(new H.transports.Console({silent:!0})),tt=H.createLogger({level:t,format:H.format.json(),transports:r,exceptionHandlers:s?[new H.transports.DailyRotateFile({filename:o,datePattern:"YYYY-MM-DD",zippedArchive:!0,maxSize:"20m",maxFiles:"14d",format:H.format.combine(H.format.timestamp(),H.format.json())})]:[],exitOnError:!1,silent:!s})}const ne=new Proxy({},{get:(e,t,n)=>{if(!tt)throw new Error("Logger not initialized. Call initializeLogger() first.");return Reflect.get(tt,t,n)}});function Oo(){const e=H.config.npm.levels;return(e[Lo]??e.info)>=e.verbose}const oc={isLoading:!1,startOption:{text:"AI is analyzing your changes"}},Mo={isLoading:!1,startOption:{text:"AI is performing a code review"}},Xt="No commit messages were generated",To="No code reviews were generated",Qt={type:"reactiveListPrompt",name:"aicommit2Prompt",message:"Pick a commit message to use: ",emptyMessage:`\u26A0 ${Xt}`,loop:!1,descPageSize:15,showDescription:!0,pickKey:"short",isDescriptionDim:!0,stopMessage:"Changes analyzed"};class Zt{constructor(t){this.choices$=new hn([]),this.destroyed$=new Is(1),this.stopMessage="Changes analyzed",this.isDestroyed=!1,this.subscriptions=new ft,this.inquirerInstance=null,this.loader$=new hn(t)}addSubscription(t){if(this.isDestroyed){t.unsubscribe();return}this.subscriptions.add(t)}initPrompt(t=Qt){return this.stopMessage=t.stopMessage,M.registerPrompt("reactiveListPrompt",Os),this.inquirerInstance=M.prompt({choices$:this.choices$,loader$:this.loader$,...t}),this.inquirerInstance}startLoader(){this.loader$.next({isLoading:!0})}updateLoaderText(t){this.isDestroyed||this.loader$.next({isLoading:!0,startOption:{text:t}})}clearLoader(){this.inquirerInstance&&this.loader$.next({isLoading:!1,clear:!0})}refreshChoices(t){if(this.isDestroyed||!t)return;const n=t.streamKey;if(n){if(!t.value){this.removeStreamingChoice(n);return}const o=[...this.currentChoices],s=o.findIndex(r=>r.streamKey===n);if(s>=0){o[s]=t,this.choices$.next(o);return}this.choices$.next([...this.currentChoices,t].sort(yo));return}t.value&&this.choices$.next([...this.currentChoices,t].sort(yo))}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){Oo()&&console.warn("Error during ReactivePromptManager destruction:",t)}finally{this.inquirerInstance=null}}}alertNoGeneratedMessage(){this.loader$.next({isLoading:!1,message:Xt,stopOption:{doneFrame:"\u26A0",color:"yellow"}})}stopLoaderOnSuccess(){this.loader$.next({isLoading:!1,message:this.stopMessage})}logEmptyCommitMessage(){console.log(`
165
+ ${h.bold.yellow("\u26A0")} ${h.yellow(`${Xt}`)}`)}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},R={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"},en={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
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
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
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(`
@@ -179,7 +179,7 @@ ${h.bold.yellow("\u26A0")} ${h.yellow(`${Vt}`)}`)}get currentChoices(){return th
179
179
  `),invalidConfigValue:(e,t)=>[`Invalid value for ${w.highlight(`"${e}"`)}`,"",`${w.label("\u2192")} Expected: ${w.dim(t)}`].join(`
180
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
181
  `),ollamaModelNotPulled:e=>[`Ollama model ${w.highlight(`"${e}"`)} is not available locally.`,"",`${w.label("\u2192")} Pull: ${w.command(`ollama pull ${e}`)}`].join(`
182
- `)},nc=e=>({401:R.INVALID_API_KEY,403:R.MODEL_ACCESS_DENIED,404:R.MODEL_NOT_FOUND,429:R.RATE_LIMITED,500:R.SERVER_ERROR,502:R.SERVICE_UNAVAILABLE,503:R.SERVICE_UNAVAILABLE,504:R.TIMEOUT})[e]||R.UNKNOWN,oc=e=>{const t=e.toLowerCase();return t.includes("api key")||t.includes("api_key")||t.includes("apikey")?t.includes("missing")?R.MISSING_API_KEY:R.INVALID_API_KEY:t.includes("401")||t.includes("unauthorized")||t.includes("authentication")?R.AUTH_FAILED:t.includes("rate")||t.includes("429")||t.includes("too many")?R.RATE_LIMITED:t.includes("quota")||t.includes("usage")||t.includes("limit exceeded")?R.QUOTA_EXCEEDED:t.includes("model")&&(t.includes("not found")||t.includes("404"))?R.MODEL_NOT_FOUND:t.includes("403")||t.includes("forbidden")||t.includes("access denied")?R.MODEL_ACCESS_DENIED:t.includes("econnrefused")||t.includes("network")||t.includes("connection")?R.NETWORK_ERROR:t.includes("timeout")||t.includes("timed out")||t.includes("504")?R.TIMEOUT:t.includes("unavailable")||t.includes("overloaded")||t.includes("503")||t.includes("502")?R.SERVICE_UNAVAILABLE:t.includes("500")||t.includes("internal server error")?R.SERVER_ERROR:R.UNKNOWN},W={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}`},sc=(e,t={})=>{const{provider:n="AI",model:o,timeout:s}=t;switch(e){case R.MISSING_API_KEY:return W.missingApiKey(n);case R.INVALID_API_KEY:case R.AUTH_FAILED:return W.invalidApiKey(n);case R.RATE_LIMITED:return W.rateLimited(n);case R.QUOTA_EXCEEDED:return W.quotaExceeded(n);case R.MODEL_NOT_FOUND:return W.modelNotFound(o||"unknown",n);case R.MODEL_ACCESS_DENIED:return W.modelAccessDenied(o||"unknown",n);case R.NETWORK_ERROR:return W.networkError(n);case R.TIMEOUT:return W.timeout(s||1e4,n);case R.SERVICE_UNAVAILABLE:return W.serviceUnavailable(n);case R.SERVER_ERROR:return W.serverError(n);default:return W.unknown(n)}},Do={locale:"en",maxLength:50,type:"conventional",generate:1,systemPrompt:"",systemPromptPath:"",codeReviewPromptPath:"",vcs_branch:"",isReasoning:!1},No={"":"<commit message>",conventional:`<type>(<optional scope>): <description>
182
+ `)},sc=e=>({401:R.INVALID_API_KEY,403:R.MODEL_ACCESS_DENIED,404:R.MODEL_NOT_FOUND,429:R.RATE_LIMITED,500:R.SERVER_ERROR,502:R.SERVICE_UNAVAILABLE,503:R.SERVICE_UNAVAILABLE,504:R.TIMEOUT})[e]||R.UNKNOWN,rc=e=>{const t=e.toLowerCase();return t.includes("api key")||t.includes("api_key")||t.includes("apikey")?t.includes("missing")?R.MISSING_API_KEY:R.INVALID_API_KEY:t.includes("401")||t.includes("unauthorized")||t.includes("authentication")?R.AUTH_FAILED:t.includes("rate")||t.includes("429")||t.includes("too many")?R.RATE_LIMITED:t.includes("quota")||t.includes("usage")||t.includes("limit exceeded")?R.QUOTA_EXCEEDED:t.includes("model")&&(t.includes("not found")||t.includes("404"))?R.MODEL_NOT_FOUND:t.includes("403")||t.includes("forbidden")||t.includes("access denied")?R.MODEL_ACCESS_DENIED:t.includes("econnrefused")||t.includes("network")||t.includes("connection")?R.NETWORK_ERROR:t.includes("timeout")||t.includes("timed out")||t.includes("504")?R.TIMEOUT:t.includes("unavailable")||t.includes("overloaded")||t.includes("503")||t.includes("502")?R.SERVICE_UNAVAILABLE:t.includes("500")||t.includes("internal server error")?R.SERVER_ERROR:R.UNKNOWN},W={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}`},ic=(e,t={})=>{const{provider:n="AI",model:o,timeout:s}=t;switch(e){case R.MISSING_API_KEY:return W.missingApiKey(n);case R.INVALID_API_KEY:case R.AUTH_FAILED:return W.invalidApiKey(n);case R.RATE_LIMITED:return W.rateLimited(n);case R.QUOTA_EXCEEDED:return W.quotaExceeded(n);case R.MODEL_NOT_FOUND:return W.modelNotFound(o||"unknown",n);case R.MODEL_ACCESS_DENIED:return W.modelAccessDenied(o||"unknown",n);case R.NETWORK_ERROR:return W.networkError(n);case R.TIMEOUT:return W.timeout(s||1e4,n);case R.SERVICE_UNAVAILABLE:return W.serviceUnavailable(n);case R.SERVER_ERROR:return W.serverError(n);default:return W.unknown(n)}},Do={locale:"en",maxLength:50,type:"conventional",generate:1,systemPrompt:"",systemPromptPath:"",codeReviewPromptPath:"",vcs_branch:"",isReasoning:!1},No={"":"<commit message>",conventional:`<type>(<optional scope>): <description>
183
183
 
184
184
  [optional body]
185
185
 
@@ -191,20 +191,20 @@ ${h.bold.yellow("\u26A0")} ${h.yellow(`${Vt}`)}`)}get currentChoices(){return th
191
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
192
  `)}`,conventional:`
193
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
- `)}`},Zt=(e,t)=>e.replace(/{(\w+)}/g,(n,o)=>t[o]?.toString()||Do[o]?.toString()),rc=(e,t)=>{const n=t.split("-")[0].toLowerCase(),o={conventional:{en:{subject:"fix(auth): fix bug in user authentication process",body:"- Update login function to handle edge cases\\n- Add additional error logging for debugging"},zh:{subject:"fix(auth): \u4FEE\u590D\u7528\u6237\u8BA4\u8BC1\u8FC7\u7A0B\u4E2D\u7684\u9519\u8BEF",body:"- \u66F4\u65B0\u767B\u5F55\u51FD\u6570\u4EE5\u5904\u7406\u8FB9\u7F18\u60C5\u51B5\\n- \u6DFB\u52A0\u989D\u5916\u7684\u9519\u8BEF\u65E5\u5FD7\u7528\u4E8E\u8C03\u8BD5"},ja:{subject:"fix(auth): \u30E6\u30FC\u30B6\u30FC\u8A8D\u8A3C\u30D7\u30ED\u30BB\u30B9\u306E\u30D0\u30B0\u3092\u4FEE\u6B63",body:"- \u30A8\u30C3\u30B8\u30B1\u30FC\u30B9\u3092\u51E6\u7406\u3059\u308B\u305F\u3081\u306B\u30ED\u30B0\u30A4\u30F3\u6A5F\u80FD\u3092\u66F4\u65B0\\n- \u30C7\u30D0\u30C3\u30B0\u7528\u306E\u8FFD\u52A0\u30A8\u30E9\u30FC\u30ED\u30B0\u3092\u8FFD\u52A0"},ko:{subject:"fix(auth): \uC0AC\uC6A9\uC790 \uC778\uC99D \uD504\uB85C\uC138\uC2A4\uC758 \uBC84\uADF8 \uC218\uC815",body:"- \uC5E3\uC9C0 \uCF00\uC774\uC2A4\uB97C \uCC98\uB9AC\uD558\uB3C4\uB85D \uB85C\uADF8\uC778 \uD568\uC218 \uC5C5\uB370\uC774\uD2B8\\n- \uB514\uBC84\uAE45\uC744 \uC704\uD55C \uCD94\uAC00 \uC624\uB958 \uB85C\uAE45 \uCD94\uAC00"},es:{subject:"fix(auth): corregir error en el proceso de autenticaci\xF3n",body:"- Actualizar funci\xF3n de inicio de sesi\xF3n para manejar casos extremos\\n- Agregar registro de errores adicional para depuraci\xF3n"},fr:{subject:"fix(auth): corriger un bug dans le processus d'authentification",body:"- Mettre \xE0 jour la fonction de connexion pour g\xE9rer les cas limites\\n- Ajouter une journalisation d'erreurs suppl\xE9mentaire pour le d\xE9bogage"},de:{subject:"fix(auth): Fehler im Benutzerauthentifizierungsprozess beheben",body:"- Login-Funktion aktualisiert, um Randf\xE4lle zu behandeln\\n- Zus\xE4tzliche Fehlerprotokollierung f\xFCr Debugging hinzugef\xFCgt"}},gitmoji:{en:{subject:":sparkles: Add real-time chat feature",body:"- Implement WebSocket connection\\n- Add message encryption\\n- Include typing indicators"},zh:{subject:":sparkles: \u6DFB\u52A0\u5B9E\u65F6\u804A\u5929\u529F\u80FD",body:"- \u5B9E\u73B0WebSocket\u8FDE\u63A5\\n- \u6DFB\u52A0\u6D88\u606F\u52A0\u5BC6\\n- \u5305\u542B\u8F93\u5165\u6307\u793A\u5668"},ja:{subject:":sparkles: \u30EA\u30A2\u30EB\u30BF\u30A4\u30E0\u30C1\u30E3\u30C3\u30C8\u6A5F\u80FD\u3092\u8FFD\u52A0",body:"- WebSocket\u63A5\u7D9A\u3092\u5B9F\u88C5\\n- \u30E1\u30C3\u30BB\u30FC\u30B8\u6697\u53F7\u5316\u3092\u8FFD\u52A0\\n- \u5165\u529B\u30A4\u30F3\u30B8\u30B1\u30FC\u30BF\u30FC\u3092\u542B\u3080"},ko:{subject:":sparkles: \uC2E4\uC2DC\uAC04 \uCC44\uD305 \uAE30\uB2A5 \uCD94\uAC00",body:"- WebSocket \uC5F0\uACB0 \uAD6C\uD604\\n- \uBA54\uC2DC\uC9C0 \uC554\uD638\uD654 \uCD94\uAC00\\n- \uC785\uB825 \uD45C\uC2DC\uAE30 \uD3EC\uD568"},es:{subject:":sparkles: Agregar funci\xF3n de chat en tiempo real",body:"- Implementar conexi\xF3n WebSocket\\n- Agregar cifrado de mensajes\\n- Incluir indicadores de escritura"},fr:{subject:":sparkles: Ajouter une fonctionnalit\xE9 de chat en temps r\xE9el",body:"- Impl\xE9menter une connexion WebSocket\\n- Ajouter le chiffrement des messages\\n- Inclure des indicateurs de saisie"},de:{subject:":sparkles: Echtzeit-Chat-Funktion hinzuf\xFCgen",body:"- WebSocket-Verbindung implementieren\\n- Nachrichtenverschl\xFCsselung hinzuf\xFCgen\\n- Tippindikatoren einschlie\xDFen"}},"":{en:{subject:"",body:""}}},s=o[e]||o[""];return s[n]||s.en},ic=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:",`${No[t]}`,`Allowed types:${_o[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
- `)},ac=e=>{const{type:t,maxLength:n,generate:o,locale:s}=e;return[`You are an expert developer writing ${t||""} commit message${o!==1?"s":""} from a git diff.`,"","Analyze the diff to understand:","1. What is the primary intent of these changes? (new feature, bug fix, refactor, etc.)","2. What is the scope? (which module, component, or system is affected?)","3. Are there any breaking changes or side effects?","",`Language: ${s}`,`Subject: max ${n} chars, imperative mood, no period`,t?`Format: ${No[t]}`:"",t?`Allowed types:${_o[t]}`:"","",`Generate exactly ${o} commit message${o!==1?"s":""}.`,"Prioritize explaining WHY the change was made over describing WHAT changed."].filter(Boolean).join(`
196
- `)},cc=(e,t,n)=>{const o=rc(e,n),r=e==="conventional"||e==="gitmoji"?`
194
+ `)}`},tn=(e,t)=>e.replace(/{(\w+)}/g,(n,o)=>t[o]?.toString()||Do[o]?.toString()),ac=(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},cc=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:",`${No[t]}`,`Allowed types:${_o[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
+ `)},lc=e=>{const{type:t,maxLength:n,generate:o,locale:s}=e;return[`You are an expert developer writing ${t||""} commit message${o!==1?"s":""} from a git diff.`,"","Analyze the diff to understand:","1. What is the primary intent of these changes? (new feature, bug fix, refactor, etc.)","2. What is the scope? (which module, component, or system is affected?)","3. Are there any breaking changes or side effects?","",`Language: ${s}`,`Subject: max ${n} chars, imperative mood, no period`,t?`Format: ${No[t]}`:"",t?`Allowed types:${_o[t]}`:"","",`Generate exactly ${o} commit message${o!==1?"s":""}.`,"Prioritize explaining WHY the change was made over describing WHAT changed."].filter(Boolean).join(`
196
+ `)},uc=(e,t,n)=>{const o=ac(e,n),r=e==="conventional"||e==="gitmoji"?`
197
197
  [
198
198
  {"subject": "${o.subject}", "body": "${o.body}", "footer": ""}
199
199
  ]`:"";return[`
200
200
  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?`
201
201
  Example:${r}`:"",`
202
202
  Return valid JSON only.`].filter(Boolean).join(`
203
- `)},lc=e=>{const{systemPrompt:t,systemPromptPath:n,type:o,generate:s,locale:r,isReasoning:a}=e,c=cc(o,s,r);if(t)return`${Zt(t,e)}
204
- ${c}`;if(n)try{const l=j.readFileSync(Ue(n),"utf-8");return`${Zt(l,e)}
205
- ${c}`}catch{}return`${a?ac(e):ic(e)}
206
- ${c}`},uc=e=>{const{codeReviewPromptPath:t,locale:n}=e;if(t)try{const o=j.readFileSync(Ue(t),"utf-8");return`${Zt(o,e)}`}catch{}return dc(n)},dc=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
- `),jo=async e=>{if(e.systemPromptPath)try{j.readFileSync(Ue(e.systemPromptPath),"utf-8")}catch(t){throw new p(`Error reading system prompt file: ${e.systemPromptPath}, ${t}`)}if(e.codeReview&&e.codeReviewPromptPath)try{j.readFileSync(Ue(e.codeReviewPromptPath),"utf-8")}catch(t){throw new p(`Error reading code review prompt file: ${e.codeReviewPromptPath}, ${t}`)}},mc=(e,t="commit",n)=>{const o=[];return n?.recentCommits&&o.push(`## Recent Commits (for style reference)
203
+ `)},dc=e=>{const{systemPrompt:t,systemPromptPath:n,type:o,generate:s,locale:r,isReasoning:a}=e,c=uc(o,s,r);if(t)return`${tn(t,e)}
204
+ ${c}`;if(n)try{const u=j.readFileSync(Ue(n),"utf-8");return`${tn(u,e)}
205
+ ${c}`}catch{}return`${a?lc(e):cc(e)}
206
+ ${c}`},mc=e=>{const{codeReviewPromptPath:t,locale:n}=e;if(t)try{const o=j.readFileSync(Ue(t),"utf-8");return`${tn(o,e)}`}catch{}return fc(n)},fc=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
+ `),jo=async e=>{if(e.systemPromptPath)try{j.readFileSync(Ue(e.systemPromptPath),"utf-8")}catch(t){throw new p(`Error reading system prompt file: ${e.systemPromptPath}, ${t}`)}if(e.codeReview&&e.codeReviewPromptPath)try{j.readFileSync(Ue(e.codeReviewPromptPath),"utf-8")}catch(t){throw new p(`Error reading code review prompt file: ${e.codeReviewPromptPath}, ${t}`)}},pc=(e,t="commit",n)=>{const o=[];return n?.recentCommits&&o.push(`## Recent Commits (for style reference)
208
208
  ${n.recentCommits}`),n?.branchName&&o.push(`## Branch
209
209
  ${n.branchName}`),`${o.length>0?o.join(`
210
210
 
@@ -212,24 +212,24 @@ ${n.branchName}`),`${o.length>0?o.join(`
212
212
 
213
213
  `:""}\`\`\`diff
214
214
  ${e}
215
- \`\`\``},_=new K;var fc=async(e,t,n,o,s,r,a,c,u,l,d,f,g,y,m,x,$)=>(async()=>{const A=x==="json";A||_.printTitle();const S=A?null:_.displaySpinner("Detecting repository...");if(await zt(),o){S&&(S.text="Staging changes...");const Z=await Xe();Z==="git"?await b("git",["add","."]):Z==="yadm"&&await b("yadm",["add","--update"])}S&&(S.text="Loading configuration...");const P={locale:e?.toString(),generate:t?.toString(),type:s?.toString(),systemPrompt:c?.toString(),...u===!0&&{includeBody:"true"},...f===!0&&{disableLowerCase:"true"}};g&&(P.logLevel="verbose");const C=await J(P,$);(u===!0||C.includeBody===!0)&&$a(C),f&&Sa(C),await jo(C);const L={autoNew:m||C.jjAutoNew};S&&(S.text="Detecting staged files...");const D=await Yt(n,C.exclude);if(S?.stop(),!D){const Z=await Xe();throw new p(Qt.noStagedChanges(Z),{code:R.NO_STAGED_CHANGES})}if(!A){const Z=ko(D,{mode:C.diffCompression,maxHunkLines:C.maxHunkLines,maxDiffLines:C.maxDiffLines});_.printStagedFiles(D,Z.compression)}const oe=pe(C,"commit");if(oe.length===0)throw new p(Qt.noApiKeysConfigured(),{code:R.MISSING_API_KEY});const X=await Qe(),os=await Ze(),ct=new et(C,D,X,os);A&&((await yc(ct,oe)).forEach(rs=>{process.stdout.write(JSON.stringify(rs)+`
216
- `)}),process.exit(0));const cn=pe(C,"review");cn.length>0&&await pc(ct,cn);const lt=await hc(ct,oe,l);C.useStats!==!1&&Ba({provider:lt.provider,model:lt.model,statsDays:C.statsDays}).catch(()=>{});let Q=lt.value;if(d){if(_.printInfo("Opening editor to modify commit message..."),Q=await gc(Q),!Q.trim())throw new p(Qt.emptyCommitMessage(),{code:R.EMPTY_COMMIT_MESSAGE});_.printSuccess("Commit message edited successfully!"),_.print(`
217
- ${Q}
218
- `)}(a||C.autoCopy)&&(ht("copy-paste").copy(Q),a&&_.printCopied()),a&&!y&&process.exit(),y&&(process.stdout.write(Q+`
219
- `),process.exit()),(r||l&&oe.length===1)&&(await Fo(Q,$,L),process.exit());const{confirmationPrompt:ss}=await T.prompt([{type:"confirm",name:"confirmationPrompt",message:"Use selected message?",default:!0}]);ss?await Fo(Q,$,L):_.printCancelledCommit(),process.exit()})().catch(A=>{if(x==="json"){const S={error:A.message||"Unknown error occurred"};process.stderr.write(JSON.stringify(S)+`
220
- `),process.exit(1)}_.printError(A.message),q(A),process.exit(1)});async function pc(e,t){const n=new Xt(To);let o=null;try{const s=n.initPrompt({...Jt,name:"codeReviewPrompt",message:"Please check code reviews: ",emptyMessage:`\u26A0 ${Oo}`,isDescriptionDim:!1,stopMessage:"Code review completed",descPageSize:20});n.startLoader(),o=e.createCodeReviewRequests$(t).subscribe({next:d=>n.refreshChoices(d),error:d=>{console.error("Code review request error:",d),n.checkErrorOnChoices()},complete:()=>n.checkErrorOnChoices()});const a=(await s).codeReviewPrompt?.value;if(!a)throw new p("An error occurred! No selected code review");_.moveCursorUp();const c=a.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||(_.printCancelledCommit(),process.exit())}finally{o&&o.unsubscribe(),n.destroy()}}const hc=async(e,t,n)=>{const o=new Xt(tc);let s=null;try{if(n&&t.length===1){const f=[];o.startLoader(),s=e.createCommitMsgRequests$(t).subscribe({next:y=>{"streamKey"in y||f.push(y),o.refreshChoices(y)},error:y=>{console.error("Commit message generation error:",y),o.checkErrorOnChoices(!1)},complete:()=>o.checkErrorOnChoices(!1)}),await new Promise(y=>{s?.add(()=>y())}),o.clearLoader(),_.moveCursorUp();const g=f.find(y=>y.value&&!y.isError&&!y.disabled);if(!g||!g.value)throw new p("No valid commit message was generated");return _.print(`
215
+ \`\`\``},_=new K;var hc=async(e,t,n,o,s,r,a,c,l,u,d,f,g,y,m,x,S)=>(async()=>{const A=x==="json";A||_.printTitle();const $=A?null:_.displaySpinner("Detecting repository...");if(await Yt(),o){$&&($.text="Staging changes...");const ee=await Xe();ee==="git"?await b("git",["add","."]):ee==="yadm"&&await b("yadm",["add","--update"])}$&&($.text="Loading configuration...");const P={locale:e?.toString(),generate:t?.toString(),type:s?.toString(),systemPrompt:c?.toString(),...l===!0&&{includeBody:"true"},...f===!0&&{disableLowerCase:"true"}};g&&(P.logLevel="verbose");const C=await J(P,S);(l===!0||C.includeBody===!0)&&Ia(C),f&&ka(C),await jo(C);const L={autoNew:m||C.jjAutoNew};$&&($.text="Detecting staged files...");const D=await Vt(n,C.exclude);if($?.stop(),!D){const ee=await Xe();throw new p(en.noStagedChanges(ee),{code:R.NO_STAGED_CHANGES})}if(!A){const ee=ko(D,{mode:C.diffCompression,maxHunkLines:C.maxHunkLines,maxDiffLines:C.maxDiffLines});_.printStagedFiles(D,ee.compression)}const X=he(C,"commit");if(X.length===0)throw new p(en.noApiKeysConfigured(),{code:R.MISSING_API_KEY});const Q=await Qe(),ct=await Ze(),lt=new et(C,D,Q,ct);A&&((await Cc(lt,X)).forEach(cs=>{process.stdout.write(JSON.stringify(cs)+`
216
+ `)}),process.exit(0));const cn=he(C,"review");cn.length>0&&await gc(lt,cn);const ut=await yc(lt,X,u);C.useStats!==!1&&Ka({provider:ut.provider,model:ut.model,statsDays:C.statsDays}).catch(()=>{});let Z=ut.value;if(d){if(_.printInfo("Opening editor to modify commit message..."),Z=await wc(Z),!Z.trim())throw new p(en.emptyCommitMessage(),{code:R.EMPTY_COMMIT_MESSAGE});_.printSuccess("Commit message edited successfully!"),_.print(`
217
+ ${Z}
218
+ `)}(a||C.autoCopy)&&(gt("copy-paste").copy(Z),a&&_.printCopied()),a&&!y&&process.exit(),y&&(process.stdout.write(Z+`
219
+ `),process.exit()),(r||u&&X.length===1)&&(await Fo(Z,S,L),process.exit());const{confirmationPrompt:as}=await M.prompt([{type:"confirm",name:"confirmationPrompt",message:"Use selected message?",default:!0}]);as?await Fo(Z,S,L):_.printCancelledCommit(),process.exit()})().catch(A=>{if(x==="json"){const $={error:A.message||"Unknown error occurred"};process.stderr.write(JSON.stringify($)+`
220
+ `),process.exit(1)}_.printError(A.message),q(A),process.exit(1)});async function gc(e,t){const n=new Zt(Mo);let o=null;try{const s=n.initPrompt({...Qt,name:"codeReviewPrompt",message:"Please check code reviews: ",emptyMessage:`\u26A0 ${To}`,isDescriptionDim:!1,stopMessage:"Code review completed",descPageSize:20});n.startLoader(),o=e.createCodeReviewRequests$(t).subscribe({next:d=>n.refreshChoices(d),error:d=>{console.error("Code review request error:",d),n.checkErrorOnChoices()},complete:()=>n.checkErrorOnChoices()});const a=(await s).codeReviewPrompt?.value;if(!a)throw new p("An error occurred! No selected code review");_.moveCursorUp();const c=a.includes("<!-- HAS_CRITICAL_ISSUES -->"),l=c?"Critical issues found in code review. Continue without fixing?":"Will you continue without changing the code?",{continuePrompt:u}=await M.prompt([{type:"confirm",name:"continuePrompt",message:l,default:!c}]);u||(_.printCancelledCommit(),process.exit())}finally{o&&o.unsubscribe(),n.destroy()}}const yc=async(e,t,n)=>{const o=new Zt(oc);let s=null;try{if(n&&t.length===1){const f=[];o.startLoader(),s=e.createCommitMsgRequests$(t).subscribe({next:y=>{"streamKey"in y||f.push(y),o.refreshChoices(y)},error:y=>{console.error("Commit message generation error:",y),o.checkErrorOnChoices(!1)},complete:()=>o.checkErrorOnChoices(!1)}),await new Promise(y=>{s?.add(()=>y())}),o.clearLoader(),_.moveCursorUp();const g=f.find(y=>y.value&&!y.isError&&!y.disabled);if(!g||!g.value)throw new p("No valid commit message was generated");return _.print(`
221
221
  ${g.name}
222
- `),{value:g.value,provider:g.provider||"unknown",model:g.model||"unknown"}}const r=new Map,a=o.initPrompt();o.startLoader();let c=0;s=e.createCommitMsgRequests$(t).subscribe({next:f=>{const g=f;g.value&&r.set(g.value,g),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 a;_.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 gc(e){const t=process.env.VISUAL||process.env.EDITOR||(process.platform==="win32"?"notepad":"vi"),n=v.join(ke.tmpdir(),`aicommit2-${Date.now()}-${cs.randomBytes(4).toString("hex")}.txt`);try{j.writeFileSync(n,e,"utf8");const o=t.split(" "),[s,...r]=o;await b(s,[...r,n],{stdio:"inherit"});const a=j.readFileSync(n,"utf8").trim();if(j.unlinkSync(n),!a)throw new p("Commit cancelled - empty message");return a}catch(o){throw j.existsSync(n)&&j.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:
222
+ `),{value:g.value,provider:g.provider||"unknown",model:g.model||"unknown"}}const r=new Map,a=o.initPrompt();o.startLoader();let c=0;s=e.createCommitMsgRequests$(t).subscribe({next:f=>{const g=f;g.value&&r.set(g.value,g),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 l=await a;_.moveCursorUp();const u=l.aicommit2Prompt?.value;if(!u)throw new p("An error occurred! No selected message");const d=r.get(u);return{value:u,provider:d?.provider||"unknown",model:d?.model||"unknown"}}finally{s&&s.unsubscribe(),o.destroy()}};async function wc(e){const t=process.env.VISUAL||process.env.EDITOR||(process.platform==="win32"?"notepad":"vi"),n=v.join(ke.tmpdir(),`aicommit2-${Date.now()}-${ds.randomBytes(4).toString("hex")}.txt`);try{j.writeFileSync(n,e,"utf8");const o=t.split(" "),[s,...r]=o;await b(s,[...r,n],{stdio:"inherit"});const a=j.readFileSync(n,"utf8").trim();if(j.unlinkSync(n),!a)throw new p("Commit cancelled - empty message");return a}catch(o){throw j.existsSync(n)&&j.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:
223
223
  - Editor binary exists in PATH
224
224
  - Editor flags are correct
225
- - 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 Fo=async(e,t,n)=>{await Qa(e,t,n),_.printCommitted()},yc=async(e,t)=>{const o=(await ft(e.createCommitMsgRequests$(t).pipe(pt()),{defaultValue:[]})).filter(s=>s.value&&!s.isError&&!s.disabled);if(o.length===0)throw new p("No valid commit messages were generated");return o.map(({value:s=""})=>{const[r="",...a]=s.split(`
225
+ - 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 Fo=async(e,t,n)=>{await tc(e,t,n),_.printCommitted()},Cc=async(e,t)=>{const o=(await pt(e.createCommitMsgRequests$(t).pipe(ht()),{defaultValue:[]})).filter(s=>s.value&&!s.isError&&!s.disabled);if(o.length===0)throw new p("No valid commit messages were generated");return o.map(({value:s=""})=>{const[r="",...a]=s.split(`
226
226
  `);return{subject:r,body:a.join(`
227
- `).trim()}})};var wc=F({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:[F({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"]}}),F({name:"get",parameters:["[<key>","[<key> ...]]"],help:{description:"Retrieve configuration values for specified AI provider.",examples:["aic2 config get OPENAI","aic2 config get ANTHROPIC"]}}),F({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"']}}),F({name:"list",parameters:[],help:{description:"Display all configuration keys and their values.",examples:["aic2 config list"]}}),F({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"]}}),F({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 a=r.split(".");let c=s,u=!0;for(const l of a)if(Ft(c,l))c=c[l];else{u=!1;break}u?console.log(r,c):console.log(`${r} not found`)}return}if(t==="set"){await We(n.map(s=>{const r=s.indexOf("=");if(r===-1)throw new p("Invalid format. Use: key=value");const a=s.slice(0,r),c=s.slice(r+1);return[a,c]}));return}if(t==="add"){await La(n.map(s=>{const r=s.indexOf("=");if(r===-1)throw new p("Invalid format. Use: key=value");const a=s.slice(0,r),c=s.slice(r+1);return[a,c]}));return}if(t==="list"){await Ma();return}if(t==="del"){if(!o)throw new p("Please provide the config name to delete.");const s=await Se(),r=o.split(".");if(r.length===2){const[a,c]=r;if(s[a]&&typeof s[a]=="object"&&Ft(s[a],c)){delete s[a][c],Object.keys(s[a]).length===0&&delete s[a];const u=await fe();await I.writeFile(u,ue.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 a=r[0];if(Ft(s,a)){delete s[a];const c=await fe();await I.writeFile(c,ue.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 Ta();return}throw new p(`Invalid mode: ${t}`)})().catch(t=>{new K().printError(t.message),q(t),process.exit(1)})});const nt="https://models.github.ai",en="/inference/chat/completions",tn="2026-03-10",nn="openai/gpt-4o-mini",Cc=/^([A-Za-z0-9][A-Za-z0-9._-]*)\/([A-Za-z0-9][A-Za-z0-9._:-]*)$/,Go=e=>(e||"").trim(),Bo=e=>{const t=Go(e);return t.length>0&&Cc.test(t)},bc=e=>{const t=Go(e);if(!Bo(t))throw new Error(`Invalid GitHub Models model ID "${t||"(empty)"}". Expected format: "publisher/model" (example: "openai/gpt-4o-mini").`);return t},Ec=e=>{const t=(e||"").trim();return t?["ghp_","gho_","ghu_","ghs_","ghr_","github_pat_"].some(o=>t.startsWith(o)):!1};class ot{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=ks.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 vc={healthy:h.green("\u2705"),error:h.red("\u274C"),warning:h.yellow("\u26A0\uFE0F"),skipped:h.gray("\u23ED\uFE0F")},Pc={healthy:h.green,error:h.red,warning:h.yellow,skipped:h.gray},on=e=>typeof e.key=="string"&&e.key.trim().length>0,Ho=e=>(Array.isArray(e.model)?e.model:typeof e.model=="string"&&e.model.trim().length>0?[e.model.trim()]:[]).length>0,Ac=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)&&Object.keys(e).length>0,xc=e=>typeof e=="string"&&e.trim()?e.replace(/\/$/,""):"https://openrouter.ai",$c=e=>`${xc(e.url)}/api/v1`,Sc=e=>({Authorization:`Bearer ${e}`,"Content-Type":"application/json","HTTP-Referer":"https://github.com/tak-bro/aicommit2","X-OpenRouter-Title":"aicommit2","X-OpenRouter-Categories":"cli-agent"}),Rc=(e,t)=>{const n=e.trim();return t.find(o=>[o.id,o.canonical_slug,o.name].filter(r=>!!r).some(r=>r===n))},Ic=(e,t)=>e.supported_parameters?.includes(t)??!1,kc=[{configKey:"OPENROUTER.responseFormat",configProperty:"responseFormat",parameters:["response_format"]},{configKey:"OPENROUTER.reasoning",configProperty:"reasoning",parameters:["reasoning","include_reasoning"]}],Lc=e=>{const t=e.supported_parameters||[];return t.length>0?`supports: ${t.join(", ")}`:"no supported parameters listed"},Mc=(e,t)=>{const n=[];for(const o of kc){if(!Ac(e[o.configProperty]))continue;o.parameters.some(r=>Ic(t,r))||n.push(o.configKey)}return n},Tc=(e,t,n)=>{const o=n.context_length||n.top_provider?.context_length,s=Lc(n),r=Mc(t,n),a=o?`${o} ctx`:"";if(r.length>0){const l=[`consider removing ${r.join(", ")}`,a,s].filter(Boolean);return`${e}: ${l.join("; ")}`}const c=[a,s].filter(Boolean);return c.length>0?`${e} (${c.join("; ")})`:e},Uo=(e,t)=>{const n=[],o=Array.isArray(e.model)?e.model:typeof e.model=="string"?[e.model]:[];for(const s of o){if(s==="openrouter/auto"){n.push("Auto routing enabled");continue}const r=Rc(s,t);if(!r){n.push(`Model not found in catalog: ${s}`);continue}n.push(Tc(s,e,r))}return n},Oc=async(e,t)=>{try{return await new ot({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}}},Dc=async(e,t)=>{const n=typeof e.key=="string"?e.key.trim():"";if(!n)return{ok:!1,error:"No API key configured"};try{const o=$c(e),s=Sc(n),r=["/models/user","/models"];let a,c;for(const y of r)try{a=await new ot({method:"GET",baseURL:`${o}${y}`,timeout:t}).setHeaders(s).execute();break}catch(m){if(c=m,!(m instanceof Error?m.message:String(m)).includes("404"))throw m}if(!a)throw c instanceof Error?c:new Error(String(c));const u=a.data?.data??[],l=Ho(e)?Array.isArray(e.model)?e.model:[e.model]:[];if(l.length===0)return{ok:!0,details:`Catalog reachable (${u.length} models)`};if(l.includes("openrouter/auto")){const y=Uo(e,u);return{ok:!0,details:y.length>0?y.join("; "):`Auto routing enabled (${u.length} models)`}}const f=Uo(e,u);return f.some(y=>y.startsWith("Model not found in catalog:"))?{ok:!1,error:"Selected model not found in OpenRouter catalog",details:f.join("; ")}:{ok:!0,details:f.join("; ")}}catch(o){const s=o instanceof Error?o.message:String(o);return s.includes("401")||s.includes("403")?{ok:!1,error:"Unauthorized or forbidden when reading OpenRouter catalog"}:s.includes("404")?{ok:!1,error:"OpenRouter catalog endpoint not found"}:{ok:!1,error:s}}},Nc=e=>Array.isArray(e.model)&&e.model.length>0?String(e.model[0]).trim():typeof e.model=="string"&&e.model.trim().length>0?e.model.trim():nn,_c=async(e,t)=>{const n=typeof e.key=="string"?e.key.trim():"";if(!n)return{ok:!1,error:"No API key configured"};const o=Nc(e);if(!Bo(o))return{ok:!1,error:"Invalid model ID format",details:`Expected "publisher/model", got "${o||"(empty)"}"`};try{const s=`${nt}${en}`;return await new ot({method:"POST",baseURL:s,timeout:t}).setHeaders({"Content-Type":"application/json",Accept:"application/vnd.github+json","X-GitHub-Api-Version":tn,Authorization:`Bearer ${n}`}).setBody({model:o,messages:[{role:"user",content:"health-check"}],max_tokens:1,stream:!1}).execute(),{ok:!0,details:`Model: ${o}`}}catch(s){const r=s instanceof Error?s.message:String(s);return r.includes("401")?{ok:!1,error:"Authentication failed (401)"}:r.includes("403")?{ok:!1,error:"Access denied (403). Check token permission: models: read"}:r.includes("404")?{ok:!1,error:`Model not found (404): ${o}`}:r.includes("422")?{ok:!1,error:`Request validation failed (422) for model: ${o}`}:{ok:!1,error:r}}},jc=e=>{const t=Array.isArray(e.model)?String(e.model[0]||"").trim():String(e.model||"").trim();if(!t)return{ok:!1,error:"No model configured"};try{if((process.env.COPILOT_GITHUB_TOKEN||"").trim().startsWith("ghp_"))return{ok:!1,error:"Unsupported classic PAT in COPILOT_GITHUB_TOKEN",details:"Copilot CLI requires Fine-Grained PAT (github_pat_...) or Copilot login flow"};const o=process.versions.node,s=Number(o.split(".")[0]||"0");if(Number.isFinite(s)&&s<22)return{ok:!1,error:`Node.js ${o} is too old for Copilot SDK`,details:"Copilot SDK v0.2.0 requires node:sqlite support (Node.js 22+ recommended)"};const r=ye("copilot --version",{stdio:["ignore","pipe","pipe"]}).toString().trim();return{ok:!0,details:r?`CLI: ${r}; Model: ${t}; Node: ${o}`:`Model: ${t}; Node: ${o}`}}catch{return{ok:!1,error:"Copilot CLI not found",details:"Install and authenticate Copilot CLI before using COPILOT_SDK provider"}}},Fc=async(e,t,n)=>{if(e==="OLLAMA"){if(!Y(t))return{provider:e,status:"skipped",message:"No models configured"};const o=typeof t.host=="string"&&t.host.trim()?t.host:Pe,s=await Oc(o,n);return s.ok?{provider:e,status:"healthy",message:"Running",details:`Host: ${o}`}:{provider:e,status:"warning",message:s.error||"Connection failed",details:`Host: ${o}`}}if(e==="HUGGINGFACE")return t.cookie?{provider:e,status:"healthy",message:"Cookie configured"}:{provider:e,status:"skipped",message:"No cookie configured"};if(e==="BEDROCK")return ze(t)?{provider:e,status:"healthy",message:"Credentials configured"}:{provider:e,status:"skipped",message:"Not configured"};if(e==="OPENROUTER"){if(!on(t))return{provider:e,status:"skipped",message:"Not configured"};const o=await Dc(t,n);return o.ok?{provider:e,status:"healthy",message:"Catalog reachable",details:o.details}:{provider:e,status:"warning",message:o.error||"Catalog check failed",details:o.details}}if(e==="GITHUB_MODELS"){if(!on(t))return{provider:e,status:"skipped",message:"Not configured"};const o=await _c(t,n);return o.ok?{provider:e,status:"healthy",message:"Models API reachable",details:o.details}:{provider:e,status:"warning",message:o.error||"Connection check failed",details:o.details}}if(e==="COPILOT_SDK"){if(!Ho(t))return{provider:e,status:"skipped",message:"No models configured"};const o=jc(t);return o.ok?{provider:e,status:"healthy",message:"SDK environment ready",details:o.details}:{provider:e,status:"warning",message:o.error||"Environment check failed",details:o.details}}return on(t)?{provider:e,status:"healthy",message:"API key configured"}:{provider:e,status:"skipped",message:"Not configured"}},Gc=async e=>{const t=[],n=e.timeout||1e4;for(const o of me){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 Fc(o,s,n);t.push(r)}return t},Bc=Math.max(...me.map(e=>e.length)),Hc=e=>e.padEnd(Bc),Uc=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=vc[n.status],s=Hc(n.provider),r=Pc[n.status](n.message),a=n.details?h.gray(` (${n.details})`):"";console.log(` ${o} ${s} ${r}${a}`)}const t={healthy:e.filter(n=>n.status==="healthy").length,error:e.filter(n=>n.status==="error").length,warning:e.filter(n=>n.status==="warning").length,skipped:e.filter(n=>n.status==="skipped").length};console.log(""),console.log(h.bold("Summary: ")+h.green(`${t.healthy} healthy`)+", "+h.red(`${t.error} error`)+", "+h.yellow(`${t.warning} warning`)+", "+h.gray(`${t.skipped} skipped`)),console.log(""),t.error>0&&(process.exitCode=1)},Kc=F({name:"doctor",parameters:[],help:{description:"Check health status of configured AI providers",examples:["aicommit2 doctor"]}},()=>{(async()=>{const e=await J({},[]),t=await Gc(e);Uc(t)})().catch(e=>{console.error(h.red(e.message)),q(e),process.exit(1)})});var Wc=F({name:"github-login",parameters:[],flags:{token:{type:String,description:"Manually provide a GitHub token for authentication",alias:"t"}},help:{description:"Login to GitHub and setup access to GitHub Models",examples:["aic2 github-login","aic2 github-login --token github_pat_xxxxxxxxxxxxxxxxxxxx"]}},e=>{(async()=>{const t=new K;if(e.flags.token){try{await qc(e.flags.token,t)}catch(n){throw new p(`Token authentication failed: ${n.message}`)}return}try{await zc(t)}catch(n){throw new p(`Browser authentication failed: ${n.message}`)}})().catch(t=>{new K().printError(t.message),q(t),process.exit(1)})});async function qc(e,t){if(t.printWarning("Authenticating with provided token..."),!Ec(e))throw new Error("Invalid token format. Expected GitHub token prefix like ghp_, gho_, ghu_, ghs_, ghr_, or github_pat_");try{const n=await fetch("https://api.github.com/user",{headers:{Authorization:`Bearer ${e}`,Accept:"application/vnd.github.v3+json","User-Agent":"aicommit2-github-models"}});if(!n.ok)throw new Error(`GitHub API request failed: ${n.status} ${n.statusText}`);const o=await n.json();try{(await fetch(`${nt}${en}`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/vnd.github+json","X-GitHub-Api-Version":tn,Authorization:`Bearer ${e}`,"User-Agent":"aicommit2-github-models"},body:JSON.stringify({messages:[{role:"user",content:"test"}],model:nn,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 We([["GITHUB_MODELS.key",e]]),t.printSuccess(`Successfully authenticated as ${o.login}`)}catch(n){throw new Error(`Token validation failed: ${n.message}`)}}async function zc(e){e.printInfo("Starting GitHub browser authentication for GitHub Models...");try{try{ye("gh --version",{stdio:"ignore"})}catch{throw new Error("GitHub CLI (gh) is not installed. Please install it first: https://cli.github.com/")}try{ye("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{ye("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=ye("gh auth token",{encoding:"utf8"}).trim();t&&(await We([["GITHUB_MODELS.key",t]]),e.printSuccess("GitHub token stored for GitHub Models access"))}catch{e.printWarning("Could not extract token from GitHub CLI, but authentication completed")}e.printSuccess("GitHub authentication completed and GitHub Models access verified!"),e.printInfo("See usage guide: https://github.com/tak-bro/aicommit2/blob/main/docs/providers/github-models.md"),e.printInfo("Use `gh models list` to view the latest available models."),e.printInfo(`Using GitHub Models API: ${nt}`)}catch(t){throw t}}const ge="prepare-commit-msg",Yc=async()=>{const e=await Xe();if(e==="git")return`.git/hooks/${ge}`;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 sa}),{stdout:r}=await s("yadm",["introspect","repo"]),a=r.trim();if(a)return v.join(a,"hooks",ge)}catch{}const n=v.join(t,".config/yadm/hooks"),o=v.join(t,".yadm/hooks");try{return await I.access(n),v.join(n,ge)}catch{return v.join(o,ge)}}throw e==="jujutsu"?new p("Hooks are not supported for Jujutsu repositories."):new p(`Hooks are not supported for ${e} repositories.`)},st=Ls(new URL("cli.mjs",import.meta.url)),Vc=process.argv[1].replace(/\\/g,"/").includes(`/hooks/${ge}`),Ko=process.platform==="win32",Wo=`
227
+ `).trim()}})};var bc=F({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:[F({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"]}}),F({name:"get",parameters:["[<key>","[<key> ...]]"],help:{description:"Retrieve configuration values for specified AI provider.",examples:["aic2 config get OPENAI","aic2 config get ANTHROPIC"]}}),F({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"']}}),F({name:"list",parameters:[],help:{description:"Display all configuration keys and their values.",examples:["aic2 config list"]}}),F({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"]}}),F({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 a=r.split(".");let c=s,l=!0;for(const u of a)if(Gt(c,u))c=c[u];else{l=!1;break}l?console.log(r,c):console.log(`${r} not found`)}return}if(t==="set"){await We(n.map(s=>{const r=s.indexOf("=");if(r===-1)throw new p("Invalid format. Use: key=value");const a=s.slice(0,r),c=s.slice(r+1);return[a,c]}));return}if(t==="add"){await Ta(n.map(s=>{const r=s.indexOf("=");if(r===-1)throw new p("Invalid format. Use: key=value");const a=s.slice(0,r),c=s.slice(r+1);return[a,c]}));return}if(t==="list"){await Da();return}if(t==="del"){if(!o)throw new p("Please provide the config name to delete.");const s=await $e(),r=o.split(".");if(r.length===2){const[a,c]=r;if(s[a]&&typeof s[a]=="object"&&Gt(s[a],c)){delete s[a][c],Object.keys(s[a]).length===0&&delete s[a];const l=await pe();await I.writeFile(l,de.stringify(s),"utf8"),console.log(`Successfully deleted config: ${o}`);const u=await I.readFile(l,"utf8");console.log("--- Updated Config Content ---"),console.log(u),console.log("----------------------------")}else throw new p(`Config not found: ${o}`)}else if(r.length===1){const a=r[0];if(Gt(s,a)){delete s[a];const c=await pe();await I.writeFile(c,de.stringify(s),"utf8"),console.log(`Successfully deleted config: ${o}`);const l=await I.readFile(c,"utf8");console.log("--- Updated Config Content ---"),console.log(l),console.log("----------------------------")}else throw new p(`Config not found: ${o}`)}else throw new p(`Invalid config name format: ${o}`);return}if(t==="path"){await Na();return}throw new p(`Invalid mode: ${t}`)})().catch(t=>{new K().printError(t.message),q(t),process.exit(1)})});const Go="gpt-4.1",Ec=["gpt-4.1","gpt-4o","gpt-5-mini"],Bo={free:["claude-haiku-4.5","gpt-5-mini","gpt-4.1"],pro:["gpt-5.4","claude-sonnet-4.5","claude-opus-4.5","claude-sonnet-4","gpt-5.3-codex","gpt-5.2-codex","gpt-5.2","gpt-5.1","gpt-5.4-mini"]},vc=[...Bo.free,...Bo.pro],Ho={"openai/gpt-4.1":"gpt-4.1","openai/gpt-4o":"gpt-4o","openai/gpt-5-mini":"gpt-5-mini"},Uo=e=>{const t=(e||"").trim().toLowerCase();return t?t in Ho?Ho[t]:t.includes("/")&&t.split("/").pop()||t:Go},Pc=e=>[Uo(e),...Ec].filter((n,o,s)=>s.indexOf(n)===o),Ac=e=>{const t=e.toLowerCase();return t.includes("unknown_model")||t.includes("unknown model")||t.includes("unavailable_model")||t.includes("unavailable model")||t.includes("model not found")||t.includes("not available")||t.includes("not enabled")||t.includes("not allowed")},xc=e=>{const t=e.toLowerCase();return t.includes("authentication")||t.includes("unauthorized")||t.includes("forbidden")||t.includes("invalid token")||t.includes("token expired")||t.includes("no authentication")||t.includes("copilot cli not found")||t.includes("copilot cli authentication")},Sc=e=>{const t=e.toLowerCase();return t.includes("classic personal access tokens")&&t.includes("ghp_")},$c=(e=process.env)=>{const t={...e};t.NODE_NO_WARNINGS="1",delete t.GH_TOKEN,delete t.GITHUB_TOKEN;const n=(e.COPILOT_GITHUB_TOKEN||"").trim();return n.length>0?(t.COPILOT_GITHUB_TOKEN=n,{githubToken:n,useLoggedInUser:!1,env:t}):(delete t.COPILOT_GITHUB_TOKEN,{useLoggedInUser:!0,env:t})},nt="https://models.github.ai",nn="/inference/chat/completions",on="2026-03-10",sn="openai/gpt-4o-mini",Rc=/^([A-Za-z0-9][A-Za-z0-9._-]*)\/([A-Za-z0-9][A-Za-z0-9._:-]*)$/,Ko=e=>(e||"").trim(),Wo=e=>{const t=Ko(e);return t.length>0&&Rc.test(t)},Ic=e=>{const t=Ko(e);if(!Wo(t))throw new Error(`Invalid GitHub Models model ID "${t||"(empty)"}". Expected format: "publisher/model" (example: "openai/gpt-4o-mini").`);return t},kc=e=>{const t=(e||"").trim();return t?["ghp_","gho_","ghu_","ghs_","ghr_","github_pat_"].some(o=>t.startsWith(o)):!1};class ot{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=Ms.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 Lc={healthy:h.green("\u2705"),error:h.red("\u274C"),warning:h.yellow("\u26A0\uFE0F"),skipped:h.gray("\u23ED\uFE0F")},Oc={healthy:h.green,error:h.red,warning:h.yellow,skipped:h.gray},rn=e=>typeof e.key=="string"&&e.key.trim().length>0,qo=e=>(Array.isArray(e.model)?e.model:typeof e.model=="string"&&e.model.trim().length>0?[e.model.trim()]:[]).length>0,Mc=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)&&Object.keys(e).length>0,Tc=e=>typeof e=="string"&&e.trim()?e.replace(/\/$/,""):"https://openrouter.ai",Dc=e=>`${Tc(e.url)}/api/v1`,Nc=e=>({Authorization:`Bearer ${e}`,"Content-Type":"application/json","HTTP-Referer":"https://github.com/tak-bro/aicommit2","X-OpenRouter-Title":"aicommit2","X-OpenRouter-Categories":"cli-agent"}),_c=(e,t)=>{const n=e.trim();return t.find(o=>[o.id,o.canonical_slug,o.name].filter(r=>!!r).some(r=>r===n))},jc=(e,t)=>e.supported_parameters?.includes(t)??!1,Fc=[{configKey:"OPENROUTER.responseFormat",configProperty:"responseFormat",parameters:["response_format"]},{configKey:"OPENROUTER.reasoning",configProperty:"reasoning",parameters:["reasoning","include_reasoning"]}],Gc=e=>{const t=e.supported_parameters||[];return t.length>0?`supports: ${t.join(", ")}`:"no supported parameters listed"},Bc=(e,t)=>{const n=[];for(const o of Fc){if(!Mc(e[o.configProperty]))continue;o.parameters.some(r=>jc(t,r))||n.push(o.configKey)}return n},Hc=(e,t,n)=>{const o=n.context_length||n.top_provider?.context_length,s=Gc(n),r=Bc(t,n),a=o?`${o} ctx`:"";if(r.length>0){const u=[`consider removing ${r.join(", ")}`,a,s].filter(Boolean);return`${e}: ${u.join("; ")}`}const c=[a,s].filter(Boolean);return c.length>0?`${e} (${c.join("; ")})`:e},zo=(e,t)=>{const n=[],o=Array.isArray(e.model)?e.model:typeof e.model=="string"?[e.model]:[];for(const s of o){if(s==="openrouter/auto"){n.push("Auto routing enabled");continue}const r=_c(s,t);if(!r){n.push(`Model not found in catalog: ${s}`);continue}n.push(Hc(s,e,r))}return n},Uc=async(e,t)=>{try{return await new ot({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}}},Kc=async(e,t)=>{const n=typeof e.key=="string"?e.key.trim():"";if(!n)return{ok:!1,error:"No API key configured"};try{const o=Dc(e),s=Nc(n),r=["/models/user","/models"];let a,c;for(const y of r)try{a=await new ot({method:"GET",baseURL:`${o}${y}`,timeout:t}).setHeaders(s).execute();break}catch(m){if(c=m,!(m instanceof Error?m.message:String(m)).includes("404"))throw m}if(!a)throw c instanceof Error?c:new Error(String(c));const l=a.data?.data??[],u=qo(e)?Array.isArray(e.model)?e.model:[e.model]:[];if(u.length===0)return{ok:!0,details:`Catalog reachable (${l.length} models)`};if(u.includes("openrouter/auto")){const y=zo(e,l);return{ok:!0,details:y.length>0?y.join("; "):`Auto routing enabled (${l.length} models)`}}const f=zo(e,l);return f.some(y=>y.startsWith("Model not found in catalog:"))?{ok:!1,error:"Selected model not found in OpenRouter catalog",details:f.join("; ")}:{ok:!0,details:f.join("; ")}}catch(o){const s=o instanceof Error?o.message:String(o);return s.includes("401")||s.includes("403")?{ok:!1,error:"Unauthorized or forbidden when reading OpenRouter catalog"}:s.includes("404")?{ok:!1,error:"OpenRouter catalog endpoint not found"}:{ok:!1,error:s}}},Wc=e=>Array.isArray(e.model)&&e.model.length>0?String(e.model[0]).trim():typeof e.model=="string"&&e.model.trim().length>0?e.model.trim():sn,qc=async(e,t)=>{const n=typeof e.key=="string"?e.key.trim():"";if(!n)return{ok:!1,error:"No API key configured"};const o=Wc(e);if(!Wo(o))return{ok:!1,error:"Invalid model ID format",details:`Expected "publisher/model", got "${o||"(empty)"}"`};try{const s=`${nt}${nn}`;return await new ot({method:"POST",baseURL:s,timeout:t}).setHeaders({"Content-Type":"application/json",Accept:"application/vnd.github+json","X-GitHub-Api-Version":on,Authorization:`Bearer ${n}`}).setBody({model:o,messages:[{role:"user",content:"health-check"}],max_tokens:1,stream:!1}).execute(),{ok:!0,details:`Model: ${o}`}}catch(s){const r=s instanceof Error?s.message:String(s);return r.includes("401")?{ok:!1,error:"Authentication failed (401)"}:r.includes("403")?{ok:!1,error:"Access denied (403). Check token permission: models: read"}:r.includes("404")?{ok:!1,error:`Model not found (404): ${o}`}:r.includes("422")?{ok:!1,error:`Request validation failed (422) for model: ${o}`}:{ok:!1,error:r}}},zc=e=>{const t=Array.isArray(e.model)?String(e.model[0]||"").trim():String(e.model||"").trim();if(!t)return{ok:!1,error:"No model configured"};try{if((process.env.COPILOT_GITHUB_TOKEN||"").trim().startsWith("ghp_"))return{ok:!1,error:"Unsupported classic PAT in COPILOT_GITHUB_TOKEN",details:"Copilot CLI requires Fine-Grained PAT (github_pat_...) or Copilot login flow"};const o=process.versions.node,s=Number(o.split(".")[0]||"0");if(Number.isFinite(s)&&s<22)return{ok:!1,error:`Node.js ${o} is too old for Copilot SDK`,details:"Copilot SDK v0.2.0 requires node:sqlite support (Node.js 22+ recommended)"};const r=ye("copilot --version",{stdio:["ignore","pipe","pipe"]}).toString().trim(),a=Uo(t),l=vc.includes(a)?void 0:`Model '${t}' is not in the known working models list and may not work`;return{ok:!0,details:r?`CLI: ${r}; Model: ${t}; Node: ${o}`:`Model: ${t}; Node: ${o}`,modelWarning:l}}catch{return{ok:!1,error:"Copilot CLI not found",details:"Install and authenticate Copilot CLI before using COPILOT_SDK provider"}}},Yc=async(e,t,n)=>{if(e==="OLLAMA"){if(!Y(t))return{provider:e,status:"skipped",message:"No models configured"};const o=typeof t.host=="string"&&t.host.trim()?t.host:Pe,s=await Uc(o,n);return s.ok?{provider:e,status:"healthy",message:"Running",details:`Host: ${o}`}:{provider:e,status:"warning",message:s.error||"Connection failed",details:`Host: ${o}`}}if(e==="HUGGINGFACE")return t.cookie?{provider:e,status:"healthy",message:"Cookie configured"}:{provider:e,status:"skipped",message:"No cookie configured"};if(e==="BEDROCK")return ze(t)?{provider:e,status:"healthy",message:"Credentials configured"}:{provider:e,status:"skipped",message:"Not configured"};if(e==="OPENROUTER"){if(!rn(t))return{provider:e,status:"skipped",message:"Not configured"};const o=await Kc(t,n);return o.ok?{provider:e,status:"healthy",message:"Catalog reachable",details:o.details}:{provider:e,status:"warning",message:o.error||"Catalog check failed",details:o.details}}if(e==="GITHUB_MODELS"){if(!rn(t))return{provider:e,status:"skipped",message:"Not configured"};const o=await qc(t,n);return o.ok?{provider:e,status:"healthy",message:"Models API reachable",details:o.details}:{provider:e,status:"warning",message:o.error||"Connection check failed",details:o.details}}if(e==="COPILOT_SDK"){if(!qo(t))return{provider:e,status:"skipped",message:"No models configured"};const o=zc(t);return o.ok?o.modelWarning?{provider:e,status:"warning",message:o.modelWarning,details:o.details}:{provider:e,status:"healthy",message:"SDK environment ready",details:o.details}:{provider:e,status:"warning",message:o.error||"Environment check failed",details:o.details}}return rn(t)?{provider:e,status:"healthy",message:"API key configured"}:{provider:e,status:"skipped",message:"Not configured"}},Vc=async e=>{const t=[],n=e.timeout||1e4;for(const o of fe){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 Yc(o,s,n);t.push(r)}return t},Jc=Math.max(...fe.map(e=>e.length)),Xc=e=>e.padEnd(Jc),Qc=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=Lc[n.status],s=Xc(n.provider),r=Oc[n.status](n.message),a=n.details?h.gray(` (${n.details})`):"";console.log(` ${o} ${s} ${r}${a}`)}const t={healthy:e.filter(n=>n.status==="healthy").length,error:e.filter(n=>n.status==="error").length,warning:e.filter(n=>n.status==="warning").length,skipped:e.filter(n=>n.status==="skipped").length};console.log(""),console.log(h.bold("Summary: ")+h.green(`${t.healthy} healthy`)+", "+h.red(`${t.error} error`)+", "+h.yellow(`${t.warning} warning`)+", "+h.gray(`${t.skipped} skipped`)),console.log(""),t.error>0&&(process.exitCode=1)},Zc=F({name:"doctor",parameters:[],help:{description:"Check health status of configured AI providers",examples:["aicommit2 doctor"]}},()=>{(async()=>{const e=await J({},[]),t=await Vc(e);Qc(t)})().catch(e=>{console.error(h.red(e.message)),q(e),process.exit(1)})});var el=F({name:"github-login",parameters:[],flags:{token:{type:String,description:"Manually provide a GitHub token for authentication",alias:"t"}},help:{description:"Login to GitHub and setup access to GitHub Models",examples:["aic2 github-login","aic2 github-login --token github_pat_xxxxxxxxxxxxxxxxxxxx"]}},e=>{(async()=>{const t=new K;if(e.flags.token){try{await tl(e.flags.token,t)}catch(n){throw new p(`Token authentication failed: ${n.message}`)}return}try{await nl(t)}catch(n){throw new p(`Browser authentication failed: ${n.message}`)}})().catch(t=>{new K().printError(t.message),q(t),process.exit(1)})});async function tl(e,t){if(t.printWarning("Authenticating with provided token..."),!kc(e))throw new Error("Invalid token format. Expected GitHub token prefix like ghp_, gho_, ghu_, ghs_, ghr_, or github_pat_");try{const n=await fetch("https://api.github.com/user",{headers:{Authorization:`Bearer ${e}`,Accept:"application/vnd.github.v3+json","User-Agent":"aicommit2-github-models"}});if(!n.ok)throw new Error(`GitHub API request failed: ${n.status} ${n.statusText}`);const o=await n.json();try{(await fetch(`${nt}${nn}`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/vnd.github+json","X-GitHub-Api-Version":on,Authorization:`Bearer ${e}`,"User-Agent":"aicommit2-github-models"},body:JSON.stringify({messages:[{role:"user",content:"test"}],model:sn,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 We([["GITHUB_MODELS.key",e]]),t.printSuccess(`Successfully authenticated as ${o.login}`)}catch(n){throw new Error(`Token validation failed: ${n.message}`)}}async function nl(e){e.printInfo("Starting GitHub browser authentication for GitHub Models...");try{try{ye("gh --version",{stdio:"ignore"})}catch{throw new Error("GitHub CLI (gh) is not installed. Please install it first: https://cli.github.com/")}try{ye("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{ye("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=ye("gh auth token",{encoding:"utf8"}).trim();t&&(await We([["GITHUB_MODELS.key",t]]),e.printSuccess("GitHub token stored for GitHub Models access"))}catch{e.printWarning("Could not extract token from GitHub CLI, but authentication completed")}e.printSuccess("GitHub authentication completed and GitHub Models access verified!"),e.printInfo("See usage guide: https://github.com/tak-bro/aicommit2/blob/main/docs/providers/github-models.md"),e.printInfo("Use `gh models list` to view the latest available models."),e.printInfo(`Using GitHub Models API: ${nt}`)}catch(t){throw t}}const ge="prepare-commit-msg",ol=async()=>{const e=await Xe();if(e==="git")return`.git/hooks/${ge}`;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 aa}),{stdout:r}=await s("yadm",["introspect","repo"]),a=r.trim();if(a)return v.join(a,"hooks",ge)}catch{}const n=v.join(t,".config/yadm/hooks"),o=v.join(t,".yadm/hooks");try{return await I.access(n),v.join(n,ge)}catch{return v.join(o,ge)}}throw e==="jujutsu"?new p("Hooks are not supported for Jujutsu repositories."):new p(`Hooks are not supported for ${e} repositories.`)},st=Ts(new URL("cli.mjs",import.meta.url)),sl=process.argv[1].replace(/\\/g,"/").includes(`/hooks/${ge}`),Yo=process.platform==="win32",Vo=`
228
228
  #!/usr/bin/env node
229
- import(${JSON.stringify(Ms(st))})
230
- `.trim();var Jc=F({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 zt(),{installUninstall:n}=e._,o=await Yc(),s=v.isAbsolute(o)?o:v.join(t,o),r=await He(s);if(n==="install"){if(r){if(await I.realpath(s).catch(()=>{})===st){console.warn("The hook is already installed");return}throw new p(`A different ${ge} hook seems to be installed. Please remove it before installing aicommit2.`)}await I.mkdir(v.dirname(s),{recursive:!0}),Ko?await I.writeFile(s,Wo):(await I.symlink(st,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(Ko){if(await I.readFile(s,"utf8")!==Wo){console.warn("Hook is not installed");return}}else if(await I.realpath(s)!==st){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 Xc=vs(ls),Qc=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]},Zc=e=>e.toLocaleDateString()+" "+e.toLocaleTimeString(),el=async e=>{try{const t=await bn(U);if(t.length===0){console.log(`${h.yellow("No log files found.")}`);return}console.log(`${h.blue("Log files in")} ${U}:
231
- `);const n=await Promise.all(t.map(async o=>{const s=te.join(U,o),r=await Ts(s);return{name:o,size:Qc(r.size),modified:Zc(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(`
232
- ${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}},tl=async e=>{try{await bn(U);const t=process.platform;let n;switch(t){case"darwin":n=`open "${U}"`;break;case"win32":n=`start "" "${U}"`;break;default:n=`xdg-open "${U}"`;break}await Xc(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}`)}},nl=async e=>{try{await Os(U,{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 ol=F({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 K;switch(t){case"list":await el();break;case"path":console.log(`${h.blue("Logs directory:")} ${U}`);break;case"open":await tl(n);break;case"removeAll":await nl(n);break;default:throw new p(`Invalid action: ${t}. Use 'list', 'path', 'open', or 'removeAll'`)}})().catch(t=>{new K().printError(t.message),q(t),process.exit(1)})});const sl=process.argv.slice(2).filter(e=>!e.startsWith("--pre-commit")),[rt,qo]=sl;var rl=(e,t,n,o,s,r,a)=>(async()=>{if(!rt)throw new p('Commit message file path is missing. This file should be called from the "pre-commit framework"');if(qo){console.log(`Skipping aicommit2 message generation for ${qo} commit`);return}const c=await Yt();if(!c)return;const u=new K;u.printTitle();const l={...e&&{locale:e},...t!=null&&{generate:t.toString()},...o&&{type:o},...s&&{systemPrompt:s},...r===!0&&{includeBody:"true"}};a&&(l.logLevel="verbose");const d=await J(l,n);if(d.systemPromptPath)try{await I.readFile(v.resolve(d.systemPromptPath),"utf-8")}catch{throw new p(`Error reading system prompt file: ${d.systemPromptPath}`)}const f=pe(d,"commit");if(f.length===0)throw new p("Please set at least one API key via the `aicommit2 config set` command");const y=await Qe(),m=await Ze(),x=new et(d,c,y,m);let $;try{$=await ft(x.createCommitMsgRequests$(f).pipe(gn(D=>!D.isError),yn(D=>D.value),pt()))}finally{u.printAnalyzed()}const S=await I.readFile(rt,"utf8")!=="",P=$.length>1;let C="";S&&(C=`# \u{1F916} Generated by aicommit2 (https://github.com/tak-bro/aicommit2)
229
+ import(${JSON.stringify(Ds(st))})
230
+ `.trim();var rl=F({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 Yt(),{installUninstall:n}=e._,o=await ol(),s=v.isAbsolute(o)?o:v.join(t,o),r=await He(s);if(n==="install"){if(r){if(await I.realpath(s).catch(()=>{})===st){console.warn("The hook is already installed");return}throw new p(`A different ${ge} hook seems to be installed. Please remove it before installing aicommit2.`)}await I.mkdir(v.dirname(s),{recursive:!0}),Yo?await I.writeFile(s,Vo):(await I.symlink(st,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(Yo){if(await I.readFile(s,"utf8")!==Vo){console.warn("Hook is not installed");return}}else if(await I.realpath(s)!==st){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 il=xs(ms),al=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]},cl=e=>e.toLocaleDateString()+" "+e.toLocaleTimeString(),ll=async e=>{try{const t=await bn(U);if(t.length===0){console.log(`${h.yellow("No log files found.")}`);return}console.log(`${h.blue("Log files in")} ${U}:
231
+ `);const n=await Promise.all(t.map(async o=>{const s=oe.join(U,o),r=await Ns(s);return{name:o,size:al(r.size),modified:cl(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(`
232
+ ${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}},ul=async e=>{try{await bn(U);const t=process.platform;let n;switch(t){case"darwin":n=`open "${U}"`;break;case"win32":n=`start "" "${U}"`;break;default:n=`xdg-open "${U}"`;break}await il(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}`)}},dl=async e=>{try{await _s(U,{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 ml=F({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 K;switch(t){case"list":await ll();break;case"path":console.log(`${h.blue("Logs directory:")} ${U}`);break;case"open":await ul(n);break;case"removeAll":await dl(n);break;default:throw new p(`Invalid action: ${t}. Use 'list', 'path', 'open', or 'removeAll'`)}})().catch(t=>{new K().printError(t.message),q(t),process.exit(1)})});const fl=new Set(["--locale","-l","--generate","-g","--type","-t","--prompt","--exclude","-x","--output"]),Jo=(e,t=[])=>{const n=new Set(t),o=[];let s=!1;for(let r=0;r<e.length;r++){const a=e[r];if(s){s=!1;continue}if(!n.has(a)){if(a.startsWith("-")){fl.has(a)&&!a.includes("=")&&(s=!0);continue}o.push(a)}}return o},[rt,Xo]=Jo(process.argv.slice(2),["--pre-commit"]);var pl=(e,t,n,o,s,r,a)=>(async()=>{if(!rt)throw new p('Commit message file path is missing. This file should be called from the "pre-commit framework"');if(Xo){console.log(`Skipping aicommit2 message generation for ${Xo} commit`);return}const c={...e&&{locale:e},...t!=null&&{generate:t.toString()},...o&&{type:o},...s&&{systemPrompt:s},...r===!0&&{includeBody:"true"}};a&&(c.logLevel="verbose");const l=await J(c);if(await Jt(l),ne.verbose(`[pre-commit] type=${l.type}, systemPrompt=${l.systemPrompt?"set":"empty"}`),l.systemPromptPath)try{await I.readFile(v.resolve(l.systemPromptPath),"utf-8")}catch{throw new p(`Error reading system prompt file: ${l.systemPromptPath}`)}const u=await Vt(n,l.exclude);if(!u)return;const d=new K;d.printTitle();const f=he(l,"commit");if(f.length===0)throw new p("Please set at least one API key via the `aicommit2 config set` command");const y=await Qe(),m=await Ze(),x=new et(l,u,y,m);let S;try{S=await pt(x.createCommitMsgRequests$(f).pipe(gn(D=>!D.isError),yn(D=>D.value),ht()))}finally{d.printAnalyzed()}const $=await I.readFile(rt,"utf8")!=="",P=S.length>1;let C="";$&&(C=`# \u{1F916} Generated by aicommit2 (https://github.com/tak-bro/aicommit2)
233
233
  `,C+=`# ----------------------------------------
234
234
  `,C+=`# How to use:
235
235
  `,P?(C+=`# 1. Remove the "#" from your chosen message
@@ -239,16 +239,21 @@ ${h.green("Total:")} ${t.length} file${t.length!==1?"s":""}`)}catch(t){if(t.code
239
239
  `,C+=`# 2. Edit the message if needed
240
240
  `,C+=`# 3. Save and close the editor
241
241
  `),C+=`# ----------------------------------------
242
- `),P?(S&&(C+=`
242
+ `),P&&$?(C+=`
243
243
  # \u{1F4DD} Choose one of these messages:
244
- `),C+=`
245
- ${$.map(D=>`# ${D}`).join(`
246
- `)}`):(S&&(C+=`
244
+ `,C+=`
245
+ ${S.map(D=>D.split(`
246
+ `).map(X=>`# ${X}`).join(`
247
+ `)).join(`
248
+ #
249
+ `)}`):P?C+=`
250
+ ${S[0]}
251
+ `:($&&(C+=`
247
252
  # \u{1F4DD} Generated commit message:
248
253
  `),C+=`
249
- ${$[0]}
254
+ ${S[0]}
250
255
  `);const k=await I.readFile(rt,"utf8"),L=C+`
251
- `+k;await I.writeFile(rt,L),u.printSavedCommitMessage()})().catch(c=>{new K().printError(c.message),q(c),process.exit(1)});const sn=process.argv.slice(2),zo=[];let rn=!1;for(let e=0;e<sn.length;e++){const t=sn[e];if(rn){rn=!1;continue}if(t!=="--hook-mode"){if(t.startsWith("-")){const n=sn[e+1];n&&!n.startsWith("-")&&(rn=!0);continue}zo.push(t)}}const[it,Yo]=zo;var il=(e,t,n,o,s,r,a)=>(async()=>{if(!it)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(Yo){console.log(`Skipping aicommit2 message generation for ${Yo} commit`);return}const c=await Yt();if(!c)return;const u=new K;u.printTitle();const l={locale:e?.toString(),generate:t?.toString(),type:o?.toString(),systemPrompt:s?.toString(),...r===!0&&{includeBody:"true"}};a&&(l.logLevel="verbose");const d=await J(l,n);if(d.systemPromptPath)try{await I.readFile(v.resolve(d.systemPromptPath),"utf-8")}catch{throw new p(`Error reading system prompt file: ${d.systemPromptPath}`)}const f=pe(d,"commit");if(f.length===0)throw new p("Please set at least one API key via the `aicommit2 config set` command");const y=await Qe(),m=await Ze(),x=new et(d,c,y,m),$=u.displaySpinner("The AI is analyzing your changes");let A;try{A=await ft(x.createCommitMsgRequests$(f).pipe(gn(X=>!X.isError),yn(X=>X.value),pt()))}finally{$.stop(),$.clear(),u.printAnalyzed()}const P=await I.readFile(it,"utf8")!=="",C=A.length>1,k=await Ja();let L="";P&&(L=`${k} \u{1F916} Generated by aicommit2 (https://github.com/tak-bro/aicommit2)
256
+ `+k;await I.writeFile(rt,L),d.printSavedCommitMessage()})().catch(c=>{new K().printError(c.message),q(c),process.exit(1)});const[it,Qo]=Jo(process.argv.slice(2),["--hook-mode"]);var hl=(e,t,n,o,s,r,a)=>(async()=>{if(!it)throw new p('Commit message file path is missing. This file should be called from the "prepare-commit-msg" git hook or with --hook-mode flag');if(Qo){console.log(`Skipping aicommit2 message generation for ${Qo} commit`);return}const c={...e&&{locale:e},...t!=null&&{generate:t.toString()},...o&&{type:o},...s&&{systemPrompt:s},...r===!0&&{includeBody:"true"}};a&&(c.logLevel="verbose");const l=await J(c);if(await Jt(l),ne.verbose(`[hook-mode] type=${l.type}, systemPrompt=${l.systemPrompt?"set":"empty"}`),l.systemPromptPath)try{await I.readFile(v.resolve(l.systemPromptPath),"utf-8")}catch{throw new p(`Error reading system prompt file: ${l.systemPromptPath}`)}const u=await Vt(n,l.exclude);if(!u)return;const d=new K;d.printTitle();const f=he(l,"commit");if(f.length===0)throw new p("Please set at least one API key via the `aicommit2 config set` command");const y=await Qe(),m=await Ze(),x=new et(l,u,y,m),S=d.displaySpinner("The AI is analyzing your changes");let A;try{A=await pt(x.createCommitMsgRequests$(f).pipe(gn(Q=>!Q.isError),yn(Q=>Q.value),ht()))}finally{S.stop(),S.clear(),d.printAnalyzed()}const P=await I.readFile(it,"utf8")!=="",C=A.length>1,k=await Za();let L="";P&&(L=`${k} \u{1F916} Generated by aicommit2 (https://github.com/tak-bro/aicommit2)
252
257
  `,L+=`${k} ----------------------------------------
253
258
  `,L+=`${k} How to use:
254
259
  `,C?(L+=`${k} 1. Remove the "${k}" from your chosen message
@@ -258,22 +263,27 @@ ${$[0]}
258
263
  `,L+=`${k} 2. Edit the message if needed
259
264
  `,L+=`${k} 3. Save and close the editor
260
265
  `),L+=`${k} ----------------------------------------
261
- `),C?(P&&(L+=`
266
+ `),C&&P?(L+=`
262
267
  ${k} \u{1F4DD} Choose one of these messages:
263
- `),L+=`
264
- ${A.map(X=>`${k} ${X}`).join(`
265
- `)}`):(P&&(L+=`
268
+ `,L+=`
269
+ ${A.map(Q=>Q.split(`
270
+ `).map(ct=>`${k} ${ct}`).join(`
271
+ `)).join(`
272
+ ${k}
273
+ `)}`):C?L+=`
274
+ ${A[0]}
275
+ `:(P&&(L+=`
266
276
  ${k} \u{1F4DD} Generated commit message:
267
277
  `),L+=`
268
278
  ${A[0]}
269
- `);const D=await I.readFile(it,"utf8"),oe=L+`
270
- `+D;await I.writeFile(it,oe),u.printSavedCommitMessage()})().catch(c=>{new K().printError(c.message),q(c),process.exit(1)});const z=new K,an={OPENAI:{displayName:"OpenAI (ChatGPT)",authType:"api-key",envKeyHint:"OPENAI_API_KEY",defaultModel:"gpt-4o-mini"},COPILOT_SDK:{displayName:"GitHub Copilot SDK (Preview)",authType:"none",defaultModel:"gpt-4.1",setupNotes:"Uses local Copilot SDK auth flow (via Copilot CLI session), not GitHub Models API keys. Install/authenticate Copilot CLI first."},OPENROUTER:{displayName:"OpenRouter",authType:"api-key",envKeyHint:"OPENROUTER_API_KEY",defaultModel:"openrouter/auto",setupNotes:"OpenRouter supports many upstream models. You can keep openrouter/auto or choose a specific model slug."},ANTHROPIC:{displayName:"Anthropic (Claude)",authType:"api-key",envKeyHint:"ANTHROPIC_API_KEY",defaultModel:"claude-sonnet-4-20250514"},GEMINI:{displayName:"Google Gemini",authType:"api-key",envKeyHint:"GEMINI_API_KEY",defaultModel:"gemini-1.5-flash"},OLLAMA:{displayName:"Ollama (Local)",authType:"none",defaultModel:"llama3.2",setupNotes:"Ollama runs locally \u2014 no API key needed. Make sure Ollama is running."},GROQ:{displayName:"Groq",authType:"api-key",envKeyHint:"GROQ_API_KEY",defaultModel:"llama-3.3-70b-versatile"},DEEPSEEK:{displayName:"DeepSeek",authType:"api-key",envKeyHint:"DEEPSEEK_API_KEY",defaultModel:"deepseek-chat"},MISTRAL:{displayName:"Mistral AI",authType:"api-key",envKeyHint:"MISTRAL_API_KEY",defaultModel:"mistral-small-latest"},CODESTRAL:{displayName:"Codestral",authType:"api-key",envKeyHint:"CODESTRAL_API_KEY",defaultModel:"codestral-latest"},COHERE:{displayName:"Cohere",authType:"api-key",envKeyHint:"COHERE_API_KEY",defaultModel:"command-r-plus"},PERPLEXITY:{displayName:"Perplexity",authType:"api-key",envKeyHint:"PERPLEXITY_API_KEY",defaultModel:"sonar"},GITHUB_MODELS:{displayName:"GitHub Models",authType:"api-key",envKeyHint:"GITHUB_MODELS_API_KEY",defaultModel:"openai/gpt-4o-mini",setupNotes:"Use a GitHub personal access token (including github_pat_...). Run `aic2 github-login` for browser-based auth."},HUGGINGFACE:{displayName:"Hugging Face",authType:"cookie",defaultModel:"CohereForAI/c4ai-command-r-plus",setupNotes:"Requires a Hugging Face cookie for authentication."},BEDROCK:{displayName:"AWS Bedrock",authType:"complex",setupNotes:"Requires AWS credentials. Configure via AWS CLI or set region + access keys."}},Vo=["OPENAI","OPENROUTER","ANTHROPIC","GEMINI","OLLAMA","GROQ","DEEPSEEK"];var al=F({name:"setup",parameters:[],help:{description:"Interactive setup wizard for configuring AI providers",examples:["aic2 setup"]}},e=>{(async()=>{for(z.printTitle(),console.log(),z.printInfo(`Welcome to aicommit2 setup! Let's configure your AI providers.
271
- `);;){const t=await cl();if(!t)break;await ll(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()}z.printSuccess("Setup complete! Run `aic2` to generate commit messages.")})().catch(t=>{z.printError(t.message),q(t),process.exit(1)})});const cl=async()=>{const e=Vo.map(r=>({name:an[r].displayName,value:r})),n=me.filter(r=>!Vo.includes(r)).map(r=>({name:an[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=an[o]||{displayName:o,authType:"api-key"};return{key:o,info:s}},ll=async(e,t)=>{console.log(),t.setupNotes&&(z.printInfo(t.setupNotes),console.log());const n=[];switch(t.authType){case"api-key":{const{apiKey:r}=await T.prompt([{type:"password",name:"apiKey",message:`Enter your ${t.displayName} API key:`,mask:"*",validate:a=>a.trim()?!0:"API key is required"}]);n.push([`${e}.key`,r.trim()]);break}case"cookie":{const{cookie:r}=await T.prompt([{type:"password",name:"cookie",message:`Enter your ${t.displayName} cookie:`,mask:"*",validate:a=>a.trim()?!0:"Cookie is required"}]);n.push([`${e}.cookie`,r.trim()]);break}case"none":{if(e==="OLLAMA"){const{host:r}=await T.prompt([{type:"input",name:"host",message:"Ollama host URL:",default:Pe}]);r&&r!==Pe&&n.push([`${e}.host`,r.trim()])}break}case"complex":{z.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:a}=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(a==="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(a==="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=z.displaySpinner("Saving configuration...");try{await We(n),z.stopSpinner(s),z.printSuccess(`${t.displayName} configured successfully!`),t.envKeyHint&&console.log(` Tip: You can also set the ${t.envKeyHint} environment variable instead.`)}catch(r){z.stopSpinner(s),z.printError(`Failed to save configuration: ${r.message}`)}},Jo=20,Xo=e=>e<1e3?`${e}ms`:`${(e/1e3).toFixed(1)}s`,Qo=e=>new Date(e).toLocaleDateString(),ul=e=>{const t=Math.round(e/100*Jo),n=Jo-t;return(e>=80?h.green:e>=50?h.yellow:h.red)("\u2588".repeat(t))+h.gray("\u2591".repeat(n))},dl=e=>{const t=e.totalRequests>0?Math.round(e.successCount/e.totalRequests*100):0,n=ul(t),o=e.provider.padEnd(14),s=`${t}%`.padStart(4),r=`${e.totalRequests}`.padStart(4),a=`${e.selectedCount}`.padStart(4),c=e.selectionRate>0?`(${e.selectionRate}%)`.padStart(7):"".padStart(7),u=Xo(e.avgResponseTimeMs).padStart(6);console.log(` ${h.bold(o)} ${s} ${n} ${r} ${h.cyan(a)} ${h.gray(c)} ${u}`)},ml=async e=>{if(!await Wa()){console.log(h.yellow(`
279
+ `);const D=await I.readFile(it,"utf8"),X=L+`
280
+ `+D;await I.writeFile(it,X),d.printSavedCommitMessage()})().catch(c=>{new K().printError(c.message),q(c),process.exit(1)});const z=new K,an={OPENAI:{displayName:"OpenAI (ChatGPT)",authType:"api-key",envKeyHint:"OPENAI_API_KEY",defaultModel:"gpt-4o-mini"},COPILOT_SDK:{displayName:"GitHub Copilot SDK (Preview)",authType:"none",defaultModel:"gpt-4.1",setupNotes:"Uses local Copilot SDK auth flow (via Copilot CLI session), not GitHub Models API keys. Install/authenticate Copilot CLI first."},OPENROUTER:{displayName:"OpenRouter",authType:"api-key",envKeyHint:"OPENROUTER_API_KEY",defaultModel:"openrouter/auto",setupNotes:"OpenRouter supports many upstream models. You can keep openrouter/auto or choose a specific model slug."},ANTHROPIC:{displayName:"Anthropic (Claude)",authType:"api-key",envKeyHint:"ANTHROPIC_API_KEY",defaultModel:"claude-sonnet-4-20250514"},GEMINI:{displayName:"Google Gemini",authType:"api-key",envKeyHint:"GEMINI_API_KEY",defaultModel:"gemini-1.5-flash"},OLLAMA:{displayName:"Ollama (Local)",authType:"none",defaultModel:"llama3.2",setupNotes:"Ollama runs locally \u2014 no API key needed. Make sure Ollama is running."},GROQ:{displayName:"Groq",authType:"api-key",envKeyHint:"GROQ_API_KEY",defaultModel:"llama-3.3-70b-versatile"},DEEPSEEK:{displayName:"DeepSeek",authType:"api-key",envKeyHint:"DEEPSEEK_API_KEY",defaultModel:"deepseek-chat"},MISTRAL:{displayName:"Mistral AI",authType:"api-key",envKeyHint:"MISTRAL_API_KEY",defaultModel:"mistral-small-latest"},CODESTRAL:{displayName:"Codestral",authType:"api-key",envKeyHint:"CODESTRAL_API_KEY",defaultModel:"codestral-latest"},COHERE:{displayName:"Cohere",authType:"api-key",envKeyHint:"COHERE_API_KEY",defaultModel:"command-r-plus"},PERPLEXITY:{displayName:"Perplexity",authType:"api-key",envKeyHint:"PERPLEXITY_API_KEY",defaultModel:"sonar"},GITHUB_MODELS:{displayName:"GitHub Models",authType:"api-key",envKeyHint:"GITHUB_MODELS_API_KEY",defaultModel:"openai/gpt-4o-mini",setupNotes:"Use a GitHub personal access token (including github_pat_...). Run `aic2 github-login` for browser-based auth."},HUGGINGFACE:{displayName:"Hugging Face",authType:"cookie",defaultModel:"CohereForAI/c4ai-command-r-plus",setupNotes:"Requires a Hugging Face cookie for authentication."},BEDROCK:{displayName:"AWS Bedrock",authType:"complex",setupNotes:"Requires AWS credentials. Configure via AWS CLI or set region + access keys."}},Zo=["OPENAI","OPENROUTER","ANTHROPIC","GEMINI","OLLAMA","GROQ","DEEPSEEK"];var gl=F({name:"setup",parameters:[],help:{description:"Interactive setup wizard for configuring AI providers",examples:["aic2 setup"]}},e=>{(async()=>{for(z.printTitle(),console.log(),z.printInfo(`Welcome to aicommit2 setup! Let's configure your AI providers.
281
+ `);;){const t=await yl();if(!t)break;await wl(t.key,t.info);const{addMore:n}=await M.prompt([{type:"confirm",name:"addMore",message:"Would you like to configure another provider?",default:!1}]);if(!n)break;console.log()}z.printSuccess("Setup complete! Run `aic2` to generate commit messages.")})().catch(t=>{z.printError(t.message),q(t),process.exit(1)})});const yl=async()=>{const e=Zo.map(r=>({name:an[r].displayName,value:r})),n=fe.filter(r=>!Zo.includes(r)).map(r=>({name:an[r]?.displayName||r,value:r})),{provider:o}=await M.prompt([{type:"list",name:"provider",message:"Select an AI provider to configure:",choices:[new M.Separator("\u2500\u2500 Popular \u2500\u2500"),...e,new M.Separator("\u2500\u2500 Other \u2500\u2500"),...n,new M.Separator,{name:"Done (exit setup)",value:null}]}]);if(!o)return null;const s=an[o]||{displayName:o,authType:"api-key"};return{key:o,info:s}},wl=async(e,t)=>{console.log(),t.setupNotes&&(z.printInfo(t.setupNotes),console.log());const n=[];switch(t.authType){case"api-key":{const{apiKey:r}=await M.prompt([{type:"password",name:"apiKey",message:`Enter your ${t.displayName} API key:`,mask:"*",validate:a=>a.trim()?!0:"API key is required"}]);n.push([`${e}.key`,r.trim()]);break}case"cookie":{const{cookie:r}=await M.prompt([{type:"password",name:"cookie",message:`Enter your ${t.displayName} cookie:`,mask:"*",validate:a=>a.trim()?!0:"Cookie is required"}]);n.push([`${e}.cookie`,r.trim()]);break}case"none":{if(e==="OLLAMA"){const{host:r}=await M.prompt([{type:"input",name:"host",message:"Ollama host URL:",default:Pe}]);r&&r!==Pe&&n.push([`${e}.host`,r.trim()])}break}case"complex":{z.printInfo("AWS Bedrock requires region and credentials."),console.log();const{region:r}=await M.prompt([{type:"input",name:"region",message:"AWS Region (e.g., us-east-1):",validate:c=>c.trim()?!0:"Region is required"}]);n.push([`${e}.region`,r.trim()]);const{authMethod:a}=await M.prompt([{type:"list",name:"authMethod",message:"Authentication method:",choices:[{name:"AWS Profile (from ~/.aws/credentials)",value:"profile"},{name:"Access Key + Secret Key",value:"keys"},{name:"Environment variables (already set)",value:"env"}]}]);if(a==="profile"){const{profile:c}=await M.prompt([{type:"input",name:"profile",message:"AWS Profile name:",default:"default"}]);n.push([`${e}.profile`,c.trim()])}else if(a==="keys"){const{accessKeyId:c,secretAccessKey:l}=await M.prompt([{type:"password",name:"accessKeyId",message:"AWS Access Key ID:",mask:"*"},{type:"password",name:"secretAccessKey",message:"AWS Secret Access Key:",mask:"*"}]);n.push([`${e}.accessKeyId`,c.trim()]),n.push([`${e}.secretAccessKey`,l.trim()])}break}}const{model:o}=await M.prompt([{type:"input",name:"model",message:"Model to use (comma-separated for multiple):",default:t.defaultModel||"",validate:r=>r.trim()?!0:"At least one model is required"}]);n.push([`${e}.model`,o.trim()]);const s=z.displaySpinner("Saving configuration...");try{await We(n),z.stopSpinner(s),z.printSuccess(`${t.displayName} configured successfully!`),t.envKeyHint&&console.log(` Tip: You can also set the ${t.envKeyHint} environment variable instead.`)}catch(r){z.stopSpinner(s),z.printError(`Failed to save configuration: ${r.message}`)}},es=20,ts=e=>e<1e3?`${e}ms`:`${(e/1e3).toFixed(1)}s`,ns=e=>new Date(e).toLocaleDateString(),Cl=e=>{const t=Math.round(e/100*es),n=es-t;return(e>=80?h.green:e>=50?h.yellow:h.red)("\u2588".repeat(t))+h.gray("\u2591".repeat(n))},bl=e=>{const t=e.totalRequests>0?Math.round(e.successCount/e.totalRequests*100):0,n=Cl(t),o=e.provider.padEnd(14),s=`${t}%`.padStart(4),r=`${e.totalRequests}`.padStart(4),a=`${e.selectedCount}`.padStart(4),c=e.selectionRate>0?`(${e.selectionRate}%)`.padStart(7):"".padStart(7),l=ts(e.avgResponseTimeMs).padStart(6);console.log(` ${h.bold(o)} ${s} ${n} ${r} ${h.cyan(a)} ${h.gray(c)} ${l}`)},El=async e=>{if(!await Ya()){console.log(h.yellow(`
272
282
  No statistics recorded yet.`)),console.log(h.gray(`Statistics will be collected as you generate commit messages.
273
- `));return}const n=await Ua(e);if(n.totalRequests===0){console.log(h.yellow(`
283
+ `));return}const n=await qa(e);if(n.totalRequests===0){console.log(h.yellow(`
274
284
  No statistics in the last ${e} days.
275
- `));return}if(console.log(""),console.log(h.bold("\u{1F4CA} aicommit2 Statistics")),console.log(h.gray(` Period: ${Qo(n.periodStart)} - ${Qo(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(Xo(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)dl(o);console.log("")}},fl=async()=>{await Ka(),console.log(h.green(`
285
+ `));return}if(console.log(""),console.log(h.bold("\u{1F4CA} aicommit2 Statistics")),console.log(h.gray(` Period: ${ns(n.periodStart)} - ${ns(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(ts(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)bl(o);console.log("")}},vl=async()=>{await za(),console.log(h.green(`
276
286
  Statistics cleared successfully.
277
- `))},pl=F({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 fl();break;default:await ml(n);break}})().catch(t=>{console.error(h.red(t.message)),q(t),process.exit(1)})});class Zo{constructor(t="SubscriptionManager"){this.destroyed$=new Ss,this.subscriptions=new mt,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 mt;return s.unsubscribe(),s}const o=t.pipe(En(this.destroyed$),vn(()=>{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(En(this.destroyed$),vn(()=>{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 hl=new Zo("Global"),Ie=()=>{hl.destroy()};process.on("exit",Ie),process.on("SIGINT",Ie),process.on("SIGTERM",Ie),process.on("uncaughtException",e=>{console.error("Uncaught exception:",e),Ie(),process.exit(1)}),process.on("unhandledRejection",(e,t)=>{console.error("Unhandled rejection at:",t,"reason:",e),Ie(),process.exit(1)});const gl=bs(ds),es=5,yl=3e3,wl=500,Cl=100,bl=1e3,El=200;class vl{constructor(){this.consoleManager=new K,this.subscriptionManager=new Zo,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=v.join(this.REPO_PATH,".git"),this.HEAD_PATH=v.join(this.GIT_PATH,"HEAD"),this.REFS_PATH=v.join(this.GIT_PATH,"refs","heads"),this.COMMIT_MSG_PATH=v.join(this.GIT_PATH,"COMMIT_EDITMSG"),this.setupProcessHandlers=()=>{const t=()=>{this.destroy(),process.exit(0)};process.on("SIGINT",t),process.on("SIGTERM",t),process.on("SIGQUIT",t)},this.watch=async(t,n,o,s,r,a)=>{this.consoleManager.printTitle(),await zt();const c=await Xe();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,a);this.configExclude=u.exclude||[],await this.initializeCurrentCommit(),await this.startWatchLoop(u)},this.startWatchLoop=async t=>{try{await this.watchGitEvents(t)}catch(n){this.retryCount<es||(this.consoleManager.printError("Watch mode failed after maximum retries. Exiting."),this.destroy(),process.exit(1)),this.retryCount++;const s=yl*Math.pow(2,this.retryCount-1);return await this.handleWatchGitError(n,s),this.startWatchLoop(t)}},this.initializeConfig=async(t,n,o,s,r)=>{const a={locale:t?.toString(),generate:n?.toString(),systemPrompt:o?.toString()};s&&(a.logLevel="verbose");const c=await J(a,r);return await jo(c),pe(c,"watch").length===0&&(this.consoleManager.printError(`Please set at least one API key and watchMode via the config command:
287
+ `))},Pl=F({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 vl();break;default:await El(n);break}})().catch(t=>{console.error(h.red(t.message)),q(t),process.exit(1)})});class os{constructor(t="SubscriptionManager"){this.destroyed$=new ks,this.subscriptions=new ft,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 ft;return s.unsubscribe(),s}const o=t.pipe(En(this.destroyed$),vn(()=>{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(En(this.destroyed$),vn(()=>{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 Al=new os("Global"),Ie=()=>{Al.destroy()};process.on("exit",Ie),process.on("SIGINT",Ie),process.on("SIGTERM",Ie),process.on("uncaughtException",e=>{console.error("Uncaught exception:",e),Ie(),process.exit(1)}),process.on("unhandledRejection",(e,t)=>{console.error("Unhandled rejection at:",t,"reason:",e),Ie(),process.exit(1)});const xl=Ps(ps),ss=5,Sl=3e3,$l=500,Rl=100,Il=1e3,kl=200;class Ll{constructor(){this.consoleManager=new K,this.subscriptionManager=new os,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=v.join(this.REPO_PATH,".git"),this.HEAD_PATH=v.join(this.GIT_PATH,"HEAD"),this.REFS_PATH=v.join(this.GIT_PATH,"refs","heads"),this.COMMIT_MSG_PATH=v.join(this.GIT_PATH,"COMMIT_EDITMSG"),this.setupProcessHandlers=()=>{const t=()=>{this.destroy(),process.exit(0)};process.on("SIGINT",t),process.on("SIGTERM",t),process.on("SIGQUIT",t)},this.watch=async(t,n,o,s,r,a)=>{this.consoleManager.printTitle(),await Yt();const c=await Xe();if(c!=="git")throw new p(`Watch mode is only supported for Git repositories. Current VCS: ${c}`);this.excludeFiles=o;const l=await this.initializeConfig(t,n,s,r,a);this.configExclude=l.exclude||[],await this.initializeCurrentCommit(),await this.startWatchLoop(l)},this.startWatchLoop=async t=>{try{await this.watchGitEvents(t)}catch(n){this.retryCount<ss||(this.consoleManager.printError("Watch mode failed after maximum retries. Exiting."),this.destroy(),process.exit(1)),this.retryCount++;const s=Sl*Math.pow(2,this.retryCount-1);return await this.handleWatchGitError(n,s),this.startWatchLoop(t)}},this.initializeConfig=async(t,n,o,s,r)=>{const a={locale:t?.toString(),generate:n?.toString(),systemPrompt:o?.toString()};s&&(a.logLevel="verbose");const c=await J(a,r);return await jo(c),he(c,"watch").length===0&&(this.consoleManager.printError(`Please set at least one API key and watchMode via the config command:
278
288
  aicommit2 config set [MODEL].key="YOUR_API_KEY"
279
- 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}/${es})`)},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 gl(t,{cwd:this.REPO_PATH});return n},this.clearTerminal=()=>{process.stdout.write("\x1Bc")},this.handleCommitEvent=async(t,n)=>{try{const o=await Va(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=pe(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 Qe(),r=await Ze(),a=new et(t,n,s,r),c=[];let u=!1;this.currentCodeReviewSubscription=this.subscriptionManager.add(a.createCodeReviewRequests$(o),{next:l=>{c.push(l),this.currentCodeReviewPromptManager?.refreshChoices(l)},error:l=>{he.error(`Code review request error: ${l}`),u=!0,this.currentCodeReviewPromptManager?.checkErrorOnChoices(!1)},complete:()=>{u=!0,this.currentCodeReviewPromptManager?.checkErrorOnChoices(!1)}});try{let l=!0;for(;l;){this.currentCodeReviewPromptManager=new Xt(To);const d=this.initializeCodeReviewInquirer();this.currentCodeReviewPromptManager.startLoader();for(const m of c)this.currentCodeReviewPromptManager.refreshChoices(m);u&&this.currentCodeReviewPromptManager.checkErrorOnChoices(!1);const g=!!(await d)?.codeReviewPrompt?.value,y=!this.currentCodeReviewPromptManager;g||u||y?l=!1:(this.currentCodeReviewPromptManager.destroy(),this.currentCodeReviewPromptManager=null)}}finally{this.cleanupCodeReview()}},this.cleanupPreviousCodeReview=()=>{this.cleanupCurrentReviewResources()},this.initializeCodeReviewInquirer=()=>this.currentCodeReviewPromptManager.initPrompt({...Jt,name:"codeReviewPrompt",message:"Please check code reviews: ",emptyMessage:`\u26A0 ${Oo}`,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,v.join(this.GIT_PATH,"logs","HEAD")].filter(s=>{try{return j.accessSync(s),!0}catch{return!1}});this.watcher=Ds.watch(o,{persistent:!0,ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:wl,pollInterval:Cl}}),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=>{he.error(`Failed to restart watcher: ${r}`)})},bl)})},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,El))}catch(r){he.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){he.warn(`Error during WatchGitManager destruction: ${t}`)}},this.setupProcessHandlers()}}const Pl=new vl,Al=async(e,t,n,o,s,r)=>Pl.watch(e,t,n,o,s,r),ts={"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"]},xl=e=>{if(!e||typeof e!="object")return!1;const t=e;return t.data?.name!==void 0&&typeof t.data.name=="string"},$l=e=>xl(e)?e.data.name:null,Sl=e=>{for(const[t,n]of Object.entries(ts))if(n.includes(e))return t;return null},Rl=e=>e.type==="section"&&e.data?.title==="Flags:",Il=e=>e.data?.body?.data?.tableData!==void 0,kl=e=>{const t=new Map;for(const n of Object.keys(ts))t.set(n,[]);if(t.set("Other",[]),!Array.isArray(e))return t;for(const n of e){if(!Array.isArray(n))continue;const o=$l(n[0]),s=o&&Sl(o)||"Other";t.get(s)?.push(n)}return t},Ll=(e,t,n,o,s)=>({type:"section",data:{title:s?`Flags - ${e}:`:` ${e}:`,body:{type:"table",data:{tableData:t,tableOptions:n,tableBreakpoints:o}}}}),Ml=(e,t)=>{const n=[];for(const o of e){if(!Rl(o)||!Il(o)){n.push(o);continue}const{tableData:s,tableOptions:r,tableBreakpoints:a}=o.data.body.data;[...kl(s).entries()].filter(([,l])=>l.length>0).forEach(([l,d],f)=>{n.push(Ll(l,d,r,a,f===0))})}return t.render(n)};process.env.NODE_NO_WARNINGS||(process.env.NODE_NO_WARNINGS="1");const at=process.argv.slice(2),{version:ns,description:Tl}=Xs;is({name:"aicommit2",version:ns,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:[wc,Kc,Wc,Jc,ol,al,pl],help:{description:Tl,render:Ml},ignoreArgv:e=>e==="unknown-flag"||e==="argument"},async e=>{const t={};e.flags.verbose&&(t.logLevel="verbose");const n=await J(t,at);if(await ec(n),he.info(`aicommit2 version: ${ns}`),e.flags["pre-commit"]){rl(e.flags.locale,e.flags.generate,e.flags.exclude,e.flags.type,e.flags.prompt,e.flags["include-body"],e.flags.verbose);return}if(e.flags["hook-mode"]||Vc){il(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"]){Al(e.flags.locale,e.flags.generate,e.flags.exclude,e.flags.prompt,e.flags.verbose,at);return}fc(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,at)},at);export{U as A,Do as D,R as E,nt as G,ot as H,p as K,W as P,ba as a,uc as b,pa as c,mc as d,oc as e,sc as f,lc as g,nc as h,ga as i,V as j,se as k,he as l,jt as m,ha as n,Pe as o,Mo as p,nn as q,bc as r,Ea as s,en as t,tn as u};
289
+ 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}/${ss})`)},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 xl(t,{cwd:this.REPO_PATH});return n},this.clearTerminal=()=>{process.stdout.write("\x1Bc")},this.handleCommitEvent=async(t,n)=>{try{const o=await Qa(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=he(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 Qe(),r=await Ze(),a=new et(t,n,s,r),c=[];let l=!1;this.currentCodeReviewSubscription=this.subscriptionManager.add(a.createCodeReviewRequests$(o),{next:u=>{c.push(u),this.currentCodeReviewPromptManager?.refreshChoices(u)},error:u=>{ne.error(`Code review request error: ${u}`),l=!0,this.currentCodeReviewPromptManager?.checkErrorOnChoices(!1)},complete:()=>{l=!0,this.currentCodeReviewPromptManager?.checkErrorOnChoices(!1)}});try{let u=!0;for(;u;){this.currentCodeReviewPromptManager=new Zt(Mo);const d=this.initializeCodeReviewInquirer();this.currentCodeReviewPromptManager.startLoader();for(const m of c)this.currentCodeReviewPromptManager.refreshChoices(m);l&&this.currentCodeReviewPromptManager.checkErrorOnChoices(!1);const g=!!(await d)?.codeReviewPrompt?.value,y=!this.currentCodeReviewPromptManager;g||l||y?u=!1:(this.currentCodeReviewPromptManager.destroy(),this.currentCodeReviewPromptManager=null)}}finally{this.cleanupCodeReview()}},this.cleanupPreviousCodeReview=()=>{this.cleanupCurrentReviewResources()},this.initializeCodeReviewInquirer=()=>this.currentCodeReviewPromptManager.initPrompt({...Qt,name:"codeReviewPrompt",message:"Please check code reviews: ",emptyMessage:`\u26A0 ${To}`,isDescriptionDim:!1,stopMessage:"Code review completed",descPageSize:20}),this.cleanupCurrentReviewResources=()=>{this.currentCodeReviewSubscription&&(this.currentCodeReviewSubscription.unsubscribe(),this.currentCodeReviewSubscription=null),this.currentCodeReviewPromptManager&&(this.currentCodeReviewPromptManager.destroy(),this.currentCodeReviewPromptManager=null)},this.cleanupCodeReview=()=>{this.cleanupCurrentReviewResources()},this.isGitReset=async t=>{if(!this.lastCommitHash)return!1;try{return await this.executeGitCommand(`git merge-base --is-ancestor ${t} ${this.lastCommitHash}`),!0}catch{return!1}},this.cancelCurrentReview=()=>{this.currentCodeReviewPromptManager&&this.currentCodeReviewPromptManager.cancel(),this.cleanupCurrentReviewResources()},this.closeWatcher=async()=>{this.watcher&&(await this.watcher.close(),this.watcher=null)},this.watchGitEvents=async t=>{this.consoleManager.showLoader("Watching for new Git commits...");const o=[this.HEAD_PATH,this.REFS_PATH,this.COMMIT_MSG_PATH,v.join(this.GIT_PATH,"logs","HEAD")].filter(s=>{try{return j.accessSync(s),!0}catch{return!1}});this.watcher=js.watch(o,{persistent:!0,ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:$l,pollInterval:Rl}}),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=>{ne.error(`Failed to restart watcher: ${r}`)})},Il)})},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,kl))}catch(r){ne.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){ne.warn(`Error during WatchGitManager destruction: ${t}`)}},this.setupProcessHandlers()}}const Ol=new Ll,Ml=async(e,t,n,o,s,r)=>Ol.watch(e,t,n,o,s,r),rs={"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"]},Tl=e=>{if(!e||typeof e!="object")return!1;const t=e;return t.data?.name!==void 0&&typeof t.data.name=="string"},Dl=e=>Tl(e)?e.data.name:null,Nl=e=>{for(const[t,n]of Object.entries(rs))if(n.includes(e))return t;return null},_l=e=>e.type==="section"&&e.data?.title==="Flags:",jl=e=>e.data?.body?.data?.tableData!==void 0,Fl=e=>{const t=new Map;for(const n of Object.keys(rs))t.set(n,[]);if(t.set("Other",[]),!Array.isArray(e))return t;for(const n of e){if(!Array.isArray(n))continue;const o=Dl(n[0]),s=o&&Nl(o)||"Other";t.get(s)?.push(n)}return t},Gl=(e,t,n,o,s)=>({type:"section",data:{title:s?`Flags - ${e}:`:` ${e}:`,body:{type:"table",data:{tableData:t,tableOptions:n,tableBreakpoints:o}}}}),Bl=(e,t)=>{const n=[];for(const o of e){if(!_l(o)||!jl(o)){n.push(o);continue}const{tableData:s,tableOptions:r,tableBreakpoints:a}=o.data.body.data;[...Fl(s).entries()].filter(([,u])=>u.length>0).forEach(([u,d],f)=>{n.push(Gl(u,d,r,a,f===0))})}return t.render(n)};process.env.NODE_NO_WARNINGS||(process.env.NODE_NO_WARNINGS="1");const at=process.argv.slice(2),{version:is,description:Hl}=er;ls({name:"aicommit2",version:is,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:[bc,Zc,el,rl,ml,gl,Pl],help:{description:Hl,render:Bl},ignoreArgv:e=>e==="unknown-flag"||e==="argument"},async e=>{const t={};e.flags.verbose&&(t.logLevel="verbose");const n=await J(t,at);if(await Jt(n),ne.info(`aicommit2 version: ${is}`),e.flags["pre-commit"]){pl(e.flags.locale,e.flags.generate,e.flags.exclude,e.flags.type,e.flags.prompt,e.flags["include-body"],e.flags.verbose);return}if(e.flags["hook-mode"]||sl){hl(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"]){Ml(e.flags.locale,e.flags.generate,e.flags.exclude,e.flags.prompt,e.flags.verbose,at);return}hc(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,at)},at);export{U as A,Go as C,Do as D,R as E,nt as G,ot as H,p as K,W as P,Pa as a,mc as b,ya as c,pc as d,rc as e,ic as f,dc as g,sc as h,Ca as i,V as j,re as k,ne as l,Ft as m,Sc as n,xc as o,Ac as p,Pc as q,$c as r,Aa as s,wa as t,Pe as u,Oo as v,sn as w,Ic as x,nn as y,on as z};