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