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]
47pub fn prepend_protocol_instructions(
48 prompt: &str,
49 profile: ProtocolRequestProfile,
50 schema_instruction_mode: ProtocolSchemaInstructionMode,
51 workspace_root: &Path,
52) -> String {
53 let protocol_usage_instructions = render_protocol_usage_instructions(profile);
54 let workspace_policy = workspace_instructions(workspace_root);
55 if !schema_instruction_mode.includes_response_json_schema() {
56 let template = ProtocolInstructionPolicyPromptTemplate {
57 prompt,
58 protocol_usage_instructions: &protocol_usage_instructions,
59 workspace_policy: &workspace_policy,
60 };
61
62 return render_template("protocol_instruction_policy_prompt.md", &template);
63 }
64
65 let response_json_schema = protocol_json_schema_json(profile);
66 let template = ProtocolInstructionPromptTemplate {
67 prompt,
68 protocol_usage_instructions: &protocol_usage_instructions,
69 response_json_schema: &response_json_schema,
70 workspace_policy: &workspace_policy,
71 };
72
73 render_template("protocol_instruction_prompt.md", &template)
74}
75
76#[must_use]
79pub fn workspace_instructions(workspace_root: &Path) -> String {
80 render_template(
81 "workspace_policy_prompt.md",
82 &WorkspacePolicyPromptTemplate {
83 workspace_root: &workspace_root_json(workspace_root),
84 },
85 )
86}
87
88#[derive(Template)]
90#[template(path = "workspace_policy_prompt.md", escape = "none")]
91struct WorkspacePolicyPromptTemplate<'a> {
92 workspace_root: &'a str,
93}
94
95#[must_use]
102pub fn prepend_protocol_refresh_reminder(
103 prompt: &str,
104 profile: ProtocolRequestProfile,
105 workspace_root: &Path,
106) -> String {
107 let protocol_refresh_instructions = render_protocol_refresh_instructions(profile);
108 let workspace_root = workspace_root_json(workspace_root);
109 let template = ProtocolRefreshPromptTemplate {
110 prompt,
111 protocol_refresh_instructions: &protocol_refresh_instructions,
112 workspace_root: &workspace_root,
113 };
114
115 render_template("protocol_refresh_prompt.md", &template)
116}
117
118pub fn build_protocol_repair_prompt(
130 parse_error: &str,
131 malformed_response: &str,
132) -> Result<String, String> {
133 if malformed_response.len() > REPAIR_PAYLOAD_MAX_BYTES {
134 return Err(format!(
135 "Protocol repair skipped: response exceeds the {REPAIR_PAYLOAD_MAX_BYTES}-byte \
136 lossless repair limit ({} bytes)",
137 malformed_response.len()
138 ));
139 }
140
141 let malformed_response = serde_json::json!(malformed_response).to_string();
142 if malformed_response.len() > REPAIR_PAYLOAD_MAX_BYTES {
143 return Err(format!(
144 "Protocol repair skipped: JSON-encoded response exceeds the \
145 {REPAIR_PAYLOAD_MAX_BYTES}-byte lossless repair limit ({} bytes)",
146 malformed_response.len()
147 ));
148 }
149
150 let parse_error = encode_repair_parse_error(parse_error);
151 let payload_bytes = malformed_response.len() + parse_error.len();
152 if payload_bytes > REPAIR_PAYLOAD_MAX_BYTES {
153 return Err(format!(
154 "Protocol repair skipped: combined JSON-encoded response and diagnostic exceed the \
155 {REPAIR_PAYLOAD_MAX_BYTES}-byte lossless repair limit ({payload_bytes} bytes)"
156 ));
157 }
158
159 let template = ProtocolRepairPromptTemplate {
160 malformed_response: &malformed_response,
161 parse_error: &parse_error,
162 };
163
164 Ok(render_template("protocol_repair_prompt.md", &template))
165}
166
167fn encode_repair_parse_error(parse_error: &str) -> String {
169 const NOTICE: &str = " [diagnostic truncated]";
170
171 let end = parse_error.floor_char_boundary(parse_error.len().min(REPAIR_PARSE_ERROR_MAX_BYTES));
172 let encoded = serde_json::json!(&parse_error[..end]).to_string();
173 if end == parse_error.len() && encoded.len() <= REPAIR_PARSE_ERROR_MAX_BYTES {
174 return encoded;
175 }
176
177 let prefix_bytes = (REPAIR_PARSE_ERROR_MAX_BYTES - NOTICE.len() - 2) / 6;
180 let end = parse_error.floor_char_boundary(parse_error.len().min(prefix_bytes));
181
182 serde_json::json!(format!("{}{NOTICE}", &parse_error[..end])).to_string()
183}
184
185fn workspace_root_json(workspace_root: &Path) -> String {
188 serde_json::json!(workspace_root.to_string_lossy())
189 .to_string()
190 .replace('`', "\\u0060")
191}
192
193#[derive(Template)]
196#[template(path = "protocol_instruction_policy_prompt.md", escape = "none")]
197struct ProtocolInstructionPolicyPromptTemplate<'a> {
198 prompt: &'a str,
199 protocol_usage_instructions: &'a str,
200 workspace_policy: &'a str,
201}
202
203#[derive(Template)]
205#[template(path = "protocol_instruction_prompt.md", escape = "none")]
206struct ProtocolInstructionPromptTemplate<'a> {
207 prompt: &'a str,
208 protocol_usage_instructions: &'a str,
209 response_json_schema: &'a str,
210 workspace_policy: &'a str,
211}
212
213#[derive(Template)]
215#[template(path = "protocol_refresh_prompt.md", escape = "none")]
216struct ProtocolRefreshPromptTemplate<'a> {
217 prompt: &'a str,
218 protocol_refresh_instructions: &'a str,
219 workspace_root: &'a str,
220}
221
222#[derive(Template)]
224#[template(path = "protocol_repair_prompt.md", escape = "none")]
225struct ProtocolRepairPromptTemplate<'a> {
226 malformed_response: &'a str,
227 parse_error: &'a str,
228}
229
230#[derive(Template)]
232#[template(path = "protocol_instruction_session_turn_usage.md", escape = "none")]
233struct ProtocolInstructionSessionTurnUsageTemplate;
234
235#[derive(Template)]
237#[template(path = "protocol_instruction_utility_prompt_usage.md", escape = "none")]
238struct ProtocolInstructionUtilityPromptUsageTemplate;
239
240#[derive(Template)]
242#[template(path = "protocol_instruction_focused_review_usage.md", escape = "none")]
243struct ProtocolInstructionFocusedReviewUsageTemplate;
244
245#[derive(Template)]
247#[template(path = "protocol_refresh_session_turn_instruction.md", escape = "none")]
248struct ProtocolRefreshSessionTurnInstructionTemplate;
249
250#[derive(Template)]
252#[template(
253 path = "protocol_refresh_utility_prompt_instruction.md",
254 escape = "none"
255)]
256struct ProtocolRefreshUtilityPromptInstructionTemplate;
257
258fn render_protocol_usage_instructions(profile: ProtocolRequestProfile) -> String {
260 if matches!(profile, ProtocolRequestProfile::ReviewMetadata) {
261 return "Return the direct review metadata object with title, description, and \
262 is_title_change_significant. Do not nest it inside answer."
263 .to_string();
264 }
265
266 if matches!(profile, ProtocolRequestProfile::FocusedReview) {
267 return render_template(
268 "protocol_instruction_focused_review_usage.md",
269 &ProtocolInstructionFocusedReviewUsageTemplate,
270 );
271 }
272
273 if matches!(profile, ProtocolRequestProfile::SessionTurn) {
274 return render_template(
275 "protocol_instruction_session_turn_usage.md",
276 &ProtocolInstructionSessionTurnUsageTemplate,
277 );
278 }
279
280 render_template(
281 "protocol_instruction_utility_prompt_usage.md",
282 &ProtocolInstructionUtilityPromptUsageTemplate,
283 )
284}
285
286fn render_protocol_refresh_instructions(profile: ProtocolRequestProfile) -> String {
288 if matches!(profile, ProtocolRequestProfile::ReviewMetadata) {
289 return "Return the direct review metadata object with title, description, and \
290 is_title_change_significant. Do not nest it inside answer."
291 .to_string();
292 }
293
294 if matches!(profile, ProtocolRequestProfile::FocusedReview) {
295 return render_template(
296 "protocol_instruction_focused_review_usage.md",
297 &ProtocolInstructionFocusedReviewUsageTemplate,
298 );
299 }
300
301 if matches!(profile, ProtocolRequestProfile::SessionTurn) {
302 return render_template(
303 "protocol_refresh_session_turn_instruction.md",
304 &ProtocolRefreshSessionTurnInstructionTemplate,
305 );
306 }
307
308 render_template(
309 "protocol_refresh_utility_prompt_instruction.md",
310 &ProtocolRefreshUtilityPromptInstructionTemplate,
311 )
312}
313
314fn render_template(template_name: &str, template: &impl Template) -> String {
316 let rendered = match template.render() {
317 Ok(rendered) => rendered,
318 Err(error) => format!("Failed to render `{template_name}`: {error}"),
319 };
320
321 rendered.trim_end().to_string()
322}
323
324#[cfg(test)]
325#[path = "envelope_test.rs"]
326mod tests;