turbocommit 2.2.1

A CLI tool to create commit messages with OpenAI GPT models 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
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
#![allow(dead_code)]

use colored::Colorize;
use crossterm::cursor::{MoveToColumn, MoveToPreviousLine};
use crossterm::style::Print;
use crossterm::terminal::{Clear, ClearType};
use crossterm::{execute, terminal};
use futures::StreamExt;
use reqwest_eventsource::{Event, EventSource};
use serde::{Deserialize, Serialize};
use std::{fmt, process};

use crate::animation;
use crate::util::count_lines;

#[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(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)]
#[serde(untagged)]
pub enum Request {
    Standard(StandardRequest),
    Reasoning(ReasoningRequest),
}

#[derive(Debug, Serialize)]
pub struct StandardRequest {
    pub model: String,
    pub messages: Vec<Message>,
    pub n: i32,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub temperature: Option<f64>,
    pub frequency_penalty: f64,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub reasoning_effort: Option<String>,
    stream: bool,
}

#[derive(Debug, Serialize)]
pub struct ReasoningRequest {
    pub model: String,
    pub messages: Vec<Message>,
    pub n: i32,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub reasoning_effort: Option<String>,
    stream: bool,
}

impl Request {
    pub fn new(
        model: String,
        messages: Vec<Message>,
        n: i32,
        temperature: f64,
        frequency_penalty: f64,
    ) -> Self {
        if model.starts_with("o1") || model.starts_with("o3") || model.starts_with("gpt-5") {
            Self::Reasoning(ReasoningRequest {
                model,
                messages,
                n,
                reasoning_effort: None,
                stream: true,
            })
        } else {
            Self::Standard(StandardRequest {
                model,
                messages,
                n,
                temperature: if temperature == 0.0 { None } else { Some(temperature) },
                frequency_penalty,
                reasoning_effort: None,
                stream: true,
            })
        }
    }

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

    fn model(&self) -> &str {
        match self {
            Self::Standard(req) => &req.model,
            Self::Reasoning(req) => &req.model,
        }
    }

    fn n(&self) -> i32 {
        match self {
            Self::Standard(req) => req.n,
            Self::Reasoning(req) => req.n,
        }
    }

    pub async fn execute(
        &self,
        api_key: String,
        no_animations: bool,
        prompt_tokens: usize,
        api_endpoint: String,
        debug: bool,
        debug_logger: &mut crate::debug_log::DebugLogger,
    ) -> anyhow::Result<Vec<String>> {
        let mut choices = vec![String::new(); self.n() as usize];
        let json = serde_json::to_string(self)?;

        // First make a regular request to check if it will be accepted
        let client = reqwest::Client::new();
        let response = client
            .post(&api_endpoint)
            .header("Content-Type", "application/json")
            .bearer_auth(&api_key)
            .body(json.clone())
            .send()
            .await?;

        if !response.status().is_success() {
            let status = response.status();
            let error_body = response.text().await?;
            
            // Try to parse as OpenAI error
            let error_details = match serde_json::from_str::<ErrorRoot>(&error_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,
                    error_body
                ),
                Err(_) => format!("Raw Response:\n{}", error_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);
        }

        let loading_ai_animation = animation::start(
            String::from("Asking AI..."),
            no_animations || debug,
            std::io::stdout(),
        )
        .await;

        let request_builder = client
            .post(api_endpoint.clone())
            .header("Content-Type", "application/json")
            .bearer_auth(api_key)
            .body(json);

        let term_width = terminal::size()?.0 as usize;
        let mut stdout = std::io::stdout();
        let mut es = EventSource::new(request_builder)?;
        let mut lines_to_move_up = 0;
        let mut response_tokens = 0;

        // Only show minimal info in regular debug mode
        if debug && !no_animations {
            println!("\n{}", "Request Info:".blue().bold());
            println!("  Model: {}", self.model().purple());
            println!("  API: {}", api_endpoint.purple());
            println!("  Input tokens: {}", prompt_tokens.to_string().purple());
        }

        while let Some(event) = es.next().await {
            if no_animations || debug {
                match event {
                    Ok(Event::Message(message)) => {
                        if message.data == "[DONE]" {
                            break;
                        }
                        let resp = serde_json::from_str::<Response>(&message.data)
                            .map_or_else(|_| Response::default(), |r| r);
                        response_tokens += 1;
                        for choice in resp.choices {
                            if let Some(content) = choice.delta.content {
                                choices[choice.index as usize].push_str(&content);
                            }
                        }
                    }
                    Err(e) => {
                        // The error string from reqwest_eventsource includes the full response
                        let error_str = e.to_string();
                        let error_details = if let Some(error_json) = error_str.strip_prefix("Error response: ") {
                            // Try to parse as OpenAI error format
                            match serde_json::from_str::<ErrorRoot>(error_json) {
                                Ok(error_root) => format!(
                                    "OpenAI Error:\n  Type: {}\n  Message: {}\n  Code: {:?}\n\nFull Response:\n{}",
                                    error_root.error.type_field,
                                    error_root.error.message,
                                    error_root.error.code,
                                    error_json
                                ),
                                Err(_) => format!("Raw Response:\n{}", error_json)
                            }
                        } else {
                            format!("Error: {}", error_str)
                        };

                        let error_msg = format!(
                            "API request failed:\nEndpoint: {}\n\n{}",
                            api_endpoint, error_details
                        );
                        debug_logger.log_error(&error_msg);
                        println!("{}", "API Error:".red().bold());
                        println!("{}", error_msg);
                        process::exit(1);
                    }
                    _ => {}
                }
            } else {
                if !loading_ai_animation.is_finished() {
                    loading_ai_animation.abort();
                    execute!(
                        std::io::stdout(),
                        Clear(ClearType::CurrentLine),
                        MoveToColumn(0),
                    )?;
                    print!("\n\n")
                }
                match event {
                    Ok(Event::Message(message)) => {
                        if message.data == "[DONE]" {
                            break;
                        }
                        execute!(stdout, MoveToPreviousLine(lines_to_move_up),)?;
                        lines_to_move_up = 0;
                        execute!(stdout, Clear(ClearType::FromCursorDown),)?;
                        let resp = serde_json::from_str::<Response>(&message.data)
                            .map_or_else(|_| Response::default(), |r| r);
                        response_tokens += 1;
                        for choice in resp.choices {
                            if let Some(content) = choice.delta.content {
                                choices[choice.index as usize].push_str(&content);
                            }
                        }
                        for (i, choice) in choices.iter().enumerate() {
                            let outp = format!(
                                "{}{}\n{}\n",
                                if i == 0 {
                                    format!(
                                        "Tokens used: {} input, {} output\n",
                                        crate::util::format_token_count(prompt_tokens).purple(),
                                        crate::util::format_token_count(response_tokens).purple(),
                                    )
                                    .bright_black()
                                } else {
                                    "".bright_black()
                                },
                                format!("[{}]====================", format!("{i}").purple())
                                    .bright_black(),
                                choice,
                            );
                            print!("{outp}");
                            lines_to_move_up += count_lines(&outp, term_width) - 1;
                        }
                    }
                    Err(e) => {
                        println!("{e}");
                        process::exit(1);
                    }
                    _ => {}
                }
            }
        }

        if no_animations || debug {
            println!(
                "Tokens: {} in, {} out (total: {})",
                crate::util::format_token_count(prompt_tokens).purple(),
                crate::util::format_token_count(response_tokens).purple(),
                crate::util::format_token_count(prompt_tokens + response_tokens).purple(),
            );
            for (i, choice) in choices.iter().enumerate() {
                println!(
                    "[{}] {}\n{}\n",
                    format!("{i}").purple(),
                    "=".repeat(77 - i.to_string().len()),
                    choice
                );
            }
        } else {
            // For regular mode (non-debug), show the final messages nicely formatted
            // Only show the messages header if we have multiple choices
            if choices.len() > 1 {
                println!("\n{}", "Generated Commit Messages:".blue().bold());
            }
            // Don't show the messages here if it's a reasoning response (has <think> tag)
            // as it will be handled by process_response
            if !choices[0].contains("<think>") {
                for (i, choice) in choices.iter().enumerate() {
                    println!(
                        "[{}] {}\n{}",
                        format!("{i}").purple(),
                        "=".repeat(77 - i.to_string().len()),
                        choice
                    );
                }
            }
        }

        execute!(
            stdout,
            Print(format!("{}\n", "=======================".bright_black())),
        )?;

        execute!(
            stdout,
            MoveToPreviousLine(lines_to_move_up),
            Clear(ClearType::FromCursorDown),
        )?;

        Ok(choices)
    }
}

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

#[derive(Debug, Serialize, Deserialize, Default)]
pub struct Choice {
    pub index: i64,
    pub finish_reason: Option<String>,
    pub delta: Delta,
}

#[derive(Debug, Serialize, Deserialize, Default)]
pub struct Delta {
    pub role: Option<Role>,
    pub content: 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_temperature_disabled_when_zero() {
        let request = Request::new(
            "gpt-4".to_string(),
            vec![Message::user("test".to_string())],
            1,
            0.0,
            0.0,
        );

        match request {
            Request::Standard(req) => {
                assert_eq!(req.temperature, None, "Temperature should be None when set to 0.0");
            }
            _ => panic!("Expected StandardRequest"),
        }
    }

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

        match request {
            Request::Standard(req) => {
                assert_eq!(req.temperature, Some(1.0), "Temperature should be Some(1.0) when set to 1.0");
            }
            _ => panic!("Expected StandardRequest"),
        }
    }

    #[test]
    fn test_o_series_models_use_reasoning_request() {
        let request = Request::new(
            "o1".to_string(),
            vec![Message::user("test".to_string())],
            1,
            1.0,
            0.0,
        );

        match request {
            Request::Reasoning(_) => {
                // Success - o1 should use Reasoning request
            }
            _ => panic!("Expected ReasoningRequest for o1 model"),
        }
    }

    #[test]
    fn test_gpt5_models_use_reasoning_request() {
        // Test all GPT-5 variants use Reasoning request (no temperature support)
        let models = vec!["gpt-5", "gpt-5-nano", "gpt-5-mini", "gpt-5-codex"];
        
        for model_name in models {
            let request = Request::new(
                model_name.to_string(),
                vec![Message::user("test".to_string())],
                1,
                1.0,
                0.0,
            );

            match request {
                Request::Reasoning(_) => {
                    // Success - GPT-5 models should use Reasoning request
                }
                _ => panic!("Expected ReasoningRequest for {} model", model_name),
            }
        }
    }

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

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

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

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