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_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/// Renders durable application policy for native developer/system instruction
76/// channels without replacing the provider's built-in coding instructions.
77#[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/// Askama view model for the policy shared by native and prompt transports.
88#[derive(Template)]
89#[template(path = "workspace_policy_prompt.md", escape = "none")]
90struct WorkspacePolicyPromptTemplate<'a> {
91    workspace_root: &'a str,
92}
93
94/// Prepends a compact refresh reminder for providers that already received
95/// the full instruction contract in the active context.
96///
97/// The reminder repeats the workspace-isolation boundary for
98/// `workspace_root` so long-lived provider contexts keep the rule even after
99/// provider-side context compaction.
100#[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
117/// Builds the protocol repair prompt text for one failed parse attempt.
118///
119/// Returns a schema-free body with the lossless response and a bounded
120/// diagnostic. Callers must apply the shared protocol envelope using the
121/// request's profile and provider schema mode before submission.
122///
123/// # Errors
124/// Returns an error instead of truncating a response when the combined
125/// JSON-encoded response and diagnostic exceed 128 KiB, including string
126/// delimiters and escapes. Static envelope instructions are outside this
127/// budget.
128pub 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
166/// Encodes a diagnostic without allocating in proportion to untrusted input.
167fn 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    // JSON escapes consume at most six bytes per input byte. Reserve room
177    // for delimiters and the notice before selecting a UTF-8-safe prefix.
178    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
184/// Encodes path data consistently across native, bootstrap, and refresh policy.
185/// Escaping backticks also keeps path text from opening Markdown code spans.
186fn 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/// Askama view model for protocol instructions when the transport enforces
193/// the response schema.
194#[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/// Askama view model for full protocol instructions with prompt-side schema.
203#[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/// Askama view model for compact refresh reminders.
213#[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/// Askama view model for repair prompts after protocol parse failures.
222#[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/// Askama view model for session-turn protocol usage instructions.
230#[derive(Template)]
231#[template(path = "protocol_instruction_session_turn_usage.md", escape = "none")]
232struct ProtocolInstructionSessionTurnUsageTemplate;
233
234/// Askama view model for one-shot protocol usage instructions.
235#[derive(Template)]
236#[template(path = "protocol_instruction_utility_prompt_usage.md", escape = "none")]
237struct ProtocolInstructionUtilityPromptUsageTemplate;
238
239/// Askama view model for direct focused-review protocol usage instructions.
240#[derive(Template)]
241#[template(path = "protocol_instruction_focused_review_usage.md", escape = "none")]
242struct ProtocolInstructionFocusedReviewUsageTemplate;
243
244/// Askama view model for session-turn refresh instructions.
245#[derive(Template)]
246#[template(path = "protocol_refresh_session_turn_instruction.md", escape = "none")]
247struct ProtocolRefreshSessionTurnInstructionTemplate;
248
249/// Askama view model for one-shot refresh instructions.
250#[derive(Template)]
251#[template(
252    path = "protocol_refresh_utility_prompt_instruction.md",
253    escape = "none"
254)]
255struct ProtocolRefreshUtilityPromptInstructionTemplate;
256
257/// Renders the protocol usage instructions for one request profile.
258fn 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
285/// Renders the compact protocol refresh instructions for one request profile.
286fn 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
313/// Renders one Askama template and removes trailing whitespace.
314fn 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;