aicommit2 2.5.4 → 2.5.6

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.
Files changed (36) hide show
  1. package/README.md +86 -18
  2. package/dist/ai.service-9119469d.mjs +17 -0
  3. package/dist/anthropic.service-68956862.mjs +1 -0
  4. package/dist/bedrock.service-9933a587.mjs +1 -0
  5. package/dist/cli-c30dd603.mjs +273 -0
  6. package/dist/cli.mjs +1 -1
  7. package/dist/codestral.service-0390f41e.mjs +1 -0
  8. package/dist/cohere.service-7282793a.mjs +1 -0
  9. package/dist/deep-seek.service-689940ee.mjs +1 -0
  10. package/dist/gemini.service-595d667c.mjs +1 -0
  11. package/dist/github-models.service-a89f5f34.mjs +5 -0
  12. package/dist/groq.service-41276877.mjs +1 -0
  13. package/dist/hugging-face.service-50193927.mjs +2 -0
  14. package/dist/mistral.service-14601dd7.mjs +1 -0
  15. package/dist/ollama.service-f01b8d7a.mjs +1 -0
  16. package/dist/{openai-a5caac9c.mjs → openai-aca766eb.mjs} +1 -1
  17. package/dist/openai-compatible.service-d8949180.mjs +1 -0
  18. package/dist/openai.service-f4ea1dc7.mjs +1 -0
  19. package/dist/perplexity.service-c2894100.mjs +1 -0
  20. package/package.json +1 -1
  21. package/dist/ai.service-e4638af5.mjs +0 -5
  22. package/dist/anthropic.service-d6f32293.mjs +0 -1
  23. package/dist/bedrock.service-8f357ef0.mjs +0 -1
  24. package/dist/cli-6797d3ee.mjs +0 -294
  25. package/dist/codestral.service-52aea4ab.mjs +0 -1
  26. package/dist/cohere.service-1de1f236.mjs +0 -1
  27. package/dist/deep-seek.service-e7d260aa.mjs +0 -1
  28. package/dist/gemini.service-9ea5644a.mjs +0 -1
  29. package/dist/github-models.service-0ec74310.mjs +0 -5
  30. package/dist/groq.service-dc7f5129.mjs +0 -1
  31. package/dist/hugging-face.service-0ca40e02.mjs +0 -2
  32. package/dist/mistral.service-e1ed37fd.mjs +0 -1
  33. package/dist/ollama.service-2905a90b.mjs +0 -1
  34. package/dist/openai-compatible.service-833e4451.mjs +0 -1
  35. package/dist/openai.service-e2d5fc19.mjs +0 -1
  36. package/dist/perplexity.service-90e30b99.mjs +0 -1
package/README.md CHANGED
@@ -38,6 +38,7 @@ ______________________________________________________________________
38
38
  - [General Settings](#general-settings)
39
39
  - [Logging](#logging)
40
40
  - [Custom Prompt Template](#custom-prompt-template)
41
+ - [Code Review](#code-review)
41
42
  - [Watch Commit Mode](#watch-commit-mode)
42
43
  - [Upgrading](#upgrading)
43
44
  - [Contributing](#contributing)
@@ -53,7 +54,10 @@ brew install aicommit2
53
54
  # Or install via npm
54
55
  npm install -g aicommit2
55
56
 
56
- # Set up at least one AI provider
57
+ # Set up AI providers (interactive wizard)
58
+ aicommit2 setup
59
+
60
+ # Or configure manually
57
61
  aicommit2 config set OPENAI.key=<your-key>
58
62
 
59
63
  # Use in your Git repository
@@ -75,6 +79,7 @@ _aicommit2_ automatically generates commit messages using AI. It supports [Git](
75
79
  - **[Multi-AI Support](#cloud-ai-services)**: Integrates with OpenAI, Anthropic Claude, Google Gemini, Mistral AI, Cohere, Groq, Ollama and more
76
80
  - **[OpenAI API Compatibility](docs/providers/compatible.md)**: Support for any service that implements the OpenAI API specification
77
81
  - **[Reactive CLI](#usage)**: Enables simultaneous requests to multiple AIs and selection of the best commit message
82
+ - **[Code Review](#code-review)**: AI-powered structured code review with severity levels before committing
78
83
  - **[Git Hook Integration](#git-hooks)**: Can be used as a prepare-commit-msg hook
79
84
  - **[Custom Prompt](#custom-prompt-template)**: Supports user-defined system prompt templates
80
85
 
@@ -113,8 +118,16 @@ npm install -g aicommit2
113
118
 
114
119
  > ⚠️ For npm installation, the minimum supported version of Node.js is v18. Check your Node.js version with `node --version`.
115
120
 
116
- 2. Set up API keys (**at least ONE key must be set**):
121
+ 2. Configure your AI provider(s) (**at least ONE provider must be configured**):
117
122
 
123
+ **Option A: Interactive setup wizard (recommended)**
124
+ ```bash
125
+ aicommit2 setup
126
+ ```
127
+
128
+ > 👉 The setup wizard guides you through provider selection, API key entry, and model configuration in one step.
129
+
130
+ **Option B: Manual configuration**
118
131
  ```bash
119
132
  aicommit2 config set OPENAI.key=<your key>
120
133
  aicommit2 config set ANTHROPIC.key=<your key>
@@ -427,6 +440,7 @@ In addition to the main commit message generation, aicommit2 provides several ut
427
440
 
428
441
  | Command | Description |
429
442
  |---------|-------------|
443
+ | `aicommit2 setup` | Interactive setup wizard for configuring AI providers |
430
444
  | `aicommit2 config` | Manage configuration (get, set, list, del) |
431
445
  | `aicommit2 doctor` | Check health status of AI providers |
432
446
  | `aicommit2 stats` | View usage statistics and performance metrics |
@@ -435,6 +449,9 @@ In addition to the main commit message generation, aicommit2 provides several ut
435
449
  | `aicommit2 github-login` | Login to GitHub for GitHub Models access |
436
450
 
437
451
  ```bash
452
+ # Interactive setup wizard
453
+ aicommit2 setup
454
+
438
455
  # Configuration management
439
456
  aicommit2 config set OPENAI.key=<your-key>
440
457
  aicommit2 config get OPENAI
@@ -640,7 +657,7 @@ aicommit2 doctor
640
657
  Example output:
641
658
 
642
659
  ```
643
- 🩺 AICommit2 Health Check
660
+ 🩺 aicommit2 Health Check
644
661
 
645
662
  Providers:
646
663
  ✅ OPENAI API key configured
@@ -872,11 +889,13 @@ For detailed information about all available settings, see the [General Settings
872
889
  | `temperature` | Model's creativity (0.0 - 2.0) | 0.7 |
873
890
  | `maxTokens` | Maximum number of tokens to generate | 1024 |
874
891
  | `includeBody` | Whether the commit message includes body | false |
875
- | `codeReview` | Enable automated code review | false |
892
+ | `codeReview` | Enable automated code review before commit | false |
893
+ | `codeReviewPromptPath` | Path to custom code review prompt file | - |
876
894
  | `autoCopy` | Auto-copy commit message to clipboard (commits normally) | false |
877
895
  | `useStats` | Enable usage statistics tracking | true |
878
896
  | `statsDays` | Days to retain statistics data (auto-cleanup) | 30 |
879
897
  | `systemPromptPath` | Path to custom system prompt file | - |
898
+ | `stream` | **Experimental.** Enable streaming for real-time commit message generation | false |
880
899
 
881
900
  ```bash
882
901
  # Example: Set settings for a specific model
@@ -889,20 +908,20 @@ aicommit2 config set ANTHROPIC.includeBody=true
889
908
 
890
909
  ### Available Settings by Model
891
910
 
892
- | | timeout | temperature | maxTokens | topP |
893
- | :-----------------------: | :-----: | :---------: | :-------: | :--: |
894
- | **OpenAI** | ✓ | ✓ | ✓ | ✓ |
895
- | **Anthropic Claude** | ✓ | ✓ | ✓ | ✓ |
896
- | **Gemini** | | ✓ | ✓ | ✓ |
897
- | **Mistral AI** | ✓ | ✓ | ✓ | ✓ |
898
- | **Codestral** | ✓ | ✓ | ✓ | ✓ |
899
- | **Cohere** | ✓ | ✓ | ✓ | ✓ |
900
- | **Groq** | ✓ | ✓ | ✓ | ✓ |
901
- | **Perplexity** | ✓ | ✓ | ✓ | ✓ |
902
- | **DeepSeek** | ✓ | ✓ | ✓ | ✓ |
903
- | **Github Models** | ✓ | ✓ | ✓ | ✓ |
904
- | **Ollama** | ✓ | ✓ | | ✓ |
905
- | **OpenAI API-Compatible** | ✓ | ✓ | ✓ | ✓ |
911
+ | | timeout | temperature | maxTokens | topP | stream |
912
+ | :-----------------------: | :-----: | :---------: | :-------: | :--: | :----: |
913
+ | **OpenAI** | ✓ | ✓ | ✓ | ✓ | ✓ |
914
+ | **Anthropic Claude** | ✓ | ✓ | ✓ | ✓ | ✓ |
915
+ | **Gemini** | | ✓ | ✓ | ✓ | ✓ |
916
+ | **Mistral AI** | ✓ | ✓ | ✓ | ✓ | |
917
+ | **Codestral** | ✓ | ✓ | ✓ | ✓ | |
918
+ | **Cohere** | ✓ | ✓ | ✓ | ✓ | |
919
+ | **Groq** | ✓ | ✓ | ✓ | ✓ | ✓ |
920
+ | **Perplexity** | ✓ | ✓ | ✓ | ✓ | |
921
+ | **DeepSeek** | ✓ | ✓ | ✓ | ✓ | ✓ |
922
+ | **Github Models** | ✓ | ✓ | ✓ | ✓ | |
923
+ | **Ollama** | ✓ | ✓ | | ✓ | ✓ |
924
+ | **OpenAI API-Compatible** | ✓ | ✓ | ✓ | ✓ | ✓ |
906
925
 
907
926
  ## Logging
908
927
 
@@ -1043,6 +1062,55 @@ The response should be valid JSON that can be parsed without errors.
1043
1062
 
1044
1063
  This ensures that the output is consistently formatted as a JSON array, regardless of the custom template used.
1045
1064
 
1065
+ ## Code Review
1066
+
1067
+ aicommit2 includes an AI-powered code review feature that analyzes your staged changes before generating commit messages. When enabled, it provides structured feedback with severity levels and actionable suggestions.
1068
+
1069
+ ### Enable Code Review
1070
+
1071
+ ```bash
1072
+ # Enable globally
1073
+ aicommit2 config set codeReview=true
1074
+
1075
+ # Or enable for specific providers only
1076
+ aicommit2 config set OPENAI.codeReview=true
1077
+ aicommit2 config set ANTHROPIC.codeReview=true
1078
+ ```
1079
+
1080
+ ### How It Works
1081
+
1082
+ When `codeReview` is enabled, the commit flow becomes:
1083
+
1084
+ 1. **Stage changes** (`git add`)
1085
+ 2. **Run aicommit2** — code review runs automatically before commit message generation
1086
+ 3. **Review results** — AI analyzes the diff and returns structured feedback
1087
+ 4. **Confirm or abort** — choose to continue with the commit or fix issues first
1088
+ 5. **Generate commit messages** — proceeds as normal after confirmation
1089
+
1090
+ ### Structured Review Output
1091
+
1092
+ Reviews are organized by severity and category:
1093
+
1094
+ - **Severity levels**: `critical`, `warning`, `suggestion`, `praise`
1095
+ - **Categories**: `bug`, `security`, `performance`, `style`, `maintainability`, `other`
1096
+
1097
+ Each review item includes a title, description, file reference, and concrete suggestion for improvement. When critical issues are found, the confirmation prompt defaults to "No" to encourage fixing before committing.
1098
+
1099
+ ### Custom Review Prompt
1100
+
1101
+ You can customize the code review prompt using a template file:
1102
+
1103
+ ```bash
1104
+ aicommit2 config set codeReviewPromptPath="/path/to/review-prompt.txt"
1105
+ aicommit2 config set OPENAI.codeReviewPromptPath="/path/to/another-prompt.txt"
1106
+ ```
1107
+
1108
+ The template supports the same `{locale}`, `{type}`, `{generate}`, `{maxLength}` placeholders as the commit prompt.
1109
+
1110
+ > **NOTE**: When using a custom review prompt, the response format is plain text (not structured JSON). The structured severity/category output is only available with the default prompt.
1111
+
1112
+ > **WARNING**: Code review runs **in addition to** commit message generation, which means **API token usage roughly doubles** per commit. If multiple providers have `codeReview` enabled, each provider performs its own review. Monitor your token usage carefully, especially with large diffs.
1113
+
1046
1114
  ## Watch Commit Mode
1047
1115
 
1048
1116
  ![watch-commit-gif](https://github.com/tak-bro/aicommit2/blob/main/img/watch-commit-min.gif?raw=true)
@@ -0,0 +1,17 @@
1
+ import{of as L,Observable as _,Subject as J,catchError as B}from"rxjs";import"fs";import"path";import{xxh64 as C}from"@pacote/xxhash";import $ from"winston";import{A as T,l as p,D as F,g as D,s as M,h as U,d as z,E as H,e as q,f as P}from"./cli-c30dd603.mjs";const y=new Map,d=(f,t,e)=>{const r=C(0).update(t).digest("hex").substring(0,8),o=`${f}_${r}_${e}`;if(y.has(o))return y.get(o);const i=new Date,s=Z(i,f,t,e),c=`${T}/${s}`,n=$.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 n.info(`=== ${f.toUpperCase()} AI SERVICE LOG ===`),n.info(`Diff Hash: ${r}`),n.info(`Request Type: ${e.toUpperCase()}`),n.info(`Start Time: ${i.toISOString()}`),n.info("=".repeat(50)),n.info(""),y.set(o,n),n},K=f=>{const t={...f},e=["authorization","x-api-key","x-goog-api-key","api-key","x-amzn-bedrock-application-key"];for(const r of e){const o=r.toLowerCase(),i=Object.keys(t).find(s=>s.toLowerCase()===o);i&&t[i]&&typeof t[i]=="string"&&(t[i].startsWith("Bearer ")?t[i]="Bearer [MASKED]":t[i]="[MASKED]")}return t},Y=(f,t,e,r,o,i,s=!0)=>{if(!s)return;const c=d(e,f,t);c.info(`Making request to ${e} API with model: ${r}`),c.info(`Request URL: ${o}`),c.info("Request headers:",K(i))},V=(f,t,e,r,o=!0)=>{if(!o)return;d(e,f,t).info("Request payload:",r)},W=(f,t,e,r,o,i=!0)=>{if(!i)return;const s=d(e,f,t);s.info("System prompt:",{prompt:r}),s.info("User prompt:",{prompt:o})},G=(f,t,e,r,o=!0)=>{if(!o)return;d(e,f,t).info("Response received:",r)},Q=(f,t,e,r,o=!0)=>{if(!o)return;d(e,f,t).error("API request failed:",r)},R=(f,t,e,r,o,i=!0)=>{if(!i)return;const s=d(e,f,t);r?s.info(`Request completed successfully in ${r}ms`):s.info("Request completed successfully"),o&&s.info("Final processed response:",{response:o}),s.info(""),s.info("=".repeat(50)),s.info(`End Time: ${new Date().toISOString()}`),s.info("=== REQUEST COMPLETED ===")},X=(f,t,e,r,o,i,s,c=!0)=>{if(!c)return;const n=d(e,f,t);s?n.error(`Request failed after ${i}ms:`,{error:s}):(n.info(`Request completed in ${i}ms`),n.info("Response:",{response:o})),R(f,t,e,i,o,c)},Z=(f,t,e,r)=>{const{year:o,month:i,day:s,hours:c,minutes:n,seconds:u}=ee(f),a=C(0).update(e).digest("hex").substring(0,8),m=t.toLowerCase().replace(/[^a-z0-9]/g,"").substring(0,20);return r==="review"?`${o}-${i}-${s}_${c}-${n}-${u}_${a}_${m}_review.log`:`${o}-${i}-${s}_${c}-${n}-${u}_${a}_${m}_commit.log`},ee=f=>{const t=f.getFullYear().toString(),e=(f.getMonth()+1).toString().padStart(2,"0"),r=f.getDate().toString().padStart(2,"0"),o=f.getHours().toString().padStart(2,"0"),i=f.getMinutes().toString().padStart(2,"0"),s=f.getSeconds().toString().padStart(2,"0");return{year:t,month:e,day:r,hours:o,minutes:i,seconds:s}},b=()=>{for(const[f,t]of y.entries())try{t.close()}catch(e){console.error(`Failed to close logger ${f}:`,e)}y.clear()};process.on("exit",b),process.on("SIGINT",()=>{b(),process.exit(0)}),process.on("SIGTERM",()=>{b(),process.exit(0)});class te{constructor(){this.buffer="",this.arrayStartFound=!1,this.scanPosition=0,this.feed=t=>{this.buffer+=t;const e=[];if(!this.arrayStartFound){const r=this.buffer.indexOf("[");if(r===-1)return e;this.arrayStartFound=!0,this.scanPosition=r+1}for(;;){const r=this.buffer.indexOf("{",this.scanPosition);if(r===-1)break;const o=this.extractBalancedBraces(r);if(!o)break;this.scanPosition=r+o.length;const i=this.tryParseCommitMessage(o);i&&e.push(i)}return e},this.flush=()=>this.feed(""),this.getBuffer=()=>this.buffer,this.getUnparsedBuffer=()=>this.buffer.slice(this.scanPosition),this.extractBalancedBraces=t=>{let e=0,r=!1,o=!1;for(let i=t;i<this.buffer.length;i++){const s=this.buffer[i];if(o){o=!1;continue}if(s==="\\"&&r){o=!0;continue}if(s==='"'){r=!r;continue}if(!r&&(s==="{"&&e++,s==="}"&&e--,e===0))return this.buffer.slice(t,i+1)}return null},this.tryParseCommitMessage=t=>{try{const e=JSON.parse(t);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(t){this.handleError$=e=>{const r=this.getDetailedErrorMessage(e),o=e.status?`HTTP ${e.status}: ${r}`:r;if(this.params.config.logging){const i=this.params.stagedDiff.diff,s=this.serviceName.replace(/\[|\]/g,"").trim();X(i,"commit",s,"Error occurred","",void 0,o)}return p.error(`${this.errorPrefix} ${o}`),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} ${o}`,value:o,isError:!0,disabled:!0})},this.extractJsonObjectFromResponse=e=>{const r=e.indexOf("{");return r!==-1?this.extractBalancedJson(e,r,"{","}"):null},this.buildCommitPrompt=()=>{const{systemPrompt:e,systemPromptPath:r,codeReviewPromptPath:o,locale:i,generate:s,type:c,maxLength:n}=this.params.config,u={...F,locale:i,maxLength:n,type:c,generate:s,systemPrompt:e,systemPromptPath:r,codeReviewPromptPath:o,vcs_branch:this.params.branchName||""};return D(u)},this.formatRawCommitMessage=(e,r)=>{const o=this.extractMessageAsType(e,r),i=o.subject,s=`${o.subject}${o.body?`
2
+
3
+ ${o.body}`:""}${o.footer?`
4
+
5
+ ${o.footer}`:""}`;return{title:i,value:s}},this.formatAsChoice=e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:this.params.config.includeBody?e.value:e.title,description:this.params.config.includeBody?e.value:"",isError:!1}),this.extractStreamPreview=e=>{const r=e.match(/"subject"\s*:\s*"((?:[^"\\]|\\.)*)(?:"|$)/),o=e.match(/"body"\s*:\s*"((?:[^"\\]|\\.)*)(?:"|$)/),i=r?r[1].replace(/\\"/g,'"').replace(/\\n/g,`
6
+ `):"",s=o?o[1].replace(/\\"/g,'"').replace(/\\n/g,`
7
+ `):"";return{subject:i,body:s}},this.createStreamingCommitMessages$=(e,r,o)=>{const i=`stream-${this.serviceName}-${Date.now()}`;return new _(s=>{const c=new te,n=new J;let u=0,l=!1,a=0;const m=100,A="streaming",w={name:"",value:"",streamKey:i,disabled:!0,isError:!1},j=(g=!1)=>{const h=Date.now();if(!g&&h-a<m)return;a=h;const v=c.getUnparsedBuffer();if(!v.trim())return;const{subject:S,body:I}=this.extractStreamPreview(v),O=S?`${this.serviceName} ${S}`:`${this.serviceName} Generating...`,N=I||S||"",k={name:O,short:S||"Generating...",value:`__streaming__${i}`,description:N,disabled:A,isError:!1,streamKey:i};s.next(k),l=!0},E=g=>{for(const h of g){if(u>=o)break;s.next(this.formatAsChoice(this.formatRawCommitMessage(h,r))),u++}},x=n.subscribe({next:g=>{if(u>=o)return;const h=c.feed(g);E(h),u<o&&j()},error:g=>{l&&s.next(w),s.error(g)},complete:()=>{E(c.flush()),l&&s.next(w);const g=c.getBuffer();if(u===0&&g.trim())try{const h=this.parseMessage(g,r,o);for(const v of h)s.next(this.formatAsChoice(v))}catch(h){s.error(h);return}s.complete()}});return e(n),()=>{x.unsubscribe()}}).pipe(B(this.handleError$))},this.parseCodeReview=e=>{const r=this.cleanJsonCodeBlock(e),o=this.extractJsonObjectFromResponse(r);if(!o)return p.warn(`${this.serviceName} Code review response did not contain JSON, falling back to plain text`),this.sanitizeResponse(e);const i=M(o);if(!i.ok)return p.warn(`${this.serviceName} Failed to parse code review JSON, falling back to plain text`),this.sanitizeResponse(e);const s=i.data;if(!(s&&typeof s.summary=="string"&&Array.isArray(s.items)))return p.warn(`${this.serviceName} Code review JSON missing summary or items, falling back to plain text`),this.sanitizeResponse(e);const n=s.items.filter(m=>typeof m.title=="string"&&typeof m.severity=="string"&&typeof m.description=="string"&&typeof m.category=="string"),u=n.some(m=>m.severity==="critical"),l=this.formatReviewSummaryTitle(s.summary,n),a=this.formatReviewAsMarkdown(s.summary,n,u);return this.isLoggingEnabled()&&p.info(`${this.serviceName} Parsed code review: ${n.length} items`),[{title:l,value:a}]},this.formatCodeReviewAsChoice=e=>({name:`${this.serviceName} ${e.title}`,short:e.title,value:e.value,description:e.value,isError:!1}),this.formatReviewSummaryTitle=(e,r)=>{const o=r.reduce((l,a)=>(l[a.severity]=(l[a.severity]??0)+1,l),{}),s=["critical","warning","suggestion","praise"].filter(l=>o[l]).map(l=>`${o[l]} ${l}`),c=s.length>0?` (${s.join(", ")})`:"",n=60;return`${e.length>n?`${e.slice(0,n-3)}...`:e}${c}`},this.formatReviewAsMarkdown=(e,r,o)=>{const s=[`## Summary
8
+ ${e}${o?`
9
+ <!-- HAS_CRITICAL_ISSUES -->
10
+ `:""}
11
+ `],c=["critical","warning","suggestion","praise"];for(const n of c){const u=r.filter(l=>l.severity===n);if(u.length!==0){s.push(`### [${n.toUpperCase()}] ${n.charAt(0).toUpperCase()}${n.slice(1)}
12
+ `);for(const l of u){const a=l.file?` (${l.file}${l.line?`:${l.line}`:""})`:"";s.push(`- **[${l.category}]** ${l.title}${a}`),s.push(` ${l.description}`),l.suggestion&&s.push(` > Suggestion: ${l.suggestion}`),s.push("")}}}return s.join(`
13
+ `)},this.serviceName="AI",this.errorPrefix="ERROR",this.colors={primary:""},this.params=t,this.logSessionId=t.logSessionId}getProviderName(){const t=String.fromCharCode(27),e=new RegExp(`${t}\\[[0-9;]*m`,"g");return this.serviceName.replace(e,"").replace(/\[|\]/g,"").trim()}getDetailedErrorMessage(t){const e=t.message||"",r=this.getProviderName(),o=this.params.config.model?.[0],i=this.params.config.timeout,s=this.getServiceSpecificErrorMessage(t);if(s)return s;const c=t.code||(t.status?U(t.status):z(e));return c!==H.UNKNOWN?q(c,{provider:r,model:o,timeout:i}):e||"Unknown error occurred"}getServiceSpecificErrorMessage(t){return null}cleanJsonCodeBlock(t){const e=/```(?:json|JSON)?\s*([\s\S]*?)\s*```/,r=t.match(e);return r?r[1].trim():t}extractJsonFromResponse(t){let e=t.indexOf("[");if(e!==-1){const r=this.extractBalancedJson(t,e,"[","]");if(r)return r}if(e=t.indexOf("{"),e!==-1){const r=this.extractBalancedJson(t,e,"{","}");if(r)return r}return null}extractBalancedJson(t,e,r,o){let i=0,s=!1,c=!1;for(let n=e;n<t.length;n++){const u=t[n];if(c){c=!1;continue}if(u==="\\"&&s){c=!0;continue}if(u==='"'){s=!s;continue}if(!s&&(u===r&&i++,u===o&&i--,i===0))return t.slice(e,n+1)}return null}parseMessage(t,e,r){const o=this.cleanJsonCodeBlock(t),i=this.extractJsonFromResponse(o);if(!i){const a=new Error("AI response did not contain a valid JSON object or array.");throw a.name="InvalidJsonResponse",a.content=t,a}const s=M(i);if(!s.ok){const a=new Error("Failed to parse AI response as JSON");throw a.name="JsonParseError",a.content=i,a.originalError=s.error,a}const c=s.data,n=Array.isArray(c)?c:[c];if(!n.length||!n.every(a=>typeof a.subject=="string")){const a=new Error("AI response contained malformed commit message data.");throw a.name="MalformedCommitMessage",a.content=t,a}const l=n.map(a=>this.extractMessageAsType(a,e)).map(a=>({title:`${a.subject}`,value:`${a.subject}${a.body?`
14
+
15
+ ${a.body}`:""}${a.footer?`
16
+
17
+ ${a.footer}`:""}`})).slice(0,r);if(this.isLoggingEnabled()){const a=l.map(m=>m.title).join(", ");p.info(`${this.serviceName} Parsed ${l.length} commit messages: ${a}`)}return l}extractMessageAsType(t,e){switch(e){case"conventional":const r=/(\w+)(?:\(.*?\))?:\s*(.*)/,o=t.subject.match(r),i=o?o[0]:t.subject;return{...t,subject:this.normalizeCommitMessage(i)};case"gitmoji":const s=/:\w*:\s*(.*)/,c=t.subject.match(s),n=this.params.config.disableLowerCase??!1;return{...t,subject:c&&!n?c[0].toLowerCase():t.subject};default:return t}}normalizeCommitMessage(t){const e=/^(\w+)(\(.*?\))?:\s(.*)$/,r=t.match(e);if(r){const[,o,i,s]=r,c=this.params.config.disableLowerCase??!1,n=o.toLowerCase(),u=c?s:s.charAt(0).toLowerCase()+s.slice(1);t=`${n}${i||""}: ${u}`}return t}sanitizeResponse(t){if(typeof t=="string")try{return[{title:`${P(t)}...`,value:t}]}catch{return[]}return t.map(e=>{try{return{title:`${P(e)}...`,value:e}}catch{return{title:"",value:""}}})}isLoggingEnabled(){return this.params.config.logging&&!!this.logSessionId}}export{se as A,W as a,V as b,G as c,R as d,Q as e,Y as l};
@@ -0,0 +1 @@
1
+ import j from"@anthropic-ai/sdk";import S from"chalk";import{concatMap as b,from as D,map as R,catchError as $}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-9119469d.mjs";import{D as z,g as H,b as G,k as K}from"./cli-c30dd603.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.errorPrefix=S.red.bold("[Anthropic]"),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(b(t=>D(t)),R(this.formatAsChoice),$(this.handleError$))}generateCodeReview$(){return U(this.generateMessage("review")).pipe(b(e=>D(e)),R(this.formatCodeReviewAsChoice),$(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-9119469d.mjs";import{D as J,b as j,g as Q,p as O,s as X,k as Z}from"./cli-c30dd603.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.errorPrefix=h.red.bold(`[${g}]`),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};