Skip to main content

compaction/
bug_summary.rs

1//! The model-written bug report summary (`generateBugReportSummary` of core/bug-report.ts): the newest messages
2//! that fit 60% of the context window, the user's description, and the report instructions, sent with the bug
3//! report system prompt; the answer must be plain report text.
4
5use ai::transcript::normalize_context;
6use ai::{
7    AssistantMessage, Context, Message, Model, StopReason, TextContent, UserContent, UserMessage, UserMessageContent,
8};
9use serde_json::Value;
10
11use crate::{SummaryRequest, convert_to_llm, estimate_tokens, has_tool_call, response_text, serialize_conversation};
12
13const BUG_SUMMARY_SYSTEM_PROMPT: &str = "You are helping a user file a bug report about pi, the coding agent they are talking to. You will be shown the conversation transcript. Write a report for the pi developers describing what the user was doing and what went wrong.
14
15Do NOT continue the conversation. Do NOT respond to any questions in the conversation. ONLY output the report.";
16
17const BUG_SUMMARY_INSTRUCTIONS: &str = "Write the bug report in Markdown with these sections:
18
19## What the user was doing
20One short paragraph.
21
22## What went wrong
23Concrete description of the failure: wrong output, errors, hangs, tool failures, unexpected behavior. Quote error messages and tool output verbatim where they exist.
24
25## Steps to reproduce
26Numbered list, as specific as the transcript allows.
27
28## Relevant details
29Tool calls involved, files touched, model behavior, anything else that helps a developer reproduce or locate the problem.
30
31Do not include file contents, secrets, or credentials from the transcript; refer to files by path only. Keep the report factual and concise.";
32
33/// `selectMessages`: the newest messages whose estimates fit `budget` (always at least the newest one).
34fn select_messages(messages: &[Value], budget: u64) -> &[Value] {
35    let mut tokens = 0u64;
36    let mut start = messages.len();
37    for (index, message) in messages.iter().enumerate().rev() {
38        let next = estimate_tokens(message);
39        if start < messages.len() && tokens + next > budget {
40            break;
41        }
42        start = index;
43        tokens += next;
44    }
45    &messages[start..]
46}
47
48/// The summary request for the session's `messages`, with the user's `hint`.
49pub fn bug_summary_request(
50    messages: &[Value],
51    hint: Option<&str>,
52    model: &Model,
53    thinking_level: Option<&str>,
54    session_id: Option<&str>,
55    now_ms: i64,
56) -> SummaryRequest {
57    let window = if model.context_window > 0 {
58        model.context_window
59    } else {
60        128_000
61    };
62    let selected = select_messages(messages, (window as f64 * 0.6).floor() as u64);
63    let hint = hint.map(jsrt::string::trim).filter(|h| !h.is_empty());
64    let mut parts = Vec::new();
65    if selected.len() < messages.len() {
66        parts.push(format!(
67            "Note: only the last {} of {} messages are shown.",
68            selected.len(),
69            messages.len()
70        ));
71    }
72    parts.push(format!(
73        "<conversation>\n{}\n</conversation>",
74        serialize_conversation(&convert_to_llm(selected))
75    ));
76    if let Some(hint) = hint {
77        parts.push(format!("<user-report>\n{hint}\n</user-report>"));
78    }
79    parts.push(BUG_SUMMARY_INSTRUCTIONS.to_string());
80    let context = normalize_context(&Context {
81        system_prompt: Some(BUG_SUMMARY_SYSTEM_PROMPT.to_string()),
82        messages: vec![Message::User(UserMessage {
83            content: UserMessageContent::Blocks(vec![UserContent::Text(TextContent {
84                text: parts.join("\n\n"),
85                text_signature: None,
86            })]),
87            timestamp: now_ms,
88        })],
89        tools: None,
90    });
91    let reasoning = thinking_level
92        .filter(|level| model.reasoning && !level.is_empty() && *level != "off")
93        .map(str::to_string);
94    SummaryRequest {
95        context,
96        max_tokens: if model.max_tokens > 0 {
97            model.max_tokens.min(4096)
98        } else {
99            4096
100        },
101        reasoning,
102        session_id: session_id.map(str::to_string),
103    }
104}
105
106/// The report text of a summary response, or why there is none.
107pub fn bug_summary_text(response: &AssistantMessage) -> Result<String, String> {
108    if response.stop_reason == StopReason::Aborted {
109        return Err("Bug report summary was cancelled".into());
110    }
111    if let Some(failure) = crate::summarization_failure(response, "Bug report summary") {
112        return Err(failure);
113    }
114    if has_tool_call(response) {
115        return Err("Bug report summary attempted to call a tool".into());
116    }
117    let text = jsrt::string::trim(&response_text(response)).to_string();
118    if text.is_empty() {
119        return Err("Bug report summary was empty".into());
120    }
121    Ok(text)
122}