aicommit2 2.5.14 → 2.5.15
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-47363f49.mjs → ai.service-c5f81726.mjs} +1 -1
- package/dist/{anthropic.service-07f000b2.mjs → anthropic.service-8683e0f3.mjs} +1 -1
- package/dist/{bedrock.service-bb73b18d.mjs → bedrock.service-6f2033a3.mjs} +1 -1
- package/dist/{cli-fd2479d5.mjs → cli-3a375308.mjs} +64 -54
- package/dist/cli.mjs +1 -1
- package/dist/{codestral.service-1f018db8.mjs → codestral.service-55e7877b.mjs} +1 -1
- package/dist/{cohere.service-792231bd.mjs → cohere.service-a97d3df4.mjs} +1 -1
- package/dist/{copilot-sdk.service-3ce57b3e.mjs → copilot-sdk.service-90220934.mjs} +1 -1
- package/dist/{deep-seek.service-18bf8bbd.mjs → deep-seek.service-17948987.mjs} +1 -1
- package/dist/{gemini.service-680451fb.mjs → gemini.service-2d64ecdf.mjs} +1 -1
- package/dist/{github-models.service-c47a9246.mjs → github-models.service-9d5cfbf0.mjs} +1 -1
- package/dist/{groq.service-b9970eb4.mjs → groq.service-8a4e7a39.mjs} +1 -1
- package/dist/{hugging-face.service-370921e2.mjs → hugging-face.service-3fb9b5db.mjs} +1 -1
- package/dist/{mistral.service-2d118a9c.mjs → mistral.service-d6adcdb9.mjs} +1 -1
- package/dist/{ollama.service-516cd32f.mjs → ollama.service-ed2ddd5b.mjs} +1 -1
- package/dist/{openai-compatible.service-3cda8bb5.mjs → openai-compatible.service-9b9b2eb5.mjs} +1 -1
- package/dist/{openai-c3c69b49.mjs → openai-e13f148b.mjs} +1 -1
- package/dist/{openai.service-41f8df31.mjs → openai.service-9a9d6468.mjs} +1 -1
- package/dist/{openrouter.service-ac2ba1cb.mjs → openrouter.service-b19d9e75.mjs} +1 -1
- package/dist/{perplexity.service-29e7b048.mjs → perplexity.service-86678853.mjs} +1 -1
- package/package.json +1 -1
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-3a375308.mjs";import"module";import"crypto";import"fs";import"os";import"path";import"node:buffer";import"node:path";import"node:child_process";import"node:process";import"child_process";import"node:url";import"node:os";import"assert";import"events";import"node:fs";import"buffer";import"stream";import"util";import"node:util";import"inquirer";import"rxjs";import"fs/promises";import"chalk";import"readline";import"figlet";import"gradient-string";import"ora";import"inquirer-reactive-list-prompt";import"winston";import"winston-daily-rotate-file";import"axios";import"url";import"node:fs/promises";import"chokidar";import"rxjs/operators";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import h from"chalk";import{concatMap as f,from as u,map as g,catchError as C}from"rxjs";import{fromPromise as y}from"rxjs/internal/observable/innerFrom";import{A,l as b,a as w,b as P,c as I,e as v,d as M}from"./ai.service-
|
|
1
|
+
import h from"chalk";import{concatMap as f,from as u,map as g,catchError as C}from"rxjs";import{fromPromise as y}from"rxjs/internal/observable/innerFrom";import{A,l as b,a as w,b as P,c as I,e as v,d as M}from"./ai.service-c5f81726.mjs";import{b as k,g as R,n as x,H as $}from"./cli-3a375308.mjs";import"fs";import"path";import"@pacote/xxhash";import"winston";import"cleye";import"module";import"crypto";import"os";import"node:buffer";import"node:path";import"node:child_process";import"node:process";import"child_process";import"node:url";import"node:os";import"assert";import"events";import"node:fs";import"buffer";import"stream";import"util";import"node:util";import"inquirer";import"fs/promises";import"readline";import"figlet";import"gradient-string";import"ora";import"inquirer-reactive-list-prompt";import"winston-daily-rotate-file";import"axios";import"url";import"node:fs/promises";import"chokidar";import"rxjs/operators";class S extends A{constructor(t){super(t),this.params=t,this.apiKey="",this.colors={primary:"#e28c58",secondary:"#fff"},this.serviceName=h.bgHex(this.colors.primary).hex(this.colors.secondary).bold(`[Codestral${this.formatModelSuffix()}]`),this.errorPrefix=h.red.bold(`[Codestral${this.formatModelSuffix()}]`),this.apiKey=this.params.config.key}getServiceSpecificErrorMessage(t){const e=t.message||"";return e.includes("API key")||e.includes("api_key")?"Invalid API key. Check your Codestral API key in configuration":e.includes("rate_limit")||e.includes("Rate limit")?"Rate limit exceeded. Wait a moment and try again, or upgrade your Codestral plan":e.includes("model")||e.includes("Model")?"Model not found or not accessible. Check if the Codestral model name is correct":e.includes("Invalid model type")?"Invalid model type. Use supported models: codestral-latest, codestral-2501":e.includes("overloaded")||e.includes("capacity")?"Codestral service is overloaded. Try again in a few minutes":e.includes("403")||e.includes("Forbidden")?"Access denied. Your API key may not have permission for this Codestral model":e.includes("404")||e.includes("Not Found")?"Model or endpoint not found. Check your Codestral model configuration":e.includes("500")||e.includes("Internal Server Error")?"Codestral server error. Try again later":null}generateCommitMessage$(){return y(this.generateMessage("commit")).pipe(f(t=>u(t)),g(this.formatAsChoice),C(this.handleError$))}generateCodeReview$(){return y(this.generateMessage("review")).pipe(f(t=>u(t)),g(this.formatCodeReviewAsChoice),C(this.handleError$))}async generateMessage(t){const e=this.params.stagedDiff.diff,{logging:o,generate:s,type:m}=this.params.config,i=this.buildPromptOptions(),n=t==="review"?k(i):R(i);this.checkAvailableModels();const a=this.buildUserPrompt(e,t),c=`${this.params.config.url||"https://codestral.mistral.ai"}/v1/chat/completions`,r={Authorization:`Bearer ${this.apiKey}`,"content-type":"application/json"};b(e,t,"Codestral",this.params.config.model,c,r,o),w(e,t,"Codestral",n,a,o);const l=await this.createChatCompletions(n,t);return t==="review"?this.parseCodeReview(l):this.parseMessage(l,m,s)}checkAvailableModels(){if(["codestral-latest","codestral-2501"].includes(this.params.config.model))return!0;throw new Error("Invalid model type of Codestral AI")}async createChatCompletions(t,e){const o=this.params.stagedDiff.diff,{logging:s}=this.params.config,m=this.params.config.url||"https://codestral.mistral.ai",i={model:this.params.config.model,messages:[{role:"system",content:t},{role:"user",content:this.buildUserPrompt(this.params.stagedDiff.diff,e)}],temperature:this.params.config.temperature,top_p:this.params.config.topP,max_tokens:this.params.config.maxTokens,stream:!1,safe_prompt:!1,random_seed:x(10,1e3)};e==="commit"&&(i.response_format={type:"json_object"}),P(o,e,"Codestral",i,s);const n=Date.now();try{const d=await new $({method:"POST",baseURL:`${m}/v1/chat/completions`,timeout:this.params.config.timeout}).setHeaders({Authorization:`Bearer ${this.apiKey}`,"content-type":"application/json"}).setBody(i).execute(),c=Date.now()-n,r=d.data;if(I(o,e,"Codestral",r,s),!r.choices||r.choices.length===0||!r.choices[0].message?.content)throw v(o,e,"Codestral",{message:"No Content on response",result:r},s),new Error("No Content on response. Please open a Bug report");const p=r.choices[0].message.content;return M(o,e,"Codestral",c,p,s),p}catch(a){throw v(o,e,"Codestral",a,s),a}}}export{S as CodestralService};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import c from"chalk";import{CohereClientV2 as P}from"cohere-ai";import{concatMap as p,from as d,map as l,catchError as h}from"rxjs";import{fromPromise as f}from"rxjs/internal/observable/innerFrom";import{A as M,l as k,a as x,b,c as R,d as E,e as S}from"./ai.service-
|
|
1
|
+
import c from"chalk";import{CohereClientV2 as P}from"cohere-ai";import{concatMap as p,from as d,map as l,catchError as h}from"rxjs";import{fromPromise as f}from"rxjs/internal/observable/innerFrom";import{A as M,l as k,a as x,b,c as R,d as E,e as S}from"./ai.service-c5f81726.mjs";import{b as $,g as V,n as D}from"./cli-3a375308.mjs";import"fs";import"path";import"@pacote/xxhash";import"winston";import"cleye";import"module";import"crypto";import"os";import"node:buffer";import"node:path";import"node:child_process";import"node:process";import"child_process";import"node:url";import"node:os";import"assert";import"events";import"node:fs";import"buffer";import"stream";import"util";import"node:util";import"inquirer";import"fs/promises";import"readline";import"figlet";import"gradient-string";import"ora";import"inquirer-reactive-list-prompt";import"winston-daily-rotate-file";import"axios";import"url";import"node:fs/promises";import"chokidar";import"rxjs/operators";class N extends M{constructor(r){super(r),this.params=r,this.colors={primary:"#D18EE2",secondary:"#fff"},this.serviceName=c.bgHex(this.colors.primary).hex(this.colors.secondary).bold(`[Cohere${this.formatModelSuffix()}]`),this.errorPrefix=c.red.bold(`[Cohere${this.formatModelSuffix()}]`),this.cohere=new P({token:this.params.config.key})}isValidCohereV2Response(r){const e=r;return e?.message?.content!==void 0&&Array.isArray(e.message.content)&&e.message.content.length>0&&typeof e.message.content[0]?.text=="string"}getServiceSpecificErrorMessage(r){const e=r.message||"";return e.includes("API key")||e.includes("api_key")?"Invalid API key. Check your Cohere API key in configuration":e.includes("rate_limit")||e.includes("Rate limit")?"Rate limit exceeded. Wait a moment and try again, or upgrade your Cohere plan":e.includes("model")||e.includes("Model")?"Model not found or not accessible. Check if the Cohere model name is correct":e.includes("overloaded")||e.includes("capacity")?"Cohere service is overloaded. Try again in a few minutes":e.includes("403")||e.includes("Forbidden")?"Access denied. Your API key may not have permission for this Cohere model":e.includes("404")||e.includes("Not Found")?"Model or endpoint not found. Check your Cohere model configuration":e.includes("500")||e.includes("Internal Server Error")?"Cohere server error. Try again later":null}generateCommitMessage$(){return f(this.generateMessage("commit")).pipe(p(r=>d(r)),l(this.formatAsChoice),h(this.handleError$))}generateCodeReview$(){return f(this.generateMessage("review")).pipe(p(r=>d(r)),l(this.formatCodeReviewAsChoice),h(this.handleError$))}async generateMessage(r){const e=this.params.stagedDiff.diff,{logging:o,temperature:g,generate:u,type:C,maxTokens:v}=this.params.config,n=this.buildPromptOptions(),i=r==="review"?$(n):V(n),a=`Here is the diff: ${e}`,y=[...i?[{role:"system",content:i}]:[],{role:"user",content:a}],A=`${this.params.config.url}/v2/chat`;k(e,r,"Cohere",this.params.config.model,A,{},o),x(e,r,"Cohere",i,a,o);const m={model:this.params.config.model,messages:y,max_tokens:v,temperature:g,seed:D(10,1e3),p:this.params.config.topP};b(e,r,"Cohere",m,o);const I=Date.now();try{const t=await this.cohere.chat(m,{timeoutInSeconds:Math.floor(this.params.config.timeout/1e3)}),w=Date.now()-I;if(!this.isValidCohereV2Response(t))throw new Error("Invalid response structure from Cohere v2 API");const s=t.message.content[0].text;return R(e,r,"Cohere",t,o),E(e,r,"Cohere",w,s,o),r==="review"?this.parseCodeReview(s):this.parseMessage(s,C,u)}catch(t){throw S(e,r,"Cohere",t,o),t}}}export{N as CohereService};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import E from"chalk";import{concatMap as O,from as S,map as _,catchError as A}from"rxjs";import{fromPromise as I}from"rxjs/internal/observable/innerFrom";import{A as P,l as b,a as y,b as U,c as R,d as x,e as z}from"./ai.service-
|
|
1
|
+
import E from"chalk";import{concatMap as O,from as S,map as _,catchError as A}from"rxjs";import{fromPromise as I}from"rxjs/internal/observable/innerFrom";import{A as P,l as b,a as y,b as U,c as R,d as x,e as z}from"./ai.service-c5f81726.mjs";import{b as B,g as H}from"./cli-3a375308.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 L="gpt-4.1",$=["gpt-4.1","gpt-4o","gpt-5-mini"],D={"openai/gpt-4.1":"gpt-4.1","openai/gpt-4o":"gpt-4o","openai/gpt-5-mini":"gpt-5-mini"},F=e=>{const o=(e||"").trim().toLowerCase();return o?o in D?D[o]:o.includes("/")&&o.split("/").pop()||o:L},G=e=>[F(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")},T=e=>{const o=e.toLowerCase();return o.includes("auth")||o.includes("unauthorized")||o.includes("forbidden")||o.includes("token")||o.includes("copilot cli")},j=e=>{const o=e.toLowerCase();return o.includes("classic personal access tokens")&&o.includes("ghp_")},V=(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 W extends P{constructor(o){super(o),this.params=o,this.colors={primary:"#8957e5",secondary:"#FFF"},this.serviceName=E.bgHex(this.colors.primary).hex(this.colors.secondary).bold(`[Copilot SDK${this.formatModelSuffix()}]`),this.errorPrefix=E.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":j(t)?"Copilot rejected classic ghp_ token. Use COPILOT_GITHUB_TOKEN with a Fine-Grained PAT or authenticate via copilot /login.":o.code==="AUTHENTICATION_FAILED"||T(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 I(this.generateMessage("commit")).pipe(O(o=>S(o)),_(this.formatAsChoice),A(this.handleError$))}generateCodeReview$(){return I(this.generateMessage("review")).pipe(O(o=>S(o)),_(this.formatCodeReviewAsChoice),A(this.handleError$))}async generateMessage(o){const t=this.params.stagedDiff.diff,{generate:i,type:r}=this.params.config,s=this.buildPromptOptions(),a=o==="review"?B(s):H(s),h=o==="review"?t:`Here's the diff:
|
|
2
2
|
|
|
3
3
|
${t}`,l=await this.makeRequest(a,h,o,t);return o==="review"?this.parseCodeReview(l):this.parseMessage(l,r,i)}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,s=i?.content;if(typeof r=="string")return r.trim();if(typeof s=="string")return s.trim();const a=i?.message?.content;return typeof a=="string"?a.trim():""}async makeRequest(o,t,i,r){const{CopilotClient:s,approveAll:a}=await this.loadSdkModule(),h=Array.isArray(this.params.config.model)?this.params.config.model[0]:this.params.config.model||L,l=G(h),{logging:c}=this.params.config;let C;for(const m of l){const w="copilot-sdk://session",K={Authorization:"Copilot CLI session"},M={model:m,prompt:t};b(r,i,"Copilot SDK",m,w,K,c),y(r,i,"Copilot SDK",o,t,c),U(r,i,"Copilot SDK",M,c);const k=Date.now();let u;try{const p=V(process.env);u=new s(p);const d=await(await u.createSession({model:m,onPermissionRequest:a})).sendAndWait({prompt:`${o}
|
|
4
4
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import u from"chalk";import U from"openai";import{concatMap as k,from as S,map as y,catchError as D}from"rxjs";import{fromPromise as v}from"rxjs/internal/observable/innerFrom";import{A as _,l as w,a as C,b as A,c as P,d as M,e as I}from"./ai.service-
|
|
1
|
+
import u from"chalk";import U from"openai";import{concatMap as k,from as S,map as y,catchError as D}from"rxjs";import{fromPromise as v}from"rxjs/internal/observable/innerFrom";import{A as _,l as w,a as C,b as A,c as P,d as M,e as I}from"./ai.service-c5f81726.mjs";import{g as b,b as O}from"./cli-3a375308.mjs";import"fs";import"path";import"@pacote/xxhash";import"winston";import"cleye";import"module";import"crypto";import"os";import"node:buffer";import"node:path";import"node:child_process";import"node:process";import"child_process";import"node:url";import"node:os";import"assert";import"events";import"node:fs";import"buffer";import"stream";import"util";import"node:util";import"inquirer";import"fs/promises";import"readline";import"figlet";import"gradient-string";import"ora";import"inquirer-reactive-list-prompt";import"winston-daily-rotate-file";import"axios";import"url";import"node:fs/promises";import"chokidar";import"rxjs/operators";class z extends _{constructor(t){super(t),this.params=t,this.generateStreamingCommitMessage$=()=>{const{generate:s,type:o}=this.params.config;return this.createStreamingCommitMessages$(r=>{this.streamChunks(r).catch(i=>r.error(i))},o,s)},this.streamChunks=async s=>{const o=this.params.stagedDiff.diff,{logging:r}=this.params.config,i=b(this.buildPromptOptions());this.checkAvailableModels();const m=this.buildUserPrompt(o,"commit"),c=`${this.params.config.url||"https://api.deepseek.com"}/chat/completions`,p={Authorization:`Bearer ${this.params.config.key}`,"Content-Type":"application/json"};w(o,"commit","DeepSeek",this.params.config.model,c,p,r),C(o,"commit","DeepSeek",i,m,r);const n={messages:[{role:"system",content:i},{role:"user",content:m}],model:this.params.config.model,max_tokens:this.params.config.maxTokens,top_p:this.params.config.topP,temperature:this.params.config.temperature,stream:!0};A(o,"commit","DeepSeek",n,r);const l=Date.now();let d="";try{const x=await this.deepSeek.chat.completions.create(n,{timeout:this.params.config.timeout});for await(const g of x){const R=g.choices?.[0]?.delta?.content||"",E=g.choices?.[0]?.delta?.reasoning_content||"",f=`${R}${E}`;f&&(d+=f,s.next(f))}const $=Date.now()-l;P(o,"commit","DeepSeek",{streamed:!0,totalLength:d.length},r),M(o,"commit","DeepSeek",$,d,r),s.complete()}catch(h){I(o,"commit","DeepSeek",h,r),s.error(h)}},this.colors={primary:"#53a3f9",secondary:"#fff"},this.serviceName=u.bgHex(this.colors.primary).hex(this.colors.secondary).bold(`[DeepSeek${this.formatModelSuffix()}]`),this.errorPrefix=u.red.bold(`[DeepSeek${this.formatModelSuffix()}]`);const e=this.params.config.url||"https://api.deepseek.com";this.deepSeek=new U({baseURL:e,apiKey:this.params.config.key})}getServiceSpecificErrorMessage(t){const e=t.message||"";return e.includes("API key")||e.includes("api_key")?"Invalid API key. Check your DeepSeek API key in configuration":e.includes("rate_limit")||e.includes("Rate limit")?"Rate limit exceeded. Wait a moment and try again, or upgrade your DeepSeek plan":e.includes("model")||e.includes("Model")?"Model not found or not accessible. Check if the DeepSeek model name is correct":e.includes("Invalid model type")?"Invalid model type. Use supported models: deepseek-reasoner, deepseek-chat":e.includes("overloaded")||e.includes("capacity")?"DeepSeek service is overloaded. Try again in a few minutes":e.includes("403")||e.includes("Forbidden")?"Access denied. Your API key may not have permission for this DeepSeek model":e.includes("404")||e.includes("Not Found")?"Model or endpoint not found. Check your DeepSeek model configuration":e.includes("500")||e.includes("Internal Server Error")?"DeepSeek server error. Try again later":null}generateCommitMessage$(){return this.params.config.stream||!1?this.generateStreamingCommitMessage$():v(this.generateMessage("commit")).pipe(k(e=>S(e)),y(this.formatAsChoice),D(this.handleError$))}generateCodeReview$(){return v(this.generateMessage("review")).pipe(k(t=>S(t)),y(this.formatCodeReviewAsChoice),D(this.handleError$))}async generateMessage(t){const e=this.params.stagedDiff.diff,{logging:s,generate:o,type:r}=this.params.config,i=this.buildPromptOptions(),m=t==="review"?O(i):b(i);this.checkAvailableModels();const a=this.buildUserPrompt(e,t),p=`${this.params.config.url||"https://api.deepseek.com"}/chat/completions`,n={Authorization:`Bearer ${this.params.config.key}`,"Content-Type":"application/json"};w(e,t,"DeepSeek",this.params.config.model,p,n,s),C(e,t,"DeepSeek",m,a,s);const l=await this.createChatCompletions(m,a,t);return t==="review"?this.parseCodeReview(l):this.parseMessage(l,r,o)}checkAvailableModels(){if(["deepseek-reasoner","deepseek-chat"].includes(this.params.config.model))return!0;throw new Error("Invalid model type of DeepSeek")}async createChatCompletions(t,e,s){const o=this.params.stagedDiff.diff,{logging:r}=this.params.config,i={messages:[{role:"system",content:t},{role:"user",content:e}],model:this.params.config.model,max_tokens:this.params.config.maxTokens,top_p:this.params.config.topP,temperature:this.params.config.temperature};A(o,s,"DeepSeek",i,r);const m=Date.now();try{const a=await this.deepSeek.chat.completions.create(i,{timeout:this.params.config.timeout}),c=Date.now()-m,p=a.choices?.[0];if(!p?.message)throw new Error("DeepSeek API returned invalid response structure");const n=p.message.content||p.message.reasoning_content||"";if(!n)throw new Error("DeepSeek API returned empty response");return P(o,s,"DeepSeek",a,r),M(o,s,"DeepSeek",c,n,r),n}catch(a){throw I(o,s,"DeepSeek",a,r),a}}}export{z as DeepSeekService};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{HarmCategory as r,HarmBlockThreshold as s,GoogleGenerativeAI as B}from"@google/generative-ai";import T from"chalk";import{concatMap as G,from as M,map as I,catchError as S}from"rxjs";import{fromPromise as P}from"rxjs/internal/observable/innerFrom";import{A as H,l as x,a as R,b as v,c as L,d as N,e as w}from"./ai.service-
|
|
1
|
+
import{HarmCategory as r,HarmBlockThreshold as s,GoogleGenerativeAI as B}from"@google/generative-ai";import T from"chalk";import{concatMap as G,from as M,map as I,catchError as S}from"rxjs";import{fromPromise as P}from"rxjs/internal/observable/innerFrom";import{A as H,l as x,a as R,b as v,c as L,d as N,e as w}from"./ai.service-c5f81726.mjs";import{g as D,b as $}from"./cli-3a375308.mjs";import"fs";import"path";import"@pacote/xxhash";import"winston";import"cleye";import"module";import"crypto";import"os";import"node:buffer";import"node:path";import"node:child_process";import"node:process";import"child_process";import"node:url";import"node:os";import"assert";import"events";import"node:fs";import"buffer";import"stream";import"util";import"node:util";import"inquirer";import"fs/promises";import"readline";import"figlet";import"gradient-string";import"ora";import"inquirer-reactive-list-prompt";import"winston-daily-rotate-file";import"axios";import"url";import"node:fs/promises";import"chokidar";import"rxjs/operators";class Y extends H{constructor(t){super(t),this.params=t,this.generateStreamingCommitMessage$=()=>{const{generate:e,type:o}=this.params.config;return this.createStreamingCommitMessages$(i=>{this.streamChunks(i).catch(c=>i.error(c))},o,e)},this.streamChunks=async e=>{const o=this.params.stagedDiff.diff,{logging:i}=this.params.config,c=this.params.config.maxTokens,p=D(this.buildPromptOptions()),d={maxOutputTokens:c,temperature:this.params.config.temperature,topP:this.params.config.topP},g=this.genAI.getGenerativeModel({model:this.params.config.model,systemInstruction:p,generationConfig:d,safetySettings:[{category:r.HARM_CATEGORY_HATE_SPEECH,threshold:s.BLOCK_LOW_AND_ABOVE},{category:r.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:s.BLOCK_LOW_AND_ABOVE},{category:r.HARM_CATEGORY_HARASSMENT,threshold:s.BLOCK_LOW_AND_ABOVE},{category:r.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:s.BLOCK_LOW_AND_ABOVE}]}),n=this.buildUserPrompt(o,"commit"),l=`${this.params.config.url||"https://generativelanguage.googleapis.com"}/v1beta/models/${this.params.config.model}:streamGenerateContent`,y={"Content-Type":"application/json","x-goog-api-key":this.params.config.key};x(o,"commit","Gemini",this.params.config.model,l,y,i),R(o,"commit","Gemini",p,n,i),v(o,"commit","Gemini",{systemInstruction:{parts:[{text:p}]},contents:[{parts:[{text:n}]}],generationConfig:d},i);const O=Date.now();let f="";try{const a=this.params.config.timeout>1e4?{request:{timeout:this.params.config.timeout}}:void 0,m=await g.generateContentStream(n,a);for await(const h of m.stream){const A=h.text();A&&(f+=A,e.next(A))}const u=Date.now()-O;L(o,"commit","Gemini",{streamed:!0,totalLength:f.length},i),N(o,"commit","Gemini",u,f,i),e.complete()}catch(a){w(o,"commit","Gemini",a,i),e.error(a)}},this.colors={primary:"#0077FF",secondary:"#fff"},this.serviceName=T.bgHex(this.colors.primary).hex(this.colors.secondary).bold(`[Gemini${this.formatModelSuffix()}]`),this.errorPrefix=T.red.bold(`[Gemini${this.formatModelSuffix()}]`),this.genAI=new B(this.params.config.key)}getServiceSpecificErrorMessage(t){const e=t.message||"";return e.includes("API key")||e.includes("api_key")?"Invalid API key. Check your Google AI Studio API key in configuration":e.includes("quota")||e.includes("QUOTA_EXCEEDED")?"API quota exceeded. Check your Google AI Studio usage limits":e.includes("model")||e.includes("Model")?"Model not found or not accessible. Check if the Gemini model name is correct":e.includes("SAFETY")||e.includes("safety")?"Content blocked by safety filters. Try rephrasing your request":e.includes("RECITATION")||e.includes("recitation")?"Content blocked due to recitation concerns. Try a different approach":e.includes("403")||e.includes("Forbidden")?"Access denied. Your API key may not have permission for this Gemini model":e.includes("404")||e.includes("Not Found")?"Model or endpoint not found. Check your Gemini model configuration":e.includes("500")||e.includes("Internal Server Error")?"Google AI service error. Try again later":e.includes("MAX_TOKENS")||e.includes("truncated")||e.includes("maxOutputTokens")?"Response truncated due to token limit. Gemini 2.5+ models use thinking tokens. Try increasing maxTokens (recommended: 8192+)":null}generateCommitMessage$(){return this.params.config.stream||!1?this.generateStreamingCommitMessage$():P(this.generateMessage("commit")).pipe(G(e=>M(e)),I(this.formatAsChoice),S(this.handleError$))}generateCodeReview$(){return P(this.generateMessage("review")).pipe(G(t=>M(t)),I(this.formatCodeReviewAsChoice),S(this.handleError$))}async generateMessage(t){const e=this.params.stagedDiff.diff,{logging:o,generate:i,type:c}=this.params.config,p=this.params.config.maxTokens,d=this.buildPromptOptions(),g=t==="review"?$(d):D(d),n={maxOutputTokens:p,temperature:this.params.config.temperature,topP:this.params.config.topP},_=this.genAI.getGenerativeModel({model:this.params.config.model,systemInstruction:g,generationConfig:n,safetySettings:[{category:r.HARM_CATEGORY_HATE_SPEECH,threshold:s.BLOCK_LOW_AND_ABOVE},{category:r.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:s.BLOCK_LOW_AND_ABOVE},{category:r.HARM_CATEGORY_HARASSMENT,threshold:s.BLOCK_LOW_AND_ABOVE},{category:r.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:s.BLOCK_LOW_AND_ABOVE}]}),l=this.buildUserPrompt(e,t),E=`${this.params.config.url||"https://generativelanguage.googleapis.com"}/v1beta/models/${this.params.config.model}:generateContent`,O={"Content-Type":"application/json","x-goog-api-key":this.params.config.key};x(e,t,"Gemini",this.params.config.model,E,O,o),R(e,t,"Gemini",g,l,o),v(e,t,"Gemini",{systemInstruction:{parts:[{text:g}]},contents:[{parts:[{text:l}]}],generationConfig:n},o);const a=Date.now();try{const m=this.params.config.timeout>1e4?{request:{timeout:this.params.config.timeout}}:void 0,u=await _.generateContent(l,m),h=u.response;if(h.candidates?.[0]?.finishReason==="MAX_TOKENS"){const k=h.usageMetadata;throw new Error(`Response truncated: maxOutputTokens exceeded. Thinking tokens: ${k?.thoughtsTokenCount??"N/A"}, Output tokens: ${k?.candidatesTokenCount??"N/A"}. Increase maxTokens config for Gemini 2.5+ thinking models.`)}const C=h.text(),b=Date.now()-a;return L(e,t,"Gemini",{response:C,candidates:u.response.candidates,usageMetadata:u.response.usageMetadata},o),N(e,t,"Gemini",b,C,o),t==="review"?this.parseCodeReview(C):this.parseMessage(C,c,i)}catch(m){throw w(e,t,"Gemini",m,o),m}}}export{Y as GeminiService};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import _ from"chalk";import{concatMap as A,from as D,map as N,catchError as O}from"rxjs";import{fromPromise as S}from"rxjs/internal/observable/innerFrom";import{A as T,l as R,a as C,b as L,e as E,c as $,d as k}from"./ai.service-
|
|
1
|
+
import _ from"chalk";import{concatMap as A,from as D,map as N,catchError as O}from"rxjs";import{fromPromise as S}from"rxjs/internal/observable/innerFrom";import{A as T,l as R,a as C,b as L,e as E,c as $,d as k}from"./ai.service-c5f81726.mjs";import{G as v,b as x,g as U,q as y,r as P,t as F,u as B}from"./cli-3a375308.mjs";import{i as j}from"./openai-e13f148b.mjs";import"fs";import"path";import"@pacote/xxhash";import"winston";import"cleye";import"module";import"crypto";import"os";import"node:buffer";import"node:path";import"node:child_process";import"node:process";import"child_process";import"node:url";import"node:os";import"assert";import"events";import"node:fs";import"buffer";import"stream";import"util";import"node:util";import"inquirer";import"fs/promises";import"readline";import"figlet";import"gradient-string";import"ora";import"inquirer-reactive-list-prompt";import"winston-daily-rotate-file";import"axios";import"url";import"node:fs/promises";import"chokidar";import"rxjs/operators";import"http";import"https";import"net";import"tls";import"tty";class V extends T{constructor(r){super(r),this.params=r,this.baseURL=v,this.colors={primary:"#24292e",secondary:"#FFF"},this.serviceName=_.bgHex(this.colors.primary).hex(this.colors.secondary).bold(`[GitHub Models${this.formatModelSuffix()}]`),this.errorPrefix=_.red.bold(`[GitHub Models${this.formatModelSuffix()}]`)}getServiceSpecificErrorMessage(r){switch(r.code){case"MISSING_TOKEN":return"GitHub token is required. Run: aicommit2 github-login";case"AUTHENTICATION_FAILED":return"Authentication failed. Your GitHub token may be expired or invalid. Run: aicommit2 github-login";case"ACCESS_DENIED":return'Access denied. Make sure your token has "models: read" permission in GitHub settings';case"INVALID_MODEL_ID":return'Invalid model ID. Use format "publisher/model" (example: openai/gpt-4o-mini)';case"MODEL_NOT_FOUND":return"Model not found in GitHub Models catalog. Check with: gh models list";case"NO_CONTENT":return"No content received from GitHub Models. The model may have failed to generate a response";default:return null}}generateCommitMessage$(){return S(this.generateMessage("commit")).pipe(A(r=>D(r)),N(this.formatAsChoice),O(this.handleError$))}generateCodeReview$(){return S(this.generateMessage("review")).pipe(A(r=>D(r)),N(this.formatCodeReviewAsChoice),O(this.handleError$))}async generateMessage(r){if(!this.params.config.key){const u=new Error("GitHub token is required for GitHub Models. Use: aicommit2 github-login");throw u.code="MISSING_TOKEN",u}const s=this.params.stagedDiff.diff,{generate:i,type:f}=this.params.config,n=this.buildPromptOptions(),M=r==="review"?x(n):U(n),p=await this.makeRequest(M,s,r);return r==="review"?this.parseCodeReview(p):this.parseMessage(p,f,i)}async makeRequest(r,s,i){const f=Array.isArray(this.params.config.model)?this.params.config.model[0]:this.params.config.model||y;let n;try{n=P(f)}catch(o){const e=new Error(o instanceof Error?o.message:String(o));throw e.code="INVALID_MODEL_ID",e}const M=[{role:"system",content:r},{role:"user",content:i==="review"?s:`Here's the diff:
|
|
2
2
|
|
|
3
3
|
${s}`}],p=j(n),u={messages:M,model:n,stream:!1,...p?{max_completion_tokens:this.params.config.maxTokens||1024,temperature:1}:{max_tokens:this.params.config.maxTokens||1024,top_p:this.params.config.topP||.95,temperature:this.params.config.temperature||.7}},b=`${this.baseURL}${F}`,w={"Content-Type":"application/json",Accept:"application/vnd.github+json","X-GitHub-Api-Version":B,Authorization:`Bearer ${this.params.config.key}`},{logging:m}=this.params.config;R(s,i,"GitHub Models",n,b,w,m),C(s,i,"GitHub Models",r,i==="review"?s:`Here's the diff:
|
|
4
4
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import G from"chalk";import b from"groq-sdk";import{concatMap as q,from as k,map as v,catchError as C}from"rxjs";import{fromPromise as P}from"rxjs/internal/observable/innerFrom";import{A as R,l as w,a as A,b as x,c as M,d as $,e as S}from"./ai.service-
|
|
1
|
+
import G from"chalk";import b from"groq-sdk";import{concatMap as q,from as k,map as v,catchError as C}from"rxjs";import{fromPromise as P}from"rxjs/internal/observable/innerFrom";import{A as R,l as w,a as A,b as x,c as M,d as $,e as S}from"./ai.service-c5f81726.mjs";import{g as I,b as D}from"./cli-3a375308.mjs";import"fs";import"path";import"@pacote/xxhash";import"winston";import"cleye";import"module";import"crypto";import"os";import"node:buffer";import"node:path";import"node:child_process";import"node:process";import"child_process";import"node:url";import"node:os";import"assert";import"events";import"node:fs";import"buffer";import"stream";import"util";import"node:util";import"inquirer";import"fs/promises";import"readline";import"figlet";import"gradient-string";import"ora";import"inquirer-reactive-list-prompt";import"winston-daily-rotate-file";import"axios";import"url";import"node:fs/promises";import"chokidar";import"rxjs/operators";class E extends R{constructor(t){super(t),this.params=t,this.generateStreamingCommitMessage$=()=>{const{generate:o,type:e}=this.params.config;return this.createStreamingCommitMessages$(r=>{this.streamChunks(r).catch(m=>r.error(m))},e,o)},this.streamChunks=async o=>{const e=this.params.stagedDiff.diff,{logging:r,temperature:m}=this.params.config,d=this.params.config.maxTokens,p=I(this.buildPromptOptions()),c=`Here is the diff: ${e}`,l=`${this.params.config.url||"https://api.groq.com"}/openai/v1/chat/completions`,y={Authorization:`Bearer ${this.params.config.key}`,"Content-Type":"application/json"};w(e,"commit","Groq",this.params.config.model,l,y,r),A(e,"commit","Groq",p,c,r);const h={messages:[{role:"system",content:p},{role:"user",content:c}],model:this.params.config.model,max_tokens:d,top_p:this.params.config.topP,temperature:m,stream:!0};x(e,"commit","Groq",h,r);const f=Date.now();let a="";try{const n=await this.groq.chat.completions.create(h,{timeout:this.params.config.timeout});for await(const u of n){const s=u.choices?.[0]?.delta?.content||"";s&&(a+=s,o.next(s))}const i=Date.now()-f;M(e,"commit","Groq",{streamed:!0,totalLength:a.length},r),$(e,"commit","Groq",i,a,r),o.complete()}catch(n){S(e,"commit","Groq",n,r),o.error(n)}},this.colors={primary:"#f55036",secondary:"#fff"},this.serviceName=G.bgHex(this.colors.primary).hex(this.colors.secondary).bold(`[Groq${this.formatModelSuffix()}]`),this.errorPrefix=G.red.bold(`[Groq${this.formatModelSuffix()}]`),this.groq=new b({apiKey:this.params.config.key})}getServiceSpecificErrorMessage(t){const o=t.message||"";return o.includes("API key")||o.includes("api_key")?"Invalid API key. Check your Groq API key in configuration":o.includes("rate_limit")||o.includes("Rate limit")?"Rate limit exceeded. Wait a moment and try again, or upgrade your Groq plan":o.includes("model")||o.includes("Model")?"Model not found or not accessible. Check if the Groq model name is correct":o.includes("overloaded")||o.includes("capacity")?"Groq service is overloaded. Try again in a few minutes":o.includes("403")||o.includes("Forbidden")?"Access denied. Your API key may not have permission for this Groq model":o.includes("404")||o.includes("Not Found")?"Model or endpoint not found. Check your Groq model configuration":o.includes("500")||o.includes("Internal Server Error")?"Groq server error. Try again later":null}generateCommitMessage$(){return this.params.config.stream||!1?this.generateStreamingCommitMessage$():P(this.generateMessage("commit")).pipe(q(o=>k(o)),v(this.formatAsChoice),C(this.handleError$))}generateCodeReview$(){return P(this.generateMessage("review")).pipe(q(t=>k(t)),v(this.formatCodeReviewAsChoice),C(this.handleError$))}async generateMessage(t){const o=this.params.stagedDiff.diff,{logging:e,temperature:r,generate:m,type:d}=this.params.config,p=this.params.config.maxTokens,c=this.buildPromptOptions(),g=t==="review"?D(c):I(c),l=`Here is the diff: ${o}`,h=`${this.params.config.url||"https://api.groq.com"}/openai/v1/chat/completions`,f={Authorization:`Bearer ${this.params.config.key}`,"Content-Type":"application/json"};w(o,t,"Groq",this.params.config.model,h,f,e),A(o,t,"Groq",g,l,e);const a={messages:[{role:"system",content:g},{role:"user",content:l}],model:this.params.config.model,max_tokens:p,top_p:this.params.config.topP,temperature:r};x(o,t,"Groq",a,e);const n=Date.now();try{const i=await this.groq.chat.completions.create(a,{timeout:this.params.config.timeout}),u=Date.now()-n,s=i.choices[0].message.content||"";return M(o,t,"Groq",i,e),$(o,t,"Groq",u,s,e),t==="review"?this.parseCodeReview(s):this.parseMessage(s,d,m)}catch(i){throw S(o,t,"Groq",i,e),i}}}export{E as GroqService};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import y from"chalk";import{concatMap as C,from as b,map as k,catchError as D}from"rxjs";import{fromPromise as E}from"rxjs/internal/observable/innerFrom";import{A as I,l as M,a as A,c as P,d as $,e as H}from"./ai.service-
|
|
1
|
+
import y from"chalk";import{concatMap as C,from as b,map as k,catchError as D}from"rxjs";import{fromPromise as E}from"rxjs/internal/observable/innerFrom";import{A as I,l as M,a as A,c as P,d as $,e as H}from"./ai.service-c5f81726.mjs";import{b as R,g as S}from"./cli-3a375308.mjs";import"fs";import"path";import"@pacote/xxhash";import"winston";import"cleye";import"module";import"crypto";import"os";import"node:buffer";import"node:path";import"node:child_process";import"node:process";import"child_process";import"node:url";import"node:os";import"assert";import"events";import"node:fs";import"buffer";import"stream";import"util";import"node:util";import"inquirer";import"fs/promises";import"readline";import"figlet";import"gradient-string";import"ora";import"inquirer-reactive-list-prompt";import"winston-daily-rotate-file";import"axios";import"url";import"node:fs/promises";import"chokidar";import"rxjs/operators";class U extends I{constructor(o){super(o),this.params=o,this.headers={},this.models=[],this.currentModelId=null,this.currentConversation=void 0,this.currentConversionID=void 0,this.cookie="",this.colors={primary:"#FED21F",secondary:"#000"},this.serviceName=y.bgHex(this.colors.primary).hex(this.colors.secondary).bold(`[HuggingFace${this.formatModelSuffix()}]`),this.errorPrefix=y.red.bold(`[HuggingFace${this.formatModelSuffix()}]`),this.cookie=this.params.config.cookie;const e=this.params.config.url||"https://huggingface.co";this.headers={accept:"*/*","accept-language":"en-US,en;q=0.9","sec-ch-ua":'"Chromium";v="116", "Not)A;Brand";v="24", "Google Chrome";v="116"',"sec-ch-ua-mobile":"?0","sec-ch-ua-platform":'"Windows"',"sec-fetch-dest":"empty","sec-fetch-mode":"cors","sec-fetch-site":"same-origin",origin:e,"Referrer-Policy":"strict-origin-when-cross-origin"}}getServiceSpecificErrorMessage(o){const e=o.message||"";return e.includes("cookie")||e.includes("Cookie")?"Invalid cookie. Check your Hugging Face session cookie in configuration":e.includes("model")||e.includes("Model")?"Model not found or not accessible. Check if the Hugging Face model name is correct":e.includes("conversation")||e.includes("conversion")?"Failed to create conversation. Try again or check your session":e.includes("401")||e.includes("Unauthorized")?"Authentication failed. Your Hugging Face session may have expired":e.includes("403")||e.includes("Forbidden")?"Access denied. You may not have permission to access this model":e.includes("404")||e.includes("Not Found")?"Model not found. Check your Hugging Face model configuration":e.includes("500")||e.includes("Internal Server Error")?"Hugging Face server error. Try again later":e.includes("overloaded")||e.includes("capacity")?"Hugging Face service is overloaded. Try again in a few minutes":null}generateCommitMessage$(){return E(this.generateMessage("commit")).pipe(C(o=>b(o)),k(this.formatAsChoice),D(this.handleError$))}generateCodeReview$(){return E(this.generateMessage("review")).pipe(C(o=>b(o)),k(this.formatCodeReviewAsChoice),D(this.handleError$))}async generateMessage(o){await this.initialize();const e=this.params.stagedDiff.diff,{logging:r,generate:t,type:l,temperature:m,maxTokens:i,topP:g,timeout:s}=this.params.config,p=this.buildPromptOptions(),a=o==="review"?R(p):S(p),w=`Here is the diff: ${e}`,f=`${this.params.config.url||"https://huggingface.co"}/chat/conversation`,n={...this.headers,cookie:this.cookie};M(e,o,"HuggingFace",this.params.config.model,f,n,r),A(e,o,"HuggingFace",a,w,r);const d=Date.now();try{const c=await this.getNewChat(a),u=await(await this.sendMessage(w,c.id)).completeResponsePromise();await this.deleteConversation(c.id);const F=Date.now()-d;return P(e,o,"HuggingFace",{response:u},r),$(e,o,"HuggingFace",F,u,r),o==="review"?this.parseCodeReview(u):this.parseMessage(u,l,t)}catch(c){throw H(e,o,"HuggingFace",c,r),c}}async initialize(){const o=await this.getRemoteLlms(),e=o.find(r=>r.name?.toLowerCase()===this.params.config.model.toLowerCase());if(e){this.currentModel=e,this.currentModelId=e.id;return}this.currentModel=o[0],this.currentModelId=o[0].id}async getRemoteLlms(){const o=this.params.config.url||"https://huggingface.co",e=await fetch(`${o}/chat/__data.json`,{headers:{...this.headers,cookie:this.cookie},body:null,method:"GET"});if(e.status!==200)throw new Error(`Failed to get remote LLMs with status code: ${e.status}`);const t=(await e.json()).nodes[0].data,l=t[t[0].models],m=[],i=g=>g===-1?null:t[g];for(const g of l){const s=t[g];if(t[s.unlisted])continue;const p={id:i(s.id),name:i(s.name),displayName:i(s.displayName),preprompt:i(s.preprompt),promptExamples:[],websiteUrl:i(s.websiteUrl),description:i(s.description),datasetName:i(s.datasetName),datasetUrl:i(s.datasetUrl),modelUrl:i(s.modelUrl),parameters:{}},a=i(s.promptExamples);if(a!==null){const f=a.map(n=>i(n));p.promptExamples=f.map(n=>({title:t[n.title],prompt:t[n.prompt]}))}const w=i(s.parameters),h={};for(const[f,n]of Object.entries(w)){if(n===-1){h[f]=null;continue}if(Array.isArray(t[n])){h[f]=t[n].map(d=>t[d]);continue}h[f]=t[n]}p.parameters=h,m.push(p)}return this.models=m,m}async getNewChat(o){const e={model:this.currentModelId,preprompt:o};let r=0;const t=this.params.config.url||"https://huggingface.co";for(;r<5;){const l=await fetch(`${t}/chat/conversation`,{headers:{...this.headers,"content-type":"application/json",cookie:this.cookie,Referer:`${t}/chat/`},body:JSON.stringify(e),method:"POST"}),{conversationId:m}=await l.json();if(m){this.currentConversionID=m;break}else r++}if(!this.currentConversionID)throw new Error("Failed to create new conversion");return await this.getConversationHistory(this.currentConversionID)}async getConversationHistory(o){if(!o)throw new Error("conversationId is required for getConversationHistory");const e=this.params.config.url||"https://huggingface.co",r=await fetch(`${e}/chat/conversation/${o}/__data.json`,{headers:{...this.headers,cookie:this.cookie,Referer:`${e}/chat/`},body:null,method:"GET"});if(r.status!=200)throw new Error("Unable get conversation details "+r);{const t=await r.json();return this.metadataParser(t,o)}}metadataParser(o,e){const r={id:"",model:"",systemPrompt:"",title:"",history:[]},t=o.nodes[1].data,l=t[t[0].model],m=t[t[0].preprompt],i=t[t[0].title],g=t[t[0].messages],s=[];for(const p of g){const a=t[p],w=new Date(t[a.createdAt][1]).getTime()/1e3,h=new Date(t[a.updatedAt][1]).getTime()/1e3;s.push({id:t[a.id],role:t[a.from],content:t[a.content],createdAt:w,updatedAt:h})}return r.id=e,r.model=l,r.systemPrompt=m,r.title=i,r.history=s,this.currentConversation=r,r}async sendMessage(o,e){if(o==="")throw new Error("the prompt can not be empty.");if(!e&&!this.currentConversionID?await this.getNewChat():e?(this.currentConversionID=e,await this.getConversationHistory(e)):this.currentConversionID&&await this.getConversationHistory(this.currentConversionID),!this.currentConversation)throw new Error("Failed to create new conversion");const r={inputs:o,id:this.currentConversation.history[this.currentConversation.history.length-1].id,is_retry:!1,is_continue:!1,web_search:!1,tools:[]},t=new FormData;t.append("data",JSON.stringify(r));const l=this.params.config.url||"https://huggingface.co",m=new AbortController,i=setTimeout(()=>m.abort(),this.params.config.timeout),g=await fetch(`${l}/chat/conversation/${this.currentConversionID}`,{headers:{...this.headers,cookie:this.cookie,Referer:`${l}/chat/conversation/${this.currentConversionID}`},body:t,method:"POST",signal:m.signal});clearTimeout(i);function s(n){try{const d=n.split(`
|
|
2
2
|
`),c=[];for(const v of d)v.trim()&&c.push(JSON.parse(v));return c}catch{return[{}]}}const p=new TextDecoder;let a="";const w=new TransformStream({async transform(n,d){const c=p.decode(n);try{const v=s(c);for(const u of v)u.type==="finalAnswer"?(a=u?.text||"",d.terminate()):u.type==="stream"&&d.enqueue(u?.token||"")}catch{throw new Error("Error during parsing response")}}}),h=g.body?.pipeThrough(w);async function f(){return new Promise(async(n,d)=>{try{if(!h)d("ModifiedStream undefined");else{const c=h.getReader();for(;;){const{done:v,value:u}=await c.read();if(v){n(a);break}}}}catch(c){d(c)}})}return{id:this.currentConversionID,stream:h,completeResponsePromise:f}}async deleteConversation(o){const e=this.params.config.url||"https://huggingface.co";return(await fetch(`${e}/chat/conversation/${o}`,{headers:{...this.headers,cookie:this.cookie,Referer:`${e}/chat/`},body:null,method:"DELETE"})).json()}}export{U as HuggingFaceService};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import h from"chalk";import{concatMap as f,from as u,map as g,catchError as A}from"rxjs";import{fromPromise as M}from"rxjs/internal/observable/innerFrom";import{A as v,l as b,a as w,b as C,c as P,e as I,d as k}from"./ai.service-
|
|
1
|
+
import h from"chalk";import{concatMap as f,from as u,map as g,catchError as A}from"rxjs";import{fromPromise as M}from"rxjs/internal/observable/innerFrom";import{A as v,l as b,a as w,b as C,c as P,e as I,d as k}from"./ai.service-c5f81726.mjs";import{b as $,g as x,H as y,n as R}from"./cli-3a375308.mjs";import"fs";import"path";import"@pacote/xxhash";import"winston";import"cleye";import"module";import"crypto";import"os";import"node:buffer";import"node:path";import"node:child_process";import"node:process";import"child_process";import"node:url";import"node:os";import"assert";import"events";import"node:fs";import"buffer";import"stream";import"util";import"node:util";import"inquirer";import"fs/promises";import"readline";import"figlet";import"gradient-string";import"ora";import"inquirer-reactive-list-prompt";import"winston-daily-rotate-file";import"axios";import"url";import"node:fs/promises";import"chokidar";import"rxjs/operators";class E extends v{constructor(e){super(e),this.params=e,this.apiKey="",this.colors={primary:"#ff7000",secondary:"#fff"},this.serviceName=h.bgHex(this.colors.primary).hex(this.colors.secondary).bold(`[MistralAI${this.formatModelSuffix()}]`),this.errorPrefix=h.red.bold(`[MistralAI${this.formatModelSuffix()}]`),this.apiKey=this.params.config.key}getServiceSpecificErrorMessage(e){const t=e.message||"";return t.includes("API key")||t.includes("api_key")?"Invalid API key. Check your Mistral AI API key in configuration":t.includes("quota")||t.includes("usage")?"API quota exceeded. Check your Mistral AI usage limits":t.includes("model")||t.includes("Model")?"Model not found or not accessible. Check if the Mistral model name is correct":t.includes("403")||t.includes("Forbidden")?"Access denied. Your API key may not have permission for this Mistral model":t.includes("404")||t.includes("Not Found")?"Model or endpoint not found. Check your Mistral model configuration":t.includes("500")||t.includes("Internal Server Error")?"Mistral AI server error. Try again later":null}generateCommitMessage$(){return M(this.generateMessage("commit")).pipe(f(e=>u(e)),g(this.formatAsChoice),A(this.handleError$))}generateCodeReview$(){return M(this.generateMessage("review")).pipe(f(e=>u(e)),g(this.formatCodeReviewAsChoice),A(this.handleError$))}async generateMessage(e){const t=this.params.stagedDiff.diff,{logging:o,generate:i,type:s}=this.params.config,n=this.buildPromptOptions(),m=e==="review"?$(n):x(n);await this.checkAvailableModels();const a=`Here is the diff: ${t}`,c=`${this.params.config.url||"https://api.mistral.ai"}/v1/chat/completions`,r={Authorization:`Bearer ${this.apiKey}`,"content-type":"application/json"};b(t,e,"MistralAI",this.params.config.model,c,r,o),w(t,e,"MistralAI",m,a,o);const l=await this.createChatCompletions(m,a,e);return e==="review"?this.parseCodeReview(l):this.parseMessage(l,s,i)}async checkAvailableModels(){if((await this.getAvailableModels()).includes(this.params.config.model))return!0;throw new Error(`Invalid model type of Mistral AI: ${this.params.config.model}`)}async getAvailableModels(){const e=this.params.config.url||"https://api.mistral.ai";return(await new y({method:"GET",baseURL:`${e}/v1/models`,timeout:this.params.config.timeout}).setHeaders({Authorization:`Bearer ${this.apiKey}`,"content-type":"application/json"}).execute()).data.data.filter(o=>o.object==="model").map(o=>o.id)}async createChatCompletions(e,t,o){const i=this.params.stagedDiff.diff,{logging:s}=this.params.config,n={model:this.params.config.model,messages:[{role:"system",content:e},{role:"user",content:t}],temperature:this.params.config.temperature,top_p:this.params.config.topP,max_tokens:this.params.config.maxTokens,stream:!1,safe_prompt:!1,random_seed:R(10,1e3)};C(i,o,"MistralAI",n,s);const m=Date.now();try{const a=this.params.config.url||"https://api.mistral.ai",p=await new y({method:"POST",baseURL:`${a}/v1/chat/completions`,timeout:this.params.config.timeout}).setHeaders({Authorization:`Bearer ${this.apiKey}`,"content-type":"application/json"}).setBody(n).execute(),c=Date.now()-m,r=p.data;if(P(i,o,"MistralAI",r,s),!r.choices||r.choices.length===0||!r.choices[0].message?.content)throw I(i,o,"MistralAI",{message:"No Content on response",result:r},s),new Error("No Content on response. Please open a Bug report");const d=r.choices[0].message.content;return k(i,o,"MistralAI",c,d,s),d}catch(a){throw I(i,o,"MistralAI",a,s),a}}}export{E as MistralService};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import k from"chalk";import{Ollama as H}from"ollama";import{concatMap as w,from as A,map as C,catchError as v}from"rxjs";import{fromPromise as P}from"rxjs/internal/observable/innerFrom";import{fetch as L,Agent as z}from"undici";import{A as U,l as x,a as M,b as O,c as R,d as S,e as _}from"./ai.service-
|
|
1
|
+
import k from"chalk";import{Ollama as H}from"ollama";import{concatMap as w,from as A,map as C,catchError as v}from"rxjs";import{fromPromise as P}from"rxjs/internal/observable/innerFrom";import{fetch as L,Agent as z}from"undici";import{A as U,l as x,a as M,b as O,c as R,d as S,e as _}from"./ai.service-c5f81726.mjs";import{o as E,n as b,c as I,P as N,b as B,g as T,H as G}from"./cli-3a375308.mjs";import"fs";import"path";import"@pacote/xxhash";import"winston";import"cleye";import"module";import"crypto";import"os";import"node:buffer";import"node:path";import"node:child_process";import"node:process";import"child_process";import"node:url";import"node:os";import"assert";import"events";import"node:fs";import"buffer";import"stream";import"util";import"node:util";import"inquirer";import"fs/promises";import"readline";import"figlet";import"gradient-string";import"ora";import"inquirer-reactive-list-prompt";import"winston-daily-rotate-file";import"axios";import"url";import"node:fs/promises";import"chokidar";import"rxjs/operators";class J extends U{constructor(s){super(s),this.params=s,this.host=E,this.model="",this.key="",this.auth="",this.generateStreamingCommitMessage$=()=>{const{generate:t,type:e}=this.params.config;return this.createStreamingCommitMessages$(o=>{this.streamChunks(o).catch(a=>o.error(a))},e,t)},this.streamChunks=async t=>{const e=this.params.stagedDiff.diff,{logging:o}=this.params.config,a=this.buildCommitPrompt();await this.checkIsAvailableOllama();const h=`Here is the diff: ${e}`,i=`Ollama_${this.model}`,l=`${this.host}/api/chat`,r=this.key?{Authorization:`${this.auth} ${this.key}`}:{};x(e,"commit",i,this.model,l,r,o),M(e,"commit",i,a,h,o);const{numCtx:m,temperature:n,topP:c,timeout:f,maxTokens:p}=this.params.config,g={model:this.model,messages:[{role:"system",content:a},{role:"user",content:h}],stream:!0,keep_alive:f,options:{num_ctx:m,temperature:n,top_p:c,seed:b(10,1e3),num_predict:p??-1}};O(e,"commit",i,g,o);const d=Date.now();let $="";try{const u=await this.ollama.chat(g);for await(const F of u){const y=F.message.content;y&&($+=y,t.next(y))}const D=Date.now()-d;R(e,"commit",i,{streamed:!0,totalLength:$.length},o),S(e,"commit",i,D,$,o),t.complete()}catch(u){_(e,"commit",i,u,o),t.error(u)}},this.setupFetch=(t,e={})=>L(t,{...e,dispatcher:new z({headersTimeout:this.params.config.timeout})}),this.colors={primary:"#FFF",secondary:"#000"},this.model=this.params.keyName,this.serviceName=k.bgHex(this.colors.primary).hex(this.colors.secondary).bold(`[${I(this.model)}]`),this.errorPrefix=k.red.bold(`[${I(this.model)}]`),this.host=this.params.config.host||E,this.auth=this.params.config.auth||"Bearer",this.key=this.params.config.key||"",this.ollama=new H({host:this.host,fetch:this.setupFetch,...this.key&&{headers:{Authorization:`${this.auth} ${this.key}`}}})}getServiceSpecificErrorMessage(s){const t=s.message||"";return t.includes("ECONNREFUSED")||t.includes("connection refused")?N.ollamaNotRunning():t.includes("model")&&(t.includes("not found")||t.includes("404"))?N.ollamaModelNotPulled(this.model):null}generateCommitMessage$(){return this.params.config.stream||!1?this.generateStreamingCommitMessage$():P(this.generateMessage("commit")).pipe(w(t=>A(t)),C(this.formatAsChoice),v(this.handleError$))}generateCodeReview$(){return P(this.generateMessage("review")).pipe(w(s=>A(s)),C(this.formatCodeReviewAsChoice),v(this.handleError$))}async generateMessage(s){const t=this.params.stagedDiff.diff,{logging:e,generate:o,type:a}=this.params.config,h=this.buildPromptOptions(),i=s==="review"?B(h):T(h);await this.checkIsAvailableOllama();const l=`Here is the diff: ${t}`,r=`Ollama_${this.model}`,m=`${this.host}/api/chat`,n=this.key?{Authorization:`${this.auth} ${this.key}`}:{};x(t,s,r,this.model,m,n,e),M(t,s,r,i,l,e);const c=await this.createChatCompletions(i,l,s);return s==="review"?this.parseCodeReview(c):this.parseMessage(c,a,o)}async checkIsAvailableOllama(){const s=new G({method:"GET",baseURL:`${this.host}`,timeout:this.params.config.timeout});return this.key&&s.setHeaders({Authorization:`${this.auth} ${this.key}`}),(await s.execute()).data}async createChatCompletions(s,t,e){const{numCtx:o,temperature:a,topP:h,timeout:i,maxTokens:l,logging:r}=this.params.config,m=this.params.stagedDiff.diff,n=`Ollama_${this.model}`,c={model:this.model,messages:[{role:"system",content:s},{role:"user",content:t}],stream:!1,keep_alive:i,options:{num_ctx:o,temperature:a,top_p:h,seed:b(10,1e3),num_predict:l??-1}};O(m,e,n,c,r);const f=Date.now();try{const p=await this.ollama.chat(c),g=Date.now()-f,d=p.message.content;return R(m,e,n,{response:d,fullResponse:p},r),S(m,e,n,g,d,r),d}catch(p){throw _(m,e,n,p,r),p}}}export{J as OllamaService};
|
package/dist/{openai-compatible.service-3cda8bb5.mjs → openai-compatible.service-9b9b2eb5.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import P from"chalk";import B from"openai";import{concatMap as v,from as $,map as w,catchError as x}from"rxjs";import{fromPromise as M}from"rxjs/internal/observable/innerFrom";import{A as F,l as S,a as _,b,c as N,d as O,e as R}from"./ai.service-
|
|
1
|
+
import P from"chalk";import B from"openai";import{concatMap as v,from as $,map as w,catchError as x}from"rxjs";import{fromPromise as M}from"rxjs/internal/observable/innerFrom";import{A as F,l as S,a as _,b,c as N,d as O,e as R}from"./ai.service-c5f81726.mjs";import{i as E}from"./openai-e13f148b.mjs";import{g as D,a as H,c as T,b as K}from"./cli-3a375308.mjs";import"fs";import"path";import"@pacote/xxhash";import"winston";import"http";import"https";import"net";import"tls";import"url";import"assert";import"tty";import"util";import"os";import"events";import"cleye";import"module";import"crypto";import"node:buffer";import"node:path";import"node:child_process";import"node:process";import"child_process";import"node:url";import"node:os";import"node:fs";import"buffer";import"stream";import"node:util";import"inquirer";import"fs/promises";import"readline";import"figlet";import"gradient-string";import"ora";import"inquirer-reactive-list-prompt";import"winston-daily-rotate-file";import"axios";import"node:fs/promises";import"chokidar";import"rxjs/operators";class U extends F{constructor(t){super(t),this.params=t,this.generateStreamingCommitMessage$=()=>{const{generate:o,type:r}=this.params.config;return this.createStreamingCommitMessages$(i=>{this.streamChunks(i).catch(m=>i.error(m))},r,o)},this.streamChunks=async o=>{const r=this.params.stagedDiff.diff,{logging:i,temperature:m,timeout:u}=this.params.config,c=this.params.config.maxTokens,p=D(this.buildPromptOptions()),l=`Here is the diff: ${r}`,s=this.params.keyName||"OpenAI-Compatible",n=`${this.params.config.url}${this.params.config.path}`,k={Authorization:`Bearer ${this.params.config.key}`,"Content-Type":"application/json"};S(r,"commit",s,this.params.config.model,n,k,i),_(r,"commit",s,p,l,i);const y=E(this.params.config.model),g={messages:[{role:"system",content:p},{role:"user",content:l}],model:this.params.config.model,stream:!0,...y?{max_completion_tokens:c,temperature:1}:{max_tokens:c,top_p:this.params.config.topP,temperature:m}};b(r,"commit",s,g,i);const f=Date.now();let h="";try{const d=await this.openAI.chat.completions.create(g,{timeout:u});for await(const I of d){const L=I.choices?.[0]?.delta?.content||"",z=I.choices?.[0]?.delta?.reasoning_content||"",C=`${L}${z}`;C&&(h+=C,o.next(C))}const A=Date.now()-f;N(r,"commit",s,{streamed:!0,totalLength:h.length},i),O(r,"commit",s,A,h,i),o.complete()}catch(a){R(r,"commit",s,a,i),o.error(a)}};const e=this.params.keyName||"OPENAI_COMPATIBLE";this.colors=H(e),this.serviceName=P.bgHex(this.colors.primary).hex(this.colors.secondary).bold(`[${T(e)}]`),this.errorPrefix=P.red.bold(`[${T(e)}]`),this.openAI=new B({apiKey:this.params.config.key,baseURL:`${this.params.config.url}${this.params.config.path}`})}getServiceSpecificErrorMessage(t){const e=t.message||"";return e.includes("API key")||e.includes("api_key")?"Invalid API key. Check your OpenAI-compatible API key in configuration":e.includes("rate_limit")||e.includes("Rate limit")?"Rate limit exceeded. Wait a moment and try again, or check your service limits":e.includes("model")||e.includes("Model")?"Model not found or not accessible. Check if the model name is correct":e.includes("network")||e.includes("connection")?"Network error. Check your internet connection and API endpoint":e.includes("quota")||e.includes("usage")?"API quota exceeded. Check your usage limits":e.includes("403")||e.includes("Forbidden")?"Access denied. Your API key may not have permission for this model":e.includes("404")||e.includes("Not Found")?"Model or endpoint not found. Check your API configuration":e.includes("500")||e.includes("Internal Server Error")?"Server error. Try again later":e.includes("overloaded")||e.includes("capacity")?"Service is overloaded. Try again in a few minutes":null}generateCommitMessage$(){return this.params.config.stream||!1?this.generateStreamingCommitMessage$():M(this.generateMessage("commit")).pipe(v(e=>$(e)),w(this.formatAsChoice),x(this.handleError$))}generateCodeReview$(){return M(this.generateMessage("review")).pipe(v(t=>$(t)),w(this.formatCodeReviewAsChoice),x(this.handleError$))}async generateMessage(t){const e=this.params.stagedDiff.diff,{logging:o,temperature:r,generate:i,type:m,timeout:u}=this.params.config,c=this.params.config.maxTokens,p=this.buildPromptOptions(),l=t==="review"?K(p):D(p),s=`Here is the diff: ${e}`,n=this.params.keyName||"OpenAI-Compatible",k=`${this.params.config.url}${this.params.config.path}`,y={Authorization:`Bearer ${this.params.config.key}`,"Content-Type":"application/json"};S(e,t,n,this.params.config.model,k,y,o),_(e,t,n,l,s,o);const g=E(this.params.config.model),f={messages:[{role:"system",content:l},{role:"user",content:s}],model:this.params.config.model,stream:!1,...g?{max_completion_tokens:c,temperature:1}:{max_tokens:c,top_p:this.params.config.topP,temperature:r}};b(e,t,n,f,o);const h=Date.now();try{const a=await this.openAI.chat.completions.create(f,{timeout:u}),d=a.choices?.[0]?.message.content||"",A=Date.now()-h;return N(e,t,n,a,o),O(e,t,n,A,d,o),t==="review"?this.parseCodeReview(d):this.parseMessage(d,m,i)}catch(a){throw R(e,t,n,a,o),a}}}export{U as OpenAICompatibleService};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import ae from"http";import ce from"https";import{j as w,k as ue,d as le,K as I}from"./cli-
|
|
1
|
+
import ae from"http";import ce from"https";import{j as w,k as ue,d as le,K as I}from"./cli-3a375308.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-c5f81726.mjs";var S={},L={exports:{}},E={exports:{}},D,W;function Oe(){if(W)return D;W=1;var t=1e3,n=t*60,i=n*60,e=i*24,f=e*7,s=e*365.25;D=function(u,r){r=r||{};var o=typeof u;if(o==="string"&&u.length>0)return p(u);if(o==="number"&&isFinite(u))return r.long?a(u):h(u);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(u))};function p(u){if(u=String(u),!(u.length>100)){var r=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(u);if(r){var o=parseFloat(r[1]),c=(r[2]||"ms").toLowerCase();switch(c){case"years":case"year":case"yrs":case"yr":case"y":return o*s;case"weeks":case"week":case"w":return o*f;case"days":case"day":case"d":return o*e;case"hours":case"hour":case"hrs":case"hr":case"h":return o*i;case"minutes":case"minute":case"mins":case"min":case"m":return o*n;case"seconds":case"second":case"secs":case"sec":case"s":return o*t;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return o;default:return}}}}function h(u){var r=Math.abs(u);return r>=e?Math.round(u/e)+"d":r>=i?Math.round(u/i)+"h":r>=n?Math.round(u/n)+"m":r>=t?Math.round(u/t)+"s":u+"ms"}function a(u){var r=Math.abs(u);return r>=e?l(u,r,e,"day"):r>=i?l(u,r,i,"hour"):r>=n?l(u,r,n,"minute"):r>=t?l(u,r,t,"second"):u+" ms"}function l(u,r,o,c){var d=r>=o*1.5;return Math.round(u/o)+" "+c+(d?"s":"")}return D}var j,Y;function K(){if(Y)return j;Y=1;function t(n){e.debug=e,e.default=e,e.coerce=l,e.disable=h,e.enable=s,e.enabled=a,e.humanize=Oe(),e.destroy=u,Object.keys(n).forEach(r=>{e[r]=n[r]}),e.names=[],e.skips=[],e.formatters={};function i(r){let o=0;for(let c=0;c<r.length;c++)o=(o<<5)-o+r.charCodeAt(c),o|=0;return e.colors[Math.abs(o)%e.colors.length]}e.selectColor=i;function e(r){let o,c=null,d,C;function m(...g){if(!m.enabled)return;const y=m,F=Number(new Date),T=F-(o||F);y.diff=T,y.prev=o,y.curr=F,o=F,g[0]=e.coerce(g[0]),typeof g[0]!="string"&&g.unshift("%O");let v=0;g[0]=g[0].replace(/%([a-zA-Z%])/g,(O,k)=>{if(O==="%%")return"%";v++;const b=e.formatters[k];if(typeof b=="function"){const ie=g[v];O=b.call(y,ie),g.splice(v,1),v--}return O}),e.formatArgs.call(y,g),(y.log||e.log).apply(y,g)}return m.namespace=r,m.useColors=e.useColors(),m.color=e.selectColor(r),m.extend=f,m.destroy=e.destroy,Object.defineProperty(m,"enabled",{enumerable:!0,configurable:!1,get:()=>c!==null?c:(d!==e.namespaces&&(d=e.namespaces,C=e.enabled(r)),C),set:g=>{c=g}}),typeof e.init=="function"&&e.init(m),m}function f(r,o){const c=e(this.namespace+(typeof o>"u"?":":o)+r);return c.log=this.log,c}function s(r){e.save(r),e.namespaces=r,e.names=[],e.skips=[];const o=(typeof r=="string"?r:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(const c of o)c[0]==="-"?e.skips.push(c.slice(1)):e.names.push(c)}function p(r,o){let c=0,d=0,C=-1,m=0;for(;c<r.length;)if(d<o.length&&(o[d]===r[c]||o[d]==="*"))o[d]==="*"?(C=d,m=c,d++):(c++,d++);else if(C!==-1)d=C+1,m++,c=m;else return!1;for(;d<o.length&&o[d]==="*";)d++;return d===o.length}function h(){const r=[...e.names,...e.skips.map(o=>"-"+o)].join(",");return e.enable(""),r}function a(r){for(const o of e.skips)if(p(r,o))return!1;for(const o of e.names)if(p(r,o))return!0;return!1}function l(r){return r instanceof Error?r.stack||r.message:r}function u(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return e.enable(e.load()),e}return j=t,j}E.exports;var Z;function Ee(){return Z||(Z=1,function(t,n){n.formatArgs=e,n.save=f,n.load=s,n.useColors=i,n.storage=p(),n.destroy=(()=>{let a=!1;return()=>{a||(a=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),n.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function i(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let a;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&(a=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(a[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function e(a){if(a[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+a[0]+(this.useColors?"%c ":" ")+"+"+t.exports.humanize(this.diff),!this.useColors)return;const l="color: "+this.color;a.splice(1,0,l,"color: inherit");let u=0,r=0;a[0].replace(/%[a-zA-Z%]/g,o=>{o!=="%%"&&(u++,o==="%c"&&(r=u))}),a.splice(r,0,l)}n.log=console.debug||console.log||(()=>{});function f(a){try{a?n.storage.setItem("debug",a):n.storage.removeItem("debug")}catch{}}function s(){let a;try{a=n.storage.getItem("debug")||n.storage.getItem("DEBUG")}catch{}return!a&&typeof process<"u"&&"env"in process&&(a=process.env.DEBUG),a}function p(){try{return localStorage}catch{}}t.exports=K()(n);const{formatters:h}=t.exports;h.j=function(a){try{return JSON.stringify(a)}catch(l){return"[UnexpectedJSONParseError]: "+l.message}}}(E,E.exports)),E.exports}var $={exports:{}},B,X;function $e(){return X||(X=1,B=(t,n=process.argv)=>{const i=t.startsWith("-")?"":t.length===1?"-":"--",e=n.indexOf(i+t),f=n.indexOf("--");return e!==-1&&(f===-1||e<f)}),B}var N,Q;function Ae(){if(Q)return N;Q=1;const t=Ce,n=V,i=$e(),{env:e}=process;let f;i("no-color")||i("no-colors")||i("color=false")||i("color=never")?f=0:(i("color")||i("colors")||i("color=true")||i("color=always"))&&(f=1),"FORCE_COLOR"in e&&(e.FORCE_COLOR==="true"?f=1:e.FORCE_COLOR==="false"?f=0:f=e.FORCE_COLOR.length===0?1:Math.min(parseInt(e.FORCE_COLOR,10),3));function s(a){return a===0?!1:{level:a,hasBasic:!0,has256:a>=2,has16m:a>=3}}function p(a,l){if(f===0)return 0;if(i("color=16m")||i("color=full")||i("color=truecolor"))return 3;if(i("color=256"))return 2;if(a&&!l&&f===void 0)return 0;const u=f||0;if(e.TERM==="dumb")return u;if(process.platform==="win32"){const r=t.release().split(".");return Number(r[0])>=10&&Number(r[2])>=10586?Number(r[2])>=14931?3:2:1}if("CI"in e)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE"].some(r=>r in e)||e.CI_NAME==="codeship"?1:u;if("TEAMCITY_VERSION"in e)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(e.TEAMCITY_VERSION)?1:0;if(e.COLORTERM==="truecolor")return 3;if("TERM_PROGRAM"in e){const r=parseInt((e.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(e.TERM_PROGRAM){case"iTerm.app":return r>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(e.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(e.TERM)||"COLORTERM"in e?1:u}function h(a){const l=p(a,a&&a.isTTY);return s(l)}return N={supportsColor:h,stdout:s(p(!0,n.isatty(1))),stderr:s(p(!0,n.isatty(2)))},N}$.exports;var ee;function xe(){return ee||(ee=1,function(t,n){const i=V,e=me;n.init=u,n.log=h,n.formatArgs=s,n.save=a,n.load=l,n.useColors=f,n.destroy=e.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."),n.colors=[6,2,3,4,5,1];try{const o=Ae();o&&(o.stderr||o).level>=2&&(n.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221])}catch{}n.inspectOpts=Object.keys(process.env).filter(o=>/^debug_/i.test(o)).reduce((o,c)=>{const d=c.substring(6).toLowerCase().replace(/_([a-z])/g,(m,g)=>g.toUpperCase());let C=process.env[c];return/^(yes|on|true|enabled)$/i.test(C)?C=!0:/^(no|off|false|disabled)$/i.test(C)?C=!1:C==="null"?C=null:C=Number(C),o[d]=C,o},{});function f(){return"colors"in n.inspectOpts?!!n.inspectOpts.colors:i.isatty(process.stderr.fd)}function s(o){const{namespace:c,useColors:d}=this;if(d){const C=this.color,m="\x1B[3"+(C<8?C:"8;5;"+C),g=` ${m};1m${c} \x1B[0m`;o[0]=g+o[0].split(`
|
|
2
2
|
`).join(`
|
|
3
3
|
`+g),o.push(m+"m+"+t.exports.humanize(this.diff)+"\x1B[0m")}else o[0]=p()+c+" "+o[0]}function p(){return n.inspectOpts.hideDate?"":new Date().toISOString()+" "}function h(...o){return process.stderr.write(e.formatWithOptions(n.inspectOpts,...o)+`
|
|
4
4
|
`)}function a(o){o?process.env.DEBUG=o:delete process.env.DEBUG}function l(){return process.env.DEBUG}function u(o){o.inspectOpts={};const c=Object.keys(n.inspectOpts);for(let d=0;d<c.length;d++)o.inspectOpts[c[d]]=n.inspectOpts[c[d]]}t.exports=K()(n);const{formatters:r}=t.exports;r.o=function(o){return this.inspectOpts.colors=this.useColors,e.inspect(o,this.inspectOpts).split(`
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import C from"chalk";import b from"openai";import{concatMap as P,from as y,map as A,catchError as I}from"rxjs";import{fromPromise as k}from"rxjs/internal/observable/innerFrom";import{A as G,l as O,a as R,b as D,c as E,d as _,e as F}from"./ai.service-
|
|
1
|
+
import C from"chalk";import b from"openai";import{concatMap as P,from as y,map as A,catchError as I}from"rxjs";import{fromPromise as k}from"rxjs/internal/observable/innerFrom";import{A as G,l as O,a as R,b as D,c as E,d as _,e as F}from"./ai.service-c5f81726.mjs";import{i as N,g as H}from"./openai-e13f148b.mjs";import{g as M,b as L,m as $}from"./cli-3a375308.mjs";import"fs";import"path";import"@pacote/xxhash";import"winston";import"http";import"https";import"net";import"tls";import"url";import"assert";import"tty";import"util";import"os";import"events";import"cleye";import"module";import"crypto";import"node:buffer";import"node:path";import"node:child_process";import"node:process";import"child_process";import"node:url";import"node:os";import"node:fs";import"buffer";import"stream";import"node:util";import"inquirer";import"fs/promises";import"readline";import"figlet";import"gradient-string";import"ora";import"inquirer-reactive-list-prompt";import"winston-daily-rotate-file";import"axios";import"node:fs/promises";import"chokidar";import"rxjs/operators";class U extends G{constructor(t){super(t),this.params=t,this.generateStreamingCommitMessage$=()=>{const{generate:i,type:e}=this.params.config;return this.createStreamingCommitMessages$(s=>{this.streamChunks(s).catch(r=>s.error(r))},e,i)},this.streamChunks=async i=>{const e=this.params.stagedDiff.diff,{temperature:s,logging:r,maxTokens:n,timeout:g}=this.params.config,a=M(this.buildPromptOptions()),p=`Here is the diff: ${e}`,c=`${this.params.config.url}${this.params.config.path}`,m={Authorization:`Bearer ${this.params.config.key}`,"Content-Type":"application/json"};O(e,"commit","ChatGPT",this.params.config.model,c,m,r),R(e,"commit","ChatGPT",a,p,r);const x=N(this.params.config.model),u={messages:[{role:"system",content:a},{role:"user",content:p}],model:this.params.config.model,stream:!0,...x?{max_completion_tokens:n,temperature:1}:{max_tokens:n,top_p:this.params.config.topP,temperature:s}};D(e,"commit","ChatGPT",u,r);const v=Date.now();let f="";try{const S=await this.openAI.chat.completions.create(u,{timeout:g});for await(const T of S){const d=T.choices?.[0]?.delta?.content||"";d&&(f+=d,i.next(d))}const w=Date.now()-v;E(e,"commit","ChatGPT",{streamed:!0,totalLength:f.length},r),_(e,"commit","ChatGPT",w,f,r),i.complete()}catch(l){F(e,"commit","ChatGPT",l,r),i.error(l)}},this.colors={primary:"#74AA9C",secondary:"#FFF"},this.serviceName=C.bgHex(this.colors.primary).hex(this.colors.secondary).bold(`[ChatGPT${this.formatModelSuffix()}]`),this.errorPrefix=C.red.bold(`[ChatGPT${this.formatModelSuffix()}]`);const o=this.params.config.url||"https://api.openai.com",h=(this.params.config.path||"/v1/chat/completions").replace(/\/chat\/completions\/?$/,"");this.openAI=new b({apiKey:this.params.config.key,baseURL:`${o}${h}`})}getServiceSpecificErrorMessage(t){const o=t.message||"";return o.includes("API key")?"Invalid API key. Check your OpenAI API key in configuration":o.includes("quota")?"API quota exceeded. Check your OpenAI usage limits":o.includes("500")?"OpenAI server error. Try again later":null}generateCommitMessage$(){return this.params.config.stream||!1?this.generateStreamingCommitMessage$():k(this.generateMessage("commit")).pipe(P(o=>y(o)),A(this.formatAsChoice),I(this.handleError$))}generateCodeReview$(){return k(this.generateMessage("review")).pipe(P(t=>y(t)),A(this.formatCodeReviewAsChoice),I(this.handleError$))}async generateMessage(t){const o=this.params.stagedDiff.diff,{temperature:h,logging:i,generate:e,type:s,proxy:r,maxTokens:n,timeout:g}=this.params.config,a=this.buildPromptOptions(),p=t==="review"?L(a):M(a),c=await H("ChatGPT",this.params.config.url,this.params.config.path,this.params.config.key,this.params.config.model,o,g,n,h,this.params.config.topP,p,i,t,r,{recentCommits:this.params.recentCommits,branchName:this.params.branchName});return t==="review"?$(c.map(m=>this.parseCodeReview(m))):$(c.map(m=>this.parseMessage(m,s,e)))}}export{U as OpenAIService};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import C from"chalk";import _ from"openai";import{concatMap as M,from as w,map as P,catchError as $}from"rxjs";import{fromPromise as v}from"rxjs/internal/observable/innerFrom";import{A as j,l as x,a as A,b as k,c as b,d as S,e as I}from"./ai.service-
|
|
1
|
+
import C from"chalk";import _ from"openai";import{concatMap as M,from as w,map as P,catchError as $}from"rxjs";import{fromPromise as v}from"rxjs/internal/observable/innerFrom";import{A as j,l as x,a as A,b as k,c as b,d as S,e as I}from"./ai.service-c5f81726.mjs";import{i as K}from"./openai-e13f148b.mjs";import{g as H,H as U,b as q}from"./cli-3a375308.mjs";import"fs";import"path";import"@pacote/xxhash";import"winston";import"http";import"https";import"net";import"tls";import"url";import"assert";import"tty";import"util";import"os";import"events";import"cleye";import"module";import"crypto";import"node:buffer";import"node:path";import"node:child_process";import"node:process";import"child_process";import"node:url";import"node:os";import"node:fs";import"buffer";import"stream";import"node:util";import"inquirer";import"fs/promises";import"readline";import"figlet";import"gradient-string";import"ora";import"inquirer-reactive-list-prompt";import"winston-daily-rotate-file";import"axios";import"node:fs/promises";import"chokidar";import"rxjs/operators";const O=class l extends j{constructor(r){super(r),this.params=r,this.getOpenRouterBaseUrl=()=>(this.params.config.url||"https://openrouter.ai").replace(/\/$/,""),this.getOpenRouterCatalogUrl=()=>`${this.getOpenRouterBaseUrl()}/api/v1`,this.getOpenRouterHeaders=()=>({"HTTP-Referer":"https://github.com/tak-bro/aicommit2","X-OpenRouter-Title":"aicommit2","X-OpenRouter-Categories":"cli-agent"}),this.getOpenRouterAuthHeaders=()=>({Authorization:`Bearer ${this.params.config.key}`,"Content-Type":"application/json",...this.getOpenRouterHeaders()}),this.hasRequestObject=t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&Object.keys(t).length>0,this.getRequestedModel=()=>Array.isArray(this.params.config.model)?this.params.config.model[0]||"":typeof this.params.config.model=="string"?this.params.config.model:"",this.getCatalogCacheKey=()=>`${this.getOpenRouterCatalogUrl()}|${this.params.config.key||""}`,this.getModelCacheKey=()=>`${this.getCatalogCacheKey()}|${this.getRequestedModel()}`,this.matchOpenRouterModel=(t,o)=>{const s=t.trim();return o.find(i=>[i.id,i.canonical_slug,i.name].filter(c=>!!c).some(c=>c===s))},this.getRequestPayloadExtras=async()=>{const t=this.params.config,o={},s=this.hasRequestObject(t.responseFormat)?t.responseFormat:{type:"json_object"};s&&await this.isResponseFormatSupported()&&(o.response_format=s),this.hasRequestObject(t.provider)&&(o.provider=t.provider);const i=await this.getReasoningPayload();return i&&(o.reasoning=i),o},this.extractOpenRouterText=t=>{if(!t||typeof t!="object")return"";const o=t;return o.content||o.reasoning_content||o.reasoning||""},this.buildChatCompletionPayload=async(t,o,s)=>{const i=this.params.config.maxTokens,m=this.params.config.temperature,c=K(this.params.config.model),n=this.getRequestedModel();return{messages:[{role:"system",content:t},{role:"user",content:o}],model:n,stream:s,...await this.getRequestPayloadExtras()||{},...c?{max_completion_tokens:i,temperature:1}:{max_tokens:i,top_p:this.params.config.topP,temperature:m}}},this.generateStreamingCommitMessage$=()=>{const{generate:t,type:o}=this.params.config;return this.createStreamingCommitMessages$(s=>{this.streamChunks(s).catch(i=>s.error(i))},o,t)},this.streamChunks=async t=>{const o=this.params.stagedDiff.diff,{logging:s,timeout:i}=this.params.config,m=H(this.buildPromptOptions()),c=`Here is the diff: ${o}`,n="OpenRouter",d=`${this.params.config.url||"https://openrouter.ai"}${this.params.config.path||"/api/v1/chat/completions"}`,g={Authorization:`Bearer ${this.params.config.key}`,"Content-Type":"application/json",...this.getOpenRouterHeaders()};x(o,"commit",n,this.params.config.model,d,g,s),A(o,"commit",n,m,c,s);const u=await this.buildChatCompletionPayload(m,c,!0);k(o,"commit",n,u,s);const f=Date.now();let p="";try{const R=await this.openAI.chat.completions.create(u,{timeout:i});for await(const T of R){const y=this.extractOpenRouterText(T.choices?.[0]?.delta);y&&(p+=y,t.next(y))}const E=Date.now()-f;b(o,"commit",n,{streamed:!0,totalLength:p.length},s),S(o,"commit",n,E,p,s),t.complete()}catch(h){I(o,"commit",n,h,s),t.error(h)}},this.colors={primary:"#f97316",secondary:"#fff"},this.serviceName=C.bgHex(this.colors.primary).hex(this.colors.secondary).bold(`[OpenRouter${this.formatModelSuffix()}]`),this.errorPrefix=C.red.bold(`[OpenRouter${this.formatModelSuffix()}]`);const e=this.params.config.url||"https://openrouter.ai",a=(this.params.config.path||"/api/v1/chat/completions").replace(/\/chat\/completions\/?$/,"");this.openAI=new _({apiKey:this.params.config.key,baseURL:`${e}${a}`,defaultHeaders:{...this.getOpenRouterHeaders()}})}async fetchOpenRouterCatalog(){const r=this.getCatalogCacheKey(),e=l.catalogCache.get(r);if(e)return e;const a=["/models/user","/models"];let t;for(const o of a)try{const i=(await new U({method:"GET",baseURL:`${this.getOpenRouterCatalogUrl()}${o}`,timeout:this.params.config.timeout}).setHeaders(this.getOpenRouterAuthHeaders()).execute()).data?.data??[];return l.catalogCache.set(r,i),i}catch(s){if(t=s,!(s instanceof Error?s.message:String(s)).includes("404"))throw s}throw t instanceof Error?t:new Error(String(t))}async getOpenRouterModel(){const r=this.getRequestedModel();if(!r||r==="openrouter/auto")return null;const e=this.getModelCacheKey(),a=l.modelCache.get(e);if(a!==void 0)return a;try{const t=await this.fetchOpenRouterCatalog(),o=this.matchOpenRouterModel(r,t)||null;return l.modelCache.set(e,o),o}catch{return null}}async supportsOpenRouterParameters(r){const e=await this.getOpenRouterModel();return e?r.some(a=>e.supported_parameters?.includes(a)??!1):!1}async isResponseFormatSupported(){return this.supportsOpenRouterParameters(["response_format"])}async isReasoningSupported(){return this.supportsOpenRouterParameters(["reasoning","include_reasoning"])}async getReasoningPayload(){if(!await this.isReasoningSupported())return;const r=this.params.config,e=this.hasRequestObject(r.reasoning)?{...r.reasoning}:void 0,a=e?{...e}:{};return"exclude"in a||(a.exclude=!0),a}getServiceSpecificErrorMessage(r){const e=r.message||"";return e.includes("API key")||e.includes("api_key")?"Invalid API key. Check your OpenRouter API key in configuration":e.includes("402")||e.includes("Payment Required")?"OpenRouter credits are exhausted or billing is required. Check your account balance.":e.includes("rate_limit")||e.includes("Rate limit")?"Rate limit exceeded. Wait a moment and try again, or check your OpenRouter limits":e.includes("model")||e.includes("Model")?"Model not found or not accessible. Check if the OpenRouter model name is correct":e.includes("403")||e.includes("Forbidden")?"Access denied. Your API key may not have permission for this OpenRouter model":e.includes("404")||e.includes("Not Found")?"Model or endpoint not found. Check your OpenRouter configuration":e.includes("500")||e.includes("Internal Server Error")?"OpenRouter server error. Try again later":e.includes("overloaded")||e.includes("capacity")?"OpenRouter is overloaded. Try again in a few minutes":null}generateCommitMessage$(){return this.params.config.stream||!1?this.generateStreamingCommitMessage$():v(this.generateMessage("commit")).pipe(M(e=>w(e)),P(this.formatAsChoice),$(this.handleError$))}generateCodeReview$(){return v(this.generateMessage("review")).pipe(M(r=>w(r)),P(this.formatCodeReviewAsChoice),$(this.handleError$))}async generateMessage(r){const e=this.params.stagedDiff.diff,{logging:a,generate:t,type:o,timeout:s}=this.params.config,i=this.buildPromptOptions(),m=r==="review"?q(i):H(i),c=`Here is the diff: ${e}`,n="OpenRouter",d=`${this.params.config.url||"https://openrouter.ai"}${this.params.config.path||"/api/v1/chat/completions"}`,g={Authorization:`Bearer ${this.params.config.key}`,"Content-Type":"application/json",...this.getOpenRouterHeaders()};x(e,r,n,this.params.config.model,d,g,a),A(e,r,n,m,c,a);const u=await this.buildChatCompletionPayload(m,c,!1);k(e,r,n,u,a);const f=Date.now();try{const p=await this.openAI.chat.completions.create(u,{timeout:s}),h=this.extractOpenRouterText(p.choices?.[0]?.message),R=Date.now()-f;return b(e,r,n,p,a),S(e,r,n,R,h,a),r==="review"?this.parseCodeReview(h):this.parseMessage(h,o,t)}catch(p){throw I(e,r,n,p,a),p}}};O.catalogCache=new Map,O.modelCache=new Map;let F=O;export{F as OpenRouterService};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import d from"chalk";import{concatMap as f,from as g,map as u,catchError as y}from"rxjs";import{fromPromise as P}from"rxjs/internal/observable/innerFrom";import{A as v,l as w,a as C,b as A,c as k,e as x,d as b}from"./ai.service-
|
|
1
|
+
import d from"chalk";import{concatMap as f,from as g,map as u,catchError as y}from"rxjs";import{fromPromise as P}from"rxjs/internal/observable/innerFrom";import{A as v,l as w,a as C,b as A,c as k,e as x,d as b}from"./ai.service-c5f81726.mjs";import{b as I,g as M,H as R}from"./cli-3a375308.mjs";import"fs";import"path";import"@pacote/xxhash";import"winston";import"cleye";import"module";import"crypto";import"os";import"node:buffer";import"node:path";import"node:child_process";import"node:process";import"child_process";import"node:url";import"node:os";import"assert";import"events";import"node:fs";import"buffer";import"stream";import"util";import"node:util";import"inquirer";import"fs/promises";import"readline";import"figlet";import"gradient-string";import"ora";import"inquirer-reactive-list-prompt";import"winston-daily-rotate-file";import"axios";import"url";import"node:fs/promises";import"chokidar";import"rxjs/operators";class S extends v{constructor(t){super(t),this.params=t,this.apiKey="",this.colors={primary:"#20808D",secondary:"#FFF"},this.serviceName=d.bgHex(this.colors.primary).hex(this.colors.secondary).bold(`[Perplexity${this.formatModelSuffix()}]`),this.errorPrefix=d.red.bold(`[Perplexity${this.formatModelSuffix()}]`),this.apiKey=this.params.config.key}getServiceSpecificErrorMessage(t){const e=t.message||"";return e.includes("API key")||e.includes("api_key")?"Invalid API key. Check your Perplexity API key in configuration":e.includes("rate_limit")||e.includes("Rate limit")?"Rate limit exceeded. Wait a moment and try again, or upgrade your Perplexity plan":e.includes("model")||e.includes("Model")?"Model not found or not accessible. Check if the Perplexity model name is correct":e.includes("overloaded")||e.includes("capacity")?"Perplexity service is overloaded. Try again in a few minutes":e.includes("403")||e.includes("Forbidden")?"Access denied. Your API key may not have permission for this Perplexity model":e.includes("404")||e.includes("Not Found")?"Model or endpoint not found. Check your Perplexity model configuration":e.includes("500")||e.includes("Internal Server Error")?"Perplexity server error. Try again later":null}generateCommitMessage$(){return P(this.generateMessage("commit")).pipe(f(t=>g(t)),u(this.formatAsChoice),y(this.handleError$))}generateCodeReview$(){return P(this.generateMessage("review")).pipe(f(t=>g(t)),u(this.formatCodeReviewAsChoice),y(this.handleError$))}extractJSONFromError(t){const e=/[{[]{1}([,:{}[\]0-9.\-+Eaeflnr-u \n\r\t]|".*?")+[}\]]{1}/gis,r=t.match(e);if(r){const o={};for(const i of r)try{Object.assign(o,JSON.parse(i))}catch{}return Object.keys(o).length>0?o:{error:{message:"Unknown error"}}}return{error:{message:"Unknown error"}}}async generateMessage(t){const e=this.params.stagedDiff.diff,{logging:r,generate:o,type:i}=this.params.config,n=this.buildPromptOptions(),p=t==="review"?I(n):M(n),a=`Here is the diff: ${e}`,c=`${this.params.config.url||"https://api.perplexity.ai"}/chat/completions`,s={Authorization:`Bearer ${this.apiKey}`,"content-type":"application/json"};w(e,t,"Perplexity",this.params.config.model,c,s,r),C(e,t,"Perplexity",p,a,r);const m=await this.createChatCompletions(p,a,t);return t==="review"?this.parseCodeReview(m):this.parseMessage(m,i,o)}async createChatCompletions(t,e,r){const o=this.params.stagedDiff.diff,{logging:i}=this.params.config,n={model:this.params.config.model,messages:[{role:"system",content:t},{role:"user",content:e}],temperature:this.params.config.temperature,top_p:this.params.config.topP,max_tokens:this.params.config.maxTokens,stream:!1};A(o,r,"Perplexity",n,i);const p=Date.now();try{const a=this.params.config.url||"https://api.perplexity.ai",l=await new R({method:"POST",baseURL:`${a}/chat/completions`,timeout:this.params.config.timeout}).setHeaders({Authorization:`Bearer ${this.apiKey}`,"content-type":"application/json"}).setBody(n).execute(),c=Date.now()-p,s=l.data;if(k(o,r,"Perplexity",s,i),!s.choices||s.choices.length===0||!s.choices[0].message?.content)throw x(o,r,"Perplexity",{message:"No Content on response",result:s},i),new Error("No Content on response. Please open a Bug report");const h=s.choices[0].message.content;return b(o,r,"Perplexity",c,h,i),h}catch(a){throw x(o,r,"Perplexity",a,i),a}}}export{S as PerplexityService};
|