1use serde::Serialize;
21use serde_json::{json, Map, Value};
22
23use crate::backend::job_templates::{self as jt, ApprovedTemplate, JobTemplateState, JobTemplates};
24use crate::backend::jobs::definition::{JobDefinition, TemplateRef};
25
26pub fn edit_needs_render(fields: &Map<String, Value>, before: &JobDefinition) -> bool {
32 if fields.contains_key("template") || fields.contains_key("params") {
33 return true;
34 }
35 let before = serde_json::to_value(before).unwrap_or_default();
36 fields.get("action").is_some_and(|action| {
37 let sent = Value::Object(Map::from_iter([("action".to_string(), action.clone())]));
38 brief_of(&sent) != brief_of(&before)
39 })
40}
41
42fn text<'a>(v: &'a Value, key: &str) -> &'a str {
43 v.get(key).and_then(Value::as_str).unwrap_or("")
44}
45
46fn service() -> Result<&'static std::sync::Arc<JobTemplates>, String> {
47 jt::service().ok_or_else(|| "job templates aren't available on this AgentMux".to_string())
48}
49
50fn reference(def: &Value) -> Option<&Value> {
52 def.get("template").filter(|t| !t.is_null())
53}
54
55pub fn apply(def: &mut Value, previous: Option<&TemplateRef>) -> Result<(), String> {
63 if reference(def).is_none() {
64 return Ok(());
65 }
66 apply_with(def, previous, service()?)
67}
68
69pub(crate) fn apply_with(def: &mut Value, previous: Option<&TemplateRef>, svc: &JobTemplates) -> Result<(), String> {
70 let Some(asked) = reference(def).cloned() else { return Ok(()) };
71 let id = text(&asked, "id").trim().to_string();
72 if id.is_empty() {
73 return Err("template.id is required".to_string());
74 }
75 let version = match text(&asked, "version").trim() {
76 "" => svc
77 .get(&id)
78 .and_then(|(info, _)| info.manifest.map(|m| m.version))
79 .ok_or_else(|| format!("no job template {id}"))?,
80 v => v.to_string(),
81 };
82 let approved = svc.resolve_approved(&id, &version).map_err(|e| {
83 if previous.is_some() && e.contains(" is at version ") {
84 format!("{e}: this job is pinned to {version}; accept the template's update first")
85 } else {
86 e
87 }
88 })?;
89 let hash = text(&asked, "hash");
90 if !hash.is_empty() && hash != approved.hash {
91 return Err(format!("{id} changed since the job's template pin was recorded; it needs the operator's approval again"));
92 }
93 let Some(obj) = def.as_object_mut() else { return Err("a job definition is a JSON object".to_string()) };
94 let given = obj.get("params").and_then(Value::as_object).cloned().unwrap_or_default();
95 let rendered = approved.render(&given)?;
96 let moved = previous.is_some_and(|p| p.id != approved.id || p.version != approved.version || p.hash != approved.hash);
97 obj.insert("params".into(), Value::Object(rendered.params.clone()));
98 obj.insert("template".into(), json!({ "id": approved.id, "version": approved.version, "hash": approved.hash }));
99 obj.insert("outputs".into(), json!(approved.manifest.outputs));
100 obj.insert("secrets".into(), secrets_of(&approved, &rendered.params));
101 if approved.manifest.kind == jt::manifest::JobTemplateKind::Drone {
102 drone_action(obj, &approved.id)?;
103 } else {
104 set_brief(obj, &approved, &rendered.brief);
105 }
106 if previous.is_none() {
107 fill_defaults(obj, &approved, &rendered.params)?;
108 } else if moved {
109 let overlay = overlay_policy(obj.get("policy"), template_policy(&approved).as_ref());
110 obj.insert("policy".into(), overlay);
111 }
112 Ok(())
113}
114
115fn secrets_of(t: &ApprovedTemplate, params: &Map<String, Value>) -> Value {
119 let list: Vec<Value> = t
120 .manifest
121 .secrets
122 .iter()
123 .filter_map(|s| params.get(&s.param).and_then(Value::as_str).map(|vault| json!({ "name": s.name, "vault": vault })))
124 .collect();
125 Value::Array(list)
126}
127
128fn drone_action(obj: &Map<String, Value>, id: &str) -> Result<(), String> {
131 let action = obj.get("action").unwrap_or(&Value::Null);
132 if text(action, "kind") == "drone" && !text(action, "drone_id").trim().is_empty() {
133 return Ok(());
134 }
135 Err(format!("{id} is a Drone template: make its drone first (jobs.templates.make_drone), then give the job the action {{\"kind\": \"drone\", \"drone_id\": …}}"))
136}
137
138fn set_brief(obj: &mut Map<String, Value>, t: &ApprovedTemplate, brief: &str) {
140 let mut action = obj.get("action").and_then(Value::as_object).cloned().unwrap_or_default();
141 if text(&Value::Object(action.clone()), "kind").is_empty() {
142 if let Some(kind) = t.manifest.action.as_ref().and_then(|a| a.get("kind")) {
143 action.insert("kind".into(), kind.clone());
144 }
145 }
146 let field = if action.get("kind").and_then(Value::as_str) == Some("task") { "payload" } else { "brief" };
147 action.insert(field.into(), Value::String(brief.to_string()));
148 obj.insert("action".into(), Value::Object(action));
149}
150
151fn fill_defaults(obj: &mut Map<String, Value>, t: &ApprovedTemplate, params: &Map<String, Value>) -> Result<(), String> {
154 if obj.get("name").and_then(Value::as_str).is_none_or(|n| n.trim().is_empty()) {
155 obj.insert("name".into(), Value::String(t.manifest.name.clone()));
156 }
157 if obj.get("trigger").is_none_or(Value::is_null) {
158 let mut trigger = t.manifest.trigger.clone().unwrap_or_else(|| json!({ "kind": "manual" }));
160 jt::graph::render_value(&mut trigger, params)?;
161 obj.insert("trigger".into(), trigger);
162 }
163 if let Some(defaults) = template_policy(t) {
164 let own = obj.get("policy").cloned();
165 obj.insert("policy".into(), overlay_policy(Some(&defaults), own.as_ref()));
166 }
167 if let Some(base) = t.manifest.action.as_ref().and_then(Value::as_object) {
169 let mut action = base.clone();
170 for (k, v) in obj.get("action").and_then(Value::as_object).cloned().unwrap_or_default() {
171 action.insert(k, v);
172 }
173 obj.insert("action".into(), Value::Object(action));
174 }
175 Ok(())
176}
177
178const NOT_RUNNABLE_YET: [&str; 1] = ["max_turns"];
182
183fn template_policy(t: &ApprovedTemplate) -> Option<Value> {
185 let mut policy = t.manifest.policy.clone()?;
186 if let Some(obj) = policy.as_object_mut() {
187 NOT_RUNNABLE_YET.iter().for_each(|k| {
188 obj.remove(*k);
189 });
190 }
191 Some(policy)
192}
193
194fn overlay_policy(base: Option<&Value>, top: Option<&Value>) -> Value {
196 let mut out = base.and_then(Value::as_object).cloned().unwrap_or_default();
197 for (key, value) in top.and_then(Value::as_object).into_iter().flatten() {
198 match (key.as_str(), out.get(key).and_then(Value::as_object), value.as_object()) {
199 ("caps", Some(have), Some(over)) => {
200 let mut caps = have.clone();
201 caps.extend(over.iter().map(|(k, v)| (k.clone(), v.clone())));
202 out.insert(key.clone(), Value::Object(caps));
203 }
204 _ => {
205 out.insert(key.clone(), value.clone());
206 }
207 }
208 }
209 Value::Object(out)
210}
211
212#[derive(Debug, Clone, PartialEq, Serialize, ts_rs::TS)]
216#[ts(export, export_to = "../../../frontend/types/rpc/")]
217pub struct TemplateUpdateView {
218 pub version: String,
219 pub approved: bool,
222}
223
224#[derive(Debug, Clone, PartialEq, Serialize, ts_rs::TS)]
226#[ts(export, export_to = "../../../frontend/types/rpc/")]
227pub struct TemplatePinView {
228 pub id: String,
229 pub version: String,
230 pub update: Option<TemplateUpdateView>,
231}
232
233pub type Latest = std::collections::HashMap<String, Option<(String, String, bool)>>;
235
236pub fn pin_view(pin: &TemplateRef, latest: &mut Latest) -> TemplatePinView {
239 let newest = latest
240 .entry(pin.id.clone())
241 .or_insert_with(|| {
242 let (info, _) = jt::service()?.get(&pin.id)?;
243 Some((info.manifest?.version, info.hash, info.state == JobTemplateState::Approved))
244 })
245 .clone();
246 let update = newest
247 .filter(|(version, hash, _)| *version != pin.version || *hash != pin.hash)
248 .map(|(version, _, approved)| TemplateUpdateView { version, approved });
249 TemplatePinView { id: pin.id.clone(), version: pin.version.clone(), update }
250}
251
252#[derive(Debug, Clone, PartialEq, Serialize, ts_rs::TS)]
256#[serde(rename_all = "snake_case")]
257#[ts(export, export_to = "../../../frontend/types/rpc/")]
258pub enum UpdateStatus {
259 None,
261 Available,
263 NeedsApproval,
265 Unavailable,
267}
268
269#[derive(Debug, Clone, PartialEq, Serialize, ts_rs::TS)]
271#[ts(export, export_to = "../../../frontend/types/rpc/")]
272pub struct TextChange {
273 pub before: String,
274 pub after: String,
275}
276
277#[derive(Debug, Clone, Default, PartialEq, Serialize, ts_rs::TS)]
279#[ts(export, export_to = "../../../frontend/types/rpc/")]
280pub struct ListChange {
281 pub added: Vec<String>,
282 pub removed: Vec<String>,
283}
284
285impl ListChange {
286 fn between(before: &[String], after: &[String]) -> Option<ListChange> {
287 let added: Vec<String> = after.iter().filter(|a| !before.contains(a)).cloned().collect();
288 let removed: Vec<String> = before.iter().filter(|b| !after.contains(b)).cloned().collect();
289 (!added.is_empty() || !removed.is_empty()).then_some(ListChange { added, removed })
290 }
291}
292
293#[derive(Debug, Clone, PartialEq, Serialize, ts_rs::TS)]
295#[ts(export, export_to = "../../../frontend/types/rpc/")]
296pub struct PolicyChange {
297 pub field: String,
299 pub before: String,
301 pub after: String,
302}
303
304#[derive(Debug, Clone, PartialEq, Serialize, ts_rs::TS)]
305#[ts(export, export_to = "../../../frontend/types/rpc/")]
306pub struct TemplateUpdateDiff {
307 pub job_id: String,
308 pub template_id: String,
309 pub status: UpdateStatus,
310 pub reason: Option<String>,
312 pub from_version: String,
313 pub to_version: String,
314 pub to_hash: String,
316 pub brief: Option<TextChange>,
317 pub outputs: Option<ListChange>,
318 pub secrets: Option<ListChange>,
319 pub policy: Vec<PolicyChange>,
320 pub params_error: Option<String>,
322}
323
324impl TemplateUpdateDiff {
325 fn without_update(job: &JobDefinition, status: UpdateStatus, reason: Option<String>) -> Self {
326 let pin = job.template.clone().unwrap_or(TemplateRef { id: String::new(), version: String::new(), hash: String::new() });
327 TemplateUpdateDiff {
328 job_id: job.id.clone(),
329 template_id: pin.id,
330 status,
331 reason,
332 from_version: pin.version.clone(),
333 to_version: pin.version,
334 to_hash: String::new(),
335 brief: None,
336 outputs: None,
337 secrets: None,
338 policy: Vec::new(),
339 params_error: None,
340 }
341 }
342}
343
344fn show(v: Option<&Value>) -> String {
345 match v {
346 None | Some(Value::Null) => "—".to_string(),
347 Some(Value::String(s)) => s.clone(),
348 Some(Value::Number(n)) => match n.as_f64() {
349 Some(f) if f.fract() == 0.0 && f.abs() < 1e15 => format!("{}", f as i64),
350 _ => n.to_string(),
351 },
352 Some(other) => other.to_string(),
353 }
354}
355
356fn same(a: Option<&Value>, b: Option<&Value>) -> bool {
358 match (a, b) {
359 (Some(Value::Number(x)), Some(Value::Number(y))) => x.as_f64() == y.as_f64(),
360 _ => a == b,
361 }
362}
363
364fn policy_changes(before: &Value, after: &Value) -> Vec<PolicyChange> {
366 let mut out = Vec::new();
367 let mut keys: Vec<&String> = after.as_object().into_iter().flat_map(|m| m.keys()).collect();
368 keys.sort();
369 for key in keys {
370 let (b, a) = (before.get(key), after.get(key));
371 if same(b, a) {
372 continue;
373 }
374 if key == "caps" {
375 let caps = |v: Option<&Value>| v.and_then(Value::as_object).cloned().unwrap_or_default();
376 let (bc, ac) = (caps(b), caps(a));
377 let mut names: Vec<&String> = ac.keys().collect();
378 names.sort();
379 for name in names.into_iter().filter(|n| !same(bc.get(*n), ac.get(*n))) {
380 out.push(PolicyChange { field: format!("caps.{name}"), before: show(bc.get(name)), after: show(ac.get(name)) });
381 }
382 continue;
383 }
384 out.push(PolicyChange { field: key.clone(), before: show(b), after: show(a) });
385 }
386 out
387}
388
389pub fn update_diff(job: &JobDefinition) -> TemplateUpdateDiff {
392 match service() {
393 Ok(svc) => update_diff_with(job, svc),
394 Err(e) => TemplateUpdateDiff::without_update(job, UpdateStatus::Unavailable, Some(e)),
395 }
396}
397
398pub(crate) fn update_diff_with(job: &JobDefinition, svc: &JobTemplates) -> TemplateUpdateDiff {
399 let Some(pin) = &job.template else { return TemplateUpdateDiff::without_update(job, UpdateStatus::None, None) };
400 let Some((info, _)) = svc.get(&pin.id) else {
401 let why = format!("{} isn't installed any more", pin.id);
402 return TemplateUpdateDiff::without_update(job, UpdateStatus::Unavailable, Some(why));
403 };
404 let Some(manifest) = info.manifest.clone() else {
405 let why = info.error.unwrap_or_else(|| format!("{} isn't a valid template", pin.id));
406 return TemplateUpdateDiff::without_update(job, UpdateStatus::Unavailable, Some(why));
407 };
408 if manifest.version == pin.version && info.hash == pin.hash {
409 return TemplateUpdateDiff::without_update(job, UpdateStatus::None, None);
410 }
411 let mut diff = TemplateUpdateDiff::without_update(job, UpdateStatus::Available, None);
412 diff.to_version = manifest.version.clone();
413 diff.to_hash = info.hash.clone();
414 if info.state != JobTemplateState::Approved {
415 diff.status = UpdateStatus::NeedsApproval;
416 diff.reason = Some(format!("{} {} hasn't been approved yet: approve it to update this job", pin.id, manifest.version));
417 return diff;
418 }
419 let mut after = serde_json::to_value(job).unwrap_or_default();
421 after["template"] = json!({ "id": pin.id, "version": manifest.version, "hash": info.hash });
422 match apply_with(&mut after, job.template.as_ref(), svc) {
423 Err(e) => diff.params_error = Some(e),
424 Ok(()) => {
425 let new_brief = brief_of(&after);
426 let old_brief = brief_of(&serde_json::to_value(job).unwrap_or_default());
427 if old_brief != new_brief {
428 diff.brief = Some(TextChange { before: old_brief, after: new_brief });
429 }
430 let list = |v: &Value, key: &str, pick: fn(&Value) -> Option<String>| -> Vec<String> {
431 v.get(key).and_then(Value::as_array).into_iter().flatten().filter_map(pick).collect()
432 };
433 let name = |s: &Value| s.get("name").and_then(Value::as_str).map(str::to_string);
434 let plain = |s: &Value| s.as_str().map(str::to_string);
435 diff.outputs = ListChange::between(&job.outputs, &list(&after, "outputs", plain));
436 let old_secrets: Vec<String> = job.secrets.iter().map(|s| s.name.clone()).collect();
437 diff.secrets = ListChange::between(&old_secrets, &list(&after, "secrets", name));
438 let old_policy = serde_json::to_value(&job.policy).unwrap_or_default();
439 diff.policy = policy_changes(&old_policy, after.get("policy").unwrap_or(&Value::Null));
440 }
441 }
442 diff
443}
444
445pub fn brief_of(def: &Value) -> String {
447 let action = def.get("action").unwrap_or(&Value::Null);
448 let key = if text(action, "kind") == "task" { "payload" } else { "brief" };
449 text(action, key).to_string()
450}
451
452#[cfg(test)]
453#[path = "from_template_tests.rs"]
454mod tests;