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