aicommit2 2.5.19 → 2.5.21

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