aicommit2 2.5.20 → 2.5.22
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.
- package/README.md +15 -0
- package/dist/{ai.service-8d25ed3e.mjs → ai.service-044bec79.mjs} +1 -1
- package/dist/{anthropic.service-0ad84ebb.mjs → anthropic.service-7e4eba3c.mjs} +1 -1
- package/dist/{bedrock.service-1d020e7f.mjs → bedrock.service-80ff2a63.mjs} +1 -1
- package/dist/cli-4ddef46c.mjs +325 -0
- package/dist/cli.mjs +1 -1
- package/dist/{codestral.service-352a099e.mjs → codestral.service-87036f48.mjs} +1 -1
- package/dist/{cohere.service-8e9a4ad8.mjs → cohere.service-1e4bab5c.mjs} +1 -1
- package/dist/{copilot-sdk.service-0ababf56.mjs → copilot-sdk.service-535a79bd.mjs} +1 -1
- package/dist/{deep-seek.service-75f2e8ac.mjs → deep-seek.service-c1232229.mjs} +1 -1
- package/dist/{gemini.service-6c27af0c.mjs → gemini.service-9918cef9.mjs} +1 -1
- package/dist/{github-models.service-1be4a71f.mjs → github-models.service-3ebf9c9c.mjs} +1 -1
- package/dist/{groq.service-6c6102d5.mjs → groq.service-02d64a85.mjs} +1 -1
- package/dist/{hugging-face.service-635e4e0a.mjs → hugging-face.service-ad52b657.mjs} +1 -1
- package/dist/{mistral.service-6eb6850b.mjs → mistral.service-13a13916.mjs} +1 -1
- package/dist/{ollama.service-27062e4b.mjs → ollama.service-874cae8a.mjs} +1 -1
- package/dist/{openai-61113ff1.mjs → openai-6970d017.mjs} +1 -1
- package/dist/{openai-compatible.service-2ea18661.mjs → openai-compatible.service-62ff73b7.mjs} +1 -1
- package/dist/{openai.service-48cd1ccd.mjs → openai.service-ccf2849b.mjs} +1 -1
- package/dist/{openrouter.service-53027f44.mjs → openrouter.service-530df5cf.mjs} +1 -1
- package/dist/{perplexity.service-7c63b8ba.mjs → perplexity.service-520a5b3c.mjs} +1 -1
- package/package.json +1 -1
- package/dist/cli-6e22e614.mjs +0 -289
|
@@ -0,0 +1,325 @@
|
|
|
1
|
+
import{command as F,cli as gs}from"cleye";import{createRequire as ys}from"module";import yt from"crypto";import O from"fs";import ue from"os";import A from"path";import{Buffer as fn}from"node:buffer";import ae from"node:path";import wt,{ChildProcess as pn,exec as ws}from"node:child_process";import U from"node:process";import Cs,{execSync as Ae,exec as bs}from"child_process";import{fileURLToPath as hn}from"node:url";import Es,{constants as gn}from"node:os";import vs from"assert";import As from"events";import{createWriteStream as Ps,createReadStream as Ss,readFileSync as xs}from"node:fs";import $s from"buffer";import Ct from"stream";import Rs,{promisify as Is}from"util";import{debuglog as ks,promisify as Ls}from"node:util";import T from"inquirer";import{from as Be,switchMap as yn,of as Ms,tap as Os,mergeMap as wn,catchError as Ts,BehaviorSubject as Cn,ReplaySubject as Ds,Subscription as bt,lastValueFrom as Et,toArray as vt,filter as bn,map as En,Subject as Ns}from"rxjs";import I from"fs/promises";import h from"chalk";import He from"readline";import vn from"figlet";import _s from"gradient-string";import An from"ora";import js from"inquirer-reactive-list-prompt";import K from"winston";import"winston-daily-rotate-file";import Fs from"axios";import{fileURLToPath as Gs,pathToFileURL as Bs}from"url";import{readdir as Pn,stat as Hs,rm as Us}from"node:fs/promises";import Ks from"chokidar";import{takeUntil as Sn,finalize as xn}from"rxjs/operators";var Ws="aicommit2",$n="2.5.22",qs="A Reactive CLI that generates commit messages for Git and Jujutsu with various AI",zs=["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"],Ys="MIT",Vs="tak-bro/aicommit2",Js="Hyungtak Jin(@tak-bro)",Xs="module",Qs=["dist"],Zs={aicommit2:"./dist/cli.mjs",aic2:"./dist/cli.mjs"},er={prepare:"simple-git-hooks",build:"pkgroll --minify",lint:"eslint --cache .","type-check":"tsc",test:"tsx tests",prepack:"pnpm build && clean-pkg-json",prettier:"prettier"},tr={"@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"},nr={"@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"},sr={extends:["@pvtnbr","prettier"],rules:{"unicorn/no-process-exit":"off"},overrides:[{files:"./src/commands/prepare-commit-msg-hook.ts",rules:{"unicorn/prevent-abbreviations":"off"}}]},rr={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"]},ir={name:Ws,version:$n,description:qs,keywords:zs,license:Ys,repository:Vs,author:Js,type:Xs,files:Qs,bin:Zs,scripts:er,"simple-git-hooks":{"pre-commit":"pnpm lint-staged"},"lint-staged":{"*.ts":["prettier --config ./.prettierrc --write","eslint --fix"]},dependencies:tr,optionalDependencies:nr,devDependencies:or,eslintConfig:sr,release:rr},At=ys(import.meta.url),oe=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,Rn;function ar(){if(Rn)return Pt;Rn=1,Pt=o,o.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 n(r,a,c){return!r.isSymbolicLink()&&!r.isFile()?!1:t(a,c)}function o(r,a,c){e.stat(r,function(l,u){c(l,l?!1:n(u,r,a))})}function s(r,a){return n(e.statSync(r),r,a)}return Pt}var St,In;function cr(){if(In)return St;In=1,St=t,t.sync=n;var e=O;function t(r,a,c){e.stat(r,function(l,u){c(l,l?!1:o(u,a))})}function n(r,a){return o(e.statSync(r),a)}function o(r,a){return r.isFile()&&s(r,a)}function s(r,a){var c=r.mode,l=r.uid,u=r.gid,d=a.uid!==void 0?a.uid:process.getuid&&process.getuid(),p=a.gid!==void 0?a.gid:process.getgid&&process.getgid(),g=parseInt("100",8),y=parseInt("010",8),f=parseInt("001",8),x=g|y,$=c&f||c&y&&u===p||c&g&&l===d||c&x&&d===0;return $}return St}var Ue;process.platform==="win32"||oe.TESTING_WINDOWS?Ue=ar():Ue=cr();var lr=xt;xt.sync=ur;function xt(e,t,n){if(typeof t=="function"&&(n=t,t={}),!n){if(typeof Promise!="function")throw new TypeError("callback not provided");return new Promise(function(o,s){xt(e,t||{},function(r,a){r?s(r):o(a)})})}Ue(e,t||{},function(o,s){o&&(o.code==="EACCES"||t&&t.ignoreErrors)&&(o=null,s=!1),n(o,s)})}function ur(e,t){try{return Ue.sync(e,t||{})}catch(n){if(t&&t.ignoreErrors||n.code==="EACCES")return!1;throw n}}const fe=process.platform==="win32"||process.env.OSTYPE==="cygwin"||process.env.OSTYPE==="msys",kn=A,dr=fe?";":":",Ln=lr,Mn=e=>Object.assign(new Error(`not found: ${e}`),{code:"ENOENT"}),On=(e,t)=>{const n=t.colon||dr,o=e.match(/\//)||fe&&e.match(/\\/)?[""]:[...fe?[process.cwd()]:[],...(t.path||process.env.PATH||"").split(n)],s=fe?t.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",r=fe?s.split(n):[""];return fe&&e.indexOf(".")!==-1&&r[0]!==""&&r.unshift(""),{pathEnv:o,pathExt:r,pathExtExe:s}},Tn=(e,t,n)=>{typeof t=="function"&&(n=t,t={}),t||(t={});const{pathEnv:o,pathExt:s,pathExtExe:r}=On(e,t),a=[],c=u=>new Promise((d,p)=>{if(u===o.length)return t.all&&a.length?d(a):p(Mn(e));const g=o[u],y=/^".*"$/.test(g)?g.slice(1,-1):g,f=kn.join(y,e),x=!y&&/^\.[\\\/]/.test(e)?e.slice(0,2)+f:f;d(l(x,u,0))}),l=(u,d,p)=>new Promise((g,y)=>{if(p===s.length)return g(c(d+1));const f=s[p];Ln(u+f,{pathExt:r},(x,$)=>{if(!x&&$)if(t.all)a.push(u+f);else return g(u+f);return g(l(u,d,p+1))})});return n?c(0).then(u=>n(null,u),n):c(0)},mr=(e,t)=>{t=t||{};const{pathEnv:n,pathExt:o,pathExtExe:s}=On(e,t),r=[];for(let a=0;a<n.length;a++){const c=n[a],l=/^".*"$/.test(c)?c.slice(1,-1):c,u=kn.join(l,e),d=!l&&/^\.[\\\/]/.test(e)?e.slice(0,2)+u:u;for(let p=0;p<o.length;p++){const g=d+o[p];try{if(Ln.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 Mn(e)};var fr=Tn;Tn.sync=mr;var $t={exports:{}};const Dn=(e={})=>{const t=e.env||process.env;return(e.platform||process.platform)!=="win32"?"PATH":Object.keys(t).reverse().find(o=>o.toUpperCase()==="PATH")||"Path"};$t.exports=Dn,$t.exports.default=Dn;var pr=$t.exports;const Nn=A,hr=fr,gr=pr;function _n(e,t){const n=e.options.env||process.env,o=process.cwd(),s=e.options.cwd!=null,r=s&&process.chdir!==void 0&&!process.chdir.disabled;if(r)try{process.chdir(e.options.cwd)}catch{}let a;try{a=hr.sync(e.command,{path:n[gr({env:n})],pathExt:t?Nn.delimiter:void 0})}catch{}finally{r&&process.chdir(o)}return a&&(a=Nn.resolve(s?e.options.cwd:"",a)),a}function yr(e){return _n(e)||_n(e,!0)}var wr=yr,Rt={};const It=/([()\][%!^"`<>&|;, *?])/g;function Cr(e){return e=e.replace(It,"^$1"),e}function br(e,t){return e=`${e}`,e=e.replace(/(?=(\\+?)?)\1"/g,'$1$1\\"'),e=e.replace(/(?=(\\+?)?)\1$/,"$1$1"),e=`"${e}"`,e=e.replace(It,"^$1"),t&&(e=e.replace(It,"^$1")),e}Rt.command=Cr,Rt.argument=br;var Er=/^#!(.*)/;const vr=Er;var Ar=(e="")=>{const t=e.match(vr);if(!t)return null;const[n,o]=t[0].replace(/#! ?/,"").split(" "),s=n.split("/").pop();return s==="env"?o:o?`${s} ${o}`:s};const kt=O,Pr=Ar;function Sr(e){const n=Buffer.alloc(150);let o;try{o=kt.openSync(e,"r"),kt.readSync(o,n,0,150,0),kt.closeSync(o)}catch{}return Pr(n.toString())}var xr=Sr;const $r=A,jn=wr,Fn=Rt,Rr=xr,Ir=process.platform==="win32",kr=/\.(?:com|exe)$/i,Lr=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function Mr(e){e.file=jn(e);const t=e.file&&Rr(e.file);return t?(e.args.unshift(e.file),e.command=t,jn(e)):e.file}function Or(e){if(!Ir)return e;const t=Mr(e),n=!kr.test(t);if(e.options.forceShell||n){const o=Lr.test(t);e.command=$r.normalize(e.command),e.command=Fn.command(e.command),e.args=e.args.map(r=>Fn.argument(r,o));const s=[e.command].concat(e.args).join(" ");e.args=["/d","/s","/c",`"${s}"`],e.command=process.env.comspec||"cmd.exe",e.options.windowsVerbatimArguments=!0}return e}function Tr(e,t,n){t&&!Array.isArray(t)&&(n=t,t=null),t=t?t.slice(0):[],n=Object.assign({},n);const o={command:e,args:t,options:n,file:void 0,original:{command:e,args:t}};return n.shell?o:Or(o)}var Dr=Tr;const Lt=process.platform==="win32";function Mt(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 Nr(e,t){if(!Lt)return;const n=e.emit;e.emit=function(o,s){if(o==="exit"){const r=Gn(s,t);if(r)return n.call(e,"error",r)}return n.apply(e,arguments)}}function Gn(e,t){return Lt&&e===1&&!t.file?Mt(t.original,"spawn"):null}function _r(e,t){return Lt&&e===1&&!t.file?Mt(t.original,"spawnSync"):null}var jr={hookChildProcess:Nr,verifyENOENT:Gn,verifyENOENTSync:_r,notFoundError:Mt};const Bn=Cs,Ot=Dr,Tt=jr;function Hn(e,t,n){const o=Ot(e,t,n),s=Bn.spawn(o.command,o.args,o.options);return Tt.hookChildProcess(s,o),s}function Fr(e,t,n){const o=Ot(e,t,n),s=Bn.spawnSync(o.command,o.args,o.options);return s.error=s.error||Tt.verifyENOENTSync(s.status,o),s}me.exports=Hn,me.exports.spawn=Hn,me.exports.sync=Fr,me.exports._parse=Ot,me.exports._enoent=Tt;var Gr=me.exports,Br=de(Gr);function Hr(e){const t=typeof e=="string"?`
|
|
2
|
+
`:`
|
|
3
|
+
`.charCodeAt(),n=typeof e=="string"?"\r":"\r".charCodeAt();return e[e.length-1]===t&&(e=e.slice(0,-1)),e[e.length-1]===n&&(e=e.slice(0,-1)),e}function Un(e={}){const{env:t=process.env,platform:n=process.platform}=e;return n!=="win32"?"PATH":Object.keys(t).reverse().find(o=>o.toUpperCase()==="PATH")||"Path"}const Ur=({cwd:e=U.cwd(),path:t=U.env[Un()],preferLocal:n=!0,execPath:o=U.execPath,addExecPath:s=!0}={})=>{const r=e instanceof URL?hn(e):e,a=ae.resolve(r),c=[];return n&&Kr(c,a),s&&Wr(c,o,a),[...c,t].join(ae.delimiter)},Kr=(e,t)=>{let n;for(;n!==t;)e.push(ae.join(t,"node_modules/.bin")),n=t,t=ae.resolve(t,"..")},Wr=(e,t,n)=>{const o=t instanceof URL?hn(t):t;e.push(ae.resolve(n,o,".."))},qr=({env:e=U.env,...t}={})=>{e={...e};const n=Un({env:e});return t.path=e[n],e[n]=Ur(t),e},zr=(e,t,n,o)=>{if(n==="length"||n==="prototype"||n==="arguments"||n==="caller")return;const s=Object.getOwnPropertyDescriptor(e,n),r=Object.getOwnPropertyDescriptor(t,n);!Yr(s,r)&&o||Object.defineProperty(e,n,r)},Yr=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)},Vr=(e,t)=>{const n=Object.getPrototypeOf(t);n!==Object.getPrototypeOf(e)&&Object.setPrototypeOf(e,n)},Jr=(e,t)=>`/* Wrapped ${e}*/
|
|
4
|
+
${t}`,Xr=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),Qr=Object.getOwnPropertyDescriptor(Function.prototype.toString,"name"),Zr=(e,t,n)=>{const o=n===""?"":`with ${n.trim()}() `,s=Jr.bind(null,o,t.toString());Object.defineProperty(s,"name",Qr),Object.defineProperty(e,"toString",{...Xr,value:s})};function ei(e,t,{ignoreNonConfigurable:n=!1}={}){const{name:o}=e;for(const s of Reflect.ownKeys(t))zr(e,t,s,n);return Vr(e,t),Zr(e,t,o),e}const Ke=new WeakMap,Kn=(e,t={})=>{if(typeof e!="function")throw new TypeError("Expected a function");let n,o=0;const s=e.displayName||e.name||"<anonymous>",r=function(...a){if(Ke.set(r,++o),o===1)n=e.apply(this,a),e=null;else if(t.throw===!0)throw new Error(`Function \`${s}\` can only be called once`);return n};return ei(r,e),Ke.set(r,o),r};Kn.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 ti=()=>{const e=qn-Wn+1;return Array.from({length:e},ni)},ni=(e,t)=>({name:`SIGRT${t+1}`,number:Wn+t,action:"terminate",description:"Application-specific signal (realtime)",standard:"posix"}),Wn=34,qn=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"}],zn=()=>{const e=ti();return[...oi,...e].map(si)},si=({name:e,number:t,description:n,action:o,forced:s=!1,standard:r})=>{const{signals:{[e]:a}}=gn,c=a!==void 0;return{name:e,number:c?a:t,description:n,supported:c,action:o,forced:s,standard:r}},ri=()=>{const e=zn();return Object.fromEntries(e.map(ii))},ii=({name:e,number:t,description:n,supported:o,action:s,forced:r,standard:a})=>[e,{name:e,number:t,description:n,supported:o,action:s,forced:r,standard:a}],ai=ri(),ci=()=>{const e=zn(),t=qn+1,n=Array.from({length:t},(o,s)=>li(s,e));return Object.assign({},...n)},li=(e,t)=>{const n=ui(e,t);if(n===void 0)return{};const{name:o,description:s,supported:r,action:a,forced:c,standard:l}=n;return{[e]:{name:o,number:e,description:s,supported:r,action:a,forced:c,standard:l}}},ui=(e,t)=>{const n=t.find(({name:o})=>gn.signals[o]===e);return n!==void 0?n:t.find(o=>o.number===e)};ci();const di=({timedOut:e,timeout:t,errorCode:n,signal:o,signalDescription:s,exitCode:r,isCanceled:a})=>e?`timed out after ${t} milliseconds`:a?"was canceled":n!==void 0?`failed with ${n}`:o!==void 0?`was killed with ${o} (${s})`:r!==void 0?`failed with exit code ${r}`:"failed",We=({stdout:e,stderr:t,all:n,error:o,signal:s,exitCode:r,command:a,escapedCommand:c,timedOut:l,isCanceled:u,killed:d,parsed:{options:{timeout:p,cwd:g=U.cwd()}}})=>{r=r===null?void 0:r,s=s===null?void 0:s;const y=s===void 0?void 0:ai[s].description,f=o&&o.code,$=`Command ${di({timedOut:l,timeout:p,errorCode:f,signal:s,signalDescription:y,exitCode:r,isCanceled:u})}: ${a}`,S=Object.prototype.toString.call(o)==="[object Error]",P=S?`${$}
|
|
5
|
+
${o.message}`:$,v=[P,t,e].filter(Boolean).join(`
|
|
6
|
+
`);return S?(o.originalMessage=o.message,o.message=v):o=new Error(v),o.shortMessage=P,o.command=a,o.escapedCommand=c,o.exitCode=r,o.signal=s,o.signalDescription=y,o.stdout=e,o.stderr=t,o.cwd=g,n!==void 0&&(o.all=n),"bufferedData"in o&&delete o.bufferedData,o.failed=!0,o.timedOut=!!l,o.isCanceled=u,o.killed=d&&!l,o},qe=["stdin","stdout","stderr"],mi=e=>qe.some(t=>e[t]!==void 0),Yn=e=>{if(!e)return;const{stdio:t}=e;if(t===void 0)return qe.map(o=>e[o]);if(mi(e))throw new Error(`It's not possible to provide \`stdio\` in combination with one of ${qe.map(o=>`\`${o}\``).join(", ")}`);if(typeof t=="string")return t;if(!Array.isArray(t))throw new TypeError(`Expected \`stdio\` to be of type \`string\` or \`Array\`, got \`${typeof t}\``);const n=Math.max(t.length,qe.length);return Array.from({length:n},(o,s)=>t[s])},fi=e=>{const t=Yn(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 Vn;function pi(){return Vn||(Vn=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=oe.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 hi=vs,Pe=pi(),gi=/^win/i.test(M.platform),Ye=As;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(oe.process))return function(){};hi.equal(typeof e,"function","a callback must be provided for exit handler"),Se===!1&&Jn();var n="exit";t&&t.alwaysLast&&(n="afterexit");var o=function(){N.removeListener(n,e),N.listeners("exit").length===0&&N.listeners("afterexit").length===0&&Dt()};return N.on(n,e),o};var Dt=function(){!Se||!ce(oe.process)||(Se=!1,Pe.forEach(function(t){try{M.removeListener(t,Nt[t])}catch{}}),M.emit=_t,M.reallyExit=Xn,N.count-=1)};pe.exports.unload=Dt;var he=function(t,n,o){N.emitted[t]||(N.emitted[t]=!0,N.emit(t,n,o))},Nt={};Pe.forEach(function(e){Nt[e]=function(){if(ce(oe.process)){var n=M.listeners(e);n.length===N.count&&(Dt(),he("exit",null,e),he("afterexit",null,e),gi&&e==="SIGHUP"&&(e="SIGINT"),M.kill(M.pid,e))}}}),pe.exports.signals=function(){return Pe};var Se=!1,Jn=function(){Se||!ce(oe.process)||(Se=!0,N.count+=1,Pe=Pe.filter(function(t){try{return M.on(t,Nt[t]),!0}catch{return!1}}),M.emit=wi,M.reallyExit=yi)};pe.exports.load=Jn;var Xn=M.reallyExit,yi=function(t){ce(oe.process)&&(M.exitCode=t||0,he("exit",M.exitCode,null),he("afterexit",M.exitCode,null),Xn.call(M,M.exitCode))},_t=M.emit,wi=function(t,n){if(t==="exit"&&ce(oe.process)){n!==void 0&&(M.exitCode=n);var o=_t.apply(this,arguments);return he("exit",M.exitCode,null),he("afterexit",M.exitCode,null),o}else return _t.apply(this,arguments)}}var Ci=pe.exports,bi=de(Ci);const Ei=1e3*5,vi=(e,t="SIGTERM",n={})=>{const o=e(t);return Ai(e,t,n,o),o},Ai=(e,t,n,o)=>{if(!Pi(t,n,o))return;const s=xi(n),r=setTimeout(()=>{e("SIGKILL")},s);r.unref&&r.unref()},Pi=(e,{forceKillAfterTimeout:t},n)=>Si(e)&&t!==!1&&n,Si=e=>e===Es.constants.signals.SIGTERM||typeof e=="string"&&e.toUpperCase()==="SIGTERM",xi=({forceKillAfterTimeout:e=!0})=>{if(e===!0)return Ei;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},$i=(e,t)=>{e.kill()&&(t.isCanceled=!0)},Ri=(e,t,n)=>{e.kill(t),n(Object.assign(new Error("Timed out"),{timedOut:!0,signal:t}))},Ii=(e,{timeout:t,killSignal:n="SIGTERM"},o)=>{if(t===0||t===void 0)return o;let s;const r=new Promise((c,l)=>{s=setTimeout(()=>{Ri(e,n,l)},t)}),a=o.finally(()=>{clearTimeout(s)});return Promise.race([r,a])},ki=({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})`)},Li=async(e,{cleanup:t,detached:n},o)=>{if(!t||n)return o;const s=bi(()=>{e.kill()});return o.finally(()=>{s()})};function jt(e){return e!==null&&typeof e=="object"&&typeof e.pipe=="function"}function Qn(e){return jt(e)&&e.writable!==!1&&typeof e._write=="function"&&typeof e._writableState=="object"}const Mi=e=>e instanceof pn&&typeof e.then=="function",Ft=(e,t,n)=>{if(typeof n=="string")return e[t].pipe(Ps(n)),e;if(Qn(n))return e[t].pipe(n),e;if(!Mi(n))throw new TypeError("The second argument must be a string, a stream or an Execa child process.");if(!Qn(n.stdin))throw new TypeError("The target child process's stdin must be available.");return e[t].pipe(n.stdin),n},Oi=e=>{e.stdout!==null&&(e.pipeStdout=Ft.bind(void 0,e,"stdout")),e.stderr!==null&&(e.pipeStderr=Ft.bind(void 0,e,"stderr")),e.all!==void 0&&(e.pipeAll=Ft.bind(void 0,e,"all"))};var xe={exports:{}};const{PassThrough:Ti}=Ct;var Di=e=>{e={...e};const{array:t}=e;let{encoding:n}=e;const o=n==="buffer";let s=!1;t?s=!(n||o):n=n||"utf8",o&&(n=null);const r=new Ti({objectMode:s});n&&r.setEncoding(n);let a=0;const c=[];return r.on("data",l=>{c.push(l),s?a=c.length:a+=l.length}),r.getBufferedValue=()=>t?c:o?Buffer.concat(c,a):c.join(""),r.getBufferedLength=()=>a,r};const{constants:Ni}=$s,_i=Ct,{promisify:ji}=Rs,Fi=Di,Gi=ji(_i.pipeline);class Zn extends Error{constructor(){super("maxBuffer exceeded"),this.name="MaxBufferError"}}async function Gt(e,t){if(!e)throw new Error("Expected a stream");t={maxBuffer:1/0,...t};const{maxBuffer:n}=t,o=Fi(t);return await new Promise((s,r)=>{const a=c=>{c&&o.getBufferedLength()<=Ni.MAX_LENGTH&&(c.bufferedData=o.getBufferedValue()),r(c)};(async()=>{try{await Gi(e,o),s()}catch(c){a(c)}})(),o.on("data",()=>{o.getBufferedLength()>n&&a(new Zn)})}),o.getBufferedValue()}xe.exports=Gt,xe.exports.buffer=(e,t)=>Gt(e,{...t,encoding:"buffer"}),xe.exports.array=(e,t)=>Gt(e,{...t,array:!0}),xe.exports.MaxBufferError=Zn;var Bi=xe.exports,eo=de(Bi);const{PassThrough:Hi}=Ct;var Ui=function(){var e=[],t=new Hi({objectMode:!0});return t.setMaxListeners(0),t.add=n,t.isEmpty=o,t.on("unpipe",s),Array.prototype.slice.call(arguments).forEach(n),t;function n(r){return Array.isArray(r)?(r.forEach(n),this):(e.push(r),r.once("end",s.bind(null,r)),r.once("error",t.emit.bind(t,"error")),r.pipe(t,{end:!1}),this)}function o(){return e.length==0}function s(r){e=e.filter(function(a){return a!==r}),!e.length&&t.readable&&t.end()}},Ki=de(Ui);const to=e=>{if(e!==void 0)throw new TypeError("The `input` and `inputFile` options cannot be both set.")},Wi=({input:e,inputFile:t})=>typeof t!="string"?e:(to(e),xs(t)),qi=e=>{const t=Wi(e);if(jt(t))throw new TypeError("The `input` option cannot be a stream in sync mode");return t},zi=({input:e,inputFile:t})=>typeof t!="string"?e:(to(e),Ss(t)),Yi=(e,t)=>{const n=zi(t);n!==void 0&&(jt(n)?n.pipe(e.stdin):e.stdin.end(n))},Vi=(e,{all:t})=>{if(!t||!e.stdout&&!e.stderr)return;const n=Ki();return e.stdout&&n.add(e.stdout),e.stderr&&n.add(e.stderr),n},Bt=async(e,t)=>{if(!(!e||t===void 0)){e.destroy();try{return await t}catch(n){return n.bufferedData}}},Ht=(e,{encoding:t,buffer:n,maxBuffer:o})=>{if(!(!e||!n))return t?eo(e,{encoding:t,maxBuffer:o}):eo.buffer(e,{maxBuffer:o})},Ji=async({stdout:e,stderr:t,all:n},{encoding:o,buffer:s,maxBuffer:r},a)=>{const c=Ht(e,{encoding:o,buffer:s,maxBuffer:r}),l=Ht(t,{encoding:o,buffer:s,maxBuffer:r}),u=Ht(n,{encoding:o,buffer:s,maxBuffer:r*2});try{return await Promise.all([a,c,l,u])}catch(d){return Promise.all([{error:d,signal:d.signal,timedOut:d.timedOut},Bt(e,c),Bt(t,l),Bt(n,u)])}},Xi=(async()=>{})().constructor.prototype,Qi=["then","catch","finally"].map(e=>[e,Reflect.getOwnPropertyDescriptor(Xi,e)]),no=(e,t)=>{for(const[n,o]of Qi){const s=typeof t=="function"?(...r)=>Reflect.apply(o.value,t(),r):o.value.bind(t);Reflect.defineProperty(e,n,{...o,value:s})}},Zi=e=>new Promise((t,n)=>{e.on("exit",(o,s)=>{t({exitCode:o,signal:s})}),e.on("error",o=>{n(o)}),e.stdin&&e.stdin.on("error",o=>{n(o)})}),oo=(e,t=[])=>Array.isArray(t)?[e,...t]:[e],ea=/^[\w.-]+$/,ta=/"/g,na=e=>typeof e!="string"||ea.test(e)?e:`"${e.replace(ta,'\\"')}"`,so=(e,t)=>oo(e,t).join(" "),ro=(e,t)=>oo(e,t).map(n=>na(n)).join(" "),io=/ +/g,ao=e=>{const t=[];for(const n of e.trim().split(io)){const o=t[t.length-1];o&&o.endsWith("\\")?t[t.length-1]=`${o.slice(0,-1)} ${n}`:t.push(n)}return t},co=e=>{const t=typeof e;if(t==="string")return e;if(t==="number")return String(e);if(t==="object"&&e!==null&&!(e instanceof pn)&&"stdout"in e){const n=typeof e.stdout;if(n==="string")return e.stdout;if(fn.isBuffer(e.stdout))return e.stdout.toString();throw new TypeError(`Unexpected "${n}" stdout in template expression`)}throw new TypeError(`Unexpected "${t}" in template expression`)},lo=(e,t,n)=>n||e.length===0||t.length===0?[...e,...t]:[...e.slice(0,-1),`${e[e.length-1]}${t[0]}`,...t.slice(1)],oa=({templates:e,expressions:t,tokens:n,index:o,template:s})=>{const r=s??e.raw[o],a=r.split(io).filter(Boolean),c=lo(n,a,r.startsWith(" "));if(o===t.length)return c;const l=t[o],u=Array.isArray(l)?l.map(d=>co(d)):[co(l)];return lo(c,u,r.endsWith(" "))},uo=(e,t)=>{let n=[];for(const[o,s]of e.entries())n=oa({templates:e,expressions:t,tokens:n,index:o,template:s});return n},sa=ks("execa").enabled,Ve=(e,t)=>String(e).padStart(t,"0"),ra=()=>{const e=new Date;return`${Ve(e.getHours(),2)}:${Ve(e.getMinutes(),2)}:${Ve(e.getSeconds(),2)}.${Ve(e.getMilliseconds(),3)}`},mo=(e,{verbose:t})=>{t&&U.stderr.write(`[${ra()}] ${e}
|
|
7
|
+
`)},ia=1e3*1e3*100,aa=({env:e,extendEnv:t,preferLocal:n,localDir:o,execPath:s})=>{const r=t?{...U.env,...e}:e;return n?qr({env:r,cwd:o,execPath:s}):r},fo=(e,t,n={})=>{const o=Br._parse(e,t,n);return e=o.command,t=o.args,n=o.options,n={maxBuffer:ia,buffer:!0,stripFinalNewline:!0,extendEnv:!0,preferLocal:!1,localDir:n.cwd||U.cwd(),execPath:U.execPath,encoding:"utf8",reject:!0,cleanup:!0,all:!1,windowsHide:!0,verbose:sa,...n},n.env=aa(n),n.stdio=Yn(n),U.platform==="win32"&&ae.basename(e,".exe")==="cmd"&&t.unshift("/q"),{file:e,args:t,options:n,parsed:o}},$e=(e,t,n)=>typeof t!="string"&&!fn.isBuffer(t)?n===void 0?void 0:"":e.stripFinalNewline?Hr(t):t;function C(e,t,n){const o=fo(e,t,n),s=so(e,t),r=ro(e,t);mo(r,o.options),ki(o.options);let a;try{a=wt.spawn(o.file,o.args,o.options)}catch(y){const f=new wt.ChildProcess,x=Promise.reject(We({error:y,stdout:"",stderr:"",all:"",command:s,escapedCommand:r,parsed:o,timedOut:!1,isCanceled:!1,killed:!1}));return no(f,x),f}const c=Zi(a),l=Ii(a,o.options,c),u=Li(a,o.options,l),d={isCanceled:!1};a.kill=vi.bind(null,a.kill.bind(a)),a.cancel=$i.bind(null,a,d);const g=Kn(async()=>{const[{error:y,exitCode:f,signal:x,timedOut:$},S,P,v]=await Ji(a,o.options,u),w=$e(o.options,S),k=$e(o.options,P),L=$e(o.options,v);if(y||f!==0||x!==null){const D=We({error:y,exitCode:f,signal:x,stdout:w,stderr:k,all:L,command:s,escapedCommand:r,parsed:o,timedOut:$,isCanceled:d.isCanceled||(o.options.signal?o.options.signal.aborted:!1),killed:a.killed});if(!o.options.reject)return D;throw D}return{command:s,escapedCommand:r,exitCode:0,stdout:w,stderr:k,all:L,failed:!1,timedOut:!1,isCanceled:!1,killed:!1}});return Yi(a,o.options),a.all=Vi(a,o.options),Oi(a),no(a,g),a}function Ut(e,t,n){const o=fo(e,t,n),s=so(e,t),r=ro(e,t);mo(r,o.options);const a=qi(o.options);let c;try{c=wt.spawnSync(o.file,o.args,{...o.options,input:a})}catch(d){throw We({error:d,stdout:"",stderr:"",all:"",command:s,escapedCommand:r,parsed:o,timedOut:!1,isCanceled:!1,killed:!1})}const l=$e(o.options,c.stdout,c.error),u=$e(o.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:o,timedOut:c.error&&c.error.code==="ETIMEDOUT",isCanceled:!1,killed:c.signal!==null});if(!o.options.reject)return d;throw d}return{command:s,escapedCommand:r,exitCode:0,stdout:l,stderr:u,failed:!1,timedOut:!1,isCanceled:!1,killed:!1}}const ca=({input:e,inputFile:t,stdio:n})=>e===void 0&&t===void 0&&n===void 0?{stdin:"inherit"}:{},po=(e={})=>({preferLocal:!0,...ca(e),...e});function ho(e){function t(n,...o){if(!Array.isArray(n))return ho({...e,...n});const[s,...r]=uo(n,o);return C(s,r,po(e))}return t.sync=(n,...o)=>{if(!Array.isArray(n))throw new TypeError("Please use $(options).sync`command` instead of $.sync(options)`command`.");const[s,...r]=uo(n,o);return Ut(s,r,po(e))},t}const la=ho();function ua(e,t){const[n,...o]=ao(e);return C(n,o,t)}function da(e,t){const[n,...o]=ao(e);return Ut(n,o,t)}function ma(e,t,n={}){t&&!Array.isArray(t)&&typeof t=="object"&&(n=t,t=[]);const o=fi(n),s=U.execArgv.filter(c=>!c.startsWith("--inspect")),{nodePath:r=U.execPath,nodeOptions:a=s}=n;return C(r,[...a,e,...Array.isArray(t)?t:[]],{...n,stdin:void 0,stdout:void 0,stderr:void 0,stdio:o,shell:!1})}var fa=Object.freeze({__proto__:null,execa:C,execaSync:Ut,$:la,execaCommand:ua,execaCommandSync:da,execaNode:ma});const{hasOwnProperty:Kt}=Object.prototype,Je=typeof process<"u"&&process.platform==="win32"?`\r
|
|
8
|
+
`:`
|
|
9
|
+
`,Wt=(e,t)=>{const n=[];let o="";typeof t=="string"?t={section:t,whitespace:!1}:(t=t||Object.create(null),t.whitespace=t.whitespace===!0);const s=t.whitespace?" = ":"=";for(const r of Object.keys(e)){const a=e[r];if(a&&Array.isArray(a))for(const c of a)o+=ge(r+"[]")+s+ge(c)+Je;else a&&typeof a=="object"?n.push(r):o+=ge(r)+s+ge(a)+Je}t.section&&o.length&&(o="["+ge(t.section)+"]"+Je+o);for(const r of n){const a=go(r).join("\\."),c=(t.section?t.section+".":"")+a,{whitespace:l}=t,u=Wt(e[r],{section:c,whitespace:l});o.length&&u.length&&(o+=Je),o+=u}return o},go=e=>e.replace(/\1/g,"LITERAL\\1LITERAL").replace(/\\\./g,"").split(/\./).map(t=>t.replace(/\1/g,"\\.").replace(/\2LITERAL\\1LITERAL\2/g,"")),yo=e=>{const t=Object.create(null);let n=t,o=null;const s=/^\[([^\]]*)\]$|^([^=]+)(=(.*))?$/i,r=e.split(/[\r\n]+/g);for(const c of r){if(!c||c.match(/^\s*[;#]/))continue;const l=c.match(s);if(!l)continue;if(l[1]!==void 0){if(o=Xe(l[1]),o==="__proto__"){n=Object.create(null);continue}n=t[o]=t[o]||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&&(Kt.call(n,p)?Array.isArray(n[p])||(n[p]=[n[p]]):n[p]=[]),Array.isArray(n[p])?n[p].push(y):n[p]=y}const a=[];for(const c of Object.keys(t)){if(!Kt.call(t,c)||typeof t[c]!="object"||Array.isArray(t[c]))continue;const l=go(c);n=t;const u=l.pop(),d=u.replace(/\\\./g,".");for(const p of l)p!=="__proto__"&&((!Kt.call(n,p)||typeof n[p]!="object")&&(n[p]=Object.create(null)),n=n[p]);n===t&&d===u||(n[d]=t[c],a.push(c))}for(const c of a)delete t[c];return t},wo=e=>e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"),ge=e=>typeof e!="string"||e.match(/[=\r\n]/)||e.match(/^\[/)||e.length>1&&wo(e)||e!==e.trim()?JSON.stringify(e):e.split(";").join("\\;").split("#").join("\\#"),Xe=(e,t)=>{if(e=(e||"").trim(),wo(e)){e.charAt(0)==="'"&&(e=e.slice(1,-1));try{e=JSON.parse(e)}catch{}}else{let n=!1,o="";for(let s=0,r=e.length;s<r;s++){const a=e.charAt(s);if(n)"\\;#".indexOf(a)!==-1?o+=a:o+="\\"+a,n=!1;else{if(";#".indexOf(a)!==-1)break;a==="\\"?n=!0:o+=a}}return n&&(o+="\\"),o.trim()}return e};var pa={parse:yo,decode:yo,stringify:Wt,encode:Wt,safe:ge,unsafe:Xe},ye=de(pa);const we=3,ha=3,Co={mode:"none",maxHunkLines:0,maxDiffLines:0},ga=(e,t={})=>{const n={...Co,...t},o=e.split(`
|
|
10
|
+
`).length;return n.mode==="none"||!e.trim()?{diff:e,stats:{originalLines:o,compressedLines:o,originalChars:e.length,compressedChars:e.length,truncatedHunks:0,truncatedFiles:0}}:ya(e,n,o)},ya=(e,t,n)=>{const o=wa(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<o.length;p++){if(s.length>=c){a+=o.length-p;break}const{lines:g,hunksTruncated:y}=Ca(o[p],l);r+=y;const f=c-s.length;if(g.length>f){s.push(...g.slice(0,f)),a+=o.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:n,compressedLines:s.length,originalChars:e.length,compressedChars:d.length,truncatedHunks:r,truncatedFiles:a}}},wa=e=>{const t=e.split(`
|
|
12
|
+
`),n=[];let o=[];for(const s of t)s.startsWith("diff --git ")?(o.length>0&&n.push(o),o=[s]):o.push(s);return o.length>0&&n.push(o),n},Ca=(e,t)=>{const o=[`=== ${Ea(e)} ===`];let s=0;const r=[];let a=null;for(const c of e)if(!va(c)){if(c.startsWith("@@")){a&&r.push(a),a={header:c,lines:[]};continue}a&&a.lines.push(c)}a&&r.push(a);for(const c of r){o.push(c.header);const l=ba(c.lines);if(t>0&&l.length>t){const u=l.length-t;o.push(...l.slice(0,t)),o.push(`[... ${u} lines truncated]`),s++}else o.push(...l)}return{lines:o,hunksTruncated:s}},ba=e=>{if(e.length===0)return[];const t=e.map(r=>r.startsWith("+")||r.startsWith("-")),n=new Array(e.length).fill(!1);for(let r=0;r<e.length;r++)if(t[r]){n[r]=!0;for(let a=1;a<=ha;a++)r-a>=0&&(n[r-a]=!0),r+a<e.length&&(n[r+a]=!0);continue}const o=[];let s=!1;for(let r=0;r<e.length;r++)n[r]?(s&&(o.push(" ..."),s=!1),o.push(e[r])):s=!0;return o},Ea=e=>{const n=(e[0]||"").match(/^diff --git a\/(.+?) b\/(.+)$/);if(!n)return"unknown";const[,o,s]=n;return o!==s?`${o} \u2192 ${s}`:s},va=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,n={}){super(t,{cause:n.cause}),this.name="KnownError",this.code=n.code,this.suggestions=n.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${$n}`)}`),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),bo=async e=>{try{await I.mkdir(e,{recursive:!0})}catch(t){if(t.code!=="EEXIST")throw t}},Aa=e=>e&&`${e[0].toUpperCase()}${e.slice(1)}`,Pa=(e,t)=>{const n=Math.ceil(e),o=Math.floor(t);return Math.floor(Math.random()*(o-n+1))+n},Eo=(e,t)=>e.disabled&&!t.disabled?1:!e.disabled&&t.disabled?-1:0,qt=e=>e.reduce((t,n)=>Array.isArray(n)?t.concat(qt(n)):t.concat(n),[]),Sa=(e,t=5)=>e.replace(/[\n\r]/g,"").split(" ").slice(0,t).join(" "),xa=e=>{let t=0;for(let n=0;n<e.length;n++){const o=e.charCodeAt(n);t=(t<<5)-t+o,t=t&t}return Math.abs(t)},$a=e=>{const t=e%360,n=65+e%15,o=45+e%10;return`hsl(${t}, ${n}%, ${o}%)`},Ra=e=>{const[t,n,o]=e.match(/\d+/g).map((p,g)=>g===0?Number(p):Number(p)/100),s=(1-Math.abs(2*o-1))*n,r=s*(1-Math.abs(t/60%2-1)),a=o-s/2;let c,l,u;t<60?[c,l,u]=[s,r,0]:t<120?[c,l,u]=[r,s,0]:t<180?[c,l,u]=[0,s,r]:t<240?[c,l,u]=[0,r,s]:t<300?[c,l,u]=[r,0,s]:[c,l,u]=[s,0,r];const d=p=>{const g=Math.round((p+a)*255).toString(16);return g.length===1?"0"+g:g};return`#${d(c)}${d(l)}${d(u)}`},Ia=e=>{const t=xa(e),n=$a(t);return{primary:Ra(n),secondary:"#FFFFFF"}},ka=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(A.isAbsolute(e))return A.resolve(e);if(Le){const t=A.dirname(Le),n=A.join(t,e);return A.resolve(n)}else return""},La=["","conventional","gitmoji"],Ie="http://localhost:11434",{hasOwnProperty:Ma}=Object.prototype,zt=(e,t)=>Ma.call(e,t),Ce=["OPENAI","COPILOT_SDK","OPENROUTER","OLLAMA","HUGGINGFACE","GEMINI","ANTHROPIC","MISTRAL","CODESTRAL","COHERE","GROQ","PERPLEXITY","DEEPSEEK","GITHUB_MODELS","BEDROCK"],vo=e=>{const t=ue.platform(),n=ue.homedir();let o,s;switch(e){case"config":o=process.env.XDG_CONFIG_HOME;break;case"data":o=process.env.XDG_DATA_HOME;break;case"cache":o=process.env.XDG_CACHE_HOME;break;case"state":o=process.env.XDG_STATE_HOME;break;default:o=void 0}if(t==="darwin")e==="cache"?s=A.join(n,"Library","Caches"):s=A.join(n,"Library","Application Support");else if(t==="win32")s=process.env.LOCALAPPDATA||n;else switch(e){case"config":s=A.join(n,".config");break;case"data":s=A.join(n,".local","share");break;case"cache":s=A.join(n,".cache");break;case"state":s=A.join(n,".local","state");break;default:s=n}return o||s},Ao=A.join(vo("config"),"aicommit2"),q=A.join(vo("state"),"aicommit2","logs"),Po=A.join(Ao,"config.ini"),So=A.join(q,"aicommit2-%DATE%.log"),xo=A.join(q,"exceptions-%DATE%.log"),Oa=e=>{const t=Object.keys(e),n=new Set([...Ce,...t.filter(o=>/^[A-Z][A-Z0-9_]*$/.test(o))]);return Array.from(n)},E=(e,t,n)=>{if(!t)throw new m(`Invalid config property ${e}: ${n}`)},G=(e,t=!1)=>n=>typeof n=="boolean"?n:n==null?t:(E(e,/^(?:true|false)$/.test(n),"Must be a boolean(true or false)"),n==="true"),et=e=>t=>{if(!t)return{};if(typeof t=="object")return E(e,!Array.isArray(t),"Must be a JSON object"),t;try{const n=JSON.parse(t);return E(e,typeof n=="object"&&n!==null&&!Array.isArray(n),"Must be a valid JSON object"),n}catch(n){throw new m(`Invalid ${e}: Must be valid JSON. Error: ${n.message}`)}},i={systemPrompt(e){return e||""},systemPromptPath(e){return e||""},codeReviewPromptPath(e){return e||""},timeout(e){if(!e)return 6e4;E("timeout",/^\d+$/.test(e),"Must be an integer");const t=Number(e);return E("timeout",t>=500,"Must be greater than 500ms"),t},temperature(e){if(!e)return .7;E("temperature",/^(2|\d)(\.\d{1,2})?$/.test(e),"Must be decimal between 0 and 2");const t=Number(e);return E("temperature",t>0,"Must be greater than 0"),E("temperature",t<=2,"Must be less than or equal to 2"),t},maxTokens(e){return e?(E("maxTokens",/^\d+$/.test(e),"Must be an integer"),Number(e)):8192},logLevel(e){return e?(E("logLevel",/^(?:error|warn|info|http|verbose|debug|silly)$/.test(e),"Must be a valid log level (error, warn, info, http, verbose, debug, silly)"),e):"info"},logFilePath(e){return e||So},exceptionLogFilePath(e){return e||xo},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",La.includes(e),"Invalid commit type"),e):"conventional"},maxLength(e){if(!e)return 50;E("maxLength",/^\d+$/.test(e),"Must be an integer");const t=Number(e);return E("maxLength",t>=20,"Must be greater than 20 characters"),t},exclude:e=>e?(typeof e=="string"?e?.split(","):e).map(n=>n.trim()).filter(n=>!!n&&n.length>0):[],topP:e=>{if(!e)return .9;E("topP",/^(1|\d)(\.\d{1,2})?$/.test(e),"Must be decimal between 0 and 1");const t=Number(e);return E("topP",t>0,"Must be greater than 0"),E("topP",t<=1,"Must be less than or equal to 1"),t},logging:G("logging",!0),includeBody:G("includeBody"),codeReview:G("codeReview"),disabled:G("disabled"),watchMode:G("watchMode"),forceGit:G("forceGit"),stream:G("stream"),disableLowerCase:G("disableLowerCase"),jjAutoNew:G("jjAutoNew"),autoCopy:G("autoCopy"),modelNameDisplay:e=>e?(E("modelNameDisplay",/^(?:none|short|full)$/.test(e),"Must be none, short, or full"),e):"short",diffCompression:e=>e?(E("diffCompression",/^(?:none|compact)$/.test(e),"Must be none or compact"),e):Co.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(n=>n.trim()).filter(n=>!!n&&n.length>0):["gpt-4o-mini"],url:e=>e?(E("OPENAI.url",/^https?:\/\//.test(e),"Must be a valid URL"),e):"https://api.openai.com",path:e=>e||"/v1/chat/completions",proxy:e=>e||"",topP:i.topP,systemPrompt:i.systemPrompt,systemPromptPath:i.systemPromptPath,codeReviewPromptPath:i.codeReviewPromptPath,timeout:i.timeout,temperature:i.temperature,maxTokens:i.maxTokens,logging:i.logging,locale:i.locale,generate:i.generate,type:i.type,maxLength:i.maxLength,includeBody:i.includeBody,codeReview:i.codeReview,disabled:i.disabled,stream:i.stream,watchMode:i.watchMode,disableLowerCase:i.disableLowerCase,diffCompression:i.diffCompression,maxHunkLines:i.maxHunkLines,maxDiffLines:i.maxDiffLines,diffContext:i.diffContext},OPENROUTER:{key:e=>e||"",envKey:e=>e||"",model:e=>e?(typeof e=="string"?e?.split(","):e).map(n=>n.trim()).filter(n=>!!n&&n.length>0):["openrouter/auto"],url:e=>e?(E("OPENROUTER.url",/^https?:\/\//.test(e),"Must be a valid URL"),e):"https://openrouter.ai",path:e=>e||"/api/v1/chat/completions",responseFormat: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(n=>n.trim()).filter(n=>!!n&&n.length>0):["CohereForAI/c4ai-command-r-plus"],systemPrompt:i.systemPrompt,systemPromptPath:i.systemPromptPath,codeReviewPromptPath:i.codeReviewPromptPath,timeout:i.timeout,temperature:i.temperature,maxTokens:i.maxTokens,topP:i.topP,logging:i.logging,locale:i.locale,generate:i.generate,type:i.type,maxLength:i.maxLength,includeBody:i.includeBody,codeReview:i.codeReview,disabled:i.disabled,stream:i.stream,watchMode:i.watchMode,disableLowerCase:i.disableLowerCase,diffCompression:i.diffCompression,maxHunkLines:i.maxHunkLines,maxDiffLines:i.maxDiffLines,diffContext:i.diffContext},GEMINI:{key:e=>e||"",envKey:e=>e||"",model:e=>e?(typeof e=="string"?e?.split(","):e).map(n=>n.trim()).filter(n=>!!n&&n.length>0):["gemini-3-flash-preview"],systemPrompt:i.systemPrompt,systemPromptPath:i.systemPromptPath,codeReviewPromptPath:i.codeReviewPromptPath,timeout:i.timeout,temperature:i.temperature,maxTokens:i.maxTokens,logging:i.logging,locale:i.locale,generate:i.generate,type:i.type,maxLength:i.maxLength,includeBody:i.includeBody,topP:i.topP,codeReview:i.codeReview,disabled:i.disabled,stream:i.stream,watchMode:i.watchMode,disableLowerCase:i.disableLowerCase,diffCompression:i.diffCompression,maxHunkLines:i.maxHunkLines,maxDiffLines:i.maxDiffLines,diffContext:i.diffContext},ANTHROPIC:{key:e=>e||"",envKey:e=>e||"",model:e=>e?(typeof e=="string"?e?.split(","):e).map(n=>n.trim()).filter(n=>!!n&&n.length>0):["claude-sonnet-4-20250514"],systemPrompt:i.systemPrompt,systemPromptPath:i.systemPromptPath,codeReviewPromptPath:i.codeReviewPromptPath,timeout:i.timeout,temperature:i.temperature,maxTokens:i.maxTokens,logging:i.logging,locale:i.locale,generate:i.generate,type:i.type,maxLength:i.maxLength,includeBody:i.includeBody,topP:i.topP,codeReview:i.codeReview,disabled:i.disabled,stream:i.stream,watchMode:i.watchMode,disableLowerCase:i.disableLowerCase,diffCompression:i.diffCompression,maxHunkLines:i.maxHunkLines,maxDiffLines:i.maxDiffLines,diffContext:i.diffContext},MISTRAL:{key:e=>e||"",envKey:e=>e||"",model:e=>e?(typeof e=="string"?e?.split(","):e).map(n=>n.trim()).filter(n=>!!n&&n.length>0):["mistral-small-latest"],systemPrompt:i.systemPrompt,systemPromptPath:i.systemPromptPath,codeReviewPromptPath:i.codeReviewPromptPath,timeout:i.timeout,temperature:i.temperature,maxTokens:i.maxTokens,logging:i.logging,locale:i.locale,generate:i.generate,type:i.type,maxLength:i.maxLength,includeBody:i.includeBody,topP:i.topP,codeReview:i.codeReview,disabled:i.disabled,stream:i.stream,watchMode:i.watchMode,disableLowerCase:i.disableLowerCase,diffCompression:i.diffCompression,maxHunkLines:i.maxHunkLines,maxDiffLines:i.maxDiffLines,diffContext:i.diffContext},CODESTRAL:{key:e=>e||"",envKey:e=>e||"",model:e=>e?(typeof e=="string"?e?.split(","):e).map(n=>n.trim()).filter(n=>!!n&&n.length>0):["codestral-latest"],topP:i.topP,systemPrompt:i.systemPrompt,systemPromptPath:i.systemPromptPath,codeReviewPromptPath:i.codeReviewPromptPath,timeout:i.timeout,temperature:i.temperature,maxTokens:i.maxTokens,logging:i.logging,locale:i.locale,generate:i.generate,type:i.type,maxLength:i.maxLength,includeBody:i.includeBody,codeReview:i.codeReview,disabled:i.disabled,stream:i.stream,watchMode:i.watchMode,disableLowerCase:i.disableLowerCase,diffCompression:i.diffCompression,maxHunkLines:i.maxHunkLines,maxDiffLines:i.maxDiffLines,diffContext:i.diffContext},OLLAMA:{model:e=>e?(typeof e=="string"?e?.split(","):e).map(n=>n.trim()).filter(n=>!!n&&n.length>0):[],host:e=>e?(E("OLLAMA.host",/^https?:\/\//.test(e),"Must be a valid URL"),e):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(n=>n.trim()).filter(n=>!!n&&n.length>0):["command-a-03-2025"],systemPrompt:i.systemPrompt,systemPromptPath:i.systemPromptPath,codeReviewPromptPath:i.codeReviewPromptPath,temperature:i.temperature,maxTokens:i.maxTokens,logging:i.logging,locale:i.locale,timeout:i.timeout,generate:i.generate,type:i.type,maxLength:i.maxLength,includeBody:i.includeBody,topP:i.topP,codeReview:i.codeReview,disabled:i.disabled,stream:i.stream,watchMode:i.watchMode,disableLowerCase:i.disableLowerCase,diffCompression:i.diffCompression,maxHunkLines:i.maxHunkLines,maxDiffLines:i.maxDiffLines,diffContext:i.diffContext},GROQ:{key:e=>e||"",envKey:e=>e||"",model:e=>e?(typeof e=="string"?e?.split(","):e).map(n=>n.trim()).filter(n=>!!n&&n.length>0):["llama-3.3-70b-versatile"],systemPrompt:i.systemPrompt,systemPromptPath:i.systemPromptPath,codeReviewPromptPath:i.codeReviewPromptPath,timeout:i.timeout,temperature:i.temperature,maxTokens:i.maxTokens,logging:i.logging,locale:i.locale,generate:i.generate,type:i.type,maxLength:i.maxLength,includeBody:i.includeBody,topP:i.topP,codeReview:i.codeReview,disabled:i.disabled,stream:i.stream,watchMode:i.watchMode,disableLowerCase:i.disableLowerCase,diffCompression:i.diffCompression,maxHunkLines:i.maxHunkLines,maxDiffLines:i.maxDiffLines,diffContext:i.diffContext},PERPLEXITY:{key:e=>e||"",envKey:e=>e||"",model:e=>e?(typeof e=="string"?e?.split(","):e).map(n=>n.trim()).filter(n=>!!n&&n.length>0):["sonar"],topP:i.topP,systemPrompt:i.systemPrompt,systemPromptPath:i.systemPromptPath,codeReviewPromptPath:i.codeReviewPromptPath,timeout:i.timeout,temperature:i.temperature,maxTokens:i.maxTokens,logging:i.logging,locale:i.locale,generate:i.generate,type:i.type,maxLength:i.maxLength,includeBody:i.includeBody,codeReview:i.codeReview,disabled:i.disabled,stream:i.stream,watchMode:i.watchMode,disableLowerCase:i.disableLowerCase,diffCompression:i.diffCompression,maxHunkLines:i.maxHunkLines,maxDiffLines:i.maxDiffLines,diffContext:i.diffContext},DEEPSEEK:{key:e=>e||"",envKey:e=>e||"",model:e=>e?(typeof e=="string"?e?.split(","):e).map(n=>n.trim()).filter(n=>!!n&&n.length>0):["deepseek-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(n=>n.trim()).filter(n=>!!n&&n.length>0):["openai/gpt-4o-mini"],systemPrompt:i.systemPrompt,systemPromptPath:i.systemPromptPath,codeReviewPromptPath:i.codeReviewPromptPath,timeout:i.timeout,temperature:i.temperature,maxTokens:i.maxTokens,logging:i.logging,locale:i.locale,generate:i.generate,type:i.type,maxLength:i.maxLength,includeBody:i.includeBody,topP:i.topP,codeReview:i.codeReview,disabled:i.disabled,stream:i.stream,watchMode:i.watchMode,disableLowerCase:i.disableLowerCase,diffCompression:i.diffCompression,maxHunkLines:i.maxHunkLines,maxDiffLines:i.maxDiffLines,diffContext:i.diffContext},COPILOT_SDK:{key:e=>e||"",envKey:e=>e||"",model:e=>e?(typeof e=="string"?e?.split(","):e).map(n=>n.trim()).filter(n=>!!n&&n.length>0):["gpt-4.1"],systemPrompt:i.systemPrompt,systemPromptPath:i.systemPromptPath,codeReviewPromptPath:i.codeReviewPromptPath,timeout:i.timeout,temperature:i.temperature,maxTokens:i.maxTokens,logging:i.logging,locale:i.locale,generate:i.generate,type:i.type,maxLength:i.maxLength,includeBody:i.includeBody,topP:i.topP,codeReview:i.codeReview,disabled:i.disabled,stream:i.stream,watchMode:i.watchMode,disableLowerCase:i.disableLowerCase,diffCompression:i.diffCompression,maxHunkLines:i.maxHunkLines,maxDiffLines:i.maxDiffLines,diffContext:i.diffContext},BEDROCK:{key:e=>e||"",envKey:e=>e&&e.length>0?e:"BEDROCK_API_KEY",model:e=>e?(typeof e=="string"?e?.split(","):e).map(n=>{const o=n.trim();return o&&!o.includes(".")&&!o.includes(":")&&console.warn(`[Bedrock] Model ID "${o}" may be invalid.
|
|
17
|
+
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`),o}).filter(n=>!!n&&n.length>0):["anthropic.claude-haiku-4-5-20251001-v1:0"],runtimeMode:e=>{e&&console.warn("[Bedrock] DEPRECATION: runtimeMode is no longer used. Authentication method is now auto-detected from configured credentials.")},region:e=>e||process.env.AWS_REGION||process.env.AWS_DEFAULT_REGION||"",profile:e=>e||process.env.AWS_PROFILE||"",accessKeyId:e=>e||process.env.AWS_ACCESS_KEY_ID||"",secretAccessKey:e=>e||process.env.AWS_SECRET_ACCESS_KEY||"",sessionToken:e=>e||process.env.AWS_SESSION_TOKEN||"",applicationEndpointId:e=>e||process.env.BEDROCK_APPLICATION_ENDPOINT_ID||"",applicationInferenceProfileArn:e=>e||process.env.BEDROCK_APPLICATION_INFERENCE_PROFILE_ARN||process.env.BEDROCK_INFERENCE_PROFILE_ARN||"",applicationBaseUrl:e=>e||process.env.BEDROCK_APPLICATION_BASE_URL||"",systemPrompt:i.systemPrompt,systemPromptPath:i.systemPromptPath,codeReviewPromptPath:i.codeReviewPromptPath,timeout:i.timeout,temperature:e=>{if(!e)return;E("temperature",/^(2|\d)(\.\d{1,2})?$/.test(e),"Must be decimal between 0 and 2");const t=Number(e);return E("temperature",t>0,"Must be greater than 0"),E("temperature",t<=2,"Must be less than or equal to 2"),t},maxTokens:e=>{if(e)return E("maxTokens",/^\d+$/.test(e),"Must be an integer"),Number(e)},logging:i.logging,locale:i.locale,generate:i.generate,type:i.type,maxLength:i.maxLength,includeBody:i.includeBody,topP:e=>{if(!e)return;E("topP",/^(1|\d)(\.\d{1,2})?$/.test(e),"Must be decimal between 0 and 1");const t=Number(e);return E("topP",t>0,"Must be greater than 0"),E("topP",t<=1,"Must be less than or equal to 1"),t},codeReview:i.codeReview,disabled:i.disabled,stream:i.stream,watchMode:i.watchMode,disableLowerCase:i.disableLowerCase,inferenceParameters:et("BEDROCK.inferenceParameters"),diffCompression:i.diffCompression,maxHunkLines:i.maxHunkLines,maxDiffLines:i.maxDiffLines,diffContext:i.diffContext}},Ta=e=>typeof e=="object"&&e!==null,$o=(e,t)=>{Object.keys(e).forEach(n=>{const o=e[n];Ta(o)&&t in o&&(o[t]=!0)})},Da=e=>{$o(e,"includeBody")},Ro=e=>{$o(e,"disableLowerCase")};let Le,Me=null,Yt=null;const Na=(e=[])=>{const t={};for(const n of e)if(n.startsWith("--")){const[o,s]=n.slice(2).split("="),[r,a]=o.split(".");r&&a&&r in ke?(t[r]||(t[r]={}),t[r][a]=s):t[o]=s}return t},_a=()=>{const e=ue.homedir(),t=process.env.AICOMMIT_CONFIG_PATH,n=Po,o=A.join(e,".aicommit2");return[t,n,o].filter(s=>!!s)},be=async()=>{const e=_a();for(const t of e)if(await Qe(t))return t;return Po},ja=e=>e.replace(/\$\{([a-zA-Z_][a-zA-Z0-9_]*)\}|\$([a-zA-Z_][a-zA-Z0-9_]*)/g,(t,n,o)=>{const s=n||o;return process.env[s]??""}),Io=e=>{if(Array.isArray(e)||e===null||typeof e!="object")return e;const t={};for(const[n,o]of Object.entries(e)){const s=Io(o);if(!n.includes(".")){t[n]=s;continue}const r=n.split(".");let a=t;for(const c of r.slice(0,-1)){const l=a[c];(!l||typeof l!="object"||Array.isArray(l))&&(a[c]={}),a=a[c]}a[r[r.length-1]]=s}return t},Oe=async()=>{const e=await be();if(Me&&Yt===e)return Me;Le=e;try{const t=await I.readFile(e,"utf8"),n=ja(t);return Me=Io(ye.parse(n)),Yt=e,Me}catch(t){return t.code==="ENOENT"?(Le=void 0,{}):(console.error(`Error reading config file ${e}:`,t),Le=void 0,{})}},ko=()=>{Me=null,Yt=null},Z=async(e,t=[])=>{const n=await Oe(),o=Na(t),s={...e,...o},r={},a=Oa(n),c={};for(const u of a){const d=n[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=n[u]?.[d],f=s[d]??n[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]??n[u];r[u]=d(p)}for(const u of a){r[u]={};const d=ke[u]||nt(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=nt(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 n=await be(),o=A.dirname(n);await I.mkdir(o,{recursive:!0}),await I.writeFile(n,ye.stringify(t),"utf8"),ko()},Fa=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]=qt([...d,...p]);continue}if(l&&l.compatible===!0){l||(t[a]={});const d=nt(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=nt(a);if(!d[c])throw new m(`Invalid config property: ${s}`);t[a]||(t[a]={}),t[a][c]=d[c](r)}}const n=await be(),o=A.dirname(n);await I.mkdir(o,{recursive:!0}),await I.writeFile(n,ye.stringify(t),"utf8"),ko()},Ga=async()=>{const e=await Oe();console.log(ye.stringify(e))},Ba=async()=>{console.log(await be())},nt=e=>({compatible:G("compatible"),stream:G("stream"),url:t=>t?(E(`${e}.url`,/^https?:\/\//.test(t),"Must be a valid URL"),t):"",path:t=>t||"",key:t=>t||"",envKey:t=>t||"",model:t=>t?(typeof t=="string"?t?.split(","):t).map(o=>o.trim()).filter(o=>!!o&&o.length>0):[],systemPrompt:i.systemPrompt,systemPromptPath:i.systemPromptPath,codeReviewPromptPath:i.codeReviewPromptPath,timeout:i.timeout,temperature:i.temperature,maxTokens:i.maxTokens,logging:i.logging,locale:i.locale,generate:i.generate,type:i.type,maxLength:i.maxLength,includeBody:i.includeBody,topP:i.topP,codeReview:i.codeReview,disabled:i.disabled,watchMode:i.watchMode,disableLowerCase:i.disableLowerCase,autoCopy:i.autoCopy,diffCompression:i.diffCompression,maxHunkLines:i.maxHunkLines,maxDiffLines:i.maxDiffLines,diffContext:i.diffContext}),_=e=>typeof e=="string"&&e.trim().length>0,Ha=()=>{try{const e=typeof At<"u"?At.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 Vt;const Ua=e=>ee(e)?(Vt===void 0&&(Vt=Ha()),Vt):!1,ee=e=>(Array.isArray(e.model)?e.model:_(e.model)?[e.model.trim()]:[]).length>0,ot=e=>{const t=_(e.key),n=_(e.region)||_(process.env.AWS_REGION)||_(process.env.AWS_DEFAULT_REGION),o=_(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 n&&(t||o||s)||(r&&t||a&&c)},le=(e,t)=>Object.entries(e).map(([n,o])=>[n,o]).filter(([n,o])=>!o.disabled).filter(([n,o])=>Ce.includes(n)||o.compatible===!0).filter(([n,o])=>{switch(t){case"commit":return n==="OLLAMA"?!!o&&ee(o):n==="COPILOT_SDK"?!!o&&Ua(o):n==="HUGGINGFACE"?!!o&&!!o.cookie:n==="BEDROCK"?ee(o)&&ot(o):!!o.key&&o.key.length>0;case"review":const s=e.codeReview||o.codeReview;return n==="OLLAMA"||n==="COPILOT_SDK"?!!o&&ee(o)&&s:n==="HUGGINGFACE"?!!o&&!!o.cookie&&s:n==="BEDROCK"?ee(o)&&ot(o)&&s:!!o.key&&o.key.length>0&&s;case"watch":const r=e.watchMode||o.watchMode;return n==="OLLAMA"||n==="COPILOT_SDK"?!!o&&ee(o)&&r:n==="HUGGINGFACE"?!!o&&!!o.cookie&&r:n==="BEDROCK"?ee(o)&&ot(o)&&r:o.compatible?!!o.url&&!!o.key&&r:!!o.key&&o.key.length>0&&r}}).map(([n])=>n);class Ka{static create(t,n){return new t(n)}}const Wa="stats.json",st=2,qa=30,Jt=()=>A.join(Ao,Wa),rt=async()=>{const e=Jt();if(!await Qe(e))return{version:st,metrics:[],selections:[]};try{const t=await I.readFile(e,"utf-8"),n=JSON.parse(t);return!n.version||n.version<st?{version:st,metrics:n.metrics||[],selections:n.selections||[]}:n}catch{return{version:st,metrics:[],selections:[]}}},za=(e,t)=>{const n=Date.now()-t*24*60*60*1e3;return{version:e.version,metrics:e.metrics.filter(o=>o.timestamp>=n),selections:e.selections.filter(o=>o.timestamp>=n)}},Lo=async(e,t)=>{const n=Jt(),o=A.dirname(n),s=t?za(e,t):e;await I.mkdir(o,{recursive:!0}),await I.writeFile(n,JSON.stringify(s,null,2),"utf-8")},Ya=async e=>{const t={timestamp:Date.now(),provider:e.provider,model:e.model,responseTimeMs:e.responseTimeMs,success:e.success,errorCode:e.errorCode,tokensUsed:e.tokensUsed},n=await rt();n.metrics.push(t),await Lo(n,e.statsDays)},Va=async e=>{const t={timestamp:Date.now(),provider:e.provider,model:e.model},n=await rt();n.selections.push(t),await Lo(n,e.statsDays)},Ja=(e,t,n)=>{const o=t.filter(u=>u.provider===e),s=n.filter(u=>u.provider===e);if(o.length===0)return{provider:e,totalRequests:0,successCount:0,failureCount:0,selectedCount:s.length,selectionRate:0,avgResponseTimeMs:0,minResponseTimeMs:0,maxResponseTimeMs:0};const r=o.filter(u=>u.success),a=o.map(u=>u.responseTimeMs),c=s.length,l=r.length>0?Math.min(100,Math.round(c/r.length*1e3)/10):0;return{provider:e,totalRequests:o.length,successCount:r.length,failureCount:o.length-r.length,selectedCount:c,selectionRate:l,avgResponseTimeMs:Math.round(a.reduce((u,d)=>u+d,0)/a.length),minResponseTimeMs:Math.min(...a),maxResponseTimeMs:Math.max(...a)}},Xa=async(e=qa)=>{const t=await rt(),n=Date.now()-e*24*60*60*1e3,o=t.metrics.filter(u=>u.timestamp>=n),s=t.selections.filter(u=>u.timestamp>=n);if(o.length===0)return{totalRequests:0,successRate:0,avgResponseTimeMs:0,providerStats:[],periodStart:n,periodEnd:Date.now()};const a=[...new Set(o.map(u=>u.provider))].map(u=>Ja(u,o,s)).sort((u,d)=>d.totalRequests-u.totalRequests),c=o.filter(u=>u.success).length,l=o.reduce((u,d)=>u+d.responseTimeMs,0);return{totalRequests:o.length,successRate:Math.round(c/o.length*1e3)/10,avgResponseTimeMs:Math.round(l/o.length),providerStats:a,periodStart:Math.min(...o.map(u=>u.timestamp)),periodEnd:Math.max(...o.map(u=>u.timestamp))}},Qa=async()=>{const e=Jt();await Qe(e)&&await I.unlink(e)},Za=async()=>(await rt()).metrics.length>0,Mo=(e,t)=>{const n=h.red.bold(`[${e}]`);return Ms({name:`${n} ${t}`,value:t,isError:!0,disabled:!0})},Oo=e=>{let t=!1;return Os({next:n=>{if(Object.assign(n,{provider:e.provider,model:e.model}),e.statsEnabled===!1||t)return;t=!0;const o=n.isError===!0,s={provider:e.provider,model:e.model,responseTimeMs:Date.now()-e.startTime,success:!o,errorCode:o?"REQUEST_ERROR":void 0,statsDays:e.statsDays};Ya(s).catch(()=>{})}})};class ec{constructor(){this.loaders=new Map,this.cache=new Map,this.loadService=async t=>{const n=this.cache.get(t);if(n)return n;const o=this.loaders.get(t);if(!o)return null;const s=await o();return this.cache.set(t,s),s},this.createService=async(t,n)=>{const o=await this.loadService(t);return o?new o(n):null},this.createRequest$=(t,n,o)=>{const s=Date.now(),r=Array.isArray(n.config.model)?n.config.model[0]:n.config.model;return Be(this.createService(t,n)).pipe(yn(a=>a?(o==="commit"?a.generateCommitMessage$():a.generateCodeReview$()).pipe(Oo({provider:t,model:r||"unknown",startTime:s,statsEnabled:n.statsEnabled,statsDays:n.statsDays})):Mo(t,"Invalid AI type")))},this.registerBuiltinProviders=()=>{this.loaders.set("OPENAI",()=>import("./openai.service-ccf2849b.mjs").then(t=>t.OpenAIService)),this.loaders.set("COPILOT_SDK",()=>import("./copilot-sdk.service-535a79bd.mjs").then(t=>t.CopilotSdkService)),this.loaders.set("OPENROUTER",()=>import("./openrouter.service-530df5cf.mjs").then(t=>t.OpenRouterService)),this.loaders.set("GEMINI",()=>import("./gemini.service-9918cef9.mjs").then(t=>t.GeminiService)),this.loaders.set("ANTHROPIC",()=>import("./anthropic.service-7e4eba3c.mjs").then(t=>t.AnthropicService)),this.loaders.set("HUGGINGFACE",()=>import("./hugging-face.service-ad52b657.mjs").then(t=>t.HuggingFaceService)),this.loaders.set("MISTRAL",()=>import("./mistral.service-13a13916.mjs").then(t=>t.MistralService)),this.loaders.set("CODESTRAL",()=>import("./codestral.service-87036f48.mjs").then(t=>t.CodestralService)),this.loaders.set("OLLAMA",()=>import("./ollama.service-874cae8a.mjs").then(t=>t.OllamaService)),this.loaders.set("COHERE",()=>import("./cohere.service-1e4bab5c.mjs").then(t=>t.CohereService)),this.loaders.set("GROQ",()=>import("./groq.service-02d64a85.mjs").then(t=>t.GroqService)),this.loaders.set("PERPLEXITY",()=>import("./perplexity.service-520a5b3c.mjs").then(t=>t.PerplexityService)),this.loaders.set("BEDROCK",()=>import("./bedrock.service-80ff2a63.mjs").then(t=>t.BedrockService)),this.loaders.set("GITHUB_MODELS",()=>import("./github-models.service-3ebf9c9c.mjs").then(t=>t.GitHubModelsService)),this.loaders.set("DEEPSEEK",()=>import("./deep-seek.service-c1232229.mjs").then(t=>t.DeepSeekService))},this.registerBuiltinProviders()}}const tc=new ec;class Xt{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":""}`}}const To="AICOMMIT2_MSG_FILE";class it extends Xt{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 C("git",["rev-parse","--show-toplevel"],{reject:!0});return t.trim()}catch(t){const n=t;if(n.code==="ENOENT")throw new m(`Git command not found!
|
|
22
|
+
|
|
23
|
+
Please install Git first: https://git-scm.com/downloads`);if(n.stderr){if(n.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(n.stderr.includes("permission denied"))throw new m(`Git permission denied: ${n.stderr.trim()}
|
|
27
|
+
|
|
28
|
+
Check file permissions and repository access.`)}throw new m(`Failed to verify Git repository: ${n.message||"Unknown error"}`)}}async getStagedDiff(t,n,o){const r=["diff","--cached","--diff-algorithm=minimal",o?.diffContext!==void 0?`-U${o.diffContext}`:`-U${we}`],a=[...t?t.map(this.excludeFromDiff):[],...n?n.map(this.excludeFromDiff):[]],c=[...this.filesToExclude,...a],[l,u,d]=await Promise.all([C("git",[...r,"--name-only",...c]),C("git",[...r,...c]),C("git",[...r,"--numstat",...a])]),p=l.stdout;if(!p)return null;const g=u.stdout,y=p.split(`
|
|
29
|
+
`).filter(Boolean),f=d.stdout,x=[],$=f.split(`
|
|
30
|
+
`).filter(Boolean);for(const v of $){const w=v.split(" ");w[0]==="-"&&w[1]==="-"&&w[2]&&x.push(w[2])}let S=g;if(x.length>0){g.trim()||(S=""),S+=`
|
|
31
|
+
|
|
32
|
+
--- Binary Files Changed ---
|
|
33
|
+
`;for(const v of x){const{stdout:w}=await C("git",["status","--porcelain",v]),k=w.substring(0,2).trim();S+=`Binary file ${v} ${k==="A"?"added":k==="M"?"modified":k==="D"?"deleted":"changed"}
|
|
34
|
+
`}}const P=[...new Set([...y,...x])];return{files:P,diff:S||`Files changed: ${P.join(", ")}`}}async getCommitDiff(t,n,o,s){const r=s?.diffContext!==void 0?`-U${s.diffContext}`:`-U${we}`,a=[...n?n.map(this.excludeFromDiff):[],...o?o.map(this.excludeFromDiff):[]],c=[...this.filesToExclude,...a],[l,u,d]=await Promise.all([C("git",["diff-tree","-r","--no-commit-id","--name-only",t,...c]),C("git",["show",r,t,"--",...c]),C("git",["diff-tree","-r","--numstat",t,...a])]),p=l.stdout;if(!p)return null;const g=u.stdout,y=d.stdout,f=[],x=y.split(`
|
|
35
|
+
`).filter(Boolean);for(const P of x){const v=P.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 P of f)$+=`Binary file ${P} changed
|
|
39
|
+
`}const S=[...new Set([...p.split(`
|
|
40
|
+
`).filter(Boolean),...f])];return{files:S,diff:$||`Files changed: ${S.join(", ")}`}}async commit(t,n=[],o={}){try{await C("git",["commit","-m",t,...n],{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 C("git",["config","--get","core.commentChar"]);return t}catch{return"#"}}async getRecentCommits(t=5,n){try{if(!n){const{stdout:a}=await C("git",["log","--format=%s",`-${t}`]);return a.trim()}const{stdout:o}=await C("git",["rev-parse",n]),s=o.trim(),{stdout:r}=await C("git",["log","--format=%H%x00%s",`-${t+1}`]);return r.split(`
|
|
52
|
+
`).map(a=>a.split("\0")).filter(([a])=>a&&a!==s).slice(0,t).map(([,a])=>a).join(`
|
|
53
|
+
`)}catch{return""}}async getBranchName(){try{const{stdout:t}=await C("git",["branch","--show-current"]),n=t.trim();if(!n){const{stdout:o}=await C("git",["rev-parse","--short","HEAD"]);return`HEAD@${o.trim()}`}return n}catch{return"HEAD"}}async getCommitMessage(t="HEAD"){try{const{stdout:n}=await C("git",["log","--format=%B","-n","1",t]);return n.trim()}catch{return""}}async rewriteCommit(t,n="HEAD"){try{if(n==="HEAD")await C("git",["commit","--amend","--only","--allow-empty","-m",t],{stdio:"inherit"});else{try{await C("git",["rev-parse","--verify",`${n}^`])}catch{throw new m(`Cannot rewrite the initial commit (${n}) via rebase.
|
|
54
|
+
|
|
55
|
+
Check out the commit and amend it directly, or use
|
|
56
|
+
\`git rebase --root -i\` manually.`)}try{await C("git",["diff-index","--quiet","HEAD","--"])}catch{throw new m(`Working tree has uncommitted changes.
|
|
57
|
+
|
|
58
|
+
Stash or commit them before rewriting a non-HEAD commit:
|
|
59
|
+
git stash push -u
|
|
60
|
+
# ... run rewrite ...
|
|
61
|
+
git stash pop`)}const{stdout:o}=await C("git",["rev-list","--merges","--count",`${n}^..HEAD`]);if(parseInt(o.trim(),10)>0)throw new m(`Cannot rewrite ${n}: the rebase range contains merge commits.
|
|
62
|
+
|
|
63
|
+
Rewriting via \`git rebase -i\` would linearize history and drop the merges.
|
|
64
|
+
Reword the merge commit directly with \`git commit --amend\` (if HEAD) or
|
|
65
|
+
use \`git rebase -i --rebase-merges\` manually.`);const{stdout:s}=await C("git",["rev-parse","--short",n]),r=s.trim(),a=A.join(ue.tmpdir(),`aicommit2-rewrite-msg-${yt.randomBytes(8).toString("hex")}.txt`);O.writeFileSync(a,t,"utf8");const c=process.platform==="darwin"?"sed -i ''":"sed -i";try{await C("git",["rebase","-i",`${n}^`,"--keep-empty"],{env:{...process.env,[To]:a,GIT_SEQUENCE_EDITOR:`${c} 's/^pick ${r}/reword ${r}/'`,GIT_EDITOR:`sh -c 'cp "$${To}" "$1"' --`},stdio:"inherit"})}finally{try{O.unlinkSync(a)}catch{}}}}catch(o){const s=o;throw s.stderr?s.stderr.includes("Author identity unknown")?new m(`Git author identity not configured.
|
|
66
|
+
|
|
67
|
+
Configure with:
|
|
68
|
+
git config --global user.name "Your Name"
|
|
69
|
+
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: ${n}.
|
|
70
|
+
|
|
71
|
+
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:n}=await C("git",["branch","-r","--contains",t]);return n.trim().length>0}catch{return!1}}}class Qt extends Xt{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 C("jj",["--version"],{reject:!0});process.env.DEBUG&&console.log(`Jujutsu version: ${t}`)}catch(t){const n=t;throw n.code==="ENOENT"?new m(`Jujutsu (jj) command not found!
|
|
72
|
+
|
|
73
|
+
Please install Jujutsu:
|
|
74
|
+
- macOS: brew install jj
|
|
75
|
+
- Linux: cargo install jj-cli
|
|
76
|
+
- Windows: cargo install jj-cli
|
|
77
|
+
- See: https://github.com/jj-vcs/jj#installation`):new m(`Failed to execute jj command: ${n.message}`)}try{const{stdout:t,stderr:n}=await C("jj",["workspace","root"],{reject:!0}),o=t.trim();if(!o)throw new m("jj workspace root returned empty path");const s=A.join(o,".jj");if(!O.existsSync(s))throw new m(`Jujutsu repository directory not found at ${s}
|
|
78
|
+
|
|
79
|
+
Initialize a jj repository with: jj init`);return o}catch(t){if(t instanceof m)throw t;const n=t;throw n.stderr?n.stderr.includes("not in a jj repo")?new m(`Not in a Jujutsu repository!
|
|
80
|
+
|
|
81
|
+
Initialize with: jj init
|
|
82
|
+
Or navigate to an existing jj repository.`):n.stderr.includes("No workspace found")?new m(`No Jujutsu workspace found!
|
|
83
|
+
|
|
84
|
+
This may be a bare repository. Navigate to a workspace directory.`):new m(`Jujutsu error: ${n.stderr.trim()}`):new m(`Failed to verify Jujutsu repository: ${n.message||"Unknown error"}`)}}async getStagedDiff(t,n,o){try{const{stdout:s}=await C("jj",["status","--no-pager"]);if(process.env.DEBUG&&(console.log("jj status output:",JSON.stringify(s)),console.log("excludeFiles:",t),console.log("exclude:",n)),s.includes("No changes.")||s.includes("The working copy is clean"))return null;const r=this.filesToExclude.map(this.excludeFromDiff),a=[...t?t.map(this.excludeFromDiff):[],...n?n.map(this.excludeFromDiff):[]],c=[...r,...a];let l="all()";c.length>0&&(l=`all() & ${c.join(" & ")}`);const u=["diff","--name-only"],d=["diff","--git"];c.length>0&&(u.push(l),d.push(l)),process.env.DEBUG&&(console.log("jj diff command with fileset:",u),console.log("fileset expression:",l));const{stdout:p}=await C("jj",u);if(process.env.DEBUG&&console.log("jj diff --name-only output:",JSON.stringify(p)),!p.trim())return null;const{stdout:g}=await C("jj",d),{stdout:y}=await C("jj",["status","--no-pager"]),f=p.split(`
|
|
85
|
+
`).filter(Boolean),x=[],$=y.split(`
|
|
86
|
+
`);for(const v of $)if(v.includes("(binary)")||v.includes("Binary file")){const w=v.match(/([^\s]+)\s*\(binary\)/);w&&w[1]&&x.push(w[1])}let S=g;if(x.length>0){S+=`
|
|
87
|
+
|
|
88
|
+
--- Binary Files Changed ---
|
|
89
|
+
`;for(const v of x)S+=`Binary file ${v} changed
|
|
90
|
+
`}const P=[...new Set([...f,...x])];return{files:P,diff:S||`Files changed: ${P.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()}
|
|
91
|
+
|
|
92
|
+
Try: jj status --no-pager`);if(r.stderr.includes("Invalid revision"))throw new m(`Jujutsu revision error: ${r.stderr.trim()}
|
|
93
|
+
|
|
94
|
+
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}
|
|
95
|
+
stderr: ${r.stderr}
|
|
96
|
+
exitCode: ${r.exitCode}`);return null}}async getCommitDiff(t,n,o,s){const r=[...n?n.map(this.excludeFromDiff):[],...o?o.map(this.excludeFromDiff):[]];try{const a=["diff","--name-only","--revision",t],c=["diff","--git","--revision",t];if(r.length>0){const p=`all() & ${r.join(" & ")}`;a.push(p),c.push(p),process.env.DEBUG&&console.log("jj getCommitDiff fileset expression:",p)}const{stdout:l}=await C("jj",a);if(!l.trim())return null;const{stdout:u}=await C("jj",c),d=l.split(`
|
|
97
|
+
`).filter(Boolean);return{files:d,diff:u||`Files changed: ${d.join(", ")}`}}catch(a){if(process.env.DEBUG){const c=a;console.log("jj getCommitDiff error:",c.message,c.stderr)}return null}}async commit(t,n=[],o={}){try{await C("jj",["describe","-m",t,...n],{stdio:"inherit"}),o.autoNew&&await C("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.
|
|
98
|
+
|
|
99
|
+
Provide a meaningful commit message.`):r.stderr.includes("No changes to commit")?new m(`No changes to commit.
|
|
100
|
+
|
|
101
|
+
Make some changes first, then try again.`):r.stderr.includes("Invalid revision")?new m(`Jujutsu commit error: ${r.stderr.trim()}
|
|
102
|
+
|
|
103
|
+
Ensure you're in a valid workspace with changes.`):r.stderr.includes("Operation not allowed")?new m(`Jujutsu operation not allowed: ${r.stderr.trim()}
|
|
104
|
+
|
|
105
|
+
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 C("jj",["config","get","ui.comment-char"]);return t.trim()||"#"}catch{return"#"}}async getRecentCommits(t=5,n){try{const{stdout:o}=await C("jj",["log","--limit",t.toString(),"--no-graph","-T",'description.first_line() ++ "\\n"']);return o.trim()}catch{return""}}async getBranchName(){try{const{stdout:t}=await C("jj",["bookmark","list","--revisions","@"]);if(t.trim()){const s=t.split(`
|
|
106
|
+
`)[0].split(":")[0].trim();if(s)return s}const{stdout:n}=await C("jj",["log","-r","@","--no-graph","-T","change_id.short()"]);return n.trim()||"HEAD"}catch{return"HEAD"}}}class Zt extends Xt{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 C("yadm",["rev-parse","--show-toplevel"],{reject:!0}),n=t.trim(),o=process.env.HOME||process.env.USERPROFILE;if(!o)throw new m("HOME environment variable not set. Cannot determine YADM repository.");const s=await import("path"),r=s.resolve(n),a=s.resolve(o);if(r!==a)throw new m(`Not a YADM repository (work tree is not $HOME).
|
|
107
|
+
|
|
108
|
+
YADM work tree: ${r}
|
|
109
|
+
Expected: ${a}
|
|
110
|
+
|
|
111
|
+
This appears to be a regular Git repository.`);const{stdout:c}=await C("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").
|
|
112
|
+
|
|
113
|
+
Git directory: ${l}
|
|
114
|
+
|
|
115
|
+
This appears to be a regular Git repository.`);return n}catch(t){if(t instanceof m)throw t;const n=t;if(n.code==="ENOENT")throw new m(`YADM command not found!
|
|
116
|
+
|
|
117
|
+
Please install YADM first: https://yadm.io/`);if(n.stderr){if(n.stderr.includes("not a git repository"))throw new m(`Not in a YADM repository!
|
|
118
|
+
|
|
119
|
+
Initialize with: yadm init
|
|
120
|
+
Or clone your dotfiles: yadm clone <url>`);if(n.stderr.includes("permission denied"))throw new m(`YADM permission denied: ${n.stderr.trim()}
|
|
121
|
+
|
|
122
|
+
Check file permissions and repository access.`)}throw new m(`Failed to verify YADM repository: ${n.message||"Unknown error"}`)}}async getStagedDiff(t,n,o){const r=["diff","--cached","--diff-algorithm=minimal",o?.diffContext!==void 0?`-U${o.diffContext}`:`-U${we}`],a=[...t?t.map(this.excludeFromDiff):[],...n?n.map(this.excludeFromDiff):[]],c=[...this.filesToExclude,...a],[l,u,d]=await Promise.all([C("yadm",[...r,"--name-only",...c]),C("yadm",[...r,...c]),C("yadm",[...r,"--numstat",...a])]),p=l.stdout;if(!p)return null;const g=u.stdout,y=p.split(`
|
|
123
|
+
`).filter(Boolean),f=d.stdout,x=[],$=f.split(`
|
|
124
|
+
`).filter(Boolean);for(const v of $){const w=v.split(" ");w[0]==="-"&&w[1]==="-"&&w[2]&&x.push(w[2])}let S=g;if(x.length>0){g.trim()||(S=""),S+=`
|
|
125
|
+
|
|
126
|
+
--- Binary Files Changed ---
|
|
127
|
+
`;for(const v of x){const{stdout:w}=await C("yadm",["status","--porcelain",v]),k=w.substring(0,2).trim();S+=`Binary file ${v} ${k==="A"?"added":k==="M"?"modified":k==="D"?"deleted":"changed"}
|
|
128
|
+
`}}const P=[...new Set([...y,...x])];return{files:P,diff:S||`Files changed: ${P.join(", ")}`}}async getCommitDiff(t,n,o,s){const r=s?.diffContext!==void 0?`-U${s.diffContext}`:`-U${we}`,a=[...n?n.map(this.excludeFromDiff):[],...o?o.map(this.excludeFromDiff):[]],c=[...this.filesToExclude,...a],[l,u,d]=await Promise.all([C("yadm",["diff-tree","-r","--no-commit-id","--name-only",t,...c]),C("yadm",["show",r,t,"--",...c]),C("yadm",["diff-tree","-r","--numstat",t,...a])]),p=l.stdout;if(!p)return null;const g=u.stdout,y=d.stdout,f=[],x=y.split(`
|
|
129
|
+
`).filter(Boolean);for(const P of x){const v=P.split(" ");v[0]==="-"&&v[1]==="-"&&v[2]&&f.push(v[2])}let $=g;if(f.length>0){g.trim()||($=""),$+=`
|
|
130
|
+
|
|
131
|
+
--- Binary Files Changed ---
|
|
132
|
+
`;for(const P of f)$+=`Binary file ${P} changed
|
|
133
|
+
`}const S=[...new Set([...p.split(`
|
|
134
|
+
`).filter(Boolean),...f])];return{files:S,diff:$||`Files changed: ${S.join(", ")}`}}async commit(t,n=[],o={}){try{await C("yadm",["commit","-m",t,...n],{stdio:"inherit"})}catch(s){const r=s;throw r.stderr?r.stderr.includes("nothing to commit")?new m(`Nothing to commit.
|
|
135
|
+
|
|
136
|
+
Stage your changes with: yadm add <file>
|
|
137
|
+
Or stage tracked file modifications: aicommit2 --all
|
|
138
|
+
|
|
139
|
+
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.
|
|
140
|
+
|
|
141
|
+
Provide a meaningful commit message.`):r.stderr.includes("Author identity unknown")?new m(`YADM author identity not configured.
|
|
142
|
+
|
|
143
|
+
Configure with:
|
|
144
|
+
yadm config --global user.name "Your Name"
|
|
145
|
+
yadm config --global user.email "your.email@example.com"`):r.stderr.includes("Permission denied")?new m(`YADM permission error: ${r.stderr.trim()}
|
|
146
|
+
|
|
147
|
+
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 C("yadm",["config","--get","core.commentChar"]);return t}catch{return"#"}}async getRecentCommits(t=5,n){try{const{stdout:o}=await C("yadm",["log","--format=%s",`-${t}`]);return o.trim()}catch{return""}}async getBranchName(){try{const{stdout:t}=await C("yadm",["branch","--show-current"]),n=t.trim();if(!n){const{stdout:o}=await C("yadm",["rev-parse","--short","HEAD"]);return`HEAD@${o.trim()}`}return n}catch{return"HEAD"}}}let en=null;const nc=async()=>{const e=process.argv.includes("--git"),t=process.argv.includes("--yadm"),n=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.
|
|
148
|
+
${f instanceof Error?f.message:String(f)}`)}if(t)try{const f=new Zt;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.
|
|
149
|
+
${f instanceof Error?f.message:String(f)}`)}if(n)try{const f=new Qt;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.
|
|
150
|
+
${f instanceof Error?f.message:String(f)}`)}const o=process.env.FORCE_GIT==="true",s=process.env.FORCE_YADM==="true",r=process.env.FORCE_JJ==="true";if(o)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.
|
|
151
|
+
${f instanceof Error?f.message:String(f)}`)}if(s)try{const f=new Zt;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.
|
|
152
|
+
${f instanceof Error?f.message:String(f)}`)}if(r)try{const f=new Qt;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.
|
|
153
|
+
${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.
|
|
154
|
+
${f instanceof Error?f.message:String(f)}`)}const[c,l,u]=await Promise.allSettled([(async()=>{const f=new Qt;return await f.assertRepo(),f})(),(async()=>{const f=new it;return await f.assertRepo(),f})(),(async()=>{const f=new Zt;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.
|
|
155
|
+
|
|
156
|
+
Jujutsu Error:
|
|
157
|
+
${p}
|
|
158
|
+
|
|
159
|
+
Git Error:
|
|
160
|
+
${g}
|
|
161
|
+
|
|
162
|
+
YADM Error:
|
|
163
|
+
${y}
|
|
164
|
+
|
|
165
|
+
Solutions:
|
|
166
|
+
\u2022 Initialize a Jujutsu repository: jj init
|
|
167
|
+
\u2022 Initialize a Git repository: git init
|
|
168
|
+
\u2022 Initialize a YADM repository: yadm init (or yadm clone <url>)
|
|
169
|
+
\u2022 Navigate to an existing Jujutsu, Git, or YADM repository
|
|
170
|
+
\u2022 Set FORCE_GIT="true" environment variable to force Git detection
|
|
171
|
+
\u2022 Set forceGit=true in config file to prefer Git detection`)},J=async()=>(en||(en=await nc()),en);let Te=null;const Do=async()=>{if(Te!==null)return Te;try{Te=(await Z({})).diffContext}catch{Te=we}return Te},tn=(e,t)=>{const{diff:n,stats:o}=ga(e.diff,t);return n===e.diff?e:{...e,diff:n,compression:o}},at=async()=>(await J()).assertRepo(),nn=async(e,t)=>{const n=await J(),o=await Do(),s=await n.getStagedDiff(e,t,{diffContext:o});return s||null},No=async(e,t,n)=>{const o=await J();if(!o.getCommitDiff)throw new m(`Commit diff not supported for ${o.name}`);const s=await Do(),r=await o.getCommitDiff(e,t,n,{diffContext:s});return r||null},oc=async()=>(await J()).getCommentChar(),sc=e=>{const t=e.files.length.toLocaleString(),n=e.files.length>1?"s":"",o=e.diff.length.toLocaleString();return`Detected ${t} changed file${n} (${o} characters)`},De=async()=>(await J()).name,rc=async(e,t,n)=>{await(await J()).commit(e,t||[],n)},Ne=async()=>(await J()).getBranchName(),_e=async(e=5,t)=>(await J()).getRecentCommits(e,t),ic=async(e,t="HEAD")=>{const n=await J();if(!n.rewriteCommit)throw new m(`Rewrite is not supported for ${n.name} repositories. Only Git is supported.`);await n.rewriteCommit(e,t)},ac=async(e="HEAD")=>{const t=await J();return t.getCommitMessage?t.getCommitMessage(e):""},cc=async(e="HEAD")=>{const t=await J();return t.isCommitPushed?t.isCommitPushed(e):!1};class je{constructor(t,n,o="",s=""){this.config=t,this.stagedDiff=n,this.branchName=o,this.recentCommits=s,this.getDiffForModel=r=>{const a={mode:r.diffCompression||"none",maxHunkLines:r.maxHunkLines||0,maxDiffLines:r.maxDiffLines||0};return tn(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(wn(c=>this.createProviderRequests$(c,a)),Ts(c=>Mo("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(wn(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 tc.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-62ff73b7.mjs")).pipe(yn(({OpenAICompatibleService:p})=>{const g=Ka.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(Oo({provider:u,model:a,startTime:l,statsEnabled:this.config.useStats,statsDays:this.config.statsDays}))}))}}}const lc=1e5;class B{constructor(){this.title="aicommit2",this.formatCompressionStats=t=>{if(!t||t.originalChars===t.compressedChars)return null;const n=Math.round((1-t.compressedChars/t.originalChars)*100);return`[compact: ${t.originalChars.toLocaleString()} \u2192 ${t.compressedChars.toLocaleString()} chars, ${n}% saved]`},this.formatBytes=t=>t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:`${(t/(1024*1024)).toFixed(1)} MB`}printTitle(){try{const t=vn.textSync(this.title,{font:"Small Slant"}),n=_s(["#8B5CF6","#A020F0","#D946EF"]);console.log(h.bold(n.multiline(t)))}catch{console.log(h.bold(vn.textSync(this.title,{font:"Small Slant"})))}}showLoader(t){if(this.loader){this.loader.text=t;return}this.loader=An(t).start()}stopLoader(){this.loader?.stop(),this.loader=void 0}displaySpinner(t){return An(t).start()}stopSpinner(t){t.stop(),t.clear()}printStagedFiles(t,n){const o=Buffer.byteLength(t.diff,"utf8"),s=this.formatBytes(o),r=sc(t),a=this.formatCompressionStats(n);console.log(h.bold.green("\u2714 ")+h.bold(r)+h.dim(` (${s})`)+(a?h.cyan(` ${a}`):"")+h.bold(":")),console.log(`${t.files.map(l=>` ${l}`).join(`
|
|
172
|
+
`)}
|
|
173
|
+
`),o>lc&&!n&&(console.log(h.yellow(`\u26A0 Large diff detected (${s}). This may increase processing time and costs.`)),console.log(h.dim(` Consider using --exclude to filter large files or diffCompression=compact.
|
|
174
|
+
`)))}printAnalyzed(){console.log(`
|
|
175
|
+
${h.bold.green("\u2714")} ${h.bold("Changes analyzed")}`)}printCommitted(){console.log(`
|
|
176
|
+
${h.bold.green("\u2714")} ${h.bold("Successfully committed!")}`)}printCopied(){console.log(`
|
|
177
|
+
${h.bold.green("\u2714")} ${h.bold("Successfully copied! Press 'Ctrl + V' to paste")}`)}printSavedCommitMessage(){console.log(`
|
|
178
|
+
${h.bold.green("\u2714")} ${h.bold("Saved commit message")}`)}printCancelledCommit(){console.log(`
|
|
179
|
+
${h.bold.yellow("\u26A0")} ${h.yellow("Commit cancelled")}`)}printError(t){console.log(`
|
|
180
|
+
${h.bold.red("\u2716")} ${h.red(`${t}`)}`)}printWarning(t){console.log(`
|
|
181
|
+
${h.bold.yellow("\u26A0")} ${h.yellow(`${t}`)}`)}printSuccess(t){console.log(`
|
|
182
|
+
${h.bold.green("\u2714")} ${h.green(`${t}`)}`)}printInfo(t){console.log(`
|
|
183
|
+
${h.bold.blue("\u2139")} ${h.blue(`${t}`)}`)}printSetupGitEvent(t){console.log(`
|
|
184
|
+
${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,_o="info";async function lt(e){if(ct){console.warn("Logger already initialized. Skipping re-initialization.");return}const t=e?.logLevel||"info";_o=t;const n=e?.logFilePath||So,o=e?.exceptionLogFilePath||xo,s=e?.logging??!0;await bo(A.dirname(n)),await bo(A.dirname(o));const r=[];s?r.push(new K.transports.DailyRotateFile({filename:n,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:o,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,n)=>{if(!ct)throw new Error("Logger not initialized. Call initializeLogger() first.");return Reflect.get(ct,t,n)}});function jo(){const e=K.config.npm.levels;return(e[_o]??e.info)>=e.verbose}const Fo={isLoading:!1,startOption:{text:"AI is analyzing your changes"}},Go={isLoading:!1,startOption:{text:"AI is performing a code review"}},on="No commit messages were generated",Bo="No code reviews were generated",sn={type:"reactiveListPrompt",name:"aicommit2Prompt",message:"Pick a commit message to use: ",emptyMessage:`\u26A0 ${on}`,loop:!1,descPageSize:15,showDescription:!0,pickKey:"short",isDescriptionDim:!0,stopMessage:"Changes analyzed"};class ut{constructor(t){this.choices$=new Cn([]),this.destroyed$=new Ds(1),this.stopMessage="Changes analyzed",this.isDestroyed=!1,this.subscriptions=new bt,this.inquirerInstance=null,this.loader$=new Cn(t)}addSubscription(t){if(this.isDestroyed){t.unsubscribe();return}this.subscriptions.add(t)}initPrompt(t=sn){return this.stopMessage=t.stopMessage,T.registerPrompt("reactiveListPrompt",js),this.inquirerInstance=T.prompt({choices$:this.choices$,loader$:this.loader$,...t}),this.inquirerInstance}startLoader(){this.loader$.next({isLoading:!0})}updateLoaderText(t){this.isDestroyed||this.loader$.next({isLoading:!0,startOption:{text:t}})}clearLoader(){this.inquirerInstance&&this.loader$.next({isLoading:!1,clear:!0})}refreshChoices(t){if(this.isDestroyed||!t)return;const n=t.streamKey;if(n){if(!t.value){this.removeStreamingChoice(n);return}const o=[...this.currentChoices],s=o.findIndex(r=>r.streamKey===n);if(s>=0){o[s]=t,this.choices$.next(o);return}this.choices$.next([...this.currentChoices,t].sort(Eo));return}t.value&&this.choices$.next([...this.currentChoices,t].sort(Eo))}removeStreamingChoice(t){if(this.isDestroyed)return;const n=this.currentChoices.filter(o=>o.streamKey!==t);this.choices$.next(n)}checkErrorOnChoices(t=!0){if(this.choices$.getValue().map(s=>s).filter(s=>!s.streamKey).every(s=>s?.isError||s?.disabled)){this.alertNoGeneratedMessage(),this.logEmptyCommitMessage(),t&&process.exit(1);return}this.stopLoaderOnSuccess()}completeSubject(){try{this.destroyed$.next(!0),this.destroyed$.complete(),this.choices$.closed||this.choices$.complete(),this.loader$.closed||this.loader$.complete()}catch(t){console.warn("Error completing subjects:",t)}}closeInquirerInstance(){if(!this.inquirerInstance)return;const t=this.inquirerInstance.ui;t?.rl&&!t.rl.closed&&t.close()}cancel(){this.inquirerInstance?.ui?.activePrompt&&this.inquirerInstance.ui.activePrompt.abortPrompt()}destroy(){if(!this.isDestroyed){this.isDestroyed=!0;try{this.cancel(),this.closeInquirerInstance(),this.subscriptions.unsubscribe(),this.completeSubject()}catch(t){jo()&&console.warn("Error during ReactivePromptManager destruction:",t)}finally{this.inquirerInstance=null}}}alertNoGeneratedMessage(){this.loader$.next({isLoading:!1,message:on,stopOption:{doneFrame:"\u26A0",color:"yellow"}})}stopLoaderOnSuccess(){this.loader$.next({isLoading:!1,message:this.stopMessage})}logEmptyCommitMessage(){console.log(`
|
|
185
|
+
${h.bold.yellow("\u26A0")} ${h.yellow(`${on}`)}`)}get currentChoices(){return this.choices$.getValue().map(t=>t)}}const b={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 ${b.highlight(t)}.`,"",`${b.label("\u2192")} Run: ${b.command(`aicommit2 config set ${t}.key=YOUR_API_KEY`)}`].join(`
|
|
186
|
+
`)},invalidApiKey:e=>{const t=e.toUpperCase();return[`Invalid or expired API key for ${b.highlight(t)}.`,"",`${b.label("\u2192")} Update: ${b.command(`aicommit2 config set ${t}.key=YOUR_NEW_KEY`)}`].join(`
|
|
187
|
+
`)},noApiKeysConfigured:()=>["No AI provider API keys configured.","",`${b.label("\u2192")} Please set at least one API key:`,` ${b.command("aicommit2 config set OPENAI.key=sk-...")}`,` ${b.command("aicommit2 config set ANTHROPIC.key=sk-ant-...")}`,` ${b.command("aicommit2 config set OLLAMA.model=llama3.2")} ${b.dim("(no key needed)")}`,"",`${b.hint("Tip:")} ${b.command("aicommit2 config get")} ${b.hint("to see current config")}`].join(`
|
|
188
|
+
`),rateLimited:e=>[`Rate limit exceeded${e?` for ${b.highlight(e)}`:""}.`,"",`${b.label("\u2192")} Wait a moment and try again`,`${b.label("\u2192")} Or use a different AI provider`].join(`
|
|
189
|
+
`),quotaExceeded:e=>[`API quota exceeded${e?` for ${b.highlight(e)}`:""}.`,"",`${b.label("\u2192")} Upgrade your API plan or wait for reset`].join(`
|
|
190
|
+
`),modelNotFound:(e,t)=>{const n=t.toUpperCase();return[`Model ${b.highlight(`"${e}"`)} not found for ${b.highlight(n)}.`,"",`${b.label("\u2192")} Update: ${b.command(`aicommit2 config set ${n}.model=VALID_MODEL`)}`].join(`
|
|
191
|
+
`)},modelAccessDenied:(e,t)=>[`Access denied to model ${b.highlight(`"${e}"`)} on ${b.highlight(t)}.`,"",`${b.label("\u2192")} Check API access or upgrade your plan`].join(`
|
|
192
|
+
`),networkError:e=>[`Network connection failed${e?` to ${b.highlight(e)}`:""}.`,"",`${b.label("\u2192")} Check internet connectivity and try again`].join(`
|
|
193
|
+
`),timeout:(e,t)=>{const n=t?` from ${b.highlight(t)}`:"",o=Math.round(e*1.5);return[`Request timed out${n} after ${e}ms.`,"",`${b.label("\u2192")} Increase: ${b.command(`aicommit2 config set timeout=${o}`)}`].join(`
|
|
194
|
+
`)},serviceUnavailable:e=>[`${b.highlight(e)} service is temporarily unavailable.`,"",`${b.label("\u2192")} Try again in a few minutes`].join(`
|
|
195
|
+
`),noStagedChanges:e=>{const t=e.toLowerCase()==="jujutsu"?"jj":e.toLowerCase()==="yadm"?"yadm add":"git add";return[`No staged changes found in ${b.highlight(e)} repository.`,"",`${b.label("\u2192")} Stage: ${b.command(`${t} <files>`)}`,`${b.label("\u2192")} Or use: ${b.command("aicommit2 --all")}`].join(`
|
|
196
|
+
`)},emptyCommitMessage:()=>"Commit message cannot be empty.",vcsNotFound:e=>{const n={git:"https://git-scm.com/downloads",yadm:"https://yadm.io/docs/install",jujutsu:"https://github.com/jj-vcs/jj#installation"}[e.toLowerCase()]||"";return[`${b.highlight(e)} is not installed or not found in PATH.`,"",n?`${b.label("\u2192")} Install: ${b.command(n)}`:""].filter(Boolean).join(`
|
|
197
|
+
`)},notInRepository:e=>[`Not in a ${b.highlight(e)} repository.`,"",`${b.label("\u2192")} Init: ${b.command(`${e.toLowerCase()} init`)}`].join(`
|
|
198
|
+
`),invalidConfigFormat:e=>[`Invalid configuration format for ${b.highlight(`"${e}"`)}`,"",`${b.label("\u2192")} Use: ${b.command("aicommit2 config set PROVIDER.key=value")}`].join(`
|
|
199
|
+
`),invalidConfigValue:(e,t)=>[`Invalid value for ${b.highlight(`"${e}"`)}`,"",`${b.label("\u2192")} Expected: ${b.dim(t)}`].join(`
|
|
200
|
+
`),serverError:(e,t)=>{const n=t?` ${b.dim(`(HTTP ${t})`)}`:"";return`${b.highlight(e)} server error${n}. Try again later.`},ollamaNotRunning:()=>[`${b.highlight("Ollama")} is not running or not accessible.`,"",`${b.label("\u2192")} Start: ${b.command("ollama serve")}`].join(`
|
|
201
|
+
`),ollamaModelNotPulled:e=>[`Ollama model ${b.highlight(`"${e}"`)} is not available locally.`,"",`${b.label("\u2192")} Pull: ${b.command(`ollama pull ${e}`)}`].join(`
|
|
202
|
+
`)},uc=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,dc=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}`},mc=(e,t={})=>{const{provider:n="AI",model:o,timeout:s}=t;switch(e){case R.MISSING_API_KEY:return z.missingApiKey(n);case R.INVALID_API_KEY:case R.AUTH_FAILED:return z.invalidApiKey(n);case R.RATE_LIMITED:return z.rateLimited(n);case R.QUOTA_EXCEEDED:return z.quotaExceeded(n);case R.MODEL_NOT_FOUND:return z.modelNotFound(o||"unknown",n);case R.MODEL_ACCESS_DENIED:return z.modelAccessDenied(o||"unknown",n);case R.NETWORK_ERROR:return z.networkError(n);case R.TIMEOUT:return z.timeout(s||1e4,n);case R.SERVICE_UNAVAILABLE:return z.serviceUnavailable(n);case R.SERVER_ERROR:return z.serverError(n);default:return z.unknown(n)}},Ho={locale:"en",maxLength:50,type:"conventional",generate:1,systemPrompt:"",systemPromptPath:"",codeReviewPromptPath:"",vcs_branch:"",isReasoning:!1},Uo={"":"<commit message>",conventional:`<type>(<optional scope>): <description>
|
|
203
|
+
|
|
204
|
+
[optional body]
|
|
205
|
+
|
|
206
|
+
[optional footer(s)]`,gitmoji:`:<emoji>:(<optional scope>): <description>
|
|
207
|
+
|
|
208
|
+
[optional body]
|
|
209
|
+
|
|
210
|
+
[optional footer(s)]`},Ko={"":"",gitmoji:`
|
|
211
|
+
${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(`
|
|
212
|
+
`)}`,conventional:`
|
|
213
|
+
${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(`
|
|
214
|
+
`)}`},rn=(e,t)=>e.replace(/{(\w+)}/g,(n,o)=>t[o]?.toString()||Ho[o]?.toString()),fc=(e,t)=>{const n=t.split("-")[0].toLowerCase(),o={conventional:{en:{subject:"fix(auth): fix bug in user authentication process",body:"- Update login function to handle edge cases\\n- Add additional error logging for debugging"},zh:{subject:"fix(auth): \u4FEE\u590D\u7528\u6237\u8BA4\u8BC1\u8FC7\u7A0B\u4E2D\u7684\u9519\u8BEF",body:"- \u66F4\u65B0\u767B\u5F55\u51FD\u6570\u4EE5\u5904\u7406\u8FB9\u7F18\u60C5\u51B5\\n- \u6DFB\u52A0\u989D\u5916\u7684\u9519\u8BEF\u65E5\u5FD7\u7528\u4E8E\u8C03\u8BD5"},ja:{subject:"fix(auth): \u30E6\u30FC\u30B6\u30FC\u8A8D\u8A3C\u30D7\u30ED\u30BB\u30B9\u306E\u30D0\u30B0\u3092\u4FEE\u6B63",body:"- \u30A8\u30C3\u30B8\u30B1\u30FC\u30B9\u3092\u51E6\u7406\u3059\u308B\u305F\u3081\u306B\u30ED\u30B0\u30A4\u30F3\u6A5F\u80FD\u3092\u66F4\u65B0\\n- \u30C7\u30D0\u30C3\u30B0\u7528\u306E\u8FFD\u52A0\u30A8\u30E9\u30FC\u30ED\u30B0\u3092\u8FFD\u52A0"},ko:{subject:"fix(auth): \uC0AC\uC6A9\uC790 \uC778\uC99D \uD504\uB85C\uC138\uC2A4\uC758 \uBC84\uADF8 \uC218\uC815",body:"- \uC5E3\uC9C0 \uCF00\uC774\uC2A4\uB97C \uCC98\uB9AC\uD558\uB3C4\uB85D \uB85C\uADF8\uC778 \uD568\uC218 \uC5C5\uB370\uC774\uD2B8\\n- \uB514\uBC84\uAE45\uC744 \uC704\uD55C \uCD94\uAC00 \uC624\uB958 \uB85C\uAE45 \uCD94\uAC00"},es:{subject:"fix(auth): corregir error en el proceso de autenticaci\xF3n",body:"- Actualizar funci\xF3n de inicio de sesi\xF3n para manejar casos extremos\\n- Agregar registro de errores adicional para depuraci\xF3n"},fr:{subject:"fix(auth): corriger un bug dans le processus d'authentification",body:"- Mettre \xE0 jour la fonction de connexion pour g\xE9rer les cas limites\\n- Ajouter une journalisation d'erreurs suppl\xE9mentaire pour le d\xE9bogage"},de:{subject:"fix(auth): Fehler im Benutzerauthentifizierungsprozess beheben",body:"- Login-Funktion aktualisiert, um Randf\xE4lle zu behandeln\\n- Zus\xE4tzliche Fehlerprotokollierung f\xFCr Debugging hinzugef\xFCgt"}},gitmoji:{en:{subject:":sparkles: Add real-time chat feature",body:"- Implement WebSocket connection\\n- Add message encryption\\n- Include typing indicators"},zh:{subject:":sparkles: \u6DFB\u52A0\u5B9E\u65F6\u804A\u5929\u529F\u80FD",body:"- \u5B9E\u73B0WebSocket\u8FDE\u63A5\\n- \u6DFB\u52A0\u6D88\u606F\u52A0\u5BC6\\n- \u5305\u542B\u8F93\u5165\u6307\u793A\u5668"},ja:{subject:":sparkles: \u30EA\u30A2\u30EB\u30BF\u30A4\u30E0\u30C1\u30E3\u30C3\u30C8\u6A5F\u80FD\u3092\u8FFD\u52A0",body:"- WebSocket\u63A5\u7D9A\u3092\u5B9F\u88C5\\n- \u30E1\u30C3\u30BB\u30FC\u30B8\u6697\u53F7\u5316\u3092\u8FFD\u52A0\\n- \u5165\u529B\u30A4\u30F3\u30B8\u30B1\u30FC\u30BF\u30FC\u3092\u542B\u3080"},ko:{subject:":sparkles: \uC2E4\uC2DC\uAC04 \uCC44\uD305 \uAE30\uB2A5 \uCD94\uAC00",body:"- WebSocket \uC5F0\uACB0 \uAD6C\uD604\\n- \uBA54\uC2DC\uC9C0 \uC554\uD638\uD654 \uCD94\uAC00\\n- \uC785\uB825 \uD45C\uC2DC\uAE30 \uD3EC\uD568"},es:{subject:":sparkles: Agregar funci\xF3n de chat en tiempo real",body:"- Implementar conexi\xF3n WebSocket\\n- Agregar cifrado de mensajes\\n- Incluir indicadores de escritura"},fr:{subject:":sparkles: Ajouter une fonctionnalit\xE9 de chat en temps r\xE9el",body:"- Impl\xE9menter une connexion WebSocket\\n- Ajouter le chiffrement des messages\\n- Inclure des indicateurs de saisie"},de:{subject:":sparkles: Echtzeit-Chat-Funktion hinzuf\xFCgen",body:"- WebSocket-Verbindung implementieren\\n- Nachrichtenverschl\xFCsselung hinzuf\xFCgen\\n- Tippindikatoren einschlie\xDFen"}},"":{en:{subject:"",body:""}}},s=o[e]||o[""];return s[n]||s.en},pc=e=>{const{type:t,maxLength:n,generate:o,locale:s}=e;return[`Generate exactly ${o} ${t} commit message${o!==1?"s":""} from the provided git diff.`,"",`Language: ${s}`,`Subject: max ${n} chars, imperative mood, no period`,"Format:",`${Uo[t]}`,`Allowed types:${Ko[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(`
|
|
215
|
+
`)},hc=e=>{const{type:t,maxLength:n,generate:o,locale:s}=e;return[`You are an expert developer writing ${t||""} commit message${o!==1?"s":""} from a git diff.`,"","Analyze the diff to understand:","1. What is the primary intent of these changes? (new feature, bug fix, refactor, etc.)","2. What is the scope? (which module, component, or system is affected?)","3. Are there any breaking changes or side effects?","",`Language: ${s}`,`Subject: max ${n} chars, imperative mood, no period`,t?`Format: ${Uo[t]}`:"",t?`Allowed types:${Ko[t]}`:"","",`Generate exactly ${o} commit message${o!==1?"s":""}.`,"Prioritize explaining WHY the change was made over describing WHAT changed."].filter(Boolean).join(`
|
|
216
|
+
`)},gc=(e,t,n)=>{const o=fc(e,n),r=e==="conventional"||e==="gitmoji"?`
|
|
217
|
+
[
|
|
218
|
+
{"subject": "${o.subject}", "body": "${o.body}", "footer": ""}
|
|
219
|
+
]`:"";return[`
|
|
220
|
+
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?`
|
|
221
|
+
Example:${r}`:"",`
|
|
222
|
+
Return valid JSON only.`].filter(Boolean).join(`
|
|
223
|
+
`)},yc=e=>{const{systemPrompt:t,systemPromptPath:n,type:o,generate:s,locale:r,isReasoning:a}=e,c=gc(o,s,r);if(t)return`${rn(t,e)}
|
|
224
|
+
${c}`;if(n)try{const u=O.readFileSync(Ze(n),"utf-8");return`${rn(u,e)}
|
|
225
|
+
${c}`}catch{}return`${a?hc(e):pc(e)}
|
|
226
|
+
${c}`},wc=e=>{const{codeReviewPromptPath:t,locale:n}=e;if(t)try{const o=O.readFileSync(Ze(t),"utf-8");return`${rn(o,e)}`}catch{}return Cc(n)},Cc=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(`
|
|
227
|
+
`),an=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}`)}},bc=(e,t="commit",n)=>{const o=[];return n?.recentCommits&&o.push(`## Recent Commits (for style reference)
|
|
228
|
+
${n.recentCommits}`),n?.branchName&&o.push(`## Branch
|
|
229
|
+
${n.branchName}`),`${o.length>0?o.join(`
|
|
230
|
+
|
|
231
|
+
`)+`
|
|
232
|
+
|
|
233
|
+
`:""}\`\`\`diff
|
|
234
|
+
${e}
|
|
235
|
+
\`\`\``},j=new B;var Ec=async(e,t,n,o,s,r,a,c,l,u,d,p,g,y,f,x,$)=>(async()=>{const S=x==="json";S||j.printTitle();const P=S?null:j.displaySpinner("Detecting repository...");if(await at(),o){P&&(P.text="Staging changes...");const se=await De();se==="git"?await C("git",["add","."]):se==="yadm"&&await C("yadm",["add","--update"])}P&&(P.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)&&Da(w),p&&Ro(w),await an(w);const L={autoNew:f||w.jjAutoNew};P&&(P.text="Detecting staged files...");const D=await nn(n,w.exclude);if(P?.stop(),!D){const se=await De();throw new m(Fe.noStagedChanges(se),{code:R.NO_STAGED_CHANGES})}if(!S){const se=tn(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);S&&((await Sc(ve,H)).forEach(hs=>{process.stdout.write(JSON.stringify(hs)+`
|
|
236
|
+
`)}),process.exit(0));const Q=le(w,"review");Q.length>0&&await vc(ve,Q);const ie=await Ac(ve,H,u);w.useStats!==!1&&Va({provider:ie.provider,model:ie.model,statsDays:w.statsDays}).catch(()=>{});let ne=ie.value;if(d){if(j.printInfo("Opening editor to modify commit message..."),ne=await Pc(ne),!ne.trim())throw new m(Fe.emptyCommitMessage(),{code:R.EMPTY_COMMIT_MESSAGE});j.printSuccess("Commit message edited successfully!"),j.print(`
|
|
237
|
+
${ne}
|
|
238
|
+
`)}(a||w.autoCopy)&&(At("copy-paste").copy(ne),a&&j.printCopied()),a&&!y&&process.exit(),y&&(process.stdout.write(ne+`
|
|
239
|
+
`),process.exit()),(r||u&&H.length===1)&&(await Wo(ne,$,L),process.exit());const{confirmationPrompt:ps}=await T.prompt([{type:"confirm",name:"confirmationPrompt",message:"Use selected message?",default:!0}]);ps?await Wo(ne,$,L):j.printCancelledCommit(),process.exit()})().catch(S=>{if(x==="json"){const P={error:S.message||"Unknown error occurred"};process.stderr.write(JSON.stringify(P)+`
|
|
240
|
+
`),process.exit(1)}j.printError(S.message),W(S),process.exit(1)});async function vc(e,t){const n=new ut(Go);let o=null;try{const s=n.initPrompt({...sn,name:"codeReviewPrompt",message:"Please check code reviews: ",emptyMessage:`\u26A0 ${Bo}`,isDescriptionDim:!1,stopMessage:"Code review completed",descPageSize:20});n.startLoader(),o=e.createCodeReviewRequests$(t).subscribe({next:d=>n.refreshChoices(d),error:d=>{console.error("Code review request error:",d),n.checkErrorOnChoices()},complete:()=>n.checkErrorOnChoices()});const a=(await s).codeReviewPrompt?.value;if(!a)throw new 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{o&&o.unsubscribe(),n.destroy()}}const Ac=async(e,t,n)=>{const o=new ut(Fo);let s=null;try{if(n&&t.length===1){const p=[];o.startLoader(),s=e.createCommitMsgRequests$(t).subscribe({next:y=>{"streamKey"in y||p.push(y),o.refreshChoices(y)},error:y=>{console.error("Commit message generation error:",y),o.checkErrorOnChoices(!1)},complete:()=>o.checkErrorOnChoices(!1)}),await new Promise(y=>{s?.add(()=>y())}),o.clearLoader(),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(`
|
|
241
|
+
${g.name}
|
|
242
|
+
`),{value:g.value,provider:g.provider||"unknown",model:g.model||"unknown"}}const r=new Map,a=o.initPrompt();o.startLoader();let c=0;s=e.createCommitMsgRequests$(t).subscribe({next:p=>{const g=p;g.value&&r.set(g.value,g),p.value&&!p.isError&&!p.disabled&&(c++,o.updateLoaderText(`AI is analyzing your changes (${c} message${c>1?"s":""} generated)`)),o.refreshChoices(p)},error:p=>{console.error("Commit message generation error:",p),o.checkErrorOnChoices()},complete:()=>o.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(),o.destroy()}};async function Pc(e){const t=process.env.VISUAL||process.env.EDITOR||(process.platform==="win32"?"notepad":"vi"),n=A.join(ue.tmpdir(),`aicommit2-${Date.now()}-${yt.randomBytes(4).toString("hex")}.txt`);try{O.writeFileSync(n,e,"utf8");const o=t.split(" "),[s,...r]=o;await C(s,[...r,n],{stdio:"inherit"});const a=O.readFileSync(n,"utf8").trim();if(O.unlinkSync(n),!a)throw new m("Commit cancelled - empty message");return a}catch(o){throw O.existsSync(n)&&O.unlinkSync(n),o instanceof m?o:o&&typeof o=="object"&&"exitCode"in o&&o.exitCode!==0?new m("Commit cancelled"):process.env.VISUAL||process.env.EDITOR?new m(`Failed to open editor "${t}". Please check:
|
|
243
|
+
- Editor binary exists in PATH
|
|
244
|
+
- Editor flags are correct
|
|
245
|
+
- 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 Wo=async(e,t,n)=>{await rc(e,t,n),j.printCommitted()},Sc=async(e,t)=>{const o=(await Et(e.createCommitMsgRequests$(t).pipe(vt()),{defaultValue:[]})).filter(s=>s.value&&!s.isError&&!s.disabled);if(o.length===0)throw new m("No valid commit messages were generated");return o.map(({value:s=""})=>{const[r="",...a]=s.split(`
|
|
246
|
+
`);return{subject:r,body:a.join(`
|
|
247
|
+
`).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:n}=e._,o=e._[1];if(t==="get"){const s=await Z({},[]);if(n.length===0){console.log(s);return}for(const r of n){const a=r.split(".");let c=s,l=!0;for(const u of a)if(zt(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(n.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 Fa(n.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 Ga();return}if(t==="del"){if(!o)throw new m("Please provide the config name to delete.");const s=await Oe(),r=o.split(".");if(r.length===2){const[a,c]=r;if(s[a]&&typeof s[a]=="object"&&zt(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: ${o}`);const u=await I.readFile(l,"utf8");console.log("--- Updated Config Content ---"),console.log(u),console.log("----------------------------")}else throw new m(`Config not found: ${o}`)}else if(r.length===1){const a=r[0];if(zt(s,a)){delete s[a];const c=await be();await I.writeFile(c,ye.stringify(s),"utf8"),console.log(`Successfully deleted config: ${o}`);const l=await I.readFile(c,"utf8");console.log("--- Updated Config Content ---"),console.log(l),console.log("----------------------------")}else throw new m(`Config not found: ${o}`)}else throw new m(`Invalid config name format: ${o}`);return}if(t==="path"){await Ba();return}throw new m(`Invalid mode: ${t}`)})().catch(t=>{new B().printError(t.message),W(t),process.exit(1)})});const qo="gpt-4.1",$c=["gpt-4.1","gpt-4o","gpt-5-mini"],zo={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"]},Rc=[...zo.free,...zo.pro],Yo={"openai/gpt-4.1":"gpt-4.1","openai/gpt-4o":"gpt-4o","openai/gpt-5-mini":"gpt-5-mini"},Vo=e=>{const t=(e||"").trim().toLowerCase();return t?t in Yo?Yo[t]:t.includes("/")&&t.split("/").pop()||t:qo},Ic=e=>[Vo(e),...$c].filter((n,o,s)=>s.indexOf(n)===o),kc=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")},Lc=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")},Mc=e=>{const t=e.toLowerCase();return t.includes("classic personal access tokens")&&t.includes("ghp_")},Oc=(e=process.env)=>{const t={...e};t.NODE_NO_WARNINGS="1",delete t.GH_TOKEN,delete t.GITHUB_TOKEN;const n=(e.COPILOT_GITHUB_TOKEN||"").trim();return n.length>0?(t.COPILOT_GITHUB_TOKEN=n,{githubToken:n,useLoggedInUser:!1,env:t}):(delete t.COPILOT_GITHUB_TOKEN,{useLoggedInUser:!0,env:t})},dt="https://models.github.ai",cn="/inference/chat/completions",ln="2026-03-10",un="openai/gpt-4o-mini",Tc=/^([A-Za-z0-9][A-Za-z0-9._-]*)\/([A-Za-z0-9][A-Za-z0-9._:-]*)$/,Jo=e=>(e||"").trim(),Xo=e=>{const t=Jo(e);return t.length>0&&Tc.test(t)},Dc=e=>{const t=Jo(e);if(!Xo(t))throw new Error(`Invalid GitHub Models model ID "${t||"(empty)"}". Expected format: "publisher/model" (example: "openai/gpt-4o-mini").`);return t},Nc=e=>{const t=(e||"").trim();return t?["ghp_","gho_","ghu_","ghs_","ghr_","github_pat_"].some(o=>t.startsWith(o)):!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=Fs.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 _c={healthy:h.green("\u2705"),error:h.red("\u274C"),warning:h.yellow("\u26A0\uFE0F"),skipped:h.gray("\u23ED\uFE0F")},jc={healthy:h.green,error:h.red,warning:h.yellow,skipped:h.gray},dn=e=>typeof e.key=="string"&&e.key.trim().length>0,Qo=e=>(Array.isArray(e.model)?e.model:typeof e.model=="string"&&e.model.trim().length>0?[e.model.trim()]:[]).length>0,Fc=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)&&Object.keys(e).length>0,Gc=e=>typeof e=="string"&&e.trim()?e.replace(/\/$/,""):"https://openrouter.ai",Bc=e=>`${Gc(e.url)}/api/v1`,Hc=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"}),Uc=(e,t)=>{const n=e.trim();return t.find(o=>[o.id,o.canonical_slug,o.name].filter(r=>!!r).some(r=>r===n))},Kc=(e,t)=>e.supported_parameters?.includes(t)??!1,Wc=[{configKey:"OPENROUTER.responseFormat",configProperty:"responseFormat",parameters:["response_format"]},{configKey:"OPENROUTER.reasoning",configProperty:"reasoning",parameters:["reasoning","include_reasoning"]}],qc=e=>{const t=e.supported_parameters||[];return t.length>0?`supports: ${t.join(", ")}`:"no supported parameters listed"},zc=(e,t)=>{const n=[];for(const o of Wc){if(!Fc(e[o.configProperty]))continue;o.parameters.some(r=>Kc(t,r))||n.push(o.configKey)}return n},Yc=(e,t,n)=>{const o=n.context_length||n.top_provider?.context_length,s=qc(n),r=zc(t,n),a=o?`${o} ctx`:"";if(r.length>0){const u=[`consider removing ${r.join(", ")}`,a,s].filter(Boolean);return`${e}: ${u.join("; ")}`}const c=[a,s].filter(Boolean);return c.length>0?`${e} (${c.join("; ")})`:e},Zo=(e,t)=>{const n=[],o=Array.isArray(e.model)?e.model:typeof e.model=="string"?[e.model]:[];for(const s of o){if(s==="openrouter/auto"){n.push("Auto routing enabled");continue}const r=Uc(s,t);if(!r){n.push(`Model not found in catalog: ${s}`);continue}n.push(Yc(s,e,r))}return n},Vc=async(e,t)=>{try{return await new mt({method:"GET",baseURL:e,timeout:t}).execute(),{ok:!0}}catch(n){const o=n instanceof Error?n.message:String(n);return o.includes("ECONNREFUSED")?{ok:!1,error:"Not running"}:{ok:!1,error:o}}},Jc=async(e,t)=>{const n=typeof e.key=="string"?e.key.trim():"";if(!n)return{ok:!1,error:"No API key configured"};try{const o=Bc(e),s=Hc(n),r=["/models/user","/models"];let a,c;for(const y of r)try{a=await new mt({method:"GET",baseURL:`${o}${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=Qo(e)?Array.isArray(e.model)?e.model:[e.model]:[];if(u.length===0)return{ok:!0,details:`Catalog reachable (${l.length} models)`};if(u.includes("openrouter/auto")){const y=Zo(e,l);return{ok:!0,details:y.length>0?y.join("; "):`Auto routing enabled (${l.length} models)`}}const p=Zo(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(o){const s=o instanceof Error?o.message:String(o);return s.includes("401")||s.includes("403")?{ok:!1,error:"Unauthorized or forbidden when reading OpenRouter catalog"}:s.includes("404")?{ok:!1,error:"OpenRouter catalog endpoint not found"}:{ok:!1,error:s}}},Xc=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():un,Qc=async(e,t)=>{const n=typeof e.key=="string"?e.key.trim():"";if(!n)return{ok:!1,error:"No API key configured"};const o=Xc(e);if(!Xo(o))return{ok:!1,error:"Invalid model ID format",details:`Expected "publisher/model", got "${o||"(empty)"}"`};try{const s=`${dt}${cn}`;return await new mt({method:"POST",baseURL:s,timeout:t}).setHeaders({"Content-Type":"application/json",Accept:"application/vnd.github+json","X-GitHub-Api-Version":ln,Authorization:`Bearer ${n}`}).setBody({model:o,messages:[{role:"user",content:"health-check"}],max_tokens:1,stream:!1}).execute(),{ok:!0,details:`Model: ${o}`}}catch(s){const r=s instanceof Error?s.message:String(s);return r.includes("401")?{ok:!1,error:"Authentication failed (401)"}:r.includes("403")?{ok:!1,error:"Access denied (403). Check token permission: models: read"}:r.includes("404")?{ok:!1,error:`Model not found (404): ${o}`}:r.includes("422")?{ok:!1,error:`Request validation failed (422) for model: ${o}`}:{ok:!1,error:r}}},Zc=e=>{const t=Array.isArray(e.model)?String(e.model[0]||"").trim():String(e.model||"").trim();if(!t)return{ok:!1,error:"No model configured"};try{if((process.env.COPILOT_GITHUB_TOKEN||"").trim().startsWith("ghp_"))return{ok:!1,error:"Unsupported classic PAT in COPILOT_GITHUB_TOKEN",details:"Copilot CLI requires Fine-Grained PAT (github_pat_...) or Copilot login flow"};const o=process.versions.node,s=Number(o.split(".")[0]||"0");if(Number.isFinite(s)&&s<22)return{ok:!1,error:`Node.js ${o} is too old for Copilot SDK`,details:"Copilot SDK v0.2.0 requires node:sqlite support (Node.js 22+ recommended)"};const r=Ae("copilot --version",{stdio:["ignore","pipe","pipe"]}).toString().trim(),a=Vo(t),l=Rc.includes(a)?void 0:`Model '${t}' is not in the known working models list and may not work`;return{ok:!0,details:r?`CLI: ${r}; Model: ${t}; Node: ${o}`:`Model: ${t}; Node: ${o}`,modelWarning:l}}catch{return{ok:!1,error:"Copilot CLI not found",details:"Install and authenticate Copilot CLI before using COPILOT_SDK provider"}}},el=async(e,t,n)=>{if(e==="OLLAMA"){if(!ee(t))return{provider:e,status:"skipped",message:"No models configured"};const o=typeof t.host=="string"&&t.host.trim()?t.host:Ie,s=await Vc(o,n);return s.ok?{provider:e,status:"healthy",message:"Running",details:`Host: ${o}`}:{provider:e,status:"warning",message:s.error||"Connection failed",details:`Host: ${o}`}}if(e==="HUGGINGFACE")return t.cookie?{provider:e,status:"healthy",message:"Cookie configured"}:{provider:e,status:"skipped",message:"No cookie configured"};if(e==="BEDROCK")return ot(t)?{provider:e,status:"healthy",message:"Credentials configured"}:{provider:e,status:"skipped",message:"Not configured"};if(e==="OPENROUTER"){if(!dn(t))return{provider:e,status:"skipped",message:"Not configured"};const o=await Jc(t,n);return o.ok?{provider:e,status:"healthy",message:"Catalog reachable",details:o.details}:{provider:e,status:"warning",message:o.error||"Catalog check failed",details:o.details}}if(e==="GITHUB_MODELS"){if(!dn(t))return{provider:e,status:"skipped",message:"Not configured"};const o=await Qc(t,n);return o.ok?{provider:e,status:"healthy",message:"Models API reachable",details:o.details}:{provider:e,status:"warning",message:o.error||"Connection check failed",details:o.details}}if(e==="COPILOT_SDK"){if(!Qo(t))return{provider:e,status:"skipped",message:"No models configured"};const o=Zc(t);return o.ok?o.modelWarning?{provider:e,status:"warning",message:o.modelWarning,details:o.details}:{provider:e,status:"healthy",message:"SDK environment ready",details:o.details}:{provider:e,status:"warning",message:o.error||"Environment check failed",details:o.details}}return dn(t)?{provider:e,status:"healthy",message:"API key configured"}:{provider:e,status:"skipped",message:"Not configured"}},tl=async e=>{const t=[],n=e.timeout||1e4;for(const o of Ce){const s=e[o];if(!s||typeof s!="object"){t.push({provider:o,status:"skipped",message:"Not configured"});continue}if(s.disabled){t.push({provider:o,status:"skipped",message:"Disabled"});continue}const r=await el(o,s,n);t.push(r)}return t},nl=Math.max(...Ce.map(e=>e.length)),ol=e=>e.padEnd(nl),sl=e=>{console.log(""),console.log(h.bold("\u{1FA7A} aicommit2 Health Check")),console.log(""),console.log(h.bold("Providers:"));for(const n of e){const o=_c[n.status],s=ol(n.provider),r=jc[n.status](n.message),a=n.details?h.gray(` (${n.details})`):"";console.log(` ${o} ${s} ${r}${a}`)}const t={healthy:e.filter(n=>n.status==="healthy").length,error:e.filter(n=>n.status==="error").length,warning:e.filter(n=>n.status==="warning").length,skipped:e.filter(n=>n.status==="skipped").length};console.log(""),console.log(h.bold("Summary: ")+h.green(`${t.healthy} healthy`)+", "+h.red(`${t.error} error`)+", "+h.yellow(`${t.warning} warning`)+", "+h.gray(`${t.skipped} skipped`)),console.log(""),t.error>0&&(process.exitCode=1)},rl=F({name:"doctor",parameters:[],help:{description:"Check health status of configured AI providers",examples:["aicommit2 doctor"]}},()=>{(async()=>{const e=await Z({},[]),t=await tl(e);sl(t)})().catch(e=>{console.error(h.red(e.message)),W(e),process.exit(1)})});var il=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 al(e.flags.token,t)}catch(n){throw new m(`Token authentication failed: ${n.message}`)}return}try{await cl(t)}catch(n){throw new m(`Browser authentication failed: ${n.message}`)}})().catch(t=>{new B().printError(t.message),W(t),process.exit(1)})});async function al(e,t){if(t.printWarning("Authenticating with provided token..."),!Nc(e))throw new Error("Invalid token format. Expected GitHub token prefix like ghp_, gho_, ghu_, ghs_, ghr_, or github_pat_");try{const n=await fetch("https://api.github.com/user",{headers:{Authorization:`Bearer ${e}`,Accept:"application/vnd.github.v3+json","User-Agent":"aicommit2-github-models"}});if(!n.ok)throw new Error(`GitHub API request failed: ${n.status} ${n.statusText}`);const o=await n.json();try{(await fetch(`${dt}${cn}`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/vnd.github+json","X-GitHub-Api-Version":ln,Authorization:`Bearer ${e}`,"User-Agent":"aicommit2-github-models"},body:JSON.stringify({messages:[{role:"user",content:"test"}],model:un,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 ${o.login}`)}catch(n){throw new Error(`Token validation failed: ${n.message}`)}}async function cl(e){e.printInfo("Starting GitHub browser authentication for GitHub Models...");try{try{Ae("gh --version",{stdio:"ignore"})}catch{throw new Error("GitHub CLI (gh) is not installed. Please install it first: https://cli.github.com/")}try{Ae("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{Ae("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=Ae("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",ll=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 fa}),{stdout:r}=await s("yadm",["introspect","repo"]),a=r.trim();if(a)return A.join(a,"hooks",Ee)}catch{}const n=A.join(t,".config/yadm/hooks"),o=A.join(t,".yadm/hooks");try{return await I.access(n),A.join(n,Ee)}catch{return A.join(o,Ee)}}throw e==="jujutsu"?new m("Hooks are not supported for Jujutsu repositories."):new m(`Hooks are not supported for ${e} repositories.`)},ft=Gs(new URL("cli.mjs",import.meta.url)),ul=process.argv[1].replace(/\\/g,"/").includes(`/hooks/${Ee}`),es=process.platform==="win32",ts=`
|
|
248
|
+
#!/usr/bin/env node
|
|
249
|
+
import(${JSON.stringify(Bs(ft))})
|
|
250
|
+
`.trim();var dl=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:n}=e._,o=await ll(),s=A.isAbsolute(o)?o:A.join(t,o),r=await Qe(s);if(n==="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(A.dirname(s),{recursive:!0}),es?await I.writeFile(s,ts):(await I.symlink(ft,s,"file"),await I.chmod(s,493)),console.log(`${h.green("\u2714")} Hook installed`);return}if(n==="uninstall"){if(!r){console.warn("Hook is not installed");return}if(es){if(await I.readFile(s,"utf8")!==ts){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: ${n}`)})().catch(t=>{console.error(`${h.red("\u2716")} ${t.message}`),W(t),process.exit(1)})});const ml=Ls(ws),fl=e=>{const t=["B","KB","MB","GB"];if(e===0)return"0 B";const n=Math.floor(Math.log(e)/Math.log(1024));return Math.round(e/Math.pow(1024,n)*100)/100+" "+t[n]},pl=e=>e.toLocaleDateString()+" "+e.toLocaleTimeString(),hl=async e=>{try{const t=await Pn(q);if(t.length===0){console.log(`${h.yellow("No log files found.")}`);return}console.log(`${h.blue("Log files in")} ${q}:
|
|
251
|
+
`);const n=await Promise.all(t.map(async o=>{const s=ae.join(q,o),r=await Hs(s);return{name:o,size:fl(r.size),modified:pl(r.mtime)}}));n.sort((o,s)=>new Date(s.modified).getTime()-new Date(o.modified).getTime()),n.forEach((o,s)=>{console.log(`${s===0?"\u{1F4C4}":" "} ${h.cyan(o.name)} ${h.gray(`(${o.size}, ${o.modified})`)}`)}),console.log(`
|
|
252
|
+
${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}},gl=async e=>{try{await Pn(q);const t=process.platform;let n;switch(t){case"darwin":n=`open "${q}"`;break;case"win32":n=`start "" "${q}"`;break;default:n=`xdg-open "${q}"`;break}await ml(n),console.log(`${h.green("\u2714")} Opened logs directory in file manager`)}catch(t){t.code==="ENOENT"?console.log(`${h.yellow("Logs directory does not exist yet.")}`):e.printError(`Failed to open logs directory: ${t.message}`)}},yl=async e=>{try{await Us(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 wl=F({name:"log",parameters:["<action>"],help:{description:"Manage log files generated by the application",examples:["aic2 log list # List all log files","aic2 log path # Show logs directory path","aic2 log open # Open logs directory","aic2 log removeAll # Remove all log files"]}},e=>{(async()=>{const{action:t}=e._,n=new B;switch(t){case"list":await hl();break;case"path":console.log(`${h.blue("Logs directory:")} ${q}`);break;case"open":await gl(n);break;case"removeAll":await yl(n);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 Cl=new Set(["--locale","-l","--generate","-g","--type","-t","--prompt","--exclude","-x","--output"]),ns=(e,t=[])=>{const n=new Set(t),o=[];let s=!1;for(let r=0;r<e.length;r++){const a=e[r];if(s){s=!1;continue}if(!n.has(a)){if(a.startsWith("-")){Cl.has(a)&&!a.includes("=")&&(s=!0);continue}o.push(a)}}return o},[pt,os]=ns(process.argv.slice(2),["--pre-commit"]);var bl=(e,t,n,o,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()},...o&&{type:o},...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(A.resolve(l.systemPromptPath),"utf-8")}catch{throw new m(`Error reading system prompt file: ${l.systemPromptPath}`)}const u=await nn(n,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(),x=new je(l,u,y,f);let $;try{$=await Et(x.createCommitMsgRequests$(p).pipe(bn(D=>!D.isError),En(D=>D.value),vt()))}finally{d.printAnalyzed()}const P=await I.readFile(pt,"utf8")!=="",v=$.length>1;let w="";P&&(w=`# \u{1F916} Generated by aicommit2 (https://github.com/tak-bro/aicommit2)
|
|
253
|
+
`,w+=`# ----------------------------------------
|
|
254
|
+
`,w+=`# How to use:
|
|
255
|
+
`,v?(w+=`# 1. Remove the "#" from your chosen message
|
|
256
|
+
`,w+=`# 2. Edit the message if needed
|
|
257
|
+
`,w+=`# 3. Save and close the editor
|
|
258
|
+
`):(w+=`# 1. The message below will be used
|
|
259
|
+
`,w+=`# 2. Edit the message if needed
|
|
260
|
+
`,w+=`# 3. Save and close the editor
|
|
261
|
+
`),w+=`# ----------------------------------------
|
|
262
|
+
`),v&&P?(w+=`
|
|
263
|
+
# \u{1F4DD} Choose one of these messages:
|
|
264
|
+
`,w+=`
|
|
265
|
+
${$.map(D=>D.split(`
|
|
266
|
+
`).map(H=>`# ${H}`).join(`
|
|
267
|
+
`)).join(`
|
|
268
|
+
#
|
|
269
|
+
`)}`):v?w+=`
|
|
270
|
+
${$[0]}
|
|
271
|
+
`:(P&&(w+=`
|
|
272
|
+
# \u{1F4DD} Generated commit message:
|
|
273
|
+
`),w+=`
|
|
274
|
+
${$[0]}
|
|
275
|
+
`);const k=await I.readFile(pt,"utf8"),L=w+`
|
|
276
|
+
`+k;await I.writeFile(pt,L),d.printSavedCommitMessage()})().catch(c=>{new B().printError(c.message),W(c),process.exit(1)});const[ht,ss]=ns(process.argv.slice(2),["--hook-mode"]);var El=(e,t,n,o,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(ss){console.log(`Skipping aicommit2 message generation for ${ss} commit`);return}const c={...e&&{locale:e},...t!=null&&{generate:t.toString()},...o&&{type:o},...s&&{systemPrompt:s},...r===!0&&{includeBody:"true"}};a&&(c.logLevel="verbose");const l=await Z(c);if(await lt(l),re.verbose(`[hook-mode] type=${l.type}, systemPrompt=${l.systemPrompt?"set":"empty"}`),l.systemPromptPath)try{await I.readFile(A.resolve(l.systemPromptPath),"utf-8")}catch{throw new m(`Error reading system prompt file: ${l.systemPromptPath}`)}const u=await nn(n,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(),x=new je(l,u,y,f),$=d.displaySpinner("The AI is analyzing your changes");let S;try{S=await Et(x.createCommitMsgRequests$(p).pipe(bn(te=>!te.isError),En(te=>te.value),vt()))}finally{$.stop(),$.clear(),d.printAnalyzed()}const v=await I.readFile(ht,"utf8")!=="",w=S.length>1,k=await oc();let L="";v&&(L=`${k} \u{1F916} Generated by aicommit2 (https://github.com/tak-bro/aicommit2)
|
|
277
|
+
`,L+=`${k} ----------------------------------------
|
|
278
|
+
`,L+=`${k} How to use:
|
|
279
|
+
`,w?(L+=`${k} 1. Remove the "${k}" from your chosen message
|
|
280
|
+
`,L+=`${k} 2. Edit the message if needed
|
|
281
|
+
`,L+=`${k} 3. Save and close the editor
|
|
282
|
+
`):(L+=`${k} 1. The message below will be used
|
|
283
|
+
`,L+=`${k} 2. Edit the message if needed
|
|
284
|
+
`,L+=`${k} 3. Save and close the editor
|
|
285
|
+
`),L+=`${k} ----------------------------------------
|
|
286
|
+
`),w&&v?(L+=`
|
|
287
|
+
${k} \u{1F4DD} Choose one of these messages:
|
|
288
|
+
`,L+=`
|
|
289
|
+
${S.map(te=>te.split(`
|
|
290
|
+
`).map(V=>`${k} ${V}`).join(`
|
|
291
|
+
`)).join(`
|
|
292
|
+
${k}
|
|
293
|
+
`)}`):w?L+=`
|
|
294
|
+
${S[0]}
|
|
295
|
+
`:(v&&(L+=`
|
|
296
|
+
${k} \u{1F4DD} Generated commit message:
|
|
297
|
+
`),L+=`
|
|
298
|
+
${S[0]}
|
|
299
|
+
`);const D=await I.readFile(ht,"utf8"),H=L+`
|
|
300
|
+
`+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 vl=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 n=await De();if(n!=="git")throw new m(`Rewrite is only supported for Git repositories. Current VCS: ${n}.
|
|
301
|
+
|
|
302
|
+
For Jujutsu, use: jj describe -m "new message"
|
|
303
|
+
For YADM, use: yadm commit --amend -m "new message"`);const o=e._.commitHash||"HEAD";if(o!=="HEAD"){t.text="Validating commit reference...";try{await C("git",["rev-parse","--verify",`${o}^{commit}`])}catch{throw new m(`Invalid commit reference: ${o}.
|
|
304
|
+
|
|
305
|
+
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"]&&Ro(r),await an(r),t.text="Reading commit information...";const a=await No(o);if(t.stop(),!a)throw new m(`Could not retrieve the diff for commit ${o}.
|
|
306
|
+
|
|
307
|
+
Make sure the commit hash is correct and the commit exists.`,{code:R.VCS_NOT_FOUND});const c=await ac(o);if(!c)throw new m(`Could not retrieve the commit message for ${o}.
|
|
308
|
+
|
|
309
|
+
Make sure the commit hash is correct and the commit exists.`);const l=o==="HEAD";Y.printInfo(`${l?"Current":`Commit ${o}`} commit message:
|
|
310
|
+
${c}
|
|
311
|
+
`);const u=tn(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(5,o),y=new je(r,a,p,g),f=e.flags["auto-select"]||!1,x=e.flags.edit||!1,$=e.flags.confirm||!1,S=e.flags["dry-run"]||!1,P=new ut(Fo);let v=null;try{const w=new Map,k=P.initPrompt();P.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++,P.updateLoaderText(`AI is analyzing your changes (${L} message${L>1?"s":""} generated)`)),P.refreshChoices(Q)},error:Q=>{console.error("Commit message generation error:",Q),P.checkErrorOnChoices()},complete:()=>P.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(x){if(Y.printInfo("Opening editor to modify commit message..."),V=await Al(V),!V.trim())throw new m(Fe.emptyCommitMessage(),{code:R.EMPTY_COMMIT_MESSAGE});Y.printSuccess("Commit message edited successfully!"),Y.print(`
|
|
312
|
+
${V}
|
|
313
|
+
`)}if(S){process.stdout.write(V+`
|
|
314
|
+
`);return}if($||f&&d.length===1){await rs(V,o);return}const{confirmationPrompt:ve}=await T.prompt([{type:"confirm",name:"confirmationPrompt",message:"Use selected message?",default:!0}]);ve?await rs(V,o):Y.printCancelledCommit()}finally{v&&v.unsubscribe(),P.destroy()}})().catch(t=>{Y.printError(t.message),W(t),process.exit(1)})});async function rs(e,t){if(await cc(t)){const o=t==="HEAD";Y.printWarning(`${o?"The HEAD":`Commit ${t.slice(0,7)}`} appears to have been pushed to the remote.
|
|
315
|
+
Rewriting will change its hash. You will need to force push:
|
|
316
|
+
git push --force-with-lease`);const{proceed:s}=await T.prompt([{type:"confirm",name:"proceed",message:"Continue with rewrite anyway?",default:!1}]);if(!s){Y.printCancelledCommit();return}}await ic(e,t),Y.printSuccess("Commit message rewritten successfully!")}async function Al(e){const t=process.env.VISUAL||process.env.EDITOR||(process.platform==="win32"?"notepad":"vi"),n=A.join(ue.tmpdir(),`aicommit2-rewrite-${Date.now()}-${yt.randomBytes(4).toString("hex")}.txt`);try{O.writeFileSync(n,e,"utf8");const o=t.split(" "),[s,...r]=o;await C(s,[...r,n],{stdio:"inherit"});const a=O.readFileSync(n,"utf8").trim();if(O.unlinkSync(n),!a)throw new m("Rewrite cancelled - empty message");return a}catch(o){try{O.unlinkSync(n)}catch{}throw o instanceof m?o:o&&typeof o=="object"&&"exitCode"in o&&o.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,mn={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."}},is=["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.
|
|
317
|
+
`);;){const t=await Sl();if(!t)break;await xl(t.key,t.info);const{addMore:n}=await T.prompt([{type:"confirm",name:"addMore",message:"Would you like to configure another provider?",default:!1}]);if(!n)break;console.log()}X.printSuccess("Setup complete! Run `aic2` to generate commit messages.")})().catch(t=>{X.printError(t.message),W(t),process.exit(1)})});const Sl=async()=>{const e=is.map(r=>({name:mn[r].displayName,value:r})),n=Ce.filter(r=>!is.includes(r)).map(r=>({name:mn[r]?.displayName||r,value:r})),{provider:o}=await T.prompt([{type:"list",name:"provider",message:"Select an AI provider to configure:",choices:[new T.Separator("\u2500\u2500 Popular \u2500\u2500"),...e,new T.Separator("\u2500\u2500 Other \u2500\u2500"),...n,new T.Separator,{name:"Done (exit setup)",value:null}]}]);if(!o)return null;const s=mn[o]||{displayName:o,authType:"api-key"};return{key:o,info:s}},xl=async(e,t)=>{console.log(),t.setupNotes&&(X.printInfo(t.setupNotes),console.log());const n=[];switch(t.authType){case"api-key":{const{apiKey:r}=await T.prompt([{type:"password",name:"apiKey",message:`Enter your ${t.displayName} API key:`,mask:"*",validate:a=>a.trim()?!0:"API key is required"}]);n.push([`${e}.key`,r.trim()]);break}case"cookie":{const{cookie:r}=await T.prompt([{type:"password",name:"cookie",message:`Enter your ${t.displayName} cookie:`,mask:"*",validate:a=>a.trim()?!0:"Cookie is required"}]);n.push([`${e}.cookie`,r.trim()]);break}case"none":{if(e==="OLLAMA"){const{host:r}=await T.prompt([{type:"input",name:"host",message:"Ollama host URL:",default:Ie}]);r&&r!==Ie&&n.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"}]);n.push([`${e}.region`,r.trim()]);const{authMethod:a}=await T.prompt([{type:"list",name:"authMethod",message:"Authentication method:",choices:[{name:"AWS Profile (from ~/.aws/credentials)",value:"profile"},{name:"Access Key + Secret Key",value:"keys"},{name:"Environment variables (already set)",value:"env"}]}]);if(a==="profile"){const{profile:c}=await T.prompt([{type:"input",name:"profile",message:"AWS Profile name:",default:"default"}]);n.push([`${e}.profile`,c.trim()])}else if(a==="keys"){const{accessKeyId:c,secretAccessKey:l}=await T.prompt([{type:"password",name:"accessKeyId",message:"AWS Access Key ID:",mask:"*"},{type:"password",name:"secretAccessKey",message:"AWS Secret Access Key:",mask:"*"}]);n.push([`${e}.accessKeyId`,c.trim()]),n.push([`${e}.secretAccessKey`,l.trim()])}break}}const{model:o}=await T.prompt([{type:"input",name:"model",message:"Model to use (comma-separated for multiple):",default:t.defaultModel||"",validate:r=>r.trim()?!0:"At least one model is required"}]);n.push([`${e}.model`,o.trim()]);const s=X.displaySpinner("Saving configuration...");try{await tt(n),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}`)}},as=20,cs=e=>e<1e3?`${e}ms`:`${(e/1e3).toFixed(1)}s`,ls=e=>new Date(e).toLocaleDateString(),$l=e=>{const t=Math.round(e/100*as),n=as-t;return(e>=80?h.green:e>=50?h.yellow:h.red)("\u2588".repeat(t))+h.gray("\u2591".repeat(n))},Rl=e=>{const t=e.totalRequests>0?Math.round(e.successCount/e.totalRequests*100):0,n=$l(t),o=e.provider.padEnd(14),s=`${t}%`.padStart(4),r=`${e.totalRequests}`.padStart(4),a=`${e.selectedCount}`.padStart(4),c=e.selectionRate>0?`(${e.selectionRate}%)`.padStart(7):"".padStart(7),l=cs(e.avgResponseTimeMs).padStart(6);console.log(` ${h.bold(o)} ${s} ${n} ${r} ${h.cyan(a)} ${h.gray(c)} ${l}`)},Il=async e=>{if(!await Za()){console.log(h.yellow(`
|
|
318
|
+
No statistics recorded yet.`)),console.log(h.gray(`Statistics will be collected as you generate commit messages.
|
|
319
|
+
`));return}const n=await Xa(e);if(n.totalRequests===0){console.log(h.yellow(`
|
|
320
|
+
No statistics in the last ${e} days.
|
|
321
|
+
`));return}if(console.log(""),console.log(h.bold("\u{1F4CA} aicommit2 Statistics")),console.log(h.gray(` Period: ${ls(n.periodStart)} - ${ls(n.periodEnd)}`)),console.log(""),console.log(h.bold("Overview:")),console.log(` Total requests: ${h.cyan(n.totalRequests)}`),console.log(` Success rate: ${h.green(n.successRate+"%")}`),console.log(` Avg response time: ${h.yellow(cs(n.avgResponseTimeMs))}`),console.log(""),n.providerStats.length>0){console.log(h.bold("Provider Usage:")),console.log(h.gray(" Provider Rate Bar Cnt Selected Time"));for(const o of n.providerStats)Rl(o);console.log("")}},kl=async()=>{await Qa(),console.log(h.green(`
|
|
322
|
+
Statistics cleared successfully.
|
|
323
|
+
`))},Ll=F({name:"stats",parameters:["[action]"],flags:{days:{type:Number,description:"Number of days to include in statistics (default: 30)",alias:"d",default:30}},help:{description:"View AI request statistics and performance metrics",examples:["aicommit2 stats Show statistics for last 30 days","aicommit2 stats -d 7 Show statistics for last 7 days","aicommit2 stats clear Clear all statistics"]}},e=>{(async()=>{const t=e._[0],{days:n}=e.flags;switch(t){case"clear":await kl();break;default:await Il(n);break}})().catch(t=>{console.error(h.red(t.message)),W(t),process.exit(1)})});class us{constructor(t="SubscriptionManager"){this.destroyed$=new Ns,this.subscriptions=new bt,this.isDestroyed=!1,this.name=t}add(t,n){if(this.isDestroyed){console.warn(`${this.name}: Cannot add subscription - manager is destroyed`);const s=new bt;return s.unsubscribe(),s}const o=t.pipe(Sn(this.destroyed$),xn(()=>{process.env.NODE_ENV==="development"&&console.log(`${this.name}: Observable finalized`)})).subscribe({next:n?.next,error:s=>{console.error(`${this.name}: Observable error:`,s),n?.error?.(s)},complete:n?.complete});return this.subscriptions.add(o),o}pipe(t){return this.isDestroyed?(console.warn(`${this.name}: Cannot pipe - manager is destroyed`),t):t.pipe(Sn(this.destroyed$),xn(()=>{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 Ml=new us("Global"),Ge=()=>{Ml.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 Ol=Is(bs),ds=5,Tl=3e3,Dl=500,Nl=100,_l=1e3,jl=200;class Fl{constructor(){this.consoleManager=new B,this.subscriptionManager=new us,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=A.join(this.REPO_PATH,".git"),this.HEAD_PATH=A.join(this.GIT_PATH,"HEAD"),this.REFS_PATH=A.join(this.GIT_PATH,"refs","heads"),this.COMMIT_MSG_PATH=A.join(this.GIT_PATH,"COMMIT_EDITMSG"),this.setupProcessHandlers=()=>{const t=()=>{this.destroy(),process.exit(0)};process.on("SIGINT",t),process.on("SIGTERM",t),process.on("SIGQUIT",t)},this.watch=async(t,n,o,s,r,a)=>{this.consoleManager.printTitle(),await at();const c=await De();if(c!=="git")throw new m(`Watch mode is only supported for Git repositories. Current VCS: ${c}`);this.excludeFiles=o;const l=await this.initializeConfig(t,n,s,r,a);this.configExclude=l.exclude||[],await this.initializeCurrentCommit(),await this.startWatchLoop(l)},this.startWatchLoop=async t=>{try{await this.watchGitEvents(t)}catch(n){this.retryCount<ds||(this.consoleManager.printError("Watch mode failed after maximum retries. Exiting."),this.destroy(),process.exit(1)),this.retryCount++;const s=Tl*Math.pow(2,this.retryCount-1);return await this.handleWatchGitError(n,s),this.startWatchLoop(t)}},this.initializeConfig=async(t,n,o,s,r)=>{const a={locale:t?.toString(),generate:n?.toString(),systemPrompt:o?.toString()};s&&(a.logLevel="verbose");const c=await Z(a,r);return await an(c),le(c,"watch").length===0&&(this.consoleManager.printError(`Please set at least one API key and watchMode via the config command:
|
|
324
|
+
aicommit2 config set [MODEL].key="YOUR_API_KEY"
|
|
325
|
+
aicommit2 config set [MODEL].watchMode="true"`),process.exit()),c},this.handleWatchGitError=async(t,n)=>{this.consoleManager.printError(`An error occurred: ${t.message}`),W(t),await new Promise(o=>setTimeout(o,n)),this.consoleManager.printWarning(`Restarting the commit monitoring process... (retry ${this.retryCount}/${ds})`)},this.initializeCurrentCommit=async()=>{try{const t=await this.executeGitCommand("git rev-parse HEAD");this.lastCommitHash=t.trim();const n=this.lastCommitHash.substring(0,8);this.consoleManager.printInfo(`Starting watch from commit: ${n}`)}catch{this.consoleManager.printWarning("No commits found in repository"),this.lastCommitHash=null}},this.executeGitCommand=async t=>{const{stdout:n}=await Ol(t,{cwd:this.REPO_PATH});return n},this.clearTerminal=()=>{process.stdout.write("\x1Bc")},this.handleCommitEvent=async(t,n)=>{try{const o=await No(n,this.excludeFiles,this.configExclude);if(!o){this.consoleManager.printWarning("No changes found in this commit");return}this.consoleManager.stopLoader(),this.consoleManager.printStagedFiles(o);const s=le(t,"watch");await this.performCodeReview(t,o,s)}catch(o){this.consoleManager.printError(`Error processing commit ${n.substring(0,8)}: ${o.message}`)}},this.performCodeReview=async(t,n,o)=>{this.cleanupPreviousCodeReview();const s=await Ne(),r=await _e(),a=new je(t,n,s,r),c=[];let l=!1;this.currentCodeReviewSubscription=this.subscriptionManager.add(a.createCodeReviewRequests$(o),{next:u=>{c.push(u),this.currentCodeReviewPromptManager?.refreshChoices(u)},error:u=>{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(Go);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({...sn,name:"codeReviewPrompt",message:"Please check code reviews: ",emptyMessage:`\u26A0 ${Bo}`,isDescriptionDim:!1,stopMessage:"Code review completed",descPageSize:20}),this.cleanupCurrentReviewResources=()=>{this.currentCodeReviewSubscription&&(this.currentCodeReviewSubscription.unsubscribe(),this.currentCodeReviewSubscription=null),this.currentCodeReviewPromptManager&&(this.currentCodeReviewPromptManager.destroy(),this.currentCodeReviewPromptManager=null)},this.cleanupCodeReview=()=>{this.cleanupCurrentReviewResources()},this.isGitReset=async t=>{if(!this.lastCommitHash)return!1;try{return await this.executeGitCommand(`git merge-base --is-ancestor ${t} ${this.lastCommitHash}`),!0}catch{return!1}},this.cancelCurrentReview=()=>{this.currentCodeReviewPromptManager&&this.currentCodeReviewPromptManager.cancel(),this.cleanupCurrentReviewResources()},this.closeWatcher=async()=>{this.watcher&&(await this.watcher.close(),this.watcher=null)},this.watchGitEvents=async t=>{this.consoleManager.showLoader("Watching for new Git commits...");const o=[this.HEAD_PATH,this.REFS_PATH,this.COMMIT_MSG_PATH,A.join(this.GIT_PATH,"logs","HEAD")].filter(s=>{try{return O.accessSync(s),!0}catch{return!1}});this.watcher=Ks.watch(o,{persistent:!0,ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:Dl,pollInterval:Nl}}),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}`)})},_l)})},this.handleGitChange=async(t,n)=>{if(this.processingLock){try{const s=(await this.executeGitCommand("git rev-parse HEAD")).trim();s!==this.lastCommitHash&&(this.pendingCommitHash=s,this.isProcessingCommit&&this.cancelCurrentReview())}catch{}return}this.processingLock=!0;try{await this.processGitChange(t),this.pendingCommitHash&&this.pendingCommitHash!==this.lastCommitHash&&(this.pendingCommitHash=null,await this.processGitChange(t)),this.pendingCommitHash=null}finally{this.processingLock=!1}},this.processGitChange=async t=>{try{const o=(await this.executeGitCommand("git rev-parse HEAD")).trim();if(o===this.lastCommitHash)return;if(this.retryCount=0,await this.isGitReset(o)){this.consoleManager.printInfo(`Git reset detected: ${o.substring(0,8)}`),this.lastCommitHash=o,this.isProcessingCommit&&(this.cancelCurrentReview(),this.isProcessingCommit=!1);return}if(this.isProcessingCommit){this.consoleManager.printInfo("New commit detected, cancelling current review...");try{this.cancelCurrentReview(),await new Promise(r=>setTimeout(r,jl))}catch(r){re.warn(`Error during review cancellation: ${r}`)}}this.isProcessingCommit=!0;try{this.consoleManager.stopLoader(),this.consoleManager.printInfo(`New commit detected: ${o.substring(0,8)}`),this.lastCommitHash=o,this.clearTerminal(),await this.handleCommitEvent(t,o)}catch(r){this.consoleManager.printError(`Error processing commit ${o.substring(0,8)}: ${r.message}`)}finally{this.isProcessingCommit=!1}}catch(n){this.isProcessingCommit=!1;const o=n.message??"";o.includes("fatal: not a git repository")||this.consoleManager.printError(`Error checking for new commits: ${o}`)}finally{this.consoleManager.showLoader("Watching for new Git commits...")}},this.destroy=()=>{this.isProcessingCommit=!1,this.lastCommitHash=null;try{this.subscriptionManager.destroy(),this.cleanupCurrentReviewResources(),this.watcher&&(this.watcher.close(),this.watcher=null),this.consoleManager.stopLoader()}catch(t){re.warn(`Error during WatchGitManager destruction: ${t}`)}},this.setupProcessHandlers()}}const Gl=new Fl,Bl=async(e,t,n,o,s,r)=>Gl.watch(e,t,n,o,s,r),ms={"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"]},Hl=e=>{if(!e||typeof e!="object")return!1;const t=e;return t.data?.name!==void 0&&typeof t.data.name=="string"},Ul=e=>Hl(e)?e.data.name:null,Kl=e=>{for(const[t,n]of Object.entries(ms))if(n.includes(e))return t;return null},Wl=e=>e.type==="section"&&e.data?.title==="Flags:",ql=e=>e.data?.body?.data?.tableData!==void 0,zl=e=>{const t=new Map;for(const n of Object.keys(ms))t.set(n,[]);if(t.set("Other",[]),!Array.isArray(e))return t;for(const n of e){if(!Array.isArray(n))continue;const o=Ul(n[0]),s=o&&Kl(o)||"Other";t.get(s)?.push(n)}return t},Yl=(e,t,n,o,s)=>({type:"section",data:{title:s?`Flags - ${e}:`:` ${e}:`,body:{type:"table",data:{tableData:t,tableOptions:n,tableBreakpoints:o}}}}),Vl=(e,t)=>{const n=[];for(const o of e){if(!Wl(o)||!ql(o)){n.push(o);continue}const{tableData:s,tableOptions:r,tableBreakpoints:a}=o.data.body.data;[...zl(s).entries()].filter(([,u])=>u.length>0).forEach(([u,d],p)=>{n.push(Yl(u,d,r,a,p===0))})}return t.render(n)};process.env.NODE_NO_WARNINGS||(process.env.NODE_NO_WARNINGS="1");const gt=process.argv.slice(2),{version:fs,description:Jl}=ir;gs({name:"aicommit2",version:fs,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,rl,il,dl,wl,vl,Pl,Ll],help:{description:Jl,render:Vl},ignoreArgv:e=>e==="unknown-flag"||e==="argument"},async e=>{const t={};e.flags.verbose&&(t.logLevel="verbose");const n=await Z(t,gt);if(await lt(n),re.info(`aicommit2 version: ${fs}`),e.flags["pre-commit"]){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["hook-mode"]||ul){El(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"]){Bl(e.flags.locale,e.flags.generate,e.flags.exclude,e.flags.prompt,e.flags.verbose,gt);return}Ec(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,qo as C,Ho as D,R as E,dt as G,mt as H,m as K,z as P,Ia as a,wc as b,Aa as c,bc as d,dc as e,mc as f,yc as g,uc as h,Sa as i,oe as j,de as k,re as l,qt as m,Mc as n,Lc as o,kc as p,Ic as q,Oc as r,ka as s,Pa as t,Ie as u,jo as v,un as w,Dc as x,cn as y,ln as z};
|