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::protocol_json_schema_json;
9
10/// Combined budget for the JSON-encoded response and diagnostic.
11const REPAIR_PAYLOAD_MAX_BYTES: usize = 128 * 1024;
12/// Maximum encoded diagnostic size, including any truncation notice.
13const REPAIR_PARSE_ERROR_MAX_BYTES: usize = 4 * 1024;
14
15/// Controls whether bootstrap prompt instructions include the full protocol
16/// JSON Schema text.
17#[derive(Debug, Clone, Copy, PartialEq, Eq)]
18pub enum ProtocolSchemaInstructionMode {
19    /// Include the full self-descriptive JSON Schema in the prompt because
20    /// the provider does not enforce Agentty's response schema natively.
21    PromptSchema,
22    /// Omit the full schema text because the provider enforces the same
23    /// response schema through its transport-level structured output API.
24    TransportSchema,
25}
26
27impl ProtocolSchemaInstructionMode {
28    /// Returns whether bootstrap instructions should embed the full JSON
29    /// Schema text in the prompt body.
30    fn includes_response_json_schema(self) -> bool {
31        matches!(self, Self::PromptSchema)
32    }
33}
34
35/// Prepends structured response protocol instructions to a prompt.
36///
37/// Tells agents to emit one top-level JSON object that matches Agentty's
38/// structured protocol while selecting the cheapest safe schema guidance for
39/// the current provider. Providers without native structured output receive
40/// the full JSON Schema in the prompt; providers with native enforcement get
41/// policy and field-routing instructions only. `workspace_root` names the
42/// only writable directory for the turn. The transport selects bootstrap or
43/// refresh delivery explicitly and calls this once for an unwrapped payload;
44/// payload text never determines whether policy is applied.
45#[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/// Prepends a compact refresh reminder for providers that already received
76/// the full instruction contract in the active context.
77///
78/// The reminder repeats the workspace-isolation boundary for
79/// `workspace_root` so long-lived provider contexts keep the rule even after
80/// provider-side context compaction.
81#[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
98/// Builds the protocol repair prompt text for one failed parse attempt.
99///
100/// Returns a schema-free body with the lossless response and a bounded
101/// diagnostic. Callers must apply the shared protocol envelope using the
102/// request's profile and provider schema mode before submission.
103///
104/// # Errors
105/// Returns an error instead of truncating a response when the combined
106/// JSON-encoded response and diagnostic exceed 128 KiB, including string
107/// delimiters and escapes. Static envelope instructions are outside this
108/// budget.
109pub 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
147/// Encodes a diagnostic without allocating in proportion to untrusted input.
148fn 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    // JSON escapes consume at most six bytes per input byte. Reserve room
158    // for delimiters and the notice before selecting a UTF-8-safe prefix.
159    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/// Askama view model for protocol instructions when the transport enforces
166/// the response schema.
167#[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/// Askama view model for full protocol instructions with prompt-side schema.
176#[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/// Askama view model for compact refresh reminders.
186#[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/// Askama view model for repair prompts after protocol parse failures.
195#[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/// Askama view model for session-turn protocol usage instructions.
203#[derive(Template)]
204#[template(path = "protocol_instruction_session_turn_usage.md", escape = "none")]
205struct ProtocolInstructionSessionTurnUsageTemplate;
206
207/// Askama view model for one-shot protocol usage instructions.
208#[derive(Template)]
209#[template(path = "protocol_instruction_utility_prompt_usage.md", escape = "none")]
210struct ProtocolInstructionUtilityPromptUsageTemplate;
211
212/// Askama view model for direct focused-review protocol usage instructions.
213#[derive(Template)]
214#[template(path = "protocol_instruction_focused_review_usage.md", escape = "none")]
215struct ProtocolInstructionFocusedReviewUsageTemplate;
216
217/// Askama view model for session-turn refresh instructions.
218#[derive(Template)]
219#[template(path = "protocol_refresh_session_turn_instruction.md", escape = "none")]
220struct ProtocolRefreshSessionTurnInstructionTemplate;
221
222/// Askama view model for one-shot refresh instructions.
223#[derive(Template)]
224#[template(
225    path = "protocol_refresh_utility_prompt_instruction.md",
226    escape = "none"
227)]
228struct ProtocolRefreshUtilityPromptInstructionTemplate;
229
230/// Renders the protocol usage instructions for one request profile.
231fn 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
252/// Renders the compact protocol refresh instructions for one request profile.
253fn 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
274/// Renders one Askama template and removes trailing whitespace.
275fn 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;