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_instruction_graph_proposal_usage.md", escape = "none")]
248struct ProtocolInstructionGraphProposalUsageTemplate;
249
250#[derive(Template)]
252#[template(path = "protocol_refresh_session_turn_instruction.md", escape = "none")]
253struct ProtocolRefreshSessionTurnInstructionTemplate;
254
255#[derive(Template)]
257#[template(
258 path = "protocol_refresh_utility_prompt_instruction.md",
259 escape = "none"
260)]
261struct ProtocolRefreshUtilityPromptInstructionTemplate;
262
263fn render_protocol_usage_instructions(profile: ProtocolRequestProfile) -> String {
265 if matches!(profile, ProtocolRequestProfile::GraphProposal) {
266 return render_template(
267 "protocol_instruction_graph_proposal_usage.md",
268 &ProtocolInstructionGraphProposalUsageTemplate,
269 );
270 }
271 if matches!(profile, ProtocolRequestProfile::ReviewMetadata) {
272 return "Return the direct review metadata object with title, description, and \
273 is_title_change_significant. Do not nest it inside answer."
274 .to_string();
275 }
276
277 if matches!(profile, ProtocolRequestProfile::FocusedReview) {
278 return render_template(
279 "protocol_instruction_focused_review_usage.md",
280 &ProtocolInstructionFocusedReviewUsageTemplate,
281 );
282 }
283
284 if matches!(profile, ProtocolRequestProfile::SessionTurn) {
285 return render_template(
286 "protocol_instruction_session_turn_usage.md",
287 &ProtocolInstructionSessionTurnUsageTemplate,
288 );
289 }
290
291 render_template(
292 "protocol_instruction_utility_prompt_usage.md",
293 &ProtocolInstructionUtilityPromptUsageTemplate,
294 )
295}
296
297fn render_protocol_refresh_instructions(profile: ProtocolRequestProfile) -> String {
299 if matches!(profile, ProtocolRequestProfile::GraphProposal) {
300 return render_template(
301 "protocol_instruction_graph_proposal_usage.md",
302 &ProtocolInstructionGraphProposalUsageTemplate,
303 );
304 }
305 if matches!(profile, ProtocolRequestProfile::ReviewMetadata) {
306 return "Return the direct review metadata object with title, description, and \
307 is_title_change_significant. Do not nest it inside answer."
308 .to_string();
309 }
310
311 if matches!(profile, ProtocolRequestProfile::FocusedReview) {
312 return render_template(
313 "protocol_instruction_focused_review_usage.md",
314 &ProtocolInstructionFocusedReviewUsageTemplate,
315 );
316 }
317
318 if matches!(profile, ProtocolRequestProfile::SessionTurn) {
319 return render_template(
320 "protocol_refresh_session_turn_instruction.md",
321 &ProtocolRefreshSessionTurnInstructionTemplate,
322 );
323 }
324
325 render_template(
326 "protocol_refresh_utility_prompt_instruction.md",
327 &ProtocolRefreshUtilityPromptInstructionTemplate,
328 )
329}
330
331fn render_template(template_name: &str, template: &impl Template) -> String {
333 let rendered = match template.render() {
334 Ok(rendered) => rendered,
335 Err(error) => format!("Failed to render `{template_name}`: {error}"),
336 };
337
338 rendered.trim_end().to_string()
339}
340
341#[cfg(test)]
342#[path = "envelope_test.rs"]
343mod tests;