1use std::path::Path;
4
5use askama::Template;
6
7use super::model::ProtocolRequestProfile;
8use super::schema::protocol_json_schema_json;
9
10const REPAIR_PAYLOAD_MAX_BYTES: usize = 128 * 1024;
12const REPAIR_PARSE_ERROR_MAX_BYTES: usize = 4 * 1024;
14
15#[derive(Debug, Clone, Copy, PartialEq, Eq)]
18pub enum ProtocolSchemaInstructionMode {
19 PromptSchema,
22 TransportSchema,
25}
26
27impl ProtocolSchemaInstructionMode {
28 fn includes_response_json_schema(self) -> bool {
31 matches!(self, Self::PromptSchema)
32 }
33}
34
35#[must_use]
46pub fn prepend_protocol_instructions(
47 prompt: &str,
48 profile: ProtocolRequestProfile,
49 schema_instruction_mode: ProtocolSchemaInstructionMode,
50 workspace_root: &Path,
51) -> String {
52 let protocol_usage_instructions = render_protocol_usage_instructions(profile);
53 let workspace_root = workspace_root.display().to_string();
54 if !schema_instruction_mode.includes_response_json_schema() {
55 let template = ProtocolInstructionPolicyPromptTemplate {
56 prompt,
57 protocol_usage_instructions: &protocol_usage_instructions,
58 workspace_root: &workspace_root,
59 };
60
61 return render_template("protocol_instruction_policy_prompt.md", &template);
62 }
63
64 let response_json_schema = protocol_json_schema_json(profile);
65 let template = ProtocolInstructionPromptTemplate {
66 prompt,
67 protocol_usage_instructions: &protocol_usage_instructions,
68 response_json_schema: &response_json_schema,
69 workspace_root: &workspace_root,
70 };
71
72 render_template("protocol_instruction_prompt.md", &template)
73}
74
75#[must_use]
82pub fn prepend_protocol_refresh_reminder(
83 prompt: &str,
84 profile: ProtocolRequestProfile,
85 workspace_root: &Path,
86) -> String {
87 let protocol_refresh_instructions = render_protocol_refresh_instructions(profile);
88 let workspace_root = workspace_root.display().to_string();
89 let template = ProtocolRefreshPromptTemplate {
90 prompt,
91 protocol_refresh_instructions: &protocol_refresh_instructions,
92 workspace_root: &workspace_root,
93 };
94
95 render_template("protocol_refresh_prompt.md", &template)
96}
97
98pub fn build_protocol_repair_prompt(
110 parse_error: &str,
111 malformed_response: &str,
112) -> Result<String, String> {
113 if malformed_response.len() > REPAIR_PAYLOAD_MAX_BYTES {
114 return Err(format!(
115 "Protocol repair skipped: response exceeds the {REPAIR_PAYLOAD_MAX_BYTES}-byte \
116 lossless repair limit ({} bytes)",
117 malformed_response.len()
118 ));
119 }
120
121 let malformed_response = serde_json::json!(malformed_response).to_string();
122 if malformed_response.len() > REPAIR_PAYLOAD_MAX_BYTES {
123 return Err(format!(
124 "Protocol repair skipped: JSON-encoded response exceeds the \
125 {REPAIR_PAYLOAD_MAX_BYTES}-byte lossless repair limit ({} bytes)",
126 malformed_response.len()
127 ));
128 }
129
130 let parse_error = encode_repair_parse_error(parse_error);
131 let payload_bytes = malformed_response.len() + parse_error.len();
132 if payload_bytes > REPAIR_PAYLOAD_MAX_BYTES {
133 return Err(format!(
134 "Protocol repair skipped: combined JSON-encoded response and diagnostic exceed the \
135 {REPAIR_PAYLOAD_MAX_BYTES}-byte lossless repair limit ({payload_bytes} bytes)"
136 ));
137 }
138
139 let template = ProtocolRepairPromptTemplate {
140 malformed_response: &malformed_response,
141 parse_error: &parse_error,
142 };
143
144 Ok(render_template("protocol_repair_prompt.md", &template))
145}
146
147fn encode_repair_parse_error(parse_error: &str) -> String {
149 const NOTICE: &str = " [diagnostic truncated]";
150
151 let end = parse_error.floor_char_boundary(parse_error.len().min(REPAIR_PARSE_ERROR_MAX_BYTES));
152 let encoded = serde_json::json!(&parse_error[..end]).to_string();
153 if end == parse_error.len() && encoded.len() <= REPAIR_PARSE_ERROR_MAX_BYTES {
154 return encoded;
155 }
156
157 let prefix_bytes = (REPAIR_PARSE_ERROR_MAX_BYTES - NOTICE.len() - 2) / 6;
160 let end = parse_error.floor_char_boundary(parse_error.len().min(prefix_bytes));
161
162 serde_json::json!(format!("{}{NOTICE}", &parse_error[..end])).to_string()
163}
164
165#[derive(Template)]
168#[template(path = "protocol_instruction_policy_prompt.md", escape = "none")]
169struct ProtocolInstructionPolicyPromptTemplate<'a> {
170 prompt: &'a str,
171 protocol_usage_instructions: &'a str,
172 workspace_root: &'a str,
173}
174
175#[derive(Template)]
177#[template(path = "protocol_instruction_prompt.md", escape = "none")]
178struct ProtocolInstructionPromptTemplate<'a> {
179 prompt: &'a str,
180 protocol_usage_instructions: &'a str,
181 response_json_schema: &'a str,
182 workspace_root: &'a str,
183}
184
185#[derive(Template)]
187#[template(path = "protocol_refresh_prompt.md", escape = "none")]
188struct ProtocolRefreshPromptTemplate<'a> {
189 prompt: &'a str,
190 protocol_refresh_instructions: &'a str,
191 workspace_root: &'a str,
192}
193
194#[derive(Template)]
196#[template(path = "protocol_repair_prompt.md", escape = "none")]
197struct ProtocolRepairPromptTemplate<'a> {
198 malformed_response: &'a str,
199 parse_error: &'a str,
200}
201
202#[derive(Template)]
204#[template(path = "protocol_instruction_session_turn_usage.md", escape = "none")]
205struct ProtocolInstructionSessionTurnUsageTemplate;
206
207#[derive(Template)]
209#[template(path = "protocol_instruction_utility_prompt_usage.md", escape = "none")]
210struct ProtocolInstructionUtilityPromptUsageTemplate;
211
212#[derive(Template)]
214#[template(path = "protocol_instruction_focused_review_usage.md", escape = "none")]
215struct ProtocolInstructionFocusedReviewUsageTemplate;
216
217#[derive(Template)]
219#[template(path = "protocol_refresh_session_turn_instruction.md", escape = "none")]
220struct ProtocolRefreshSessionTurnInstructionTemplate;
221
222#[derive(Template)]
224#[template(
225 path = "protocol_refresh_utility_prompt_instruction.md",
226 escape = "none"
227)]
228struct ProtocolRefreshUtilityPromptInstructionTemplate;
229
230fn render_protocol_usage_instructions(profile: ProtocolRequestProfile) -> String {
232 if matches!(profile, ProtocolRequestProfile::FocusedReview) {
233 return render_template(
234 "protocol_instruction_focused_review_usage.md",
235 &ProtocolInstructionFocusedReviewUsageTemplate,
236 );
237 }
238
239 if matches!(profile, ProtocolRequestProfile::SessionTurn) {
240 return render_template(
241 "protocol_instruction_session_turn_usage.md",
242 &ProtocolInstructionSessionTurnUsageTemplate,
243 );
244 }
245
246 render_template(
247 "protocol_instruction_utility_prompt_usage.md",
248 &ProtocolInstructionUtilityPromptUsageTemplate,
249 )
250}
251
252fn render_protocol_refresh_instructions(profile: ProtocolRequestProfile) -> String {
254 if matches!(profile, ProtocolRequestProfile::FocusedReview) {
255 return render_template(
256 "protocol_instruction_focused_review_usage.md",
257 &ProtocolInstructionFocusedReviewUsageTemplate,
258 );
259 }
260
261 if matches!(profile, ProtocolRequestProfile::SessionTurn) {
262 return render_template(
263 "protocol_refresh_session_turn_instruction.md",
264 &ProtocolRefreshSessionTurnInstructionTemplate,
265 );
266 }
267
268 render_template(
269 "protocol_refresh_utility_prompt_instruction.md",
270 &ProtocolRefreshUtilityPromptInstructionTemplate,
271 )
272}
273
274fn render_template(template_name: &str, template: &impl Template) -> String {
276 let rendered = match template.render() {
277 Ok(rendered) => rendered,
278 Err(error) => format!("Failed to render `{template_name}`: {error}"),
279 };
280
281 rendered.trim_end().to_string()
282}
283
284#[cfg(test)]
285#[path = "envelope_test.rs"]
286mod tests;