aicommit2 2.5.12 → 2.5.13
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/dist/{ai.service-a9047145.mjs → ai.service-f59388bb.mjs} +1 -1
- package/dist/{anthropic.service-c1c51fcc.mjs → anthropic.service-fb44d54e.mjs} +1 -1
- package/dist/{bedrock.service-3d914394.mjs → bedrock.service-40cbd1e5.mjs} +1 -1
- package/dist/{cli-5d0ec142.mjs → cli-d193cf90.mjs} +3 -3
- package/dist/cli.mjs +1 -1
- package/dist/{codestral.service-12ba24c3.mjs → codestral.service-f6ae65a5.mjs} +1 -1
- package/dist/{cohere.service-8c4441c5.mjs → cohere.service-af885cf7.mjs} +1 -1
- package/dist/copilot-sdk.service-f1cc1873.mjs +5 -0
- package/dist/{deep-seek.service-d2bde249.mjs → deep-seek.service-de8b4395.mjs} +1 -1
- package/dist/{gemini.service-d388f388.mjs → gemini.service-c9b02d26.mjs} +1 -1
- package/dist/{github-models.service-04f6badc.mjs → github-models.service-becd2e94.mjs} +1 -1
- package/dist/{groq.service-61f21765.mjs → groq.service-180e7478.mjs} +1 -1
- package/dist/{hugging-face.service-e09db43f.mjs → hugging-face.service-2c8f4576.mjs} +1 -1
- package/dist/{mistral.service-7251283a.mjs → mistral.service-7a553113.mjs} +1 -1
- package/dist/{ollama.service-e8633778.mjs → ollama.service-31b2908b.mjs} +1 -1
- package/dist/{openai-compatible.service-a24deda0.mjs → openai-compatible.service-2bea7313.mjs} +1 -1
- package/dist/{openai-f05c4d4e.mjs → openai-dc366083.mjs} +1 -1
- package/dist/{openai.service-302b8175.mjs → openai.service-ca071f6c.mjs} +1 -1
- package/dist/{openrouter.service-2b8fbca1.mjs → openrouter.service-2e239655.mjs} +1 -1
- package/dist/{perplexity.service-53baa468.mjs → perplexity.service-fe8bfcd5.mjs} +1 -1
- package/package.json +1 -1
- package/dist/copilot-sdk.service-d1ea1c28.mjs +0 -5
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{of as L,Observable as _,Subject as J,catchError as B}from"rxjs";import"fs";import"path";import{xxh64 as M}from"@pacote/xxhash";import $ from"winston";import{A as T,l as p,D as F,g as D,s as b,h as U,d as z,E as H,e as q,f as P}from"./cli-
|
|
1
|
+
import{of as L,Observable as _,Subject as J,catchError as B}from"rxjs";import"fs";import"path";import{xxh64 as M}from"@pacote/xxhash";import $ from"winston";import{A as T,l as p,D as F,g as D,s as b,h as U,d as z,E as H,e as q,f as P}from"./cli-d193cf90.mjs";const y=new Map,d=(f,r,e)=>{const o=M(0).update(r).digest("hex").substring(0,8),s=`${f}_${o}_${e}`;if(y.has(s))return y.get(s);const n=new Date,t=Z(n,f,r,e),c=`${T}/${t}`,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: ${o}`),i.info(`Request Type: ${e.toUpperCase()}`),i.info(`Start Time: ${n.toISOString()}`),i.info("=".repeat(50)),i.info(""),y.set(s,i),i},K=f=>{const r={...f},e=["authorization","x-api-key","x-goog-api-key","api-key","x-amzn-bedrock-application-key"];for(const o of e){const s=o.toLowerCase(),n=Object.keys(r).find(t=>t.toLowerCase()===s);n&&r[n]&&typeof r[n]=="string"&&(r[n].startsWith("Bearer ")?r[n]="Bearer [MASKED]":r[n]="[MASKED]")}return r},Y=(f,r,e,o,s,n,t=!0)=>{if(!t)return;const c=d(e,f,r);c.info(`Making request to ${e} API with model: ${o}`),c.info(`Request URL: ${s}`),c.info("Request headers:",K(n))},V=(f,r,e,o,s=!0)=>{if(!s)return;d(e,f,r).info("Request payload:",o)},W=(f,r,e,o,s,n=!0)=>{if(!n)return;const t=d(e,f,r);t.info("System prompt:",{prompt:o}),t.info("User prompt:",{prompt:s})},G=(f,r,e,o,s=!0)=>{if(!s)return;d(e,f,r).info("Response received:",o)},Q=(f,r,e,o,s=!0)=>{if(!s)return;d(e,f,r).error("API request failed:",o)},R=(f,r,e,o,s,n=!0)=>{if(!n)return;const t=d(e,f,r);o?t.info(`Request completed successfully in ${o}ms`):t.info("Request completed successfully"),s&&t.info("Final processed response:",{response:s}),t.info(""),t.info("=".repeat(50)),t.info(`End Time: ${new Date().toISOString()}`),t.info("=== REQUEST COMPLETED ===")},X=(f,r,e,o,s,n,t,c=!0)=>{if(!c)return;const i=d(e,f,r);t?i.error(`Request failed after ${n}ms:`,{error:t}):(i.info(`Request completed in ${n}ms`),i.info("Response:",{response:s})),R(f,r,e,n,s,c)},Z=(f,r,e,o)=>{const{year:s,month:n,day:t,hours:c,minutes:i,seconds:u}=ee(f),a=M(0).update(e).digest("hex").substring(0,8),m=r.toLowerCase().replace(/[^a-z0-9]/g,"").substring(0,20);return o==="review"?`${s}-${n}-${t}_${c}-${i}-${u}_${a}_${m}_review.log`:`${s}-${n}-${t}_${c}-${i}-${u}_${a}_${m}_commit.log`},ee=f=>{const r=f.getFullYear().toString(),e=(f.getMonth()+1).toString().padStart(2,"0"),o=f.getDate().toString().padStart(2,"0"),s=f.getHours().toString().padStart(2,"0"),n=f.getMinutes().toString().padStart(2,"0"),t=f.getSeconds().toString().padStart(2,"0");return{year:r,month:e,day:o,hours:s,minutes:n,seconds:t}},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)});class te{constructor(){this.buffer="",this.arrayStartFound=!1,this.scanPosition=0,this.feed=r=>{this.buffer+=r;const e=[];if(!this.arrayStartFound){const o=this.buffer.indexOf("[");if(o===-1)return e;this.arrayStartFound=!0,this.scanPosition=o+1}for(;;){const o=this.buffer.indexOf("{",this.scanPosition);if(o===-1)break;const s=this.extractBalancedBraces(o);if(!s)break;this.scanPosition=o+s.length;const n=this.tryParseCommitMessage(s);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,o=!1,s=!1;for(let n=r;n<this.buffer.length;n++){const t=this.buffer[n];if(s){s=!1;continue}if(t==="\\"&&o){s=!0;continue}if(t==='"'){o=!o;continue}if(!o&&(t==="{"&&e++,t==="}"&&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 se{constructor(r){this.formatModelSuffix=()=>{const e=this.params.modelNameDisplay??"short",o=this.params.config.model;if(e==="none"||!o)return"";const s=Array.isArray(o)?o[0]:String(o);if(e==="full")return`/${s}`;const n=s.split("/").pop()||s;return n.length>20?`/${n.slice(0,19)}\u2026`:`/${n}`},this.handleError$=e=>{const o=this.getDetailedErrorMessage(e),s=e.status?`HTTP ${e.status}: ${o}`:o;if(this.params.config.logging){const n=this.params.stagedDiff.diff,t=this.serviceName.replace(/\[|\]/g,"").trim();X(n,"commit",t,"Error occurred","",void 0,s)}return p.error(`${this.errorPrefix} ${s}`),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} ${s}`,value:s,isError:!0,disabled:!0})},this.extractJsonObjectFromResponse=e=>{const o=e.indexOf("{");return o!==-1?this.extractBalancedJson(e,o,"{","}"):null},this.buildCommitPrompt=()=>{const{systemPrompt:e,systemPromptPath:o,codeReviewPromptPath:s,locale:n,generate:t,type:c,maxLength:i}=this.params.config,u={...F,locale:n,maxLength:i,type:c,generate:t,systemPrompt:e,systemPromptPath:o,codeReviewPromptPath:s,vcs_branch:this.params.branchName||""};return D(u)},this.formatRawCommitMessage=(e,o)=>{const s=this.extractMessageAsType(e,o),n=s.subject,t=`${s.subject}${s.body?`
|
|
2
2
|
|
|
3
3
|
${s.body}`:""}${s.footer?`
|
|
4
4
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import j from"@anthropic-ai/sdk";import E from"chalk";import{concatMap as $,from as b,map as D,catchError as R}from"rxjs";import{fromPromise as U}from"rxjs/internal/observable/innerFrom";import{A as B,l as F,a as O,b as L,c as T,d as N,e as W}from"./ai.service-
|
|
1
|
+
import j from"@anthropic-ai/sdk";import E from"chalk";import{concatMap as $,from as b,map as D,catchError as R}from"rxjs";import{fromPromise as U}from"rxjs/internal/observable/innerFrom";import{A as B,l as F,a as O,b as L,c as T,d as N,e as W}from"./ai.service-f59388bb.mjs";import{D as z,g as H,b as G,k as K}from"./cli-d193cf90.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 J=["claude-4","claude-haiku-4","claude-sonnet-4","claude-opus-4"],X=I=>{const e=I.toLowerCase();return J.some(t=>e===t||e.startsWith(`${t}-`)||e.startsWith(`${t}.`))},Q=10*60*1e3;class V extends B{constructor(e){super(e),this.params=e,this.generateStreamingCommitMessage$=()=>{const{generate:t,type:o}=this.params.config;return this.createStreamingCommitMessages$(n=>{this.streamChunks(n).catch(c=>n.error(c))},o,t)},this.streamChunks=async t=>{const o=this.params.stagedDiff.diff,{systemPrompt:n,systemPromptPath:c,codeReviewPromptPath:s,logging:i,temperature:P,locale:l,generate:d,type:y,maxLength:M,maxTokens:C,topP:p,model:m}=this.params.config,u={...z,locale:l,maxLength:M,type:y,generate:d,systemPrompt:n,systemPromptPath:c,codeReviewPromptPath:s,vcs_branch:this.params.branchName||""},h=H(u),k=K(o,"commit"),v=`${this.params.config.url||"https://api.anthropic.com"}/v1/messages`,w={"Content-Type":"application/json","x-api-key":this.params.config.key,"anthropic-version":"2023-06-01"};F(o,"commit","Anthropic",m,v,w,i),O(o,"commit","Anthropic",h,k,i);const g=X(m),f={max_tokens:C,temperature:P,system:h,messages:[{role:"user",content:k}],model:m,stream:!0,...g?{}:{top_p:p}};L(o,"commit","Anthropic",f,i);const a=Date.now();let A="";try{const r=this.anthropic.messages.stream(f);r.on("text",_=>{A+=_,t.next(_)});const x=await r.finalMessage(),Y=Date.now()-a;T(o,"commit","Anthropic",x,i),N(o,"commit","Anthropic",Y,A,i),t.complete()}catch(r){W(o,"commit","Anthropic",r,i),t.error(r)}},this.colors={primary:"#AE5630",secondary:"#fff"},this.serviceName=E.bgHex(this.colors.primary).hex(this.colors.secondary).bold(`[Anthropic${this.formatModelSuffix()}]`),this.errorPrefix=E.red.bold(`[Anthropic${this.formatModelSuffix()}]`),this.anthropic=new j({apiKey:this.params.config.key,...this.params.config.timeout>Q&&{timeout:this.params.config.timeout}})}getServiceSpecificErrorMessage(e){const t=e.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$():U(this.generateMessage("commit")).pipe($(t=>b(t)),D(this.formatAsChoice),R(this.handleError$))}generateCodeReview$(){return U(this.generateMessage("review")).pipe($(e=>b(e)),D(this.formatCodeReviewAsChoice),R(this.handleError$))}async generateMessage(e){const t=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:n,codeReviewPromptPath:c,logging:s,temperature:i,locale:P,generate:l,type:d,maxLength:y,maxTokens:M,topP:C,model:p}=this.params.config,m={...z,locale:P,maxLength:y,type:d,generate:l,systemPrompt:o,systemPromptPath:n,codeReviewPromptPath:c,vcs_branch:this.params.branchName||""},u=e==="review"?G(m):H(m),h=K(t,e),S=`${this.params.config.url||"https://api.anthropic.com"}/v1/messages`,v={"Content-Type":"application/json","x-api-key":this.params.config.key,"anthropic-version":"2023-06-01"};F(t,e,"Anthropic",p,S,v,s),O(t,e,"Anthropic",u,h,s);const w=X(p),g={max_tokens:M,temperature:i,system:u,messages:[{role:"user",content:h}],model:p,...w?{}:{top_p:C}};L(t,e,"Anthropic",g,s);const f=Date.now();try{const a=await this.anthropic.messages.create(g),A=Date.now()-f;T(t,e,"Anthropic",a,s);const r=a.content.map(({text:x})=>x).join("");return N(t,e,"Anthropic",A,r,s),e==="review"?this.parseCodeReview(r):this.parseMessage(r,d,l)}catch(a){throw W(t,e,"Anthropic",a,s),a}}}export{V as AnthropicService};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import F from"https";import h from"chalk";import{concatMap as $,from as T,map as x,catchError as L}from"rxjs";import{fromPromise as W}from"rxjs/internal/observable/innerFrom";import{A as q,l as Y,a as H,b as z,d as V,e as _,c as K}from"./ai.service-
|
|
1
|
+
import F from"https";import h from"chalk";import{concatMap as $,from as T,map as x,catchError as L}from"rxjs";import{fromPromise as W}from"rxjs/internal/observable/innerFrom";import{A as q,l as Y,a as H,b as z,d as V,e as _,c as K}from"./ai.service-f59388bb.mjs";import{D as J,b as j,g as Q,p as O,s as X,k as Z}from"./cli-d193cf90.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 M=null,v=null;const G=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},ee=async()=>{if(M)return M;try{return M=await import("@aws-sdk/client-bedrock-runtime"),M}catch(f){throw M=null,G(f)}},U=async()=>{if(v)return v;try{return v=await import("@aws-sdk/credential-providers"),v}catch(f){throw v=null,G(f)}};class oe 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 t=new Error("Model ID or inference profile ARN is required.");throw t.name=S.MISSING_MODEL_ID,t}if(!this.getRegion()){const t=new Error("AWS region is required. Configure BEDROCK.region or set AWS_REGION/AWS_DEFAULT_REGION.");throw t.name=S.MISSING_REGION,t}const r=i(e.key),o=this.canUseAwsSdk();if(!r&&!o){const t=new Error("Authentication required: Configure AWS credentials (profile, access keys, IAM role) or API key (BEDROCK.key).");throw t.name=S.MISSING_API_KEY,t}if(r&&!o&&!this.getRegion()&&!i(e.applicationBaseUrl)){const t=new Error("Bearer token authentication requires region or applicationBaseUrl to construct endpoint.");throw t.name=S.MISSING_REGION,t}}canUseAwsSdk(){const e=this.bedrockConfig,r=i(e.profile)||i(process.env.AWS_PROFILE),o=i(e.accessKeyId)&&i(e.secretAccessKey)||i(process.env.AWS_ACCESS_KEY_ID)&&i(process.env.AWS_SECRET_ACCESS_KEY);return r||o}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 r=e?.name||e.code,o=e.message||"";switch(r){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 o.includes("Region")?"AWS region is required for Bedrock. Configure BEDROCK.region or set AWS_REGION/AWS_DEFAULT_REGION.":null}generateCommitMessage$(){return W(this.generateMessage("commit")).pipe($(e=>T(e)),x(this.formatAsChoice),L(this.handleError$))}generateCodeReview$(){return W(this.generateMessage("review")).pipe($(e=>T(e)),x(this.formatCodeReviewAsChoice),L(this.handleError$))}async generateMessage(e){const r=this.params.stagedDiff.diff,o=this.bedrockConfig,t=o.model,{logging:c,inferenceParameters:n}=o,s={...J,locale:o.locale,maxLength:o.maxLength,type:o.type,generate:o.generate,systemPrompt:o.systemPrompt,systemPromptPath:o.systemPromptPath,codeReviewPromptPath:o.codeReviewPromptPath},a=e==="review"?j(s):Q(s),m=Z(r,e),y={region:this.getRegion(),profile:o.profile,modelId:t},w=`https://bedrock-runtime.${this.getRegion()||"unknown"}.amazonaws.com/model/${encodeURIComponent(t)}/converse`;Y(r,e,g,t,w,y,c),H(r,e,g,a,m,c);const R={modelId:t,systemPrompt:a,userPrompt:m,...n&&Object.keys(n).length>0&&{inferenceConfig:n}};z(r,e,g,R,c);const u=Date.now();try{const l=this.determineAuthMethod();O()&&(console.log(h.cyan(`[Bedrock] Authentication method: ${l}`)),console.log(h.cyan(`[Bedrock] Model ID: ${t}`)),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(o.key)}`)));const E=l==="bearer-token"?await this.invokeWithBearerToken({model:t,systemPrompt:a,userPrompt:m,logging:c,requestType:e,diff:r,inferenceConfig:n}):await this.invokeWithAwsSdk({model:t,systemPrompt:a,userPrompt:m,logging:c,requestType:e,diff:r,inferenceConfig:n}),I=Date.now()-u;return V(r,e,g,I,E,c),e==="review"?this.parseCodeReview(E):this.parseMessage(E,o.type,o.generate)}catch(l){throw _(r,e,g,l,c),l instanceof Error&&(l.status=l?.status||l?.$metadata?.httpStatusCode),l}}async invokeWithAwsSdk(e){const r=this.getRegion(),{model:o,systemPrompt:t,userPrompt:c,inferenceConfig:n,logging:s,requestType:a,diff:m}=e,{BedrockRuntimeClient:y,ConverseCommand:w}=await ee(),R=this.bedrockConfig,u={region:r,requestHandler:{requestTimeout:R.timeout||12e4}},l=await this.resolveCredentials();l&&(u.credentials=l);const E=new y(u),I=new w({modelId:o,messages:[{role:"user",content:[{text:c}]}],...t?{system:[{text:t}]}:{},...n&&Object.keys(n).length>0&&{inferenceConfig:n}});O()&&console.log(h.cyan(`[Bedrock] Sending ConverseCommand with modelId: ${o}`));let C;try{C=await E.send(I),K(m,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:r,systemPrompt:o,userPrompt:t,inferenceConfig:c,logging:n,requestType:s,diff:a}=e,m=this.bedrockConfig,y=this.getRegion(),w=encodeURIComponent(r),R=m.applicationBaseUrl||`https://bedrock-runtime.${y}.amazonaws.com/model/${w}/converse`,u=new URL(R),l={modelId:r,messages:[{role:"user",content:[{text:t}]}],...c&&Object.keys(c).length>0&&{inferenceConfig:c}};o&&(l.system=[{text:o}]);const E=JSON.stringify(l),I={"Content-Type":"application/json","Content-Length":Buffer.byteLength(E).toString()};return i(m.key)&&(I.Authorization=`Bearer ${m.key}`),i(m.applicationInferenceProfileArn)&&(I["x-amzn-bedrock-inference-profile-arn"]=m.applicationInferenceProfileArn),i(m.applicationEndpointId)&&(I["x-amzn-bedrock-endpoint-id"]=m.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:m.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,_(a,s,g,p,n),A(p)}const D=X(N);if(!D.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,_(a,s,g,p,n),A(p)}const B=D.data;K(a,s,g,B,n);const b=B.output?.message?.content?.[0]?.text||"";if(!b){const p=new Error("No text content found in Bedrock response.");return p.name=S.EMPTY_RESPONSE,p.content=B,_(a,s,g,p,n),A(p)}C(b)})});d.on("error",k=>{const P=k;_(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 r=this.bedrockConfig,o=r.profile,t=r.accessKeyId,c=r.secretAccessKey,n=r.sessionToken;let s;if(i(o)){const{fromIni:a}=await U();s=a({profile:o})}else if(i(t)&&i(c))s=async()=>({accessKeyId:t,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{oe as BedrockService};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{command as j,cli as ss}from"cleye";import{createRequire as rs}from"module";import is from"crypto";import _ from"fs";import Ie from"os";import P from"path";import{Buffer as cn}from"node:buffer";import ee from"node:path";import lt,{ChildProcess as ln,exec as as}from"node:child_process";import G from"node:process";import cs,{execSync as ge,exec as ls}from"child_process";import{fileURLToPath as un}from"node:url";import us,{constants as dn}from"node:os";import ds from"assert";import ms from"events";import{createWriteStream as fs,createReadStream as ps,readFileSync as hs}from"node:fs";import gs from"buffer";import ut from"stream";import ys,{promisify as ws}from"util";import{debuglog as Cs,promisify as bs}from"node:util";import M from"inquirer";import{from as ke,switchMap as mn,of as Es,tap as vs,mergeMap as fn,catchError as Ps,BehaviorSubject as pn,ReplaySubject as As,Subscription as dt,lastValueFrom as mt,toArray as ft,filter as hn,map as gn,Subject as xs}from"rxjs";import I from"fs/promises";import h from"chalk";import Le from"readline";import yn from"figlet";import Ss from"gradient-string";import wn from"ora";import $s from"inquirer-reactive-list-prompt";import B from"winston";import"winston-daily-rotate-file";import Rs from"axios";import{fileURLToPath as Is,pathToFileURL as ks}from"url";import{readdir as Cn,stat as Ls,rm as Ms}from"node:fs/promises";import Ts from"chokidar";import{takeUntil as bn,finalize as En}from"rxjs/operators";var Os="aicommit2",vn="2.5.12",Ds="A Reactive CLI that generates commit messages for Git and Jujutsu with various AI",Ns=["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"],_s="MIT",js="tak-bro/aicommit2",Fs="Hyungtak Jin(@tak-bro)",Gs="module",Bs=["dist"],Hs={aicommit2:"./dist/cli.mjs",aic2:"./dist/cli.mjs"},Us={prepare:"simple-git-hooks",build:"pkgroll --minify",lint:"eslint --cache .","type-check":"tsc",test:"tsx tests",prepack:"pnpm build && clean-pkg-json",prettier:"prettier"},Ks={"@anthropic-ai/sdk":"^0.39.0","@aws-sdk/client-bedrock-runtime":"^3.678.0","@aws-sdk/credential-providers":"^3.678.0","@dqbd/tiktoken":"^1.0.21","@google/generative-ai":"^0.24.1","@inquirer/prompts":"^3.3.2","@pacote/xxhash":"^0.3.2","@types/winston":"^2.4.4",axios:"^1.9.0",chalk:"^5.4.1",chokidar:"^4.0.3",cleye:"^1.3.4","cohere-ai":"^7.19.0","copy-paste":"^1.5.3",figlet:"^1.8.1","formdata-node":"^6.0.3","gradient-string":"^3.0.0","groq-sdk":"^0.7.0",inquirer:"9.2.8","inquirer-reactive-list-prompt":"^1.0.16",ollama:"^0.5.15",openai:"^6.3.0",ora:"^8.2.0",readline:"^1.3.0",rxjs:"^7.8.2",undici:"^7.10.0",uuid:"^9.0.1",winston:"^3.17.0","winston-daily-rotate-file":"^5.0.0"},Ws={"@github/copilot-sdk":"0.2.0"},qs={"@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"},zs={extends:["@pvtnbr","prettier"],rules:{"unicorn/no-process-exit":"off"},overrides:[{files:"./src/commands/prepare-commit-msg-hook.ts",rules:{"unicorn/prevent-abbreviations":"off"}}]},Ys={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"]},Vs={name:Os,version:vn,description:Ds,keywords:Ns,license:_s,repository:js,author:Fs,type:Gs,files:Bs,bin:Hs,scripts:Us,"simple-git-hooks":{"pre-commit":"pnpm lint-staged"},"lint-staged":{"*.ts":["prettier --config ./.prettierrc --write","eslint --fix"]},dependencies:Ks,optionalDependencies:Ws,devDependencies:qs,eslintConfig:zs,release:Ys},pt=rs(import.meta.url),J=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function oe(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var se={exports:{}},ht,Pn;function Js(){if(Pn)return ht;Pn=1,ht=o,o.sync=s;var e=_;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 ht}var gt,An;function Xs(){if(An)return gt;An=1,gt=t,t.sync=n;var e=_;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(),m=a.gid!==void 0?a.gid:process.getgid&&process.getgid(),g=parseInt("100",8),y=parseInt("010",8),f=parseInt("001",8),A=g|y,R=c&f||c&y&&u===m||c&g&&l===d||c&A&&d===0;return R}return gt}var Me;process.platform==="win32"||J.TESTING_WINDOWS?Me=Js():Me=Xs();var Qs=yt;yt.sync=Zs;function yt(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){yt(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 Zs(e,t){try{return Me.sync(e,t||{})}catch(n){if(t&&t.ignoreErrors||n.code==="EACCES")return!1;throw n}}const re=process.platform==="win32"||process.env.OSTYPE==="cygwin"||process.env.OSTYPE==="msys",xn=P,er=re?";":":",Sn=Qs,$n=e=>Object.assign(new Error(`not found: ${e}`),{code:"ENOENT"}),Rn=(e,t)=>{const n=t.colon||er,o=e.match(/\//)||re&&e.match(/\\/)?[""]:[...re?[process.cwd()]:[],...(t.path||process.env.PATH||"").split(n)],s=re?t.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",r=re?s.split(n):[""];return re&&e.indexOf(".")!==-1&&r[0]!==""&&r.unshift(""),{pathEnv:o,pathExt:r,pathExtExe:s}},In=(e,t,n)=>{typeof t=="function"&&(n=t,t={}),t||(t={});const{pathEnv:o,pathExt:s,pathExtExe:r}=Rn(e,t),a=[],c=u=>new Promise((d,m)=>{if(u===o.length)return t.all&&a.length?d(a):m($n(e));const g=o[u],y=/^".*"$/.test(g)?g.slice(1,-1):g,f=xn.join(y,e),A=!y&&/^\.[\\\/]/.test(e)?e.slice(0,2)+f:f;d(l(A,u,0))}),l=(u,d,m)=>new Promise((g,y)=>{if(m===s.length)return g(c(d+1));const f=s[m];Sn(u+f,{pathExt:r},(A,R)=>{if(!A&&R)if(t.all)a.push(u+f);else return g(u+f);return g(l(u,d,m+1))})});return n?c(0).then(u=>n(null,u),n):c(0)},tr=(e,t)=>{t=t||{};const{pathEnv:n,pathExt:o,pathExtExe:s}=Rn(e,t),r=[];for(let a=0;a<n.length;a++){const c=n[a],l=/^".*"$/.test(c)?c.slice(1,-1):c,u=xn.join(l,e),d=!l&&/^\.[\\\/]/.test(e)?e.slice(0,2)+u:u;for(let m=0;m<o.length;m++){const g=d+o[m];try{if(Sn.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 $n(e)};var nr=In;In.sync=tr;var wt={exports:{}};const kn=(e={})=>{const t=e.env||process.env;return(e.platform||process.platform)!=="win32"?"PATH":Object.keys(t).reverse().find(o=>o.toUpperCase()==="PATH")||"Path"};wt.exports=kn,wt.exports.default=kn;var or=wt.exports;const Ln=P,sr=nr,rr=or;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=sr.sync(e.command,{path:n[rr({env:n})],pathExt:t?Ln.delimiter:void 0})}catch{}finally{r&&process.chdir(o)}return a&&(a=Ln.resolve(s?e.options.cwd:"",a)),a}function ir(e){return Mn(e)||Mn(e,!0)}var ar=ir,Ct={};const bt=/([()\][%!^"`<>&|;, *?])/g;function cr(e){return e=e.replace(bt,"^$1"),e}function lr(e,t){return e=`${e}`,e=e.replace(/(?=(\\+?)?)\1"/g,'$1$1\\"'),e=e.replace(/(?=(\\+?)?)\1$/,"$1$1"),e=`"${e}"`,e=e.replace(bt,"^$1"),t&&(e=e.replace(bt,"^$1")),e}Ct.command=cr,Ct.argument=lr;var ur=/^#!(.*)/;const dr=ur;var mr=(e="")=>{const t=e.match(dr);if(!t)return null;const[n,o]=t[0].replace(/#! ?/,"").split(" "),s=n.split("/").pop();return s==="env"?o:o?`${s} ${o}`:s};const Et=_,fr=mr;function pr(e){const n=Buffer.alloc(150);let o;try{o=Et.openSync(e,"r"),Et.readSync(o,n,0,150,0),Et.closeSync(o)}catch{}return fr(n.toString())}var hr=pr;const gr=P,Tn=ar,On=Ct,yr=hr,wr=process.platform==="win32",Cr=/\.(?:com|exe)$/i,br=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function Er(e){e.file=Tn(e);const t=e.file&&yr(e.file);return t?(e.args.unshift(e.file),e.command=t,Tn(e)):e.file}function vr(e){if(!wr)return e;const t=Er(e),n=!Cr.test(t);if(e.options.forceShell||n){const o=br.test(t);e.command=gr.normalize(e.command),e.command=On.command(e.command),e.args=e.args.map(r=>On.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 Pr(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:vr(o)}var Ar=Pr;const vt=process.platform==="win32";function Pt(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 xr(e,t){if(!vt)return;const n=e.emit;e.emit=function(o,s){if(o==="exit"){const r=Dn(s,t);if(r)return n.call(e,"error",r)}return n.apply(e,arguments)}}function Dn(e,t){return vt&&e===1&&!t.file?Pt(t.original,"spawn"):null}function Sr(e,t){return vt&&e===1&&!t.file?Pt(t.original,"spawnSync"):null}var $r={hookChildProcess:xr,verifyENOENT:Dn,verifyENOENTSync:Sr,notFoundError:Pt};const Nn=cs,At=Ar,xt=$r;function _n(e,t,n){const o=At(e,t,n),s=Nn.spawn(o.command,o.args,o.options);return xt.hookChildProcess(s,o),s}function Rr(e,t,n){const o=At(e,t,n),s=Nn.spawnSync(o.command,o.args,o.options);return s.error=s.error||xt.verifyENOENTSync(s.status,o),s}se.exports=_n,se.exports.spawn=_n,se.exports.sync=Rr,se.exports._parse=At,se.exports._enoent=xt;var Ir=se.exports,kr=oe(Ir);function Lr(e){const t=typeof e=="string"?`
|
|
1
|
+
import{command as j,cli as ss}from"cleye";import{createRequire as rs}from"module";import is from"crypto";import _ from"fs";import Ie from"os";import P from"path";import{Buffer as cn}from"node:buffer";import ee from"node:path";import lt,{ChildProcess as ln,exec as as}from"node:child_process";import G from"node:process";import cs,{execSync as ge,exec as ls}from"child_process";import{fileURLToPath as un}from"node:url";import us,{constants as dn}from"node:os";import ds from"assert";import ms from"events";import{createWriteStream as fs,createReadStream as ps,readFileSync as hs}from"node:fs";import gs from"buffer";import ut from"stream";import ys,{promisify as ws}from"util";import{debuglog as Cs,promisify as bs}from"node:util";import M from"inquirer";import{from as ke,switchMap as mn,of as Es,tap as vs,mergeMap as fn,catchError as Ps,BehaviorSubject as pn,ReplaySubject as As,Subscription as dt,lastValueFrom as mt,toArray as ft,filter as hn,map as gn,Subject as xs}from"rxjs";import I from"fs/promises";import h from"chalk";import Le from"readline";import yn from"figlet";import Ss from"gradient-string";import wn from"ora";import $s from"inquirer-reactive-list-prompt";import B from"winston";import"winston-daily-rotate-file";import Rs from"axios";import{fileURLToPath as Is,pathToFileURL as ks}from"url";import{readdir as Cn,stat as Ls,rm as Ms}from"node:fs/promises";import Ts from"chokidar";import{takeUntil as bn,finalize as En}from"rxjs/operators";var Os="aicommit2",vn="2.5.13",Ds="A Reactive CLI that generates commit messages for Git and Jujutsu with various AI",Ns=["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"],_s="MIT",js="tak-bro/aicommit2",Fs="Hyungtak Jin(@tak-bro)",Gs="module",Bs=["dist"],Hs={aicommit2:"./dist/cli.mjs",aic2:"./dist/cli.mjs"},Us={prepare:"simple-git-hooks",build:"pkgroll --minify",lint:"eslint --cache .","type-check":"tsc",test:"tsx tests",prepack:"pnpm build && clean-pkg-json",prettier:"prettier"},Ks={"@anthropic-ai/sdk":"^0.39.0","@aws-sdk/client-bedrock-runtime":"^3.678.0","@aws-sdk/credential-providers":"^3.678.0","@dqbd/tiktoken":"^1.0.21","@google/generative-ai":"^0.24.1","@inquirer/prompts":"^3.3.2","@pacote/xxhash":"^0.3.2","@types/winston":"^2.4.4",axios:"^1.9.0",chalk:"^5.4.1",chokidar:"^4.0.3",cleye:"^1.3.4","cohere-ai":"^7.19.0","copy-paste":"^1.5.3",figlet:"^1.8.1","formdata-node":"^6.0.3","gradient-string":"^3.0.0","groq-sdk":"^0.7.0",inquirer:"9.2.8","inquirer-reactive-list-prompt":"^1.0.16",ollama:"^0.5.15",openai:"^6.3.0",ora:"^8.2.0",readline:"^1.3.0",rxjs:"^7.8.2",undici:"^7.10.0",uuid:"^9.0.1",winston:"^3.17.0","winston-daily-rotate-file":"^5.0.0"},Ws={"@github/copilot-sdk":"0.2.0"},qs={"@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"},zs={extends:["@pvtnbr","prettier"],rules:{"unicorn/no-process-exit":"off"},overrides:[{files:"./src/commands/prepare-commit-msg-hook.ts",rules:{"unicorn/prevent-abbreviations":"off"}}]},Ys={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"]},Vs={name:Os,version:vn,description:Ds,keywords:Ns,license:_s,repository:js,author:Fs,type:Gs,files:Bs,bin:Hs,scripts:Us,"simple-git-hooks":{"pre-commit":"pnpm lint-staged"},"lint-staged":{"*.ts":["prettier --config ./.prettierrc --write","eslint --fix"]},dependencies:Ks,optionalDependencies:Ws,devDependencies:qs,eslintConfig:zs,release:Ys},pt=rs(import.meta.url),J=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function oe(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var se={exports:{}},ht,Pn;function Js(){if(Pn)return ht;Pn=1,ht=o,o.sync=s;var e=_;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 ht}var gt,An;function Xs(){if(An)return gt;An=1,gt=t,t.sync=n;var e=_;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(),m=a.gid!==void 0?a.gid:process.getgid&&process.getgid(),g=parseInt("100",8),y=parseInt("010",8),f=parseInt("001",8),A=g|y,R=c&f||c&y&&u===m||c&g&&l===d||c&A&&d===0;return R}return gt}var Me;process.platform==="win32"||J.TESTING_WINDOWS?Me=Js():Me=Xs();var Qs=yt;yt.sync=Zs;function yt(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){yt(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 Zs(e,t){try{return Me.sync(e,t||{})}catch(n){if(t&&t.ignoreErrors||n.code==="EACCES")return!1;throw n}}const re=process.platform==="win32"||process.env.OSTYPE==="cygwin"||process.env.OSTYPE==="msys",xn=P,er=re?";":":",Sn=Qs,$n=e=>Object.assign(new Error(`not found: ${e}`),{code:"ENOENT"}),Rn=(e,t)=>{const n=t.colon||er,o=e.match(/\//)||re&&e.match(/\\/)?[""]:[...re?[process.cwd()]:[],...(t.path||process.env.PATH||"").split(n)],s=re?t.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",r=re?s.split(n):[""];return re&&e.indexOf(".")!==-1&&r[0]!==""&&r.unshift(""),{pathEnv:o,pathExt:r,pathExtExe:s}},In=(e,t,n)=>{typeof t=="function"&&(n=t,t={}),t||(t={});const{pathEnv:o,pathExt:s,pathExtExe:r}=Rn(e,t),a=[],c=u=>new Promise((d,m)=>{if(u===o.length)return t.all&&a.length?d(a):m($n(e));const g=o[u],y=/^".*"$/.test(g)?g.slice(1,-1):g,f=xn.join(y,e),A=!y&&/^\.[\\\/]/.test(e)?e.slice(0,2)+f:f;d(l(A,u,0))}),l=(u,d,m)=>new Promise((g,y)=>{if(m===s.length)return g(c(d+1));const f=s[m];Sn(u+f,{pathExt:r},(A,R)=>{if(!A&&R)if(t.all)a.push(u+f);else return g(u+f);return g(l(u,d,m+1))})});return n?c(0).then(u=>n(null,u),n):c(0)},tr=(e,t)=>{t=t||{};const{pathEnv:n,pathExt:o,pathExtExe:s}=Rn(e,t),r=[];for(let a=0;a<n.length;a++){const c=n[a],l=/^".*"$/.test(c)?c.slice(1,-1):c,u=xn.join(l,e),d=!l&&/^\.[\\\/]/.test(e)?e.slice(0,2)+u:u;for(let m=0;m<o.length;m++){const g=d+o[m];try{if(Sn.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 $n(e)};var nr=In;In.sync=tr;var wt={exports:{}};const kn=(e={})=>{const t=e.env||process.env;return(e.platform||process.platform)!=="win32"?"PATH":Object.keys(t).reverse().find(o=>o.toUpperCase()==="PATH")||"Path"};wt.exports=kn,wt.exports.default=kn;var or=wt.exports;const Ln=P,sr=nr,rr=or;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=sr.sync(e.command,{path:n[rr({env:n})],pathExt:t?Ln.delimiter:void 0})}catch{}finally{r&&process.chdir(o)}return a&&(a=Ln.resolve(s?e.options.cwd:"",a)),a}function ir(e){return Mn(e)||Mn(e,!0)}var ar=ir,Ct={};const bt=/([()\][%!^"`<>&|;, *?])/g;function cr(e){return e=e.replace(bt,"^$1"),e}function lr(e,t){return e=`${e}`,e=e.replace(/(?=(\\+?)?)\1"/g,'$1$1\\"'),e=e.replace(/(?=(\\+?)?)\1$/,"$1$1"),e=`"${e}"`,e=e.replace(bt,"^$1"),t&&(e=e.replace(bt,"^$1")),e}Ct.command=cr,Ct.argument=lr;var ur=/^#!(.*)/;const dr=ur;var mr=(e="")=>{const t=e.match(dr);if(!t)return null;const[n,o]=t[0].replace(/#! ?/,"").split(" "),s=n.split("/").pop();return s==="env"?o:o?`${s} ${o}`:s};const Et=_,fr=mr;function pr(e){const n=Buffer.alloc(150);let o;try{o=Et.openSync(e,"r"),Et.readSync(o,n,0,150,0),Et.closeSync(o)}catch{}return fr(n.toString())}var hr=pr;const gr=P,Tn=ar,On=Ct,yr=hr,wr=process.platform==="win32",Cr=/\.(?:com|exe)$/i,br=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function Er(e){e.file=Tn(e);const t=e.file&&yr(e.file);return t?(e.args.unshift(e.file),e.command=t,Tn(e)):e.file}function vr(e){if(!wr)return e;const t=Er(e),n=!Cr.test(t);if(e.options.forceShell||n){const o=br.test(t);e.command=gr.normalize(e.command),e.command=On.command(e.command),e.args=e.args.map(r=>On.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 Pr(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:vr(o)}var Ar=Pr;const vt=process.platform==="win32";function Pt(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 xr(e,t){if(!vt)return;const n=e.emit;e.emit=function(o,s){if(o==="exit"){const r=Dn(s,t);if(r)return n.call(e,"error",r)}return n.apply(e,arguments)}}function Dn(e,t){return vt&&e===1&&!t.file?Pt(t.original,"spawn"):null}function Sr(e,t){return vt&&e===1&&!t.file?Pt(t.original,"spawnSync"):null}var $r={hookChildProcess:xr,verifyENOENT:Dn,verifyENOENTSync:Sr,notFoundError:Pt};const Nn=cs,At=Ar,xt=$r;function _n(e,t,n){const o=At(e,t,n),s=Nn.spawn(o.command,o.args,o.options);return xt.hookChildProcess(s,o),s}function Rr(e,t,n){const o=At(e,t,n),s=Nn.spawnSync(o.command,o.args,o.options);return s.error=s.error||xt.verifyENOENTSync(s.status,o),s}se.exports=_n,se.exports.spawn=_n,se.exports.sync=Rr,se.exports._parse=At,se.exports._enoent=xt;var Ir=se.exports,kr=oe(Ir);function Lr(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 jn(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 Mr=({cwd:e=G.cwd(),path:t=G.env[jn()],preferLocal:n=!0,execPath:o=G.execPath,addExecPath:s=!0}={})=>{const r=e instanceof URL?un(e):e,a=ee.resolve(r),c=[];return n&&Tr(c,a),s&&Or(c,o,a),[...c,t].join(ee.delimiter)},Tr=(e,t)=>{let n;for(;n!==t;)e.push(ee.join(t,"node_modules/.bin")),n=t,t=ee.resolve(t,"..")},Or=(e,t,n)=>{const o=t instanceof URL?un(t):t;e.push(ee.resolve(n,o,".."))},Dr=({env:e=G.env,...t}={})=>{e={...e};const n=jn({env:e});return t.path=e[n],e[n]=Mr(t),e},Nr=(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);!_r(s,r)&&o||Object.defineProperty(e,n,r)},_r=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)},jr=(e,t)=>{const n=Object.getPrototypeOf(t);n!==Object.getPrototypeOf(e)&&Object.setPrototypeOf(e,n)},Fr=(e,t)=>`/* Wrapped ${e}*/
|
|
4
4
|
${t}`,Gr=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),Br=Object.getOwnPropertyDescriptor(Function.prototype.toString,"name"),Hr=(e,t,n)=>{const o=n===""?"":`with ${n.trim()}() `,s=Fr.bind(null,o,t.toString());Object.defineProperty(s,"name",Br),Object.defineProperty(e,"toString",{...Gr,value:s})};function Ur(e,t,{ignoreNonConfigurable:n=!1}={}){const{name:o}=e;for(const s of Reflect.ownKeys(t))Nr(e,t,s,n);return jr(e,t),Hr(e,t,o),e}const Te=new WeakMap,Fn=(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 Ur(r,e),Te.set(r,o),r};Fn.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 Kr=()=>{const e=Bn-Gn+1;return Array.from({length:e},Wr)},Wr=(e,t)=>({name:`SIGRT${t+1}`,number:Gn+t,action:"terminate",description:"Application-specific signal (realtime)",standard:"posix"}),Gn=34,Bn=64,qr=[{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"}],Hn=()=>{const e=Kr();return[...qr,...e].map(zr)},zr=({name:e,number:t,description:n,action:o,forced:s=!1,standard:r})=>{const{signals:{[e]:a}}=dn,c=a!==void 0;return{name:e,number:c?a:t,description:n,supported:c,action:o,forced:s,standard:r}},Yr=()=>{const e=Hn();return Object.fromEntries(e.map(Vr))},Vr=({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}],Jr=Yr(),Xr=()=>{const e=Hn(),t=Bn+1,n=Array.from({length:t},(o,s)=>Qr(s,e));return Object.assign({},...n)},Qr=(e,t)=>{const n=Zr(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}}},Zr=(e,t)=>{const n=t.find(({name:o})=>dn.signals[o]===e);return n!==void 0?n:t.find(o=>o.number===e)};Xr();const ei=({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",Oe=({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:m,cwd:g=G.cwd()}}})=>{r=r===null?void 0:r,s=s===null?void 0:s;const y=s===void 0?void 0:Jr[s].description,f=o&&o.code,R=`Command ${ei({timedOut:l,timeout:m,errorCode:f,signal:s,signalDescription:y,exitCode:r,isCanceled:u})}: ${a}`,x=Object.prototype.toString.call(o)==="[object Error]",S=x?`${R}
|
|
@@ -18,7 +18,7 @@ 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;v("temperature",/^(2|\d)(\.\d{1,2})?$/.test(e),"Must be decimal between 0 and 2");const t=Number(e);return v("temperature",t>0,"Must be greater than 0"),v("temperature",t<=2,"Must be less than or equal to 2"),t},maxTokens:e=>{if(e)return v("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;v("topP",/^(1|\d)(\.\d{1,2})?$/.test(e),"Must be decimal between 0 and 1");const t=Number(e);return v("topP",t>0,"Must be greater than 0"),v("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:Ue("BEDROCK.inferenceParameters"),diffCompression:i.diffCompression,maxHunkLines:i.maxHunkLines,maxDiffLines:i.maxDiffLines,diffContext:i.diffContext}},Pa=e=>typeof e=="object"&&e!==null,vo=(e,t)=>{Object.keys(e).forEach(n=>{const o=e[n];Pa(o)&&t in o&&(o[t]=!0)})},Aa=e=>{vo(e,"includeBody")},xa=e=>{vo(e,"disableLowerCase")};let Ae,xe=null,Ft=null;const Sa=(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 Pe?(t[r]||(t[r]={}),t[r][a]=s):t[o]=s}return t},$a=()=>{const e=Ie.homedir(),t=process.env.AICOMMIT_CONFIG_PATH,n=Co,o=P.join(e,".aicommit2");return[t,n,o].filter(s=>!!s)},me=async()=>{const e=$a();for(const t of e)if(await Be(t))return t;return Co},Ra=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]??""}),Po=e=>{if(Array.isArray(e)||e===null||typeof e!="object")return e;const t={};for(const[n,o]of Object.entries(e)){const s=Po(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},Se=async()=>{const e=await me();if(xe&&Ft===e)return xe;Ae=e;try{const t=await I.readFile(e,"utf8"),n=Ra(t);return xe=Po(le.parse(n)),Ft=e,xe}catch(t){return t.code==="ENOENT"?(Ae=void 0,{}):(console.error(`Error reading config file ${e}:`,t),Ae=void 0,{})}},Ao=()=>{xe=null,Ft=null},X=async(e,t=[])=>{const n=await Se(),o=Sa(t),s={...e,...o},r={},a=va(n),c={};for(const u of a){const d=n[u]?.envKey;let m;d?(m=[d],u==="BEDROCK"&&d!=="BEDROCK_APPLICATION_API_KEY"&&m.push("BEDROCK_APPLICATION_API_KEY")):u==="BEDROCK"?m=["BEDROCK_API_KEY","BEDROCK_APPLICATION_API_KEY"]:m=[`${u}_API_KEY`];const g=m.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 m=s[`${u}.${d}`]??s[u]?.[d],g=c[u]?.[d],y=n[u]?.[d],f=s[d]??n[d];return m!==void 0?m:g!==void 0?g:y!==void 0?y:f};for(const[u,d]of Object.entries(i)){const m=s[u]??n[u];r[u]=d(m)}for(const u of a){r[u]={};const d=Pe[u]||We(u);for(const[m,g]of Object.entries(d)){const y=l(u,m);r[u][m]=g(y)}}return r},Ke=async e=>{const t=await Se();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]={}),de.includes(a)){const d=Pe[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=We(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 me(),o=P.dirname(n);await I.mkdir(o,{recursive:!0}),await I.writeFile(n,le.stringify(t),"utf8"),Ao()},Ia=async e=>{const t=await Se();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]||[],m=typeof r=="string"?r.split(",").map(g=>g.trim()).filter(g=>!!g):r;t[a][c]=_t([...d,...m]);continue}if(l&&l.compatible===!0){l||(t[a]={});const d=We(a);if(!d[c])throw new p(`Invalid config property: ${s}`);try{t[a][c]=d[c](r)}catch(m){throw m instanceof p?m:new p(`Invalid value for ${s}: ${m.message}`)}continue}if(a in Pe){l||(t[a]={});const d=Pe[a][c];if(!d)throw new p(`Invalid config property: ${s}`);t[a][c]=d(r)}else{const d=We(a);if(!d[c])throw new p(`Invalid config property: ${s}`);t[a]||(t[a]={}),t[a][c]=d[c](r)}}const n=await me(),o=P.dirname(n);await I.mkdir(o,{recursive:!0}),await I.writeFile(n,le.stringify(t),"utf8"),Ao()},ka=async()=>{const e=await Se();console.log(le.stringify(e))},La=async()=>{console.log(await me())},We=e=>({compatible:F("compatible"),stream:F("stream"),url:t=>t?(v(`${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}),D=e=>typeof e=="string"&&e.trim().length>0,Ma=()=>{try{const e=typeof pt<"u"?pt.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 Gt;const Ta=e=>Y(e)?(Gt===void 0&&(Gt=Ma()),Gt):!1,Y=e=>(Array.isArray(e.model)?e.model:D(e.model)?[e.model.trim()]:[]).length>0,qe=e=>{const t=D(e.key),n=D(e.region)||D(process.env.AWS_REGION)||D(process.env.AWS_DEFAULT_REGION),o=D(e.profile)||D(process.env.AWS_PROFILE),s=D(e.accessKeyId)&&D(e.secretAccessKey)||D(process.env.AWS_ACCESS_KEY_ID)&&D(process.env.AWS_SECRET_ACCESS_KEY),r=D(e.applicationBaseUrl)||D(process.env.BEDROCK_APPLICATION_BASE_URL),a=D(e.applicationEndpointId)||D(process.env.BEDROCK_APPLICATION_ENDPOINT_ID),c=D(process.env.BEDROCK_APPLICATION_API_KEY);return n&&(t||o||s)||(r&&t||a&&c)},fe=(e,t)=>Object.entries(e).map(([n,o])=>[n,o]).filter(([n,o])=>!o.disabled).filter(([n,o])=>de.includes(n)||o.compatible===!0).filter(([n,o])=>{switch(t){case"commit":return n==="OLLAMA"?!!o&&Y(o):n==="COPILOT_SDK"?!!o&&Ta(o):n==="HUGGINGFACE"?!!o&&!!o.cookie:n==="BEDROCK"?Y(o)&&qe(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)&&qe(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)&&qe(o)&&r:o.compatible?!!o.url&&!!o.key&&r:!!o.key&&o.key.length>0&&r}}).map(([n])=>n);class Oa{static create(t,n){return new t(n)}}const Da="stats.json",ze=2,Na=30,Bt=()=>P.join(wo,Da),Ye=async()=>{const e=Bt();if(!await Be(e))return{version:ze,metrics:[],selections:[]};try{const t=await I.readFile(e,"utf-8"),n=JSON.parse(t);return!n.version||n.version<ze?{version:ze,metrics:n.metrics||[],selections:n.selections||[]}:n}catch{return{version:ze,metrics:[],selections:[]}}},_a=(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)}},xo=async(e,t)=>{const n=Bt(),o=P.dirname(n),s=t?_a(e,t):e;await I.mkdir(o,{recursive:!0}),await I.writeFile(n,JSON.stringify(s,null,2),"utf-8")},ja=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 Ye();n.metrics.push(t),await xo(n,e.statsDays)},Fa=async e=>{const t={timestamp:Date.now(),provider:e.provider,model:e.model},n=await Ye();n.selections.push(t),await xo(n,e.statsDays)},Ga=(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)}},Ba=async(e=Na)=>{const t=await Ye(),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=>Ga(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))}},Ha=async()=>{const e=Bt();await Be(e)&&await I.unlink(e)},Ua=async()=>(await Ye()).metrics.length>0,So=(e,t)=>{const n=h.red.bold(`[${e}]`);return Es({name:`${n} ${t}`,value:t,isError:!0,disabled:!0})},$o=e=>{let t=!1;return vs({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};ja(s).catch(()=>{})}})};class Ka{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 ke(this.createService(t,n)).pipe(mn(a=>a?(o==="commit"?a.generateCommitMessage$():a.generateCodeReview$()).pipe($o({provider:t,model:r||"unknown",startTime:s,statsEnabled:n.statsEnabled,statsDays:n.statsDays})):So(t,"Invalid AI type")))},this.registerBuiltinProviders=()=>{this.loaders.set("OPENAI",()=>import("./openai.service-302b8175.mjs").then(t=>t.OpenAIService)),this.loaders.set("COPILOT_SDK",()=>import("./copilot-sdk.service-d1ea1c28.mjs").then(t=>t.CopilotSdkService)),this.loaders.set("OPENROUTER",()=>import("./openrouter.service-2b8fbca1.mjs").then(t=>t.OpenRouterService)),this.loaders.set("GEMINI",()=>import("./gemini.service-d388f388.mjs").then(t=>t.GeminiService)),this.loaders.set("ANTHROPIC",()=>import("./anthropic.service-c1c51fcc.mjs").then(t=>t.AnthropicService)),this.loaders.set("HUGGINGFACE",()=>import("./hugging-face.service-e09db43f.mjs").then(t=>t.HuggingFaceService)),this.loaders.set("MISTRAL",()=>import("./mistral.service-7251283a.mjs").then(t=>t.MistralService)),this.loaders.set("CODESTRAL",()=>import("./codestral.service-12ba24c3.mjs").then(t=>t.CodestralService)),this.loaders.set("OLLAMA",()=>import("./ollama.service-e8633778.mjs").then(t=>t.OllamaService)),this.loaders.set("COHERE",()=>import("./cohere.service-8c4441c5.mjs").then(t=>t.CohereService)),this.loaders.set("GROQ",()=>import("./groq.service-61f21765.mjs").then(t=>t.GroqService)),this.loaders.set("PERPLEXITY",()=>import("./perplexity.service-53baa468.mjs").then(t=>t.PerplexityService)),this.loaders.set("BEDROCK",()=>import("./bedrock.service-3d914394.mjs").then(t=>t.BedrockService)),this.loaders.set("GITHUB_MODELS",()=>import("./github-models.service-04f6badc.mjs").then(t=>t.GitHubModelsService)),this.loaders.set("DEEPSEEK",()=>import("./deep-seek.service-d2bde249.mjs").then(t=>t.DeepSeekService))},this.registerBuiltinProviders()}}const Wa=new Ka;class Ht{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 Ve extends Ht{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 E("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;v("temperature",/^(2|\d)(\.\d{1,2})?$/.test(e),"Must be decimal between 0 and 2");const t=Number(e);return v("temperature",t>0,"Must be greater than 0"),v("temperature",t<=2,"Must be less than or equal to 2"),t},maxTokens:e=>{if(e)return v("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;v("topP",/^(1|\d)(\.\d{1,2})?$/.test(e),"Must be decimal between 0 and 1");const t=Number(e);return v("topP",t>0,"Must be greater than 0"),v("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:Ue("BEDROCK.inferenceParameters"),diffCompression:i.diffCompression,maxHunkLines:i.maxHunkLines,maxDiffLines:i.maxDiffLines,diffContext:i.diffContext}},Pa=e=>typeof e=="object"&&e!==null,vo=(e,t)=>{Object.keys(e).forEach(n=>{const o=e[n];Pa(o)&&t in o&&(o[t]=!0)})},Aa=e=>{vo(e,"includeBody")},xa=e=>{vo(e,"disableLowerCase")};let Ae,xe=null,Ft=null;const Sa=(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 Pe?(t[r]||(t[r]={}),t[r][a]=s):t[o]=s}return t},$a=()=>{const e=Ie.homedir(),t=process.env.AICOMMIT_CONFIG_PATH,n=Co,o=P.join(e,".aicommit2");return[t,n,o].filter(s=>!!s)},me=async()=>{const e=$a();for(const t of e)if(await Be(t))return t;return Co},Ra=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]??""}),Po=e=>{if(Array.isArray(e)||e===null||typeof e!="object")return e;const t={};for(const[n,o]of Object.entries(e)){const s=Po(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},Se=async()=>{const e=await me();if(xe&&Ft===e)return xe;Ae=e;try{const t=await I.readFile(e,"utf8"),n=Ra(t);return xe=Po(le.parse(n)),Ft=e,xe}catch(t){return t.code==="ENOENT"?(Ae=void 0,{}):(console.error(`Error reading config file ${e}:`,t),Ae=void 0,{})}},Ao=()=>{xe=null,Ft=null},X=async(e,t=[])=>{const n=await Se(),o=Sa(t),s={...e,...o},r={},a=va(n),c={};for(const u of a){const d=n[u]?.envKey;let m;d?(m=[d],u==="BEDROCK"&&d!=="BEDROCK_APPLICATION_API_KEY"&&m.push("BEDROCK_APPLICATION_API_KEY")):u==="BEDROCK"?m=["BEDROCK_API_KEY","BEDROCK_APPLICATION_API_KEY"]:m=[`${u}_API_KEY`];const g=m.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 m=s[`${u}.${d}`]??s[u]?.[d],g=c[u]?.[d],y=n[u]?.[d],f=s[d]??n[d];return m!==void 0?m:g!==void 0?g:y!==void 0?y:f};for(const[u,d]of Object.entries(i)){const m=s[u]??n[u];r[u]=d(m)}for(const u of a){r[u]={};const d=Pe[u]||We(u);for(const[m,g]of Object.entries(d)){const y=l(u,m);r[u][m]=g(y)}}return r},Ke=async e=>{const t=await Se();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]={}),de.includes(a)){const d=Pe[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=We(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 me(),o=P.dirname(n);await I.mkdir(o,{recursive:!0}),await I.writeFile(n,le.stringify(t),"utf8"),Ao()},Ia=async e=>{const t=await Se();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]||[],m=typeof r=="string"?r.split(",").map(g=>g.trim()).filter(g=>!!g):r;t[a][c]=_t([...d,...m]);continue}if(l&&l.compatible===!0){l||(t[a]={});const d=We(a);if(!d[c])throw new p(`Invalid config property: ${s}`);try{t[a][c]=d[c](r)}catch(m){throw m instanceof p?m:new p(`Invalid value for ${s}: ${m.message}`)}continue}if(a in Pe){l||(t[a]={});const d=Pe[a][c];if(!d)throw new p(`Invalid config property: ${s}`);t[a][c]=d(r)}else{const d=We(a);if(!d[c])throw new p(`Invalid config property: ${s}`);t[a]||(t[a]={}),t[a][c]=d[c](r)}}const n=await me(),o=P.dirname(n);await I.mkdir(o,{recursive:!0}),await I.writeFile(n,le.stringify(t),"utf8"),Ao()},ka=async()=>{const e=await Se();console.log(le.stringify(e))},La=async()=>{console.log(await me())},We=e=>({compatible:F("compatible"),stream:F("stream"),url:t=>t?(v(`${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}),D=e=>typeof e=="string"&&e.trim().length>0,Ma=()=>{try{const e=typeof pt<"u"?pt.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 Gt;const Ta=e=>Y(e)?(Gt===void 0&&(Gt=Ma()),Gt):!1,Y=e=>(Array.isArray(e.model)?e.model:D(e.model)?[e.model.trim()]:[]).length>0,qe=e=>{const t=D(e.key),n=D(e.region)||D(process.env.AWS_REGION)||D(process.env.AWS_DEFAULT_REGION),o=D(e.profile)||D(process.env.AWS_PROFILE),s=D(e.accessKeyId)&&D(e.secretAccessKey)||D(process.env.AWS_ACCESS_KEY_ID)&&D(process.env.AWS_SECRET_ACCESS_KEY),r=D(e.applicationBaseUrl)||D(process.env.BEDROCK_APPLICATION_BASE_URL),a=D(e.applicationEndpointId)||D(process.env.BEDROCK_APPLICATION_ENDPOINT_ID),c=D(process.env.BEDROCK_APPLICATION_API_KEY);return n&&(t||o||s)||(r&&t||a&&c)},fe=(e,t)=>Object.entries(e).map(([n,o])=>[n,o]).filter(([n,o])=>!o.disabled).filter(([n,o])=>de.includes(n)||o.compatible===!0).filter(([n,o])=>{switch(t){case"commit":return n==="OLLAMA"?!!o&&Y(o):n==="COPILOT_SDK"?!!o&&Ta(o):n==="HUGGINGFACE"?!!o&&!!o.cookie:n==="BEDROCK"?Y(o)&&qe(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)&&qe(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)&&qe(o)&&r:o.compatible?!!o.url&&!!o.key&&r:!!o.key&&o.key.length>0&&r}}).map(([n])=>n);class Oa{static create(t,n){return new t(n)}}const Da="stats.json",ze=2,Na=30,Bt=()=>P.join(wo,Da),Ye=async()=>{const e=Bt();if(!await Be(e))return{version:ze,metrics:[],selections:[]};try{const t=await I.readFile(e,"utf-8"),n=JSON.parse(t);return!n.version||n.version<ze?{version:ze,metrics:n.metrics||[],selections:n.selections||[]}:n}catch{return{version:ze,metrics:[],selections:[]}}},_a=(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)}},xo=async(e,t)=>{const n=Bt(),o=P.dirname(n),s=t?_a(e,t):e;await I.mkdir(o,{recursive:!0}),await I.writeFile(n,JSON.stringify(s,null,2),"utf-8")},ja=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 Ye();n.metrics.push(t),await xo(n,e.statsDays)},Fa=async e=>{const t={timestamp:Date.now(),provider:e.provider,model:e.model},n=await Ye();n.selections.push(t),await xo(n,e.statsDays)},Ga=(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)}},Ba=async(e=Na)=>{const t=await Ye(),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=>Ga(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))}},Ha=async()=>{const e=Bt();await Be(e)&&await I.unlink(e)},Ua=async()=>(await Ye()).metrics.length>0,So=(e,t)=>{const n=h.red.bold(`[${e}]`);return Es({name:`${n} ${t}`,value:t,isError:!0,disabled:!0})},$o=e=>{let t=!1;return vs({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};ja(s).catch(()=>{})}})};class Ka{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 ke(this.createService(t,n)).pipe(mn(a=>a?(o==="commit"?a.generateCommitMessage$():a.generateCodeReview$()).pipe($o({provider:t,model:r||"unknown",startTime:s,statsEnabled:n.statsEnabled,statsDays:n.statsDays})):So(t,"Invalid AI type")))},this.registerBuiltinProviders=()=>{this.loaders.set("OPENAI",()=>import("./openai.service-ca071f6c.mjs").then(t=>t.OpenAIService)),this.loaders.set("COPILOT_SDK",()=>import("./copilot-sdk.service-f1cc1873.mjs").then(t=>t.CopilotSdkService)),this.loaders.set("OPENROUTER",()=>import("./openrouter.service-2e239655.mjs").then(t=>t.OpenRouterService)),this.loaders.set("GEMINI",()=>import("./gemini.service-c9b02d26.mjs").then(t=>t.GeminiService)),this.loaders.set("ANTHROPIC",()=>import("./anthropic.service-fb44d54e.mjs").then(t=>t.AnthropicService)),this.loaders.set("HUGGINGFACE",()=>import("./hugging-face.service-2c8f4576.mjs").then(t=>t.HuggingFaceService)),this.loaders.set("MISTRAL",()=>import("./mistral.service-7a553113.mjs").then(t=>t.MistralService)),this.loaders.set("CODESTRAL",()=>import("./codestral.service-f6ae65a5.mjs").then(t=>t.CodestralService)),this.loaders.set("OLLAMA",()=>import("./ollama.service-31b2908b.mjs").then(t=>t.OllamaService)),this.loaders.set("COHERE",()=>import("./cohere.service-af885cf7.mjs").then(t=>t.CohereService)),this.loaders.set("GROQ",()=>import("./groq.service-180e7478.mjs").then(t=>t.GroqService)),this.loaders.set("PERPLEXITY",()=>import("./perplexity.service-fe8bfcd5.mjs").then(t=>t.PerplexityService)),this.loaders.set("BEDROCK",()=>import("./bedrock.service-40cbd1e5.mjs").then(t=>t.BedrockService)),this.loaders.set("GITHUB_MODELS",()=>import("./github-models.service-becd2e94.mjs").then(t=>t.GitHubModelsService)),this.loaders.set("DEEPSEEK",()=>import("./deep-seek.service-de8b4395.mjs").then(t=>t.DeepSeekService))},this.registerBuiltinProviders()}}const Wa=new Ka;class Ht{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 Ve extends Ht{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 E("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`)},ne=async()=>(Wt||(Wt=await qa()),Wt);let $e=null;const Ro=async()=>{if($e!==null)return $e;try{$e=(await X({})).diffContext}catch{$e=ue}return $e},Io=(e,t)=>{const{diff:n,stats:o}=ra(e.diff,t);return n===e.diff?e:{...e,diff:n,compression:o}},qt=async()=>(await ne()).assertRepo(),zt=async(e,t)=>{const n=await ne(),o=await Ro(),s=await n.getStagedDiff(e,t,{diffContext:o});return s||null},za=async(e,t,n)=>{const o=await ne();if(!o.getCommitDiff)throw new p(`Commit diff not supported for ${o.name}`);const s=await Ro(),r=await o.getCommitDiff(e,t,n,{diffContext:s});return r||null},Ya=async()=>(await ne()).getCommentChar(),Va=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)`},Je=async()=>(await ne()).name,Ja=async(e,t,n)=>{await(await ne()).commit(e,t||[],n)},Xe=async()=>(await ne()).getBranchName();class Qe{constructor(t,n,o=""){this.config=t,this.stagedDiff=n,this.branchName=o,this.getDiffForModel=s=>{const r={mode:s.diffCompression||"none",maxHunkLines:s.maxHunkLines||0,maxDiffLines:s.maxDiffLines||0};return Io(this.stagedDiff,r)},this.extractProviderName=s=>{if(!s)return"compatible";try{return new URL(s).hostname}catch{return"compatible"}},this.createCommitMsgRequests$=s=>this.createServiceRequests$(s,"commit"),this.createCodeReviewRequests$=s=>this.createServiceRequests$(s,"review"),this.createServiceRequests$=(s,r)=>ke(s).pipe(fn(a=>this.createProviderRequests$(a,r)),Ps(a=>So("UNKNOWN",a.message||"Unknown error"))),this.createProviderRequests$=(s,r)=>{const a=this.config[s],c=Array.isArray(a.model)?a.model:[a.model];return ke(c).pipe(fn(l=>this.createModelRequest$(s,l,r)))},this.createModelRequest$=(s,r,a)=>{const c=this.config[s];if(c.compatible)return this.createCompatibleServiceRequest$(c,r,a);const l=this.getDiffForModel(c);return Wa.createRequest$(s,{config:{...c,model:r},stagedDiff:l,keyName:r,branchName:this.branchName,statsEnabled:this.config.useStats,statsDays:this.config.statsDays,modelNameDisplay:this.config.modelNameDisplay},a)},this.createCompatibleServiceRequest$=(s,r,a)=>{const c=Date.now(),l=this.extractProviderName(s.url),u=this.getDiffForModel(s);return ke(import("./openai-compatible.service-
|
|
151
|
+
\u2022 Set forceGit=true in config file to prefer Git detection`)},ne=async()=>(Wt||(Wt=await qa()),Wt);let $e=null;const Ro=async()=>{if($e!==null)return $e;try{$e=(await X({})).diffContext}catch{$e=ue}return $e},Io=(e,t)=>{const{diff:n,stats:o}=ra(e.diff,t);return n===e.diff?e:{...e,diff:n,compression:o}},qt=async()=>(await ne()).assertRepo(),zt=async(e,t)=>{const n=await ne(),o=await Ro(),s=await n.getStagedDiff(e,t,{diffContext:o});return s||null},za=async(e,t,n)=>{const o=await ne();if(!o.getCommitDiff)throw new p(`Commit diff not supported for ${o.name}`);const s=await Ro(),r=await o.getCommitDiff(e,t,n,{diffContext:s});return r||null},Ya=async()=>(await ne()).getCommentChar(),Va=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)`},Je=async()=>(await ne()).name,Ja=async(e,t,n)=>{await(await ne()).commit(e,t||[],n)},Xe=async()=>(await ne()).getBranchName();class Qe{constructor(t,n,o=""){this.config=t,this.stagedDiff=n,this.branchName=o,this.getDiffForModel=s=>{const r={mode:s.diffCompression||"none",maxHunkLines:s.maxHunkLines||0,maxDiffLines:s.maxDiffLines||0};return Io(this.stagedDiff,r)},this.extractProviderName=s=>{if(!s)return"compatible";try{return new URL(s).hostname}catch{return"compatible"}},this.createCommitMsgRequests$=s=>this.createServiceRequests$(s,"commit"),this.createCodeReviewRequests$=s=>this.createServiceRequests$(s,"review"),this.createServiceRequests$=(s,r)=>ke(s).pipe(fn(a=>this.createProviderRequests$(a,r)),Ps(a=>So("UNKNOWN",a.message||"Unknown error"))),this.createProviderRequests$=(s,r)=>{const a=this.config[s],c=Array.isArray(a.model)?a.model:[a.model];return ke(c).pipe(fn(l=>this.createModelRequest$(s,l,r)))},this.createModelRequest$=(s,r,a)=>{const c=this.config[s];if(c.compatible)return this.createCompatibleServiceRequest$(c,r,a);const l=this.getDiffForModel(c);return Wa.createRequest$(s,{config:{...c,model:r},stagedDiff:l,keyName:r,branchName:this.branchName,statsEnabled:this.config.useStats,statsDays:this.config.statsDays,modelNameDisplay:this.config.modelNameDisplay},a)},this.createCompatibleServiceRequest$=(s,r,a)=>{const c=Date.now(),l=this.extractProviderName(s.url),u=this.getDiffForModel(s);return ke(import("./openai-compatible.service-2bea7313.mjs")).pipe(mn(({OpenAICompatibleService:d})=>{const m=Oa.create(d,{config:{...s,url:s.url||"",path:s.path||"",model:r},stagedDiff:u,keyName:r,branchName:this.branchName,modelNameDisplay:this.config.modelNameDisplay});return(a==="commit"?m.generateCommitMessage$():m.generateCodeReview$()).pipe($o({provider:l,model:r,startTime:c,statsEnabled:this.config.useStats,statsDays:this.config.statsDays}))}))}}}const Xa=1e5;class U{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=yn.textSync(this.title,{font:"Small Slant"}),n=Ss(["#8B5CF6","#A020F0","#D946EF"]);console.log(h.bold(n.multiline(t)))}catch{console.log(h.bold(yn.textSync(this.title,{font:"Small Slant"})))}}showLoader(t){if(this.loader){this.loader.text=t;return}this.loader=wn(t).start()}stopLoader(){this.loader?.stop(),this.loader=void 0}displaySpinner(t){return wn(t).start()}stopSpinner(t){t.stop(),t.clear()}printStagedFiles(t,n){const o=Buffer.byteLength(t.diff,"utf8"),s=this.formatBytes(o),r=Va(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>Xa&&!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(`
|
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-d193cf90.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 f from"chalk";import{concatMap as u,from as g,map as C,catchError as y}from"rxjs";import{fromPromise as v}from"rxjs/internal/observable/innerFrom";import{A as b,l as k,a as R,b as x,c as _,e as P,d as S}from"./ai.service-
|
|
1
|
+
import f from"chalk";import{concatMap as u,from as g,map as C,catchError as y}from"rxjs";import{fromPromise as v}from"rxjs/internal/observable/innerFrom";import{A as b,l as k,a as R,b as x,c as _,e as P,d as S}from"./ai.service-f59388bb.mjs";import{D as $,b as D,g as E,k as A,n as N,H as B}from"./cli-d193cf90.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 b{constructor(t){super(t),this.params=t,this.apiKey="",this.colors={primary:"#e28c58",secondary:"#fff"},this.serviceName=f.bgHex(this.colors.primary).hex(this.colors.secondary).bold(`[Codestral${this.formatModelSuffix()}]`),this.errorPrefix=f.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 v(this.generateMessage("commit")).pipe(u(t=>g(t)),C(this.formatAsChoice),y(this.handleError$))}generateCodeReview$(){return v(this.generateMessage("review")).pipe(u(t=>g(t)),C(this.formatCodeReviewAsChoice),y(this.handleError$))}async generateMessage(t){const e=this.params.stagedDiff.diff,{systemPrompt:r,systemPromptPath:s,codeReviewPromptPath:c,logging:i,locale:l,generate:a,type:n,maxLength:p}=this.params.config,o={...$,locale:l,maxLength:p,type:n,generate:a,systemPrompt:r,systemPromptPath:s,codeReviewPromptPath:c,vcs_branch:this.params.branchName||""},d=t==="review"?D(o):E(o);this.checkAvailableModels();const m=A(e,t),I=`${this.params.config.url||"https://codestral.mistral.ai"}/v1/chat/completions`,M={Authorization:`Bearer ${this.apiKey}`,"content-type":"application/json"};k(e,t,"Codestral",this.params.config.model,I,M,i),R(e,t,"Codestral",d,m,i);const h=await this.createChatCompletions(d,t);return t==="review"?this.parseCodeReview(h):this.parseMessage(h,n,a)}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 r=this.params.stagedDiff.diff,{logging:s}=this.params.config,c=this.params.config.url||"https://codestral.mistral.ai",i={model:this.params.config.model,messages:[{role:"system",content:t},{role:"user",content:A(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:N(10,1e3)};e==="commit"&&(i.response_format={type:"json_object"}),x(r,e,"Codestral",i,s);const l=Date.now();try{const n=await new B({method:"POST",baseURL:`${c}/v1/chat/completions`,timeout:this.params.config.timeout}).setHeaders({Authorization:`Bearer ${this.apiKey}`,"content-type":"application/json"}).setBody(i).execute(),p=Date.now()-l,o=n.data;if(_(r,e,"Codestral",o,s),!o.choices||o.choices.length===0||!o.choices[0].message?.content)throw P(r,e,"Codestral",{message:"No Content on response",result:o},s),new Error("No Content on response. Please open a Bug report");const m=o.choices[0].message.content;return S(r,e,"Codestral",p,m,s),m}catch(a){throw P(r,e,"Codestral",a,s),a}}}export{U as CodestralService};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import h from"chalk";import{CohereClientV2 as b}from"cohere-ai";import{concatMap as d,from as l,map as f,catchError as g}from"rxjs";import{fromPromise as u}from"rxjs/internal/observable/innerFrom";import{A as E,l as S,a as $,b as D,c as _,d as N,e as V}from"./ai.service-
|
|
1
|
+
import h from"chalk";import{CohereClientV2 as b}from"cohere-ai";import{concatMap as d,from as l,map as f,catchError as g}from"rxjs";import{fromPromise as u}from"rxjs/internal/observable/innerFrom";import{A as E,l as S,a as $,b as D,c as _,d as N,e as V}from"./ai.service-f59388bb.mjs";import{D as O,b as F,g as U,n as H}from"./cli-d193cf90.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 E{constructor(r){super(r),this.params=r,this.colors={primary:"#D18EE2",secondary:"#fff"},this.serviceName=h.bgHex(this.colors.primary).hex(this.colors.secondary).bold(`[Cohere${this.formatModelSuffix()}]`),this.errorPrefix=h.red.bold(`[Cohere${this.formatModelSuffix()}]`),this.cohere=new b({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 u(this.generateMessage("commit")).pipe(d(r=>l(r)),f(this.formatAsChoice),g(this.handleError$))}generateCodeReview$(){return u(this.generateMessage("review")).pipe(d(r=>l(r)),f(this.formatCodeReviewAsChoice),g(this.handleError$))}async generateMessage(r){const e=this.params.stagedDiff.diff,{systemPrompt:C,systemPromptPath:v,codeReviewPromptPath:y,logging:o,temperature:P,locale:A,generate:n,type:a,maxLength:I,maxTokens:w}=this.params.config,m={...O,locale:A,maxLength:I,type:a,generate:n,systemPrompt:C,systemPromptPath:v,codeReviewPromptPath:y,vcs_branch:this.params.branchName||""},i=r==="review"?F(m):U(m),c=`Here is the diff: ${e}`,M=[...i?[{role:"system",content:i}]:[],{role:"user",content:c}],k=`${this.params.config.url}/v2/chat`;S(e,r,"Cohere",this.params.config.model,k,{},o),$(e,r,"Cohere",i,c,o);const p={model:this.params.config.model,messages:M,max_tokens:w,temperature:P,seed:H(10,1e3),p:this.params.config.topP};D(e,r,"Cohere",p,o);const x=Date.now();try{const t=await this.cohere.chat(p,{timeoutInSeconds:Math.floor(this.params.config.timeout/1e3)}),R=Date.now()-x;if(!this.isValidCohereV2Response(t))throw new Error("Invalid response structure from Cohere v2 API");const s=t.message.content[0].text;return _(e,r,"Cohere",t,o),N(e,r,"Cohere",R,s,o),r==="review"?this.parseCodeReview(s):this.parseMessage(s,a,n)}catch(t){throw V(e,r,"Cohere",t,o),t}}}export{L as CohereService};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import S from"chalk";import{concatMap as _,from as A,map as I,catchError as L}from"rxjs";import{fromPromise as D}from"rxjs/internal/observable/innerFrom";import{A as k,l as b,a as y,b as R,c as U,d as x,e as z}from"./ai.service-f59388bb.mjs";import{D as B,b as H,g as F}from"./cli-d193cf90.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 N="gpt-4.1",$=["gpt-4.1","gpt-4o","gpt-5-mini"],T={"openai/gpt-4.1":"gpt-4.1","openai/gpt-4o":"gpt-4o","openai/gpt-5-mini":"gpt-5-mini"},G=e=>{const o=(e||"").trim().toLowerCase();return o?o in T?T[o]:o.includes("/")&&o.split("/").pop()||o:N},j=e=>[G(e),...$].filter((t,i,r)=>r.indexOf(t)===i),w=e=>{const o=e.toLowerCase();return o.includes("unknown_model")||o.includes("unknown model")||o.includes("unavailable_model")||o.includes("unavailable model")||o.includes("model not found")||o.includes("not available")||o.includes("not enabled")||o.includes("not allowed")},K=e=>{const o=e.toLowerCase();return o.includes("auth")||o.includes("unauthorized")||o.includes("forbidden")||o.includes("token")||o.includes("copilot cli")},V=e=>{const o=e.toLowerCase();return o.includes("classic personal access tokens")&&o.includes("ghp_")},W=(e=process.env)=>{const o={...e};o.NODE_NO_WARNINGS="1",delete o.GH_TOKEN,delete o.GITHUB_TOKEN;const t=(e.COPILOT_GITHUB_TOKEN||"").trim();return t.length>0?(o.COPILOT_GITHUB_TOKEN=t,{githubToken:t,useLoggedInUser:!1,env:o}):(delete o.COPILOT_GITHUB_TOKEN,{useLoggedInUser:!0,env:o})};class q extends k{constructor(o){super(o),this.params=o,this.colors={primary:"#1f6feb",secondary:"#FFF"},this.serviceName=S.bgHex(this.colors.primary).hex(this.colors.secondary).bold(`[Copilot SDK${this.formatModelSuffix()}]`),this.errorPrefix=S.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":V(t)?"Copilot rejected classic ghp_ token. Use COPILOT_GITHUB_TOKEN with a Fine-Grained PAT or authenticate via copilot /login.":o.code==="AUTHENTICATION_FAILED"||K(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"||w(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 D(this.generateMessage("commit")).pipe(_(o=>A(o)),I(this.formatAsChoice),L(this.handleError$))}generateCodeReview$(){return D(this.generateMessage("review")).pipe(_(o=>A(o)),I(this.formatCodeReviewAsChoice),L(this.handleError$))}async generateMessage(o){const t=this.params.stagedDiff.diff,{systemPrompt:i,systemPromptPath:r,codeReviewPromptPath:a,locale:l,generate:g,type:c,maxLength:s}=this.params.config,m={...B,locale:l,maxLength:s,type:c,generate:g,systemPrompt:i,systemPromptPath:r,codeReviewPromptPath:a,vcs_branch:this.params.branchName||""},p=o==="review"?H(m):F(m),E=o==="review"?t:`Here's the diff:
|
|
2
|
+
|
|
3
|
+
${t}`,h=await this.makeRequest(p,E,o,t);return o==="review"?this.parseCodeReview(h):this.parseMessage(h,c,g)}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,i=t.data,r=t.content,a=i?.content;if(typeof r=="string")return r.trim();if(typeof a=="string")return a.trim();const l=i?.message?.content;return typeof l=="string"?l.trim():""}async makeRequest(o,t,i,r){const{CopilotClient:a,approveAll:l}=await this.loadSdkModule(),g=Array.isArray(this.params.config.model)?this.params.config.model[0]:this.params.config.model||N,c=j(g),{logging:s}=this.params.config;let m;for(const p of c){const E="copilot-sdk://session",h={Authorization:"Copilot CLI session"},M={model:p,prompt:t};b(r,i,"Copilot SDK",p,E,h,s),y(r,i,"Copilot SDK",o,t,s),R(r,i,"Copilot SDK",M,s);const P=Date.now();let f;try{const d=W(process.env);f=new a(d);const u=await(await f.createSession({model:p,onPermissionRequest:l})).sendAndWait({prompt:`${o}
|
|
4
|
+
|
|
5
|
+
${t}`}),C=this.extractContent(u);if(!C){const O=new Error("No content in Copilot SDK response");throw O.code="NO_CONTENT",O}const v=Date.now()-P;return U(r,i,"Copilot SDK",u,s),x(r,i,"Copilot SDK",v,C,s),C}catch(d){const n=d instanceof Error?d:new Error(String(d)),u=n.message||String(d);if(!n.code&&K(u)&&(n.code="AUTHENTICATION_FAILED"),!n.code&&w(u)&&(n.code="MODEL_NOT_AVAILABLE"),z(r,i,"Copilot SDK",n,s),m=n,!(n.code==="MODEL_NOT_AVAILABLE"&&p!==c[c.length-1]))throw n}finally{f?.stop&&await f.stop()}}throw m||new Error("Copilot SDK request failed for all candidate models")}}export{q as CopilotSdkService};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import v from"chalk";import K from"openai";import{concatMap as w,from as A,map as C,catchError as M}from"rxjs";import{fromPromise as I}from"rxjs/internal/observable/innerFrom";import{A as W,l as b,a as x,b as $,c as R,d as _,e as E}from"./ai.service-
|
|
1
|
+
import v from"chalk";import K from"openai";import{concatMap as w,from as A,map as C,catchError as M}from"rxjs";import{fromPromise as I}from"rxjs/internal/observable/innerFrom";import{A as W,l as b,a as x,b as $,c as R,d as _,e as E}from"./ai.service-f59388bb.mjs";import{D as U,g as O,b as Y,k as L}from"./cli-d193cf90.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 G extends W{constructor(t){super(t),this.params=t,this.generateStreamingCommitMessage$=()=>{const{generate:s,type:o}=this.params.config;return this.createStreamingCommitMessages$(i=>{this.streamChunks(i).catch(a=>i.error(a))},o,s)},this.streamChunks=async s=>{const o=this.params.stagedDiff.diff,{systemPrompt:i,systemPromptPath:a,codeReviewPromptPath:p,logging:r,locale:c,generate:m,type:n,maxLength:l}=this.params.config,h={...U,locale:c,maxLength:l,type:n,generate:m,systemPrompt:i,systemPromptPath:a,codeReviewPromptPath:p,vcs_branch:this.params.branchName||""},f=O(h);this.checkAvailableModels();const d=L(o,"commit"),g=`${this.params.config.url||"https://api.deepseek.com"}/chat/completions`,N={Authorization:`Bearer ${this.params.config.key}`,"Content-Type":"application/json"};b(o,"commit","DeepSeek",this.params.config.model,g,N,r),x(o,"commit","DeepSeek",f,d,r);const D={messages:[{role:"system",content:f},{role:"user",content:d}],model:this.params.config.model,max_tokens:this.params.config.maxTokens,top_p:this.params.config.topP,temperature:this.params.config.temperature,stream:!0};$(o,"commit","DeepSeek",D,r);const T=Date.now();let u="";try{const F=await this.deepSeek.chat.completions.create(D,{timeout:this.params.config.timeout});for await(const P of F){const B=P.choices?.[0]?.delta?.content||"",H=P.choices?.[0]?.delta?.reasoning_content||"",S=`${B}${H}`;S&&(u+=S,s.next(S))}const z=Date.now()-T;R(o,"commit","DeepSeek",{streamed:!0,totalLength:u.length},r),_(o,"commit","DeepSeek",z,u,r),s.complete()}catch(k){E(o,"commit","DeepSeek",k,r),s.error(k)}},this.colors={primary:"#53a3f9",secondary:"#fff"},this.serviceName=v.bgHex(this.colors.primary).hex(this.colors.secondary).bold(`[DeepSeek${this.formatModelSuffix()}]`),this.errorPrefix=v.red.bold(`[DeepSeek${this.formatModelSuffix()}]`);const e=this.params.config.url||"https://api.deepseek.com";this.deepSeek=new K({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$():I(this.generateMessage("commit")).pipe(w(e=>A(e)),C(this.formatAsChoice),M(this.handleError$))}generateCodeReview$(){return I(this.generateMessage("review")).pipe(w(t=>A(t)),C(this.formatCodeReviewAsChoice),M(this.handleError$))}async generateMessage(t){const e=this.params.stagedDiff.diff,{systemPrompt:s,systemPromptPath:o,codeReviewPromptPath:i,logging:a,locale:p,generate:r,type:c,maxLength:m}=this.params.config,n={...U,locale:p,maxLength:m,type:c,generate:r,systemPrompt:s,systemPromptPath:o,codeReviewPromptPath:i,vcs_branch:this.params.branchName||""},l=t==="review"?Y(n):O(n);this.checkAvailableModels();const h=L(e,t),d=`${this.params.config.url||"https://api.deepseek.com"}/chat/completions`,y={Authorization:`Bearer ${this.params.config.key}`,"Content-Type":"application/json"};b(e,t,"DeepSeek",this.params.config.model,d,y,a),x(e,t,"DeepSeek",l,h,a);const g=await this.createChatCompletions(l,h,t);return t==="review"?this.parseCodeReview(g):this.parseMessage(g,c,r)}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:i}=this.params.config,a={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};$(o,s,"DeepSeek",a,i);const p=Date.now();try{const r=await this.deepSeek.chat.completions.create(a,{timeout:this.params.config.timeout}),c=Date.now()-p,m=r.choices?.[0];if(!m?.message)throw new Error("DeepSeek API returned invalid response structure");const n=m.message.content||m.message.reasoning_content||"";if(!n)throw new Error("DeepSeek API returned empty response");return R(o,s,"DeepSeek",r,i),_(o,s,"DeepSeek",c,n,i),n}catch(r){throw E(o,s,"DeepSeek",r,i),r}}}export{G as DeepSeekService};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{HarmCategory as n,HarmBlockThreshold as a,GoogleGenerativeAI as W}from"@google/generative-ai";import S from"chalk";import{concatMap as x,from as v,map as L,catchError as N}from"rxjs";import{fromPromise as w}from"rxjs/internal/observable/innerFrom";import{A as X,l as D,a as b,b as B,c as H,d as $,e as Y}from"./ai.service-
|
|
1
|
+
import{HarmCategory as n,HarmBlockThreshold as a,GoogleGenerativeAI as W}from"@google/generative-ai";import S from"chalk";import{concatMap as x,from as v,map as L,catchError as N}from"rxjs";import{fromPromise as w}from"rxjs/internal/observable/innerFrom";import{A as X,l as D,a as b,b as B,c as H,d as $,e as Y}from"./ai.service-f59388bb.mjs";import{D as U,g as K,b as F,k as V}from"./cli-d193cf90.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 q extends X{constructor(t){super(t),this.params=t,this.generateStreamingCommitMessage$=()=>{const{generate:e,type:o}=this.params.config;return this.createStreamingCommitMessages$(c=>{this.streamChunks(c).catch(r=>c.error(r))},o,e)},this.streamChunks=async e=>{const o=this.params.stagedDiff.diff,{systemPrompt:c,systemPromptPath:r,codeReviewPromptPath:O,logging:i,locale:f,generate:A,type:E,maxLength:T}=this.params.config,_=this.params.config.maxTokens,h={...U,locale:f,maxLength:T,type:E,generate:A,systemPrompt:c,systemPromptPath:r,codeReviewPromptPath:O,vcs_branch:this.params.branchName||""},p=K(h),y={maxOutputTokens:_,temperature:this.params.config.temperature,topP:this.params.config.topP},u=this.genAI.getGenerativeModel({model:this.params.config.model,systemInstruction:p,generationConfig:y,safetySettings:[{category:n.HARM_CATEGORY_HATE_SPEECH,threshold:a.BLOCK_LOW_AND_ABOVE},{category:n.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:a.BLOCK_LOW_AND_ABOVE},{category:n.HARM_CATEGORY_HARASSMENT,threshold:a.BLOCK_LOW_AND_ABOVE},{category:n.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:a.BLOCK_LOW_AND_ABOVE}]}),C=V(o,"commit"),k=`${this.params.config.url||"https://generativelanguage.googleapis.com"}/v1beta/models/${this.params.config.model}:streamGenerateContent`,M={"Content-Type":"application/json","x-goog-api-key":this.params.config.key};D(o,"commit","Gemini",this.params.config.model,k,M,i),b(o,"commit","Gemini",p,C,i),B(o,"commit","Gemini",{systemInstruction:{parts:[{text:p}]},contents:[{parts:[{text:C}]}],generationConfig:y},i);const g=Date.now();let m="";try{const s=this.params.config.timeout>1e4?{request:{timeout:this.params.config.timeout}}:void 0,R=await u.generateContentStream(C,s);for await(const P of R.stream){const l=P.text();l&&(m+=l,e.next(l))}const d=Date.now()-g;H(o,"commit","Gemini",{streamed:!0,totalLength:m.length},i),$(o,"commit","Gemini",d,m,i),e.complete()}catch(s){Y(o,"commit","Gemini",s,i),e.error(s)}},this.colors={primary:"#0077FF",secondary:"#fff"},this.serviceName=S.bgHex(this.colors.primary).hex(this.colors.secondary).bold(`[Gemini${this.formatModelSuffix()}]`),this.errorPrefix=S.red.bold(`[Gemini${this.formatModelSuffix()}]`),this.genAI=new W(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$():w(this.generateMessage("commit")).pipe(x(e=>v(e)),L(this.formatAsChoice),N(this.handleError$))}generateCodeReview$(){return w(this.generateMessage("review")).pipe(x(t=>v(t)),L(this.formatCodeReviewAsChoice),N(this.handleError$))}async generateMessage(t){const e=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:c,logging:r,locale:O,codeReviewPromptPath:i,generate:f,type:A,maxLength:E}=this.params.config,T=this.params.config.maxTokens,_={...U,locale:O,maxLength:E,type:A,generate:f,systemPrompt:o,systemPromptPath:c,codeReviewPromptPath:i,vcs_branch:this.params.branchName||""},h=t==="review"?F(_):K(_),p={maxOutputTokens:T,temperature:this.params.config.temperature,topP:this.params.config.topP},y=this.genAI.getGenerativeModel({model:this.params.config.model,systemInstruction:h,generationConfig:p,safetySettings:[{category:n.HARM_CATEGORY_HATE_SPEECH,threshold:a.BLOCK_LOW_AND_ABOVE},{category:n.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:a.BLOCK_LOW_AND_ABOVE},{category:n.HARM_CATEGORY_HARASSMENT,threshold:a.BLOCK_LOW_AND_ABOVE},{category:n.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:a.BLOCK_LOW_AND_ABOVE}]}),u=V(e,t),G=`${this.params.config.url||"https://generativelanguage.googleapis.com"}/v1beta/models/${this.params.config.model}:generateContent`,k={"Content-Type":"application/json","x-goog-api-key":this.params.config.key};D(e,t,"Gemini",this.params.config.model,G,k,r),b(e,t,"Gemini",h,u,r),B(e,t,"Gemini",{systemInstruction:{parts:[{text:h}]},contents:[{parts:[{text:u}]}],generationConfig:p},r);const I=Date.now();try{const g=this.params.config.timeout>1e4?{request:{timeout:this.params.config.timeout}}:void 0,m=await y.generateContent(u,g),s=m.response;if(s.candidates?.[0]?.finishReason==="MAX_TOKENS"){const l=s.usageMetadata;throw new Error(`Response truncated: maxOutputTokens exceeded. Thinking tokens: ${l?.thoughtsTokenCount??"N/A"}, Output tokens: ${l?.candidatesTokenCount??"N/A"}. Increase maxTokens config for Gemini 2.5+ thinking models.`)}const d=s.text(),P=Date.now()-I;return H(e,t,"Gemini",{response:d,candidates:m.response.candidates,usageMetadata:m.response.usageMetadata},r),$(e,t,"Gemini",P,d,r),t==="review"?this.parseCodeReview(d):this.parseMessage(d,A,f)}catch(g){throw Y(e,t,"Gemini",g,r),g}}}export{q as GeminiService};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import D from"chalk";import{concatMap as A,from as G,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 L,b as v,e as I,c as P,d as x}from"./ai.service-
|
|
1
|
+
import D from"chalk";import{concatMap as A,from as G,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 L,b as v,e as I,c as P,d as x}from"./ai.service-f59388bb.mjs";import{G as C,D as $,b as k,g as U,q as y,r as F,t as B,u as j}from"./cli-d193cf90.mjs";import{i as V}from"./openai-dc366083.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 J extends T{constructor(r){super(r),this.params=r,this.baseURL=C,this.colors={primary:"#24292e",secondary:"#FFF"},this.serviceName=D.bgHex(this.colors.primary).hex(this.colors.secondary).bold(`[GitHub Models${this.formatModelSuffix()}]`),this.errorPrefix=D.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=>G(r)),N(this.formatAsChoice),O(this.handleError$))}generateCodeReview$(){return S(this.generateMessage("review")).pipe(A(r=>G(r)),N(this.formatCodeReviewAsChoice),O(this.handleError$))}async generateMessage(r){if(!this.params.config.key){const g=new Error("GitHub token is required for GitHub Models. Use: aicommit2 github-login");throw g.code="MISSING_TOKEN",g}const s=this.params.stagedDiff.diff,{systemPrompt:i,systemPromptPath:w,codeReviewPromptPath:m,locale:H,generate:f,type:u,maxLength:d}=this.params.config,p={...$,locale:H,maxLength:d,type:u,generate:f,systemPrompt:i,systemPromptPath:w,codeReviewPromptPath:m,vcs_branch:this.params.branchName||""},a=r==="review"?k(p):U(p),h=await this.makeRequest(a,s,r);return r==="review"?this.parseCodeReview(h):this.parseMessage(h,u,f)}async makeRequest(r,s,i){const w=Array.isArray(this.params.config.model)?this.params.config.model[0]:this.params.config.model||y;let m;try{m=F(w)}catch(o){const e=new Error(o instanceof Error?o.message:String(o));throw e.code="INVALID_MODEL_ID",e}const H=[{role:"system",content:r},{role:"user",content:i==="review"?s:`Here's the diff:
|
|
2
2
|
|
|
3
3
|
${s}`}],f=V(m),u={messages:H,model:m,stream:!1,...f?{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}},d=`${this.baseURL}${B}`,p={"Content-Type":"application/json",Accept:"application/vnd.github+json","X-GitHub-Api-Version":j,Authorization:`Bearer ${this.params.config.key}`},{logging:a}=this.params.config;R(s,i,"GitHub Models",m,d,p,a),L(s,i,"GitHub Models",r,i==="review"?s:`Here's the diff:
|
|
4
4
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import x from"chalk";import L from"groq-sdk";import{concatMap as A,from as C,map as M,catchError as S}from"rxjs";import{fromPromise as $}from"rxjs/internal/observable/innerFrom";import{A as F,l as I,a as b,b as R,c as _,d as D,e as E}from"./ai.service-
|
|
1
|
+
import x from"chalk";import L from"groq-sdk";import{concatMap as A,from as C,map as M,catchError as S}from"rxjs";import{fromPromise as $}from"rxjs/internal/observable/innerFrom";import{A as F,l as I,a as b,b as R,c as _,d as D,e as E}from"./ai.service-f59388bb.mjs";import{D as T,g as N,b as H}from"./cli-d193cf90.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 F{constructor(e){super(e),this.params=e,this.generateStreamingCommitMessage$=()=>{const{generate:t,type:o}=this.params.config;return this.createStreamingCommitMessages$(n=>{this.streamChunks(n).catch(m=>n.error(m))},o,t)},this.streamChunks=async t=>{const o=this.params.stagedDiff.diff,{systemPrompt:n,systemPromptPath:m,codeReviewPromptPath:r,logging:i,locale:y,temperature:h,generate:l,type:P,maxLength:v}=this.params.config,d=this.params.config.maxTokens,g={...T,locale:y,maxLength:v,type:P,generate:l,systemPrompt:n,systemPromptPath:m,codeReviewPromptPath:r,vcs_branch:this.params.branchName||""},c=N(g),G=`Here is the diff: ${o}`,q=`${this.params.config.url||"https://api.groq.com"}/openai/v1/chat/completions`,f={Authorization:`Bearer ${this.params.config.key}`,"Content-Type":"application/json"};I(o,"commit","Groq",this.params.config.model,q,f,i),b(o,"commit","Groq",c,G,i);const u={messages:[{role:"system",content:c},{role:"user",content:G}],model:this.params.config.model,max_tokens:d,top_p:this.params.config.topP,temperature:h,stream:!0};R(o,"commit","Groq",u,i);const a=Date.now();let p="";try{const s=await this.groq.chat.completions.create(u,{timeout:this.params.config.timeout});for await(const U of s){const k=U.choices?.[0]?.delta?.content||"";k&&(p+=k,t.next(k))}const O=Date.now()-a;_(o,"commit","Groq",{streamed:!0,totalLength:p.length},i),D(o,"commit","Groq",O,p,i),t.complete()}catch(s){E(o,"commit","Groq",s,i),t.error(s)}},this.colors={primary:"#f55036",secondary:"#fff"},this.serviceName=x.bgHex(this.colors.primary).hex(this.colors.secondary).bold(`[Groq${this.formatModelSuffix()}]`),this.errorPrefix=x.red.bold(`[Groq${this.formatModelSuffix()}]`),this.groq=new L({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 Groq API key in configuration":t.includes("rate_limit")||t.includes("Rate limit")?"Rate limit exceeded. Wait a moment and try again, or upgrade your Groq plan":t.includes("model")||t.includes("Model")?"Model not found or not accessible. Check if the Groq model name is correct":t.includes("overloaded")||t.includes("capacity")?"Groq service is overloaded. Try again in a few minutes":t.includes("403")||t.includes("Forbidden")?"Access denied. Your API key may not have permission for this Groq model":t.includes("404")||t.includes("Not Found")?"Model or endpoint not found. Check your Groq model configuration":t.includes("500")||t.includes("Internal Server Error")?"Groq server error. Try again later":null}generateCommitMessage$(){return this.params.config.stream||!1?this.generateStreamingCommitMessage$():$(this.generateMessage("commit")).pipe(A(t=>C(t)),M(this.formatAsChoice),S(this.handleError$))}generateCodeReview$(){return $(this.generateMessage("review")).pipe(A(e=>C(e)),M(this.formatCodeReviewAsChoice),S(this.handleError$))}async generateMessage(e){const t=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:n,codeReviewPromptPath:m,logging:r,locale:i,temperature:y,generate:h,type:l,maxLength:P}=this.params.config,v=this.params.config.maxTokens,d={...T,locale:i,maxLength:P,type:l,generate:h,systemPrompt:o,systemPromptPath:n,codeReviewPromptPath:m,vcs_branch:this.params.branchName||""},g=e==="review"?H(d):N(d),c=`Here is the diff: ${t}`,w=`${this.params.config.url||"https://api.groq.com"}/openai/v1/chat/completions`,q={Authorization:`Bearer ${this.params.config.key}`,"Content-Type":"application/json"};I(t,e,"Groq",this.params.config.model,w,q,r),b(t,e,"Groq",g,c,r);const f={messages:[{role:"system",content:g},{role:"user",content:c}],model:this.params.config.model,max_tokens:v,top_p:this.params.config.topP,temperature:y};R(t,e,"Groq",f,r);const u=Date.now();try{const a=await this.groq.chat.completions.create(f,{timeout:this.params.config.timeout}),p=Date.now()-u,s=a.choices[0].message.content||"";return _(t,e,"Groq",a,r),D(t,e,"Groq",p,s,r),e==="review"?this.parseCodeReview(s):this.parseMessage(s,l,h)}catch(a){throw E(t,e,"Groq",a,r),a}}}export{z as GroqService};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import b from"chalk";import{concatMap as k,from as D,map as P,catchError as E}from"rxjs";import{fromPromise as F}from"rxjs/internal/observable/innerFrom";import{A as $,l as H,a as R,c as S,d as U,e as x}from"./ai.service-
|
|
1
|
+
import b from"chalk";import{concatMap as k,from as D,map as P,catchError as E}from"rxjs";import{fromPromise as F}from"rxjs/internal/observable/innerFrom";import{A as $,l as H,a as R,c as S,d as U,e as x}from"./ai.service-f59388bb.mjs";import{D as N,b as T,g as _}from"./cli-d193cf90.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 ${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=b.bgHex(this.colors.primary).hex(this.colors.secondary).bold(`[HuggingFace${this.formatModelSuffix()}]`),this.errorPrefix=b.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 F(this.generateMessage("commit")).pipe(k(o=>D(o)),P(this.formatAsChoice),E(this.handleError$))}generateCodeReview$(){return F(this.generateMessage("review")).pipe(k(o=>D(o)),P(this.formatCodeReviewAsChoice),E(this.handleError$))}async generateMessage(o){await this.initialize();const e=this.params.stagedDiff.diff,{systemPrompt:r,systemPromptPath:t,codeReviewPromptPath:p,logging:a,locale:i,generate:d,type:s,maxLength:u,temperature:m,maxTokens:v,topP:h,timeout:g}=this.params.config,n={...N,locale:i,maxLength:u,type:s,generate:d,systemPrompt:r,systemPromptPath:t,codeReviewPromptPath:p,vcs_branch:this.params.branchName||""},c=o==="review"?T(n):_(n),l=`Here is the diff: ${e}`,w=`${this.params.config.url||"https://huggingface.co"}/chat/conversation`,I={...this.headers,cookie:this.cookie};H(e,o,"HuggingFace",this.params.config.model,w,I,a),R(e,o,"HuggingFace",c,l,a);const M=Date.now();try{const y=await this.getNewChat(c),C=await(await this.sendMessage(l,y.id)).completeResponsePromise();await this.deleteConversation(y.id);const A=Date.now()-M;return S(e,o,"HuggingFace",{response:C},a),U(e,o,"HuggingFace",A,C,a),o==="review"?this.parseCodeReview(C):this.parseMessage(C,s,d)}catch(y){throw x(e,o,"HuggingFace",y,a),y}}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,p=t[t[0].models],a=[],i=d=>d===-1?null:t[d];for(const d of p){const s=t[d];if(t[s.unlisted])continue;const u={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:{}},m=i(s.promptExamples);if(m!==null){const g=m.map(n=>i(n));u.promptExamples=g.map(n=>({title:t[n.title],prompt:t[n.prompt]}))}const v=i(s.parameters),h={};for(const[g,n]of Object.entries(v)){if(n===-1){h[g]=null;continue}if(Array.isArray(t[n])){h[g]=t[n].map(c=>t[c]);continue}h[g]=t[n]}u.parameters=h,a.push(u)}return this.models=a,a}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 p=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:a}=await p.json();if(a){this.currentConversionID=a;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,p=t[t[0].model],a=t[t[0].preprompt],i=t[t[0].title],d=t[t[0].messages],s=[];for(const u of d){const m=t[u],v=new Date(t[m.createdAt][1]).getTime()/1e3,h=new Date(t[m.updatedAt][1]).getTime()/1e3;s.push({id:t[m.id],role:t[m.from],content:t[m.content],createdAt:v,updatedAt:h})}return r.id=e,r.model=p,r.systemPrompt=a,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 p=this.params.config.url||"https://huggingface.co",a=new AbortController,i=setTimeout(()=>a.abort(),this.params.config.timeout),d=await fetch(`${p}/chat/conversation/${this.currentConversionID}`,{headers:{...this.headers,cookie:this.cookie,Referer:`${p}/chat/conversation/${this.currentConversionID}`},body:t,method:"POST",signal:a.signal});clearTimeout(i);function s(n){try{const c=n.split(`
|
|
2
2
|
`),l=[];for(const f of c)f.trim()&&l.push(JSON.parse(f));return l}catch{return[{}]}}const u=new TextDecoder;let m="";const v=new TransformStream({async transform(n,c){const l=u.decode(n);try{const f=s(l);for(const w of f)w.type==="finalAnswer"?(m=w?.text||"",c.terminate()):w.type==="stream"&&c.enqueue(w?.token||"")}catch{throw new Error("Error during parsing response")}}}),h=d.body?.pipeThrough(v);async function g(){return new Promise(async(n,c)=>{try{if(!h)c("ModifiedStream undefined");else{const l=h.getReader();for(;;){const{done:f,value:w}=await l.read();if(f){n(m);break}}}}catch(l){c(l)}})}return{id:this.currentConversionID,stream:h,completeResponsePromise:g}}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{j as HuggingFaceService};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import f from"chalk";import{concatMap as g,from as u,map as A,catchError as M}from"rxjs";import{fromPromise as y}from"rxjs/internal/observable/innerFrom";import{A as C,l as k,a as $,b as x,c as R,e as I,d as E}from"./ai.service-
|
|
1
|
+
import f from"chalk";import{concatMap as g,from as u,map as A,catchError as M}from"rxjs";import{fromPromise as y}from"rxjs/internal/observable/innerFrom";import{A as C,l as k,a as $,b as x,c as R,e as I,d as E}from"./ai.service-f59388bb.mjs";import{D as S,b as N,g as D,H as v,n as _}from"./cli-d193cf90.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 C{constructor(e){super(e),this.params=e,this.apiKey="",this.colors={primary:"#ff7000",secondary:"#fff"},this.serviceName=f.bgHex(this.colors.primary).hex(this.colors.secondary).bold(`[MistralAI${this.formatModelSuffix()}]`),this.errorPrefix=f.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 y(this.generateMessage("commit")).pipe(g(e=>u(e)),A(this.formatAsChoice),M(this.handleError$))}generateCodeReview$(){return y(this.generateMessage("review")).pipe(g(e=>u(e)),A(this.formatCodeReviewAsChoice),M(this.handleError$))}async generateMessage(e){const t=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:i,logging:n,locale:l,generate:a,type:c,maxLength:p}=this.params.config,r={...S,locale:l,maxLength:p,type:c,generate:a,systemPrompt:o,systemPromptPath:s,codeReviewPromptPath:i,vcs_branch:this.params.branchName||""},h=e==="review"?N(r):D(r);await this.checkAvailableModels();const m=`Here is the diff: ${t}`,b=`${this.params.config.url||"https://api.mistral.ai"}/v1/chat/completions`,w={Authorization:`Bearer ${this.apiKey}`,"content-type":"application/json"};k(t,e,"MistralAI",this.params.config.model,b,w,n),$(t,e,"MistralAI",h,m,n);const d=await this.createChatCompletions(h,m,e);return e==="review"?this.parseCodeReview(d):this.parseMessage(d,c,a)}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 v({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 s=this.params.stagedDiff.diff,{logging:i}=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:_(10,1e3)};x(s,o,"MistralAI",n,i);const l=Date.now();try{const a=this.params.config.url||"https://api.mistral.ai",c=await new v({method:"POST",baseURL:`${a}/v1/chat/completions`,timeout:this.params.config.timeout}).setHeaders({Authorization:`Bearer ${this.apiKey}`,"content-type":"application/json"}).setBody(n).execute(),p=Date.now()-l,r=c.data;if(R(s,o,"MistralAI",r,i),!r.choices||r.choices.length===0||!r.choices[0].message?.content)throw I(s,o,"MistralAI",{message:"No Content on response",result:r},i),new Error("No Content on response. Please open a Bug report");const m=r.choices[0].message.content;return E(s,o,"MistralAI",p,m,i),m}catch(a){throw I(s,o,"MistralAI",a,i),a}}}export{U as MistralService};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import P from"chalk";import{Ollama as L}from"ollama";import{concatMap as w,from as k,map as A,catchError as v}from"rxjs";import{fromPromise as C}from"rxjs/internal/observable/innerFrom";import{fetch as H,Agent as z}from"undici";import{A as T,l as _,a as x,b as M,c as O,d as R,e as S}from"./ai.service-
|
|
1
|
+
import P from"chalk";import{Ollama as L}from"ollama";import{concatMap as w,from as k,map as A,catchError as v}from"rxjs";import{fromPromise as C}from"rxjs/internal/observable/innerFrom";import{fetch as H,Agent as z}from"undici";import{A as T,l as _,a as x,b as M,c as O,d as R,e as S}from"./ai.service-f59388bb.mjs";import{o as E,n as N,c as b,P as D,D as U,b as B,g as G,H as J}from"./cli-d193cf90.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 K extends T{constructor(e){super(e),this.params=e,this.host=E,this.model="",this.key="",this.auth="",this.generateStreamingCommitMessage$=()=>{const{generate:t,type:s}=this.params.config;return this.createStreamingCommitMessages$(o=>{this.streamChunks(o).catch(n=>o.error(n))},s,t)},this.streamChunks=async t=>{const s=this.params.stagedDiff.diff,{logging:o}=this.params.config,n=this.buildCommitPrompt();await this.checkIsAvailableOllama();const c=`Here is the diff: ${s}`,i=`Ollama_${this.model}`,d=`${this.host}/api/chat`,a=this.key?{Authorization:`${this.auth} ${this.key}`}:{};_(s,"commit",i,this.model,d,a,o),x(s,"commit",i,n,c,o);const{numCtx:h,temperature:m,topP:p,timeout:g,maxTokens:r}=this.params.config,u={model:this.model,messages:[{role:"system",content:n},{role:"user",content:c}],stream:!0,keep_alive:g,options:{num_ctx:h,temperature:m,top_p:p,seed:N(10,1e3),num_predict:r??-1}};M(s,"commit",i,u,o);const l=Date.now();let f="";try{const y=await this.ollama.chat(u);for await(const F of y){const $=F.message.content;$&&(f+=$,t.next($))}const I=Date.now()-l;O(s,"commit",i,{streamed:!0,totalLength:f.length},o),R(s,"commit",i,I,f,o),t.complete()}catch(y){S(s,"commit",i,y,o),t.error(y)}},this.setupFetch=(t,s={})=>H(t,{...s,dispatcher:new z({headersTimeout:this.params.config.timeout})}),this.colors={primary:"#FFF",secondary:"#000"},this.model=this.params.keyName,this.serviceName=P.bgHex(this.colors.primary).hex(this.colors.secondary).bold(`[${b(this.model)}]`),this.errorPrefix=P.red.bold(`[${b(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 L({host:this.host,fetch:this.setupFetch,...this.key&&{headers:{Authorization:`${this.auth} ${this.key}`}}})}getServiceSpecificErrorMessage(e){const t=e.message||"";return t.includes("ECONNREFUSED")||t.includes("connection refused")?D.ollamaNotRunning():t.includes("model")&&(t.includes("not found")||t.includes("404"))?D.ollamaModelNotPulled(this.model):null}generateCommitMessage$(){return this.params.config.stream||!1?this.generateStreamingCommitMessage$():C(this.generateMessage("commit")).pipe(w(t=>k(t)),A(this.formatAsChoice),v(this.handleError$))}generateCodeReview$(){return C(this.generateMessage("review")).pipe(w(e=>k(e)),A(this.formatCodeReviewAsChoice),v(this.handleError$))}async generateMessage(e){const t=this.params.stagedDiff.diff,{systemPrompt:s,systemPromptPath:o,codeReviewPromptPath:n,logging:c,locale:i,generate:d,type:a,maxLength:h}=this.params.config,m={...U,locale:i,maxLength:h,type:a,generate:d,systemPrompt:s,systemPromptPath:o,codeReviewPromptPath:n,vcs_branch:this.params.branchName||""},p=e==="review"?B(m):G(m);await this.checkIsAvailableOllama();const g=`Here is the diff: ${t}`,r=`Ollama_${this.model}`,u=`${this.host}/api/chat`,l=this.key?{Authorization:`${this.auth} ${this.key}`}:{};_(t,e,r,this.model,u,l,c),x(t,e,r,p,g,c);const f=await this.createChatCompletions(p,g,e);return e==="review"?this.parseCodeReview(f):this.parseMessage(f,a,d)}async checkIsAvailableOllama(){const e=new J({method:"GET",baseURL:`${this.host}`,timeout:this.params.config.timeout});return this.key&&e.setHeaders({Authorization:`${this.auth} ${this.key}`}),(await e.execute()).data}async createChatCompletions(e,t,s){const{numCtx:o,temperature:n,topP:c,timeout:i,maxTokens:d,logging:a}=this.params.config,h=this.params.stagedDiff.diff,m=`Ollama_${this.model}`,p={model:this.model,messages:[{role:"system",content:e},{role:"user",content:t}],stream:!1,keep_alive:i,options:{num_ctx:o,temperature:n,top_p:c,seed:N(10,1e3),num_predict:d??-1}};M(h,s,m,p,a);const g=Date.now();try{const r=await this.ollama.chat(p),u=Date.now()-g,l=r.message.content;return O(h,s,m,{response:l,fullResponse:r},a),R(h,s,m,u,l,a),l}catch(r){throw S(h,s,m,r,a),r}}}export{K as OllamaService};
|
package/dist/{openai-compatible.service-a24deda0.mjs → openai-compatible.service-2bea7313.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import S from"chalk";import Q from"openai";import{concatMap as _,from as b,map as N,catchError as R}from"rxjs";import{fromPromise as O}from"rxjs/internal/observable/innerFrom";import{A as V,l as E,a as T,b as D,c as L,d as F,e as z}from"./ai.service-
|
|
1
|
+
import S from"chalk";import Q from"openai";import{concatMap as _,from as b,map as N,catchError as R}from"rxjs";import{fromPromise as O}from"rxjs/internal/observable/innerFrom";import{A as V,l as E,a as T,b as D,c as L,d as F,e as z}from"./ai.service-f59388bb.mjs";import{i as B}from"./openai-dc366083.mjs";import{D as H,g as U,a as X,c as K,b as Z}from"./cli-d193cf90.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 j extends V{constructor(t){super(t),this.params=t,this.generateStreamingCommitMessage$=()=>{const{generate:m,type:o}=this.params.config;return this.createStreamingCommitMessages$(c=>{this.streamChunks(c).catch(r=>c.error(r))},o,m)},this.streamChunks=async m=>{const o=this.params.stagedDiff.diff,{systemPrompt:c,systemPromptPath:r,codeReviewPromptPath:A,logging:s,locale:d,temperature:g,generate:I,type:C,maxLength:f,timeout:u}=this.params.config,p=this.params.config.maxTokens,y={...H,locale:d,maxLength:f,type:C,generate:I,systemPrompt:c,systemPromptPath:r,codeReviewPromptPath:A,vcs_branch:this.params.branchName||""},i=U(y),P=`Here is the diff: ${o}`,a=this.params.keyName||"OpenAI-Compatible",v=`${this.params.config.url}${this.params.config.path}`,k={Authorization:`Bearer ${this.params.config.key}`,"Content-Type":"application/json"};E(o,"commit",a,this.params.config.model,v,k,s),T(o,"commit",a,i,P,s);const w=B(this.params.config.model),n={messages:[{role:"system",content:i},{role:"user",content:P}],model:this.params.config.model,stream:!0,...w?{max_completion_tokens:p,temperature:1}:{max_tokens:p,top_p:this.params.config.topP,temperature:g}};D(o,"commit",a,n,s);const l=Date.now();let h="";try{const W=await this.openAI.chat.completions.create(n,{timeout:u});for await(const M of W){const G=M.choices?.[0]?.delta?.content||"",J=M.choices?.[0]?.delta?.reasoning_content||"",x=`${G}${J}`;x&&(h+=x,m.next(x))}const Y=Date.now()-l;L(o,"commit",a,{streamed:!0,totalLength:h.length},s),F(o,"commit",a,Y,h,s),m.complete()}catch($){z(o,"commit",a,$,s),m.error($)}};const e=this.params.keyName||"OPENAI_COMPATIBLE";this.colors=X(e),this.serviceName=S.bgHex(this.colors.primary).hex(this.colors.secondary).bold(`[${K(e)}]`),this.errorPrefix=S.red.bold(`[${K(e)}]`),this.openAI=new Q({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$():O(this.generateMessage("commit")).pipe(_(e=>b(e)),N(this.formatAsChoice),R(this.handleError$))}generateCodeReview$(){return O(this.generateMessage("review")).pipe(_(t=>b(t)),N(this.formatCodeReviewAsChoice),R(this.handleError$))}async generateMessage(t){const e=this.params.stagedDiff.diff,{systemPrompt:m,systemPromptPath:o,codeReviewPromptPath:c,logging:r,locale:A,temperature:s,generate:d,type:g,maxLength:I,timeout:C}=this.params.config,f=this.params.config.maxTokens,u={...H,locale:A,maxLength:I,type:g,generate:d,systemPrompt:m,systemPromptPath:o,codeReviewPromptPath:c,vcs_branch:this.params.branchName||""},p=t==="review"?Z(u):U(u),y=`Here is the diff: ${e}`,i=this.params.keyName||"OpenAI-Compatible",P=`${this.params.config.url}${this.params.config.path}`,a={Authorization:`Bearer ${this.params.config.key}`,"Content-Type":"application/json"};E(e,t,i,this.params.config.model,P,a,r),T(e,t,i,p,y,r);const v=B(this.params.config.model),k={messages:[{role:"system",content:p},{role:"user",content:y}],model:this.params.config.model,stream:!1,...v?{max_completion_tokens:f,temperature:1}:{max_tokens:f,top_p:this.params.config.topP,temperature:s}};D(e,t,i,k,r);const w=Date.now();try{const n=await this.openAI.chat.completions.create(k,{timeout:C}),l=n.choices?.[0]?.message.content||"",h=Date.now()-w;return L(e,t,i,n,r),F(e,t,i,h,l,r),t==="review"?this.parseCodeReview(l):this.parseMessage(l,g,d)}catch(n){throw z(e,t,i,n,r),n}}}export{j as OpenAICompatibleService};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import ae from"http";import ce from"https";import{i as y,j as ue,k as le,K as R}from"./cli-
|
|
1
|
+
import ae from"http";import ce from"https";import{i as y,j as ue,k as le,K as R}from"./cli-d193cf90.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-f59388bb.mjs";var T={},k={exports:{}},E={exports:{}},S,W;function Oe(){if(W)return S;W=1;var t=1e3,n=t*60,i=n*60,e=i*24,f=e*7,s=e*365.25;S=function(u,r){r=r||{};var o=typeof u;if(o==="string"&&u.length>0)return d(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 d(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 p=r>=o*1.5;return Math.round(u/o)+" "+c+(p?"s":"")}return S}var L,Y;function K(){if(Y)return L;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,p,m;function C(...g){if(!C.enabled)return;const b=C,v=Number(new Date),M=v-(o||v);b.diff=M,b.prev=o,b.curr=v,o=v,g[0]=e.coerce(g[0]),typeof g[0]!="string"&&g.unshift("%O");let F=0;g[0]=g[0].replace(/%([a-zA-Z%])/g,(O,w)=>{if(O==="%%")return"%";F++;const J=e.formatters[w];if(typeof J=="function"){const ie=g[F];O=J.call(b,ie),g.splice(F,1),F--}return O}),e.formatArgs.call(b,g),(b.log||e.log).apply(b,g)}return C.namespace=r,C.useColors=e.useColors(),C.color=e.selectColor(r),C.extend=f,C.destroy=e.destroy,Object.defineProperty(C,"enabled",{enumerable:!0,configurable:!1,get:()=>c!==null?c:(p!==e.namespaces&&(p=e.namespaces,m=e.enabled(r)),m),set:g=>{c=g}}),typeof e.init=="function"&&e.init(C),C}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 d(r,o){let c=0,p=0,m=-1,C=0;for(;c<r.length;)if(p<o.length&&(o[p]===r[c]||o[p]==="*"))o[p]==="*"?(m=p,C=c,p++):(c++,p++);else if(m!==-1)p=m+1,C++,c=C;else return!1;for(;p<o.length&&o[p]==="*";)p++;return p===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(d(r,o))return!1;for(const o of e.names)if(d(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 L=t,L}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=d(),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 d(){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:{}},D,X;function $e(){return X||(X=1,D=(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)}),D}var j,Q;function Ae(){if(Q)return j;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 d(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=d(a,a&&a.isTTY);return s(l)}return j={supportsColor:h,stdout:s(d(!0,n.isatty(1))),stderr:s(d(!0,n.isatty(2)))},j}$.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 p=c.substring(6).toLowerCase().replace(/_([a-z])/g,(C,g)=>g.toUpperCase());let m=process.env[c];return/^(yes|on|true|enabled)$/i.test(m)?m=!0:/^(no|off|false|disabled)$/i.test(m)?m=!1:m==="null"?m=null:m=Number(m),o[p]=m,o},{});function f(){return"colors"in n.inspectOpts?!!n.inspectOpts.colors:i.isatty(process.stderr.fd)}function s(o){const{namespace:c,useColors:p}=this;if(p){const m=this.color,C="\x1B[3"+(m<8?m:"8;5;"+m),g=` ${C};1m${c} \x1B[0m`;o[0]=g+o[0].split(`
|
|
2
2
|
`).join(`
|
|
3
3
|
`+g),o.push(C+"m+"+t.exports.humanize(this.diff)+"\x1B[0m")}else o[0]=d()+c+" "+o[0]}function d(){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 p=0;p<c.length;p++)o.inspectOpts[c[p]]=n.inspectOpts[c[p]]}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(`
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import x from"chalk";import N from"openai";import{concatMap as M,from as k,map as T,catchError as $}from"rxjs";import{fromPromise as w}from"rxjs/internal/observable/innerFrom";import{A as U,l as H,a as q,b as z,c as B,d as K,e as J}from"./ai.service-
|
|
1
|
+
import x from"chalk";import N from"openai";import{concatMap as M,from as k,map as T,catchError as $}from"rxjs";import{fromPromise as w}from"rxjs/internal/observable/innerFrom";import{A as U,l as H,a as q,b as z,c as B,d as K,e as J}from"./ai.service-f59388bb.mjs";import{i as Q,g as V}from"./openai-dc366083.mjs";import{D as S,g as R,b as W,m as O}from"./cli-d193cf90.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 X extends U{constructor(t){super(t),this.params=t,this.generateStreamingCommitMessage$=()=>{const{generate:s,type:e}=this.params.config;return this.createStreamingCommitMessages$(a=>{this.streamChunks(a).catch(m=>a.error(m))},e,s)},this.streamChunks=async s=>{const e=this.params.stagedDiff.diff,{systemPrompt:a,systemPromptPath:m,codeReviewPromptPath:g,temperature:p,logging:o,locale:l,generate:f,type:d,maxLength:u,maxTokens:n,timeout:P}=this.params.config,c={...S,locale:l,maxLength:u,type:d,generate:f,systemPrompt:a,systemPromptPath:m,codeReviewPromptPath:g,vcs_branch:this.params.branchName||""},i=R(c),I=`Here is the diff: ${e}`,b=`${this.params.config.url}${this.params.config.path}`,G={Authorization:`Bearer ${this.params.config.key}`,"Content-Type":"application/json"};H(e,"commit","ChatGPT",this.params.config.model,b,G,o),q(e,"commit","ChatGPT",i,I,o);const _=Q(this.params.config.model),v={messages:[{role:"system",content:i},{role:"user",content:I}],model:this.params.config.model,stream:!0,..._?{max_completion_tokens:n,temperature:1}:{max_tokens:n,top_p:this.params.config.topP,temperature:p}};z(e,"commit","ChatGPT",v,o);const D=Date.now();let y="";try{const E=await this.openAI.chat.completions.create(v,{timeout:P});for await(const F of E){const A=F.choices?.[0]?.delta?.content||"";A&&(y+=A,s.next(A))}const L=Date.now()-D;B(e,"commit","ChatGPT",{streamed:!0,totalLength:y.length},o),K(e,"commit","ChatGPT",L,y,o),s.complete()}catch(C){J(e,"commit","ChatGPT",C,o),s.error(C)}},this.colors={primary:"#74AA9C",secondary:"#FFF"},this.serviceName=x.bgHex(this.colors.primary).hex(this.colors.secondary).bold(`[ChatGPT${this.formatModelSuffix()}]`),this.errorPrefix=x.red.bold(`[ChatGPT${this.formatModelSuffix()}]`);const r=this.params.config.url||"https://api.openai.com",h=(this.params.config.path||"/v1/chat/completions").replace(/\/chat\/completions\/?$/,"");this.openAI=new N({apiKey:this.params.config.key,baseURL:`${r}${h}`})}getServiceSpecificErrorMessage(t){const r=t.message||"";return r.includes("API key")?"Invalid API key. Check your OpenAI API key in configuration":r.includes("quota")?"API quota exceeded. Check your OpenAI usage limits":r.includes("500")?"OpenAI server error. Try again later":null}generateCommitMessage$(){return this.params.config.stream||!1?this.generateStreamingCommitMessage$():w(this.generateMessage("commit")).pipe(M(r=>k(r)),T(this.formatAsChoice),$(this.handleError$))}generateCodeReview$(){return w(this.generateMessage("review")).pipe(M(t=>k(t)),T(this.formatCodeReviewAsChoice),$(this.handleError$))}async generateMessage(t){const r=this.params.stagedDiff.diff,{systemPrompt:h,systemPromptPath:s,codeReviewPromptPath:e,temperature:a,logging:m,locale:g,generate:p,type:o,maxLength:l,proxy:f,maxTokens:d,timeout:u}=this.params.config,n={...S,locale:g,maxLength:l,type:o,generate:p,systemPrompt:h,systemPromptPath:s,codeReviewPromptPath:e,vcs_branch:this.params.branchName||""},P=t==="review"?W(n):R(n),c=await V("ChatGPT",this.params.config.url,this.params.config.path,this.params.config.key,this.params.config.model,r,u,d,a,this.params.config.topP,P,m,t,f);return t==="review"?O(c.map(i=>this.parseCodeReview(i))):O(c.map(i=>this.parseMessage(i,o,p)))}}export{X as OpenAIService};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import $ from"chalk";import L from"openai";import{concatMap as b,from as k,map as S,catchError as I}from"rxjs";import{fromPromise as H}from"rxjs/internal/observable/innerFrom";import{A as z,l as _,a as E,b as T,c as j,d as U,e as D}from"./ai.service-
|
|
1
|
+
import $ from"chalk";import L from"openai";import{concatMap as b,from as k,map as S,catchError as I}from"rxjs";import{fromPromise as H}from"rxjs/internal/observable/innerFrom";import{A as z,l as _,a as E,b as T,c as j,d as U,e as D}from"./ai.service-f59388bb.mjs";import{i as X}from"./openai-dc366083.mjs";import{D as F,g as K,H as G,b as W}from"./cli-d193cf90.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 A=class d extends z{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(a=>[a.id,a.canonical_slug,a.name].filter(i=>!!i).some(i=>i===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 a=await this.getReasoningPayload();return a&&(o.reasoning=a),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 a=this.params.config.maxTokens,m=this.params.config.temperature,i=X(this.params.config.model),u=this.getRequestedModel();return{messages:[{role:"system",content:t},{role:"user",content:o}],model:u,stream:s,...await this.getRequestPayloadExtras()||{},...i?{max_completion_tokens:a,temperature:1}:{max_tokens:a,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(a=>s.error(a))},o,t)},this.streamChunks=async t=>{const o=this.params.stagedDiff.diff,{systemPrompt:s,systemPromptPath:a,codeReviewPromptPath:m,logging:i,locale:u,generate:C,type:g,maxLength:f,timeout:R}=this.params.config,p={...F,locale:u,maxLength:f,type:g,generate:C,systemPrompt:s,systemPromptPath:a,codeReviewPromptPath:m,vcs_branch:this.params.branchName||""},y=K(p),O=`Here is the diff: ${o}`,c="OpenRouter",P=`${this.params.config.url||"https://openrouter.ai"}${this.params.config.path||"/api/v1/chat/completions"}`,h={Authorization:`Bearer ${this.params.config.key}`,"Content-Type":"application/json",...this.getOpenRouterHeaders()};_(o,"commit",c,this.params.config.model,P,h,i),E(o,"commit",c,y,O,i);const l=await this.buildChatCompletionPayload(y,O,!0);T(o,"commit",c,l,i);const M=Date.now();let w="";try{const q=await this.openAI.chat.completions.create(l,{timeout:R});for await(const B of q){const x=this.extractOpenRouterText(B.choices?.[0]?.delta);x&&(w+=x,t.next(x))}const N=Date.now()-M;j(o,"commit",c,{streamed:!0,totalLength:w.length},i),U(o,"commit",c,N,w,i),t.complete()}catch(v){D(o,"commit",c,v,i),t.error(v)}},this.colors={primary:"#f97316",secondary:"#fff"},this.serviceName=$.bgHex(this.colors.primary).hex(this.colors.secondary).bold(`[OpenRouter${this.formatModelSuffix()}]`),this.errorPrefix=$.red.bold(`[OpenRouter${this.formatModelSuffix()}]`);const e=this.params.config.url||"https://openrouter.ai",n=(this.params.config.path||"/api/v1/chat/completions").replace(/\/chat\/completions\/?$/,"");this.openAI=new L({apiKey:this.params.config.key,baseURL:`${e}${n}`,defaultHeaders:{...this.getOpenRouterHeaders()}})}async fetchOpenRouterCatalog(){const r=this.getCatalogCacheKey(),e=d.catalogCache.get(r);if(e)return e;const n=["/models/user","/models"];let t;for(const o of n)try{const a=(await new G({method:"GET",baseURL:`${this.getOpenRouterCatalogUrl()}${o}`,timeout:this.params.config.timeout}).setHeaders(this.getOpenRouterAuthHeaders()).execute()).data?.data??[];return d.catalogCache.set(r,a),a}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(),n=d.modelCache.get(e);if(n!==void 0)return n;try{const t=await this.fetchOpenRouterCatalog(),o=this.matchOpenRouterModel(r,t)||null;return d.modelCache.set(e,o),o}catch{return null}}async supportsOpenRouterParameters(r){const e=await this.getOpenRouterModel();return e?r.some(n=>e.supported_parameters?.includes(n)??!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,n=e?{...e}:{};return"exclude"in n||(n.exclude=!0),n}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$():H(this.generateMessage("commit")).pipe(b(e=>k(e)),S(this.formatAsChoice),I(this.handleError$))}generateCodeReview$(){return H(this.generateMessage("review")).pipe(b(r=>k(r)),S(this.formatCodeReviewAsChoice),I(this.handleError$))}async generateMessage(r){const e=this.params.stagedDiff.diff,{systemPrompt:n,systemPromptPath:t,codeReviewPromptPath:o,logging:s,locale:a,generate:m,type:i,maxLength:u,timeout:C}=this.params.config,g={...F,locale:a,maxLength:u,type:i,generate:m,systemPrompt:n,systemPromptPath:t,codeReviewPromptPath:o,vcs_branch:this.params.branchName||""},f=r==="review"?W(g):K(g),R=`Here is the diff: ${e}`,p="OpenRouter",y=`${this.params.config.url||"https://openrouter.ai"}${this.params.config.path||"/api/v1/chat/completions"}`,O={Authorization:`Bearer ${this.params.config.key}`,"Content-Type":"application/json",...this.getOpenRouterHeaders()};_(e,r,p,this.params.config.model,y,O,s),E(e,r,p,f,R,s);const c=await this.buildChatCompletionPayload(f,R,!1);T(e,r,p,c,s);const P=Date.now();try{const h=await this.openAI.chat.completions.create(c,{timeout:C}),l=this.extractOpenRouterText(h.choices?.[0]?.message),M=Date.now()-P;return j(e,r,p,h,s),U(e,r,p,M,l,s),r==="review"?this.parseCodeReview(l):this.parseMessage(l,i,m)}catch(h){throw D(e,r,p,h,s),h}}};A.catalogCache=new Map,A.modelCache=new Map;let Y=A;export{Y as OpenRouterService};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import f from"chalk";import{concatMap as g,from as u,map as y,catchError as P}from"rxjs";import{fromPromise as x}from"rxjs/internal/observable/innerFrom";import{A as b,l as k,a as I,b as M,c as R,e as v,d as S}from"./ai.service-
|
|
1
|
+
import f from"chalk";import{concatMap as g,from as u,map as y,catchError as P}from"rxjs";import{fromPromise as x}from"rxjs/internal/observable/innerFrom";import{A as b,l as k,a as I,b as M,c as R,e as v,d as S}from"./ai.service-f59388bb.mjs";import{D as $,b as E,g as N,H as D}from"./cli-d193cf90.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 O extends b{constructor(t){super(t),this.params=t,this.apiKey="",this.colors={primary:"#20808D",secondary:"#FFF"},this.serviceName=f.bgHex(this.colors.primary).hex(this.colors.secondary).bold(`[Perplexity${this.formatModelSuffix()}]`),this.errorPrefix=f.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 x(this.generateMessage("commit")).pipe(g(t=>u(t)),y(this.formatAsChoice),P(this.handleError$))}generateCodeReview$(){return x(this.generateMessage("review")).pipe(g(t=>u(t)),y(this.formatCodeReviewAsChoice),P(this.handleError$))}extractJSONFromError(t){const e=/[{[]{1}([,:{}[\]0-9.\-+Eaeflnr-u \n\r\t]|".*?")+[}\]]{1}/gis,o=t.match(e);if(o){const r={};for(const i of o)try{Object.assign(r,JSON.parse(i))}catch{}return Object.keys(r).length>0?r:{error:{message:"Unknown error"}}}return{error:{message:"Unknown error"}}}async generateMessage(t){const e=this.params.stagedDiff.diff,{systemPrompt:o,systemPromptPath:r,codeReviewPromptPath:i,logging:n,locale:m,generate:a,type:c,maxLength:l}=this.params.config,s={...$,locale:m,maxLength:l,type:c,generate:a,systemPrompt:o,systemPromptPath:r,codeReviewPromptPath:i,vcs_branch:this.params.branchName||""},h=t==="review"?E(s):N(s),p=`Here is the diff: ${e}`,A=`${this.params.config.url||"https://api.perplexity.ai"}/chat/completions`,C={Authorization:`Bearer ${this.apiKey}`,"content-type":"application/json"};k(e,t,"Perplexity",this.params.config.model,A,C,n),I(e,t,"Perplexity",h,p,n);const d=await this.createChatCompletions(h,p,t);return t==="review"?this.parseCodeReview(d):this.parseMessage(d,c,a)}async createChatCompletions(t,e,o){const r=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};M(r,o,"Perplexity",n,i);const m=Date.now();try{const a=this.params.config.url||"https://api.perplexity.ai",c=await new D({method:"POST",baseURL:`${a}/chat/completions`,timeout:this.params.config.timeout}).setHeaders({Authorization:`Bearer ${this.apiKey}`,"content-type":"application/json"}).setBody(n).execute(),l=Date.now()-m,s=c.data;if(R(r,o,"Perplexity",s,i),!s.choices||s.choices.length===0||!s.choices[0].message?.content)throw v(r,o,"Perplexity",{message:"No Content on response",result:s},i),new Error("No Content on response. Please open a Bug report");const p=s.choices[0].message.content;return S(r,o,"Perplexity",l,p,i),p}catch(a){throw v(r,o,"Perplexity",a,i),a}}}export{O as PerplexityService};
|
package/package.json
CHANGED
|
@@ -1,5 +0,0 @@
|
|
|
1
|
-
import S from"chalk";import{concatMap as _,from as A,map as L,catchError as I}from"rxjs";import{fromPromise as T}from"rxjs/internal/observable/innerFrom";import{A as k,l as b,a as y,b as U,c as R,d as x,e as z}from"./ai.service-a9047145.mjs";import{D as B,b as H,g as F}from"./cli-5d0ec142.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 D="gpt-4.1",$=["gpt-4.1","gpt-4o","gpt-5-mini"],w={"openai/gpt-4.1":"gpt-4.1","openai/gpt-4o":"gpt-4o","openai/gpt-5-mini":"gpt-5-mini"},G=e=>{const o=(e||"").trim().toLowerCase();return o?o in w?w[o]:o.includes("/")&&o.split("/").pop()||o:D},j=e=>[G(e),...$].filter((t,i,r)=>r.indexOf(t)===i),N=e=>{const o=e.toLowerCase();return o.includes("unknown_model")||o.includes("unknown model")||o.includes("unavailable_model")||o.includes("unavailable model")||o.includes("model not found")||o.includes("not available")||o.includes("not enabled")||o.includes("not allowed")},K=e=>{const o=e.toLowerCase();return o.includes("auth")||o.includes("unauthorized")||o.includes("forbidden")||o.includes("token")||o.includes("copilot cli")},V=e=>{const o=e.toLowerCase();return o.includes("classic personal access tokens")&&o.includes("ghp_")},W=(e=process.env)=>{const o={...e};delete o.GH_TOKEN,delete o.GITHUB_TOKEN;const t=(e.COPILOT_GITHUB_TOKEN||"").trim();return t.length>0?(o.COPILOT_GITHUB_TOKEN=t,{githubToken:t,useLoggedInUser:!1,env:o}):(delete o.COPILOT_GITHUB_TOKEN,{useLoggedInUser:!0,env:o})};class q extends k{constructor(o){super(o),this.params=o,this.colors={primary:"#1f6feb",secondary:"#FFF"},this.serviceName=S.bgHex(this.colors.primary).hex(this.colors.secondary).bold(`[Copilot SDK${this.formatModelSuffix()}]`),this.errorPrefix=S.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":V(t)?"Copilot rejected classic ghp_ token. Use COPILOT_GITHUB_TOKEN with a Fine-Grained PAT or authenticate via copilot /login.":o.code==="AUTHENTICATION_FAILED"||K(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"||N(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 T(this.generateMessage("commit")).pipe(_(o=>A(o)),L(this.formatAsChoice),I(this.handleError$))}generateCodeReview$(){return T(this.generateMessage("review")).pipe(_(o=>A(o)),L(this.formatCodeReviewAsChoice),I(this.handleError$))}async generateMessage(o){const t=this.params.stagedDiff.diff,{systemPrompt:i,systemPromptPath:r,codeReviewPromptPath:a,locale:l,generate:g,type:c,maxLength:s}=this.params.config,m={...B,locale:l,maxLength:s,type:c,generate:g,systemPrompt:i,systemPromptPath:r,codeReviewPromptPath:a,vcs_branch:this.params.branchName||""},p=o==="review"?H(m):F(m),E=o==="review"?t:`Here's the diff:
|
|
2
|
-
|
|
3
|
-
${t}`,h=await this.makeRequest(p,E,o,t);return o==="review"?this.parseCodeReview(h):this.parseMessage(h,c,g)}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,i=t.data,r=t.content,a=i?.content;if(typeof r=="string")return r.trim();if(typeof a=="string")return a.trim();const l=i?.message?.content;return typeof l=="string"?l.trim():""}async makeRequest(o,t,i,r){const{CopilotClient:a,approveAll:l}=await this.loadSdkModule(),g=Array.isArray(this.params.config.model)?this.params.config.model[0]:this.params.config.model||D,c=j(g),{logging:s}=this.params.config;let m;for(const p of c){const E="copilot-sdk://session",h={Authorization:"Copilot CLI session"},M={model:p,prompt:t};b(r,i,"Copilot SDK",p,E,h,s),y(r,i,"Copilot SDK",o,t,s),U(r,i,"Copilot SDK",M,s);const P=Date.now();let f;try{const d=W(process.env);f=new a(d);const u=await(await f.createSession({model:p,onPermissionRequest:l})).sendAndWait({prompt:`${o}
|
|
4
|
-
|
|
5
|
-
${t}`}),C=this.extractContent(u);if(!C){const O=new Error("No content in Copilot SDK response");throw O.code="NO_CONTENT",O}const v=Date.now()-P;return R(r,i,"Copilot SDK",u,s),x(r,i,"Copilot SDK",v,C,s),C}catch(d){const n=d instanceof Error?d:new Error(String(d)),u=n.message||String(d);if(!n.code&&K(u)&&(n.code="AUTHENTICATION_FAILED"),!n.code&&N(u)&&(n.code="MODEL_NOT_AVAILABLE"),z(r,i,"Copilot SDK",n,s),m=n,!(n.code==="MODEL_NOT_AVAILABLE"&&p!==c[c.length-1]))throw n}finally{f?.stop&&await f.stop()}}throw m||new Error("Copilot SDK request failed for all candidate models")}}export{q as CopilotSdkService};
|