aicommit2 2.5.9 → 2.5.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +8 -1
- package/dist/{ai.service-5e7a5c6e.mjs → ai.service-1ba3c081.mjs} +1 -1
- package/dist/anthropic.service-7842f514.mjs +1 -0
- package/dist/bedrock.service-65bb3c73.mjs +1 -0
- package/dist/cli-e0859d73.mjs +273 -0
- package/dist/cli.mjs +1 -1
- package/dist/codestral.service-cd9177f4.mjs +1 -0
- package/dist/cohere.service-03179c4c.mjs +1 -0
- package/dist/copilot-sdk.service-5c240291.mjs +5 -0
- package/dist/deep-seek.service-0c494b66.mjs +1 -0
- package/dist/gemini.service-ef22fdae.mjs +1 -0
- package/dist/github-models.service-7c104b0a.mjs +5 -0
- package/dist/groq.service-ecd1e518.mjs +1 -0
- package/dist/hugging-face.service-e6a0100a.mjs +2 -0
- package/dist/mistral.service-902039e1.mjs +1 -0
- package/dist/{ollama.service-b6b03f63.mjs → ollama.service-d60eeaa2.mjs} +1 -1
- package/dist/{openai-3abcf411.mjs → openai-22ac0386.mjs} +2 -2
- package/dist/{openai-compatible.service-d1902a30.mjs → openai-compatible.service-987d206d.mjs} +1 -1
- package/dist/{openai.service-b721d675.mjs → openai.service-fb8b0aec.mjs} +1 -1
- package/dist/openrouter.service-16a86909.mjs +1 -0
- package/dist/perplexity.service-6a36f05d.mjs +1 -0
- package/package.json +2 -1
- package/dist/anthropic.service-28cf3eaf.mjs +0 -1
- package/dist/bedrock.service-f1eb56bf.mjs +0 -1
- package/dist/cli-263fe309.mjs +0 -273
- package/dist/codestral.service-34c935d0.mjs +0 -1
- package/dist/cohere.service-834c59db.mjs +0 -1
- package/dist/deep-seek.service-4a737d5f.mjs +0 -1
- package/dist/gemini.service-71595043.mjs +0 -1
- package/dist/github-models.service-823a172a.mjs +0 -5
- package/dist/groq.service-2d45e479.mjs +0 -1
- package/dist/hugging-face.service-c6b4b518.mjs +0 -2
- package/dist/mistral.service-6eea631e.mjs +0 -1
- package/dist/openrouter.service-728f8bb2.mjs +0 -1
- package/dist/perplexity.service-b1967d22.mjs +0 -1
package/README.md
CHANGED
|
@@ -88,6 +88,7 @@ _aicommit2_ automatically generates commit messages using AI. It supports [Git](
|
|
|
88
88
|
| Provider | Default Model | Documentation |
|
|
89
89
|
|----------|---------------|---------------|
|
|
90
90
|
| OpenAI | `gpt-4o-mini` | [Guide](docs/providers/openai.md) |
|
|
91
|
+
| Copilot SDK (Preview) | `gpt-4.1` | [Guide](docs/providers/copilot-sdk.md) |
|
|
91
92
|
| OpenRouter | `openrouter/auto` | [Guide](docs/providers/openrouter.md) |
|
|
92
93
|
| Anthropic | `claude-sonnet-4-20250514` | [Guide](docs/providers/anthropic.md) |
|
|
93
94
|
| Gemini | `gemini-3-flash-preview` | [Guide](docs/providers/gemini.md) |
|
|
@@ -97,11 +98,15 @@ _aicommit2_ automatically generates commit messages using AI. It supports [Git](
|
|
|
97
98
|
| Groq | `llama-3.3-70b-versatile` | [Guide](docs/providers/groq.md) |
|
|
98
99
|
| Perplexity | `sonar` | [Guide](docs/providers/perplexity.md) |
|
|
99
100
|
| DeepSeek | `deepseek-chat` | [Guide](docs/providers/deepseek.md) |
|
|
100
|
-
| GitHub Models | `gpt-4o-mini` | [Guide](docs/providers/github-models.md) |
|
|
101
|
+
| GitHub Models | `openai/gpt-4o-mini` | [Guide](docs/providers/github-models.md) |
|
|
101
102
|
| Bedrock | `anthropic.claude-haiku-4-5-20251001-v1:0` | [Guide](docs/providers/bedrock.md) |
|
|
102
103
|
| Ollama | *(user configured)* | [Guide](docs/providers/ollama.md) |
|
|
103
104
|
|
|
104
105
|
> 📘 For OpenAI-compatible APIs, see [Compatibility Guide](docs/providers/compatible.md)
|
|
106
|
+
>
|
|
107
|
+
> 📘 GitHub note: `COPILOT_SDK` uses Copilot CLI authentication (`Copilot Requests` permission), while `GITHUB_MODELS` uses GitHub Models API tokens (`models: read`).
|
|
108
|
+
>
|
|
109
|
+
> 📘 Copilot SDK stable setup example (`config.ini` + env): [Copilot SDK Guide](docs/providers/copilot-sdk.md#recommended-configini-stable-baseline).
|
|
105
110
|
|
|
106
111
|
## Setup
|
|
107
112
|
|
|
@@ -471,6 +476,8 @@ aicommit2 hook install
|
|
|
471
476
|
aicommit2 hook uninstall
|
|
472
477
|
```
|
|
473
478
|
|
|
479
|
+
> GitHub Models tip: use `aicommit2 github-login` and set `GITHUB_MODELS.model` in `publisher/model` format (for example, `openai/gpt-5`).
|
|
480
|
+
|
|
474
481
|
## Integrations
|
|
475
482
|
|
|
476
483
|
### LazyGit
|
|
@@ -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-e0859d73.mjs";const y=new Map,d=(f,s,e)=>{const o=M(0).update(s).digest("hex").substring(0,8),r=`${f}_${o}_${e}`;if(y.has(r))return y.get(r);const n=new Date,t=Z(n,f,s,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(r,i),i},K=f=>{const s={...f},e=["authorization","x-api-key","x-goog-api-key","api-key","x-amzn-bedrock-application-key"];for(const o of e){const r=o.toLowerCase(),n=Object.keys(s).find(t=>t.toLowerCase()===r);n&&s[n]&&typeof s[n]=="string"&&(s[n].startsWith("Bearer ")?s[n]="Bearer [MASKED]":s[n]="[MASKED]")}return s},Y=(f,s,e,o,r,n,t=!0)=>{if(!t)return;const c=d(e,f,s);c.info(`Making request to ${e} API with model: ${o}`),c.info(`Request URL: ${r}`),c.info("Request headers:",K(n))},V=(f,s,e,o,r=!0)=>{if(!r)return;d(e,f,s).info("Request payload:",o)},W=(f,s,e,o,r,n=!0)=>{if(!n)return;const t=d(e,f,s);t.info("System prompt:",{prompt:o}),t.info("User prompt:",{prompt:r})},G=(f,s,e,o,r=!0)=>{if(!r)return;d(e,f,s).info("Response received:",o)},Q=(f,s,e,o,r=!0)=>{if(!r)return;d(e,f,s).error("API request failed:",o)},R=(f,s,e,o,r,n=!0)=>{if(!n)return;const t=d(e,f,s);o?t.info(`Request completed successfully in ${o}ms`):t.info("Request completed successfully"),r&&t.info("Final processed response:",{response:r}),t.info(""),t.info("=".repeat(50)),t.info(`End Time: ${new Date().toISOString()}`),t.info("=== REQUEST COMPLETED ===")},X=(f,s,e,o,r,n,t,c=!0)=>{if(!c)return;const i=d(e,f,s);t?i.error(`Request failed after ${n}ms:`,{error:t}):(i.info(`Request completed in ${n}ms`),i.info("Response:",{response:r})),R(f,s,e,n,r,c)},Z=(f,s,e,o)=>{const{year:r,month:n,day:t,hours:c,minutes:i,seconds:u}=ee(f),a=M(0).update(e).digest("hex").substring(0,8),m=s.toLowerCase().replace(/[^a-z0-9]/g,"").substring(0,20);return o==="review"?`${r}-${n}-${t}_${c}-${i}-${u}_${a}_${m}_review.log`:`${r}-${n}-${t}_${c}-${i}-${u}_${a}_${m}_commit.log`},ee=f=>{const s=f.getFullYear().toString(),e=(f.getMonth()+1).toString().padStart(2,"0"),o=f.getDate().toString().padStart(2,"0"),r=f.getHours().toString().padStart(2,"0"),n=f.getMinutes().toString().padStart(2,"0"),t=f.getSeconds().toString().padStart(2,"0");return{year:s,month:e,day:o,hours:r,minutes:n,seconds:t}},w=()=>{for(const[f,s]of y.entries())try{s.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=s=>{this.buffer+=s;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 r=this.extractBalancedBraces(o);if(!r)break;this.scanPosition=o+r.length;const n=this.tryParseCommitMessage(r);n&&e.push(n)}return e},this.flush=()=>this.feed(""),this.getBuffer=()=>this.buffer,this.getUnparsedBuffer=()=>this.buffer.slice(this.scanPosition),this.extractBalancedBraces=s=>{let e=0,o=!1,r=!1;for(let n=s;n<this.buffer.length;n++){const t=this.buffer[n];if(r){r=!1;continue}if(t==="\\"&&o){r=!0;continue}if(t==='"'){o=!o;continue}if(!o&&(t==="{"&&e++,t==="}"&&e--,e===0))return this.buffer.slice(s,n+1)}return null},this.tryParseCommitMessage=s=>{try{const e=JSON.parse(s);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(s){this.handleError$=e=>{const o=this.getDetailedErrorMessage(e),r=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,r)}return p.error(`${this.errorPrefix} ${r}`),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} ${r}`,value:r,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:r,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:r,vcs_branch:this.params.branchName||""};return D(u)},this.formatRawCommitMessage=(e,o)=>{const r=this.extractMessageAsType(e,o),n=r.subject,t=`${r.subject}${r.body?`
|
|
2
2
|
|
|
3
3
|
${r.body}`:""}${r.footer?`
|
|
4
4
|
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import j from"@anthropic-ai/sdk";import S 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-1ba3c081.mjs";import{D as z,g as H,b as G,k as K}from"./cli-e0859d73.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=x=>{const e=x.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:C,maxTokens:k,topP:p,model:m}=this.params.config,g={...z,locale:l,maxLength:C,type:y,generate:d,systemPrompt:n,systemPromptPath:c,codeReviewPromptPath:s,vcs_branch:this.params.branchName||""},h=H(g),v=K(o,"commit"),M=`${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,M,w,i),O(o,"commit","Anthropic",h,v,i);const u=X(m),f={max_tokens:k,temperature:P,system:h,messages:[{role:"user",content:v}],model:m,stream:!0,...u?{}:{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",E=>{A+=E,t.next(E)});const I=await r.finalMessage(),Y=Date.now()-a;T(o,"commit","Anthropic",I,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=S.bgHex(this.colors.primary).hex(this.colors.secondary).bold(`[Anthropic/${this.params.config.model}]`),this.errorPrefix=S.red.bold(`[Anthropic/${this.params.config.model}]`),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:C,topP:k,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||""},g=e==="review"?G(m):H(m),h=K(t,e),_=`${this.params.config.url||"https://api.anthropic.com"}/v1/messages`,M={"Content-Type":"application/json","x-api-key":this.params.config.key,"anthropic-version":"2023-06-01"};F(t,e,"Anthropic",p,_,M,s),O(t,e,"Anthropic",g,h,s);const w=X(p),u={max_tokens:C,temperature:i,system:g,messages:[{role:"user",content:h}],model:p,...w?{}:{top_p:k}};L(t,e,"Anthropic",u,s);const f=Date.now();try{const a=await this.anthropic.messages.create(u),A=Date.now()-f;T(t,e,"Anthropic",a,s);const r=a.content.map(({text:I})=>I).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};
|
|
@@ -0,0 +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-1ba3c081.mjs";import{D as J,b as j,g as Q,p as O,s as X,k as Z}from"./cli-e0859d73.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 v=null,M=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(v)return v;try{return v=await import("@aws-sdk/client-bedrock-runtime"),v}catch(f){throw v=null,G(f)}},U=async()=>{if(M)return M;try{return M=await import("@aws-sdk/credential-providers"),M}catch(f){throw M=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.params.config.model}]`),this.errorPrefix=h.red.bold(`[${g}/${this.params.config.model}]`),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};
|