aicommit2 2.5.16 → 2.5.18
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 +1 -1
- package/dist/{ai.service-8e59106d.mjs → ai.service-8f81dd1f.mjs} +1 -1
- package/dist/{anthropic.service-cdd97556.mjs → anthropic.service-11f6192a.mjs} +1 -1
- package/dist/{bedrock.service-3487fda6.mjs → bedrock.service-66a1b85e.mjs} +1 -1
- package/dist/{cli-6be3c9c1.mjs → cli-005bffd8.mjs} +5 -5
- package/dist/cli.mjs +1 -1
- package/dist/{codestral.service-cf085c39.mjs → codestral.service-74ed0b75.mjs} +1 -1
- package/dist/{cohere.service-2b555628.mjs → cohere.service-86c58a47.mjs} +1 -1
- package/dist/{copilot-sdk.service-0775d505.mjs → copilot-sdk.service-e3bf61b3.mjs} +1 -1
- package/dist/deep-seek.service-99b5c137.mjs +1 -0
- package/dist/{gemini.service-25c72218.mjs → gemini.service-0f288526.mjs} +1 -1
- package/dist/{github-models.service-5d43907f.mjs → github-models.service-a7f34295.mjs} +1 -1
- package/dist/{groq.service-f7770363.mjs → groq.service-73312be1.mjs} +1 -1
- package/dist/{hugging-face.service-f7dcc31e.mjs → hugging-face.service-135bd6ce.mjs} +1 -1
- package/dist/{mistral.service-7a073354.mjs → mistral.service-ac6622a0.mjs} +1 -1
- package/dist/{ollama.service-aa773594.mjs → ollama.service-782b098b.mjs} +1 -1
- package/dist/{openai-e41e415b.mjs → openai-5c9e718a.mjs} +1 -1
- package/dist/{openai-compatible.service-3da32dc7.mjs → openai-compatible.service-7fead9c0.mjs} +1 -1
- package/dist/{openai.service-663ad5da.mjs → openai.service-c0d8d959.mjs} +1 -1
- package/dist/{openrouter.service-f6552be3.mjs → openrouter.service-0791fb7b.mjs} +1 -1
- package/dist/{perplexity.service-f582f58e.mjs → perplexity.service-977e0442.mjs} +1 -1
- package/package.json +1 -1
- package/dist/deep-seek.service-f7f29cf5.mjs +0 -1
package/README.md
CHANGED
|
@@ -99,7 +99,7 @@ _aicommit2_ automatically generates commit messages using AI. It supports [Git](
|
|
|
99
99
|
| Cohere | `command-a-03-2025` | [Guide](docs/providers/cohere.md) |
|
|
100
100
|
| Groq | `llama-3.3-70b-versatile` | [Guide](docs/providers/groq.md) |
|
|
101
101
|
| Perplexity | `sonar` | [Guide](docs/providers/perplexity.md) |
|
|
102
|
-
| DeepSeek | `deepseek-
|
|
102
|
+
| DeepSeek | `deepseek-v4-flash` | [Guide](docs/providers/deepseek.md) |
|
|
103
103
|
| GitHub Models | `openai/gpt-4o-mini` | [Guide](docs/providers/github-models.md) |
|
|
104
104
|
| Bedrock | `anthropic.claude-haiku-4-5-20251001-v1:0` | [Guide](docs/providers/bedrock.md) |
|
|
105
105
|
| Ollama | *(user configured)* | [Guide](docs/providers/ollama.md) |
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{of as L,Observable as _,Subject as T,catchError as B}from"rxjs";import"fs";import"path";import{xxh64 as P}from"@pacote/xxhash";import $ from"winston";import{A as J,l as p,D as F,g as U,d as D,s as b,h as z,e as q,E as H,f as K,i as R}from"./cli-
|
|
1
|
+
import{of as L,Observable as _,Subject as T,catchError as B}from"rxjs";import"fs";import"path";import{xxh64 as P}from"@pacote/xxhash";import $ from"winston";import{A as J,l as p,D as F,g as U,d as D,s as b,h as z,e as q,E as H,f as K,i as R}from"./cli-005bffd8.mjs";const y=new Map,d=(f,r,e)=>{const s=P(0).update(r).digest("hex").substring(0,8),t=`${f}_${s}_${e}`;if(y.has(t))return y.get(t);const n=new Date,o=ee(n,f,r,e),c=`${J}/${o}`,i=$.createLogger({level:"info",format:$.format.combine($.format.timestamp({format:"YYYY-MM-DDTHH:mm:ss.SSSZ"}),$.format.printf(({timestamp:u,level:l,message:a,...m})=>m&&Object.keys(m).length>0?`[${u}] ${l}: ${a} ${JSON.stringify(m,null,2)}`:`[${u}] ${l}: ${a}`)),transports:[new $.transports.File({filename:c})]});return i.info(`=== ${f.toUpperCase()} AI SERVICE LOG ===`),i.info(`Diff Hash: ${s}`),i.info(`Request Type: ${e.toUpperCase()}`),i.info(`Start Time: ${n.toISOString()}`),i.info("=".repeat(50)),i.info(""),y.set(t,i),i},G=f=>{const r={...f},e=["authorization","x-api-key","x-goog-api-key","api-key","x-amzn-bedrock-application-key"];for(const s of e){const t=s.toLowerCase(),n=Object.keys(r).find(o=>o.toLowerCase()===t);n&&r[n]&&typeof r[n]=="string"&&(r[n].startsWith("Bearer ")?r[n]="Bearer [MASKED]":r[n]="[MASKED]")}return r},W=(f,r,e,s,t,n,o=!0)=>{if(!o)return;const c=d(e,f,r);c.info(`Making request to ${e} API with model: ${s}`),c.info(`Request URL: ${t}`),c.info("Request headers:",G(n))},Y=(f,r,e,s,t=!0)=>{if(!t)return;d(e,f,r).info("Request payload:",s)},V=(f,r,e,s,t,n=!0)=>{if(!n)return;const o=d(e,f,r);o.info("System prompt:",{prompt:s}),o.info("User prompt:",{prompt:t})},X=(f,r,e,s,t=!0)=>{if(!t)return;d(e,f,r).info("Response received:",s)},Q=(f,r,e,s,t=!0)=>{if(!t)return;d(e,f,r).error("API request failed:",s)},M=(f,r,e,s,t,n=!0)=>{if(!n)return;const o=d(e,f,r);s?o.info(`Request completed successfully in ${s}ms`):o.info("Request completed successfully"),t&&o.info("Final processed response:",{response:t}),o.info(""),o.info("=".repeat(50)),o.info(`End Time: ${new Date().toISOString()}`),o.info("=== REQUEST COMPLETED ===")},Z=(f,r,e,s,t,n,o,c=!0)=>{if(!c)return;const i=d(e,f,r);o?i.error(`Request failed after ${n}ms:`,{error:o}):(i.info(`Request completed in ${n}ms`),i.info("Response:",{response:t})),M(f,r,e,n,t,c)},ee=(f,r,e,s)=>{const{year:t,month:n,day:o,hours:c,minutes:i,seconds:u}=te(f),a=P(0).update(e).digest("hex").substring(0,8),m=r.toLowerCase().replace(/[^a-z0-9]/g,"").substring(0,20);return s==="review"?`${t}-${n}-${o}_${c}-${i}-${u}_${a}_${m}_review.log`:`${t}-${n}-${o}_${c}-${i}-${u}_${a}_${m}_commit.log`},te=f=>{const r=f.getFullYear().toString(),e=(f.getMonth()+1).toString().padStart(2,"0"),s=f.getDate().toString().padStart(2,"0"),t=f.getHours().toString().padStart(2,"0"),n=f.getMinutes().toString().padStart(2,"0"),o=f.getSeconds().toString().padStart(2,"0");return{year:r,month:e,day:s,hours:t,minutes:n,seconds:o}},w=()=>{for(const[f,r]of y.entries())try{r.close()}catch(e){console.error(`Failed to close logger ${f}:`,e)}y.clear()};process.on("exit",w),process.on("SIGINT",()=>{w(),process.exit(0)}),process.on("SIGTERM",()=>{w(),process.exit(0)});const se=["o1","o3","o4-mini","gpt-5","deepseek-v4-flash","deepseek-v4-pro","deepseek-reasoner","deepseek-r1","qwq","qwen3","phi4-mini-reasoning","smallthinker"],re=["gemini-2.5"],oe=f=>{const r=f.toLowerCase(),e=r.includes("/")&&r.split("/").pop()||r,s=e.includes(":")?e.split(":")[0]:e;return re.some(t=>s.includes(t))?!0:se.some(t=>s===t||s.startsWith(`${t}-`)||s.startsWith(`${t}.`))};class ne{constructor(){this.buffer="",this.arrayStartFound=!1,this.scanPosition=0,this.feed=r=>{this.buffer+=r;const e=[];if(!this.arrayStartFound){const s=this.buffer.indexOf("[");if(s===-1)return e;this.arrayStartFound=!0,this.scanPosition=s+1}for(;;){const s=this.buffer.indexOf("{",this.scanPosition);if(s===-1)break;const t=this.extractBalancedBraces(s);if(!t)break;this.scanPosition=s+t.length;const n=this.tryParseCommitMessage(t);n&&e.push(n)}return e},this.flush=()=>this.feed(""),this.getBuffer=()=>this.buffer,this.getUnparsedBuffer=()=>this.buffer.slice(this.scanPosition),this.extractBalancedBraces=r=>{let e=0,s=!1,t=!1;for(let n=r;n<this.buffer.length;n++){const o=this.buffer[n];if(t){t=!1;continue}if(o==="\\"&&s){t=!0;continue}if(o==='"'){s=!s;continue}if(!s&&(o==="{"&&e++,o==="}"&&e--,e===0))return this.buffer.slice(r,n+1)}return null},this.tryParseCommitMessage=r=>{try{const e=JSON.parse(r);return typeof e.subject!="string"?null:{subject:e.subject,body:typeof e.body=="string"?e.body:void 0,footer:typeof e.footer=="string"?e.footer:void 0}}catch{return null}}}}class ie{constructor(r){this.formatModelSuffix=()=>{const e=this.params.modelNameDisplay??"short",s=this.params.config.model;if(e==="none"||!s)return"";const t=Array.isArray(s)?s[0]:String(s);if(e==="full")return`/${t}`;const n=t.split("/").pop()||t;return n.length>20?`/${n.slice(0,19)}\u2026`:`/${n}`},this.handleError$=e=>{const s=this.getDetailedErrorMessage(e),t=e.status?`HTTP ${e.status}: ${s}`:s;if(this.params.config.logging){const n=this.params.stagedDiff.diff,o=this.serviceName.replace(/\[|\]/g,"").trim();Z(n,"commit",o,"Error occurred","",void 0,t)}return p.error(`${this.errorPrefix} ${t}`),e.stack&&p.error(` ${e.stack}`),e.content&&p.error(` Problematic content: ${e.content}`),e.originalError&&p.error(` Original error: ${e.originalError}`),L({name:`${this.errorPrefix} ${t}`,value:t,isError:!0,disabled:!0})},this.extractJsonObjectFromResponse=e=>{const s=e.indexOf("{");return s!==-1?this.extractBalancedJson(e,s,"{","}"):null},this.buildPromptOptions=()=>{const{systemPrompt:e,systemPromptPath:s,codeReviewPromptPath:t,locale:n,generate:o,type:c,maxLength:i,model:u}=this.params.config,l=Array.isArray(u)?u[0]||"":String(u||"");return{...F,locale:n,maxLength:i,type:c,generate:o,systemPrompt:e,systemPromptPath:s,codeReviewPromptPath:t,vcs_branch:this.params.branchName||"",isReasoning:oe(l)}},this.buildCommitPrompt=()=>U(this.buildPromptOptions()),this.buildUserPrompt=(e,s="commit")=>{const t={recentCommits:this.params.recentCommits,branchName:this.params.branchName};return D(e,s,t)},this.formatRawCommitMessage=(e,s)=>{const t=this.extractMessageAsType(e,s),n=t.subject,o=`${t.subject}${t.body?`
|
|
2
2
|
|
|
3
3
|
${t.body}`:""}${t.footer?`
|
|
4
4
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import L from"@anthropic-ai/sdk";import P from"chalk";import{concatMap as v,from as w,map as I,catchError as x}from"rxjs";import{fromPromise as S}from"rxjs/internal/observable/innerFrom";import{A as T,l as E,a as $,b,c as _,d as U,e as D}from"./ai.service-
|
|
1
|
+
import L from"@anthropic-ai/sdk";import P from"chalk";import{concatMap as v,from as w,map as I,catchError as x}from"rxjs";import{fromPromise as S}from"rxjs/internal/observable/innerFrom";import{A as T,l as E,a as $,b,c as _,d as U,e as D}from"./ai.service-8f81dd1f.mjs";import{g as F,b as N}from"./cli-005bffd8.mjs";import"fs";import"path";import"@pacote/xxhash";import"winston";import"cleye";import"module";import"crypto";import"os";import"node:buffer";import"node:path";import"node:child_process";import"node:process";import"child_process";import"node:url";import"node:os";import"assert";import"events";import"node:fs";import"buffer";import"stream";import"util";import"node:util";import"inquirer";import"fs/promises";import"readline";import"figlet";import"gradient-string";import"ora";import"inquirer-reactive-list-prompt";import"winston-daily-rotate-file";import"axios";import"url";import"node:fs/promises";import"chokidar";import"rxjs/operators";const W=["claude-4","claude-haiku-4","claude-sonnet-4","claude-opus-4"],R=M=>{const o=M.toLowerCase();return W.some(t=>o===t||o.startsWith(`${t}-`)||o.startsWith(`${t}.`))},z=10*60*1e3;class H extends T{constructor(o){super(o),this.params=o,this.generateStreamingCommitMessage$=()=>{const{generate:t,type:e}=this.params.config;return this.createStreamingCommitMessages$(r=>{this.streamChunks(r).catch(m=>r.error(m))},e,t)},this.streamChunks=async t=>{const e=this.params.stagedDiff.diff,{logging:r,temperature:m,maxTokens:u,topP:g,model:c}=this.params.config,n=F(this.buildPromptOptions()),p=this.buildUserPrompt(e,"commit"),l=`${this.params.config.url||"https://api.anthropic.com"}/v1/messages`,k={"Content-Type":"application/json","x-api-key":this.params.config.key,"anthropic-version":"2023-06-01"};E(e,"commit","Anthropic",c,l,k,r),$(e,"commit","Anthropic",n,p,r);const A=R(c),d={max_tokens:u,temperature:m,system:n,messages:[{role:"user",content:p}],model:c,stream:!0,...A?{}:{top_p:g}};b(e,"commit","Anthropic",d,r);const y=Date.now();let h="";try{const i=this.anthropic.messages.stream(d);i.on("text",a=>{h+=a,t.next(a)});const s=await i.finalMessage(),C=Date.now()-y;_(e,"commit","Anthropic",s,r),U(e,"commit","Anthropic",C,h,r),t.complete()}catch(i){D(e,"commit","Anthropic",i,r),t.error(i)}},this.colors={primary:"#AE5630",secondary:"#fff"},this.serviceName=P.bgHex(this.colors.primary).hex(this.colors.secondary).bold(`[Anthropic${this.formatModelSuffix()}]`),this.errorPrefix=P.red.bold(`[Anthropic${this.formatModelSuffix()}]`),this.anthropic=new L({apiKey:this.params.config.key,...this.params.config.timeout>z&&{timeout:this.params.config.timeout}})}getServiceSpecificErrorMessage(o){const t=o.message||"";return t.includes("API key")||t.includes("api_key")?"Invalid API key. Check your Anthropic API key in configuration":t.includes("quota")||t.includes("usage")?"API quota exceeded. Check your Anthropic usage limits":t.includes("model_not_found")||t.includes("Model not found")||/model.*does not exist/i.test(t)?"Model not found or not accessible. Check if the Claude model name is correct":t.includes("403")||t.includes("Forbidden")?"Access denied. Your API key may not have permission for this Claude model":t.includes("404")||t.includes("Not Found")?"Model or endpoint not found. Check your Claude model configuration":t.includes("500")||t.includes("Internal Server Error")?"Anthropic server error. Try again later":null}generateCommitMessage$(){return this.params.config.stream||!1?this.generateStreamingCommitMessage$():S(this.generateMessage("commit")).pipe(v(t=>w(t)),I(this.formatAsChoice),x(this.handleError$))}generateCodeReview$(){return S(this.generateMessage("review")).pipe(v(o=>w(o)),I(this.formatCodeReviewAsChoice),x(this.handleError$))}async generateMessage(o){const t=this.params.stagedDiff.diff,{logging:e,temperature:r,generate:m,type:u,maxTokens:g,topP:c,model:n}=this.params.config,p=this.buildPromptOptions(),f=o==="review"?N(p):F(p),l=this.buildUserPrompt(t,o),A=`${this.params.config.url||"https://api.anthropic.com"}/v1/messages`,d={"Content-Type":"application/json","x-api-key":this.params.config.key,"anthropic-version":"2023-06-01"};E(t,o,"Anthropic",n,A,d,e),$(t,o,"Anthropic",f,l,e);const y=R(n),h={max_tokens:g,temperature:r,system:f,messages:[{role:"user",content:l}],model:n,...y?{}:{top_p:c}};b(t,o,"Anthropic",h,e);const i=Date.now();try{const s=await this.anthropic.messages.create(h),C=Date.now()-i;_(t,o,"Anthropic",s,e);const a=s.content.map(({text:O})=>O).join("");return U(t,o,"Anthropic",C,a,e),o==="review"?this.parseCodeReview(a):this.parseMessage(a,u,m)}catch(s){throw D(t,o,"Anthropic",s,e),s}}}export{H as AnthropicService};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import F from"https";import h from"chalk";import{concatMap as $,from as x,map as T,catchError as W}from"rxjs";import{fromPromise as K}from"rxjs/internal/observable/innerFrom";import{A as q,l as Y,a as H,b as z,d as V,e as M,c as G}from"./ai.service-
|
|
1
|
+
import F from"https";import h from"chalk";import{concatMap as $,from as x,map as T,catchError as W}from"rxjs";import{fromPromise as K}from"rxjs/internal/observable/innerFrom";import{A as q,l as Y,a as H,b as z,d as V,e as M,c as G}from"./ai.service-8f81dd1f.mjs";import{b as J,g as j,v as O,s as Q}from"./cli-005bffd8.mjs";import"fs";import"path";import"@pacote/xxhash";import"winston";import"cleye";import"module";import"crypto";import"os";import"node:buffer";import"node:path";import"node:child_process";import"node:process";import"child_process";import"node:url";import"node:os";import"assert";import"events";import"node:fs";import"buffer";import"stream";import"util";import"node:util";import"inquirer";import"fs/promises";import"readline";import"figlet";import"gradient-string";import"ora";import"inquirer-reactive-list-prompt";import"winston-daily-rotate-file";import"axios";import"url";import"node:fs/promises";import"chokidar";import"rxjs/operators";const g="Bedrock",S={MISSING_DEPENDENCY:"MissingDependencyError",MISSING_REGION:"MissingRegionError",MISSING_MODEL_ID:"MissingModelIdError",MISSING_API_KEY:"MissingApiKeyError",MISSING_APPLICATION_KEY:"MissingApplicationKeyError",INVALID_RESPONSE:"InvalidResponseError",EMPTY_RESPONSE:"EmptyResponseError"},i=f=>typeof f=="string"&&f.length>0;let _=null,v=null;const L=f=>{const e=new Error('Amazon Bedrock support requires "@aws-sdk/client-bedrock-runtime" and "@aws-sdk/credential-providers". Install them with `pnpm add @aws-sdk/client-bedrock-runtime @aws-sdk/credential-providers`.');return e.name=S.MISSING_DEPENDENCY,e.originalError=f,e},X=async()=>{if(_)return _;try{return _=await import("@aws-sdk/client-bedrock-runtime"),_}catch(f){throw _=null,L(f)}},U=async()=>{if(v)return v;try{return v=await import("@aws-sdk/credential-providers"),v}catch(f){throw v=null,L(f)}};class Z extends q{constructor(e){super(e),this.params=e,this.credentialCache=void 0,this.credentialCacheTimestamp=0,this.CREDENTIAL_CACHE_TTL=5*60*1e3,this.bedrockConfig=this.params.config,this.colors={primary:"#232F3E",secondary:"#FF9900"},this.serviceName=h.bgHex(this.colors.primary).hex(this.colors.secondary).bold(`[${g}${this.formatModelSuffix()}]`),this.errorPrefix=h.red.bold(`[${g}${this.formatModelSuffix()}]`),this.validateConfiguration()}validateConfiguration(){const e=this.bedrockConfig;if(!i(e.model)){const o=new Error("Model ID or inference profile ARN is required.");throw o.name=S.MISSING_MODEL_ID,o}if(!this.getRegion()){const o=new Error("AWS region is required. Configure BEDROCK.region or set AWS_REGION/AWS_DEFAULT_REGION.");throw o.name=S.MISSING_REGION,o}const t=i(e.key),r=this.canUseAwsSdk();if(!t&&!r){const o=new Error("Authentication required: Configure AWS credentials (profile, access keys, IAM role) or API key (BEDROCK.key).");throw o.name=S.MISSING_API_KEY,o}if(t&&!r&&!this.getRegion()&&!i(e.applicationBaseUrl)){const o=new Error("Bearer token authentication requires region or applicationBaseUrl to construct endpoint.");throw o.name=S.MISSING_REGION,o}}canUseAwsSdk(){const e=this.bedrockConfig,t=i(e.profile)||i(process.env.AWS_PROFILE),r=i(e.accessKeyId)&&i(e.secretAccessKey)||i(process.env.AWS_ACCESS_KEY_ID)&&i(process.env.AWS_SECRET_ACCESS_KEY);return t||r}determineAuthMethod(){const e=i(this.bedrockConfig.key);if(this.canUseAwsSdk())return"aws-sdk";if(e)return"bearer-token";throw new Error("No authentication method configured")}getServiceSpecificErrorMessage(e){const t=e?.name||e.code,r=e.message||"";switch(t){case"UnrecognizedClientException":case"InvalidSignatureException":return"Authentication with AWS failed. Check your IAM credentials or Bedrock API key settings.";case"AccessDeniedException":return"Access denied. Ensure the IAM principal or application key has permission to invoke the Bedrock resource.";case"ValidationException":return"Invalid request for the selected Bedrock model. Verify the model ID and payload.";case"ResourceNotFoundException":return"The specified Bedrock model, endpoint, or inference profile could not be found.";case"ThrottlingException":return"Request throttled by Bedrock. Reduce request rate or check service quotas."}return r.includes("Region")?"AWS region is required for Bedrock. Configure BEDROCK.region or set AWS_REGION/AWS_DEFAULT_REGION.":null}generateCommitMessage$(){return K(this.generateMessage("commit")).pipe($(e=>x(e)),T(this.formatAsChoice),W(this.handleError$))}generateCodeReview$(){return K(this.generateMessage("review")).pipe($(e=>x(e)),T(this.formatCodeReviewAsChoice),W(this.handleError$))}async generateMessage(e){const t=this.params.stagedDiff.diff,r=this.bedrockConfig,o=r.model,{logging:c,inferenceParameters:n}=r,s=this.buildPromptOptions(),a=e==="review"?J(s):j(s),l=this.buildUserPrompt(t,e),w={region:this.getRegion(),profile:r.profile,modelId:o},y=`https://bedrock-runtime.${this.getRegion()||"unknown"}.amazonaws.com/model/${encodeURIComponent(o)}/converse`;Y(t,e,g,o,y,w,c),H(t,e,g,a,l,c);const R={modelId:o,systemPrompt:a,userPrompt:l,...n&&Object.keys(n).length>0&&{inferenceConfig:n}};z(t,e,g,R,c);const u=Date.now();try{const m=this.determineAuthMethod();O()&&(console.log(h.cyan(`[Bedrock] Authentication method: ${m}`)),console.log(h.cyan(`[Bedrock] Model ID: ${o}`)),console.log(h.cyan(`[Bedrock] Region: ${this.getRegion()}`)),console.log(h.cyan(`[Bedrock] Has AWS credentials: ${this.canUseAwsSdk()}`)),console.log(h.cyan(`[Bedrock] Has API key: ${i(r.key)}`)));const E=m==="bearer-token"?await this.invokeWithBearerToken({model:o,systemPrompt:a,userPrompt:l,logging:c,requestType:e,diff:t,inferenceConfig:n}):await this.invokeWithAwsSdk({model:o,systemPrompt:a,userPrompt:l,logging:c,requestType:e,diff:t,inferenceConfig:n}),I=Date.now()-u;return V(t,e,g,I,E,c),e==="review"?this.parseCodeReview(E):this.parseMessage(E,r.type,r.generate)}catch(m){throw M(t,e,g,m,c),m instanceof Error&&(m.status=m?.status||m?.$metadata?.httpStatusCode),m}}async invokeWithAwsSdk(e){const t=this.getRegion(),{model:r,systemPrompt:o,userPrompt:c,inferenceConfig:n,logging:s,requestType:a,diff:l}=e,{BedrockRuntimeClient:w,ConverseCommand:y}=await X(),R=this.bedrockConfig,u={region:t,requestHandler:{requestTimeout:R.timeout||12e4}},m=await this.resolveCredentials();m&&(u.credentials=m);const E=new w(u),I=new y({modelId:r,messages:[{role:"user",content:[{text:c}]}],...o?{system:[{text:o}]}:{},...n&&Object.keys(n).length>0&&{inferenceConfig:n}});O()&&console.log(h.cyan(`[Bedrock] Sending ConverseCommand with modelId: ${r}`));let C;try{C=await E.send(I),G(l,a,g,C,s)}catch(d){throw O()&&(console.error(h.red(`[Bedrock] AWS SDK Error: ${d.name}`)),console.error(h.red(`[Bedrock] Error message: ${d.message}`)),d.$metadata&&(console.error(h.red(`[Bedrock] Request ID: ${d.$metadata.requestId}`)),console.error(h.red(`[Bedrock] HTTP Status: ${d.$metadata.httpStatusCode}`))),d.$fault&&console.error(h.red(`[Bedrock] Fault: ${d.$fault}`))),d}const A=C.output?.message?.content?.[0]?.text||"";if(!A){const d=new Error("No text content found in Bedrock response.");throw d.name=S.EMPTY_RESPONSE,d.content=C,d}return A}invokeWithBearerToken(e){const{model:t,systemPrompt:r,userPrompt:o,inferenceConfig:c,logging:n,requestType:s,diff:a}=e,l=this.bedrockConfig,w=this.getRegion(),y=encodeURIComponent(t),R=l.applicationBaseUrl||`https://bedrock-runtime.${w}.amazonaws.com/model/${y}/converse`,u=new URL(R),m={modelId:t,messages:[{role:"user",content:[{text:o}]}],...c&&Object.keys(c).length>0&&{inferenceConfig:c}};r&&(m.system=[{text:r}]);const E=JSON.stringify(m),I={"Content-Type":"application/json","Content-Length":Buffer.byteLength(E).toString()};return i(l.key)&&(I.Authorization=`Bearer ${l.key}`),i(l.applicationInferenceProfileArn)&&(I["x-amzn-bedrock-inference-profile-arn"]=l.applicationInferenceProfileArn),i(l.applicationEndpointId)&&(I["x-amzn-bedrock-endpoint-id"]=l.applicationEndpointId),new Promise((C,A)=>{const d=F.request({method:"POST",protocol:u.protocol,hostname:u.hostname,port:u.port,path:u.pathname+u.search,headers:I,timeout:l.timeout},k=>{const P=[];k.on("data",N=>P.push(N)),k.on("end",()=>{const N=Buffer.concat(P).toString("utf8");if(k.statusCode&&k.statusCode>=400){const p=new Error(`Bedrock application endpoint responded with status ${k.statusCode}.`);return p.status=k.statusCode,p.content=N,M(a,s,g,p,n),A(p)}const b=Q(N);if(!b.ok){const p=new Error("Failed to parse Bedrock application response as JSON. The Bedrock Converse API should always return valid JSON.");return p.name=S.INVALID_RESPONSE,p.content=N,M(a,s,g,p,n),A(p)}const B=b.data;G(a,s,g,B,n);const D=B.output?.message?.content?.[0]?.text||"";if(!D){const p=new Error("No text content found in Bedrock response.");return p.name=S.EMPTY_RESPONSE,p.content=B,M(a,s,g,p,n),A(p)}C(D)})});d.on("error",k=>{const P=k;M(a,s,g,P,n),A(P)}),d.write(E),d.end()})}getRegion(){return this.bedrockConfig.region||process.env.AWS_REGION||process.env.AWS_DEFAULT_REGION||""}async resolveCredentials(){const e=Date.now();if(this.credentialCache&&e-this.credentialCacheTimestamp<this.CREDENTIAL_CACHE_TTL)return this.credentialCache;const t=this.bedrockConfig,r=t.profile,o=t.accessKeyId,c=t.secretAccessKey,n=t.sessionToken;let s;if(i(r)){const{fromIni:a}=await U();s=a({profile:r})}else if(i(o)&&i(c))s=async()=>({accessKeyId:o,secretAccessKey:c,sessionToken:n||process.env.AWS_SESSION_TOKEN||void 0});else if(process.env.AWS_PROFILE){const{fromIni:a}=await U();s=a({profile:process.env.AWS_PROFILE})}return s&&(this.credentialCache=s,this.credentialCacheTimestamp=e),s}}export{Z as BedrockService};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{command as F,cli as ls}from"cleye";import{createRequire as us}from"module";import ds from"crypto";import j from"fs";import ke from"os";import v from"path";import{Buffer as ln}from"node:buffer";import oe from"node:path";import dt,{ChildProcess as un,exec as ms}from"node:child_process";import B from"node:process";import fs,{execSync as ye,exec as ps}from"child_process";import{fileURLToPath as dn}from"node:url";import hs,{constants as mn}from"node:os";import gs from"assert";import ys from"events";import{createWriteStream as ws,createReadStream as Cs,readFileSync as bs}from"node:fs";import Es from"buffer";import mt from"stream";import vs,{promisify as Ps}from"util";import{debuglog as As,promisify as xs}from"node:util";import M from"inquirer";import{from as Le,switchMap as fn,of as Ss,tap as $s,mergeMap as pn,catchError as Rs,BehaviorSubject as hn,ReplaySubject as Is,Subscription as ft,lastValueFrom as pt,toArray as ht,filter as gn,map as yn,Subject as ks}from"rxjs";import I from"fs/promises";import h from"chalk";import Oe from"readline";import wn from"figlet";import Ls from"gradient-string";import Cn from"ora";import Os from"inquirer-reactive-list-prompt";import H from"winston";import"winston-daily-rotate-file";import Ms from"axios";import{fileURLToPath as Ts,pathToFileURL as Ds}from"url";import{readdir as bn,stat as Ns,rm as _s}from"node:fs/promises";import js from"chokidar";import{takeUntil as En,finalize as vn}from"rxjs/operators";var Fs="aicommit2",Pn="2.5.16",Gs="A Reactive CLI that generates commit messages for Git and Jujutsu with various AI",Bs=["cli","ai","git","jujutsu","jj","vcs","version-control","commit","git-commit","jujutsu-commit","command-line","commandline","aipick","aicommit","aicommits","aicommit2","openai","huggingface","anthropic","claude","claude3","gemini","gemini-pro","generative-ai","mistral","ollama","llama3","llama3.2","llama3.3","gemma","llm","chatgpt","cohere","groq","codestral","perplexity","deepseek","deepseek-r1","pre-commit"],Hs="MIT",Us="tak-bro/aicommit2",Ks="Hyungtak Jin(@tak-bro)",Ws="module",qs=["dist"],zs={aicommit2:"./dist/cli.mjs",aic2:"./dist/cli.mjs"},Ys={prepare:"simple-git-hooks",build:"pkgroll --minify",lint:"eslint --cache .","type-check":"tsc",test:"tsx tests",prepack:"pnpm build && clean-pkg-json",prettier:"prettier"},Vs={"@anthropic-ai/sdk":"^0.39.0","@aws-sdk/client-bedrock-runtime":"^3.678.0","@aws-sdk/credential-providers":"^3.678.0","@dqbd/tiktoken":"^1.0.21","@google/generative-ai":"^0.24.1","@inquirer/prompts":"^3.3.2","@pacote/xxhash":"^0.3.2","@types/winston":"^2.4.4",axios:"^1.9.0",chalk:"^5.4.1",chokidar:"^4.0.3",cleye:"^1.3.4","cohere-ai":"^7.19.0","copy-paste":"^1.5.3",figlet:"^1.8.1","formdata-node":"^6.0.3","gradient-string":"^3.0.0","groq-sdk":"^0.7.0",inquirer:"9.2.8","inquirer-reactive-list-prompt":"1.1.0",ollama:"^0.5.15",openai:"^6.3.0",ora:"^8.2.0",readline:"^1.3.0",rxjs:"^7.8.2",undici:"^7.10.0",uuid:"^9.0.1",winston:"^3.17.0","winston-daily-rotate-file":"^5.0.0"},Js={"@github/copilot-sdk":"0.2.0"},Xs={"@pvtnbr/eslint-config":"^0.33.0","@semantic-release/changelog":"^6.0.3","@semantic-release/commit-analyzer":"^12.0.0","@semantic-release/git":"^10.0.1","@semantic-release/github":"^10.3.5","@semantic-release/npm":"^12.0.1","@semantic-release/release-notes-generator":"^13.0.0","@types/figlet":"^1.7.0","@types/ini":"^1.3.34","@types/inquirer":"^9.0.8","@types/node":"^18.19.103","@types/uuid":"^9.0.8","@typescript-eslint/eslint-plugin":"^6.21.0","@typescript-eslint/parser":"^6.21.0","clean-pkg-json":"^1.3.0","conventional-changelog-conventionalcommits":"^7.0.2","conventional-commits-parser":"^5.0.0",eslint:"^8.57.1","eslint-config-prettier":"^8.10.0","eslint-plugin-eslint-comments":"^3.2.0","eslint-plugin-import":"^2.31.0","eslint-plugin-jsonc":"^2.20.1","eslint-plugin-no-use-extend-native":"^0.5.0","eslint-plugin-promise":"^6.6.0","eslint-plugin-unicorn":"^49.0.0","eslint-plugin-unused-imports":"^3.2.0",execa:"^7.2.0","fs-fixture":"^1.2.0","https-proxy-agent":"^5.0.1",ini:"^3.0.1","lint-staged":"^13.3.0",manten:"^0.7.0",pkgroll:"^1.11.1",prettier:"^3.5.3","semantic-release":"^23.1.1","simple-git-hooks":"^2.13.0",tsx:"^3.14.0",typescript:"^4.9.5","undici-types":"^7.10.0"},Qs={extends:["@pvtnbr","prettier"],rules:{"unicorn/no-process-exit":"off"},overrides:[{files:"./src/commands/prepare-commit-msg-hook.ts",rules:{"unicorn/prevent-abbreviations":"off"}}]},Zs={branches:["main"],plugins:[["@semantic-release/commit-analyzer",{preset:"conventionalcommits",releaseRules:[{type:"docs",release:!1},{type:"style",release:!1},{type:"test",release:!1},{type:"ci",release:!1},{type:"refactor",release:"patch"},{type:"chore",release:"patch"},{type:"feat",release:"patch"},{scope:"major",release:"major"},{scope:"minor",release:"minor"},{scope:"patch",release:"patch"}]}],"@semantic-release/release-notes-generator",["@semantic-release/changelog",{changelogFile:"CHANGELOG.md"}],"@semantic-release/github",["@semantic-release/git",{assets:["CHANGELOG.md"],message:"chore(release): ${nextRelease.version} [skip ci]\n\n${nextRelease.notes}"}],"@semantic-release/npm"]},er={name:Fs,version:Pn,description:Gs,keywords:Bs,license:Hs,repository:Us,author:Ks,type:Ws,files:qs,bin:zs,scripts:Ys,"simple-git-hooks":{"pre-commit":"pnpm lint-staged"},"lint-staged":{"*.ts":["prettier --config ./.prettierrc --write","eslint --fix"]},dependencies:Vs,optionalDependencies:Js,devDependencies:Xs,eslintConfig:Qs,release:Zs},gt=us(import.meta.url),V=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function re(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var ie={exports:{}},yt,An;function tr(){if(An)return yt;An=1,yt=o,o.sync=s;var e=j;function t(r,a){var c=a.pathExt!==void 0?a.pathExt:process.env.PATHEXT;if(!c||(c=c.split(";"),c.indexOf("")!==-1))return!0;for(var l=0;l<c.length;l++){var u=c[l].toLowerCase();if(u&&r.substr(-u.length).toLowerCase()===u)return!0}return!1}function n(r,a,c){return!r.isSymbolicLink()&&!r.isFile()?!1:t(a,c)}function o(r,a,c){e.stat(r,function(l,u){c(l,l?!1:n(u,r,a))})}function s(r,a){return n(e.statSync(r),r,a)}return yt}var wt,xn;function nr(){if(xn)return wt;xn=1,wt=t,t.sync=n;var e=j;function t(r,a,c){e.stat(r,function(l,u){c(l,l?!1:o(u,a))})}function n(r,a){return o(e.statSync(r),a)}function o(r,a){return r.isFile()&&s(r,a)}function s(r,a){var c=r.mode,l=r.uid,u=r.gid,d=a.uid!==void 0?a.uid:process.getuid&&process.getuid(),f=a.gid!==void 0?a.gid:process.getgid&&process.getgid(),g=parseInt("100",8),y=parseInt("010",8),m=parseInt("001",8),x=g|y,S=c&m||c&y&&u===f||c&g&&l===d||c&x&&d===0;return S}return wt}var Me;process.platform==="win32"||V.TESTING_WINDOWS?Me=tr():Me=nr();var or=Ct;Ct.sync=sr;function Ct(e,t,n){if(typeof t=="function"&&(n=t,t={}),!n){if(typeof Promise!="function")throw new TypeError("callback not provided");return new Promise(function(o,s){Ct(e,t||{},function(r,a){r?s(r):o(a)})})}Me(e,t||{},function(o,s){o&&(o.code==="EACCES"||t&&t.ignoreErrors)&&(o=null,s=!1),n(o,s)})}function sr(e,t){try{return Me.sync(e,t||{})}catch(n){if(t&&t.ignoreErrors||n.code==="EACCES")return!1;throw n}}const ae=process.platform==="win32"||process.env.OSTYPE==="cygwin"||process.env.OSTYPE==="msys",Sn=v,rr=ae?";":":",$n=or,Rn=e=>Object.assign(new Error(`not found: ${e}`),{code:"ENOENT"}),In=(e,t)=>{const n=t.colon||rr,o=e.match(/\//)||ae&&e.match(/\\/)?[""]:[...ae?[process.cwd()]:[],...(t.path||process.env.PATH||"").split(n)],s=ae?t.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",r=ae?s.split(n):[""];return ae&&e.indexOf(".")!==-1&&r[0]!==""&&r.unshift(""),{pathEnv:o,pathExt:r,pathExtExe:s}},kn=(e,t,n)=>{typeof t=="function"&&(n=t,t={}),t||(t={});const{pathEnv:o,pathExt:s,pathExtExe:r}=In(e,t),a=[],c=u=>new Promise((d,f)=>{if(u===o.length)return t.all&&a.length?d(a):f(Rn(e));const g=o[u],y=/^".*"$/.test(g)?g.slice(1,-1):g,m=Sn.join(y,e),x=!y&&/^\.[\\\/]/.test(e)?e.slice(0,2)+m:m;d(l(x,u,0))}),l=(u,d,f)=>new Promise((g,y)=>{if(f===s.length)return g(c(d+1));const m=s[f];$n(u+m,{pathExt:r},(x,S)=>{if(!x&&S)if(t.all)a.push(u+m);else return g(u+m);return g(l(u,d,f+1))})});return n?c(0).then(u=>n(null,u),n):c(0)},ir=(e,t)=>{t=t||{};const{pathEnv:n,pathExt:o,pathExtExe:s}=In(e,t),r=[];for(let a=0;a<n.length;a++){const c=n[a],l=/^".*"$/.test(c)?c.slice(1,-1):c,u=Sn.join(l,e),d=!l&&/^\.[\\\/]/.test(e)?e.slice(0,2)+u:u;for(let f=0;f<o.length;f++){const g=d+o[f];try{if($n.sync(g,{pathExt:s}))if(t.all)r.push(g);else return g}catch{}}}if(t.all&&r.length)return r;if(t.nothrow)return null;throw Rn(e)};var ar=kn;kn.sync=ir;var bt={exports:{}};const Ln=(e={})=>{const t=e.env||process.env;return(e.platform||process.platform)!=="win32"?"PATH":Object.keys(t).reverse().find(o=>o.toUpperCase()==="PATH")||"Path"};bt.exports=Ln,bt.exports.default=Ln;var cr=bt.exports;const On=v,lr=ar,ur=cr;function Mn(e,t){const n=e.options.env||process.env,o=process.cwd(),s=e.options.cwd!=null,r=s&&process.chdir!==void 0&&!process.chdir.disabled;if(r)try{process.chdir(e.options.cwd)}catch{}let a;try{a=lr.sync(e.command,{path:n[ur({env:n})],pathExt:t?On.delimiter:void 0})}catch{}finally{r&&process.chdir(o)}return a&&(a=On.resolve(s?e.options.cwd:"",a)),a}function dr(e){return Mn(e)||Mn(e,!0)}var mr=dr,Et={};const vt=/([()\][%!^"`<>&|;, *?])/g;function fr(e){return e=e.replace(vt,"^$1"),e}function pr(e,t){return e=`${e}`,e=e.replace(/(?=(\\+?)?)\1"/g,'$1$1\\"'),e=e.replace(/(?=(\\+?)?)\1$/,"$1$1"),e=`"${e}"`,e=e.replace(vt,"^$1"),t&&(e=e.replace(vt,"^$1")),e}Et.command=fr,Et.argument=pr;var hr=/^#!(.*)/;const gr=hr;var yr=(e="")=>{const t=e.match(gr);if(!t)return null;const[n,o]=t[0].replace(/#! ?/,"").split(" "),s=n.split("/").pop();return s==="env"?o:o?`${s} ${o}`:s};const Pt=j,wr=yr;function Cr(e){const n=Buffer.alloc(150);let o;try{o=Pt.openSync(e,"r"),Pt.readSync(o,n,0,150,0),Pt.closeSync(o)}catch{}return wr(n.toString())}var br=Cr;const Er=v,Tn=mr,Dn=Et,vr=br,Pr=process.platform==="win32",Ar=/\.(?:com|exe)$/i,xr=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function Sr(e){e.file=Tn(e);const t=e.file&&vr(e.file);return t?(e.args.unshift(e.file),e.command=t,Tn(e)):e.file}function $r(e){if(!Pr)return e;const t=Sr(e),n=!Ar.test(t);if(e.options.forceShell||n){const o=xr.test(t);e.command=Er.normalize(e.command),e.command=Dn.command(e.command),e.args=e.args.map(r=>Dn.argument(r,o));const s=[e.command].concat(e.args).join(" ");e.args=["/d","/s","/c",`"${s}"`],e.command=process.env.comspec||"cmd.exe",e.options.windowsVerbatimArguments=!0}return e}function Rr(e,t,n){t&&!Array.isArray(t)&&(n=t,t=null),t=t?t.slice(0):[],n=Object.assign({},n);const o={command:e,args:t,options:n,file:void 0,original:{command:e,args:t}};return n.shell?o:$r(o)}var Ir=Rr;const At=process.platform==="win32";function xt(e,t){return Object.assign(new Error(`${t} ${e.command} ENOENT`),{code:"ENOENT",errno:"ENOENT",syscall:`${t} ${e.command}`,path:e.command,spawnargs:e.args})}function kr(e,t){if(!At)return;const n=e.emit;e.emit=function(o,s){if(o==="exit"){const r=Nn(s,t);if(r)return n.call(e,"error",r)}return n.apply(e,arguments)}}function Nn(e,t){return At&&e===1&&!t.file?xt(t.original,"spawn"):null}function Lr(e,t){return At&&e===1&&!t.file?xt(t.original,"spawnSync"):null}var Or={hookChildProcess:kr,verifyENOENT:Nn,verifyENOENTSync:Lr,notFoundError:xt};const _n=fs,St=Ir,$t=Or;function jn(e,t,n){const o=St(e,t,n),s=_n.spawn(o.command,o.args,o.options);return $t.hookChildProcess(s,o),s}function Mr(e,t,n){const o=St(e,t,n),s=_n.spawnSync(o.command,o.args,o.options);return s.error=s.error||$t.verifyENOENTSync(s.status,o),s}ie.exports=jn,ie.exports.spawn=jn,ie.exports.sync=Mr,ie.exports._parse=St,ie.exports._enoent=$t;var Tr=ie.exports,Dr=re(Tr);function Nr(e){const t=typeof e=="string"?`
|
|
1
|
+
import{command as F,cli as ls}from"cleye";import{createRequire as us}from"module";import ds from"crypto";import j from"fs";import ke from"os";import v from"path";import{Buffer as ln}from"node:buffer";import oe from"node:path";import dt,{ChildProcess as un,exec as ms}from"node:child_process";import B from"node:process";import fs,{execSync as ye,exec as ps}from"child_process";import{fileURLToPath as dn}from"node:url";import hs,{constants as mn}from"node:os";import gs from"assert";import ys from"events";import{createWriteStream as ws,createReadStream as Cs,readFileSync as bs}from"node:fs";import Es from"buffer";import mt from"stream";import vs,{promisify as Ps}from"util";import{debuglog as As,promisify as xs}from"node:util";import M from"inquirer";import{from as Le,switchMap as fn,of as Ss,tap as $s,mergeMap as pn,catchError as Rs,BehaviorSubject as hn,ReplaySubject as Is,Subscription as ft,lastValueFrom as pt,toArray as ht,filter as gn,map as yn,Subject as ks}from"rxjs";import I from"fs/promises";import h from"chalk";import Oe from"readline";import wn from"figlet";import Ls from"gradient-string";import Cn from"ora";import Os from"inquirer-reactive-list-prompt";import H from"winston";import"winston-daily-rotate-file";import Ms from"axios";import{fileURLToPath as Ts,pathToFileURL as Ds}from"url";import{readdir as bn,stat as Ns,rm as _s}from"node:fs/promises";import js from"chokidar";import{takeUntil as En,finalize as vn}from"rxjs/operators";var Fs="aicommit2",Pn="2.5.18",Gs="A Reactive CLI that generates commit messages for Git and Jujutsu with various AI",Bs=["cli","ai","git","jujutsu","jj","vcs","version-control","commit","git-commit","jujutsu-commit","command-line","commandline","aipick","aicommit","aicommits","aicommit2","openai","huggingface","anthropic","claude","claude3","gemini","gemini-pro","generative-ai","mistral","ollama","llama3","llama3.2","llama3.3","gemma","llm","chatgpt","cohere","groq","codestral","perplexity","deepseek","deepseek-r1","pre-commit"],Hs="MIT",Us="tak-bro/aicommit2",Ks="Hyungtak Jin(@tak-bro)",Ws="module",qs=["dist"],zs={aicommit2:"./dist/cli.mjs",aic2:"./dist/cli.mjs"},Ys={prepare:"simple-git-hooks",build:"pkgroll --minify",lint:"eslint --cache .","type-check":"tsc",test:"tsx tests",prepack:"pnpm build && clean-pkg-json",prettier:"prettier"},Vs={"@anthropic-ai/sdk":"^0.39.0","@aws-sdk/client-bedrock-runtime":"^3.678.0","@aws-sdk/credential-providers":"^3.678.0","@dqbd/tiktoken":"^1.0.21","@google/generative-ai":"^0.24.1","@inquirer/prompts":"^3.3.2","@pacote/xxhash":"^0.3.2","@types/winston":"^2.4.4",axios:"^1.9.0",chalk:"^5.4.1",chokidar:"^4.0.3",cleye:"^1.3.4","cohere-ai":"^7.19.0","copy-paste":"^1.5.3",figlet:"^1.8.1","formdata-node":"^6.0.3","gradient-string":"^3.0.0","groq-sdk":"^0.7.0",inquirer:"9.2.8","inquirer-reactive-list-prompt":"1.1.0",ollama:"^0.5.15",openai:"^6.3.0",ora:"^8.2.0",readline:"^1.3.0",rxjs:"^7.8.2",undici:"^7.10.0",uuid:"^9.0.1",winston:"^3.17.0","winston-daily-rotate-file":"^5.0.0"},Js={"@github/copilot-sdk":"0.2.0"},Xs={"@pvtnbr/eslint-config":"^0.33.0","@semantic-release/changelog":"^6.0.3","@semantic-release/commit-analyzer":"^12.0.0","@semantic-release/git":"^10.0.1","@semantic-release/github":"^10.3.5","@semantic-release/npm":"^12.0.1","@semantic-release/release-notes-generator":"^13.0.0","@types/figlet":"^1.7.0","@types/ini":"^1.3.34","@types/inquirer":"^9.0.8","@types/node":"^18.19.103","@types/uuid":"^9.0.8","@typescript-eslint/eslint-plugin":"^6.21.0","@typescript-eslint/parser":"^6.21.0","clean-pkg-json":"^1.3.0","conventional-changelog-conventionalcommits":"^7.0.2","conventional-commits-parser":"^5.0.0",eslint:"^8.57.1","eslint-config-prettier":"^8.10.0","eslint-plugin-eslint-comments":"^3.2.0","eslint-plugin-import":"^2.31.0","eslint-plugin-jsonc":"^2.20.1","eslint-plugin-no-use-extend-native":"^0.5.0","eslint-plugin-promise":"^6.6.0","eslint-plugin-unicorn":"^49.0.0","eslint-plugin-unused-imports":"^3.2.0",execa:"^7.2.0","fs-fixture":"^1.2.0","https-proxy-agent":"^5.0.1",ini:"^3.0.1","lint-staged":"^13.3.0",manten:"^0.7.0",pkgroll:"^1.11.1",prettier:"^3.5.3","semantic-release":"^23.1.1","simple-git-hooks":"^2.13.0",tsx:"^3.14.0",typescript:"^4.9.5","undici-types":"^7.10.0"},Qs={extends:["@pvtnbr","prettier"],rules:{"unicorn/no-process-exit":"off"},overrides:[{files:"./src/commands/prepare-commit-msg-hook.ts",rules:{"unicorn/prevent-abbreviations":"off"}}]},Zs={branches:["main"],plugins:[["@semantic-release/commit-analyzer",{preset:"conventionalcommits",releaseRules:[{type:"docs",release:!1},{type:"style",release:!1},{type:"test",release:!1},{type:"ci",release:!1},{type:"refactor",release:"patch"},{type:"chore",release:"patch"},{type:"feat",release:"patch"},{scope:"major",release:"major"},{scope:"minor",release:"minor"},{scope:"patch",release:"patch"}]}],"@semantic-release/release-notes-generator",["@semantic-release/changelog",{changelogFile:"CHANGELOG.md"}],"@semantic-release/github",["@semantic-release/git",{assets:["CHANGELOG.md"],message:"chore(release): ${nextRelease.version} [skip ci]\n\n${nextRelease.notes}"}],"@semantic-release/npm"]},er={name:Fs,version:Pn,description:Gs,keywords:Bs,license:Hs,repository:Us,author:Ks,type:Ws,files:qs,bin:zs,scripts:Ys,"simple-git-hooks":{"pre-commit":"pnpm lint-staged"},"lint-staged":{"*.ts":["prettier --config ./.prettierrc --write","eslint --fix"]},dependencies:Vs,optionalDependencies:Js,devDependencies:Xs,eslintConfig:Qs,release:Zs},gt=us(import.meta.url),V=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function re(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var ie={exports:{}},yt,An;function tr(){if(An)return yt;An=1,yt=o,o.sync=s;var e=j;function t(r,a){var c=a.pathExt!==void 0?a.pathExt:process.env.PATHEXT;if(!c||(c=c.split(";"),c.indexOf("")!==-1))return!0;for(var l=0;l<c.length;l++){var u=c[l].toLowerCase();if(u&&r.substr(-u.length).toLowerCase()===u)return!0}return!1}function n(r,a,c){return!r.isSymbolicLink()&&!r.isFile()?!1:t(a,c)}function o(r,a,c){e.stat(r,function(l,u){c(l,l?!1:n(u,r,a))})}function s(r,a){return n(e.statSync(r),r,a)}return yt}var wt,xn;function nr(){if(xn)return wt;xn=1,wt=t,t.sync=n;var e=j;function t(r,a,c){e.stat(r,function(l,u){c(l,l?!1:o(u,a))})}function n(r,a){return o(e.statSync(r),a)}function o(r,a){return r.isFile()&&s(r,a)}function s(r,a){var c=r.mode,l=r.uid,u=r.gid,d=a.uid!==void 0?a.uid:process.getuid&&process.getuid(),f=a.gid!==void 0?a.gid:process.getgid&&process.getgid(),g=parseInt("100",8),y=parseInt("010",8),m=parseInt("001",8),x=g|y,S=c&m||c&y&&u===f||c&g&&l===d||c&x&&d===0;return S}return wt}var Me;process.platform==="win32"||V.TESTING_WINDOWS?Me=tr():Me=nr();var or=Ct;Ct.sync=sr;function Ct(e,t,n){if(typeof t=="function"&&(n=t,t={}),!n){if(typeof Promise!="function")throw new TypeError("callback not provided");return new Promise(function(o,s){Ct(e,t||{},function(r,a){r?s(r):o(a)})})}Me(e,t||{},function(o,s){o&&(o.code==="EACCES"||t&&t.ignoreErrors)&&(o=null,s=!1),n(o,s)})}function sr(e,t){try{return Me.sync(e,t||{})}catch(n){if(t&&t.ignoreErrors||n.code==="EACCES")return!1;throw n}}const ae=process.platform==="win32"||process.env.OSTYPE==="cygwin"||process.env.OSTYPE==="msys",Sn=v,rr=ae?";":":",$n=or,Rn=e=>Object.assign(new Error(`not found: ${e}`),{code:"ENOENT"}),In=(e,t)=>{const n=t.colon||rr,o=e.match(/\//)||ae&&e.match(/\\/)?[""]:[...ae?[process.cwd()]:[],...(t.path||process.env.PATH||"").split(n)],s=ae?t.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",r=ae?s.split(n):[""];return ae&&e.indexOf(".")!==-1&&r[0]!==""&&r.unshift(""),{pathEnv:o,pathExt:r,pathExtExe:s}},kn=(e,t,n)=>{typeof t=="function"&&(n=t,t={}),t||(t={});const{pathEnv:o,pathExt:s,pathExtExe:r}=In(e,t),a=[],c=u=>new Promise((d,f)=>{if(u===o.length)return t.all&&a.length?d(a):f(Rn(e));const g=o[u],y=/^".*"$/.test(g)?g.slice(1,-1):g,m=Sn.join(y,e),x=!y&&/^\.[\\\/]/.test(e)?e.slice(0,2)+m:m;d(l(x,u,0))}),l=(u,d,f)=>new Promise((g,y)=>{if(f===s.length)return g(c(d+1));const m=s[f];$n(u+m,{pathExt:r},(x,S)=>{if(!x&&S)if(t.all)a.push(u+m);else return g(u+m);return g(l(u,d,f+1))})});return n?c(0).then(u=>n(null,u),n):c(0)},ir=(e,t)=>{t=t||{};const{pathEnv:n,pathExt:o,pathExtExe:s}=In(e,t),r=[];for(let a=0;a<n.length;a++){const c=n[a],l=/^".*"$/.test(c)?c.slice(1,-1):c,u=Sn.join(l,e),d=!l&&/^\.[\\\/]/.test(e)?e.slice(0,2)+u:u;for(let f=0;f<o.length;f++){const g=d+o[f];try{if($n.sync(g,{pathExt:s}))if(t.all)r.push(g);else return g}catch{}}}if(t.all&&r.length)return r;if(t.nothrow)return null;throw Rn(e)};var ar=kn;kn.sync=ir;var bt={exports:{}};const Ln=(e={})=>{const t=e.env||process.env;return(e.platform||process.platform)!=="win32"?"PATH":Object.keys(t).reverse().find(o=>o.toUpperCase()==="PATH")||"Path"};bt.exports=Ln,bt.exports.default=Ln;var cr=bt.exports;const On=v,lr=ar,ur=cr;function Mn(e,t){const n=e.options.env||process.env,o=process.cwd(),s=e.options.cwd!=null,r=s&&process.chdir!==void 0&&!process.chdir.disabled;if(r)try{process.chdir(e.options.cwd)}catch{}let a;try{a=lr.sync(e.command,{path:n[ur({env:n})],pathExt:t?On.delimiter:void 0})}catch{}finally{r&&process.chdir(o)}return a&&(a=On.resolve(s?e.options.cwd:"",a)),a}function dr(e){return Mn(e)||Mn(e,!0)}var mr=dr,Et={};const vt=/([()\][%!^"`<>&|;, *?])/g;function fr(e){return e=e.replace(vt,"^$1"),e}function pr(e,t){return e=`${e}`,e=e.replace(/(?=(\\+?)?)\1"/g,'$1$1\\"'),e=e.replace(/(?=(\\+?)?)\1$/,"$1$1"),e=`"${e}"`,e=e.replace(vt,"^$1"),t&&(e=e.replace(vt,"^$1")),e}Et.command=fr,Et.argument=pr;var hr=/^#!(.*)/;const gr=hr;var yr=(e="")=>{const t=e.match(gr);if(!t)return null;const[n,o]=t[0].replace(/#! ?/,"").split(" "),s=n.split("/").pop();return s==="env"?o:o?`${s} ${o}`:s};const Pt=j,wr=yr;function Cr(e){const n=Buffer.alloc(150);let o;try{o=Pt.openSync(e,"r"),Pt.readSync(o,n,0,150,0),Pt.closeSync(o)}catch{}return wr(n.toString())}var br=Cr;const Er=v,Tn=mr,Dn=Et,vr=br,Pr=process.platform==="win32",Ar=/\.(?:com|exe)$/i,xr=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function Sr(e){e.file=Tn(e);const t=e.file&&vr(e.file);return t?(e.args.unshift(e.file),e.command=t,Tn(e)):e.file}function $r(e){if(!Pr)return e;const t=Sr(e),n=!Ar.test(t);if(e.options.forceShell||n){const o=xr.test(t);e.command=Er.normalize(e.command),e.command=Dn.command(e.command),e.args=e.args.map(r=>Dn.argument(r,o));const s=[e.command].concat(e.args).join(" ");e.args=["/d","/s","/c",`"${s}"`],e.command=process.env.comspec||"cmd.exe",e.options.windowsVerbatimArguments=!0}return e}function Rr(e,t,n){t&&!Array.isArray(t)&&(n=t,t=null),t=t?t.slice(0):[],n=Object.assign({},n);const o={command:e,args:t,options:n,file:void 0,original:{command:e,args:t}};return n.shell?o:$r(o)}var Ir=Rr;const At=process.platform==="win32";function xt(e,t){return Object.assign(new Error(`${t} ${e.command} ENOENT`),{code:"ENOENT",errno:"ENOENT",syscall:`${t} ${e.command}`,path:e.command,spawnargs:e.args})}function kr(e,t){if(!At)return;const n=e.emit;e.emit=function(o,s){if(o==="exit"){const r=Nn(s,t);if(r)return n.call(e,"error",r)}return n.apply(e,arguments)}}function Nn(e,t){return At&&e===1&&!t.file?xt(t.original,"spawn"):null}function Lr(e,t){return At&&e===1&&!t.file?xt(t.original,"spawnSync"):null}var Or={hookChildProcess:kr,verifyENOENT:Nn,verifyENOENTSync:Lr,notFoundError:xt};const _n=fs,St=Ir,$t=Or;function jn(e,t,n){const o=St(e,t,n),s=_n.spawn(o.command,o.args,o.options);return $t.hookChildProcess(s,o),s}function Mr(e,t,n){const o=St(e,t,n),s=_n.spawnSync(o.command,o.args,o.options);return s.error=s.error||$t.verifyENOENTSync(s.status,o),s}ie.exports=jn,ie.exports.spawn=jn,ie.exports.sync=Mr,ie.exports._parse=St,ie.exports._enoent=$t;var Tr=ie.exports,Dr=re(Tr);function Nr(e){const t=typeof e=="string"?`
|
|
2
2
|
`:`
|
|
3
3
|
`.charCodeAt(),n=typeof e=="string"?"\r":"\r".charCodeAt();return e[e.length-1]===t&&(e=e.slice(0,-1)),e[e.length-1]===n&&(e=e.slice(0,-1)),e}function Fn(e={}){const{env:t=process.env,platform:n=process.platform}=e;return n!=="win32"?"PATH":Object.keys(t).reverse().find(o=>o.toUpperCase()==="PATH")||"Path"}const _r=({cwd:e=B.cwd(),path:t=B.env[Fn()],preferLocal:n=!0,execPath:o=B.execPath,addExecPath:s=!0}={})=>{const r=e instanceof URL?dn(e):e,a=oe.resolve(r),c=[];return n&&jr(c,a),s&&Fr(c,o,a),[...c,t].join(oe.delimiter)},jr=(e,t)=>{let n;for(;n!==t;)e.push(oe.join(t,"node_modules/.bin")),n=t,t=oe.resolve(t,"..")},Fr=(e,t,n)=>{const o=t instanceof URL?dn(t):t;e.push(oe.resolve(n,o,".."))},Gr=({env:e=B.env,...t}={})=>{e={...e};const n=Fn({env:e});return t.path=e[n],e[n]=_r(t),e},Br=(e,t,n,o)=>{if(n==="length"||n==="prototype"||n==="arguments"||n==="caller")return;const s=Object.getOwnPropertyDescriptor(e,n),r=Object.getOwnPropertyDescriptor(t,n);!Hr(s,r)&&o||Object.defineProperty(e,n,r)},Hr=function(e,t){return e===void 0||e.configurable||e.writable===t.writable&&e.enumerable===t.enumerable&&e.configurable===t.configurable&&(e.writable||e.value===t.value)},Ur=(e,t)=>{const n=Object.getPrototypeOf(t);n!==Object.getPrototypeOf(e)&&Object.setPrototypeOf(e,n)},Kr=(e,t)=>`/* Wrapped ${e}*/
|
|
4
4
|
${t}`,Wr=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),qr=Object.getOwnPropertyDescriptor(Function.prototype.toString,"name"),zr=(e,t,n)=>{const o=n===""?"":`with ${n.trim()}() `,s=Kr.bind(null,o,t.toString());Object.defineProperty(s,"name",qr),Object.defineProperty(e,"toString",{...Wr,value:s})};function Yr(e,t,{ignoreNonConfigurable:n=!1}={}){const{name:o}=e;for(const s of Reflect.ownKeys(t))Br(e,t,s,n);return Ur(e,t),zr(e,t,o),e}const Te=new WeakMap,Gn=(e,t={})=>{if(typeof e!="function")throw new TypeError("Expected a function");let n,o=0;const s=e.displayName||e.name||"<anonymous>",r=function(...a){if(Te.set(r,++o),o===1)n=e.apply(this,a),e=null;else if(t.throw===!0)throw new Error(`Function \`${s}\` can only be called once`);return n};return Yr(r,e),Te.set(r,o),r};Gn.callCount=e=>{if(!Te.has(e))throw new Error(`The given function \`${e.name}\` is not wrapped by the \`onetime\` package`);return Te.get(e)};const Vr=()=>{const e=Hn-Bn+1;return Array.from({length:e},Jr)},Jr=(e,t)=>({name:`SIGRT${t+1}`,number:Bn+t,action:"terminate",description:"Application-specific signal (realtime)",standard:"posix"}),Bn=34,Hn=64,Xr=[{name:"SIGHUP",number:1,action:"terminate",description:"Terminal closed",standard:"posix"},{name:"SIGINT",number:2,action:"terminate",description:"User interruption with CTRL-C",standard:"ansi"},{name:"SIGQUIT",number:3,action:"core",description:"User interruption with CTRL-\\",standard:"posix"},{name:"SIGILL",number:4,action:"core",description:"Invalid machine instruction",standard:"ansi"},{name:"SIGTRAP",number:5,action:"core",description:"Debugger breakpoint",standard:"posix"},{name:"SIGABRT",number:6,action:"core",description:"Aborted",standard:"ansi"},{name:"SIGIOT",number:6,action:"core",description:"Aborted",standard:"bsd"},{name:"SIGBUS",number:7,action:"core",description:"Bus error due to misaligned, non-existing address or paging error",standard:"bsd"},{name:"SIGEMT",number:7,action:"terminate",description:"Command should be emulated but is not implemented",standard:"other"},{name:"SIGFPE",number:8,action:"core",description:"Floating point arithmetic error",standard:"ansi"},{name:"SIGKILL",number:9,action:"terminate",description:"Forced termination",standard:"posix",forced:!0},{name:"SIGUSR1",number:10,action:"terminate",description:"Application-specific signal",standard:"posix"},{name:"SIGSEGV",number:11,action:"core",description:"Segmentation fault",standard:"ansi"},{name:"SIGUSR2",number:12,action:"terminate",description:"Application-specific signal",standard:"posix"},{name:"SIGPIPE",number:13,action:"terminate",description:"Broken pipe or socket",standard:"posix"},{name:"SIGALRM",number:14,action:"terminate",description:"Timeout or timer",standard:"posix"},{name:"SIGTERM",number:15,action:"terminate",description:"Termination",standard:"ansi"},{name:"SIGSTKFLT",number:16,action:"terminate",description:"Stack is empty or overflowed",standard:"other"},{name:"SIGCHLD",number:17,action:"ignore",description:"Child process terminated, paused or unpaused",standard:"posix"},{name:"SIGCLD",number:17,action:"ignore",description:"Child process terminated, paused or unpaused",standard:"other"},{name:"SIGCONT",number:18,action:"unpause",description:"Unpaused",standard:"posix",forced:!0},{name:"SIGSTOP",number:19,action:"pause",description:"Paused",standard:"posix",forced:!0},{name:"SIGTSTP",number:20,action:"pause",description:'Paused using CTRL-Z or "suspend"',standard:"posix"},{name:"SIGTTIN",number:21,action:"pause",description:"Background process cannot read terminal input",standard:"posix"},{name:"SIGBREAK",number:21,action:"terminate",description:"User interruption with CTRL-BREAK",standard:"other"},{name:"SIGTTOU",number:22,action:"pause",description:"Background process cannot write to terminal output",standard:"posix"},{name:"SIGURG",number:23,action:"ignore",description:"Socket received out-of-band data",standard:"bsd"},{name:"SIGXCPU",number:24,action:"core",description:"Process timed out",standard:"bsd"},{name:"SIGXFSZ",number:25,action:"core",description:"File too big",standard:"bsd"},{name:"SIGVTALRM",number:26,action:"terminate",description:"Timeout or timer",standard:"bsd"},{name:"SIGPROF",number:27,action:"terminate",description:"Timeout or timer",standard:"bsd"},{name:"SIGWINCH",number:28,action:"ignore",description:"Terminal window size changed",standard:"bsd"},{name:"SIGIO",number:29,action:"terminate",description:"I/O is available",standard:"other"},{name:"SIGPOLL",number:29,action:"terminate",description:"Watched event",standard:"other"},{name:"SIGINFO",number:29,action:"ignore",description:"Request for process information",standard:"other"},{name:"SIGPWR",number:30,action:"terminate",description:"Device running out of power",standard:"systemv"},{name:"SIGSYS",number:31,action:"core",description:"Invalid system call",standard:"other"},{name:"SIGUNUSED",number:31,action:"terminate",description:"Invalid system call",standard:"other"}],Un=()=>{const e=Vr();return[...Xr,...e].map(Qr)},Qr=({name:e,number:t,description:n,action:o,forced:s=!1,standard:r})=>{const{signals:{[e]:a}}=mn,c=a!==void 0;return{name:e,number:c?a:t,description:n,supported:c,action:o,forced:s,standard:r}},Zr=()=>{const e=Un();return Object.fromEntries(e.map(ei))},ei=({name:e,number:t,description:n,supported:o,action:s,forced:r,standard:a})=>[e,{name:e,number:t,description:n,supported:o,action:s,forced:r,standard:a}],ti=Zr(),ni=()=>{const e=Un(),t=Hn+1,n=Array.from({length:t},(o,s)=>oi(s,e));return Object.assign({},...n)},oi=(e,t)=>{const n=si(e,t);if(n===void 0)return{};const{name:o,description:s,supported:r,action:a,forced:c,standard:l}=n;return{[e]:{name:o,number:e,description:s,supported:r,action:a,forced:c,standard:l}}},si=(e,t)=>{const n=t.find(({name:o})=>mn.signals[o]===e);return n!==void 0?n:t.find(o=>o.number===e)};ni();const ri=({timedOut:e,timeout:t,errorCode:n,signal:o,signalDescription:s,exitCode:r,isCanceled:a})=>e?`timed out after ${t} milliseconds`:a?"was canceled":n!==void 0?`failed with ${n}`:o!==void 0?`was killed with ${o} (${s})`:r!==void 0?`failed with exit code ${r}`:"failed",De=({stdout:e,stderr:t,all:n,error:o,signal:s,exitCode:r,command:a,escapedCommand:c,timedOut:l,isCanceled:u,killed:d,parsed:{options:{timeout:f,cwd:g=B.cwd()}}})=>{r=r===null?void 0:r,s=s===null?void 0:s;const y=s===void 0?void 0:ti[s].description,m=o&&o.code,S=`Command ${ri({timedOut:l,timeout:f,errorCode:m,signal:s,signalDescription:y,exitCode:r,isCanceled:u})}: ${a}`,A=Object.prototype.toString.call(o)==="[object Error]",$=A?`${S}
|
|
@@ -13,12 +13,12 @@ ${o.message}`:S,P=[$,t,e].filter(Boolean).join(`
|
|
|
13
13
|
`).slice(1).join(`
|
|
14
14
|
`))),console.error(`
|
|
15
15
|
${ve}${h.dim(`aicommit2 v${Pn}`)}`),console.error(`
|
|
16
|
-
${ve}Please open a Bug report with the information above:`),console.error(`${ve}https://github.com/tak-bro/aicommit2/issues/new/choose`)}},He=e=>I.lstat(e).then(()=>!0,()=>!1),go=async e=>{try{await I.mkdir(e,{recursive:!0})}catch(t){if(t.code!=="EEXIST")throw t}},ya=e=>e&&`${e[0].toUpperCase()}${e.slice(1)}`,wa=(e,t)=>{const n=Math.ceil(e),o=Math.floor(t);return Math.floor(Math.random()*(o-n+1))+n},yo=(e,t)=>e.disabled&&!t.disabled?1:!e.disabled&&t.disabled?-1:0,Ft=e=>e.reduce((t,n)=>Array.isArray(n)?t.concat(Ft(n)):t.concat(n),[]),Ca=(e,t=5)=>e.replace(/[\n\r]/g,"").split(" ").slice(0,t).join(" "),ba=e=>{let t=0;for(let n=0;n<e.length;n++){const o=e.charCodeAt(n);t=(t<<5)-t+o,t=t&t}return Math.abs(t)},Ea=e=>{const t=e%360,n=65+e%15,o=45+e%10;return`hsl(${t}, ${n}%, ${o}%)`},va=e=>{const[t,n,o]=e.match(/\d+/g).map((f,g)=>g===0?Number(f):Number(f)/100),s=(1-Math.abs(2*o-1))*n,r=s*(1-Math.abs(t/60%2-1)),a=o-s/2;let c,l,u;t<60?[c,l,u]=[s,r,0]:t<120?[c,l,u]=[r,s,0]:t<180?[c,l,u]=[0,s,r]:t<240?[c,l,u]=[0,r,s]:t<300?[c,l,u]=[r,0,s]:[c,l,u]=[s,0,r];const d=f=>{const g=Math.round((f+a)*255).toString(16);return g.length===1?"0"+g:g};return`#${d(c)}${d(l)}${d(u)}`},Pa=e=>{const t=ba(e),n=Ea(t);return{primary:va(n),secondary:"#FFFFFF"}},Aa=e=>{try{return{ok:!0,data:JSON.parse(e)}}catch(t){return{ok:!1,error:t}}},Ue=e=>{if(!e||typeof e!="string")return"";if(v.isAbsolute(e))return v.resolve(e);if(xe){const t=v.dirname(xe),n=v.join(t,e);return v.resolve(n)}else return""},xa=["","conventional","gitmoji"],Pe="http://localhost:11434",{hasOwnProperty:Sa}=Object.prototype,Gt=(e,t)=>Sa.call(e,t),fe=["OPENAI","COPILOT_SDK","OPENROUTER","OLLAMA","HUGGINGFACE","GEMINI","ANTHROPIC","MISTRAL","CODESTRAL","COHERE","GROQ","PERPLEXITY","DEEPSEEK","GITHUB_MODELS","BEDROCK"],wo=e=>{const t=ke.platform(),n=ke.homedir();let o,s;switch(e){case"config":o=process.env.XDG_CONFIG_HOME;break;case"data":o=process.env.XDG_DATA_HOME;break;case"cache":o=process.env.XDG_CACHE_HOME;break;case"state":o=process.env.XDG_STATE_HOME;break;default:o=void 0}if(t==="darwin")e==="cache"?s=v.join(n,"Library","Caches"):s=v.join(n,"Library","Application Support");else if(t==="win32")s=process.env.LOCALAPPDATA||n;else switch(e){case"config":s=v.join(n,".config");break;case"data":s=v.join(n,".local","share");break;case"cache":s=v.join(n,".cache");break;case"state":s=v.join(n,".local","state");break;default:s=n}return o||s},Co=v.join(wo("config"),"aicommit2"),U=v.join(wo("state"),"aicommit2","logs"),bo=v.join(Co,"config.ini"),Eo=v.join(U,"aicommit2-%DATE%.log"),vo=v.join(U,"exceptions-%DATE%.log"),$a=e=>{const t=Object.keys(e),n=new Set([...fe,...t.filter(o=>/^[A-Z][A-Z0-9_]*$/.test(o))]);return Array.from(n)},E=(e,t,n)=>{if(!t)throw new p(`Invalid config property ${e}: ${n}`)},G=(e,t=!1)=>n=>typeof n=="boolean"?n:n==null?t:(E(e,/^(?:true|false)$/.test(n),"Must be a boolean(true or false)"),n==="true"),Ke=e=>t=>{if(!t)return{};if(typeof t=="object")return E(e,!Array.isArray(t),"Must be a JSON object"),t;try{const n=JSON.parse(t);return E(e,typeof n=="object"&&n!==null&&!Array.isArray(n),"Must be a valid JSON object"),n}catch(n){throw new p(`Invalid ${e}: Must be valid JSON. Error: ${n.message}`)}},i={systemPrompt(e){return e||""},systemPromptPath(e){return e||""},codeReviewPromptPath(e){return e||""},timeout(e){if(!e)return 6e4;E("timeout",/^\d+$/.test(e),"Must be an integer");const t=Number(e);return E("timeout",t>=500,"Must be greater than 500ms"),t},temperature(e){if(!e)return .7;E("temperature",/^(2|\d)(\.\d{1,2})?$/.test(e),"Must be decimal between 0 and 2");const t=Number(e);return E("temperature",t>0,"Must be greater than 0"),E("temperature",t<=2,"Must be less than or equal to 2"),t},maxTokens(e){return e?(E("maxTokens",/^\d+$/.test(e),"Must be an integer"),Number(e)):8192},logLevel(e){return e?(E("logLevel",/^(?:error|warn|info|http|verbose|debug|silly)$/.test(e),"Must be a valid log level (error, warn, info, http, verbose, debug, silly)"),e):"info"},logFilePath(e){return e||Eo},exceptionLogFilePath(e){return e||vo},locale(e){return e?(E("locale",e,"Cannot be empty"),E("locale",/^[a-z-]+$/i.test(e),"Must be a valid locale (letters and dashes/underscores). You can consult the list of codes in: https://wikipedia.org/wiki/List_of_ISO_639-1_codes"),e):"en"},generate(e){if(!e)return 1;E("generate",/^\d+$/.test(e),"Must be an integer");const t=Number(e);return E("generate",t>0,"Must be greater than 0"),E("generate",t<=5,"Must be less or equal to 5"),t},type(e){return e?(E("type",xa.includes(e),"Invalid commit type"),e):"conventional"},maxLength(e){if(!e)return 50;E("maxLength",/^\d+$/.test(e),"Must be an integer");const t=Number(e);return E("maxLength",t>=20,"Must be greater than 20 characters"),t},exclude:e=>e?(typeof e=="string"?e?.split(","):e).map(n=>n.trim()).filter(n=>!!n&&n.length>0):[],topP:e=>{if(!e)return .9;E("topP",/^(1|\d)(\.\d{1,2})?$/.test(e),"Must be decimal between 0 and 1");const t=Number(e);return E("topP",t>0,"Must be greater than 0"),E("topP",t<=1,"Must be less than or equal to 1"),t},logging:G("logging",!0),includeBody:G("includeBody"),codeReview:G("codeReview"),disabled:G("disabled"),watchMode:G("watchMode"),forceGit:G("forceGit"),stream:G("stream"),disableLowerCase:G("disableLowerCase"),jjAutoNew:G("jjAutoNew"),autoCopy:G("autoCopy"),modelNameDisplay:e=>e?(E("modelNameDisplay",/^(?:none|short|full)$/.test(e),"Must be none, short, or full"),e):"short",diffCompression:e=>e?(E("diffCompression",/^(?:none|compact)$/.test(e),"Must be none or compact"),e):ho.mode,maxHunkLines:e=>e?(E("maxHunkLines",/^\d+$/.test(e),"Must be an integer"),Number(e)):0,maxDiffLines:e=>e?(E("maxDiffLines",/^\d+$/.test(e),"Must be an integer"),Number(e)):0,diffContext:e=>{if(!e)return me;E("diffContext",/^\d+$/.test(e),"Must be an integer");const t=Number(e);return E("diffContext",t>=0&&t<=10,"Must be between 0 and 10"),t},useStats:G("useStats",!0),statsDays:e=>{if(!e)return 30;E("statsDays",/^\d+$/.test(e),"Must be an integer");const t=Number(e);return E("statsDays",t>0,"Must be greater than 0"),t}},Ae={OPENAI:{key:e=>e||"",envKey:e=>e||"",model:e=>e?(typeof e=="string"?e?.split(","):e).map(n=>n.trim()).filter(n=>!!n&&n.length>0):["gpt-4o-mini"],url:e=>e?(E("OPENAI.url",/^https?:\/\//.test(e),"Must be a valid URL"),e):"https://api.openai.com",path:e=>e||"/v1/chat/completions",proxy:e=>e||"",topP:i.topP,systemPrompt:i.systemPrompt,systemPromptPath:i.systemPromptPath,codeReviewPromptPath:i.codeReviewPromptPath,timeout:i.timeout,temperature:i.temperature,maxTokens:i.maxTokens,logging:i.logging,locale:i.locale,generate:i.generate,type:i.type,maxLength:i.maxLength,includeBody:i.includeBody,codeReview:i.codeReview,disabled:i.disabled,stream:i.stream,watchMode:i.watchMode,disableLowerCase:i.disableLowerCase,diffCompression:i.diffCompression,maxHunkLines:i.maxHunkLines,maxDiffLines:i.maxDiffLines,diffContext:i.diffContext},OPENROUTER:{key:e=>e||"",envKey:e=>e||"",model:e=>e?(typeof e=="string"?e?.split(","):e).map(n=>n.trim()).filter(n=>!!n&&n.length>0):["openrouter/auto"],url:e=>e?(E("OPENROUTER.url",/^https?:\/\//.test(e),"Must be a valid URL"),e):"https://openrouter.ai",path:e=>e||"/api/v1/chat/completions",responseFormat:Ke("OPENROUTER.responseFormat"),provider:Ke("OPENROUTER.provider"),reasoning:Ke("OPENROUTER.reasoning"),topP:i.topP,systemPrompt:i.systemPrompt,systemPromptPath:i.systemPromptPath,codeReviewPromptPath:i.codeReviewPromptPath,timeout:i.timeout,temperature:i.temperature,maxTokens:i.maxTokens,logging:i.logging,locale:i.locale,generate:i.generate,type:i.type,maxLength:i.maxLength,includeBody:i.includeBody,codeReview:i.codeReview,disabled:i.disabled,stream:i.stream,watchMode:i.watchMode,disableLowerCase:i.disableLowerCase,diffCompression:i.diffCompression,maxHunkLines:i.maxHunkLines,maxDiffLines:i.maxDiffLines,diffContext:i.diffContext},HUGGINGFACE:{cookie:e=>e||"",model:e=>e?(typeof e=="string"?e?.split(","):e).map(n=>n.trim()).filter(n=>!!n&&n.length>0):["CohereForAI/c4ai-command-r-plus"],systemPrompt:i.systemPrompt,systemPromptPath:i.systemPromptPath,codeReviewPromptPath:i.codeReviewPromptPath,timeout:i.timeout,temperature:i.temperature,maxTokens:i.maxTokens,topP:i.topP,logging:i.logging,locale:i.locale,generate:i.generate,type:i.type,maxLength:i.maxLength,includeBody:i.includeBody,codeReview:i.codeReview,disabled:i.disabled,stream:i.stream,watchMode:i.watchMode,disableLowerCase:i.disableLowerCase,diffCompression:i.diffCompression,maxHunkLines:i.maxHunkLines,maxDiffLines:i.maxDiffLines,diffContext:i.diffContext},GEMINI:{key:e=>e||"",envKey:e=>e||"",model:e=>e?(typeof e=="string"?e?.split(","):e).map(n=>n.trim()).filter(n=>!!n&&n.length>0):["gemini-3-flash-preview"],systemPrompt:i.systemPrompt,systemPromptPath:i.systemPromptPath,codeReviewPromptPath:i.codeReviewPromptPath,timeout:i.timeout,temperature:i.temperature,maxTokens:i.maxTokens,logging:i.logging,locale:i.locale,generate:i.generate,type:i.type,maxLength:i.maxLength,includeBody:i.includeBody,topP:i.topP,codeReview:i.codeReview,disabled:i.disabled,stream:i.stream,watchMode:i.watchMode,disableLowerCase:i.disableLowerCase,diffCompression:i.diffCompression,maxHunkLines:i.maxHunkLines,maxDiffLines:i.maxDiffLines,diffContext:i.diffContext},ANTHROPIC:{key:e=>e||"",envKey:e=>e||"",model:e=>e?(typeof e=="string"?e?.split(","):e).map(n=>n.trim()).filter(n=>!!n&&n.length>0):["claude-sonnet-4-20250514"],systemPrompt:i.systemPrompt,systemPromptPath:i.systemPromptPath,codeReviewPromptPath:i.codeReviewPromptPath,timeout:i.timeout,temperature:i.temperature,maxTokens:i.maxTokens,logging:i.logging,locale:i.locale,generate:i.generate,type:i.type,maxLength:i.maxLength,includeBody:i.includeBody,topP:i.topP,codeReview:i.codeReview,disabled:i.disabled,stream:i.stream,watchMode:i.watchMode,disableLowerCase:i.disableLowerCase,diffCompression:i.diffCompression,maxHunkLines:i.maxHunkLines,maxDiffLines:i.maxDiffLines,diffContext:i.diffContext},MISTRAL:{key:e=>e||"",envKey:e=>e||"",model:e=>e?(typeof e=="string"?e?.split(","):e).map(n=>n.trim()).filter(n=>!!n&&n.length>0):["mistral-small-latest"],systemPrompt:i.systemPrompt,systemPromptPath:i.systemPromptPath,codeReviewPromptPath:i.codeReviewPromptPath,timeout:i.timeout,temperature:i.temperature,maxTokens:i.maxTokens,logging:i.logging,locale:i.locale,generate:i.generate,type:i.type,maxLength:i.maxLength,includeBody:i.includeBody,topP:i.topP,codeReview:i.codeReview,disabled:i.disabled,stream:i.stream,watchMode:i.watchMode,disableLowerCase:i.disableLowerCase,diffCompression:i.diffCompression,maxHunkLines:i.maxHunkLines,maxDiffLines:i.maxDiffLines,diffContext:i.diffContext},CODESTRAL:{key:e=>e||"",envKey:e=>e||"",model:e=>e?(typeof e=="string"?e?.split(","):e).map(n=>n.trim()).filter(n=>!!n&&n.length>0):["codestral-latest"],topP:i.topP,systemPrompt:i.systemPrompt,systemPromptPath:i.systemPromptPath,codeReviewPromptPath:i.codeReviewPromptPath,timeout:i.timeout,temperature:i.temperature,maxTokens:i.maxTokens,logging:i.logging,locale:i.locale,generate:i.generate,type:i.type,maxLength:i.maxLength,includeBody:i.includeBody,codeReview:i.codeReview,disabled:i.disabled,stream:i.stream,watchMode:i.watchMode,disableLowerCase:i.disableLowerCase,diffCompression:i.diffCompression,maxHunkLines:i.maxHunkLines,maxDiffLines:i.maxDiffLines,diffContext:i.diffContext},OLLAMA:{model:e=>e?(typeof e=="string"?e?.split(","):e).map(n=>n.trim()).filter(n=>!!n&&n.length>0):[],host:e=>e?(E("OLLAMA.host",/^https?:\/\//.test(e),"Must be a valid URL"),e):Pe,timeout:e=>{if(!e)return 1e5;E("OLLAMA.timeout",/^\d+$/.test(e),"Must be an integer");const t=Number(e);return E("OLLAMA.timeout",t>=500,"Must be greater than 500ms"),t},auth:e=>e||"",key:e=>e||"",envKey:e=>e||"",numCtx:e=>{if(!e)return 2048;E("OLLAMA.numCtx",/^\d+$/.test(e),"Must be an integer");const t=Number(e);return E("OLLAMA.numCtx",t>=2048,"Must be greater than 2048"),t},systemPrompt:i.systemPrompt,systemPromptPath:i.systemPromptPath,codeReviewPromptPath:i.codeReviewPromptPath,temperature:i.temperature,maxTokens:i.maxTokens,logging:i.logging,locale:i.locale,generate:i.generate,type:i.type,maxLength:i.maxLength,includeBody:i.includeBody,topP:i.topP,codeReview:i.codeReview,disabled:i.disabled,stream:i.stream,watchMode:i.watchMode,disableLowerCase:i.disableLowerCase,diffCompression:i.diffCompression,maxHunkLines:i.maxHunkLines,maxDiffLines:i.maxDiffLines,diffContext:i.diffContext},COHERE:{key:e=>e||"",envKey:e=>e||"",url:e=>e?(E("COHERE.url",/^https?:\/\//.test(e),"Must be a valid URL"),e):"https://api.cohere.ai",model:e=>e?(typeof e=="string"?e?.split(","):e).map(n=>n.trim()).filter(n=>!!n&&n.length>0):["command-a-03-2025"],systemPrompt:i.systemPrompt,systemPromptPath:i.systemPromptPath,codeReviewPromptPath:i.codeReviewPromptPath,temperature:i.temperature,maxTokens:i.maxTokens,logging:i.logging,locale:i.locale,timeout:i.timeout,generate:i.generate,type:i.type,maxLength:i.maxLength,includeBody:i.includeBody,topP:i.topP,codeReview:i.codeReview,disabled:i.disabled,stream:i.stream,watchMode:i.watchMode,disableLowerCase:i.disableLowerCase,diffCompression:i.diffCompression,maxHunkLines:i.maxHunkLines,maxDiffLines:i.maxDiffLines,diffContext:i.diffContext},GROQ:{key:e=>e||"",envKey:e=>e||"",model:e=>e?(typeof e=="string"?e?.split(","):e).map(n=>n.trim()).filter(n=>!!n&&n.length>0):["llama-3.3-70b-versatile"],systemPrompt:i.systemPrompt,systemPromptPath:i.systemPromptPath,codeReviewPromptPath:i.codeReviewPromptPath,timeout:i.timeout,temperature:i.temperature,maxTokens:i.maxTokens,logging:i.logging,locale:i.locale,generate:i.generate,type:i.type,maxLength:i.maxLength,includeBody:i.includeBody,topP:i.topP,codeReview:i.codeReview,disabled:i.disabled,stream:i.stream,watchMode:i.watchMode,disableLowerCase:i.disableLowerCase,diffCompression:i.diffCompression,maxHunkLines:i.maxHunkLines,maxDiffLines:i.maxDiffLines,diffContext:i.diffContext},PERPLEXITY:{key:e=>e||"",envKey:e=>e||"",model:e=>e?(typeof e=="string"?e?.split(","):e).map(n=>n.trim()).filter(n=>!!n&&n.length>0):["sonar"],topP:i.topP,systemPrompt:i.systemPrompt,systemPromptPath:i.systemPromptPath,codeReviewPromptPath:i.codeReviewPromptPath,timeout:i.timeout,temperature:i.temperature,maxTokens:i.maxTokens,logging:i.logging,locale:i.locale,generate:i.generate,type:i.type,maxLength:i.maxLength,includeBody:i.includeBody,codeReview:i.codeReview,disabled:i.disabled,stream:i.stream,watchMode:i.watchMode,disableLowerCase:i.disableLowerCase,diffCompression:i.diffCompression,maxHunkLines:i.maxHunkLines,maxDiffLines:i.maxDiffLines,diffContext:i.diffContext},DEEPSEEK:{key:e=>e||"",envKey:e=>e||"",model:e=>e?(typeof e=="string"?e?.split(","):e).map(n=>n.trim()).filter(n=>!!n&&n.length>0):["deepseek-chat"],topP:i.topP,systemPrompt:i.systemPrompt,systemPromptPath:i.systemPromptPath,codeReviewPromptPath:i.codeReviewPromptPath,timeout:i.timeout,temperature:i.temperature,maxTokens:i.maxTokens,logging:i.logging,locale:i.locale,generate:i.generate,type:i.type,maxLength:i.maxLength,includeBody:i.includeBody,codeReview:i.codeReview,disabled:i.disabled,stream:i.stream,watchMode:i.watchMode,disableLowerCase:i.disableLowerCase,diffCompression:i.diffCompression,maxHunkLines:i.maxHunkLines,maxDiffLines:i.maxDiffLines,diffContext:i.diffContext},GITHUB_MODELS:{key:e=>e||"",envKey:e=>e||"",model:e=>e?(typeof e=="string"?e?.split(","):e).map(n=>n.trim()).filter(n=>!!n&&n.length>0):["openai/gpt-4o-mini"],systemPrompt:i.systemPrompt,systemPromptPath:i.systemPromptPath,codeReviewPromptPath:i.codeReviewPromptPath,timeout:i.timeout,temperature:i.temperature,maxTokens:i.maxTokens,logging:i.logging,locale:i.locale,generate:i.generate,type:i.type,maxLength:i.maxLength,includeBody:i.includeBody,topP:i.topP,codeReview:i.codeReview,disabled:i.disabled,stream:i.stream,watchMode:i.watchMode,disableLowerCase:i.disableLowerCase,diffCompression:i.diffCompression,maxHunkLines:i.maxHunkLines,maxDiffLines:i.maxDiffLines,diffContext:i.diffContext},COPILOT_SDK:{key:e=>e||"",envKey:e=>e||"",model:e=>e?(typeof e=="string"?e?.split(","):e).map(n=>n.trim()).filter(n=>!!n&&n.length>0):["gpt-4.1"],systemPrompt:i.systemPrompt,systemPromptPath:i.systemPromptPath,codeReviewPromptPath:i.codeReviewPromptPath,timeout:i.timeout,temperature:i.temperature,maxTokens:i.maxTokens,logging:i.logging,locale:i.locale,generate:i.generate,type:i.type,maxLength:i.maxLength,includeBody:i.includeBody,topP:i.topP,codeReview:i.codeReview,disabled:i.disabled,stream:i.stream,watchMode:i.watchMode,disableLowerCase:i.disableLowerCase,diffCompression:i.diffCompression,maxHunkLines:i.maxHunkLines,maxDiffLines:i.maxDiffLines,diffContext:i.diffContext},BEDROCK:{key:e=>e||"",envKey:e=>e&&e.length>0?e:"BEDROCK_API_KEY",model:e=>e?(typeof e=="string"?e?.split(","):e).map(n=>{const o=n.trim();return o&&!o.includes(".")&&!o.includes(":")&&console.warn(`[Bedrock] Model ID "${o}" may be invalid.
|
|
16
|
+
${ve}Please open a Bug report with the information above:`),console.error(`${ve}https://github.com/tak-bro/aicommit2/issues/new/choose`)}},He=e=>I.lstat(e).then(()=>!0,()=>!1),go=async e=>{try{await I.mkdir(e,{recursive:!0})}catch(t){if(t.code!=="EEXIST")throw t}},ya=e=>e&&`${e[0].toUpperCase()}${e.slice(1)}`,wa=(e,t)=>{const n=Math.ceil(e),o=Math.floor(t);return Math.floor(Math.random()*(o-n+1))+n},yo=(e,t)=>e.disabled&&!t.disabled?1:!e.disabled&&t.disabled?-1:0,Ft=e=>e.reduce((t,n)=>Array.isArray(n)?t.concat(Ft(n)):t.concat(n),[]),Ca=(e,t=5)=>e.replace(/[\n\r]/g,"").split(" ").slice(0,t).join(" "),ba=e=>{let t=0;for(let n=0;n<e.length;n++){const o=e.charCodeAt(n);t=(t<<5)-t+o,t=t&t}return Math.abs(t)},Ea=e=>{const t=e%360,n=65+e%15,o=45+e%10;return`hsl(${t}, ${n}%, ${o}%)`},va=e=>{const[t,n,o]=e.match(/\d+/g).map((f,g)=>g===0?Number(f):Number(f)/100),s=(1-Math.abs(2*o-1))*n,r=s*(1-Math.abs(t/60%2-1)),a=o-s/2;let c,l,u;t<60?[c,l,u]=[s,r,0]:t<120?[c,l,u]=[r,s,0]:t<180?[c,l,u]=[0,s,r]:t<240?[c,l,u]=[0,r,s]:t<300?[c,l,u]=[r,0,s]:[c,l,u]=[s,0,r];const d=f=>{const g=Math.round((f+a)*255).toString(16);return g.length===1?"0"+g:g};return`#${d(c)}${d(l)}${d(u)}`},Pa=e=>{const t=ba(e),n=Ea(t);return{primary:va(n),secondary:"#FFFFFF"}},Aa=e=>{try{return{ok:!0,data:JSON.parse(e)}}catch(t){return{ok:!1,error:t}}},Ue=e=>{if(!e||typeof e!="string")return"";if(v.isAbsolute(e))return v.resolve(e);if(xe){const t=v.dirname(xe),n=v.join(t,e);return v.resolve(n)}else return""},xa=["","conventional","gitmoji"],Pe="http://localhost:11434",{hasOwnProperty:Sa}=Object.prototype,Gt=(e,t)=>Sa.call(e,t),fe=["OPENAI","COPILOT_SDK","OPENROUTER","OLLAMA","HUGGINGFACE","GEMINI","ANTHROPIC","MISTRAL","CODESTRAL","COHERE","GROQ","PERPLEXITY","DEEPSEEK","GITHUB_MODELS","BEDROCK"],wo=e=>{const t=ke.platform(),n=ke.homedir();let o,s;switch(e){case"config":o=process.env.XDG_CONFIG_HOME;break;case"data":o=process.env.XDG_DATA_HOME;break;case"cache":o=process.env.XDG_CACHE_HOME;break;case"state":o=process.env.XDG_STATE_HOME;break;default:o=void 0}if(t==="darwin")e==="cache"?s=v.join(n,"Library","Caches"):s=v.join(n,"Library","Application Support");else if(t==="win32")s=process.env.LOCALAPPDATA||n;else switch(e){case"config":s=v.join(n,".config");break;case"data":s=v.join(n,".local","share");break;case"cache":s=v.join(n,".cache");break;case"state":s=v.join(n,".local","state");break;default:s=n}return o||s},Co=v.join(wo("config"),"aicommit2"),U=v.join(wo("state"),"aicommit2","logs"),bo=v.join(Co,"config.ini"),Eo=v.join(U,"aicommit2-%DATE%.log"),vo=v.join(U,"exceptions-%DATE%.log"),$a=e=>{const t=Object.keys(e),n=new Set([...fe,...t.filter(o=>/^[A-Z][A-Z0-9_]*$/.test(o))]);return Array.from(n)},E=(e,t,n)=>{if(!t)throw new p(`Invalid config property ${e}: ${n}`)},G=(e,t=!1)=>n=>typeof n=="boolean"?n:n==null?t:(E(e,/^(?:true|false)$/.test(n),"Must be a boolean(true or false)"),n==="true"),Ke=e=>t=>{if(!t)return{};if(typeof t=="object")return E(e,!Array.isArray(t),"Must be a JSON object"),t;try{const n=JSON.parse(t);return E(e,typeof n=="object"&&n!==null&&!Array.isArray(n),"Must be a valid JSON object"),n}catch(n){throw new p(`Invalid ${e}: Must be valid JSON. Error: ${n.message}`)}},i={systemPrompt(e){return e||""},systemPromptPath(e){return e||""},codeReviewPromptPath(e){return e||""},timeout(e){if(!e)return 6e4;E("timeout",/^\d+$/.test(e),"Must be an integer");const t=Number(e);return E("timeout",t>=500,"Must be greater than 500ms"),t},temperature(e){if(!e)return .7;E("temperature",/^(2|\d)(\.\d{1,2})?$/.test(e),"Must be decimal between 0 and 2");const t=Number(e);return E("temperature",t>0,"Must be greater than 0"),E("temperature",t<=2,"Must be less than or equal to 2"),t},maxTokens(e){return e?(E("maxTokens",/^\d+$/.test(e),"Must be an integer"),Number(e)):8192},logLevel(e){return e?(E("logLevel",/^(?:error|warn|info|http|verbose|debug|silly)$/.test(e),"Must be a valid log level (error, warn, info, http, verbose, debug, silly)"),e):"info"},logFilePath(e){return e||Eo},exceptionLogFilePath(e){return e||vo},locale(e){return e?(E("locale",e,"Cannot be empty"),E("locale",/^[a-z-]+$/i.test(e),"Must be a valid locale (letters and dashes/underscores). You can consult the list of codes in: https://wikipedia.org/wiki/List_of_ISO_639-1_codes"),e):"en"},generate(e){if(!e)return 1;E("generate",/^\d+$/.test(e),"Must be an integer");const t=Number(e);return E("generate",t>0,"Must be greater than 0"),E("generate",t<=5,"Must be less or equal to 5"),t},type(e){return e?(E("type",xa.includes(e),"Invalid commit type"),e):"conventional"},maxLength(e){if(!e)return 50;E("maxLength",/^\d+$/.test(e),"Must be an integer");const t=Number(e);return E("maxLength",t>=20,"Must be greater than 20 characters"),t},exclude:e=>e?(typeof e=="string"?e?.split(","):e).map(n=>n.trim()).filter(n=>!!n&&n.length>0):[],topP:e=>{if(!e)return .9;E("topP",/^(1|\d)(\.\d{1,2})?$/.test(e),"Must be decimal between 0 and 1");const t=Number(e);return E("topP",t>0,"Must be greater than 0"),E("topP",t<=1,"Must be less than or equal to 1"),t},logging:G("logging",!0),includeBody:G("includeBody"),codeReview:G("codeReview"),disabled:G("disabled"),watchMode:G("watchMode"),forceGit:G("forceGit"),stream:G("stream"),disableLowerCase:G("disableLowerCase"),jjAutoNew:G("jjAutoNew"),autoCopy:G("autoCopy"),modelNameDisplay:e=>e?(E("modelNameDisplay",/^(?:none|short|full)$/.test(e),"Must be none, short, or full"),e):"short",diffCompression:e=>e?(E("diffCompression",/^(?:none|compact)$/.test(e),"Must be none or compact"),e):ho.mode,maxHunkLines:e=>e?(E("maxHunkLines",/^\d+$/.test(e),"Must be an integer"),Number(e)):0,maxDiffLines:e=>e?(E("maxDiffLines",/^\d+$/.test(e),"Must be an integer"),Number(e)):0,diffContext:e=>{if(!e)return me;E("diffContext",/^\d+$/.test(e),"Must be an integer");const t=Number(e);return E("diffContext",t>=0&&t<=10,"Must be between 0 and 10"),t},useStats:G("useStats",!0),statsDays:e=>{if(!e)return 30;E("statsDays",/^\d+$/.test(e),"Must be an integer");const t=Number(e);return E("statsDays",t>0,"Must be greater than 0"),t}},Ae={OPENAI:{key:e=>e||"",envKey:e=>e||"",model:e=>e?(typeof e=="string"?e?.split(","):e).map(n=>n.trim()).filter(n=>!!n&&n.length>0):["gpt-4o-mini"],url:e=>e?(E("OPENAI.url",/^https?:\/\//.test(e),"Must be a valid URL"),e):"https://api.openai.com",path:e=>e||"/v1/chat/completions",proxy:e=>e||"",topP:i.topP,systemPrompt:i.systemPrompt,systemPromptPath:i.systemPromptPath,codeReviewPromptPath:i.codeReviewPromptPath,timeout:i.timeout,temperature:i.temperature,maxTokens:i.maxTokens,logging:i.logging,locale:i.locale,generate:i.generate,type:i.type,maxLength:i.maxLength,includeBody:i.includeBody,codeReview:i.codeReview,disabled:i.disabled,stream:i.stream,watchMode:i.watchMode,disableLowerCase:i.disableLowerCase,diffCompression:i.diffCompression,maxHunkLines:i.maxHunkLines,maxDiffLines:i.maxDiffLines,diffContext:i.diffContext},OPENROUTER:{key:e=>e||"",envKey:e=>e||"",model:e=>e?(typeof e=="string"?e?.split(","):e).map(n=>n.trim()).filter(n=>!!n&&n.length>0):["openrouter/auto"],url:e=>e?(E("OPENROUTER.url",/^https?:\/\//.test(e),"Must be a valid URL"),e):"https://openrouter.ai",path:e=>e||"/api/v1/chat/completions",responseFormat:Ke("OPENROUTER.responseFormat"),provider:Ke("OPENROUTER.provider"),reasoning:Ke("OPENROUTER.reasoning"),topP:i.topP,systemPrompt:i.systemPrompt,systemPromptPath:i.systemPromptPath,codeReviewPromptPath:i.codeReviewPromptPath,timeout:i.timeout,temperature:i.temperature,maxTokens:i.maxTokens,logging:i.logging,locale:i.locale,generate:i.generate,type:i.type,maxLength:i.maxLength,includeBody:i.includeBody,codeReview:i.codeReview,disabled:i.disabled,stream:i.stream,watchMode:i.watchMode,disableLowerCase:i.disableLowerCase,diffCompression:i.diffCompression,maxHunkLines:i.maxHunkLines,maxDiffLines:i.maxDiffLines,diffContext:i.diffContext},HUGGINGFACE:{cookie:e=>e||"",model:e=>e?(typeof e=="string"?e?.split(","):e).map(n=>n.trim()).filter(n=>!!n&&n.length>0):["CohereForAI/c4ai-command-r-plus"],systemPrompt:i.systemPrompt,systemPromptPath:i.systemPromptPath,codeReviewPromptPath:i.codeReviewPromptPath,timeout:i.timeout,temperature:i.temperature,maxTokens:i.maxTokens,topP:i.topP,logging:i.logging,locale:i.locale,generate:i.generate,type:i.type,maxLength:i.maxLength,includeBody:i.includeBody,codeReview:i.codeReview,disabled:i.disabled,stream:i.stream,watchMode:i.watchMode,disableLowerCase:i.disableLowerCase,diffCompression:i.diffCompression,maxHunkLines:i.maxHunkLines,maxDiffLines:i.maxDiffLines,diffContext:i.diffContext},GEMINI:{key:e=>e||"",envKey:e=>e||"",model:e=>e?(typeof e=="string"?e?.split(","):e).map(n=>n.trim()).filter(n=>!!n&&n.length>0):["gemini-3-flash-preview"],systemPrompt:i.systemPrompt,systemPromptPath:i.systemPromptPath,codeReviewPromptPath:i.codeReviewPromptPath,timeout:i.timeout,temperature:i.temperature,maxTokens:i.maxTokens,logging:i.logging,locale:i.locale,generate:i.generate,type:i.type,maxLength:i.maxLength,includeBody:i.includeBody,topP:i.topP,codeReview:i.codeReview,disabled:i.disabled,stream:i.stream,watchMode:i.watchMode,disableLowerCase:i.disableLowerCase,diffCompression:i.diffCompression,maxHunkLines:i.maxHunkLines,maxDiffLines:i.maxDiffLines,diffContext:i.diffContext},ANTHROPIC:{key:e=>e||"",envKey:e=>e||"",model:e=>e?(typeof e=="string"?e?.split(","):e).map(n=>n.trim()).filter(n=>!!n&&n.length>0):["claude-sonnet-4-20250514"],systemPrompt:i.systemPrompt,systemPromptPath:i.systemPromptPath,codeReviewPromptPath:i.codeReviewPromptPath,timeout:i.timeout,temperature:i.temperature,maxTokens:i.maxTokens,logging:i.logging,locale:i.locale,generate:i.generate,type:i.type,maxLength:i.maxLength,includeBody:i.includeBody,topP:i.topP,codeReview:i.codeReview,disabled:i.disabled,stream:i.stream,watchMode:i.watchMode,disableLowerCase:i.disableLowerCase,diffCompression:i.diffCompression,maxHunkLines:i.maxHunkLines,maxDiffLines:i.maxDiffLines,diffContext:i.diffContext},MISTRAL:{key:e=>e||"",envKey:e=>e||"",model:e=>e?(typeof e=="string"?e?.split(","):e).map(n=>n.trim()).filter(n=>!!n&&n.length>0):["mistral-small-latest"],systemPrompt:i.systemPrompt,systemPromptPath:i.systemPromptPath,codeReviewPromptPath:i.codeReviewPromptPath,timeout:i.timeout,temperature:i.temperature,maxTokens:i.maxTokens,logging:i.logging,locale:i.locale,generate:i.generate,type:i.type,maxLength:i.maxLength,includeBody:i.includeBody,topP:i.topP,codeReview:i.codeReview,disabled:i.disabled,stream:i.stream,watchMode:i.watchMode,disableLowerCase:i.disableLowerCase,diffCompression:i.diffCompression,maxHunkLines:i.maxHunkLines,maxDiffLines:i.maxDiffLines,diffContext:i.diffContext},CODESTRAL:{key:e=>e||"",envKey:e=>e||"",model:e=>e?(typeof e=="string"?e?.split(","):e).map(n=>n.trim()).filter(n=>!!n&&n.length>0):["codestral-latest"],topP:i.topP,systemPrompt:i.systemPrompt,systemPromptPath:i.systemPromptPath,codeReviewPromptPath:i.codeReviewPromptPath,timeout:i.timeout,temperature:i.temperature,maxTokens:i.maxTokens,logging:i.logging,locale:i.locale,generate:i.generate,type:i.type,maxLength:i.maxLength,includeBody:i.includeBody,codeReview:i.codeReview,disabled:i.disabled,stream:i.stream,watchMode:i.watchMode,disableLowerCase:i.disableLowerCase,diffCompression:i.diffCompression,maxHunkLines:i.maxHunkLines,maxDiffLines:i.maxDiffLines,diffContext:i.diffContext},OLLAMA:{model:e=>e?(typeof e=="string"?e?.split(","):e).map(n=>n.trim()).filter(n=>!!n&&n.length>0):[],host:e=>e?(E("OLLAMA.host",/^https?:\/\//.test(e),"Must be a valid URL"),e):Pe,timeout:e=>{if(!e)return 1e5;E("OLLAMA.timeout",/^\d+$/.test(e),"Must be an integer");const t=Number(e);return E("OLLAMA.timeout",t>=500,"Must be greater than 500ms"),t},auth:e=>e||"",key:e=>e||"",envKey:e=>e||"",numCtx:e=>{if(!e)return 2048;E("OLLAMA.numCtx",/^\d+$/.test(e),"Must be an integer");const t=Number(e);return E("OLLAMA.numCtx",t>=2048,"Must be greater than 2048"),t},systemPrompt:i.systemPrompt,systemPromptPath:i.systemPromptPath,codeReviewPromptPath:i.codeReviewPromptPath,temperature:i.temperature,maxTokens:i.maxTokens,logging:i.logging,locale:i.locale,generate:i.generate,type:i.type,maxLength:i.maxLength,includeBody:i.includeBody,topP:i.topP,codeReview:i.codeReview,disabled:i.disabled,stream:i.stream,watchMode:i.watchMode,disableLowerCase:i.disableLowerCase,diffCompression:i.diffCompression,maxHunkLines:i.maxHunkLines,maxDiffLines:i.maxDiffLines,diffContext:i.diffContext},COHERE:{key:e=>e||"",envKey:e=>e||"",url:e=>e?(E("COHERE.url",/^https?:\/\//.test(e),"Must be a valid URL"),e):"https://api.cohere.ai",model:e=>e?(typeof e=="string"?e?.split(","):e).map(n=>n.trim()).filter(n=>!!n&&n.length>0):["command-a-03-2025"],systemPrompt:i.systemPrompt,systemPromptPath:i.systemPromptPath,codeReviewPromptPath:i.codeReviewPromptPath,temperature:i.temperature,maxTokens:i.maxTokens,logging:i.logging,locale:i.locale,timeout:i.timeout,generate:i.generate,type:i.type,maxLength:i.maxLength,includeBody:i.includeBody,topP:i.topP,codeReview:i.codeReview,disabled:i.disabled,stream:i.stream,watchMode:i.watchMode,disableLowerCase:i.disableLowerCase,diffCompression:i.diffCompression,maxHunkLines:i.maxHunkLines,maxDiffLines:i.maxDiffLines,diffContext:i.diffContext},GROQ:{key:e=>e||"",envKey:e=>e||"",model:e=>e?(typeof e=="string"?e?.split(","):e).map(n=>n.trim()).filter(n=>!!n&&n.length>0):["llama-3.3-70b-versatile"],systemPrompt:i.systemPrompt,systemPromptPath:i.systemPromptPath,codeReviewPromptPath:i.codeReviewPromptPath,timeout:i.timeout,temperature:i.temperature,maxTokens:i.maxTokens,logging:i.logging,locale:i.locale,generate:i.generate,type:i.type,maxLength:i.maxLength,includeBody:i.includeBody,topP:i.topP,codeReview:i.codeReview,disabled:i.disabled,stream:i.stream,watchMode:i.watchMode,disableLowerCase:i.disableLowerCase,diffCompression:i.diffCompression,maxHunkLines:i.maxHunkLines,maxDiffLines:i.maxDiffLines,diffContext:i.diffContext},PERPLEXITY:{key:e=>e||"",envKey:e=>e||"",model:e=>e?(typeof e=="string"?e?.split(","):e).map(n=>n.trim()).filter(n=>!!n&&n.length>0):["sonar"],topP:i.topP,systemPrompt:i.systemPrompt,systemPromptPath:i.systemPromptPath,codeReviewPromptPath:i.codeReviewPromptPath,timeout:i.timeout,temperature:i.temperature,maxTokens:i.maxTokens,logging:i.logging,locale:i.locale,generate:i.generate,type:i.type,maxLength:i.maxLength,includeBody:i.includeBody,codeReview:i.codeReview,disabled:i.disabled,stream:i.stream,watchMode:i.watchMode,disableLowerCase:i.disableLowerCase,diffCompression:i.diffCompression,maxHunkLines:i.maxHunkLines,maxDiffLines:i.maxDiffLines,diffContext:i.diffContext},DEEPSEEK:{key:e=>e||"",envKey:e=>e||"",model:e=>e?(typeof e=="string"?e?.split(","):e).map(n=>n.trim()).filter(n=>!!n&&n.length>0):["deepseek-v4-flash"],thinking:e=>{if(!(e==null||e===""))return typeof e=="boolean"?e:(E("DEEPSEEK.thinking",/^(?:true|false)$/.test(e),"Must be a boolean(true or false)"),e==="true")},reasoningEffort:e=>{if(!e||e.trim()==="")return;const t=e.trim().toLowerCase();return E("DEEPSEEK.reasoningEffort",t==="high"||t==="max","Must be high or max"),t},topP:i.topP,systemPrompt:i.systemPrompt,systemPromptPath:i.systemPromptPath,codeReviewPromptPath:i.codeReviewPromptPath,timeout:i.timeout,temperature:i.temperature,maxTokens:i.maxTokens,logging:i.logging,locale:i.locale,generate:i.generate,type:i.type,maxLength:i.maxLength,includeBody:i.includeBody,codeReview:i.codeReview,disabled:i.disabled,stream:i.stream,watchMode:i.watchMode,disableLowerCase:i.disableLowerCase,diffCompression:i.diffCompression,maxHunkLines:i.maxHunkLines,maxDiffLines:i.maxDiffLines,diffContext:i.diffContext},GITHUB_MODELS:{key:e=>e||"",envKey:e=>e||"",model:e=>e?(typeof e=="string"?e?.split(","):e).map(n=>n.trim()).filter(n=>!!n&&n.length>0):["openai/gpt-4o-mini"],systemPrompt:i.systemPrompt,systemPromptPath:i.systemPromptPath,codeReviewPromptPath:i.codeReviewPromptPath,timeout:i.timeout,temperature:i.temperature,maxTokens:i.maxTokens,logging:i.logging,locale:i.locale,generate:i.generate,type:i.type,maxLength:i.maxLength,includeBody:i.includeBody,topP:i.topP,codeReview:i.codeReview,disabled:i.disabled,stream:i.stream,watchMode:i.watchMode,disableLowerCase:i.disableLowerCase,diffCompression:i.diffCompression,maxHunkLines:i.maxHunkLines,maxDiffLines:i.maxDiffLines,diffContext:i.diffContext},COPILOT_SDK:{key:e=>e||"",envKey:e=>e||"",model:e=>e?(typeof e=="string"?e?.split(","):e).map(n=>n.trim()).filter(n=>!!n&&n.length>0):["gpt-4.1"],systemPrompt:i.systemPrompt,systemPromptPath:i.systemPromptPath,codeReviewPromptPath:i.codeReviewPromptPath,timeout:i.timeout,temperature:i.temperature,maxTokens:i.maxTokens,logging:i.logging,locale:i.locale,generate:i.generate,type:i.type,maxLength:i.maxLength,includeBody:i.includeBody,topP:i.topP,codeReview:i.codeReview,disabled:i.disabled,stream:i.stream,watchMode:i.watchMode,disableLowerCase:i.disableLowerCase,diffCompression:i.diffCompression,maxHunkLines:i.maxHunkLines,maxDiffLines:i.maxDiffLines,diffContext:i.diffContext},BEDROCK:{key:e=>e||"",envKey:e=>e&&e.length>0?e:"BEDROCK_API_KEY",model:e=>e?(typeof e=="string"?e?.split(","):e).map(n=>{const o=n.trim();return o&&!o.includes(".")&&!o.includes(":")&&console.warn(`[Bedrock] Model ID "${o}" may be invalid.
|
|
17
17
|
Expected formats:
|
|
18
18
|
- Foundation model: "provider.model-name-version" (e.g., "anthropic.claude-haiku-4-5-20251001-v1:0")
|
|
19
19
|
- Inference profile: "prefix.provider.model-name-version" (e.g., "us.anthropic.claude-haiku-4-5-20251001-v1:0")
|
|
20
20
|
- ARN: Full Amazon Resource Name
|
|
21
|
-
See https://docs.aws.amazon.com/bedrock/latest/userguide/inference-profiles.html`),o}).filter(n=>!!n&&n.length>0):["anthropic.claude-haiku-4-5-20251001-v1:0"],runtimeMode:e=>{e&&console.warn("[Bedrock] DEPRECATION: runtimeMode is no longer used. Authentication method is now auto-detected from configured credentials.")},region:e=>e||process.env.AWS_REGION||process.env.AWS_DEFAULT_REGION||"",profile:e=>e||process.env.AWS_PROFILE||"",accessKeyId:e=>e||process.env.AWS_ACCESS_KEY_ID||"",secretAccessKey:e=>e||process.env.AWS_SECRET_ACCESS_KEY||"",sessionToken:e=>e||process.env.AWS_SESSION_TOKEN||"",applicationEndpointId:e=>e||process.env.BEDROCK_APPLICATION_ENDPOINT_ID||"",applicationInferenceProfileArn:e=>e||process.env.BEDROCK_APPLICATION_INFERENCE_PROFILE_ARN||process.env.BEDROCK_INFERENCE_PROFILE_ARN||"",applicationBaseUrl:e=>e||process.env.BEDROCK_APPLICATION_BASE_URL||"",systemPrompt:i.systemPrompt,systemPromptPath:i.systemPromptPath,codeReviewPromptPath:i.codeReviewPromptPath,timeout:i.timeout,temperature:e=>{if(!e)return;E("temperature",/^(2|\d)(\.\d{1,2})?$/.test(e),"Must be decimal between 0 and 2");const t=Number(e);return E("temperature",t>0,"Must be greater than 0"),E("temperature",t<=2,"Must be less than or equal to 2"),t},maxTokens:e=>{if(e)return E("maxTokens",/^\d+$/.test(e),"Must be an integer"),Number(e)},logging:i.logging,locale:i.locale,generate:i.generate,type:i.type,maxLength:i.maxLength,includeBody:i.includeBody,topP:e=>{if(!e)return;E("topP",/^(1|\d)(\.\d{1,2})?$/.test(e),"Must be decimal between 0 and 1");const t=Number(e);return E("topP",t>0,"Must be greater than 0"),E("topP",t<=1,"Must be less than or equal to 1"),t},codeReview:i.codeReview,disabled:i.disabled,stream:i.stream,watchMode:i.watchMode,disableLowerCase:i.disableLowerCase,inferenceParameters:Ke("BEDROCK.inferenceParameters"),diffCompression:i.diffCompression,maxHunkLines:i.maxHunkLines,maxDiffLines:i.maxDiffLines,diffContext:i.diffContext}},Ra=e=>typeof e=="object"&&e!==null,Po=(e,t)=>{Object.keys(e).forEach(n=>{const o=e[n];Ra(o)&&t in o&&(o[t]=!0)})},Ia=e=>{Po(e,"includeBody")},ka=e=>{Po(e,"disableLowerCase")};let xe,Se=null,Bt=null;const La=(e=[])=>{const t={};for(const n of e)if(n.startsWith("--")){const[o,s]=n.slice(2).split("="),[r,a]=o.split(".");r&&a&&r in Ae?(t[r]||(t[r]={}),t[r][a]=s):t[o]=s}return t},Oa=()=>{const e=ke.homedir(),t=process.env.AICOMMIT_CONFIG_PATH,n=bo,o=v.join(e,".aicommit2");return[t,n,o].filter(s=>!!s)},pe=async()=>{const e=Oa();for(const t of e)if(await He(t))return t;return bo},Ma=e=>e.replace(/\$\{([a-zA-Z_][a-zA-Z0-9_]*)\}|\$([a-zA-Z_][a-zA-Z0-9_]*)/g,(t,n,o)=>{const s=n||o;return process.env[s]??""}),Ao=e=>{if(Array.isArray(e)||e===null||typeof e!="object")return e;const t={};for(const[n,o]of Object.entries(e)){const s=Ao(o);if(!n.includes(".")){t[n]=s;continue}const r=n.split(".");let a=t;for(const c of r.slice(0,-1)){const l=a[c];(!l||typeof l!="object"||Array.isArray(l))&&(a[c]={}),a=a[c]}a[r[r.length-1]]=s}return t},$e=async()=>{const e=await pe();if(Se&&Bt===e)return Se;xe=e;try{const t=await I.readFile(e,"utf8"),n=Ma(t);return Se=Ao(de.parse(n)),Bt=e,Se}catch(t){return t.code==="ENOENT"?(xe=void 0,{}):(console.error(`Error reading config file ${e}:`,t),xe=void 0,{})}},xo=()=>{Se=null,Bt=null},J=async(e,t=[])=>{const n=await $e(),o=La(t),s={...e,...o},r={},a=$a(n),c={};for(const u of a){const d=n[u]?.envKey;let f;d?(f=[d],u==="BEDROCK"&&d!=="BEDROCK_APPLICATION_API_KEY"&&f.push("BEDROCK_APPLICATION_API_KEY")):u==="BEDROCK"?f=["BEDROCK_API_KEY","BEDROCK_APPLICATION_API_KEY"]:f=[`${u}_API_KEY`];const g=f.map(y=>y?process.env[y]:void 0).find(y=>typeof y=="string"&&y.length>0);g&&(c[u]={key:g})}const l=(u,d)=>{const f=s[`${u}.${d}`]??s[u]?.[d],g=c[u]?.[d],y=n[u]?.[d],m=s[d]??n[d];return f!==void 0?f:g!==void 0?g:y!==void 0?y:m};for(const[u,d]of Object.entries(i)){const f=s[u]??n[u];r[u]=d(f)}for(const u of a){r[u]={};const d=Ae[u]||qe(u);for(const[f,g]of Object.entries(d)){const y=l(u,f);r[u][f]=g(y)}}return r},We=async e=>{const t=await $e();for(const[s,r]of e){const[a,c]=s.split(".");if(!c){const d=i[s];if(!d)throw new p(`Invalid config property: ${s}`);t[s]=d(r);continue}if(t[a]||(t[a]={}),fe.includes(a)){const d=Ae[a][c];if(!d)throw new p(`Invalid config property: ${s}`);t[a][c]=d(r);continue}if(!/^[A-Z][A-Z0-9_]*$/.test(a))throw new p(`Invalid service name: ${a}. Service names must be uppercase letters, numbers, and underscores.`);const u=qe(a);if(!u[c])throw new p(`Invalid config property for custom service: ${s}`);try{t[a][c]=u[c](r)}catch(d){throw d instanceof p?d:new p(`Invalid value for ${s}: ${d.message}`)}}const n=await pe(),o=v.dirname(n);await I.mkdir(o,{recursive:!0}),await I.writeFile(n,de.stringify(t),"utf8"),xo()},Ta=async e=>{const t=await $e();for(const[s,r]of e){const[a,c]=s.split("."),l=t[a];if(c==="model"){l||(t[a]={});const d=t[a][c]||[],f=typeof r=="string"?r.split(",").map(g=>g.trim()).filter(g=>!!g):r;t[a][c]=Ft([...d,...f]);continue}if(l&&l.compatible===!0){l||(t[a]={});const d=qe(a);if(!d[c])throw new p(`Invalid config property: ${s}`);try{t[a][c]=d[c](r)}catch(f){throw f instanceof p?f:new p(`Invalid value for ${s}: ${f.message}`)}continue}if(a in Ae){l||(t[a]={});const d=Ae[a][c];if(!d)throw new p(`Invalid config property: ${s}`);t[a][c]=d(r)}else{const d=qe(a);if(!d[c])throw new p(`Invalid config property: ${s}`);t[a]||(t[a]={}),t[a][c]=d[c](r)}}const n=await pe(),o=v.dirname(n);await I.mkdir(o,{recursive:!0}),await I.writeFile(n,de.stringify(t),"utf8"),xo()},Da=async()=>{const e=await $e();console.log(de.stringify(e))},Na=async()=>{console.log(await pe())},qe=e=>({compatible:G("compatible"),stream:G("stream"),url:t=>t?(E(`${e}.url`,/^https?:\/\//.test(t),"Must be a valid URL"),t):"",path:t=>t||"",key:t=>t||"",envKey:t=>t||"",model:t=>t?(typeof t=="string"?t?.split(","):t).map(o=>o.trim()).filter(o=>!!o&&o.length>0):[],systemPrompt:i.systemPrompt,systemPromptPath:i.systemPromptPath,codeReviewPromptPath:i.codeReviewPromptPath,timeout:i.timeout,temperature:i.temperature,maxTokens:i.maxTokens,logging:i.logging,locale:i.locale,generate:i.generate,type:i.type,maxLength:i.maxLength,includeBody:i.includeBody,topP:i.topP,codeReview:i.codeReview,disabled:i.disabled,watchMode:i.watchMode,disableLowerCase:i.disableLowerCase,autoCopy:i.autoCopy,diffCompression:i.diffCompression,maxHunkLines:i.maxHunkLines,maxDiffLines:i.maxDiffLines,diffContext:i.diffContext}),N=e=>typeof e=="string"&&e.trim().length>0,_a=()=>{try{const e=typeof gt<"u"?gt.resolve:void 0;return e?(e("@github/copilot-sdk"),!0):typeof import.meta.resolve=="function"?(import.meta.resolve("@github/copilot-sdk"),!0):!1}catch{return!1}};let Ht;const ja=e=>Y(e)?(Ht===void 0&&(Ht=_a()),Ht):!1,Y=e=>(Array.isArray(e.model)?e.model:N(e.model)?[e.model.trim()]:[]).length>0,ze=e=>{const t=N(e.key),n=N(e.region)||N(process.env.AWS_REGION)||N(process.env.AWS_DEFAULT_REGION),o=N(e.profile)||N(process.env.AWS_PROFILE),s=N(e.accessKeyId)&&N(e.secretAccessKey)||N(process.env.AWS_ACCESS_KEY_ID)&&N(process.env.AWS_SECRET_ACCESS_KEY),r=N(e.applicationBaseUrl)||N(process.env.BEDROCK_APPLICATION_BASE_URL),a=N(e.applicationEndpointId)||N(process.env.BEDROCK_APPLICATION_ENDPOINT_ID),c=N(process.env.BEDROCK_APPLICATION_API_KEY);return n&&(t||o||s)||(r&&t||a&&c)},he=(e,t)=>Object.entries(e).map(([n,o])=>[n,o]).filter(([n,o])=>!o.disabled).filter(([n,o])=>fe.includes(n)||o.compatible===!0).filter(([n,o])=>{switch(t){case"commit":return n==="OLLAMA"?!!o&&Y(o):n==="COPILOT_SDK"?!!o&&ja(o):n==="HUGGINGFACE"?!!o&&!!o.cookie:n==="BEDROCK"?Y(o)&&ze(o):!!o.key&&o.key.length>0;case"review":const s=e.codeReview||o.codeReview;return n==="OLLAMA"||n==="COPILOT_SDK"?!!o&&Y(o)&&s:n==="HUGGINGFACE"?!!o&&!!o.cookie&&s:n==="BEDROCK"?Y(o)&&ze(o)&&s:!!o.key&&o.key.length>0&&s;case"watch":const r=e.watchMode||o.watchMode;return n==="OLLAMA"||n==="COPILOT_SDK"?!!o&&Y(o)&&r:n==="HUGGINGFACE"?!!o&&!!o.cookie&&r:n==="BEDROCK"?Y(o)&&ze(o)&&r:o.compatible?!!o.url&&!!o.key&&r:!!o.key&&o.key.length>0&&r}}).map(([n])=>n);class Fa{static create(t,n){return new t(n)}}const Ga="stats.json",Ye=2,Ba=30,Ut=()=>v.join(Co,Ga),Ve=async()=>{const e=Ut();if(!await He(e))return{version:Ye,metrics:[],selections:[]};try{const t=await I.readFile(e,"utf-8"),n=JSON.parse(t);return!n.version||n.version<Ye?{version:Ye,metrics:n.metrics||[],selections:n.selections||[]}:n}catch{return{version:Ye,metrics:[],selections:[]}}},Ha=(e,t)=>{const n=Date.now()-t*24*60*60*1e3;return{version:e.version,metrics:e.metrics.filter(o=>o.timestamp>=n),selections:e.selections.filter(o=>o.timestamp>=n)}},So=async(e,t)=>{const n=Ut(),o=v.dirname(n),s=t?Ha(e,t):e;await I.mkdir(o,{recursive:!0}),await I.writeFile(n,JSON.stringify(s,null,2),"utf-8")},Ua=async e=>{const t={timestamp:Date.now(),provider:e.provider,model:e.model,responseTimeMs:e.responseTimeMs,success:e.success,errorCode:e.errorCode,tokensUsed:e.tokensUsed},n=await Ve();n.metrics.push(t),await So(n,e.statsDays)},Ka=async e=>{const t={timestamp:Date.now(),provider:e.provider,model:e.model},n=await Ve();n.selections.push(t),await So(n,e.statsDays)},Wa=(e,t,n)=>{const o=t.filter(u=>u.provider===e),s=n.filter(u=>u.provider===e);if(o.length===0)return{provider:e,totalRequests:0,successCount:0,failureCount:0,selectedCount:s.length,selectionRate:0,avgResponseTimeMs:0,minResponseTimeMs:0,maxResponseTimeMs:0};const r=o.filter(u=>u.success),a=o.map(u=>u.responseTimeMs),c=s.length,l=r.length>0?Math.min(100,Math.round(c/r.length*1e3)/10):0;return{provider:e,totalRequests:o.length,successCount:r.length,failureCount:o.length-r.length,selectedCount:c,selectionRate:l,avgResponseTimeMs:Math.round(a.reduce((u,d)=>u+d,0)/a.length),minResponseTimeMs:Math.min(...a),maxResponseTimeMs:Math.max(...a)}},qa=async(e=Ba)=>{const t=await Ve(),n=Date.now()-e*24*60*60*1e3,o=t.metrics.filter(u=>u.timestamp>=n),s=t.selections.filter(u=>u.timestamp>=n);if(o.length===0)return{totalRequests:0,successRate:0,avgResponseTimeMs:0,providerStats:[],periodStart:n,periodEnd:Date.now()};const a=[...new Set(o.map(u=>u.provider))].map(u=>Wa(u,o,s)).sort((u,d)=>d.totalRequests-u.totalRequests),c=o.filter(u=>u.success).length,l=o.reduce((u,d)=>u+d.responseTimeMs,0);return{totalRequests:o.length,successRate:Math.round(c/o.length*1e3)/10,avgResponseTimeMs:Math.round(l/o.length),providerStats:a,periodStart:Math.min(...o.map(u=>u.timestamp)),periodEnd:Math.max(...o.map(u=>u.timestamp))}},za=async()=>{const e=Ut();await He(e)&&await I.unlink(e)},Ya=async()=>(await Ve()).metrics.length>0,$o=(e,t)=>{const n=h.red.bold(`[${e}]`);return Ss({name:`${n} ${t}`,value:t,isError:!0,disabled:!0})},Ro=e=>{let t=!1;return $s({next:n=>{if(Object.assign(n,{provider:e.provider,model:e.model}),e.statsEnabled===!1||t)return;t=!0;const o=n.isError===!0,s={provider:e.provider,model:e.model,responseTimeMs:Date.now()-e.startTime,success:!o,errorCode:o?"REQUEST_ERROR":void 0,statsDays:e.statsDays};Ua(s).catch(()=>{})}})};class Va{constructor(){this.loaders=new Map,this.cache=new Map,this.loadService=async t=>{const n=this.cache.get(t);if(n)return n;const o=this.loaders.get(t);if(!o)return null;const s=await o();return this.cache.set(t,s),s},this.createService=async(t,n)=>{const o=await this.loadService(t);return o?new o(n):null},this.createRequest$=(t,n,o)=>{const s=Date.now(),r=Array.isArray(n.config.model)?n.config.model[0]:n.config.model;return Le(this.createService(t,n)).pipe(fn(a=>a?(o==="commit"?a.generateCommitMessage$():a.generateCodeReview$()).pipe(Ro({provider:t,model:r||"unknown",startTime:s,statsEnabled:n.statsEnabled,statsDays:n.statsDays})):$o(t,"Invalid AI type")))},this.registerBuiltinProviders=()=>{this.loaders.set("OPENAI",()=>import("./openai.service-663ad5da.mjs").then(t=>t.OpenAIService)),this.loaders.set("COPILOT_SDK",()=>import("./copilot-sdk.service-0775d505.mjs").then(t=>t.CopilotSdkService)),this.loaders.set("OPENROUTER",()=>import("./openrouter.service-f6552be3.mjs").then(t=>t.OpenRouterService)),this.loaders.set("GEMINI",()=>import("./gemini.service-25c72218.mjs").then(t=>t.GeminiService)),this.loaders.set("ANTHROPIC",()=>import("./anthropic.service-cdd97556.mjs").then(t=>t.AnthropicService)),this.loaders.set("HUGGINGFACE",()=>import("./hugging-face.service-f7dcc31e.mjs").then(t=>t.HuggingFaceService)),this.loaders.set("MISTRAL",()=>import("./mistral.service-7a073354.mjs").then(t=>t.MistralService)),this.loaders.set("CODESTRAL",()=>import("./codestral.service-cf085c39.mjs").then(t=>t.CodestralService)),this.loaders.set("OLLAMA",()=>import("./ollama.service-aa773594.mjs").then(t=>t.OllamaService)),this.loaders.set("COHERE",()=>import("./cohere.service-2b555628.mjs").then(t=>t.CohereService)),this.loaders.set("GROQ",()=>import("./groq.service-f7770363.mjs").then(t=>t.GroqService)),this.loaders.set("PERPLEXITY",()=>import("./perplexity.service-f582f58e.mjs").then(t=>t.PerplexityService)),this.loaders.set("BEDROCK",()=>import("./bedrock.service-3487fda6.mjs").then(t=>t.BedrockService)),this.loaders.set("GITHUB_MODELS",()=>import("./github-models.service-5d43907f.mjs").then(t=>t.GitHubModelsService)),this.loaders.set("DEEPSEEK",()=>import("./deep-seek.service-f7f29cf5.mjs").then(t=>t.DeepSeekService))},this.registerBuiltinProviders()}}const Ja=new Va;class Kt{getDetectedMessage(t){return`Detected ${t.files.length.toLocaleString()} changed file${t.files.length>1?"s":""} (${t.diff.length.toLocaleString()} characters)`}getDetectedFiles(t){return`Detected ${t.length.toLocaleString()} changed file${t.length>1?"s":""}`}}class Je extends Kt{constructor(){super(...arguments),this.name="git",this.excludeFromDiff=t=>`:(exclude)${t}`,this.filesToExclude=["package-lock.json","pnpm-lock.yaml","*.lock","*.lockb"].map(this.excludeFromDiff)}async assertRepo(){try{const{stdout:t}=await b("git",["rev-parse","--show-toplevel"],{reject:!0});return t.trim()}catch(t){const n=t;if(n.code==="ENOENT")throw new p(`Git command not found!
|
|
21
|
+
See https://docs.aws.amazon.com/bedrock/latest/userguide/inference-profiles.html`),o}).filter(n=>!!n&&n.length>0):["anthropic.claude-haiku-4-5-20251001-v1:0"],runtimeMode:e=>{e&&console.warn("[Bedrock] DEPRECATION: runtimeMode is no longer used. Authentication method is now auto-detected from configured credentials.")},region:e=>e||process.env.AWS_REGION||process.env.AWS_DEFAULT_REGION||"",profile:e=>e||process.env.AWS_PROFILE||"",accessKeyId:e=>e||process.env.AWS_ACCESS_KEY_ID||"",secretAccessKey:e=>e||process.env.AWS_SECRET_ACCESS_KEY||"",sessionToken:e=>e||process.env.AWS_SESSION_TOKEN||"",applicationEndpointId:e=>e||process.env.BEDROCK_APPLICATION_ENDPOINT_ID||"",applicationInferenceProfileArn:e=>e||process.env.BEDROCK_APPLICATION_INFERENCE_PROFILE_ARN||process.env.BEDROCK_INFERENCE_PROFILE_ARN||"",applicationBaseUrl:e=>e||process.env.BEDROCK_APPLICATION_BASE_URL||"",systemPrompt:i.systemPrompt,systemPromptPath:i.systemPromptPath,codeReviewPromptPath:i.codeReviewPromptPath,timeout:i.timeout,temperature:e=>{if(!e)return;E("temperature",/^(2|\d)(\.\d{1,2})?$/.test(e),"Must be decimal between 0 and 2");const t=Number(e);return E("temperature",t>0,"Must be greater than 0"),E("temperature",t<=2,"Must be less than or equal to 2"),t},maxTokens:e=>{if(e)return E("maxTokens",/^\d+$/.test(e),"Must be an integer"),Number(e)},logging:i.logging,locale:i.locale,generate:i.generate,type:i.type,maxLength:i.maxLength,includeBody:i.includeBody,topP:e=>{if(!e)return;E("topP",/^(1|\d)(\.\d{1,2})?$/.test(e),"Must be decimal between 0 and 1");const t=Number(e);return E("topP",t>0,"Must be greater than 0"),E("topP",t<=1,"Must be less than or equal to 1"),t},codeReview:i.codeReview,disabled:i.disabled,stream:i.stream,watchMode:i.watchMode,disableLowerCase:i.disableLowerCase,inferenceParameters:Ke("BEDROCK.inferenceParameters"),diffCompression:i.diffCompression,maxHunkLines:i.maxHunkLines,maxDiffLines:i.maxDiffLines,diffContext:i.diffContext}},Ra=e=>typeof e=="object"&&e!==null,Po=(e,t)=>{Object.keys(e).forEach(n=>{const o=e[n];Ra(o)&&t in o&&(o[t]=!0)})},Ia=e=>{Po(e,"includeBody")},ka=e=>{Po(e,"disableLowerCase")};let xe,Se=null,Bt=null;const La=(e=[])=>{const t={};for(const n of e)if(n.startsWith("--")){const[o,s]=n.slice(2).split("="),[r,a]=o.split(".");r&&a&&r in Ae?(t[r]||(t[r]={}),t[r][a]=s):t[o]=s}return t},Oa=()=>{const e=ke.homedir(),t=process.env.AICOMMIT_CONFIG_PATH,n=bo,o=v.join(e,".aicommit2");return[t,n,o].filter(s=>!!s)},pe=async()=>{const e=Oa();for(const t of e)if(await He(t))return t;return bo},Ma=e=>e.replace(/\$\{([a-zA-Z_][a-zA-Z0-9_]*)\}|\$([a-zA-Z_][a-zA-Z0-9_]*)/g,(t,n,o)=>{const s=n||o;return process.env[s]??""}),Ao=e=>{if(Array.isArray(e)||e===null||typeof e!="object")return e;const t={};for(const[n,o]of Object.entries(e)){const s=Ao(o);if(!n.includes(".")){t[n]=s;continue}const r=n.split(".");let a=t;for(const c of r.slice(0,-1)){const l=a[c];(!l||typeof l!="object"||Array.isArray(l))&&(a[c]={}),a=a[c]}a[r[r.length-1]]=s}return t},$e=async()=>{const e=await pe();if(Se&&Bt===e)return Se;xe=e;try{const t=await I.readFile(e,"utf8"),n=Ma(t);return Se=Ao(de.parse(n)),Bt=e,Se}catch(t){return t.code==="ENOENT"?(xe=void 0,{}):(console.error(`Error reading config file ${e}:`,t),xe=void 0,{})}},xo=()=>{Se=null,Bt=null},J=async(e,t=[])=>{const n=await $e(),o=La(t),s={...e,...o},r={},a=$a(n),c={};for(const u of a){const d=n[u]?.envKey;let f;d?(f=[d],u==="BEDROCK"&&d!=="BEDROCK_APPLICATION_API_KEY"&&f.push("BEDROCK_APPLICATION_API_KEY")):u==="BEDROCK"?f=["BEDROCK_API_KEY","BEDROCK_APPLICATION_API_KEY"]:f=[`${u}_API_KEY`];const g=f.map(y=>y?process.env[y]:void 0).find(y=>typeof y=="string"&&y.length>0);g&&(c[u]={key:g})}const l=(u,d)=>{const f=s[`${u}.${d}`]??s[u]?.[d],g=c[u]?.[d],y=n[u]?.[d],m=s[d]??n[d];return f!==void 0?f:g!==void 0?g:y!==void 0?y:m};for(const[u,d]of Object.entries(i)){const f=s[u]??n[u];r[u]=d(f)}for(const u of a){r[u]={};const d=Ae[u]||qe(u);for(const[f,g]of Object.entries(d)){const y=l(u,f);r[u][f]=g(y)}}return r},We=async e=>{const t=await $e();for(const[s,r]of e){const[a,c]=s.split(".");if(!c){const d=i[s];if(!d)throw new p(`Invalid config property: ${s}`);t[s]=d(r);continue}if(t[a]||(t[a]={}),fe.includes(a)){const d=Ae[a][c];if(!d)throw new p(`Invalid config property: ${s}`);t[a][c]=d(r);continue}if(!/^[A-Z][A-Z0-9_]*$/.test(a))throw new p(`Invalid service name: ${a}. Service names must be uppercase letters, numbers, and underscores.`);const u=qe(a);if(!u[c])throw new p(`Invalid config property for custom service: ${s}`);try{t[a][c]=u[c](r)}catch(d){throw d instanceof p?d:new p(`Invalid value for ${s}: ${d.message}`)}}const n=await pe(),o=v.dirname(n);await I.mkdir(o,{recursive:!0}),await I.writeFile(n,de.stringify(t),"utf8"),xo()},Ta=async e=>{const t=await $e();for(const[s,r]of e){const[a,c]=s.split("."),l=t[a];if(c==="model"){l||(t[a]={});const d=t[a][c]||[],f=typeof r=="string"?r.split(",").map(g=>g.trim()).filter(g=>!!g):r;t[a][c]=Ft([...d,...f]);continue}if(l&&l.compatible===!0){l||(t[a]={});const d=qe(a);if(!d[c])throw new p(`Invalid config property: ${s}`);try{t[a][c]=d[c](r)}catch(f){throw f instanceof p?f:new p(`Invalid value for ${s}: ${f.message}`)}continue}if(a in Ae){l||(t[a]={});const d=Ae[a][c];if(!d)throw new p(`Invalid config property: ${s}`);t[a][c]=d(r)}else{const d=qe(a);if(!d[c])throw new p(`Invalid config property: ${s}`);t[a]||(t[a]={}),t[a][c]=d[c](r)}}const n=await pe(),o=v.dirname(n);await I.mkdir(o,{recursive:!0}),await I.writeFile(n,de.stringify(t),"utf8"),xo()},Da=async()=>{const e=await $e();console.log(de.stringify(e))},Na=async()=>{console.log(await pe())},qe=e=>({compatible:G("compatible"),stream:G("stream"),url:t=>t?(E(`${e}.url`,/^https?:\/\//.test(t),"Must be a valid URL"),t):"",path:t=>t||"",key:t=>t||"",envKey:t=>t||"",model:t=>t?(typeof t=="string"?t?.split(","):t).map(o=>o.trim()).filter(o=>!!o&&o.length>0):[],systemPrompt:i.systemPrompt,systemPromptPath:i.systemPromptPath,codeReviewPromptPath:i.codeReviewPromptPath,timeout:i.timeout,temperature:i.temperature,maxTokens:i.maxTokens,logging:i.logging,locale:i.locale,generate:i.generate,type:i.type,maxLength:i.maxLength,includeBody:i.includeBody,topP:i.topP,codeReview:i.codeReview,disabled:i.disabled,watchMode:i.watchMode,disableLowerCase:i.disableLowerCase,autoCopy:i.autoCopy,diffCompression:i.diffCompression,maxHunkLines:i.maxHunkLines,maxDiffLines:i.maxDiffLines,diffContext:i.diffContext}),N=e=>typeof e=="string"&&e.trim().length>0,_a=()=>{try{const e=typeof gt<"u"?gt.resolve:void 0;return e?(e("@github/copilot-sdk"),!0):typeof import.meta.resolve=="function"?(import.meta.resolve("@github/copilot-sdk"),!0):!1}catch{return!1}};let Ht;const ja=e=>Y(e)?(Ht===void 0&&(Ht=_a()),Ht):!1,Y=e=>(Array.isArray(e.model)?e.model:N(e.model)?[e.model.trim()]:[]).length>0,ze=e=>{const t=N(e.key),n=N(e.region)||N(process.env.AWS_REGION)||N(process.env.AWS_DEFAULT_REGION),o=N(e.profile)||N(process.env.AWS_PROFILE),s=N(e.accessKeyId)&&N(e.secretAccessKey)||N(process.env.AWS_ACCESS_KEY_ID)&&N(process.env.AWS_SECRET_ACCESS_KEY),r=N(e.applicationBaseUrl)||N(process.env.BEDROCK_APPLICATION_BASE_URL),a=N(e.applicationEndpointId)||N(process.env.BEDROCK_APPLICATION_ENDPOINT_ID),c=N(process.env.BEDROCK_APPLICATION_API_KEY);return n&&(t||o||s)||(r&&t||a&&c)},he=(e,t)=>Object.entries(e).map(([n,o])=>[n,o]).filter(([n,o])=>!o.disabled).filter(([n,o])=>fe.includes(n)||o.compatible===!0).filter(([n,o])=>{switch(t){case"commit":return n==="OLLAMA"?!!o&&Y(o):n==="COPILOT_SDK"?!!o&&ja(o):n==="HUGGINGFACE"?!!o&&!!o.cookie:n==="BEDROCK"?Y(o)&&ze(o):!!o.key&&o.key.length>0;case"review":const s=e.codeReview||o.codeReview;return n==="OLLAMA"||n==="COPILOT_SDK"?!!o&&Y(o)&&s:n==="HUGGINGFACE"?!!o&&!!o.cookie&&s:n==="BEDROCK"?Y(o)&&ze(o)&&s:!!o.key&&o.key.length>0&&s;case"watch":const r=e.watchMode||o.watchMode;return n==="OLLAMA"||n==="COPILOT_SDK"?!!o&&Y(o)&&r:n==="HUGGINGFACE"?!!o&&!!o.cookie&&r:n==="BEDROCK"?Y(o)&&ze(o)&&r:o.compatible?!!o.url&&!!o.key&&r:!!o.key&&o.key.length>0&&r}}).map(([n])=>n);class Fa{static create(t,n){return new t(n)}}const Ga="stats.json",Ye=2,Ba=30,Ut=()=>v.join(Co,Ga),Ve=async()=>{const e=Ut();if(!await He(e))return{version:Ye,metrics:[],selections:[]};try{const t=await I.readFile(e,"utf-8"),n=JSON.parse(t);return!n.version||n.version<Ye?{version:Ye,metrics:n.metrics||[],selections:n.selections||[]}:n}catch{return{version:Ye,metrics:[],selections:[]}}},Ha=(e,t)=>{const n=Date.now()-t*24*60*60*1e3;return{version:e.version,metrics:e.metrics.filter(o=>o.timestamp>=n),selections:e.selections.filter(o=>o.timestamp>=n)}},So=async(e,t)=>{const n=Ut(),o=v.dirname(n),s=t?Ha(e,t):e;await I.mkdir(o,{recursive:!0}),await I.writeFile(n,JSON.stringify(s,null,2),"utf-8")},Ua=async e=>{const t={timestamp:Date.now(),provider:e.provider,model:e.model,responseTimeMs:e.responseTimeMs,success:e.success,errorCode:e.errorCode,tokensUsed:e.tokensUsed},n=await Ve();n.metrics.push(t),await So(n,e.statsDays)},Ka=async e=>{const t={timestamp:Date.now(),provider:e.provider,model:e.model},n=await Ve();n.selections.push(t),await So(n,e.statsDays)},Wa=(e,t,n)=>{const o=t.filter(u=>u.provider===e),s=n.filter(u=>u.provider===e);if(o.length===0)return{provider:e,totalRequests:0,successCount:0,failureCount:0,selectedCount:s.length,selectionRate:0,avgResponseTimeMs:0,minResponseTimeMs:0,maxResponseTimeMs:0};const r=o.filter(u=>u.success),a=o.map(u=>u.responseTimeMs),c=s.length,l=r.length>0?Math.min(100,Math.round(c/r.length*1e3)/10):0;return{provider:e,totalRequests:o.length,successCount:r.length,failureCount:o.length-r.length,selectedCount:c,selectionRate:l,avgResponseTimeMs:Math.round(a.reduce((u,d)=>u+d,0)/a.length),minResponseTimeMs:Math.min(...a),maxResponseTimeMs:Math.max(...a)}},qa=async(e=Ba)=>{const t=await Ve(),n=Date.now()-e*24*60*60*1e3,o=t.metrics.filter(u=>u.timestamp>=n),s=t.selections.filter(u=>u.timestamp>=n);if(o.length===0)return{totalRequests:0,successRate:0,avgResponseTimeMs:0,providerStats:[],periodStart:n,periodEnd:Date.now()};const a=[...new Set(o.map(u=>u.provider))].map(u=>Wa(u,o,s)).sort((u,d)=>d.totalRequests-u.totalRequests),c=o.filter(u=>u.success).length,l=o.reduce((u,d)=>u+d.responseTimeMs,0);return{totalRequests:o.length,successRate:Math.round(c/o.length*1e3)/10,avgResponseTimeMs:Math.round(l/o.length),providerStats:a,periodStart:Math.min(...o.map(u=>u.timestamp)),periodEnd:Math.max(...o.map(u=>u.timestamp))}},za=async()=>{const e=Ut();await He(e)&&await I.unlink(e)},Ya=async()=>(await Ve()).metrics.length>0,$o=(e,t)=>{const n=h.red.bold(`[${e}]`);return Ss({name:`${n} ${t}`,value:t,isError:!0,disabled:!0})},Ro=e=>{let t=!1;return $s({next:n=>{if(Object.assign(n,{provider:e.provider,model:e.model}),e.statsEnabled===!1||t)return;t=!0;const o=n.isError===!0,s={provider:e.provider,model:e.model,responseTimeMs:Date.now()-e.startTime,success:!o,errorCode:o?"REQUEST_ERROR":void 0,statsDays:e.statsDays};Ua(s).catch(()=>{})}})};class Va{constructor(){this.loaders=new Map,this.cache=new Map,this.loadService=async t=>{const n=this.cache.get(t);if(n)return n;const o=this.loaders.get(t);if(!o)return null;const s=await o();return this.cache.set(t,s),s},this.createService=async(t,n)=>{const o=await this.loadService(t);return o?new o(n):null},this.createRequest$=(t,n,o)=>{const s=Date.now(),r=Array.isArray(n.config.model)?n.config.model[0]:n.config.model;return Le(this.createService(t,n)).pipe(fn(a=>a?(o==="commit"?a.generateCommitMessage$():a.generateCodeReview$()).pipe(Ro({provider:t,model:r||"unknown",startTime:s,statsEnabled:n.statsEnabled,statsDays:n.statsDays})):$o(t,"Invalid AI type")))},this.registerBuiltinProviders=()=>{this.loaders.set("OPENAI",()=>import("./openai.service-c0d8d959.mjs").then(t=>t.OpenAIService)),this.loaders.set("COPILOT_SDK",()=>import("./copilot-sdk.service-e3bf61b3.mjs").then(t=>t.CopilotSdkService)),this.loaders.set("OPENROUTER",()=>import("./openrouter.service-0791fb7b.mjs").then(t=>t.OpenRouterService)),this.loaders.set("GEMINI",()=>import("./gemini.service-0f288526.mjs").then(t=>t.GeminiService)),this.loaders.set("ANTHROPIC",()=>import("./anthropic.service-11f6192a.mjs").then(t=>t.AnthropicService)),this.loaders.set("HUGGINGFACE",()=>import("./hugging-face.service-135bd6ce.mjs").then(t=>t.HuggingFaceService)),this.loaders.set("MISTRAL",()=>import("./mistral.service-ac6622a0.mjs").then(t=>t.MistralService)),this.loaders.set("CODESTRAL",()=>import("./codestral.service-74ed0b75.mjs").then(t=>t.CodestralService)),this.loaders.set("OLLAMA",()=>import("./ollama.service-782b098b.mjs").then(t=>t.OllamaService)),this.loaders.set("COHERE",()=>import("./cohere.service-86c58a47.mjs").then(t=>t.CohereService)),this.loaders.set("GROQ",()=>import("./groq.service-73312be1.mjs").then(t=>t.GroqService)),this.loaders.set("PERPLEXITY",()=>import("./perplexity.service-977e0442.mjs").then(t=>t.PerplexityService)),this.loaders.set("BEDROCK",()=>import("./bedrock.service-66a1b85e.mjs").then(t=>t.BedrockService)),this.loaders.set("GITHUB_MODELS",()=>import("./github-models.service-a7f34295.mjs").then(t=>t.GitHubModelsService)),this.loaders.set("DEEPSEEK",()=>import("./deep-seek.service-99b5c137.mjs").then(t=>t.DeepSeekService))},this.registerBuiltinProviders()}}const Ja=new Va;class Kt{getDetectedMessage(t){return`Detected ${t.files.length.toLocaleString()} changed file${t.files.length>1?"s":""} (${t.diff.length.toLocaleString()} characters)`}getDetectedFiles(t){return`Detected ${t.length.toLocaleString()} changed file${t.length>1?"s":""}`}}class Je extends Kt{constructor(){super(...arguments),this.name="git",this.excludeFromDiff=t=>`:(exclude)${t}`,this.filesToExclude=["package-lock.json","pnpm-lock.yaml","*.lock","*.lockb"].map(this.excludeFromDiff)}async assertRepo(){try{const{stdout:t}=await b("git",["rev-parse","--show-toplevel"],{reject:!0});return t.trim()}catch(t){const n=t;if(n.code==="ENOENT")throw new p(`Git command not found!
|
|
22
22
|
|
|
23
23
|
Please install Git first: https://git-scm.com/downloads`);if(n.stderr){if(n.stderr.includes("not a git repository"))throw new p(`Not in a Git repository!
|
|
24
24
|
|
|
@@ -148,7 +148,7 @@ Solutions:
|
|
|
148
148
|
\u2022 Initialize a YADM repository: yadm init (or yadm clone <url>)
|
|
149
149
|
\u2022 Navigate to an existing Jujutsu, Git, or YADM repository
|
|
150
150
|
\u2022 Set FORCE_GIT="true" environment variable to force Git detection
|
|
151
|
-
\u2022 Set forceGit=true in config file to prefer Git detection`)},te=async()=>(zt||(zt=await Xa()),zt);let Re=null;const Io=async()=>{if(Re!==null)return Re;try{Re=(await J({})).diffContext}catch{Re=me}return Re},ko=(e,t)=>{const{diff:n,stats:o}=ua(e.diff,t);return n===e.diff?e:{...e,diff:n,compression:o}},Yt=async()=>(await te()).assertRepo(),Vt=async(e,t)=>{const n=await te(),o=await Io(),s=await n.getStagedDiff(e,t,{diffContext:o});return s||null},Qa=async(e,t,n)=>{const o=await te();if(!o.getCommitDiff)throw new p(`Commit diff not supported for ${o.name}`);const s=await Io(),r=await o.getCommitDiff(e,t,n,{diffContext:s});return r||null},Za=async()=>(await te()).getCommentChar(),ec=e=>{const t=e.files.length.toLocaleString(),n=e.files.length>1?"s":"",o=e.diff.length.toLocaleString();return`Detected ${t} changed file${n} (${o} characters)`},Xe=async()=>(await te()).name,tc=async(e,t,n)=>{await(await te()).commit(e,t||[],n)},Qe=async()=>(await te()).getBranchName(),Ze=async(e=5)=>(await te()).getRecentCommits(e);class et{constructor(t,n,o="",s=""){this.config=t,this.stagedDiff=n,this.branchName=o,this.recentCommits=s,this.getDiffForModel=r=>{const a={mode:r.diffCompression||"none",maxHunkLines:r.maxHunkLines||0,maxDiffLines:r.maxDiffLines||0};return ko(this.stagedDiff,a)},this.extractProviderName=r=>{if(!r)return"compatible";try{return new URL(r).hostname}catch{return"compatible"}},this.createCommitMsgRequests$=r=>this.createServiceRequests$(r,"commit"),this.createCodeReviewRequests$=r=>this.createServiceRequests$(r,"review"),this.createServiceRequests$=(r,a)=>Le(r).pipe(pn(c=>this.createProviderRequests$(c,a)),Rs(c=>$o("UNKNOWN",c.message||"Unknown error"))),this.createProviderRequests$=(r,a)=>{const c=this.config[r],l=Array.isArray(c.model)?c.model:[c.model];return Le(l).pipe(pn(u=>this.createModelRequest$(r,u,a)))},this.createModelRequest$=(r,a,c)=>{const l=this.config[r];if(l.compatible)return this.createCompatibleServiceRequest$(l,a,c);const u=this.getDiffForModel(l);return Ja.createRequest$(r,{config:{...l,model:a},stagedDiff:u,keyName:a,branchName:this.branchName,recentCommits:this.recentCommits,statsEnabled:this.config.useStats,statsDays:this.config.statsDays,modelNameDisplay:this.config.modelNameDisplay},c)},this.createCompatibleServiceRequest$=(r,a,c)=>{const l=Date.now(),u=this.extractProviderName(r.url),d=this.getDiffForModel(r);return Le(import("./openai-compatible.service-
|
|
151
|
+
\u2022 Set forceGit=true in config file to prefer Git detection`)},te=async()=>(zt||(zt=await Xa()),zt);let Re=null;const Io=async()=>{if(Re!==null)return Re;try{Re=(await J({})).diffContext}catch{Re=me}return Re},ko=(e,t)=>{const{diff:n,stats:o}=ua(e.diff,t);return n===e.diff?e:{...e,diff:n,compression:o}},Yt=async()=>(await te()).assertRepo(),Vt=async(e,t)=>{const n=await te(),o=await Io(),s=await n.getStagedDiff(e,t,{diffContext:o});return s||null},Qa=async(e,t,n)=>{const o=await te();if(!o.getCommitDiff)throw new p(`Commit diff not supported for ${o.name}`);const s=await Io(),r=await o.getCommitDiff(e,t,n,{diffContext:s});return r||null},Za=async()=>(await te()).getCommentChar(),ec=e=>{const t=e.files.length.toLocaleString(),n=e.files.length>1?"s":"",o=e.diff.length.toLocaleString();return`Detected ${t} changed file${n} (${o} characters)`},Xe=async()=>(await te()).name,tc=async(e,t,n)=>{await(await te()).commit(e,t||[],n)},Qe=async()=>(await te()).getBranchName(),Ze=async(e=5)=>(await te()).getRecentCommits(e);class et{constructor(t,n,o="",s=""){this.config=t,this.stagedDiff=n,this.branchName=o,this.recentCommits=s,this.getDiffForModel=r=>{const a={mode:r.diffCompression||"none",maxHunkLines:r.maxHunkLines||0,maxDiffLines:r.maxDiffLines||0};return ko(this.stagedDiff,a)},this.extractProviderName=r=>{if(!r)return"compatible";try{return new URL(r).hostname}catch{return"compatible"}},this.createCommitMsgRequests$=r=>this.createServiceRequests$(r,"commit"),this.createCodeReviewRequests$=r=>this.createServiceRequests$(r,"review"),this.createServiceRequests$=(r,a)=>Le(r).pipe(pn(c=>this.createProviderRequests$(c,a)),Rs(c=>$o("UNKNOWN",c.message||"Unknown error"))),this.createProviderRequests$=(r,a)=>{const c=this.config[r],l=Array.isArray(c.model)?c.model:[c.model];return Le(l).pipe(pn(u=>this.createModelRequest$(r,u,a)))},this.createModelRequest$=(r,a,c)=>{const l=this.config[r];if(l.compatible)return this.createCompatibleServiceRequest$(l,a,c);const u=this.getDiffForModel(l);return Ja.createRequest$(r,{config:{...l,model:a},stagedDiff:u,keyName:a,branchName:this.branchName,recentCommits:this.recentCommits,statsEnabled:this.config.useStats,statsDays:this.config.statsDays,modelNameDisplay:this.config.modelNameDisplay},c)},this.createCompatibleServiceRequest$=(r,a,c)=>{const l=Date.now(),u=this.extractProviderName(r.url),d=this.getDiffForModel(r);return Le(import("./openai-compatible.service-7fead9c0.mjs")).pipe(fn(({OpenAICompatibleService:f})=>{const g=Fa.create(f,{config:{...r,url:r.url||"",path:r.path||"",model:a},stagedDiff:d,keyName:a,branchName:this.branchName,recentCommits:this.recentCommits,modelNameDisplay:this.config.modelNameDisplay});return(c==="commit"?g.generateCommitMessage$():g.generateCodeReview$()).pipe(Ro({provider:u,model:a,startTime:l,statsEnabled:this.config.useStats,statsDays:this.config.statsDays}))}))}}}const nc=1e5;class K{constructor(){this.title="aicommit2",this.formatCompressionStats=t=>{if(!t||t.originalChars===t.compressedChars)return null;const n=Math.round((1-t.compressedChars/t.originalChars)*100);return`[compact: ${t.originalChars.toLocaleString()} \u2192 ${t.compressedChars.toLocaleString()} chars, ${n}% saved]`},this.formatBytes=t=>t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:`${(t/(1024*1024)).toFixed(1)} MB`}printTitle(){try{const t=wn.textSync(this.title,{font:"Small Slant"}),n=Ls(["#8B5CF6","#A020F0","#D946EF"]);console.log(h.bold(n.multiline(t)))}catch{console.log(h.bold(wn.textSync(this.title,{font:"Small Slant"})))}}showLoader(t){if(this.loader){this.loader.text=t;return}this.loader=Cn(t).start()}stopLoader(){this.loader?.stop(),this.loader=void 0}displaySpinner(t){return Cn(t).start()}stopSpinner(t){t.stop(),t.clear()}printStagedFiles(t,n){const o=Buffer.byteLength(t.diff,"utf8"),s=this.formatBytes(o),r=ec(t),a=this.formatCompressionStats(n);console.log(h.bold.green("\u2714 ")+h.bold(r)+h.dim(` (${s})`)+(a?h.cyan(` ${a}`):"")+h.bold(":")),console.log(`${t.files.map(l=>` ${l}`).join(`
|
|
152
152
|
`)}
|
|
153
153
|
`),o>nc&&!n&&(console.log(h.yellow(`\u26A0 Large diff detected (${s}). This may increase processing time and costs.`)),console.log(h.dim(` Consider using --exclude to filter large files or diffCompression=compact.
|
|
154
154
|
`)))}printAnalyzed(){console.log(`
|
|
@@ -277,7 +277,7 @@ ${k} \u{1F4DD} Generated commit message:
|
|
|
277
277
|
`),L+=`
|
|
278
278
|
${A[0]}
|
|
279
279
|
`);const D=await I.readFile(it,"utf8"),X=L+`
|
|
280
|
-
`+D;await I.writeFile(it,X),d.printSavedCommitMessage()})().catch(c=>{new K().printError(c.message),q(c),process.exit(1)});const z=new K,an={OPENAI:{displayName:"OpenAI (ChatGPT)",authType:"api-key",envKeyHint:"OPENAI_API_KEY",defaultModel:"gpt-4o-mini"},COPILOT_SDK:{displayName:"GitHub Copilot SDK (Preview)",authType:"none",defaultModel:"gpt-4.1",setupNotes:"Uses local Copilot SDK auth flow (via Copilot CLI session), not GitHub Models API keys. Install/authenticate Copilot CLI first."},OPENROUTER:{displayName:"OpenRouter",authType:"api-key",envKeyHint:"OPENROUTER_API_KEY",defaultModel:"openrouter/auto",setupNotes:"OpenRouter supports many upstream models. You can keep openrouter/auto or choose a specific model slug."},ANTHROPIC:{displayName:"Anthropic (Claude)",authType:"api-key",envKeyHint:"ANTHROPIC_API_KEY",defaultModel:"claude-sonnet-4-20250514"},GEMINI:{displayName:"Google Gemini",authType:"api-key",envKeyHint:"GEMINI_API_KEY",defaultModel:"gemini-1.5-flash"},OLLAMA:{displayName:"Ollama (Local)",authType:"none",defaultModel:"llama3.2",setupNotes:"Ollama runs locally \u2014 no API key needed. Make sure Ollama is running."},GROQ:{displayName:"Groq",authType:"api-key",envKeyHint:"GROQ_API_KEY",defaultModel:"llama-3.3-70b-versatile"},DEEPSEEK:{displayName:"DeepSeek",authType:"api-key",envKeyHint:"DEEPSEEK_API_KEY",defaultModel:"deepseek-
|
|
280
|
+
`+D;await I.writeFile(it,X),d.printSavedCommitMessage()})().catch(c=>{new K().printError(c.message),q(c),process.exit(1)});const z=new K,an={OPENAI:{displayName:"OpenAI (ChatGPT)",authType:"api-key",envKeyHint:"OPENAI_API_KEY",defaultModel:"gpt-4o-mini"},COPILOT_SDK:{displayName:"GitHub Copilot SDK (Preview)",authType:"none",defaultModel:"gpt-4.1",setupNotes:"Uses local Copilot SDK auth flow (via Copilot CLI session), not GitHub Models API keys. Install/authenticate Copilot CLI first."},OPENROUTER:{displayName:"OpenRouter",authType:"api-key",envKeyHint:"OPENROUTER_API_KEY",defaultModel:"openrouter/auto",setupNotes:"OpenRouter supports many upstream models. You can keep openrouter/auto or choose a specific model slug."},ANTHROPIC:{displayName:"Anthropic (Claude)",authType:"api-key",envKeyHint:"ANTHROPIC_API_KEY",defaultModel:"claude-sonnet-4-20250514"},GEMINI:{displayName:"Google Gemini",authType:"api-key",envKeyHint:"GEMINI_API_KEY",defaultModel:"gemini-1.5-flash"},OLLAMA:{displayName:"Ollama (Local)",authType:"none",defaultModel:"llama3.2",setupNotes:"Ollama runs locally \u2014 no API key needed. Make sure Ollama is running."},GROQ:{displayName:"Groq",authType:"api-key",envKeyHint:"GROQ_API_KEY",defaultModel:"llama-3.3-70b-versatile"},DEEPSEEK:{displayName:"DeepSeek",authType:"api-key",envKeyHint:"DEEPSEEK_API_KEY",defaultModel:"deepseek-v4-flash"},MISTRAL:{displayName:"Mistral AI",authType:"api-key",envKeyHint:"MISTRAL_API_KEY",defaultModel:"mistral-small-latest"},CODESTRAL:{displayName:"Codestral",authType:"api-key",envKeyHint:"CODESTRAL_API_KEY",defaultModel:"codestral-latest"},COHERE:{displayName:"Cohere",authType:"api-key",envKeyHint:"COHERE_API_KEY",defaultModel:"command-r-plus"},PERPLEXITY:{displayName:"Perplexity",authType:"api-key",envKeyHint:"PERPLEXITY_API_KEY",defaultModel:"sonar"},GITHUB_MODELS:{displayName:"GitHub Models",authType:"api-key",envKeyHint:"GITHUB_MODELS_API_KEY",defaultModel:"openai/gpt-4o-mini",setupNotes:"Use a GitHub personal access token (including github_pat_...). Run `aic2 github-login` for browser-based auth."},HUGGINGFACE:{displayName:"Hugging Face",authType:"cookie",defaultModel:"CohereForAI/c4ai-command-r-plus",setupNotes:"Requires a Hugging Face cookie for authentication."},BEDROCK:{displayName:"AWS Bedrock",authType:"complex",setupNotes:"Requires AWS credentials. Configure via AWS CLI or set region + access keys."}},Zo=["OPENAI","OPENROUTER","ANTHROPIC","GEMINI","OLLAMA","GROQ","DEEPSEEK"];var gl=F({name:"setup",parameters:[],help:{description:"Interactive setup wizard for configuring AI providers",examples:["aic2 setup"]}},e=>{(async()=>{for(z.printTitle(),console.log(),z.printInfo(`Welcome to aicommit2 setup! Let's configure your AI providers.
|
|
281
281
|
`);;){const t=await yl();if(!t)break;await wl(t.key,t.info);const{addMore:n}=await M.prompt([{type:"confirm",name:"addMore",message:"Would you like to configure another provider?",default:!1}]);if(!n)break;console.log()}z.printSuccess("Setup complete! Run `aic2` to generate commit messages.")})().catch(t=>{z.printError(t.message),q(t),process.exit(1)})});const yl=async()=>{const e=Zo.map(r=>({name:an[r].displayName,value:r})),n=fe.filter(r=>!Zo.includes(r)).map(r=>({name:an[r]?.displayName||r,value:r})),{provider:o}=await M.prompt([{type:"list",name:"provider",message:"Select an AI provider to configure:",choices:[new M.Separator("\u2500\u2500 Popular \u2500\u2500"),...e,new M.Separator("\u2500\u2500 Other \u2500\u2500"),...n,new M.Separator,{name:"Done (exit setup)",value:null}]}]);if(!o)return null;const s=an[o]||{displayName:o,authType:"api-key"};return{key:o,info:s}},wl=async(e,t)=>{console.log(),t.setupNotes&&(z.printInfo(t.setupNotes),console.log());const n=[];switch(t.authType){case"api-key":{const{apiKey:r}=await M.prompt([{type:"password",name:"apiKey",message:`Enter your ${t.displayName} API key:`,mask:"*",validate:a=>a.trim()?!0:"API key is required"}]);n.push([`${e}.key`,r.trim()]);break}case"cookie":{const{cookie:r}=await M.prompt([{type:"password",name:"cookie",message:`Enter your ${t.displayName} cookie:`,mask:"*",validate:a=>a.trim()?!0:"Cookie is required"}]);n.push([`${e}.cookie`,r.trim()]);break}case"none":{if(e==="OLLAMA"){const{host:r}=await M.prompt([{type:"input",name:"host",message:"Ollama host URL:",default:Pe}]);r&&r!==Pe&&n.push([`${e}.host`,r.trim()])}break}case"complex":{z.printInfo("AWS Bedrock requires region and credentials."),console.log();const{region:r}=await M.prompt([{type:"input",name:"region",message:"AWS Region (e.g., us-east-1):",validate:c=>c.trim()?!0:"Region is required"}]);n.push([`${e}.region`,r.trim()]);const{authMethod:a}=await M.prompt([{type:"list",name:"authMethod",message:"Authentication method:",choices:[{name:"AWS Profile (from ~/.aws/credentials)",value:"profile"},{name:"Access Key + Secret Key",value:"keys"},{name:"Environment variables (already set)",value:"env"}]}]);if(a==="profile"){const{profile:c}=await M.prompt([{type:"input",name:"profile",message:"AWS Profile name:",default:"default"}]);n.push([`${e}.profile`,c.trim()])}else if(a==="keys"){const{accessKeyId:c,secretAccessKey:l}=await M.prompt([{type:"password",name:"accessKeyId",message:"AWS Access Key ID:",mask:"*"},{type:"password",name:"secretAccessKey",message:"AWS Secret Access Key:",mask:"*"}]);n.push([`${e}.accessKeyId`,c.trim()]),n.push([`${e}.secretAccessKey`,l.trim()])}break}}const{model:o}=await M.prompt([{type:"input",name:"model",message:"Model to use (comma-separated for multiple):",default:t.defaultModel||"",validate:r=>r.trim()?!0:"At least one model is required"}]);n.push([`${e}.model`,o.trim()]);const s=z.displaySpinner("Saving configuration...");try{await We(n),z.stopSpinner(s),z.printSuccess(`${t.displayName} configured successfully!`),t.envKeyHint&&console.log(` Tip: You can also set the ${t.envKeyHint} environment variable instead.`)}catch(r){z.stopSpinner(s),z.printError(`Failed to save configuration: ${r.message}`)}},es=20,ts=e=>e<1e3?`${e}ms`:`${(e/1e3).toFixed(1)}s`,ns=e=>new Date(e).toLocaleDateString(),Cl=e=>{const t=Math.round(e/100*es),n=es-t;return(e>=80?h.green:e>=50?h.yellow:h.red)("\u2588".repeat(t))+h.gray("\u2591".repeat(n))},bl=e=>{const t=e.totalRequests>0?Math.round(e.successCount/e.totalRequests*100):0,n=Cl(t),o=e.provider.padEnd(14),s=`${t}%`.padStart(4),r=`${e.totalRequests}`.padStart(4),a=`${e.selectedCount}`.padStart(4),c=e.selectionRate>0?`(${e.selectionRate}%)`.padStart(7):"".padStart(7),l=ts(e.avgResponseTimeMs).padStart(6);console.log(` ${h.bold(o)} ${s} ${n} ${r} ${h.cyan(a)} ${h.gray(c)} ${l}`)},El=async e=>{if(!await Ya()){console.log(h.yellow(`
|
|
282
282
|
No statistics recorded yet.`)),console.log(h.gray(`Statistics will be collected as you generate commit messages.
|
|
283
283
|
`));return}const n=await qa(e);if(n.totalRequests===0){console.log(h.yellow(`
|
package/dist/cli.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import"cleye";import"./cli-
|
|
2
|
+
import"cleye";import"./cli-005bffd8.mjs";import"module";import"crypto";import"fs";import"os";import"path";import"node:buffer";import"node:path";import"node:child_process";import"node:process";import"child_process";import"node:url";import"node:os";import"assert";import"events";import"node:fs";import"buffer";import"stream";import"util";import"node:util";import"inquirer";import"rxjs";import"fs/promises";import"chalk";import"readline";import"figlet";import"gradient-string";import"ora";import"inquirer-reactive-list-prompt";import"winston";import"winston-daily-rotate-file";import"axios";import"url";import"node:fs/promises";import"chokidar";import"rxjs/operators";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import h from"chalk";import{concatMap as f,from as u,map as g,catchError as C}from"rxjs";import{fromPromise as y}from"rxjs/internal/observable/innerFrom";import{A,l as b,a as w,b as P,c as I,e as v,d as M}from"./ai.service-
|
|
1
|
+
import h from"chalk";import{concatMap as f,from as u,map as g,catchError as C}from"rxjs";import{fromPromise as y}from"rxjs/internal/observable/innerFrom";import{A,l as b,a as w,b as P,c as I,e as v,d as M}from"./ai.service-8f81dd1f.mjs";import{b as k,g as R,t as x,H as $}from"./cli-005bffd8.mjs";import"fs";import"path";import"@pacote/xxhash";import"winston";import"cleye";import"module";import"crypto";import"os";import"node:buffer";import"node:path";import"node:child_process";import"node:process";import"child_process";import"node:url";import"node:os";import"assert";import"events";import"node:fs";import"buffer";import"stream";import"util";import"node:util";import"inquirer";import"fs/promises";import"readline";import"figlet";import"gradient-string";import"ora";import"inquirer-reactive-list-prompt";import"winston-daily-rotate-file";import"axios";import"url";import"node:fs/promises";import"chokidar";import"rxjs/operators";class S extends A{constructor(t){super(t),this.params=t,this.apiKey="",this.colors={primary:"#e28c58",secondary:"#fff"},this.serviceName=h.bgHex(this.colors.primary).hex(this.colors.secondary).bold(`[Codestral${this.formatModelSuffix()}]`),this.errorPrefix=h.red.bold(`[Codestral${this.formatModelSuffix()}]`),this.apiKey=this.params.config.key}getServiceSpecificErrorMessage(t){const e=t.message||"";return e.includes("API key")||e.includes("api_key")?"Invalid API key. Check your Codestral API key in configuration":e.includes("rate_limit")||e.includes("Rate limit")?"Rate limit exceeded. Wait a moment and try again, or upgrade your Codestral plan":e.includes("model")||e.includes("Model")?"Model not found or not accessible. Check if the Codestral model name is correct":e.includes("Invalid model type")?"Invalid model type. Use supported models: codestral-latest, codestral-2501":e.includes("overloaded")||e.includes("capacity")?"Codestral service is overloaded. Try again in a few minutes":e.includes("403")||e.includes("Forbidden")?"Access denied. Your API key may not have permission for this Codestral model":e.includes("404")||e.includes("Not Found")?"Model or endpoint not found. Check your Codestral model configuration":e.includes("500")||e.includes("Internal Server Error")?"Codestral server error. Try again later":null}generateCommitMessage$(){return y(this.generateMessage("commit")).pipe(f(t=>u(t)),g(this.formatAsChoice),C(this.handleError$))}generateCodeReview$(){return y(this.generateMessage("review")).pipe(f(t=>u(t)),g(this.formatCodeReviewAsChoice),C(this.handleError$))}async generateMessage(t){const e=this.params.stagedDiff.diff,{logging:o,generate:s,type:m}=this.params.config,i=this.buildPromptOptions(),n=t==="review"?k(i):R(i);this.checkAvailableModels();const a=this.buildUserPrompt(e,t),c=`${this.params.config.url||"https://codestral.mistral.ai"}/v1/chat/completions`,r={Authorization:`Bearer ${this.apiKey}`,"content-type":"application/json"};b(e,t,"Codestral",this.params.config.model,c,r,o),w(e,t,"Codestral",n,a,o);const l=await this.createChatCompletions(n,t);return t==="review"?this.parseCodeReview(l):this.parseMessage(l,m,s)}checkAvailableModels(){if(["codestral-latest","codestral-2501"].includes(this.params.config.model))return!0;throw new Error("Invalid model type of Codestral AI")}async createChatCompletions(t,e){const o=this.params.stagedDiff.diff,{logging:s}=this.params.config,m=this.params.config.url||"https://codestral.mistral.ai",i={model:this.params.config.model,messages:[{role:"system",content:t},{role:"user",content:this.buildUserPrompt(this.params.stagedDiff.diff,e)}],temperature:this.params.config.temperature,top_p:this.params.config.topP,max_tokens:this.params.config.maxTokens,stream:!1,safe_prompt:!1,random_seed:x(10,1e3)};e==="commit"&&(i.response_format={type:"json_object"}),P(o,e,"Codestral",i,s);const n=Date.now();try{const d=await new $({method:"POST",baseURL:`${m}/v1/chat/completions`,timeout:this.params.config.timeout}).setHeaders({Authorization:`Bearer ${this.apiKey}`,"content-type":"application/json"}).setBody(i).execute(),c=Date.now()-n,r=d.data;if(I(o,e,"Codestral",r,s),!r.choices||r.choices.length===0||!r.choices[0].message?.content)throw v(o,e,"Codestral",{message:"No Content on response",result:r},s),new Error("No Content on response. Please open a Bug report");const p=r.choices[0].message.content;return M(o,e,"Codestral",c,p,s),p}catch(a){throw v(o,e,"Codestral",a,s),a}}}export{S as CodestralService};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import c from"chalk";import{CohereClientV2 as P}from"cohere-ai";import{concatMap as p,from as d,map as l,catchError as h}from"rxjs";import{fromPromise as f}from"rxjs/internal/observable/innerFrom";import{A as M,l as k,a as x,b,c as R,d as E,e as S}from"./ai.service-
|
|
1
|
+
import c from"chalk";import{CohereClientV2 as P}from"cohere-ai";import{concatMap as p,from as d,map as l,catchError as h}from"rxjs";import{fromPromise as f}from"rxjs/internal/observable/innerFrom";import{A as M,l as k,a as x,b,c as R,d as E,e as S}from"./ai.service-8f81dd1f.mjs";import{b as $,g as V,t as D}from"./cli-005bffd8.mjs";import"fs";import"path";import"@pacote/xxhash";import"winston";import"cleye";import"module";import"crypto";import"os";import"node:buffer";import"node:path";import"node:child_process";import"node:process";import"child_process";import"node:url";import"node:os";import"assert";import"events";import"node:fs";import"buffer";import"stream";import"util";import"node:util";import"inquirer";import"fs/promises";import"readline";import"figlet";import"gradient-string";import"ora";import"inquirer-reactive-list-prompt";import"winston-daily-rotate-file";import"axios";import"url";import"node:fs/promises";import"chokidar";import"rxjs/operators";class N extends M{constructor(r){super(r),this.params=r,this.colors={primary:"#D18EE2",secondary:"#fff"},this.serviceName=c.bgHex(this.colors.primary).hex(this.colors.secondary).bold(`[Cohere${this.formatModelSuffix()}]`),this.errorPrefix=c.red.bold(`[Cohere${this.formatModelSuffix()}]`),this.cohere=new P({token:this.params.config.key})}isValidCohereV2Response(r){const e=r;return e?.message?.content!==void 0&&Array.isArray(e.message.content)&&e.message.content.length>0&&typeof e.message.content[0]?.text=="string"}getServiceSpecificErrorMessage(r){const e=r.message||"";return e.includes("API key")||e.includes("api_key")?"Invalid API key. Check your Cohere API key in configuration":e.includes("rate_limit")||e.includes("Rate limit")?"Rate limit exceeded. Wait a moment and try again, or upgrade your Cohere plan":e.includes("model")||e.includes("Model")?"Model not found or not accessible. Check if the Cohere model name is correct":e.includes("overloaded")||e.includes("capacity")?"Cohere service is overloaded. Try again in a few minutes":e.includes("403")||e.includes("Forbidden")?"Access denied. Your API key may not have permission for this Cohere model":e.includes("404")||e.includes("Not Found")?"Model or endpoint not found. Check your Cohere model configuration":e.includes("500")||e.includes("Internal Server Error")?"Cohere server error. Try again later":null}generateCommitMessage$(){return f(this.generateMessage("commit")).pipe(p(r=>d(r)),l(this.formatAsChoice),h(this.handleError$))}generateCodeReview$(){return f(this.generateMessage("review")).pipe(p(r=>d(r)),l(this.formatCodeReviewAsChoice),h(this.handleError$))}async generateMessage(r){const e=this.params.stagedDiff.diff,{logging:o,temperature:g,generate:u,type:C,maxTokens:v}=this.params.config,n=this.buildPromptOptions(),i=r==="review"?$(n):V(n),a=`Here is the diff: ${e}`,y=[...i?[{role:"system",content:i}]:[],{role:"user",content:a}],A=`${this.params.config.url}/v2/chat`;k(e,r,"Cohere",this.params.config.model,A,{},o),x(e,r,"Cohere",i,a,o);const m={model:this.params.config.model,messages:y,max_tokens:v,temperature:g,seed:D(10,1e3),p:this.params.config.topP};b(e,r,"Cohere",m,o);const I=Date.now();try{const t=await this.cohere.chat(m,{timeoutInSeconds:Math.floor(this.params.config.timeout/1e3)}),w=Date.now()-I;if(!this.isValidCohereV2Response(t))throw new Error("Invalid response structure from Cohere v2 API");const s=t.message.content[0].text;return R(e,r,"Cohere",t,o),E(e,r,"Cohere",w,s,o),r==="review"?this.parseCodeReview(s):this.parseMessage(s,C,u)}catch(t){throw S(e,r,"Cohere",t,o),t}}}export{N as CohereService};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import u from"chalk";import{concatMap as S,from as E,map as A,catchError as D}from"rxjs";import{fromPromise as w}from"rxjs/internal/observable/innerFrom";import{A as T,l as k,a as v,b as y,c as b,d as P,e as R}from"./ai.service-
|
|
1
|
+
import u from"chalk";import{concatMap as S,from as E,map as A,catchError as D}from"rxjs";import{fromPromise as w}from"rxjs/internal/observable/innerFrom";import{A as T,l as k,a as v,b as y,c as b,d as P,e as R}from"./ai.service-8f81dd1f.mjs";import{n as x,o as N,p as I,b as $,g as U,C as F,q as B,r as H}from"./cli-005bffd8.mjs";import"fs";import"path";import"@pacote/xxhash";import"winston";import"cleye";import"module";import"crypto";import"os";import"node:buffer";import"node:path";import"node:child_process";import"node:process";import"child_process";import"node:url";import"node:os";import"assert";import"events";import"node:fs";import"buffer";import"stream";import"util";import"node:util";import"inquirer";import"fs/promises";import"readline";import"figlet";import"gradient-string";import"ora";import"inquirer-reactive-list-prompt";import"winston-daily-rotate-file";import"axios";import"url";import"node:fs/promises";import"chokidar";import"rxjs/operators";class j extends T{constructor(o){super(o),this.params=o,this.colors={primary:"#8957e5",secondary:"#FFF"},this.serviceName=u.bgHex(this.colors.primary).hex(this.colors.secondary).bold(`[Copilot SDK${this.formatModelSuffix()}]`),this.errorPrefix=u.red.bold(`[Copilot SDK${this.formatModelSuffix()}]`)}getServiceSpecificErrorMessage(o){const t=o.message||"";return o.code==="SDK_NOT_INSTALLED"?"Copilot SDK is not installed. Run: npm install @github/copilot-sdk":x(t)?"Copilot rejected classic ghp_ token. Use COPILOT_GITHUB_TOKEN with a Fine-Grained PAT or authenticate via copilot /login.":o.code==="AUTHENTICATION_FAILED"||N(t)?"Copilot authentication failed. Install/authenticate Copilot CLI, then retry.":t.includes("ERR_UNKNOWN_BUILTIN_MODULE")&&t.includes("node:sqlite")?"Copilot SDK requires a newer Node.js runtime (node:sqlite is unavailable). Please use Node.js 22+ and retry.":o.code==="MODEL_NOT_AVAILABLE"||I(t)?"Model is unavailable in Copilot SDK for this account/plan/client. Try another model.":o.code==="NO_CONTENT"?"Copilot SDK returned no content.":null}generateCommitMessage$(){return w(this.generateMessage("commit")).pipe(S(o=>E(o)),A(this.formatAsChoice),D(this.handleError$))}generateCodeReview$(){return w(this.generateMessage("review")).pipe(S(o=>E(o)),A(this.formatCodeReviewAsChoice),D(this.handleError$))}async generateMessage(o){const t=this.params.stagedDiff.diff,{generate:e,type:i}=this.params.config,s=this.buildPromptOptions(),n=o==="review"?$(s):U(s),g=o==="review"?t:`Here's the diff:
|
|
2
2
|
|
|
3
3
|
${t}`,a=await this.makeRequest(n,g,o,t);return o==="review"?this.parseCodeReview(a):this.parseMessage(a,i,e)}async loadSdkModule(){try{return await import("@github/copilot-sdk")}catch(o){const t=new Error("Copilot SDK package is missing. Install with: npm install @github/copilot-sdk");throw t.code="SDK_NOT_INSTALLED",t.originalError=o,t}}extractContent(o){if(!o||typeof o!="object")return"";const t=o,e=t.data,i=t.content,s=e?.content;if(typeof i=="string")return i.trim();if(typeof s=="string")return s.trim();const n=e?.message?.content;return typeof n=="string"?n.trim():""}async makeRequest(o,t,e,i){const{CopilotClient:s,approveAll:n}=await this.loadSdkModule(),g=Array.isArray(this.params.config.model)?this.params.config.model[0]:this.params.config.model||F,a=B(g),{logging:l}=this.params.config;let C;for(const m of a){const O="copilot-sdk://session",L={Authorization:"Copilot CLI session"},_={model:m,prompt:t};k(i,e,"Copilot SDK",m,O,L,l),v(i,e,"Copilot SDK",o,t,l),y(i,e,"Copilot SDK",_,l);const M=Date.now();let d;try{const c=H(process.env);d=new s(c);const p=await(await d.createSession({model:m,onPermissionRequest:n})).sendAndWait({prompt:`${o}
|
|
4
4
|
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import u from"chalk";import T from"openai";import{concatMap as k,from as S,map as y,catchError as D}from"rxjs";import{fromPromise as v}from"rxjs/internal/observable/innerFrom";import{A as U,l as C,a as w,b as M,c as P,d as A,e as b}from"./ai.service-8f81dd1f.mjs";import{g as I,b as _}from"./cli-005bffd8.mjs";import"fs";import"path";import"@pacote/xxhash";import"winston";import"cleye";import"module";import"crypto";import"os";import"node:buffer";import"node:path";import"node:child_process";import"node:process";import"child_process";import"node:url";import"node:os";import"assert";import"events";import"node:fs";import"buffer";import"stream";import"util";import"node:util";import"inquirer";import"fs/promises";import"readline";import"figlet";import"gradient-string";import"ora";import"inquirer-reactive-list-prompt";import"winston-daily-rotate-file";import"axios";import"url";import"node:fs/promises";import"chokidar";import"rxjs/operators";class L extends U{constructor(t){super(t),this.params=t,this.generateStreamingCommitMessage$=()=>{const{generate:s,type:r}=this.params.config;return this.createStreamingCommitMessages$(o=>{this.streamChunks(o).catch(i=>o.error(i))},r,s)},this.streamChunks=async s=>{const r=this.params.stagedDiff.diff,{logging:o}=this.params.config,i=I(this.buildPromptOptions()),m=this.buildUserPrompt(r,"commit"),p=`${this.params.config.url||"https://api.deepseek.com"}/chat/completions`,c={Authorization:`Bearer ${this.params.config.key}`,"Content-Type":"application/json"};C(r,"commit","DeepSeek",this.effectiveModel(),p,c,o),w(r,"commit","DeepSeek",i,m,o);const a=this.buildCompletionPayload([{role:"system",content:i},{role:"user",content:m}],!0);M(r,"commit","DeepSeek",a,o);const l=Date.now();let d="";try{const $=await this.deepSeek.chat.completions.create(a,{timeout:this.params.config.timeout});for await(const g of $){const E=g.choices?.[0]?.delta?.content||"",R=g.choices?.[0]?.delta?.reasoning_content||"",f=`${E}${R}`;f&&(d+=f,s.next(f))}const x=Date.now()-l;P(r,"commit","DeepSeek",{streamed:!0,totalLength:d.length},o),A(r,"commit","DeepSeek",x,d,o),s.complete()}catch(h){b(r,"commit","DeepSeek",h,o),s.error(h)}},this.colors={primary:"#53a3f9",secondary:"#fff"},this.serviceName=u.bgHex(this.colors.primary).hex(this.colors.secondary).bold(`[DeepSeek${this.formatModelSuffix()}]`),this.errorPrefix=u.red.bold(`[DeepSeek${this.formatModelSuffix()}]`);const e=this.params.config.url||"https://api.deepseek.com";this.deepSeek=new T({baseURL:e,apiKey:this.params.config.key})}effectiveModel(){const t=this.params.config.model;return Array.isArray(t)&&t.length>0?t[0]:String(t||"")}modelDefaultsToThinking(t){const e=t.toLowerCase();return e==="deepseek-chat"?!1:!!(e==="deepseek-reasoner"||e.startsWith("deepseek-v4-")||e.startsWith("deepseek-r1"))}isDeepSeekV4Model(t){return t.toLowerCase().startsWith("deepseek-v4-")}resolveThinkingMode(){const t=this.effectiveModel(),e=this.params.config.thinking,s=this.params.config.reasoningEffort;return{thinking:e??this.modelDefaultsToThinking(t),reasoningEffort:s??"high"}}buildCompletionPayload(t,e){const{thinking:s,reasoningEffort:r}=this.resolveThinkingMode(),o=this.effectiveModel(),i={messages:t,model:o,max_tokens:this.params.config.maxTokens};return e&&(i.stream=!0),s?(i.thinking={type:"enabled"},i.reasoning_effort=r):(i.top_p=this.params.config.topP,i.temperature=this.params.config.temperature,this.isDeepSeekV4Model(o)&&(i.thinking={type:"disabled"})),i}getServiceSpecificErrorMessage(t){const e=t.message||"";return e.includes("API key")||e.includes("api_key")?"Invalid API key. Check your DeepSeek API key in configuration":e.includes("rate_limit")||e.includes("Rate limit")?"Rate limit exceeded. Wait a moment and try again, or upgrade your DeepSeek plan":e.includes("Invalid model type")?"Invalid model type. Prefer deepseek-v4-flash or deepseek-v4-pro. Legacy aliases deepseek-chat and deepseek-reasoner map to v4-flash non-thinking and thinking modes (may be deprecated by DeepSeek).":e.includes("model")||e.includes("Model")?"Model not found or not accessible. Check if the DeepSeek model name is correct":e.includes("overloaded")||e.includes("capacity")?"DeepSeek service is overloaded. Try again in a few minutes":e.includes("403")||e.includes("Forbidden")?"Access denied. Your API key may not have permission for this DeepSeek model":e.includes("404")||e.includes("Not Found")?"Model or endpoint not found. Check your DeepSeek model configuration":e.includes("500")||e.includes("Internal Server Error")?"DeepSeek server error. Try again later":null}generateCommitMessage$(){return this.params.config.stream||!1?this.generateStreamingCommitMessage$():v(this.generateMessage("commit")).pipe(k(e=>S(e)),y(this.formatAsChoice),D(this.handleError$))}generateCodeReview$(){return v(this.generateMessage("review")).pipe(k(t=>S(t)),y(this.formatCodeReviewAsChoice),D(this.handleError$))}async generateMessage(t){const e=this.params.stagedDiff.diff,{logging:s,generate:r,type:o}=this.params.config,i=this.buildPromptOptions(),m=t==="review"?_(i):I(i),n=this.buildUserPrompt(e,t),c=`${this.params.config.url||"https://api.deepseek.com"}/chat/completions`,a={Authorization:`Bearer ${this.params.config.key}`,"Content-Type":"application/json"};C(e,t,"DeepSeek",this.effectiveModel(),c,a,s),w(e,t,"DeepSeek",m,n,s);const l=await this.createChatCompletions(m,n,t);return t==="review"?this.parseCodeReview(l):this.parseMessage(l,o,r)}async createChatCompletions(t,e,s){const r=this.params.stagedDiff.diff,{logging:o}=this.params.config,i=this.buildCompletionPayload([{role:"system",content:t},{role:"user",content:e}],!1);M(r,s,"DeepSeek",i,o);const m=Date.now();try{const n=await this.deepSeek.chat.completions.create(i,{timeout:this.params.config.timeout}),p=Date.now()-m,c=n.choices?.[0];if(!c?.message)throw new Error("DeepSeek API returned invalid response structure");const a=c.message.content||c.message.reasoning_content||"";if(!a)throw new Error("DeepSeek API returned empty response");return P(r,s,"DeepSeek",n,o),A(r,s,"DeepSeek",p,a,o),a}catch(n){throw b(r,s,"DeepSeek",n,o),n}}}export{L as DeepSeekService};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{HarmCategory as r,HarmBlockThreshold as s,GoogleGenerativeAI as B}from"@google/generative-ai";import T from"chalk";import{concatMap as G,from as M,map as I,catchError as S}from"rxjs";import{fromPromise as P}from"rxjs/internal/observable/innerFrom";import{A as H,l as x,a as R,b as v,c as L,d as N,e as w}from"./ai.service-
|
|
1
|
+
import{HarmCategory as r,HarmBlockThreshold as s,GoogleGenerativeAI as B}from"@google/generative-ai";import T from"chalk";import{concatMap as G,from as M,map as I,catchError as S}from"rxjs";import{fromPromise as P}from"rxjs/internal/observable/innerFrom";import{A as H,l as x,a as R,b as v,c as L,d as N,e as w}from"./ai.service-8f81dd1f.mjs";import{g as D,b as $}from"./cli-005bffd8.mjs";import"fs";import"path";import"@pacote/xxhash";import"winston";import"cleye";import"module";import"crypto";import"os";import"node:buffer";import"node:path";import"node:child_process";import"node:process";import"child_process";import"node:url";import"node:os";import"assert";import"events";import"node:fs";import"buffer";import"stream";import"util";import"node:util";import"inquirer";import"fs/promises";import"readline";import"figlet";import"gradient-string";import"ora";import"inquirer-reactive-list-prompt";import"winston-daily-rotate-file";import"axios";import"url";import"node:fs/promises";import"chokidar";import"rxjs/operators";class Y extends H{constructor(t){super(t),this.params=t,this.generateStreamingCommitMessage$=()=>{const{generate:e,type:o}=this.params.config;return this.createStreamingCommitMessages$(i=>{this.streamChunks(i).catch(c=>i.error(c))},o,e)},this.streamChunks=async e=>{const o=this.params.stagedDiff.diff,{logging:i}=this.params.config,c=this.params.config.maxTokens,p=D(this.buildPromptOptions()),d={maxOutputTokens:c,temperature:this.params.config.temperature,topP:this.params.config.topP},g=this.genAI.getGenerativeModel({model:this.params.config.model,systemInstruction:p,generationConfig:d,safetySettings:[{category:r.HARM_CATEGORY_HATE_SPEECH,threshold:s.BLOCK_LOW_AND_ABOVE},{category:r.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:s.BLOCK_LOW_AND_ABOVE},{category:r.HARM_CATEGORY_HARASSMENT,threshold:s.BLOCK_LOW_AND_ABOVE},{category:r.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:s.BLOCK_LOW_AND_ABOVE}]}),n=this.buildUserPrompt(o,"commit"),l=`${this.params.config.url||"https://generativelanguage.googleapis.com"}/v1beta/models/${this.params.config.model}:streamGenerateContent`,y={"Content-Type":"application/json","x-goog-api-key":this.params.config.key};x(o,"commit","Gemini",this.params.config.model,l,y,i),R(o,"commit","Gemini",p,n,i),v(o,"commit","Gemini",{systemInstruction:{parts:[{text:p}]},contents:[{parts:[{text:n}]}],generationConfig:d},i);const O=Date.now();let f="";try{const a=this.params.config.timeout>1e4?{request:{timeout:this.params.config.timeout}}:void 0,m=await g.generateContentStream(n,a);for await(const h of m.stream){const A=h.text();A&&(f+=A,e.next(A))}const u=Date.now()-O;L(o,"commit","Gemini",{streamed:!0,totalLength:f.length},i),N(o,"commit","Gemini",u,f,i),e.complete()}catch(a){w(o,"commit","Gemini",a,i),e.error(a)}},this.colors={primary:"#0077FF",secondary:"#fff"},this.serviceName=T.bgHex(this.colors.primary).hex(this.colors.secondary).bold(`[Gemini${this.formatModelSuffix()}]`),this.errorPrefix=T.red.bold(`[Gemini${this.formatModelSuffix()}]`),this.genAI=new B(this.params.config.key)}getServiceSpecificErrorMessage(t){const e=t.message||"";return e.includes("API key")||e.includes("api_key")?"Invalid API key. Check your Google AI Studio API key in configuration":e.includes("quota")||e.includes("QUOTA_EXCEEDED")?"API quota exceeded. Check your Google AI Studio usage limits":e.includes("model")||e.includes("Model")?"Model not found or not accessible. Check if the Gemini model name is correct":e.includes("SAFETY")||e.includes("safety")?"Content blocked by safety filters. Try rephrasing your request":e.includes("RECITATION")||e.includes("recitation")?"Content blocked due to recitation concerns. Try a different approach":e.includes("403")||e.includes("Forbidden")?"Access denied. Your API key may not have permission for this Gemini model":e.includes("404")||e.includes("Not Found")?"Model or endpoint not found. Check your Gemini model configuration":e.includes("500")||e.includes("Internal Server Error")?"Google AI service error. Try again later":e.includes("MAX_TOKENS")||e.includes("truncated")||e.includes("maxOutputTokens")?"Response truncated due to token limit. Gemini 2.5+ models use thinking tokens. Try increasing maxTokens (recommended: 8192+)":null}generateCommitMessage$(){return this.params.config.stream||!1?this.generateStreamingCommitMessage$():P(this.generateMessage("commit")).pipe(G(e=>M(e)),I(this.formatAsChoice),S(this.handleError$))}generateCodeReview$(){return P(this.generateMessage("review")).pipe(G(t=>M(t)),I(this.formatCodeReviewAsChoice),S(this.handleError$))}async generateMessage(t){const e=this.params.stagedDiff.diff,{logging:o,generate:i,type:c}=this.params.config,p=this.params.config.maxTokens,d=this.buildPromptOptions(),g=t==="review"?$(d):D(d),n={maxOutputTokens:p,temperature:this.params.config.temperature,topP:this.params.config.topP},_=this.genAI.getGenerativeModel({model:this.params.config.model,systemInstruction:g,generationConfig:n,safetySettings:[{category:r.HARM_CATEGORY_HATE_SPEECH,threshold:s.BLOCK_LOW_AND_ABOVE},{category:r.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:s.BLOCK_LOW_AND_ABOVE},{category:r.HARM_CATEGORY_HARASSMENT,threshold:s.BLOCK_LOW_AND_ABOVE},{category:r.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:s.BLOCK_LOW_AND_ABOVE}]}),l=this.buildUserPrompt(e,t),E=`${this.params.config.url||"https://generativelanguage.googleapis.com"}/v1beta/models/${this.params.config.model}:generateContent`,O={"Content-Type":"application/json","x-goog-api-key":this.params.config.key};x(e,t,"Gemini",this.params.config.model,E,O,o),R(e,t,"Gemini",g,l,o),v(e,t,"Gemini",{systemInstruction:{parts:[{text:g}]},contents:[{parts:[{text:l}]}],generationConfig:n},o);const a=Date.now();try{const m=this.params.config.timeout>1e4?{request:{timeout:this.params.config.timeout}}:void 0,u=await _.generateContent(l,m),h=u.response;if(h.candidates?.[0]?.finishReason==="MAX_TOKENS"){const k=h.usageMetadata;throw new Error(`Response truncated: maxOutputTokens exceeded. Thinking tokens: ${k?.thoughtsTokenCount??"N/A"}, Output tokens: ${k?.candidatesTokenCount??"N/A"}. Increase maxTokens config for Gemini 2.5+ thinking models.`)}const C=h.text(),b=Date.now()-a;return L(e,t,"Gemini",{response:C,candidates:u.response.candidates,usageMetadata:u.response.usageMetadata},o),N(e,t,"Gemini",b,C,o),t==="review"?this.parseCodeReview(C):this.parseMessage(C,c,i)}catch(m){throw w(e,t,"Gemini",m,o),m}}}export{Y as GeminiService};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import _ from"chalk";import{concatMap as A,from as D,map as N,catchError as O}from"rxjs";import{fromPromise as S}from"rxjs/internal/observable/innerFrom";import{A as T,l as R,a as x,b as C,e as E,c as L,d as $}from"./ai.service-
|
|
1
|
+
import _ from"chalk";import{concatMap as A,from as D,map as N,catchError as O}from"rxjs";import{fromPromise as S}from"rxjs/internal/observable/innerFrom";import{A as T,l as R,a as x,b as C,e as E,c as L,d as $}from"./ai.service-8f81dd1f.mjs";import{G as k,b as v,g as U,w as y,x as P,y as F,z as B}from"./cli-005bffd8.mjs";import{i as j}from"./openai-5c9e718a.mjs";import"fs";import"path";import"@pacote/xxhash";import"winston";import"cleye";import"module";import"crypto";import"os";import"node:buffer";import"node:path";import"node:child_process";import"node:process";import"child_process";import"node:url";import"node:os";import"assert";import"events";import"node:fs";import"buffer";import"stream";import"util";import"node:util";import"inquirer";import"fs/promises";import"readline";import"figlet";import"gradient-string";import"ora";import"inquirer-reactive-list-prompt";import"winston-daily-rotate-file";import"axios";import"url";import"node:fs/promises";import"chokidar";import"rxjs/operators";import"http";import"https";import"net";import"tls";import"tty";class V extends T{constructor(r){super(r),this.params=r,this.baseURL=k,this.colors={primary:"#24292e",secondary:"#FFF"},this.serviceName=_.bgHex(this.colors.primary).hex(this.colors.secondary).bold(`[GitHub Models${this.formatModelSuffix()}]`),this.errorPrefix=_.red.bold(`[GitHub Models${this.formatModelSuffix()}]`)}getServiceSpecificErrorMessage(r){switch(r.code){case"MISSING_TOKEN":return"GitHub token is required. Run: aicommit2 github-login";case"AUTHENTICATION_FAILED":return"Authentication failed. Your GitHub token may be expired or invalid. Run: aicommit2 github-login";case"ACCESS_DENIED":return'Access denied. Make sure your token has "models: read" permission in GitHub settings';case"INVALID_MODEL_ID":return'Invalid model ID. Use format "publisher/model" (example: openai/gpt-4o-mini)';case"MODEL_NOT_FOUND":return"Model not found in GitHub Models catalog. Check with: gh models list";case"NO_CONTENT":return"No content received from GitHub Models. The model may have failed to generate a response";default:return null}}generateCommitMessage$(){return S(this.generateMessage("commit")).pipe(A(r=>D(r)),N(this.formatAsChoice),O(this.handleError$))}generateCodeReview$(){return S(this.generateMessage("review")).pipe(A(r=>D(r)),N(this.formatCodeReviewAsChoice),O(this.handleError$))}async generateMessage(r){if(!this.params.config.key){const u=new Error("GitHub token is required for GitHub Models. Use: aicommit2 github-login");throw u.code="MISSING_TOKEN",u}const s=this.params.stagedDiff.diff,{generate:i,type:f}=this.params.config,n=this.buildPromptOptions(),M=r==="review"?v(n):U(n),p=await this.makeRequest(M,s,r);return r==="review"?this.parseCodeReview(p):this.parseMessage(p,f,i)}async makeRequest(r,s,i){const f=Array.isArray(this.params.config.model)?this.params.config.model[0]:this.params.config.model||y;let n;try{n=P(f)}catch(o){const e=new Error(o instanceof Error?o.message:String(o));throw e.code="INVALID_MODEL_ID",e}const M=[{role:"system",content:r},{role:"user",content:i==="review"?s:`Here's the diff:
|
|
2
2
|
|
|
3
3
|
${s}`}],p=j(n),u={messages:M,model:n,stream:!1,...p?{max_completion_tokens:this.params.config.maxTokens||1024,temperature:1}:{max_tokens:this.params.config.maxTokens||1024,top_p:this.params.config.topP||.95,temperature:this.params.config.temperature||.7}},b=`${this.baseURL}${F}`,I={"Content-Type":"application/json",Accept:"application/vnd.github+json","X-GitHub-Api-Version":B,Authorization:`Bearer ${this.params.config.key}`},{logging:m}=this.params.config;R(s,i,"GitHub Models",n,b,I,m),x(s,i,"GitHub Models",r,i==="review"?s:`Here's the diff:
|
|
4
4
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import G from"chalk";import b from"groq-sdk";import{concatMap as q,from as k,map as v,catchError as C}from"rxjs";import{fromPromise as P}from"rxjs/internal/observable/innerFrom";import{A as R,l as w,a as A,b as x,c as M,d as $,e as S}from"./ai.service-
|
|
1
|
+
import G from"chalk";import b from"groq-sdk";import{concatMap as q,from as k,map as v,catchError as C}from"rxjs";import{fromPromise as P}from"rxjs/internal/observable/innerFrom";import{A as R,l as w,a as A,b as x,c as M,d as $,e as S}from"./ai.service-8f81dd1f.mjs";import{g as I,b as D}from"./cli-005bffd8.mjs";import"fs";import"path";import"@pacote/xxhash";import"winston";import"cleye";import"module";import"crypto";import"os";import"node:buffer";import"node:path";import"node:child_process";import"node:process";import"child_process";import"node:url";import"node:os";import"assert";import"events";import"node:fs";import"buffer";import"stream";import"util";import"node:util";import"inquirer";import"fs/promises";import"readline";import"figlet";import"gradient-string";import"ora";import"inquirer-reactive-list-prompt";import"winston-daily-rotate-file";import"axios";import"url";import"node:fs/promises";import"chokidar";import"rxjs/operators";class E extends R{constructor(t){super(t),this.params=t,this.generateStreamingCommitMessage$=()=>{const{generate:o,type:e}=this.params.config;return this.createStreamingCommitMessages$(r=>{this.streamChunks(r).catch(m=>r.error(m))},e,o)},this.streamChunks=async o=>{const e=this.params.stagedDiff.diff,{logging:r,temperature:m}=this.params.config,d=this.params.config.maxTokens,p=I(this.buildPromptOptions()),c=`Here is the diff: ${e}`,l=`${this.params.config.url||"https://api.groq.com"}/openai/v1/chat/completions`,y={Authorization:`Bearer ${this.params.config.key}`,"Content-Type":"application/json"};w(e,"commit","Groq",this.params.config.model,l,y,r),A(e,"commit","Groq",p,c,r);const h={messages:[{role:"system",content:p},{role:"user",content:c}],model:this.params.config.model,max_tokens:d,top_p:this.params.config.topP,temperature:m,stream:!0};x(e,"commit","Groq",h,r);const f=Date.now();let a="";try{const n=await this.groq.chat.completions.create(h,{timeout:this.params.config.timeout});for await(const u of n){const s=u.choices?.[0]?.delta?.content||"";s&&(a+=s,o.next(s))}const i=Date.now()-f;M(e,"commit","Groq",{streamed:!0,totalLength:a.length},r),$(e,"commit","Groq",i,a,r),o.complete()}catch(n){S(e,"commit","Groq",n,r),o.error(n)}},this.colors={primary:"#f55036",secondary:"#fff"},this.serviceName=G.bgHex(this.colors.primary).hex(this.colors.secondary).bold(`[Groq${this.formatModelSuffix()}]`),this.errorPrefix=G.red.bold(`[Groq${this.formatModelSuffix()}]`),this.groq=new b({apiKey:this.params.config.key})}getServiceSpecificErrorMessage(t){const o=t.message||"";return o.includes("API key")||o.includes("api_key")?"Invalid API key. Check your Groq API key in configuration":o.includes("rate_limit")||o.includes("Rate limit")?"Rate limit exceeded. Wait a moment and try again, or upgrade your Groq plan":o.includes("model")||o.includes("Model")?"Model not found or not accessible. Check if the Groq model name is correct":o.includes("overloaded")||o.includes("capacity")?"Groq service is overloaded. Try again in a few minutes":o.includes("403")||o.includes("Forbidden")?"Access denied. Your API key may not have permission for this Groq model":o.includes("404")||o.includes("Not Found")?"Model or endpoint not found. Check your Groq model configuration":o.includes("500")||o.includes("Internal Server Error")?"Groq server error. Try again later":null}generateCommitMessage$(){return this.params.config.stream||!1?this.generateStreamingCommitMessage$():P(this.generateMessage("commit")).pipe(q(o=>k(o)),v(this.formatAsChoice),C(this.handleError$))}generateCodeReview$(){return P(this.generateMessage("review")).pipe(q(t=>k(t)),v(this.formatCodeReviewAsChoice),C(this.handleError$))}async generateMessage(t){const o=this.params.stagedDiff.diff,{logging:e,temperature:r,generate:m,type:d}=this.params.config,p=this.params.config.maxTokens,c=this.buildPromptOptions(),g=t==="review"?D(c):I(c),l=`Here is the diff: ${o}`,h=`${this.params.config.url||"https://api.groq.com"}/openai/v1/chat/completions`,f={Authorization:`Bearer ${this.params.config.key}`,"Content-Type":"application/json"};w(o,t,"Groq",this.params.config.model,h,f,e),A(o,t,"Groq",g,l,e);const a={messages:[{role:"system",content:g},{role:"user",content:l}],model:this.params.config.model,max_tokens:p,top_p:this.params.config.topP,temperature:r};x(o,t,"Groq",a,e);const n=Date.now();try{const i=await this.groq.chat.completions.create(a,{timeout:this.params.config.timeout}),u=Date.now()-n,s=i.choices[0].message.content||"";return M(o,t,"Groq",i,e),$(o,t,"Groq",u,s,e),t==="review"?this.parseCodeReview(s):this.parseMessage(s,d,m)}catch(i){throw S(o,t,"Groq",i,e),i}}}export{E as GroqService};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import y from"chalk";import{concatMap as C,from as b,map as k,catchError as D}from"rxjs";import{fromPromise as E}from"rxjs/internal/observable/innerFrom";import{A as I,l as M,a as A,c as P,d as $,e as H}from"./ai.service-
|
|
1
|
+
import y from"chalk";import{concatMap as C,from as b,map as k,catchError as D}from"rxjs";import{fromPromise as E}from"rxjs/internal/observable/innerFrom";import{A as I,l as M,a as A,c as P,d as $,e as H}from"./ai.service-8f81dd1f.mjs";import{b as R,g as S}from"./cli-005bffd8.mjs";import"fs";import"path";import"@pacote/xxhash";import"winston";import"cleye";import"module";import"crypto";import"os";import"node:buffer";import"node:path";import"node:child_process";import"node:process";import"child_process";import"node:url";import"node:os";import"assert";import"events";import"node:fs";import"buffer";import"stream";import"util";import"node:util";import"inquirer";import"fs/promises";import"readline";import"figlet";import"gradient-string";import"ora";import"inquirer-reactive-list-prompt";import"winston-daily-rotate-file";import"axios";import"url";import"node:fs/promises";import"chokidar";import"rxjs/operators";class U extends I{constructor(o){super(o),this.params=o,this.headers={},this.models=[],this.currentModelId=null,this.currentConversation=void 0,this.currentConversionID=void 0,this.cookie="",this.colors={primary:"#FED21F",secondary:"#000"},this.serviceName=y.bgHex(this.colors.primary).hex(this.colors.secondary).bold(`[HuggingFace${this.formatModelSuffix()}]`),this.errorPrefix=y.red.bold(`[HuggingFace${this.formatModelSuffix()}]`),this.cookie=this.params.config.cookie;const e=this.params.config.url||"https://huggingface.co";this.headers={accept:"*/*","accept-language":"en-US,en;q=0.9","sec-ch-ua":'"Chromium";v="116", "Not)A;Brand";v="24", "Google Chrome";v="116"',"sec-ch-ua-mobile":"?0","sec-ch-ua-platform":'"Windows"',"sec-fetch-dest":"empty","sec-fetch-mode":"cors","sec-fetch-site":"same-origin",origin:e,"Referrer-Policy":"strict-origin-when-cross-origin"}}getServiceSpecificErrorMessage(o){const e=o.message||"";return e.includes("cookie")||e.includes("Cookie")?"Invalid cookie. Check your Hugging Face session cookie in configuration":e.includes("model")||e.includes("Model")?"Model not found or not accessible. Check if the Hugging Face model name is correct":e.includes("conversation")||e.includes("conversion")?"Failed to create conversation. Try again or check your session":e.includes("401")||e.includes("Unauthorized")?"Authentication failed. Your Hugging Face session may have expired":e.includes("403")||e.includes("Forbidden")?"Access denied. You may not have permission to access this model":e.includes("404")||e.includes("Not Found")?"Model not found. Check your Hugging Face model configuration":e.includes("500")||e.includes("Internal Server Error")?"Hugging Face server error. Try again later":e.includes("overloaded")||e.includes("capacity")?"Hugging Face service is overloaded. Try again in a few minutes":null}generateCommitMessage$(){return E(this.generateMessage("commit")).pipe(C(o=>b(o)),k(this.formatAsChoice),D(this.handleError$))}generateCodeReview$(){return E(this.generateMessage("review")).pipe(C(o=>b(o)),k(this.formatCodeReviewAsChoice),D(this.handleError$))}async generateMessage(o){await this.initialize();const e=this.params.stagedDiff.diff,{logging:r,generate:t,type:l,temperature:m,maxTokens:i,topP:g,timeout:s}=this.params.config,p=this.buildPromptOptions(),a=o==="review"?R(p):S(p),w=`Here is the diff: ${e}`,f=`${this.params.config.url||"https://huggingface.co"}/chat/conversation`,n={...this.headers,cookie:this.cookie};M(e,o,"HuggingFace",this.params.config.model,f,n,r),A(e,o,"HuggingFace",a,w,r);const d=Date.now();try{const c=await this.getNewChat(a),u=await(await this.sendMessage(w,c.id)).completeResponsePromise();await this.deleteConversation(c.id);const F=Date.now()-d;return P(e,o,"HuggingFace",{response:u},r),$(e,o,"HuggingFace",F,u,r),o==="review"?this.parseCodeReview(u):this.parseMessage(u,l,t)}catch(c){throw H(e,o,"HuggingFace",c,r),c}}async initialize(){const o=await this.getRemoteLlms(),e=o.find(r=>r.name?.toLowerCase()===this.params.config.model.toLowerCase());if(e){this.currentModel=e,this.currentModelId=e.id;return}this.currentModel=o[0],this.currentModelId=o[0].id}async getRemoteLlms(){const o=this.params.config.url||"https://huggingface.co",e=await fetch(`${o}/chat/__data.json`,{headers:{...this.headers,cookie:this.cookie},body:null,method:"GET"});if(e.status!==200)throw new Error(`Failed to get remote LLMs with status code: ${e.status}`);const t=(await e.json()).nodes[0].data,l=t[t[0].models],m=[],i=g=>g===-1?null:t[g];for(const g of l){const s=t[g];if(t[s.unlisted])continue;const p={id:i(s.id),name:i(s.name),displayName:i(s.displayName),preprompt:i(s.preprompt),promptExamples:[],websiteUrl:i(s.websiteUrl),description:i(s.description),datasetName:i(s.datasetName),datasetUrl:i(s.datasetUrl),modelUrl:i(s.modelUrl),parameters:{}},a=i(s.promptExamples);if(a!==null){const f=a.map(n=>i(n));p.promptExamples=f.map(n=>({title:t[n.title],prompt:t[n.prompt]}))}const w=i(s.parameters),h={};for(const[f,n]of Object.entries(w)){if(n===-1){h[f]=null;continue}if(Array.isArray(t[n])){h[f]=t[n].map(d=>t[d]);continue}h[f]=t[n]}p.parameters=h,m.push(p)}return this.models=m,m}async getNewChat(o){const e={model:this.currentModelId,preprompt:o};let r=0;const t=this.params.config.url||"https://huggingface.co";for(;r<5;){const l=await fetch(`${t}/chat/conversation`,{headers:{...this.headers,"content-type":"application/json",cookie:this.cookie,Referer:`${t}/chat/`},body:JSON.stringify(e),method:"POST"}),{conversationId:m}=await l.json();if(m){this.currentConversionID=m;break}else r++}if(!this.currentConversionID)throw new Error("Failed to create new conversion");return await this.getConversationHistory(this.currentConversionID)}async getConversationHistory(o){if(!o)throw new Error("conversationId is required for getConversationHistory");const e=this.params.config.url||"https://huggingface.co",r=await fetch(`${e}/chat/conversation/${o}/__data.json`,{headers:{...this.headers,cookie:this.cookie,Referer:`${e}/chat/`},body:null,method:"GET"});if(r.status!=200)throw new Error("Unable get conversation details "+r);{const t=await r.json();return this.metadataParser(t,o)}}metadataParser(o,e){const r={id:"",model:"",systemPrompt:"",title:"",history:[]},t=o.nodes[1].data,l=t[t[0].model],m=t[t[0].preprompt],i=t[t[0].title],g=t[t[0].messages],s=[];for(const p of g){const a=t[p],w=new Date(t[a.createdAt][1]).getTime()/1e3,h=new Date(t[a.updatedAt][1]).getTime()/1e3;s.push({id:t[a.id],role:t[a.from],content:t[a.content],createdAt:w,updatedAt:h})}return r.id=e,r.model=l,r.systemPrompt=m,r.title=i,r.history=s,this.currentConversation=r,r}async sendMessage(o,e){if(o==="")throw new Error("the prompt can not be empty.");if(!e&&!this.currentConversionID?await this.getNewChat():e?(this.currentConversionID=e,await this.getConversationHistory(e)):this.currentConversionID&&await this.getConversationHistory(this.currentConversionID),!this.currentConversation)throw new Error("Failed to create new conversion");const r={inputs:o,id:this.currentConversation.history[this.currentConversation.history.length-1].id,is_retry:!1,is_continue:!1,web_search:!1,tools:[]},t=new FormData;t.append("data",JSON.stringify(r));const l=this.params.config.url||"https://huggingface.co",m=new AbortController,i=setTimeout(()=>m.abort(),this.params.config.timeout),g=await fetch(`${l}/chat/conversation/${this.currentConversionID}`,{headers:{...this.headers,cookie:this.cookie,Referer:`${l}/chat/conversation/${this.currentConversionID}`},body:t,method:"POST",signal:m.signal});clearTimeout(i);function s(n){try{const d=n.split(`
|
|
2
2
|
`),c=[];for(const v of d)v.trim()&&c.push(JSON.parse(v));return c}catch{return[{}]}}const p=new TextDecoder;let a="";const w=new TransformStream({async transform(n,d){const c=p.decode(n);try{const v=s(c);for(const u of v)u.type==="finalAnswer"?(a=u?.text||"",d.terminate()):u.type==="stream"&&d.enqueue(u?.token||"")}catch{throw new Error("Error during parsing response")}}}),h=g.body?.pipeThrough(w);async function f(){return new Promise(async(n,d)=>{try{if(!h)d("ModifiedStream undefined");else{const c=h.getReader();for(;;){const{done:v,value:u}=await c.read();if(v){n(a);break}}}}catch(c){d(c)}})}return{id:this.currentConversionID,stream:h,completeResponsePromise:f}}async deleteConversation(o){const e=this.params.config.url||"https://huggingface.co";return(await fetch(`${e}/chat/conversation/${o}`,{headers:{...this.headers,cookie:this.cookie,Referer:`${e}/chat/`},body:null,method:"DELETE"})).json()}}export{U as HuggingFaceService};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import h from"chalk";import{concatMap as f,from as u,map as g,catchError as A}from"rxjs";import{fromPromise as M}from"rxjs/internal/observable/innerFrom";import{A as v,l as b,a as w,b as C,c as P,e as I,d as k}from"./ai.service-
|
|
1
|
+
import h from"chalk";import{concatMap as f,from as u,map as g,catchError as A}from"rxjs";import{fromPromise as M}from"rxjs/internal/observable/innerFrom";import{A as v,l as b,a as w,b as C,c as P,e as I,d as k}from"./ai.service-8f81dd1f.mjs";import{b as $,g as x,H as y,t as R}from"./cli-005bffd8.mjs";import"fs";import"path";import"@pacote/xxhash";import"winston";import"cleye";import"module";import"crypto";import"os";import"node:buffer";import"node:path";import"node:child_process";import"node:process";import"child_process";import"node:url";import"node:os";import"assert";import"events";import"node:fs";import"buffer";import"stream";import"util";import"node:util";import"inquirer";import"fs/promises";import"readline";import"figlet";import"gradient-string";import"ora";import"inquirer-reactive-list-prompt";import"winston-daily-rotate-file";import"axios";import"url";import"node:fs/promises";import"chokidar";import"rxjs/operators";class E extends v{constructor(e){super(e),this.params=e,this.apiKey="",this.colors={primary:"#ff7000",secondary:"#fff"},this.serviceName=h.bgHex(this.colors.primary).hex(this.colors.secondary).bold(`[MistralAI${this.formatModelSuffix()}]`),this.errorPrefix=h.red.bold(`[MistralAI${this.formatModelSuffix()}]`),this.apiKey=this.params.config.key}getServiceSpecificErrorMessage(e){const t=e.message||"";return t.includes("API key")||t.includes("api_key")?"Invalid API key. Check your Mistral AI API key in configuration":t.includes("quota")||t.includes("usage")?"API quota exceeded. Check your Mistral AI usage limits":t.includes("model")||t.includes("Model")?"Model not found or not accessible. Check if the Mistral model name is correct":t.includes("403")||t.includes("Forbidden")?"Access denied. Your API key may not have permission for this Mistral model":t.includes("404")||t.includes("Not Found")?"Model or endpoint not found. Check your Mistral model configuration":t.includes("500")||t.includes("Internal Server Error")?"Mistral AI server error. Try again later":null}generateCommitMessage$(){return M(this.generateMessage("commit")).pipe(f(e=>u(e)),g(this.formatAsChoice),A(this.handleError$))}generateCodeReview$(){return M(this.generateMessage("review")).pipe(f(e=>u(e)),g(this.formatCodeReviewAsChoice),A(this.handleError$))}async generateMessage(e){const t=this.params.stagedDiff.diff,{logging:o,generate:i,type:s}=this.params.config,n=this.buildPromptOptions(),m=e==="review"?$(n):x(n);await this.checkAvailableModels();const a=`Here is the diff: ${t}`,c=`${this.params.config.url||"https://api.mistral.ai"}/v1/chat/completions`,r={Authorization:`Bearer ${this.apiKey}`,"content-type":"application/json"};b(t,e,"MistralAI",this.params.config.model,c,r,o),w(t,e,"MistralAI",m,a,o);const l=await this.createChatCompletions(m,a,e);return e==="review"?this.parseCodeReview(l):this.parseMessage(l,s,i)}async checkAvailableModels(){if((await this.getAvailableModels()).includes(this.params.config.model))return!0;throw new Error(`Invalid model type of Mistral AI: ${this.params.config.model}`)}async getAvailableModels(){const e=this.params.config.url||"https://api.mistral.ai";return(await new y({method:"GET",baseURL:`${e}/v1/models`,timeout:this.params.config.timeout}).setHeaders({Authorization:`Bearer ${this.apiKey}`,"content-type":"application/json"}).execute()).data.data.filter(o=>o.object==="model").map(o=>o.id)}async createChatCompletions(e,t,o){const i=this.params.stagedDiff.diff,{logging:s}=this.params.config,n={model:this.params.config.model,messages:[{role:"system",content:e},{role:"user",content:t}],temperature:this.params.config.temperature,top_p:this.params.config.topP,max_tokens:this.params.config.maxTokens,stream:!1,safe_prompt:!1,random_seed:R(10,1e3)};C(i,o,"MistralAI",n,s);const m=Date.now();try{const a=this.params.config.url||"https://api.mistral.ai",p=await new y({method:"POST",baseURL:`${a}/v1/chat/completions`,timeout:this.params.config.timeout}).setHeaders({Authorization:`Bearer ${this.apiKey}`,"content-type":"application/json"}).setBody(n).execute(),c=Date.now()-m,r=p.data;if(P(i,o,"MistralAI",r,s),!r.choices||r.choices.length===0||!r.choices[0].message?.content)throw I(i,o,"MistralAI",{message:"No Content on response",result:r},s),new Error("No Content on response. Please open a Bug report");const d=r.choices[0].message.content;return k(i,o,"MistralAI",c,d,s),d}catch(a){throw I(i,o,"MistralAI",a,s),a}}}export{E as MistralService};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import k from"chalk";import{Ollama as H}from"ollama";import{concatMap as w,from as A,map as C,catchError as v}from"rxjs";import{fromPromise as P}from"rxjs/internal/observable/innerFrom";import{fetch as L,Agent as z}from"undici";import{A as U,l as x,a as M,b as O,c as R,d as S,e as _}from"./ai.service-
|
|
1
|
+
import k from"chalk";import{Ollama as H}from"ollama";import{concatMap as w,from as A,map as C,catchError as v}from"rxjs";import{fromPromise as P}from"rxjs/internal/observable/innerFrom";import{fetch as L,Agent as z}from"undici";import{A as U,l as x,a as M,b as O,c as R,d as S,e as _}from"./ai.service-8f81dd1f.mjs";import{u as E,t as b,c as I,P as N,b as B,g as T,H as G}from"./cli-005bffd8.mjs";import"fs";import"path";import"@pacote/xxhash";import"winston";import"cleye";import"module";import"crypto";import"os";import"node:buffer";import"node:path";import"node:child_process";import"node:process";import"child_process";import"node:url";import"node:os";import"assert";import"events";import"node:fs";import"buffer";import"stream";import"util";import"node:util";import"inquirer";import"fs/promises";import"readline";import"figlet";import"gradient-string";import"ora";import"inquirer-reactive-list-prompt";import"winston-daily-rotate-file";import"axios";import"url";import"node:fs/promises";import"chokidar";import"rxjs/operators";class J extends U{constructor(s){super(s),this.params=s,this.host=E,this.model="",this.key="",this.auth="",this.generateStreamingCommitMessage$=()=>{const{generate:t,type:e}=this.params.config;return this.createStreamingCommitMessages$(o=>{this.streamChunks(o).catch(a=>o.error(a))},e,t)},this.streamChunks=async t=>{const e=this.params.stagedDiff.diff,{logging:o}=this.params.config,a=this.buildCommitPrompt();await this.checkIsAvailableOllama();const h=`Here is the diff: ${e}`,i=`Ollama_${this.model}`,l=`${this.host}/api/chat`,r=this.key?{Authorization:`${this.auth} ${this.key}`}:{};x(e,"commit",i,this.model,l,r,o),M(e,"commit",i,a,h,o);const{numCtx:m,temperature:n,topP:c,timeout:f,maxTokens:p}=this.params.config,g={model:this.model,messages:[{role:"system",content:a},{role:"user",content:h}],stream:!0,keep_alive:f,options:{num_ctx:m,temperature:n,top_p:c,seed:b(10,1e3),num_predict:p??-1}};O(e,"commit",i,g,o);const d=Date.now();let $="";try{const u=await this.ollama.chat(g);for await(const F of u){const y=F.message.content;y&&($+=y,t.next(y))}const D=Date.now()-d;R(e,"commit",i,{streamed:!0,totalLength:$.length},o),S(e,"commit",i,D,$,o),t.complete()}catch(u){_(e,"commit",i,u,o),t.error(u)}},this.setupFetch=(t,e={})=>L(t,{...e,dispatcher:new z({headersTimeout:this.params.config.timeout})}),this.colors={primary:"#FFF",secondary:"#000"},this.model=this.params.keyName,this.serviceName=k.bgHex(this.colors.primary).hex(this.colors.secondary).bold(`[${I(this.model)}]`),this.errorPrefix=k.red.bold(`[${I(this.model)}]`),this.host=this.params.config.host||E,this.auth=this.params.config.auth||"Bearer",this.key=this.params.config.key||"",this.ollama=new H({host:this.host,fetch:this.setupFetch,...this.key&&{headers:{Authorization:`${this.auth} ${this.key}`}}})}getServiceSpecificErrorMessage(s){const t=s.message||"";return t.includes("ECONNREFUSED")||t.includes("connection refused")?N.ollamaNotRunning():t.includes("model")&&(t.includes("not found")||t.includes("404"))?N.ollamaModelNotPulled(this.model):null}generateCommitMessage$(){return this.params.config.stream||!1?this.generateStreamingCommitMessage$():P(this.generateMessage("commit")).pipe(w(t=>A(t)),C(this.formatAsChoice),v(this.handleError$))}generateCodeReview$(){return P(this.generateMessage("review")).pipe(w(s=>A(s)),C(this.formatCodeReviewAsChoice),v(this.handleError$))}async generateMessage(s){const t=this.params.stagedDiff.diff,{logging:e,generate:o,type:a}=this.params.config,h=this.buildPromptOptions(),i=s==="review"?B(h):T(h);await this.checkIsAvailableOllama();const l=`Here is the diff: ${t}`,r=`Ollama_${this.model}`,m=`${this.host}/api/chat`,n=this.key?{Authorization:`${this.auth} ${this.key}`}:{};x(t,s,r,this.model,m,n,e),M(t,s,r,i,l,e);const c=await this.createChatCompletions(i,l,s);return s==="review"?this.parseCodeReview(c):this.parseMessage(c,a,o)}async checkIsAvailableOllama(){const s=new G({method:"GET",baseURL:`${this.host}`,timeout:this.params.config.timeout});return this.key&&s.setHeaders({Authorization:`${this.auth} ${this.key}`}),(await s.execute()).data}async createChatCompletions(s,t,e){const{numCtx:o,temperature:a,topP:h,timeout:i,maxTokens:l,logging:r}=this.params.config,m=this.params.stagedDiff.diff,n=`Ollama_${this.model}`,c={model:this.model,messages:[{role:"system",content:s},{role:"user",content:t}],stream:!1,keep_alive:i,options:{num_ctx:o,temperature:a,top_p:h,seed:b(10,1e3),num_predict:l??-1}};O(m,e,n,c,r);const f=Date.now();try{const p=await this.ollama.chat(c),g=Date.now()-f,d=p.message.content;return R(m,e,n,{response:d,fullResponse:p},r),S(m,e,n,g,d,r),d}catch(p){throw _(m,e,n,p,r),p}}}export{J as OllamaService};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import ae from"http";import ce from"https";import{j as w,k as ue,d as le,K as I}from"./cli-
|
|
1
|
+
import ae from"http";import ce from"https";import{j as w,k as ue,d as le,K as I}from"./cli-005bffd8.mjs";import fe from"net";import pe from"tls";import de from"url";import he from"assert";import V from"tty";import me from"util";import Ce from"os";import ge from"events";import{l as ye,a as be,b as we,c as Fe,d as ve,e as _e}from"./ai.service-8f81dd1f.mjs";var S={},L={exports:{}},E={exports:{}},D,W;function Oe(){if(W)return D;W=1;var t=1e3,n=t*60,i=n*60,e=i*24,f=e*7,s=e*365.25;D=function(u,r){r=r||{};var o=typeof u;if(o==="string"&&u.length>0)return p(u);if(o==="number"&&isFinite(u))return r.long?a(u):h(u);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(u))};function p(u){if(u=String(u),!(u.length>100)){var r=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(u);if(r){var o=parseFloat(r[1]),c=(r[2]||"ms").toLowerCase();switch(c){case"years":case"year":case"yrs":case"yr":case"y":return o*s;case"weeks":case"week":case"w":return o*f;case"days":case"day":case"d":return o*e;case"hours":case"hour":case"hrs":case"hr":case"h":return o*i;case"minutes":case"minute":case"mins":case"min":case"m":return o*n;case"seconds":case"second":case"secs":case"sec":case"s":return o*t;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return o;default:return}}}}function h(u){var r=Math.abs(u);return r>=e?Math.round(u/e)+"d":r>=i?Math.round(u/i)+"h":r>=n?Math.round(u/n)+"m":r>=t?Math.round(u/t)+"s":u+"ms"}function a(u){var r=Math.abs(u);return r>=e?l(u,r,e,"day"):r>=i?l(u,r,i,"hour"):r>=n?l(u,r,n,"minute"):r>=t?l(u,r,t,"second"):u+" ms"}function l(u,r,o,c){var d=r>=o*1.5;return Math.round(u/o)+" "+c+(d?"s":"")}return D}var j,Y;function K(){if(Y)return j;Y=1;function t(n){e.debug=e,e.default=e,e.coerce=l,e.disable=h,e.enable=s,e.enabled=a,e.humanize=Oe(),e.destroy=u,Object.keys(n).forEach(r=>{e[r]=n[r]}),e.names=[],e.skips=[],e.formatters={};function i(r){let o=0;for(let c=0;c<r.length;c++)o=(o<<5)-o+r.charCodeAt(c),o|=0;return e.colors[Math.abs(o)%e.colors.length]}e.selectColor=i;function e(r){let o,c=null,d,C;function m(...g){if(!m.enabled)return;const y=m,F=Number(new Date),T=F-(o||F);y.diff=T,y.prev=o,y.curr=F,o=F,g[0]=e.coerce(g[0]),typeof g[0]!="string"&&g.unshift("%O");let v=0;g[0]=g[0].replace(/%([a-zA-Z%])/g,(O,k)=>{if(O==="%%")return"%";v++;const b=e.formatters[k];if(typeof b=="function"){const ie=g[v];O=b.call(y,ie),g.splice(v,1),v--}return O}),e.formatArgs.call(y,g),(y.log||e.log).apply(y,g)}return m.namespace=r,m.useColors=e.useColors(),m.color=e.selectColor(r),m.extend=f,m.destroy=e.destroy,Object.defineProperty(m,"enabled",{enumerable:!0,configurable:!1,get:()=>c!==null?c:(d!==e.namespaces&&(d=e.namespaces,C=e.enabled(r)),C),set:g=>{c=g}}),typeof e.init=="function"&&e.init(m),m}function f(r,o){const c=e(this.namespace+(typeof o>"u"?":":o)+r);return c.log=this.log,c}function s(r){e.save(r),e.namespaces=r,e.names=[],e.skips=[];const o=(typeof r=="string"?r:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(const c of o)c[0]==="-"?e.skips.push(c.slice(1)):e.names.push(c)}function p(r,o){let c=0,d=0,C=-1,m=0;for(;c<r.length;)if(d<o.length&&(o[d]===r[c]||o[d]==="*"))o[d]==="*"?(C=d,m=c,d++):(c++,d++);else if(C!==-1)d=C+1,m++,c=m;else return!1;for(;d<o.length&&o[d]==="*";)d++;return d===o.length}function h(){const r=[...e.names,...e.skips.map(o=>"-"+o)].join(",");return e.enable(""),r}function a(r){for(const o of e.skips)if(p(r,o))return!1;for(const o of e.names)if(p(r,o))return!0;return!1}function l(r){return r instanceof Error?r.stack||r.message:r}function u(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return e.enable(e.load()),e}return j=t,j}E.exports;var Z;function Ee(){return Z||(Z=1,function(t,n){n.formatArgs=e,n.save=f,n.load=s,n.useColors=i,n.storage=p(),n.destroy=(()=>{let a=!1;return()=>{a||(a=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),n.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function i(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let a;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&(a=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(a[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function e(a){if(a[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+a[0]+(this.useColors?"%c ":" ")+"+"+t.exports.humanize(this.diff),!this.useColors)return;const l="color: "+this.color;a.splice(1,0,l,"color: inherit");let u=0,r=0;a[0].replace(/%[a-zA-Z%]/g,o=>{o!=="%%"&&(u++,o==="%c"&&(r=u))}),a.splice(r,0,l)}n.log=console.debug||console.log||(()=>{});function f(a){try{a?n.storage.setItem("debug",a):n.storage.removeItem("debug")}catch{}}function s(){let a;try{a=n.storage.getItem("debug")||n.storage.getItem("DEBUG")}catch{}return!a&&typeof process<"u"&&"env"in process&&(a=process.env.DEBUG),a}function p(){try{return localStorage}catch{}}t.exports=K()(n);const{formatters:h}=t.exports;h.j=function(a){try{return JSON.stringify(a)}catch(l){return"[UnexpectedJSONParseError]: "+l.message}}}(E,E.exports)),E.exports}var $={exports:{}},B,X;function $e(){return X||(X=1,B=(t,n=process.argv)=>{const i=t.startsWith("-")?"":t.length===1?"-":"--",e=n.indexOf(i+t),f=n.indexOf("--");return e!==-1&&(f===-1||e<f)}),B}var N,Q;function Ae(){if(Q)return N;Q=1;const t=Ce,n=V,i=$e(),{env:e}=process;let f;i("no-color")||i("no-colors")||i("color=false")||i("color=never")?f=0:(i("color")||i("colors")||i("color=true")||i("color=always"))&&(f=1),"FORCE_COLOR"in e&&(e.FORCE_COLOR==="true"?f=1:e.FORCE_COLOR==="false"?f=0:f=e.FORCE_COLOR.length===0?1:Math.min(parseInt(e.FORCE_COLOR,10),3));function s(a){return a===0?!1:{level:a,hasBasic:!0,has256:a>=2,has16m:a>=3}}function p(a,l){if(f===0)return 0;if(i("color=16m")||i("color=full")||i("color=truecolor"))return 3;if(i("color=256"))return 2;if(a&&!l&&f===void 0)return 0;const u=f||0;if(e.TERM==="dumb")return u;if(process.platform==="win32"){const r=t.release().split(".");return Number(r[0])>=10&&Number(r[2])>=10586?Number(r[2])>=14931?3:2:1}if("CI"in e)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE"].some(r=>r in e)||e.CI_NAME==="codeship"?1:u;if("TEAMCITY_VERSION"in e)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(e.TEAMCITY_VERSION)?1:0;if(e.COLORTERM==="truecolor")return 3;if("TERM_PROGRAM"in e){const r=parseInt((e.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(e.TERM_PROGRAM){case"iTerm.app":return r>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(e.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(e.TERM)||"COLORTERM"in e?1:u}function h(a){const l=p(a,a&&a.isTTY);return s(l)}return N={supportsColor:h,stdout:s(p(!0,n.isatty(1))),stderr:s(p(!0,n.isatty(2)))},N}$.exports;var ee;function xe(){return ee||(ee=1,function(t,n){const i=V,e=me;n.init=u,n.log=h,n.formatArgs=s,n.save=a,n.load=l,n.useColors=f,n.destroy=e.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."),n.colors=[6,2,3,4,5,1];try{const o=Ae();o&&(o.stderr||o).level>=2&&(n.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221])}catch{}n.inspectOpts=Object.keys(process.env).filter(o=>/^debug_/i.test(o)).reduce((o,c)=>{const d=c.substring(6).toLowerCase().replace(/_([a-z])/g,(m,g)=>g.toUpperCase());let C=process.env[c];return/^(yes|on|true|enabled)$/i.test(C)?C=!0:/^(no|off|false|disabled)$/i.test(C)?C=!1:C==="null"?C=null:C=Number(C),o[d]=C,o},{});function f(){return"colors"in n.inspectOpts?!!n.inspectOpts.colors:i.isatty(process.stderr.fd)}function s(o){const{namespace:c,useColors:d}=this;if(d){const C=this.color,m="\x1B[3"+(C<8?C:"8;5;"+C),g=` ${m};1m${c} \x1B[0m`;o[0]=g+o[0].split(`
|
|
2
2
|
`).join(`
|
|
3
3
|
`+g),o.push(m+"m+"+t.exports.humanize(this.diff)+"\x1B[0m")}else o[0]=p()+c+" "+o[0]}function p(){return n.inspectOpts.hideDate?"":new Date().toISOString()+" "}function h(...o){return process.stderr.write(e.formatWithOptions(n.inspectOpts,...o)+`
|
|
4
4
|
`)}function a(o){o?process.env.DEBUG=o:delete process.env.DEBUG}function l(){return process.env.DEBUG}function u(o){o.inspectOpts={};const c=Object.keys(n.inspectOpts);for(let d=0;d<c.length;d++)o.inspectOpts[c[d]]=n.inspectOpts[c[d]]}t.exports=K()(n);const{formatters:r}=t.exports;r.o=function(o){return this.inspectOpts.colors=this.useColors,e.inspect(o,this.inspectOpts).split(`
|
package/dist/{openai-compatible.service-3da32dc7.mjs → openai-compatible.service-7fead9c0.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import P from"chalk";import B from"openai";import{concatMap as v,from as $,map as w,catchError as x}from"rxjs";import{fromPromise as M}from"rxjs/internal/observable/innerFrom";import{A as F,l as S,a as _,b,c as N,d as O,e as R}from"./ai.service-
|
|
1
|
+
import P from"chalk";import B from"openai";import{concatMap as v,from as $,map as w,catchError as x}from"rxjs";import{fromPromise as M}from"rxjs/internal/observable/innerFrom";import{A as F,l as S,a as _,b,c as N,d as O,e as R}from"./ai.service-8f81dd1f.mjs";import{i as E}from"./openai-5c9e718a.mjs";import{g as D,a as H,c as T,b as K}from"./cli-005bffd8.mjs";import"fs";import"path";import"@pacote/xxhash";import"winston";import"http";import"https";import"net";import"tls";import"url";import"assert";import"tty";import"util";import"os";import"events";import"cleye";import"module";import"crypto";import"node:buffer";import"node:path";import"node:child_process";import"node:process";import"child_process";import"node:url";import"node:os";import"node:fs";import"buffer";import"stream";import"node:util";import"inquirer";import"fs/promises";import"readline";import"figlet";import"gradient-string";import"ora";import"inquirer-reactive-list-prompt";import"winston-daily-rotate-file";import"axios";import"node:fs/promises";import"chokidar";import"rxjs/operators";class U extends F{constructor(t){super(t),this.params=t,this.generateStreamingCommitMessage$=()=>{const{generate:o,type:r}=this.params.config;return this.createStreamingCommitMessages$(i=>{this.streamChunks(i).catch(m=>i.error(m))},r,o)},this.streamChunks=async o=>{const r=this.params.stagedDiff.diff,{logging:i,temperature:m,timeout:u}=this.params.config,c=this.params.config.maxTokens,p=D(this.buildPromptOptions()),l=`Here is the diff: ${r}`,s=this.params.keyName||"OpenAI-Compatible",n=`${this.params.config.url}${this.params.config.path}`,k={Authorization:`Bearer ${this.params.config.key}`,"Content-Type":"application/json"};S(r,"commit",s,this.params.config.model,n,k,i),_(r,"commit",s,p,l,i);const y=E(this.params.config.model),g={messages:[{role:"system",content:p},{role:"user",content:l}],model:this.params.config.model,stream:!0,...y?{max_completion_tokens:c,temperature:1}:{max_tokens:c,top_p:this.params.config.topP,temperature:m}};b(r,"commit",s,g,i);const f=Date.now();let h="";try{const d=await this.openAI.chat.completions.create(g,{timeout:u});for await(const I of d){const L=I.choices?.[0]?.delta?.content||"",z=I.choices?.[0]?.delta?.reasoning_content||"",C=`${L}${z}`;C&&(h+=C,o.next(C))}const A=Date.now()-f;N(r,"commit",s,{streamed:!0,totalLength:h.length},i),O(r,"commit",s,A,h,i),o.complete()}catch(a){R(r,"commit",s,a,i),o.error(a)}};const e=this.params.keyName||"OPENAI_COMPATIBLE";this.colors=H(e),this.serviceName=P.bgHex(this.colors.primary).hex(this.colors.secondary).bold(`[${T(e)}]`),this.errorPrefix=P.red.bold(`[${T(e)}]`),this.openAI=new B({apiKey:this.params.config.key,baseURL:`${this.params.config.url}${this.params.config.path}`})}getServiceSpecificErrorMessage(t){const e=t.message||"";return e.includes("API key")||e.includes("api_key")?"Invalid API key. Check your OpenAI-compatible API key in configuration":e.includes("rate_limit")||e.includes("Rate limit")?"Rate limit exceeded. Wait a moment and try again, or check your service limits":e.includes("model")||e.includes("Model")?"Model not found or not accessible. Check if the model name is correct":e.includes("network")||e.includes("connection")?"Network error. Check your internet connection and API endpoint":e.includes("quota")||e.includes("usage")?"API quota exceeded. Check your usage limits":e.includes("403")||e.includes("Forbidden")?"Access denied. Your API key may not have permission for this model":e.includes("404")||e.includes("Not Found")?"Model or endpoint not found. Check your API configuration":e.includes("500")||e.includes("Internal Server Error")?"Server error. Try again later":e.includes("overloaded")||e.includes("capacity")?"Service is overloaded. Try again in a few minutes":null}generateCommitMessage$(){return this.params.config.stream||!1?this.generateStreamingCommitMessage$():M(this.generateMessage("commit")).pipe(v(e=>$(e)),w(this.formatAsChoice),x(this.handleError$))}generateCodeReview$(){return M(this.generateMessage("review")).pipe(v(t=>$(t)),w(this.formatCodeReviewAsChoice),x(this.handleError$))}async generateMessage(t){const e=this.params.stagedDiff.diff,{logging:o,temperature:r,generate:i,type:m,timeout:u}=this.params.config,c=this.params.config.maxTokens,p=this.buildPromptOptions(),l=t==="review"?K(p):D(p),s=`Here is the diff: ${e}`,n=this.params.keyName||"OpenAI-Compatible",k=`${this.params.config.url}${this.params.config.path}`,y={Authorization:`Bearer ${this.params.config.key}`,"Content-Type":"application/json"};S(e,t,n,this.params.config.model,k,y,o),_(e,t,n,l,s,o);const g=E(this.params.config.model),f={messages:[{role:"system",content:l},{role:"user",content:s}],model:this.params.config.model,stream:!1,...g?{max_completion_tokens:c,temperature:1}:{max_tokens:c,top_p:this.params.config.topP,temperature:r}};b(e,t,n,f,o);const h=Date.now();try{const a=await this.openAI.chat.completions.create(f,{timeout:u}),d=a.choices?.[0]?.message.content||"",A=Date.now()-h;return N(e,t,n,a,o),O(e,t,n,A,d,o),t==="review"?this.parseCodeReview(d):this.parseMessage(d,m,i)}catch(a){throw R(e,t,n,a,o),a}}}export{U as OpenAICompatibleService};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import C from"chalk";import b from"openai";import{concatMap as P,from as y,map as A,catchError as I}from"rxjs";import{fromPromise as k}from"rxjs/internal/observable/innerFrom";import{A as G,l as O,a as R,b as D,c as E,d as _,e as F}from"./ai.service-
|
|
1
|
+
import C from"chalk";import b from"openai";import{concatMap as P,from as y,map as A,catchError as I}from"rxjs";import{fromPromise as k}from"rxjs/internal/observable/innerFrom";import{A as G,l as O,a as R,b as D,c as E,d as _,e as F}from"./ai.service-8f81dd1f.mjs";import{i as N,g as H}from"./openai-5c9e718a.mjs";import{g as M,b as L,m as $}from"./cli-005bffd8.mjs";import"fs";import"path";import"@pacote/xxhash";import"winston";import"http";import"https";import"net";import"tls";import"url";import"assert";import"tty";import"util";import"os";import"events";import"cleye";import"module";import"crypto";import"node:buffer";import"node:path";import"node:child_process";import"node:process";import"child_process";import"node:url";import"node:os";import"node:fs";import"buffer";import"stream";import"node:util";import"inquirer";import"fs/promises";import"readline";import"figlet";import"gradient-string";import"ora";import"inquirer-reactive-list-prompt";import"winston-daily-rotate-file";import"axios";import"node:fs/promises";import"chokidar";import"rxjs/operators";class U extends G{constructor(t){super(t),this.params=t,this.generateStreamingCommitMessage$=()=>{const{generate:i,type:e}=this.params.config;return this.createStreamingCommitMessages$(s=>{this.streamChunks(s).catch(r=>s.error(r))},e,i)},this.streamChunks=async i=>{const e=this.params.stagedDiff.diff,{temperature:s,logging:r,maxTokens:n,timeout:g}=this.params.config,a=M(this.buildPromptOptions()),p=`Here is the diff: ${e}`,c=`${this.params.config.url}${this.params.config.path}`,m={Authorization:`Bearer ${this.params.config.key}`,"Content-Type":"application/json"};O(e,"commit","ChatGPT",this.params.config.model,c,m,r),R(e,"commit","ChatGPT",a,p,r);const x=N(this.params.config.model),u={messages:[{role:"system",content:a},{role:"user",content:p}],model:this.params.config.model,stream:!0,...x?{max_completion_tokens:n,temperature:1}:{max_tokens:n,top_p:this.params.config.topP,temperature:s}};D(e,"commit","ChatGPT",u,r);const v=Date.now();let f="";try{const S=await this.openAI.chat.completions.create(u,{timeout:g});for await(const T of S){const d=T.choices?.[0]?.delta?.content||"";d&&(f+=d,i.next(d))}const w=Date.now()-v;E(e,"commit","ChatGPT",{streamed:!0,totalLength:f.length},r),_(e,"commit","ChatGPT",w,f,r),i.complete()}catch(l){F(e,"commit","ChatGPT",l,r),i.error(l)}},this.colors={primary:"#74AA9C",secondary:"#FFF"},this.serviceName=C.bgHex(this.colors.primary).hex(this.colors.secondary).bold(`[ChatGPT${this.formatModelSuffix()}]`),this.errorPrefix=C.red.bold(`[ChatGPT${this.formatModelSuffix()}]`);const o=this.params.config.url||"https://api.openai.com",h=(this.params.config.path||"/v1/chat/completions").replace(/\/chat\/completions\/?$/,"");this.openAI=new b({apiKey:this.params.config.key,baseURL:`${o}${h}`})}getServiceSpecificErrorMessage(t){const o=t.message||"";return o.includes("API key")?"Invalid API key. Check your OpenAI API key in configuration":o.includes("quota")?"API quota exceeded. Check your OpenAI usage limits":o.includes("500")?"OpenAI server error. Try again later":null}generateCommitMessage$(){return this.params.config.stream||!1?this.generateStreamingCommitMessage$():k(this.generateMessage("commit")).pipe(P(o=>y(o)),A(this.formatAsChoice),I(this.handleError$))}generateCodeReview$(){return k(this.generateMessage("review")).pipe(P(t=>y(t)),A(this.formatCodeReviewAsChoice),I(this.handleError$))}async generateMessage(t){const o=this.params.stagedDiff.diff,{temperature:h,logging:i,generate:e,type:s,proxy:r,maxTokens:n,timeout:g}=this.params.config,a=this.buildPromptOptions(),p=t==="review"?L(a):M(a),c=await H("ChatGPT",this.params.config.url,this.params.config.path,this.params.config.key,this.params.config.model,o,g,n,h,this.params.config.topP,p,i,t,r,{recentCommits:this.params.recentCommits,branchName:this.params.branchName});return t==="review"?$(c.map(m=>this.parseCodeReview(m))):$(c.map(m=>this.parseMessage(m,s,e)))}}export{U as OpenAIService};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import C from"chalk";import _ from"openai";import{concatMap as M,from as w,map as P,catchError as $}from"rxjs";import{fromPromise as v}from"rxjs/internal/observable/innerFrom";import{A as j,l as x,a as A,b as k,c as b,d as S,e as I}from"./ai.service-
|
|
1
|
+
import C from"chalk";import _ from"openai";import{concatMap as M,from as w,map as P,catchError as $}from"rxjs";import{fromPromise as v}from"rxjs/internal/observable/innerFrom";import{A as j,l as x,a as A,b as k,c as b,d as S,e as I}from"./ai.service-8f81dd1f.mjs";import{i as K}from"./openai-5c9e718a.mjs";import{g as H,H as U,b as q}from"./cli-005bffd8.mjs";import"fs";import"path";import"@pacote/xxhash";import"winston";import"http";import"https";import"net";import"tls";import"url";import"assert";import"tty";import"util";import"os";import"events";import"cleye";import"module";import"crypto";import"node:buffer";import"node:path";import"node:child_process";import"node:process";import"child_process";import"node:url";import"node:os";import"node:fs";import"buffer";import"stream";import"node:util";import"inquirer";import"fs/promises";import"readline";import"figlet";import"gradient-string";import"ora";import"inquirer-reactive-list-prompt";import"winston-daily-rotate-file";import"axios";import"node:fs/promises";import"chokidar";import"rxjs/operators";const O=class l extends j{constructor(r){super(r),this.params=r,this.getOpenRouterBaseUrl=()=>(this.params.config.url||"https://openrouter.ai").replace(/\/$/,""),this.getOpenRouterCatalogUrl=()=>`${this.getOpenRouterBaseUrl()}/api/v1`,this.getOpenRouterHeaders=()=>({"HTTP-Referer":"https://github.com/tak-bro/aicommit2","X-OpenRouter-Title":"aicommit2","X-OpenRouter-Categories":"cli-agent"}),this.getOpenRouterAuthHeaders=()=>({Authorization:`Bearer ${this.params.config.key}`,"Content-Type":"application/json",...this.getOpenRouterHeaders()}),this.hasRequestObject=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&Object.keys(t).length>0,this.getRequestedModel=()=>Array.isArray(this.params.config.model)?this.params.config.model[0]||"":typeof this.params.config.model=="string"?this.params.config.model:"",this.getCatalogCacheKey=()=>`${this.getOpenRouterCatalogUrl()}|${this.params.config.key||""}`,this.getModelCacheKey=()=>`${this.getCatalogCacheKey()}|${this.getRequestedModel()}`,this.matchOpenRouterModel=(t,o)=>{const s=t.trim();return o.find(i=>[i.id,i.canonical_slug,i.name].filter(c=>!!c).some(c=>c===s))},this.getRequestPayloadExtras=async()=>{const t=this.params.config,o={},s=this.hasRequestObject(t.responseFormat)?t.responseFormat:{type:"json_object"};s&&await this.isResponseFormatSupported()&&(o.response_format=s),this.hasRequestObject(t.provider)&&(o.provider=t.provider);const i=await this.getReasoningPayload();return i&&(o.reasoning=i),o},this.extractOpenRouterText=t=>{if(!t||typeof t!="object")return"";const o=t;return o.content||o.reasoning_content||o.reasoning||""},this.buildChatCompletionPayload=async(t,o,s)=>{const i=this.params.config.maxTokens,m=this.params.config.temperature,c=K(this.params.config.model),n=this.getRequestedModel();return{messages:[{role:"system",content:t},{role:"user",content:o}],model:n,stream:s,...await this.getRequestPayloadExtras()||{},...c?{max_completion_tokens:i,temperature:1}:{max_tokens:i,top_p:this.params.config.topP,temperature:m}}},this.generateStreamingCommitMessage$=()=>{const{generate:t,type:o}=this.params.config;return this.createStreamingCommitMessages$(s=>{this.streamChunks(s).catch(i=>s.error(i))},o,t)},this.streamChunks=async t=>{const o=this.params.stagedDiff.diff,{logging:s,timeout:i}=this.params.config,m=H(this.buildPromptOptions()),c=`Here is the diff: ${o}`,n="OpenRouter",d=`${this.params.config.url||"https://openrouter.ai"}${this.params.config.path||"/api/v1/chat/completions"}`,g={Authorization:`Bearer ${this.params.config.key}`,"Content-Type":"application/json",...this.getOpenRouterHeaders()};x(o,"commit",n,this.params.config.model,d,g,s),A(o,"commit",n,m,c,s);const u=await this.buildChatCompletionPayload(m,c,!0);k(o,"commit",n,u,s);const f=Date.now();let p="";try{const R=await this.openAI.chat.completions.create(u,{timeout:i});for await(const T of R){const y=this.extractOpenRouterText(T.choices?.[0]?.delta);y&&(p+=y,t.next(y))}const E=Date.now()-f;b(o,"commit",n,{streamed:!0,totalLength:p.length},s),S(o,"commit",n,E,p,s),t.complete()}catch(h){I(o,"commit",n,h,s),t.error(h)}},this.colors={primary:"#f97316",secondary:"#fff"},this.serviceName=C.bgHex(this.colors.primary).hex(this.colors.secondary).bold(`[OpenRouter${this.formatModelSuffix()}]`),this.errorPrefix=C.red.bold(`[OpenRouter${this.formatModelSuffix()}]`);const e=this.params.config.url||"https://openrouter.ai",a=(this.params.config.path||"/api/v1/chat/completions").replace(/\/chat\/completions\/?$/,"");this.openAI=new _({apiKey:this.params.config.key,baseURL:`${e}${a}`,defaultHeaders:{...this.getOpenRouterHeaders()}})}async fetchOpenRouterCatalog(){const r=this.getCatalogCacheKey(),e=l.catalogCache.get(r);if(e)return e;const a=["/models/user","/models"];let t;for(const o of a)try{const i=(await new U({method:"GET",baseURL:`${this.getOpenRouterCatalogUrl()}${o}`,timeout:this.params.config.timeout}).setHeaders(this.getOpenRouterAuthHeaders()).execute()).data?.data??[];return l.catalogCache.set(r,i),i}catch(s){if(t=s,!(s instanceof Error?s.message:String(s)).includes("404"))throw s}throw t instanceof Error?t:new Error(String(t))}async getOpenRouterModel(){const r=this.getRequestedModel();if(!r||r==="openrouter/auto")return null;const e=this.getModelCacheKey(),a=l.modelCache.get(e);if(a!==void 0)return a;try{const t=await this.fetchOpenRouterCatalog(),o=this.matchOpenRouterModel(r,t)||null;return l.modelCache.set(e,o),o}catch{return null}}async supportsOpenRouterParameters(r){const e=await this.getOpenRouterModel();return e?r.some(a=>e.supported_parameters?.includes(a)??!1):!1}async isResponseFormatSupported(){return this.supportsOpenRouterParameters(["response_format"])}async isReasoningSupported(){return this.supportsOpenRouterParameters(["reasoning","include_reasoning"])}async getReasoningPayload(){if(!await this.isReasoningSupported())return;const r=this.params.config,e=this.hasRequestObject(r.reasoning)?{...r.reasoning}:void 0,a=e?{...e}:{};return"exclude"in a||(a.exclude=!0),a}getServiceSpecificErrorMessage(r){const e=r.message||"";return e.includes("API key")||e.includes("api_key")?"Invalid API key. Check your OpenRouter API key in configuration":e.includes("402")||e.includes("Payment Required")?"OpenRouter credits are exhausted or billing is required. Check your account balance.":e.includes("rate_limit")||e.includes("Rate limit")?"Rate limit exceeded. Wait a moment and try again, or check your OpenRouter limits":e.includes("model")||e.includes("Model")?"Model not found or not accessible. Check if the OpenRouter model name is correct":e.includes("403")||e.includes("Forbidden")?"Access denied. Your API key may not have permission for this OpenRouter model":e.includes("404")||e.includes("Not Found")?"Model or endpoint not found. Check your OpenRouter configuration":e.includes("500")||e.includes("Internal Server Error")?"OpenRouter server error. Try again later":e.includes("overloaded")||e.includes("capacity")?"OpenRouter is overloaded. Try again in a few minutes":null}generateCommitMessage$(){return this.params.config.stream||!1?this.generateStreamingCommitMessage$():v(this.generateMessage("commit")).pipe(M(e=>w(e)),P(this.formatAsChoice),$(this.handleError$))}generateCodeReview$(){return v(this.generateMessage("review")).pipe(M(r=>w(r)),P(this.formatCodeReviewAsChoice),$(this.handleError$))}async generateMessage(r){const e=this.params.stagedDiff.diff,{logging:a,generate:t,type:o,timeout:s}=this.params.config,i=this.buildPromptOptions(),m=r==="review"?q(i):H(i),c=`Here is the diff: ${e}`,n="OpenRouter",d=`${this.params.config.url||"https://openrouter.ai"}${this.params.config.path||"/api/v1/chat/completions"}`,g={Authorization:`Bearer ${this.params.config.key}`,"Content-Type":"application/json",...this.getOpenRouterHeaders()};x(e,r,n,this.params.config.model,d,g,a),A(e,r,n,m,c,a);const u=await this.buildChatCompletionPayload(m,c,!1);k(e,r,n,u,a);const f=Date.now();try{const p=await this.openAI.chat.completions.create(u,{timeout:s}),h=this.extractOpenRouterText(p.choices?.[0]?.message),R=Date.now()-f;return b(e,r,n,p,a),S(e,r,n,R,h,a),r==="review"?this.parseCodeReview(h):this.parseMessage(h,o,t)}catch(p){throw I(e,r,n,p,a),p}}};O.catalogCache=new Map,O.modelCache=new Map;let F=O;export{F as OpenRouterService};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import d from"chalk";import{concatMap as f,from as g,map as u,catchError as y}from"rxjs";import{fromPromise as P}from"rxjs/internal/observable/innerFrom";import{A as v,l as w,a as C,b as A,c as k,e as x,d as b}from"./ai.service-
|
|
1
|
+
import d from"chalk";import{concatMap as f,from as g,map as u,catchError as y}from"rxjs";import{fromPromise as P}from"rxjs/internal/observable/innerFrom";import{A as v,l as w,a as C,b as A,c as k,e as x,d as b}from"./ai.service-8f81dd1f.mjs";import{b as I,g as M,H as R}from"./cli-005bffd8.mjs";import"fs";import"path";import"@pacote/xxhash";import"winston";import"cleye";import"module";import"crypto";import"os";import"node:buffer";import"node:path";import"node:child_process";import"node:process";import"child_process";import"node:url";import"node:os";import"assert";import"events";import"node:fs";import"buffer";import"stream";import"util";import"node:util";import"inquirer";import"fs/promises";import"readline";import"figlet";import"gradient-string";import"ora";import"inquirer-reactive-list-prompt";import"winston-daily-rotate-file";import"axios";import"url";import"node:fs/promises";import"chokidar";import"rxjs/operators";class S extends v{constructor(t){super(t),this.params=t,this.apiKey="",this.colors={primary:"#20808D",secondary:"#FFF"},this.serviceName=d.bgHex(this.colors.primary).hex(this.colors.secondary).bold(`[Perplexity${this.formatModelSuffix()}]`),this.errorPrefix=d.red.bold(`[Perplexity${this.formatModelSuffix()}]`),this.apiKey=this.params.config.key}getServiceSpecificErrorMessage(t){const e=t.message||"";return e.includes("API key")||e.includes("api_key")?"Invalid API key. Check your Perplexity API key in configuration":e.includes("rate_limit")||e.includes("Rate limit")?"Rate limit exceeded. Wait a moment and try again, or upgrade your Perplexity plan":e.includes("model")||e.includes("Model")?"Model not found or not accessible. Check if the Perplexity model name is correct":e.includes("overloaded")||e.includes("capacity")?"Perplexity service is overloaded. Try again in a few minutes":e.includes("403")||e.includes("Forbidden")?"Access denied. Your API key may not have permission for this Perplexity model":e.includes("404")||e.includes("Not Found")?"Model or endpoint not found. Check your Perplexity model configuration":e.includes("500")||e.includes("Internal Server Error")?"Perplexity server error. Try again later":null}generateCommitMessage$(){return P(this.generateMessage("commit")).pipe(f(t=>g(t)),u(this.formatAsChoice),y(this.handleError$))}generateCodeReview$(){return P(this.generateMessage("review")).pipe(f(t=>g(t)),u(this.formatCodeReviewAsChoice),y(this.handleError$))}extractJSONFromError(t){const e=/[{[]{1}([,:{}[\]0-9.\-+Eaeflnr-u \n\r\t]|".*?")+[}\]]{1}/gis,r=t.match(e);if(r){const o={};for(const i of r)try{Object.assign(o,JSON.parse(i))}catch{}return Object.keys(o).length>0?o:{error:{message:"Unknown error"}}}return{error:{message:"Unknown error"}}}async generateMessage(t){const e=this.params.stagedDiff.diff,{logging:r,generate:o,type:i}=this.params.config,n=this.buildPromptOptions(),p=t==="review"?I(n):M(n),a=`Here is the diff: ${e}`,c=`${this.params.config.url||"https://api.perplexity.ai"}/chat/completions`,s={Authorization:`Bearer ${this.apiKey}`,"content-type":"application/json"};w(e,t,"Perplexity",this.params.config.model,c,s,r),C(e,t,"Perplexity",p,a,r);const m=await this.createChatCompletions(p,a,t);return t==="review"?this.parseCodeReview(m):this.parseMessage(m,i,o)}async createChatCompletions(t,e,r){const o=this.params.stagedDiff.diff,{logging:i}=this.params.config,n={model:this.params.config.model,messages:[{role:"system",content:t},{role:"user",content:e}],temperature:this.params.config.temperature,top_p:this.params.config.topP,max_tokens:this.params.config.maxTokens,stream:!1};A(o,r,"Perplexity",n,i);const p=Date.now();try{const a=this.params.config.url||"https://api.perplexity.ai",l=await new R({method:"POST",baseURL:`${a}/chat/completions`,timeout:this.params.config.timeout}).setHeaders({Authorization:`Bearer ${this.apiKey}`,"content-type":"application/json"}).setBody(n).execute(),c=Date.now()-p,s=l.data;if(k(o,r,"Perplexity",s,i),!s.choices||s.choices.length===0||!s.choices[0].message?.content)throw x(o,r,"Perplexity",{message:"No Content on response",result:s},i),new Error("No Content on response. Please open a Bug report");const h=s.choices[0].message.content;return b(o,r,"Perplexity",c,h,i),h}catch(a){throw x(o,r,"Perplexity",a,i),a}}}export{S as PerplexityService};
|
package/package.json
CHANGED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import u from"chalk";import U from"openai";import{concatMap as k,from as S,map as y,catchError as D}from"rxjs";import{fromPromise as v}from"rxjs/internal/observable/innerFrom";import{A as _,l as w,a as C,b as A,c as P,d as M,e as I}from"./ai.service-8e59106d.mjs";import{g as b,b as O}from"./cli-6be3c9c1.mjs";import"fs";import"path";import"@pacote/xxhash";import"winston";import"cleye";import"module";import"crypto";import"os";import"node:buffer";import"node:path";import"node:child_process";import"node:process";import"child_process";import"node:url";import"node:os";import"assert";import"events";import"node:fs";import"buffer";import"stream";import"util";import"node:util";import"inquirer";import"fs/promises";import"readline";import"figlet";import"gradient-string";import"ora";import"inquirer-reactive-list-prompt";import"winston-daily-rotate-file";import"axios";import"url";import"node:fs/promises";import"chokidar";import"rxjs/operators";class z extends _{constructor(t){super(t),this.params=t,this.generateStreamingCommitMessage$=()=>{const{generate:s,type:o}=this.params.config;return this.createStreamingCommitMessages$(r=>{this.streamChunks(r).catch(i=>r.error(i))},o,s)},this.streamChunks=async s=>{const o=this.params.stagedDiff.diff,{logging:r}=this.params.config,i=b(this.buildPromptOptions());this.checkAvailableModels();const m=this.buildUserPrompt(o,"commit"),c=`${this.params.config.url||"https://api.deepseek.com"}/chat/completions`,p={Authorization:`Bearer ${this.params.config.key}`,"Content-Type":"application/json"};w(o,"commit","DeepSeek",this.params.config.model,c,p,r),C(o,"commit","DeepSeek",i,m,r);const n={messages:[{role:"system",content:i},{role:"user",content:m}],model:this.params.config.model,max_tokens:this.params.config.maxTokens,top_p:this.params.config.topP,temperature:this.params.config.temperature,stream:!0};A(o,"commit","DeepSeek",n,r);const l=Date.now();let d="";try{const x=await this.deepSeek.chat.completions.create(n,{timeout:this.params.config.timeout});for await(const g of x){const R=g.choices?.[0]?.delta?.content||"",E=g.choices?.[0]?.delta?.reasoning_content||"",f=`${R}${E}`;f&&(d+=f,s.next(f))}const $=Date.now()-l;P(o,"commit","DeepSeek",{streamed:!0,totalLength:d.length},r),M(o,"commit","DeepSeek",$,d,r),s.complete()}catch(h){I(o,"commit","DeepSeek",h,r),s.error(h)}},this.colors={primary:"#53a3f9",secondary:"#fff"},this.serviceName=u.bgHex(this.colors.primary).hex(this.colors.secondary).bold(`[DeepSeek${this.formatModelSuffix()}]`),this.errorPrefix=u.red.bold(`[DeepSeek${this.formatModelSuffix()}]`);const e=this.params.config.url||"https://api.deepseek.com";this.deepSeek=new U({baseURL:e,apiKey:this.params.config.key})}getServiceSpecificErrorMessage(t){const e=t.message||"";return e.includes("API key")||e.includes("api_key")?"Invalid API key. Check your DeepSeek API key in configuration":e.includes("rate_limit")||e.includes("Rate limit")?"Rate limit exceeded. Wait a moment and try again, or upgrade your DeepSeek plan":e.includes("model")||e.includes("Model")?"Model not found or not accessible. Check if the DeepSeek model name is correct":e.includes("Invalid model type")?"Invalid model type. Use supported models: deepseek-reasoner, deepseek-chat":e.includes("overloaded")||e.includes("capacity")?"DeepSeek service is overloaded. Try again in a few minutes":e.includes("403")||e.includes("Forbidden")?"Access denied. Your API key may not have permission for this DeepSeek model":e.includes("404")||e.includes("Not Found")?"Model or endpoint not found. Check your DeepSeek model configuration":e.includes("500")||e.includes("Internal Server Error")?"DeepSeek server error. Try again later":null}generateCommitMessage$(){return this.params.config.stream||!1?this.generateStreamingCommitMessage$():v(this.generateMessage("commit")).pipe(k(e=>S(e)),y(this.formatAsChoice),D(this.handleError$))}generateCodeReview$(){return v(this.generateMessage("review")).pipe(k(t=>S(t)),y(this.formatCodeReviewAsChoice),D(this.handleError$))}async generateMessage(t){const e=this.params.stagedDiff.diff,{logging:s,generate:o,type:r}=this.params.config,i=this.buildPromptOptions(),m=t==="review"?O(i):b(i);this.checkAvailableModels();const a=this.buildUserPrompt(e,t),p=`${this.params.config.url||"https://api.deepseek.com"}/chat/completions`,n={Authorization:`Bearer ${this.params.config.key}`,"Content-Type":"application/json"};w(e,t,"DeepSeek",this.params.config.model,p,n,s),C(e,t,"DeepSeek",m,a,s);const l=await this.createChatCompletions(m,a,t);return t==="review"?this.parseCodeReview(l):this.parseMessage(l,r,o)}checkAvailableModels(){if(["deepseek-reasoner","deepseek-chat"].includes(this.params.config.model))return!0;throw new Error("Invalid model type of DeepSeek")}async createChatCompletions(t,e,s){const o=this.params.stagedDiff.diff,{logging:r}=this.params.config,i={messages:[{role:"system",content:t},{role:"user",content:e}],model:this.params.config.model,max_tokens:this.params.config.maxTokens,top_p:this.params.config.topP,temperature:this.params.config.temperature};A(o,s,"DeepSeek",i,r);const m=Date.now();try{const a=await this.deepSeek.chat.completions.create(i,{timeout:this.params.config.timeout}),c=Date.now()-m,p=a.choices?.[0];if(!p?.message)throw new Error("DeepSeek API returned invalid response structure");const n=p.message.content||p.message.reasoning_content||"";if(!n)throw new Error("DeepSeek API returned empty response");return P(o,s,"DeepSeek",a,r),M(o,s,"DeepSeek",c,n,r),n}catch(a){throw I(o,s,"DeepSeek",a,r),a}}}export{z as DeepSeekService};
|