turbocommit 3.1.0

A CLI tool to create commit messages with OpenAI GPT-5.4 for Git and Jujutsu (JJ) repositories
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
#![allow(dead_code)]

use colored::Colorize;
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use std::{
    fmt, process,
    time::{Duration, Instant},
};

use crate::{debug_log::DebugLogger, spinner};

#[derive(Serialize, Deserialize, Debug, PartialEq, Clone)]
#[serde(rename_all = "lowercase")]
pub enum Role {
    System,
    User,
    Assistant,
    Developer,
}

impl fmt::Display for Role {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Role::System => write!(f, "system"),
            Role::User => write!(f, "user"),
            Role::Assistant => write!(f, "assistant"),
            Role::Developer => write!(f, "developer"),
        }
    }
}

#[derive(Serialize, Deserialize, Debug, PartialEq, Clone)]
pub struct Message {
    pub role: Role,
    pub content: String,
}

impl Message {
    pub const fn system(content: String) -> Self {
        Self {
            role: Role::System,
            content,
        }
    }
    pub const fn developer(content: String) -> Self {
        Self {
            role: Role::Developer,
            content,
        }
    }
    pub const fn user(content: String) -> Self {
        Self {
            role: Role::User,
            content,
        }
    }
    pub const fn assistant(content: String) -> Self {
        Self {
            role: Role::Assistant,
            content,
        }
    }
}

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct CommitSuggestion {
    pub title: String,
    #[serde(default)]
    pub body: Option<String>,
}

impl CommitSuggestion {
    pub fn as_commit_message(&self) -> String {
        let title = self.title.trim();
        match self
            .body
            .as_ref()
            .map(|b| b.trim())
            .filter(|b| !b.is_empty())
        {
            Some(body) => format!("{title}\n\n{body}"),
            None => title.to_string(),
        }
    }
}

#[derive(Debug, Serialize, Deserialize)]
pub struct CommitSuggestionsEnvelope {
    pub suggestions: Vec<CommitSuggestion>,
}

#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct ErrorRoot {
    pub error: Error,
}

#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct Error {
    pub message: String,
    #[serde(rename = "type")]
    pub type_field: String,
    pub param: Option<String>,
    pub code: Option<String>,
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{} ({:?}): {:?}",
            self.type_field.red(),
            self.code,
            self.message
        )
    }
}

#[derive(Debug, Serialize)]
pub struct Request {
    pub model: String,
    pub messages: Vec<Message>,
    #[serde(skip)]
    suggestion_count: usize,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub reasoning_effort: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub verbosity: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub response_format: Option<ResponseFormat>,
}

#[derive(Debug, Serialize)]
pub struct ResponseFormat {
    #[serde(rename = "type")]
    type_field: String,
    json_schema: JsonSchemaFormat,
}

#[derive(Debug, Serialize)]
pub struct JsonSchemaFormat {
    name: String,
    strict: bool,
    schema: Value,
}

impl ResponseFormat {
    fn commit_suggestions(suggestion_count: usize) -> Self {
        let count = suggestion_count.max(1) as u64;
        Self {
            type_field: "json_schema".to_string(),
            json_schema: JsonSchemaFormat {
                name: "commit_suggestions".to_string(),
                strict: true,
                schema: json!({
                    "type": "object",
                    "additionalProperties": false,
                    "properties": {
                        "suggestions": {
                            "type": "array",
                            "minItems": count,
                            "maxItems": count,
                            "items": {
                                "type": "object",
                                "additionalProperties": false,
                                "properties": {
                                    "title": {
                                        "type": "string",
                                        "description": "Conventional commit title (<type>(scope?): description)",
                                        "minLength": 1
                                    },
                                    "body": {
                                        "type": ["string", "null"],
                                        "description": "Optional conventional commit body paragraph focusing on motivation (use null when not needed)"
                                    }
                                },
                                "required": ["title", "body"]
                            }
                        }
                    },
                    "required": ["suggestions"]
                }),
            },
        }
    }
}

impl Request {
    pub fn new(model: String, messages: Vec<Message>, suggestion_count: usize) -> Self {
        let normalized = suggestion_count.max(1);
        Self {
            model,
            messages,
            suggestion_count: normalized,
            reasoning_effort: None,
            verbosity: None,
            response_format: Some(ResponseFormat::commit_suggestions(normalized)),
        }
    }

    pub fn with_reasoning_effort(mut self, effort: Option<String>) -> Self {
        self.reasoning_effort = effort;
        self
    }

    pub fn with_verbosity(mut self, verbosity: Option<String>) -> Self {
        self.verbosity = verbosity;
        self
    }

    pub fn suggestion_count(&self) -> usize {
        self.suggestion_count
    }

    pub async fn execute(
        &self,
        api_key: String,
        prompt_tokens: usize,
        api_endpoint: String,
        debug: bool,
        debug_logger: &mut DebugLogger,
    ) -> anyhow::Result<CompletionResult> {
        let client = reqwest::Client::new();
        let mut spinner_handle = spinner::Spinner::start("Asking AI...".to_string());
        let request_start = Instant::now();
        let response = match client
            .post(&api_endpoint)
            .header("Content-Type", "application/json")
            .bearer_auth(&api_key)
            .json(self)
            .send()
            .await
        {
            Ok(resp) => resp,
            Err(err) => {
                if let Some(spinner) = spinner_handle.take() {
                    spinner.stop().await;
                }
                return Err(err.into());
            }
        };

        let status = response.status();
        let body = match response.text().await {
            Ok(body) => body,
            Err(err) => {
                if let Some(spinner) = spinner_handle.take() {
                    spinner.stop().await;
                }
                return Err(err.into());
            }
        };

        if let Some(spinner) = spinner_handle.take() {
            spinner.stop().await;
        }

        let duration = request_start.elapsed();

        if !status.is_success() {
            let error_details = match serde_json::from_str::<ErrorRoot>(&body) {
                Ok(error_root) => format!(
                    "OpenAI Error:\n  Type: {}\n  Message: {}\n  Code: {:?}\n  Parameter: {:?}\n\nFull Response:\n{}",
                    error_root.error.type_field,
                    error_root.error.message,
                    error_root.error.code,
                    error_root.error.param,
                    body
                ),
                Err(_) => format!("Raw Response:\n{}", body),
            };

            let error_msg = format!(
                "API request failed (HTTP {}):\nEndpoint: {}\n\n{}",
                status, api_endpoint, error_details
            );
            debug_logger.log_error(&error_msg);
            println!("{}", "API Error:".red().bold());
            println!("{}", error_msg);
            process::exit(1);
        }

        debug_logger.log_response(&body);

        let completion: ChatCompletionResponse = serde_json::from_str(&body).map_err(|err| {
            let msg = format!("Failed to parse API response as chat completion JSON: {err}");
            debug_logger.log_error(&format!("{msg}\nRaw body: {body}"));
            anyhow::anyhow!(msg)
        })?;

        let choice = completion
            .choices
            .into_iter()
            .next()
            .ok_or_else(|| anyhow::anyhow!("API response did not include any choices"))?;

        let structured_payload = choice
            .message
            .into_text()
            .ok_or_else(|| anyhow::anyhow!("Assistant response did not include textual content"))?;

        let envelope: CommitSuggestionsEnvelope = serde_json::from_str(&structured_payload)
            .map_err(|err| {
                let msg = format!("Failed to parse structured suggestions: {err}");
                debug_logger.log_error(&format!("{msg}\nPayload: {structured_payload}"));
                anyhow::anyhow!(msg)
            })?;

        if envelope.suggestions.is_empty() {
            return Err(anyhow::anyhow!(
                "Model returned zero commit suggestions; expected at least one"
            ));
        }

        if envelope.suggestions.len() != self.suggestion_count {
            println!(
                "{} {} -> {}",
                "Warning:".yellow(),
                "Model returned a different number of suggestions than requested".bright_black(),
                envelope.suggestions.len()
            );
        }

        if debug {
            println!("\n{}", "=== API Response ===".blue().bold());
            println!("  Model: {}", self.model.purple());
            println!("  Input tokens: {}", prompt_tokens.to_string().purple());
            if let Some(usage) = &completion.usage {
                println!(
                    "  Output tokens: {} (total: {})",
                    usage.completion_tokens.to_string().purple(),
                    usage.total_tokens.to_string().purple()
                );
            }
            println!(
                "  Suggestions returned: {}",
                envelope.suggestions.len().to_string().purple()
            );
            println!(
                "  Duration: {}",
                format!("{:.1}s", duration.as_secs_f32()).purple()
            );
        }

        Ok(CompletionResult {
            suggestions: envelope.suggestions,
            usage: completion.usage,
            duration,
        })
    }
}

#[derive(Debug, Serialize, Deserialize)]
pub struct CompletionResult {
    pub suggestions: Vec<CommitSuggestion>,
    pub usage: Option<Usage>,
    pub duration: Duration,
}

#[derive(Debug, Deserialize)]
struct ChatCompletionResponse {
    pub id: String,
    pub object: String,
    pub created: i64,
    pub model: String,
    pub choices: Vec<ChatCompletionChoice>,
    pub usage: Option<Usage>,
}

#[derive(Debug, Deserialize)]
struct ChatCompletionChoice {
    pub index: usize,
    pub message: ChoiceMessage,
}

#[derive(Debug, Deserialize)]
struct ChoiceMessage {
    pub role: Role,
    pub content: MessageContent,
}

impl ChoiceMessage {
    fn into_text(self) -> Option<String> {
        match self.content {
            MessageContent::Text(s) => Some(s),
            MessageContent::Array(parts) => {
                let mut text = String::new();
                for part in parts {
                    if part.kind == "output_text" || part.kind == "text" {
                        if let Some(content) = part.text {
                            text.push_str(&content);
                        }
                    }
                }
                if text.is_empty() {
                    None
                } else {
                    Some(text)
                }
            }
        }
    }
}

#[derive(Debug, Deserialize)]
#[serde(untagged)]
enum MessageContent {
    Text(String),
    Array(Vec<ContentPart>),
}

#[derive(Debug, Deserialize)]
struct ContentPart {
    #[serde(rename = "type")]
    kind: String,
    text: Option<String>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct Usage {
    pub prompt_tokens: usize,
    pub completion_tokens: usize,
    pub total_tokens: usize,
    #[serde(default)]
    pub completion_tokens_details: CompletionTokensDetails,
}

#[derive(Serialize, Deserialize, Debug, Default)]
pub struct CompletionTokensDetails {
    pub reasoning_tokens: usize,
    pub accepted_prediction_tokens: usize,
    pub rejected_prediction_tokens: usize,
}

pub fn count_token(s: &str) -> anyhow::Result<usize> {
    let bpe = tiktoken_rs::cl100k_base()?;
    let tokens = bpe.encode_with_special_tokens(s);
    Ok(tokens.len())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_verbosity_with_request() {
        let request = Request::new(
            "gpt-5.4".to_string(),
            vec![Message::user("test".to_string())],
            1,
        )
        .with_verbosity(Some("high".to_string()));

        assert_eq!(request.verbosity, Some("high".to_string()));
    }

    #[test]
    fn test_reasoning_effort_none() {
        let request = Request::new(
            "gpt-5.4".to_string(),
            vec![Message::user("test".to_string())],
            1,
        )
        .with_reasoning_effort(Some("none".to_string()));

        assert_eq!(request.reasoning_effort, Some("none".to_string()));
    }

    #[test]
    fn test_verbosity_serialization_skipped_when_none() {
        let request = Request::new(
            "gpt-5.4".to_string(),
            vec![Message::user("test".to_string())],
            1,
        );

        let json = serde_json::to_string(&request).expect("Failed to serialize");
        assert!(
            !json.contains("\"verbosity\""),
            "Serialized JSON should not contain 'verbosity' field when it's None"
        );
    }

    #[test]
    fn test_verbosity_serialization_included_when_some() {
        let request = Request::new(
            "gpt-5.4".to_string(),
            vec![Message::user("test".to_string())],
            1,
        )
        .with_verbosity(Some("high".to_string()));

        let json = serde_json::to_string(&request).expect("Failed to serialize");
        assert!(
            json.contains("\"verbosity\""),
            "Serialized JSON should contain 'verbosity' field when it's Some"
        );
        assert!(
            json.contains("\"high\""),
            "Serialized JSON should contain the verbosity value"
        );
    }

    #[test]
    fn commit_suggestion_to_message_body_optional() {
        let suggestion = CommitSuggestion {
            title: "feat: example".to_string(),
            body: Some("Explain why".to_string()),
        };
        assert_eq!(
            suggestion.as_commit_message(),
            "feat: example\n\nExplain why".to_string()
        );

        let suggestion_no_body = CommitSuggestion {
            title: "fix: bug".to_string(),
            body: None,
        };
        assert_eq!(suggestion_no_body.as_commit_message(), "fix: bug");
    }
}