Skip to main content

mlua_swarm/operator/
render.rs

1//! `system_prompt` template rendering for the Operator path.
2//!
3//! Lets the agent.md body (`AgentDef.profile.system_prompt`) carry
4//! Jinja2-compatible syntax (`{{ directive }}` / `{% if intent %}` /
5//! `{{ x | upper }}` and so on). The caller passes
6//! `TaskSpec.initial_directive` as JSON and its fields expand into the
7//! template slots.
8//!
9//! ## Engine choice
10//!
11//! minijinja (maintained by Armin Ronacher, the Jinja2 author — a light
12//! dependency). Two defaults are forced up front to avoid classic traps:
13//!
14//! - `auto_escape = None`. HTML auto-escape is off; for LLM prompts,
15//!   turning `<` / `>` into `&lt;` / `&gt;` corrupts the prompt.
16//! - `UndefinedBehavior::Strict`. A typo'd variable would otherwise
17//!   silently render as an empty string; in a production prompt
18//!   template we want that to fail loud.
19//!
20//! ## Syntax available inside the agent.md body (Jinja2-compatible, per
21//! minijinja v2)
22//!
23//! ```text
24//! Variables:  {{ directive }} / {{ slot.nested }} / {{ items[0] }}
25//! Filters:    {{ name | upper }} / {{ x | default("fallback") }} / {{ s | length }}
26//! Branch:     {% if intent %}...{% elif other %}...{% else %}...{% endif %}
27//! Loop:       {% for x in items %}{{ x }},{% endfor %}
28//! Comment:    {# note #}
29//! Raw:        {% raw %}{{ literal }}{% endraw %}
30//! ```
31//!
32//! Macros, `include`, and inheritance are not available here — this
33//! layer performs a flat render over one string handed in by the caller,
34//! and does not support multi-template composition. If we ever need
35//! that, adding a source loader to `Environment` is a carry.
36//!
37//! ## Slot names (the variables the caller can reference in the
38//! template)
39//!
40//! `slots_from_prompt(prompt: &str)` builds the slot map:
41//!
42//! - When `prompt` is a **JSON object**, the object's top-level keys
43//!   become the slot names — for example
44//!   `r#"{"directive":"X","intent":"fix"}"#` exposes `{{ directive }}`
45//!   and `{{ intent }}`.
46//! - When `prompt` is **anything else** (a plain string, a number, an
47//!   array, an already-stringified JSON), it is wrapped as
48//!   `{"directive": <the prompt itself>}`; only `{{ directive }}` is
49//!   available.
50//!
51//! To expose additional slots, the caller (whoever assembles
52//! `TaskSpec.initial_directive`) passes a JSON object. Conventions:
53//!
54//! - `directive` (effectively required) — the main task instruction;
55//!   the plain-prompt fallback also lives here.
56//! - `intent` — task kind / classification hint (optional; used in
57//!   `if` branches).
58//! - `context` — additional context (optional).
59//! - Beyond those, agent.md authors are free to add whatever slots the
60//!   template needs.
61//!
62//! ## Errors
63//!
64//! - Undefined variable → `RenderError::Template` (strict mode).
65//! - Syntax error → `RenderError::Template`.
66//! - On the `OperatorSpawner` path this is wrapped in
67//!   `SpawnError::Internal("render system_prompt: ...")` and propagated
68//!   — no silent fallback, fail loud.
69
70use minijinja::{Environment, UndefinedBehavior, Value};
71use thiserror::Error;
72
73/// Render errors. Anything from minijinja is wrapped as `Template`.
74#[derive(Debug, Error)]
75pub enum RenderError {
76    /// minijinja syntax errors, undefined-variable errors, runtime
77    /// errors, and the like.
78    #[error("template render failed: {0}")]
79    Template(String),
80}
81
82impl From<minijinja::Error> for RenderError {
83    fn from(e: minijinja::Error) -> Self {
84        RenderError::Template(format!("{e:#}"))
85    }
86}
87
88/// Render a `system_prompt` template in strict mode with auto-escape
89/// disabled.
90///
91/// `slots` is any JSON value. When it is an object, the top-level keys
92/// are exposed as variables — `{{ directive }}` reads `slots.directive`.
93/// When it is not an object, this function binds the value under a
94/// single variable named `value`, reachable as `{{ value }}`.
95pub fn render_system(template: &str, slots: &serde_json::Value) -> Result<String, RenderError> {
96    let mut env = Environment::new();
97    env.set_auto_escape_callback(|_| minijinja::AutoEscape::None);
98    env.set_undefined_behavior(UndefinedBehavior::Strict);
99
100    let tmpl = env.template_from_str(template)?;
101    let value = Value::from_serialize(slots);
102    let rendered = if let serde_json::Value::Object(_) = slots {
103        tmpl.render(value)?
104    } else {
105        // A non-object is bound as the single variable `value`.
106        tmpl.render(minijinja::context! { value => value })?
107    };
108    Ok(rendered)
109}
110
111/// If `prompt` is a JSON object, treat it as the slot map; otherwise
112/// wrap it as `{"directive": prompt}`. Corresponds to the
113/// `initial_directive` intake convention on the caller side
114/// (`OperatorSpawner`). Takes `Value` directly (issue #18): `Value`
115/// flows end-to-end through `EngineState.prompts` and
116/// `Engine::fetch_prompt`; parsing a JSON literal `String` back into
117/// an `Object` is no longer required at this boundary.
118pub fn slots_from_prompt(prompt: &serde_json::Value) -> serde_json::Value {
119    match prompt {
120        v @ serde_json::Value::Object(_) => v.clone(),
121        other => serde_json::json!({ "directive": other }),
122    }
123}
124
125#[cfg(test)]
126mod tests {
127    use super::*;
128    use serde_json::json;
129
130    #[test]
131    fn expands_simple_variable() {
132        let out = render_system("hello {{ directive }}", &json!({ "directive": "world" }))
133            .expect("render ok");
134        assert_eq!(out, "hello world");
135    }
136
137    #[test]
138    fn supports_if_branch() {
139        let tmpl = "{% if intent %}intent={{ intent }}{% else %}no-intent{% endif %}";
140        let with = render_system(tmpl, &json!({ "intent": "fix-bug" })).unwrap();
141        assert_eq!(with, "intent=fix-bug");
142        let without = render_system(tmpl, &json!({ "intent": null })).unwrap();
143        assert_eq!(without, "no-intent");
144    }
145
146    #[test]
147    fn supports_filter() {
148        let out = render_system("{{ name | upper }}", &json!({ "name": "shi" })).unwrap();
149        assert_eq!(out, "SHI");
150    }
151
152    #[test]
153    fn undefined_variable_errors_strict() {
154        let err = render_system("hello {{ missing }}", &json!({ "directive": "x" }))
155            .expect_err("strict undef must fail");
156        let msg = format!("{err}");
157        assert!(
158            msg.contains("undefined") || msg.contains("missing"),
159            "expected strict undef error, got: {msg}"
160        );
161    }
162
163    #[test]
164    fn syntax_error_returns_err() {
165        let err = render_system("hello {{ unclosed", &json!({})).expect_err("syntax error");
166        let msg = format!("{err}");
167        assert!(
168            msg.contains("syntax") || msg.contains("unexpected"),
169            "got: {msg}"
170        );
171    }
172
173    #[test]
174    fn html_chars_not_escaped() {
175        // For LLM prompt use, escaping `<` / `>` / `&` corrupts the prompt.
176        let out = render_system("{{ snippet }}", &json!({ "snippet": "<tag>&amp;" })).unwrap();
177        assert_eq!(out, "<tag>&amp;");
178    }
179
180    #[test]
181    fn supports_for_loop() {
182        let tmpl = "{% for x in xs %}{{ x }},{% endfor %}";
183        let out = render_system(tmpl, &json!({ "xs": ["a", "b", "c"] })).unwrap();
184        assert_eq!(out, "a,b,c,");
185    }
186
187    #[test]
188    fn slots_from_prompt_object() {
189        let v = slots_from_prompt(&json!({"directive":"do-X","intent":"fix"}));
190        assert_eq!(v["directive"], "do-X");
191        assert_eq!(v["intent"], "fix");
192    }
193
194    #[test]
195    fn slots_from_prompt_plain_string() {
196        let v = slots_from_prompt(&json!("just a plain instruction"));
197        assert_eq!(v["directive"], "just a plain instruction");
198    }
199
200    #[test]
201    fn slots_from_prompt_json_array_falls_back_to_directive() {
202        // A top-level array is not an object, so fall back to wrapping in `directive`.
203        let v = slots_from_prompt(&json!(["a", "b"]));
204        assert_eq!(v["directive"], json!(["a", "b"]));
205    }
206}