//! Resolve an installed package act on the writer, then run its shared engine. use super::*; use crate::mcp::handlers::common::{now_ms, today_in, workspace_timezone}; use cotton_core::definitions::{acts, automations::expressions}; use cotton_store::mint::Held; pub fn run_record_act(ctx: &mut Ctx<'_>, args: &Map) -> ToolResult { atomically_noted(ctx, |ctx| { let table = definition(ctx, &id_arg(args, "table")?)?; let id = id_arg(args, "id")?; let name = id_arg(args, "act")?; let tool = super::super::tool_packages::live_tool_definitions(ctx)? .into_iter() .find(|tool| tool.tables.contains(&table.id)) .ok_or_else(|| ToolFailure::new("act table belongs to no installed tool"))?; let tables = tool .tables .iter() .map(|id| definition(ctx, id)) .collect::>>()?; cotton_core::definitions::automations::validate_tables(&tool, &tables) .map_err(ToolFailure::new)?; let act = table .acts .iter() .flatten() .find(|act| act.id == name) .ok_or_else(|| ToolFailure::new("table has no such package act"))?; let mut stored = load_live(ctx, &table, &id)?; if table.has_computed() { computed_in_step(ctx)?; with_computed(ctx, &table, std::slice::from_mut(&mut stored))?; } for column in &table.columns { stored.data.entry(column.key.clone()).or_insert(Value::Null); } stored.data.insert("id".into(), Value::String(id.clone())); if !act.offered_on(&Value::Object(stored.data.clone())) { return Err(ToolFailure::new("act is no longer offered for this record")); } match act.verb.as_deref() { Some("set") => { let (set, _) = acts::set(act).map_err(ToolFailure::new)?; let now = now_iso(ctx); let today = today_in(&workspace_timezone(ctx)?, now_ms(ctx))?; let value = expressions::evaluate_at(&set.value, &stored.data, &now, &today) .map_err(ToolFailure::new)?; let claim = tool .reserve .as_ref() .is_some_and(|r| r.claim_table == table.id); if claim && ctx.writer_held() != Some(Held::Served) { return Err(ToolFailure::new( "reservation acts run on the serving machine", )); } let writing = claim.then(reservations::Writing::enter); let answer = update_record_now( ctx, json!({"table":table.id,"id":id,"patch":{set.column:value}}) .as_object() .unwrap(), )?; drop(writing); automations::run(ctx, answer) } Some(verb @ ("reserve_record" | "cancel_reservation" | "create")) => { let mut bound: Map = act .data .iter() .flat_map(|data| data.iter()) .map(|(k, v)| (k.clone(), v.clone())) .collect(); for (argument, column) in act.bindings.iter().flat_map(|data| data.iter()) { let value = if column == "$id" { Value::String(id.clone()) } else { stored.data.get(column).cloned().ok_or_else(|| { ToolFailure::new("act binding names an absent column") })? }; put(&mut bound, argument, value)?; } let picked_list = if let Some(picks) = &act.picks { let values = args.get("picked").and_then(Value::as_array) .ok_or_else(|| ToolFailure::new("act needs an ordered list of picked values"))?; if values.len() != picks.len() { return Err(ToolFailure::new("act needs one value for each pick")); } Some(values) } else { None }; for (index, pick) in act.ordered_picks().iter().enumerate() { let supplied = picked_list.map(|values| &values[index]).or_else(|| args.get("picked")); if pick.kind == cotton_core::definitions::PickKind::Number { let value = pick .number_value(supplied) .map_err(ToolFailure::new)?; put(&mut bound, &pick.argument, value)?; } else { let value = supplied .cloned() .or_else(|| (pick.optional == Some(true)).then(|| json!(""))) .ok_or_else(|| ToolFailure::new("act needs the picked value"))?; let text = value .as_str() .ok_or_else(|| ToolFailure::new("act pick must be a string"))?; match pick.kind { cotton_core::definitions::PickKind::Record => { let target = definition(ctx, pick.table.as_deref().unwrap_or_default())?; let picked = load_live(ctx, &target, text)?; if !pick.accepts_on(&Value::Object(picked.data), Some(&id)) { return Err(ToolFailure::new( "that record is no longer a choice for this act", )); } } cotton_core::definitions::PickKind::Datetime => { chrono::DateTime::parse_from_rfc3339(text).map_err(|_| { ToolFailure::new("act needs an ISO 8601 moment") })?; } cotton_core::definitions::PickKind::Text if !text.trim().is_empty() || pick.optional == Some(true) => {} _ => return Err(ToolFailure::new("act needs the picked value")), } if !(pick.kind == cotton_core::definitions::PickKind::Text && pick.optional == Some(true) && text.trim().is_empty()) { put(&mut bound, &pick.argument, value)?; } } } if verb == "create" { bound.insert( "table".into(), Value::String(acts::create_table(act).map_err(ToolFailure::new)?.into()), ); bound.entry("data").or_insert(json!({})); let answer = create_record_now(ctx, &bound)?; return automations::run(ctx, answer); } bound.insert("tool".into(), Value::String(tool.id)); if verb == "reserve_record" { // Taken on the slot itself, or on its item with the slot picked. bound.entry("slot").or_insert(Value::String(id)); bound.entry("data").or_insert(json!({})); reservations::reserve_record(ctx, &bound) } else { bound.insert("id".into(), Value::String(id)); reservations::cancel_reservation(ctx, &bound) } } _ => Err(ToolFailure::new("unknown package act")), } }) } fn put(args: &mut Map, path: &str, value: Value) -> Valid<()> { if let Some((head, tail)) = path.split_once('.') { let nested = args .entry(head.to_string()) .or_insert(json!({})) .as_object_mut() .ok_or_else(|| ToolFailure::new("act argument is not an object"))?; put(nested, tail, value) } else { args.insert(path.into(), value); Ok(()) } }