Skip to main content

brep_app/automation/
command.rs

1//! The command registry and the wire envelope (Appendix A).
2//!
3//! A command is a [`CommandSpec`]: name, group, doc, the JSON Schemas of its
4//! argument and result types (derived with `schemars`), the frame phase it
5//! runs in, MCP-style annotations, and a handler. Each `cmd_*` module owns a
6//! `pub static COMMANDS: &[CommandSpec]`; [`registry`] gathers them. A host
7//! generates its tool list from [`describe`]; nothing lists commands by hand.
8use serde::{Deserialize, Serialize};
9use serde_json::Value;
10use brep_render::engine_state::EngineState;
11
12/// Where in the frame a command runs (§4.4).
13#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
14#[serde(rename_all = "snake_case")]
15pub enum Phase {
16    /// `raw_input_hook`: the handler emits `egui::Event`s.
17    Input,
18    /// Top of `ui`, before any panel draws.
19    Mutate,
20    /// Bottom of `ui`, after the state registry is rebuilt.
21    Read,
22}
23
24#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, schemars::JsonSchema)]
25pub struct Annotations {
26    pub read_only: bool,
27    pub destructive: bool,
28    pub idempotent: bool,
29    /// The host applies the idle contract (§6) before returning.
30    pub waits: bool,
31}
32
33impl Annotations {
34    pub const READ: Annotations = Annotations { read_only: true, destructive: false, idempotent: true, waits: false };
35    pub const INPUT: Annotations = Annotations { read_only: false, destructive: false, idempotent: false, waits: false };
36    pub const MUTATE: Annotations = Annotations { read_only: false, destructive: false, idempotent: false, waits: true };
37    pub const MUTATE_NOWAIT: Annotations = Annotations { read_only: false, destructive: false, idempotent: true, waits: false };
38    pub const DESTRUCTIVE: Annotations = Annotations { read_only: false, destructive: true, idempotent: false, waits: true };
39}
40
41/// What an app-phase handler sees.
42pub struct Ctx<'a> {
43    pub app: &'a mut crate::app::BrepApp,
44    pub egui: &'a egui::Context,
45}
46
47/// What a handler returns.
48pub enum Outcome {
49    Done(Value),
50    /// A JSON result plus a binary payload (a PNG) carried beside it.
51    Blob { json: Value, bytes: Vec<u8> },
52    /// The reply completes when `Event::Screenshot` with this token arrives.
53    /// `document` is the visible document's handle when the capture was asked
54    /// for; the capture is refused if another one is showing when it lands.
55    /// `ppp` is the window's density and `scale` the render scale over it
56    /// (1: the window's own frame).
57    AwaitScreenshot { token: u64, region: crate::automation::cmd_capture::Region, document: Option<String>, ppp: f32, scale: f32 },
58    /// Long work the command has STARTED without waiting for it: the queue
59    /// calls the poller once per frame in the command's phase, from the frame
60    /// thread, until it answers. A handler never waits inside a frame —
61    /// geometry, a PLM answer or a store write lands on later frames, and
62    /// the app keeps drawing and answering other commands meanwhile.
63    Poll(Poller),
64}
65
66/// See [`Outcome::Poll`]: `None` = not yet, `Some(result)` = the reply.
67pub type Poller = Box<dyn FnMut(&mut Ctx<'_>) -> Option<Result<Outcome, String>> + Send>;
68
69pub type InputHandler = fn(&mut crate::automation::pointer::Pointer, Value, &mut Vec<egui::Event>) -> Result<Value, String>;
70pub type AppHandler = fn(&mut Ctx<'_>, Value) -> Result<Outcome, String>;
71
72pub enum Handler {
73    Input(InputHandler),
74    App(AppHandler),
75}
76
77pub struct CommandSpec {
78    pub name: &'static str,
79    pub group: &'static str,
80    pub doc: &'static str,
81    pub phase: Phase,
82    pub annotations: Annotations,
83    pub args_schema: fn() -> Value,
84    pub result_schema: fn() -> Value,
85    pub handler: Handler,
86}
87
88/// One app-handled [`CommandSpec`] on one line:
89/// `app_command!(group, name, doc, Args, handler, Phase, ANNOTATIONS, result_schema)`.
90/// `Args` is the argument type (its schema is `schema_of::<Args>`), `Phase` and
91/// `ANNOTATIONS` name the [`Phase`] and [`Annotations`] constants. Leaving out
92/// `result_schema` declares the exactly-empty result ([`empty_result_schema`]).
93/// Input-phase commands, and any spec whose annotations or argument schema is
94/// not one of those shapes, stay written out as literals.
95macro_rules! app_command {
96    ($group:literal, $name:literal, $doc:expr, $args:ty, $handler:path, $phase:ident, $annotation:ident, $output:expr) => {
97        $crate::automation::command::CommandSpec {
98            name: $name,
99            group: $group,
100            doc: $doc,
101            phase: $crate::automation::command::Phase::$phase,
102            annotations: $crate::automation::command::Annotations::$annotation,
103            args_schema: $crate::automation::command::schema_of::<$args>,
104            result_schema: $output,
105            handler: $crate::automation::command::Handler::App($handler),
106        }
107    };
108    ($group:literal, $name:literal, $doc:expr, $args:ty, $handler:path, $phase:ident, $annotation:ident) => {
109        $crate::automation::command::app_command!($group, $name, $doc, $args, $handler, $phase, $annotation, $crate::automation::command::empty_result_schema)
110    };
111}
112pub(crate) use app_command;
113
114/// A mutate handler that parses its arguments, makes one engine call and
115/// answers the empty result: `engine_call(ctx, args, |e, a: Args| e.m(&a.id))`.
116/// The call's own value is dropped, its error is the command's error.
117pub fn engine_call<A, R, E>(ctx: &mut Ctx<'_>, args: Value, f: impl FnOnce(&mut EngineState, A) -> Result<R, E>) -> Result<Outcome, String>
118where
119    A: serde::de::DeserializeOwned,
120    String: From<E>,
121{
122    let a: A = parse_args(args)?;
123    f(ctx.app.docs.engine_mut(), a)?;
124    Ok(Outcome::Done(serde_json::json!({})))
125}
126
127/// A reader that takes no arguments and answers what `f` reads from the
128/// engine: `read_engine(ctx, args, |e| e.feature_catalogue())`.
129pub fn read_engine(ctx: &mut Ctx<'_>, args: Value, f: impl FnOnce(&EngineState) -> Value) -> Result<Outcome, String> {
130    let _: NoArgs = parse_args(args)?;
131    Ok(Outcome::Done(f(ctx.app.docs.engine())))
132}
133
134/// The JSON Schema of a type, as a `serde_json::Value`.
135///
136/// `schemars` renders an unconstrained value (e.g. a `serde_json::Value` field)
137/// as the boolean schema `true`. Strict MCP tool-schema validators (such as
138/// Claude Code's) reject a bare boolean where a schema object is expected, and
139/// that rejects the *whole* `tools/list` — one such field zeroes out every tool.
140/// So we normalize boolean subschemas to their object form before publishing.
141pub fn schema_of<T: schemars::JsonSchema>() -> Value {
142    let mut schema = serde_json::to_value(schemars::schema_for!(T)).unwrap_or(Value::Null);
143    normalize_bool_subschemas(&mut schema);
144    schema
145}
146
147/// A source-reviewed command whose successful native result is exactly `{}`.
148/// Use this only for genuinely empty payloads, never as a placeholder for an
149/// undeclared result. The MCP adapter adds its own envelope fields separately.
150pub fn empty_result_schema() -> Value {
151    serde_json::json!({
152        "type": "object",
153        "properties": {},
154        "additionalProperties": false,
155        "description": "No native application payload. The MCP adapter adds frame, optional notices and settlement information."
156    })
157}
158
159/// Replace boolean subschemas (`true`/`false` used where a schema *object* is
160/// expected — a `properties` member or `items`) with their object equivalents
161/// (`true` → `{}`, `false` → `{"not": {}}`). Legitimate booleans such as
162/// `additionalProperties` and `default` are left untouched.
163pub(super) fn normalize_bool_subschemas(node: &mut Value) {
164    match node {
165        Value::Object(map) => {
166            if let Some(Value::Object(props)) = map.get_mut("properties") {
167                for value in props.values_mut() {
168                    if let Some(b) = value.as_bool() {
169                        *value = if b { serde_json::json!({}) } else { serde_json::json!({"not": {}}) };
170                    }
171                }
172            }
173            if let Some(items) = map.get_mut("items") {
174                if let Some(b) = items.as_bool() {
175                    *items = if b { serde_json::json!({}) } else { serde_json::json!({"not": {}}) };
176                }
177            }
178            for value in map.values_mut() {
179                normalize_bool_subschemas(value);
180            }
181        }
182        Value::Array(arr) => {
183            for value in arr.iter_mut() {
184                normalize_bool_subschemas(value);
185            }
186        }
187        _ => {}
188    }
189}
190
191pub fn parse_args<T: serde::de::DeserializeOwned>(args: Value) -> Result<T, String> {
192    // A call with no arguments arrives as `null` or `{}`; both mean "none".
193    let args = if args.is_null() { Value::Object(Default::default()) } else { args };
194    serde_json::from_value(args).map_err(|e| format!("arguments: {e}"))
195}
196
197/// A command that takes nothing.
198#[derive(Debug, Default, Deserialize, schemars::JsonSchema)]
199#[serde(deny_unknown_fields)]
200pub struct NoArgs {}
201
202/// A command that returns nothing beyond the envelope.
203#[derive(Debug, Default, Serialize, schemars::JsonSchema)]
204pub struct Empty {}
205
206/// Every registered command, in module order. Each `cmd_*` module contributes
207/// its `COMMANDS` static; `tests/automation_registry.rs` walks the source tree
208/// for `static COMMANDS` declarations and fails if one is missing here, so this
209/// function cannot silently become a hand-kept subset.
210pub fn registry() -> Vec<&'static CommandSpec> {
211    use crate::automation::*;
212    let sets: &[&[CommandSpec]] = &[
213        cmd_frame::COMMANDS,
214        cmd_files::COMMANDS,
215        cmd_import_preview::COMMANDS,
216        cmd_perf::COMMANDS,
217        cmd_input::COMMANDS,
218        cmd_capture::COMMANDS,
219        cmd_state::COMMANDS,
220        cmd_document::COMMANDS,
221        cmd_classes::COMMANDS,
222        cmd_history::COMMANDS,
223        cmd_scene::COMMANDS,
224        cmd_camera::COMMANDS,
225        cmd_navigate::COMMANDS,
226        cmd_settings::COMMANDS,
227        cmd_sketch::COMMANDS,
228        cmd_shell::COMMANDS,
229        cmd_ui::COMMANDS,
230        cmd_plugins::COMMANDS,
231        cmd_metadata::COMMANDS,
232        cmd_assembly::COMMANDS,
233        cmd_pmi::COMMANDS,
234        cmd_sheets::COMMANDS,
235        cmd_wire_harness::COMMANDS,
236        cmd_cam::COMMANDS,
237        cmd_exploded::COMMANDS,
238        cmd_instructions::COMMANDS,
239        cmd_instructions_motion::COMMANDS,
240        cmd_simulation::COMMANDS,
241        cmd_simulation_play::COMMANDS,
242        cmd_cam_sim::COMMANDS,
243        cmd_ecad::COMMANDS,
244        #[cfg(not(target_arch = "wasm32"))]
245        cmd_plm::COMMANDS,
246        #[cfg(not(target_arch = "wasm32"))]
247        cmd_kicad::COMMANDS,
248    ];
249    sets.iter().flat_map(|s| s.iter()).collect()
250}
251
252pub fn lookup(name: &str) -> Option<&'static CommandSpec> {
253    registry().into_iter().find(|c| c.name == name)
254}
255
256/// The registry as JSON — what a host turns into `tools/list` and what the
257/// generated docs render: `[{name, group, doc, phase, annotations, argsSchema, resultSchema}]`.
258pub fn describe() -> Value {
259    Value::Array(
260        registry()
261            .into_iter()
262            .map(|c| {
263                serde_json::json!({
264                    "name": c.name,
265                    "group": c.group,
266                    "doc": c.doc,
267                    "phase": c.phase,
268                    "annotations": c.annotations,
269                    "argsSchema": (c.args_schema)(),
270                    "resultSchema": (c.result_schema)(),
271                })
272            })
273            .collect(),
274    )
275}
276
277// --- wire -------------------------------------------------------------------
278
279#[derive(Debug, Clone, Serialize, Deserialize)]
280pub struct Envelope {
281    pub id: u64,
282    pub cmd: String,
283    #[serde(default)]
284    pub args: Value,
285}
286
287#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
288#[serde(rename_all = "snake_case")]
289pub enum NoticeKind {
290    Panic,
291    LogError,
292    RunnerRefusal,
293    Toast,
294    Console,
295}
296
297#[derive(Debug, Clone, Serialize, Deserialize, schemars::JsonSchema)]
298pub struct Notice {
299    pub kind: NoticeKind,
300    pub frame: u64,
301    pub text: String,
302}
303
304#[derive(Debug, Clone, Default, Serialize, Deserialize)]
305pub struct Reply {
306    pub id: u64,
307    pub frame: u64,
308    pub ok: bool,
309    #[serde(default, skip_serializing_if = "Option::is_none")]
310    pub result: Option<Value>,
311    #[serde(default, skip_serializing_if = "Option::is_none")]
312    pub error: Option<String>,
313    #[serde(default, skip_serializing_if = "Vec::is_empty")]
314    pub notices: Vec<Notice>,
315    /// A binary payload beside the JSON (a PNG). In-process hosts pass it
316    /// through; the dial-in adapter sends it as a binary frame.
317    #[serde(skip)]
318    pub blob: Option<Vec<u8>>,
319}
320
321impl Reply {
322    pub fn ok(id: u64, frame: u64, result: Value, notices: Vec<Notice>) -> Self {
323        Self { id, frame, ok: true, result: Some(result), error: None, notices, blob: None }
324    }
325    pub fn err(id: u64, frame: u64, error: impl Into<String>, notices: Vec<Notice>) -> Self {
326        Self { id, frame, ok: false, result: None, error: Some(error.into()), notices, blob: None }
327    }
328
329    /// This reply in the MCP host protocol's shape: the same JSON, the blob
330    /// beside it. The one conversion the window embed (`mcp.rs`), the WebMCP
331    /// host (`webmcp.rs`) and BREP_mcp's headless host all make; the two
332    /// `Reply` types stay mirrored because `brep_mcp_core` must not depend on
333    /// the app (`BREP_mcp_core/src/host.rs`).
334    pub fn into_host(mut self) -> brep_mcp_core::host::Reply {
335        use brep_mcp_core::host::Reply as HostReply;
336        let blob = self.blob.take();
337        let (id, frame) = (self.id, self.frame);
338        match serde_json::to_value(&self).map_err(|e| e.to_string()).and_then(|v| HostReply::from_app(v, blob)) {
339            Ok(reply) => reply,
340            Err(e) => HostReply::err(id, frame, e),
341        }
342    }
343}
344