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` bounds
42/// project edits; documented tool-managed support state may live outside it
43/// when execution permissions allow writes. The transport selects bootstrap or
44/// refresh delivery explicitly and calls this once for an unwrapped payload;
45/// payload text never determines whether policy is applied.
46#[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/// Renders durable application policy for native developer/system instruction
77/// channels without replacing the provider's built-in coding instructions.
78#[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/// Askama view model for the policy shared by native and prompt transports.
89#[derive(Template)]
90#[template(path = "workspace_policy_prompt.md", escape = "none")]
91struct WorkspacePolicyPromptTemplate<'a> {
92    workspace_root: &'a str,
93}
94
95/// Prepends a compact refresh reminder for providers that already received
96/// the full instruction contract in the active context.
97///
98/// The reminder repeats the workspace-isolation boundary for
99/// `workspace_root` so long-lived provider contexts keep the rule even after
100/// provider-side context compaction.
101#[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
118/// Builds the protocol repair prompt text for one failed parse attempt.
119///
120/// Returns a schema-free body with the lossless response and a bounded
121/// diagnostic. Callers must apply the shared protocol envelope using the
122/// request's profile and provider schema mode before submission.
123///
124/// # Errors
125/// Returns an error instead of truncating a response when the combined
126/// JSON-encoded response and diagnostic exceed 128 KiB, including string
127/// delimiters and escapes. Static envelope instructions are outside this
128/// budget.
129pub 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
167/// Encodes a diagnostic without allocating in proportion to untrusted input.
168fn 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    // JSON escapes consume at most six bytes per input byte. Reserve room
178    // for delimiters and the notice before selecting a UTF-8-safe prefix.
179    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
185/// Encodes path data consistently across native, bootstrap, and refresh policy.
186/// Escaping backticks also keeps path text from opening Markdown code spans.
187fn 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/// Askama view model for protocol instructions when the transport enforces
194/// the response schema.
195#[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/// Askama view model for full protocol instructions with prompt-side schema.
204#[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/// Askama view model for compact refresh reminders.
214#[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/// Askama view model for repair prompts after protocol parse failures.
223#[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/// Askama view model for session-turn protocol usage instructions.
231#[derive(Template)]
232#[template(path = "protocol_instruction_session_turn_usage.md", escape = "none")]
233struct ProtocolInstructionSessionTurnUsageTemplate;
234
235/// Askama view model for one-shot protocol usage instructions.
236#[derive(Template)]
237#[template(path = "protocol_instruction_utility_prompt_usage.md", escape = "none")]
238struct ProtocolInstructionUtilityPromptUsageTemplate;
239
240/// Askama view model for direct focused-review protocol usage instructions.
241#[derive(Template)]
242#[template(path = "protocol_instruction_focused_review_usage.md", escape = "none")]
243struct ProtocolInstructionFocusedReviewUsageTemplate;
244
245/// Askama view model for session-turn refresh instructions.
246#[derive(Template)]
247#[template(path = "protocol_refresh_session_turn_instruction.md", escape = "none")]
248struct ProtocolRefreshSessionTurnInstructionTemplate;
249
250/// Askama view model for one-shot refresh instructions.
251#[derive(Template)]
252#[template(
253    path = "protocol_refresh_utility_prompt_instruction.md",
254    escape = "none"
255)]
256struct ProtocolRefreshUtilityPromptInstructionTemplate;
257
258/// Renders the protocol usage instructions for one request profile.
259fn render_protocol_usage_instructions(profile: ProtocolRequestProfile) -> String {
260    if matches!(profile, ProtocolRequestProfile::ReviewMetadata) {
261        return "Return the direct review metadata object with title, description, and \
262                is_title_change_significant. Do not nest it inside answer."
263            .to_string();
264    }
265
266    if matches!(profile, ProtocolRequestProfile::FocusedReview) {
267        return render_template(
268            "protocol_instruction_focused_review_usage.md",
269            &ProtocolInstructionFocusedReviewUsageTemplate,
270        );
271    }
272
273    if matches!(profile, ProtocolRequestProfile::SessionTurn) {
274        return render_template(
275            "protocol_instruction_session_turn_usage.md",
276            &ProtocolInstructionSessionTurnUsageTemplate,
277        );
278    }
279
280    render_template(
281        "protocol_instruction_utility_prompt_usage.md",
282        &ProtocolInstructionUtilityPromptUsageTemplate,
283    )
284}
285
286/// Renders the compact protocol refresh instructions for one request profile.
287fn render_protocol_refresh_instructions(profile: ProtocolRequestProfile) -> String {
288    if matches!(profile, ProtocolRequestProfile::ReviewMetadata) {
289        return "Return the direct review metadata object with title, description, and \
290                is_title_change_significant. Do not nest it inside answer."
291            .to_string();
292    }
293
294    if matches!(profile, ProtocolRequestProfile::FocusedReview) {
295        return render_template(
296            "protocol_instruction_focused_review_usage.md",
297            &ProtocolInstructionFocusedReviewUsageTemplate,
298        );
299    }
300
301    if matches!(profile, ProtocolRequestProfile::SessionTurn) {
302        return render_template(
303            "protocol_refresh_session_turn_instruction.md",
304            &ProtocolRefreshSessionTurnInstructionTemplate,
305        );
306    }
307
308    render_template(
309        "protocol_refresh_utility_prompt_instruction.md",
310        &ProtocolRefreshUtilityPromptInstructionTemplate,
311    )
312}
313
314/// Renders one Askama template and removes trailing whitespace.
315fn render_template(template_name: &str, template: &impl Template) -> String {
316    let rendered = match template.render() {
317        Ok(rendered) => rendered,
318        Err(error) => format!("Failed to render `{template_name}`: {error}"),
319    };
320
321    rendered.trim_end().to_string()
322}
323
324#[cfg(test)]
325#[path = "envelope_test.rs"]
326mod tests;