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,
73 Reply(String),
77}
78
79#[derive(Debug, Clone, PartialEq, Eq)]
81pub struct Proposal {
82 pub label: String,
83 pub kind: ProposalKind,
84}
85
86impl Proposal {
87 pub fn restart(label: impl Into<String>) -> Self {
90 Self {
91 label: label.into(),
92 kind: ProposalKind::Restart,
93 }
94 }
95
96 pub fn reply(text: impl Into<String>) -> Self {
98 let text = text.into();
99 Self {
100 label: text.clone(),
101 kind: ProposalKind::Reply(text),
102 }
103 }
104
105 pub fn is_reply(&self) -> bool {
107 matches!(self.kind, ProposalKind::Reply(_))
108 }
109
110 pub fn is_executable(&self) -> bool {
113 matches!(self.kind, ProposalKind::Restart)
114 }
115
116 pub fn insert_text(&self) -> Option<String> {
118 match &self.kind {
119 ProposalKind::Shell(cmd) => Some(format!("!{cmd}")),
120 ProposalKind::Slash(cmd) => Some(format!("/{cmd}")),
121 ProposalKind::Reply(text) => Some(text.clone()),
122 ProposalKind::Restart => None,
123 }
124 }
125}
126
127#[derive(Debug, Clone, PartialEq, Eq)]
130pub enum VetError {
131 NotAnObject,
132 MissingField(&'static str),
133 UnknownKind(String),
134 EmptyField(&'static str),
135 TooLong { field: &'static str, max: usize },
136 ControlChar(&'static str),
137 Placeholder { field: &'static str, token: String },
138 SecretShaped(&'static str),
139 RestartTakesNoCommand,
140}
141
142impl fmt::Display for VetError {
143 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
144 match self {
145 Self::NotAnObject => write!(f, "propose: arguments must be a JSON object"),
146 Self::MissingField(k) => write!(f, "propose: `{k}` is required"),
147 Self::UnknownKind(k) => write!(
148 f,
149 "propose: kind `{k}` is not allowed; use one of {}",
150 KINDS.join(", ")
151 ),
152 Self::EmptyField(k) => write!(f, "propose: `{k}` must not be empty"),
153 Self::TooLong { field, max } => {
154 write!(f, "propose: `{field}` is longer than {max} characters")
155 }
156 Self::ControlChar(k) => write!(
157 f,
158 "propose: `{k}` contains a newline or control character; propose one single-line command"
159 ),
160 Self::Placeholder { field, token } => write!(
161 f,
162 "propose: `{field}` contains the placeholder `{token}`; write the concrete value"
163 ),
164 Self::SecretShaped(k) => write!(
165 f,
166 "propose: `{k}` looks like it contains a secret; never put credentials in a proposal"
167 ),
168 Self::RestartTakesNoCommand => write!(
169 f,
170 "propose: `restart` takes no `command`; it always restarts you, the proposing agent"
171 ),
172 }
173 }
174}
175
176impl std::error::Error for VetError {}
177
178pub fn vet(args: &serde_json::Value) -> Result<Proposal, VetError> {
184 let obj = args.as_object().ok_or(VetError::NotAnObject)?;
185 let label = str_field(obj, "label")?.ok_or(VetError::MissingField("label"))?;
186 let kind = str_field(obj, "kind")?.ok_or(VetError::MissingField("kind"))?;
187 let command = str_field(obj, "command")?;
188
189 check_text("label", label, LABEL_MAX_CHARS)?;
190
191 let kind = match kind {
192 KIND_RESTART => {
193 if command.is_some() {
194 return Err(VetError::RestartTakesNoCommand);
195 }
196 ProposalKind::Restart
197 }
198 KIND_SHELL | KIND_SLASH => {
199 let raw = command.ok_or(VetError::MissingField("command"))?;
200 if raw.chars().any(char::is_control) {
203 return Err(VetError::ControlChar("command"));
204 }
205 let prefix = if kind == KIND_SHELL { '!' } else { '/' };
207 let cmd = raw.trim().strip_prefix(prefix).unwrap_or(raw.trim()).trim();
208 check_text("command", cmd, COMMAND_MAX_CHARS)?;
209 if kind == KIND_SHELL {
210 ProposalKind::Shell(cmd.to_string())
211 } else {
212 ProposalKind::Slash(cmd.to_string())
213 }
214 }
215 other => return Err(VetError::UnknownKind(other.to_string())),
216 };
217
218 Ok(Proposal {
219 label: label.trim().to_string(),
220 kind,
221 })
222}
223
224fn str_field<'a>(
225 obj: &'a serde_json::Map<String, serde_json::Value>,
226 key: &'static str,
227) -> Result<Option<&'a str>, VetError> {
228 match obj.get(key) {
229 None | Some(serde_json::Value::Null) => Ok(None),
230 Some(serde_json::Value::String(s)) => Ok(Some(s.as_str())),
231 Some(_) => Err(VetError::MissingField(key)),
232 }
233}
234
235fn check_text(field: &'static str, s: &str, max: usize) -> Result<(), VetError> {
236 if s.chars().any(char::is_control) {
237 return Err(VetError::ControlChar(field));
238 }
239 if s.trim().is_empty() {
240 return Err(VetError::EmptyField(field));
241 }
242 if s.chars().count() > max {
243 return Err(VetError::TooLong { field, max });
244 }
245 if let Some(token) = find_placeholder(s) {
246 return Err(VetError::Placeholder { field, token });
247 }
248 if matches!(crate::redact::redact_secrets(s), std::borrow::Cow::Owned(_)) {
249 return Err(VetError::SecretShaped(field));
250 }
251 Ok(())
252}
253
254fn find_placeholder(s: &str) -> Option<String> {
257 use regex_lite::Regex;
258 use std::sync::OnceLock;
259 static RX: OnceLock<Regex> = OnceLock::new();
260 let rx = RX.get_or_init(|| {
261 Regex::new(r"<[A-Za-z_][A-Za-z0-9_-]*>|(^|[^$])(\{\{?[A-Za-z_][A-Za-z0-9_-]*\}\}?)")
262 .expect("static placeholder regex")
263 });
264 let caps = rx.captures(s)?;
265 let m = caps.get(2).or_else(|| caps.get(0))?;
266 Some(m.as_str().to_string())
267}
268
269#[cfg(test)]
270#[path = "proposal_tests.rs"]
271mod tests;