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