Skip to main content

ag_protocol/
envelope.rs

1//! Protocol-owned prompt envelopes for agent-facing instruction text.
2
3use std::path::Path;
4
5use askama::Template;
6
7use super::model::ProtocolRequestProfile;
8use super::schema::agent_response_json_schema_json;
9
10const PROTOCOL_INSTRUCTIONS_MARKER: &str = "Structured response protocol:";
11const PROTOCOL_REFRESH_REMINDER_MARKER: &str = "Protocol refresh reminder:";
12const REPAIR_RESPONSE_PREVIEW_MAX_CHARS: usize = 500;
13
14/// Controls whether bootstrap prompt instructions include the full protocol
15/// JSON Schema text.
16#[derive(Debug, Clone, Copy, PartialEq, Eq)]
17pub enum ProtocolSchemaInstructionMode {
18    /// Include the full self-descriptive JSON Schema in the prompt because
19    /// the provider does not enforce Agentty's response schema natively.
20    PromptSchema,
21    /// Omit the full schema text because the provider enforces the same
22    /// response schema through its transport-level structured output API.
23    TransportSchema,
24}
25
26impl ProtocolSchemaInstructionMode {
27    /// Returns whether bootstrap instructions should embed the full JSON
28    /// Schema text in the prompt body.
29    fn includes_response_json_schema(self) -> bool {
30        matches!(self, Self::PromptSchema)
31    }
32}
33
34/// Prepends structured response protocol instructions to a prompt.
35///
36/// Tells agents to emit one top-level JSON object that matches Agentty's
37/// structured protocol while selecting the cheapest safe schema guidance for
38/// the current provider. Providers without native structured output receive
39/// the full JSON Schema in the prompt; providers with native enforcement get
40/// policy and field-routing instructions only. `workspace_root` names the
41/// only writable directory for the turn. If the prompt already contains the
42/// protocol marker, this function returns the prompt unchanged to avoid
43/// duplicated guidance.
44#[must_use]
45pub fn prepend_protocol_instructions(
46    prompt: &str,
47    profile: ProtocolRequestProfile,
48    schema_instruction_mode: ProtocolSchemaInstructionMode,
49    workspace_root: &Path,
50) -> String {
51    if prompt.contains(PROTOCOL_INSTRUCTIONS_MARKER) {
52        return prompt.to_string();
53    }
54
55    let protocol_usage_instructions = render_protocol_usage_instructions(profile);
56    let workspace_root = workspace_root.display().to_string();
57    if !schema_instruction_mode.includes_response_json_schema() {
58        let template = ProtocolInstructionPolicyPromptTemplate {
59            prompt,
60            protocol_usage_instructions: &protocol_usage_instructions,
61            workspace_root: &workspace_root,
62        };
63
64        return render_template("protocol_instruction_policy_prompt.md", &template);
65    }
66
67    let response_json_schema = agent_response_json_schema_json();
68    let template = ProtocolInstructionPromptTemplate {
69        prompt,
70        protocol_usage_instructions: &protocol_usage_instructions,
71        response_json_schema: &response_json_schema,
72        workspace_root: &workspace_root,
73    };
74
75    render_template("protocol_instruction_prompt.md", &template)
76}
77
78/// Prepends a compact refresh reminder for providers that already received
79/// the full instruction contract in the active context.
80///
81/// The reminder repeats the workspace-isolation boundary for
82/// `workspace_root` so long-lived provider contexts keep the rule even after
83/// provider-side context compaction.
84#[must_use]
85pub fn prepend_protocol_refresh_reminder(
86    prompt: &str,
87    profile: ProtocolRequestProfile,
88    workspace_root: &Path,
89) -> String {
90    if prompt.contains(PROTOCOL_INSTRUCTIONS_MARKER)
91        || prompt.contains(PROTOCOL_REFRESH_REMINDER_MARKER)
92    {
93        return prompt.to_string();
94    }
95
96    let protocol_refresh_instructions = render_protocol_refresh_instructions(profile);
97    let workspace_root = workspace_root.display().to_string();
98    let template = ProtocolRefreshPromptTemplate {
99        prompt,
100        protocol_refresh_instructions: &protocol_refresh_instructions,
101        workspace_root: &workspace_root,
102    };
103
104    render_template("protocol_refresh_prompt.md", &template)
105}
106
107/// Builds the protocol repair prompt text for one failed parse attempt.
108///
109/// The returned prompt is self-contained: it includes the full JSON schema
110/// and the `Structured response protocol:` marker so it can be submitted
111/// through the standard prompt pipeline without being double-wrapped.
112#[must_use]
113pub fn build_protocol_repair_prompt(parse_error: &str, malformed_response: &str) -> String {
114    let response_json_schema = agent_response_json_schema_json();
115    let response_preview = truncate_preview(malformed_response, REPAIR_RESPONSE_PREVIEW_MAX_CHARS);
116    let template = ProtocolRepairPromptTemplate {
117        parse_error,
118        response_json_schema: &response_json_schema,
119        response_preview: &response_preview,
120    };
121
122    render_template("protocol_repair_prompt.md", &template)
123}
124
125/// Askama view model for protocol instructions when the transport enforces
126/// the response schema.
127#[derive(Template)]
128#[template(path = "protocol_instruction_policy_prompt.md", escape = "none")]
129struct ProtocolInstructionPolicyPromptTemplate<'a> {
130    prompt: &'a str,
131    protocol_usage_instructions: &'a str,
132    workspace_root: &'a str,
133}
134
135/// Askama view model for full protocol instructions with prompt-side schema.
136#[derive(Template)]
137#[template(path = "protocol_instruction_prompt.md", escape = "none")]
138struct ProtocolInstructionPromptTemplate<'a> {
139    prompt: &'a str,
140    protocol_usage_instructions: &'a str,
141    response_json_schema: &'a str,
142    workspace_root: &'a str,
143}
144
145/// Askama view model for compact refresh reminders.
146#[derive(Template)]
147#[template(path = "protocol_refresh_prompt.md", escape = "none")]
148struct ProtocolRefreshPromptTemplate<'a> {
149    prompt: &'a str,
150    protocol_refresh_instructions: &'a str,
151    workspace_root: &'a str,
152}
153
154/// Askama view model for repair prompts after protocol parse failures.
155#[derive(Template)]
156#[template(path = "protocol_repair_prompt.md", escape = "none")]
157struct ProtocolRepairPromptTemplate<'a> {
158    parse_error: &'a str,
159    response_json_schema: &'a str,
160    response_preview: &'a str,
161}
162
163/// Askama view model for session-turn protocol usage instructions.
164#[derive(Template)]
165#[template(path = "protocol_instruction_session_turn_usage.md", escape = "none")]
166struct ProtocolInstructionSessionTurnUsageTemplate;
167
168/// Askama view model for one-shot protocol usage instructions.
169#[derive(Template)]
170#[template(path = "protocol_instruction_utility_prompt_usage.md", escape = "none")]
171struct ProtocolInstructionUtilityPromptUsageTemplate;
172
173/// Askama view model for session-turn refresh instructions.
174#[derive(Template)]
175#[template(path = "protocol_refresh_session_turn_instruction.md", escape = "none")]
176struct ProtocolRefreshSessionTurnInstructionTemplate;
177
178/// Askama view model for one-shot refresh instructions.
179#[derive(Template)]
180#[template(
181    path = "protocol_refresh_utility_prompt_instruction.md",
182    escape = "none"
183)]
184struct ProtocolRefreshUtilityPromptInstructionTemplate;
185
186/// Renders the protocol usage instructions for one request profile.
187fn render_protocol_usage_instructions(profile: ProtocolRequestProfile) -> String {
188    if matches!(profile, ProtocolRequestProfile::SessionTurn) {
189        return render_template(
190            "protocol_instruction_session_turn_usage.md",
191            &ProtocolInstructionSessionTurnUsageTemplate,
192        );
193    }
194
195    render_template(
196        "protocol_instruction_utility_prompt_usage.md",
197        &ProtocolInstructionUtilityPromptUsageTemplate,
198    )
199}
200
201/// Renders the compact protocol refresh instructions for one request profile.
202fn render_protocol_refresh_instructions(profile: ProtocolRequestProfile) -> String {
203    if matches!(profile, ProtocolRequestProfile::SessionTurn) {
204        return render_template(
205            "protocol_refresh_session_turn_instruction.md",
206            &ProtocolRefreshSessionTurnInstructionTemplate,
207        );
208    }
209
210    render_template(
211        "protocol_refresh_utility_prompt_instruction.md",
212        &ProtocolRefreshUtilityPromptInstructionTemplate,
213    )
214}
215
216/// Renders one Askama template and removes trailing whitespace.
217fn render_template(template_name: &str, template: &impl Template) -> String {
218    let rendered = match template.render() {
219        Ok(rendered) => rendered,
220        Err(error) => format!("Failed to render `{template_name}`: {error}"),
221    };
222
223    rendered.trim_end().to_string()
224}
225
226/// Truncates one malformed response preview to a character-count limit.
227fn truncate_preview(raw: &str, max_chars: usize) -> String {
228    let preview: String = raw.chars().take(max_chars).collect();
229    let total_chars = raw.chars().count();
230
231    if total_chars <= max_chars {
232        return preview;
233    }
234
235    format!("{preview}\n... [{} more chars]", total_chars - max_chars)
236}
237
238#[cfg(test)]
239mod tests {
240    use super::*;
241
242    /// Returns the workspace root used by envelope rendering tests.
243    fn test_workspace_root() -> &'static Path {
244        Path::new("/tmp/agentty-wt/session-1")
245    }
246
247    #[test]
248    /// Ensures session prompts include the critical protocol contract markers.
249    fn test_prepend_protocol_instructions_adds_session_protocol_instructions() {
250        // Arrange
251        let prompt = "Implement feature";
252
253        // Act
254        let rendered_prompt = prepend_protocol_instructions(
255            prompt,
256            ProtocolRequestProfile::SessionTurn,
257            ProtocolSchemaInstructionMode::PromptSchema,
258            test_workspace_root(),
259        );
260
261        // Assert
262        assert!(rendered_prompt.contains("File path output requirements:"));
263        assert!(rendered_prompt.contains("Workspace isolation requirements:"));
264        assert!(rendered_prompt.contains("Your workspace root is `/tmp/agentty-wt/session-1`."));
265        assert!(rendered_prompt.contains("Anything outside that"));
266        assert!(rendered_prompt.contains("root is read-only."));
267        assert!(rendered_prompt.contains("repository-root-relative POSIX paths"));
268        assert!(
269            rendered_prompt.contains("Allowed forms: `path`, `path:line`, `path:line:column`.")
270        );
271        assert!(rendered_prompt.contains("If you run git commands, use read-only commands only"));
272        assert!(rendered_prompt.contains("Do not run mutating git commands"));
273        assert!(rendered_prompt.contains("Quality check requirements:"));
274        assert!(rendered_prompt.contains("repository-defined quality checks"));
275        let normalized_rendered_prompt = rendered_prompt.split_whitespace().collect::<Vec<_>>();
276        let normalized_rendered_prompt = normalized_rendered_prompt.join(" ");
277        assert!(normalized_rendered_prompt.contains("affected dependencies and dependents"));
278        assert!(rendered_prompt.contains("full repository test/check suite"));
279        assert!(rendered_prompt.contains("Remove any temporary scripts or files"));
280        assert!(rendered_prompt.contains("Structured response protocol:"));
281        assert!(rendered_prompt.contains("Return a single JSON object"));
282        assert!(rendered_prompt.contains("Do not wrap the JSON in markdown code fences."));
283        assert!(rendered_prompt.contains("Follow this JSON Schema exactly."));
284        assert!(rendered_prompt.contains("Treat the JSON Schema titles and descriptions"));
285        assert!(rendered_prompt.contains("Authoritative JSON Schema:"));
286        assert!(
287            rendered_prompt
288                .contains("______________________________________________________________________")
289        );
290        assert!(!rendered_prompt.contains("{# task separator #}"));
291        assert!(rendered_prompt.contains("For this session turn"));
292        assert!(rendered_prompt.contains("```mermaid"));
293        assert!(rendered_prompt.contains("put the diagram only in `answer`"));
294        assert!(normalized_rendered_prompt.contains("start the opening fence at column 1"));
295        assert!(rendered_prompt.contains("recognizes Mermaid diagrams only in this fenced"));
296        assert!(rendered_prompt.contains("Do not emit Mermaid as plain text"));
297        assert!(rendered_prompt.contains("Supported mermaid syntax"));
298        assert!(normalized_rendered_prompt.contains("Do not create commits"));
299        assert!(normalized_rendered_prompt.contains("suggest creating commits"));
300        assert!(rendered_prompt.contains("summary"));
301        assert!(rendered_prompt.contains("turn"));
302        assert!(rendered_prompt.contains("session"));
303        assert!(rendered_prompt.contains("\"answer\""));
304        assert!(rendered_prompt.contains("\"questions\""));
305        assert!(rendered_prompt.contains("\"title\""));
306        assert!(rendered_prompt.contains("\"description\""));
307        assert!(rendered_prompt.contains("summary"));
308        assert!(rendered_prompt.ends_with(prompt));
309    }
310
311    #[test]
312    /// Ensures schema-enforcing transports get protocol policy without the
313    /// large prompt-side JSON Schema body.
314    fn test_prepend_protocol_instructions_omits_schema_for_transport_schema_mode() {
315        // Arrange
316        let prompt = "Implement feature";
317
318        // Act
319        let rendered_prompt = prepend_protocol_instructions(
320            prompt,
321            ProtocolRequestProfile::SessionTurn,
322            ProtocolSchemaInstructionMode::TransportSchema,
323            test_workspace_root(),
324        );
325
326        // Assert
327        assert!(rendered_prompt.contains("Structured response protocol:"));
328        assert!(rendered_prompt.contains("Workspace isolation requirements:"));
329        assert!(rendered_prompt.contains("Your workspace root is `/tmp/agentty-wt/session-1`."));
330        assert!(rendered_prompt.contains("Anything outside that"));
331        assert!(rendered_prompt.contains("root is read-only."));
332        assert!(rendered_prompt.contains("provider enforces Agentty's response JSON schema"));
333        assert!(rendered_prompt.contains("Return a single JSON object"));
334        assert!(!rendered_prompt.contains("Follow this JSON Schema exactly."));
335        assert!(!rendered_prompt.contains("Authoritative JSON Schema:"));
336        assert!(rendered_prompt.ends_with(prompt));
337    }
338
339    #[test]
340    /// Ensures protocol instructions are not duplicated when already present.
341    fn test_prepend_protocol_instructions_is_idempotent() {
342        // Arrange
343        let prompt = prepend_protocol_instructions(
344            "Implement feature",
345            ProtocolRequestProfile::SessionTurn,
346            ProtocolSchemaInstructionMode::PromptSchema,
347            test_workspace_root(),
348        );
349
350        // Act
351        let rendered_prompt = prepend_protocol_instructions(
352            &prompt,
353            ProtocolRequestProfile::UtilityPrompt,
354            ProtocolSchemaInstructionMode::TransportSchema,
355            test_workspace_root(),
356        );
357
358        // Assert
359        assert_eq!(rendered_prompt, prompt);
360    }
361
362    #[test]
363    /// Ensures one-shot prompts reuse the shared full-schema protocol
364    /// instructions.
365    fn test_prepend_protocol_instructions_reuses_same_contract_for_one_shot() {
366        // Arrange
367        let prompt = "Generate title";
368
369        // Act
370        let rendered_prompt = prepend_protocol_instructions(
371            prompt,
372            ProtocolRequestProfile::UtilityPrompt,
373            ProtocolSchemaInstructionMode::PromptSchema,
374            test_workspace_root(),
375        );
376
377        // Assert
378        assert!(rendered_prompt.contains("Structured response protocol:"));
379        assert!(
380            rendered_prompt
381                .contains("______________________________________________________________________")
382        );
383        assert!(rendered_prompt.contains("For this one-shot utility prompt"));
384        assert!(!rendered_prompt.contains("mermaid"));
385        assert!(rendered_prompt.contains(
386            r#"{"answer":"...","questions":[],"review_comment_outcomes":[],"summary":null}"#
387        ));
388        assert!(rendered_prompt.contains("\"review_comment_outcomes\""));
389        assert!(rendered_prompt.contains("\"summary\""));
390        assert!(rendered_prompt.ends_with(prompt));
391    }
392
393    #[test]
394    /// Ensures user prompt text is inserted after generated protocol
395    /// placeholders so prompt content cannot trigger recursive expansion.
396    fn test_prepend_protocol_instructions_preserves_prompt_placeholders() {
397        // Arrange
398        let prompt = "Keep these literal: {{ response_json_schema }} {{ \
399                      protocol_usage_instructions }} {{ workspace_root }}";
400
401        // Act
402        let rendered_prompt = prepend_protocol_instructions(
403            prompt,
404            ProtocolRequestProfile::UtilityPrompt,
405            ProtocolSchemaInstructionMode::PromptSchema,
406            test_workspace_root(),
407        );
408
409        // Assert
410        assert!(rendered_prompt.ends_with(prompt));
411    }
412
413    #[test]
414    /// Ensures compact refresh reminders omit the full schema while keeping
415    /// the contract reminder and task body.
416    fn test_prepend_protocol_refresh_reminder_adds_compact_contract_notice() {
417        // Arrange
418        let prompt = "Continue the implementation";
419
420        // Act
421        let rendered_prompt = prepend_protocol_refresh_reminder(
422            prompt,
423            ProtocolRequestProfile::SessionTurn,
424            test_workspace_root(),
425        );
426        let normalized_prompt = rendered_prompt
427            .split_whitespace()
428            .collect::<Vec<_>>()
429            .join(" ");
430
431        // Assert
432        assert!(rendered_prompt.contains("Protocol refresh reminder:"));
433        assert!(rendered_prompt.contains("repository-root-relative POSIX paths"));
434        assert!(rendered_prompt.contains("If you run git commands, use read-only commands only."));
435        assert!(rendered_prompt.contains("Do not run mutating git commands."));
436        assert!(rendered_prompt.contains("inside the workspace root `/tmp/agentty-wt/session-1`"));
437        assert!(rendered_prompt.contains("anything outside that root is read-only"));
438        assert!(normalized_prompt.contains("Mermaid diagrams must remain in `answer`"));
439        assert!(normalized_prompt.contains("fences without the `mermaid` info string"));
440        assert!(
441            rendered_prompt
442                .contains("______________________________________________________________________")
443        );
444        assert!(!rendered_prompt.contains("Authoritative JSON Schema:"));
445        assert!(rendered_prompt.ends_with(prompt));
446    }
447
448    #[test]
449    /// Ensures refresh prompt text is inserted after generated reminder
450    /// placeholders so prompt content cannot trigger recursive expansion.
451    fn test_prepend_protocol_refresh_reminder_preserves_prompt_placeholders() {
452        // Arrange
453        let prompt = "Keep this literal: {{ protocol_refresh_instructions }} {{ workspace_root }}";
454
455        // Act
456        let rendered_prompt = prepend_protocol_refresh_reminder(
457            prompt,
458            ProtocolRequestProfile::SessionTurn,
459            test_workspace_root(),
460        );
461
462        // Assert
463        assert!(rendered_prompt.ends_with(prompt));
464    }
465
466    #[test]
467    /// Repair prompt renders with the parse error and a response preview.
468    fn test_build_protocol_repair_prompt_includes_error_and_preview() {
469        // Arrange
470        let parse_error = "response is not valid protocol JSON: invalid JSON";
471        let malformed_response = "plain text response";
472
473        // Act
474        let repair_prompt = build_protocol_repair_prompt(parse_error, malformed_response);
475
476        // Assert
477        assert!(repair_prompt.contains(parse_error));
478        assert!(repair_prompt.contains("plain text response"));
479        assert!(repair_prompt.contains("Structured response protocol:"));
480        assert!(repair_prompt.contains("Authoritative JSON Schema:"));
481        assert!(repair_prompt.contains("\"answer\""));
482    }
483
484    #[test]
485    /// Ensures malformed response previews are inserted after generated
486    /// schema placeholders so agent output cannot trigger recursive expansion.
487    fn test_build_protocol_repair_prompt_preserves_response_preview_placeholders() {
488        // Arrange
489        let malformed_response = "Keep this literal: {{ response_json_schema }}";
490
491        // Act
492        let repair_prompt =
493            build_protocol_repair_prompt("schema validation failed", malformed_response);
494
495        // Assert
496        assert!(repair_prompt.contains(malformed_response));
497    }
498
499    #[test]
500    /// Repair prompt truncates long malformed responses to the preview limit.
501    fn test_build_protocol_repair_prompt_truncates_long_response() {
502        // Arrange
503        let parse_error = "schema validation failed";
504        let malformed_response = "x".repeat(1000);
505
506        // Act
507        let repair_prompt = build_protocol_repair_prompt(parse_error, &malformed_response);
508
509        // Assert
510        assert!(repair_prompt.contains("500 more chars"));
511        assert!(!repair_prompt.contains(&malformed_response));
512    }
513
514    #[test]
515    /// Repair prompt includes the protocol marker to prevent double-wrapping.
516    fn test_build_protocol_repair_prompt_contains_protocol_marker() {
517        // Arrange / Act
518        let repair_prompt = build_protocol_repair_prompt("error", "response");
519
520        // Assert
521        assert!(repair_prompt.contains("Structured response protocol:"));
522    }
523
524    #[test]
525    /// Short responses are not truncated.
526    fn test_truncate_preview_keeps_short_responses_intact() {
527        // Arrange / Act
528        let preview = truncate_preview("short", 500);
529
530        // Assert
531        assert_eq!(preview, "short");
532    }
533
534    #[test]
535    /// Long responses are truncated with a character count suffix.
536    fn test_truncate_preview_truncates_long_responses() {
537        // Arrange
538        let long_response = "a".repeat(600);
539
540        // Act
541        let preview = truncate_preview(&long_response, 500);
542
543        // Assert
544        assert!(preview.starts_with(&"a".repeat(500)));
545        assert!(preview.contains("100 more chars"));
546    }
547}