1use std::fmt;
24
25pub const PROPOSE_TOOL: &str = "propose";
27
28pub const LABEL_MAX_CHARS: usize = 80;
30
31pub const COMMAND_MAX_CHARS: usize = 500;
33
34pub const KIND_SHELL: &str = "shell";
36pub const KIND_SLASH: &str = "slash";
37pub const KIND_RESTART: &str = "restart";
38
39pub const KINDS: [&str; 3] = [KIND_SHELL, KIND_SLASH, KIND_RESTART];
41
42pub const PROPOSAL_MIME: &str = "application/vnd.mur.proposal+json";
47
48pub fn restart_args(label: &str) -> serde_json::Value {
50 serde_json::json!({ "label": label, "kind": KIND_RESTART })
51}
52
53pub fn attached(parts: &serde_json::Value) -> Option<Proposal> {
56 parts
57 .as_array()?
58 .iter()
59 .rev()
60 .filter(|p| p.get("mimeType").and_then(|m| m.as_str()) == Some(PROPOSAL_MIME))
61 .find_map(|p| vet(p.get("data")?).ok())
62}
63
64#[derive(Debug, Clone, PartialEq, Eq)]
66pub enum ProposalKind {
67 Shell(String),
69 Slash(String),
71 Restart,
74 Reply(String),
78}
79
80#[derive(Debug, Clone, PartialEq, Eq)]
82pub struct Proposal {
83 pub label: String,
84 pub kind: ProposalKind,
85}
86
87impl Proposal {
88 pub fn restart(label: impl Into<String>) -> Self {
91 Self {
92 label: label.into(),
93 kind: ProposalKind::Restart,
94 }
95 }
96
97 pub fn reply(text: impl Into<String>) -> Self {
99 let text = text.into();
100 Self {
101 label: text.clone(),
102 kind: ProposalKind::Reply(text),
103 }
104 }
105
106 pub fn is_reply(&self) -> bool {
108 matches!(self.kind, ProposalKind::Reply(_))
109 }
110
111 pub fn restart_command(agent: &str) -> String {
113 format!("mur agent restart {agent}")
114 }
115
116 pub fn insert_text(&self, agent: &str) -> String {
120 match &self.kind {
121 ProposalKind::Shell(cmd) => format!("!{cmd}"),
122 ProposalKind::Slash(cmd) => format!("/{cmd}"),
123 ProposalKind::Reply(text) => text.clone(),
124 ProposalKind::Restart => format!("!{}", Self::restart_command(agent)),
125 }
126 }
127}
128
129#[derive(Debug, Clone, PartialEq, Eq)]
132pub enum VetError {
133 NotAnObject,
134 MissingField(&'static str),
135 UnknownKind(String),
136 EmptyField(&'static str),
137 TooLong { field: &'static str, max: usize },
138 ControlChar(&'static str),
139 Placeholder { field: &'static str, token: String },
140 SecretShaped(&'static str),
141 RestartTakesNoCommand,
142}
143
144impl fmt::Display for VetError {
145 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
146 match self {
147 Self::NotAnObject => write!(f, "propose: arguments must be a JSON object"),
148 Self::MissingField(k) => write!(f, "propose: `{k}` is required"),
149 Self::UnknownKind(k) => write!(
150 f,
151 "propose: kind `{k}` is not allowed; use one of {}",
152 KINDS.join(", ")
153 ),
154 Self::EmptyField(k) => write!(f, "propose: `{k}` must not be empty"),
155 Self::TooLong { field, max } => {
156 write!(f, "propose: `{field}` is longer than {max} characters")
157 }
158 Self::ControlChar(k) => write!(
159 f,
160 "propose: `{k}` contains a newline or control character; propose one single-line command"
161 ),
162 Self::Placeholder { field, token } => write!(
163 f,
164 "propose: `{field}` contains the placeholder `{token}`; write the concrete value"
165 ),
166 Self::SecretShaped(k) => write!(
167 f,
168 "propose: `{k}` looks like it contains a secret; never put credentials in a proposal"
169 ),
170 Self::RestartTakesNoCommand => write!(
171 f,
172 "propose: `restart` takes no `command`; it always restarts you, the proposing agent"
173 ),
174 }
175 }
176}
177
178impl std::error::Error for VetError {}
179
180pub fn vet(args: &serde_json::Value) -> Result<Proposal, VetError> {
186 let obj = args.as_object().ok_or(VetError::NotAnObject)?;
187 let label = str_field(obj, "label")?.ok_or(VetError::MissingField("label"))?;
188 let kind = str_field(obj, "kind")?.ok_or(VetError::MissingField("kind"))?;
189 let command = str_field(obj, "command")?;
190
191 check_text("label", label, LABEL_MAX_CHARS)?;
192
193 let kind = match kind {
194 KIND_RESTART => {
195 if command.is_some() {
196 return Err(VetError::RestartTakesNoCommand);
197 }
198 ProposalKind::Restart
199 }
200 KIND_SHELL | KIND_SLASH => {
201 let raw = command.ok_or(VetError::MissingField("command"))?;
202 if raw.chars().any(char::is_control) {
205 return Err(VetError::ControlChar("command"));
206 }
207 let prefix = if kind == KIND_SHELL { '!' } else { '/' };
209 let cmd = raw.trim().strip_prefix(prefix).unwrap_or(raw.trim()).trim();
210 check_text("command", cmd, COMMAND_MAX_CHARS)?;
211 if kind == KIND_SHELL {
212 ProposalKind::Shell(cmd.to_string())
213 } else {
214 ProposalKind::Slash(cmd.to_string())
215 }
216 }
217 other => return Err(VetError::UnknownKind(other.to_string())),
218 };
219
220 Ok(Proposal {
221 label: label.trim().to_string(),
222 kind,
223 })
224}
225
226fn str_field<'a>(
227 obj: &'a serde_json::Map<String, serde_json::Value>,
228 key: &'static str,
229) -> Result<Option<&'a str>, VetError> {
230 match obj.get(key) {
231 None | Some(serde_json::Value::Null) => Ok(None),
232 Some(serde_json::Value::String(s)) => Ok(Some(s.as_str())),
233 Some(_) => Err(VetError::MissingField(key)),
234 }
235}
236
237fn check_text(field: &'static str, s: &str, max: usize) -> Result<(), VetError> {
238 if s.chars().any(char::is_control) {
239 return Err(VetError::ControlChar(field));
240 }
241 if s.trim().is_empty() {
242 return Err(VetError::EmptyField(field));
243 }
244 if s.chars().count() > max {
245 return Err(VetError::TooLong { field, max });
246 }
247 if let Some(token) = find_placeholder(s) {
248 return Err(VetError::Placeholder { field, token });
249 }
250 if matches!(crate::redact::redact_secrets(s), std::borrow::Cow::Owned(_)) {
251 return Err(VetError::SecretShaped(field));
252 }
253 Ok(())
254}
255
256fn find_placeholder(s: &str) -> Option<String> {
259 use regex_lite::Regex;
260 use std::sync::OnceLock;
261 static RX: OnceLock<Regex> = OnceLock::new();
262 let rx = RX.get_or_init(|| {
263 Regex::new(r"<[A-Za-z_][A-Za-z0-9_-]*>|(^|[^$])(\{\{?[A-Za-z_][A-Za-z0-9_-]*\}\}?)")
264 .expect("static placeholder regex")
265 });
266 let caps = rx.captures(s)?;
267 let m = caps.get(2).or_else(|| caps.get(0))?;
268 Some(m.as_str().to_string())
269}
270
271#[cfg(test)]
272#[path = "proposal_tests.rs"]
273mod tests;