diff --git a/CHANGELOG.md b/CHANGELOG.md index 8df72e7..77600f2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,29 @@ The release also adds public invoke types rather than changing existing ones: `g `Registry::merge_live_table`, `registry_from_invoke_table`, `op_schema_from_invoke` and `schema_file_json_from_invoke_table`. +- **Per-app recipe schemas: `gpui-agent recipe schema`.** Prints `schemas/recipe.v1.schema.json` + specialized for an app's invokes, so an editor or any JSON Schema validator can check an invoke + step's `args` before `recipe validate` runs. The generic `invoke` step branch is replaced by one + branch per invoke the registry knows: `name` pinned as a `const`, `args` built from the argument + specs (top-level types, `required` the union of the schema's list and the specs marked required, + embedded per-argument JSON Schemas reflected and composed with the type, closed + `additionalProperties` when the invoke lists its args — including `"args": {}` — and open when it + does not), a string holding a `$param` placeholder admitted for every typed argument, the `args` + key itself required when the invoke has required arguments, and `null` accepted when it has none — + mirroring validation reading missing or null `args` as `{}`. The invoke metadata is the same + registry validation uses: `--schema` files offline, the live host table merged in when a target is + named on the command line — never from ambient `GPUI_AGENT_ADDR`/`GPUI_AGENT_SESSION` alone. + `gpui-agent-recipe` gains the public `base_recipe_schema` and `recipe_schema_for_registry`; the + base schema is embedded in the crate (a test keeps it byte-identical to the workspace file) so the + published binary carries it. Generation compiles the schema offline before printing, and embedded + argument schemas using internal `$ref`/`$dynamicRef` keep their resource semantics through a + preserved or generated deterministic `urn:` `$id`. A recursive generated probe mirrors validation's + nested-placeholder escape hatch for embedded object/array arguments. The generated schema stays an + editor aid: exact `$$` escaping and `$.node` reference rules, unknown `needs`, cycles and + param usage remain `recipe validate`'s job, and the one-directional contract (what validation + accepts, the schema accepts) is pinned by the document-level parity test against the generated todo + schema. + - **Host-declared invoke tables.** A host declares each invoke once — name, description, effects, argument specs — in `AgentHost::invokes`, and everything reads the one table: the read-only `invokes` op serves it (`AgentClient::invoke_table` parses it), the shared dispatch runs diff --git a/crates/gpui-agent-cli/src/main.rs b/crates/gpui-agent-cli/src/main.rs index 72e4c7a..17ac0ee 100644 --- a/crates/gpui-agent-cli/src/main.rs +++ b/crates/gpui-agent-cli/src/main.rs @@ -121,7 +121,7 @@ const AFTER_HELP: &str = "\ App-specific helpers (for example the sample todo app) live in examples/, not in this CLI. Navigate pages with click + assert on stable ids, or invoke a command the host registered. Batch many ops in one process -with `recipe validate|plan|run` (JSON canonical; `.wants` also +with `recipe validate|plan|schema|run` (JSON canonical; `.wants` also accepted — see docs/RECIPES.md). Host bind is default-deny: set GPUI_AGENT_TOKEN on the host. `recipe run` and `mcp` require a non-empty GPUI_AGENT_TOKEN or --token; set the same value on the host. Non-loopback @@ -761,7 +761,7 @@ fn require_recipe_mcp_token(token: Option<&str>) -> Result<&str> { /// True when the user aimed the CLI at a host — `--addr`, `--connect` or /// `--session` typed on the command line. The read-only recipe commands -/// (validate/plan/resolve) stay offline without one; with one they read +/// (validate/plan/schema/resolve) stay offline without one; with one they read /// the host's live invoke table so validation matches what the app /// would actually answer. Only the command line counts: the matching /// environment variables are ambient — often set for a whole shell or CI @@ -814,6 +814,7 @@ fn run() -> Result<()> { Command::Recipe { action: RecipeCommand::Validate { .. } | RecipeCommand::Plan { .. } + | RecipeCommand::Schema | RecipeCommand::Resolve { .. }, .. } @@ -930,7 +931,7 @@ fn run() -> Result<()> { })?; Some(connect(addr, request_timeout).with_token(token)) } else { - // validate/plan/resolve reach the connected path only when the + // validate/plan/schema/resolve reach the connected path only when the // user named a target (`--addr` / `--connect` / `--session`): // validate against the live table. The token is used when one // is configured but never required — unless the host itself @@ -1785,7 +1786,7 @@ mod tests { "help should not list a todo subcommand:\n{help}" ); assert!( - help.contains("recipe validate|plan|run"), + help.contains("recipe validate|plan|schema|run"), "top-level help should point at recipes:\n{help}" ); } @@ -1819,7 +1820,7 @@ mod tests { ); let help = recipe.render_long_help().to_string(); - for name in ["validate", "plan", "run", "resolve"] { + for name in ["validate", "plan", "run", "schema", "resolve"] { assert!(help.contains(name), "missing {name} in:\n{help}"); } let validate = recipe.find_subcommand("validate").expect("validate"); @@ -2141,6 +2142,19 @@ mod tests { other => panic!("unexpected {other:?}"), } + let schema_cmd = Cli::try_parse_from(["gpui-agent", "recipe", "schema"]).unwrap(); + assert!( + matches!( + schema_cmd.command, + Command::Recipe { + action: RecipeCommand::Schema, + .. + } + ), + "unexpected {:?}", + schema_cmd.command + ); + let with_schema = Cli::try_parse_from([ "gpui-agent", "recipe", diff --git a/crates/gpui-agent-cli/src/recipe_cmd.rs b/crates/gpui-agent-cli/src/recipe_cmd.rs index 36dcb74..233a171 100644 --- a/crates/gpui-agent-cli/src/recipe_cmd.rs +++ b/crates/gpui-agent-cli/src/recipe_cmd.rs @@ -6,9 +6,9 @@ use clap::Subcommand; use gpui_agent::CallFailure; use gpui_agent::client::AgentClient; use gpui_agent_recipe::{ - RecipeError, RecipeErrorCode, RunError, RunOptions, ScreenshotCapture, compile_plan, - merge_live_invokes, order_check, parse_recipe, registry_from_schema_paths, resolve_intent, - run_plan, validate_recipe, + RecipeError, RecipeErrorCode, RunError, RunOptions, ScreenshotCapture, base_recipe_schema, + compile_plan, merge_live_invokes, order_check, parse_recipe, recipe_schema_for_registry, + registry_from_schema_paths, resolve_intent, run_plan, validate_recipe, }; #[derive(Debug, Subcommand)] @@ -50,6 +50,10 @@ pub(crate) enum RecipeCommand { #[arg(long)] screenshot_flagged: bool, }, + /// Print the recipe JSON Schema specialized for the app's invokes: one + /// `invoke` branch per invoke the registry knows, for editors. Offline + /// without a target; reads the live invoke table when one is named. + Schema, /// \[experimental\] Map a natural-language intent through the local schema registry. Resolve { intent: String }, } @@ -78,12 +82,19 @@ pub(crate) fn run( let mut registry = registry_from_schema_paths(schema_paths).map_err(anyhow::Error::new)?; if let Some(client) = client.as_mut() { // A client means a target host was chosen (`recipe run` always has - // one; validate/plan/resolve only when the user named a target): - // the live table is authoritative for every invoke it names, and - // a host without one leaves the files exactly as they were. + // one; validate/plan/schema/resolve only when the user named a + // target): the live table is authoritative for every invoke it + // names, and a host without one leaves the files exactly as they + // were. merge_live_invokes(&mut registry, client).map_err(anyhow::Error::new)?; } match command { + RecipeCommand::Schema => { + let schema = recipe_schema_for_registry(&base_recipe_schema(), ®istry) + .map_err(anyhow::Error::new)?; + println!("{}", serde_json::to_string_pretty(&schema)?); + Ok(()) + } RecipeCommand::Validate { path } => { let recipe = parse_recipe(&path).map_err(anyhow::Error::new)?; validate_recipe(&recipe, ®istry).map_err(anyhow::Error::new)?; diff --git a/crates/gpui-agent-cli/tests/recipe_live_schema.rs b/crates/gpui-agent-cli/tests/recipe_live_schema.rs index 35bc260..1732dc6 100644 --- a/crates/gpui-agent-cli/tests/recipe_live_schema.rs +++ b/crates/gpui-agent-cli/tests/recipe_live_schema.rs @@ -599,3 +599,153 @@ fn mcp_recipe_validate_reads_the_live_table() { serde_json::from_str(reply["result"]["content"][0]["text"].as_str().unwrap()).unwrap(); assert_eq!(text["ok"], true, "{text}"); } + +/// Invoke names carried by a printed `recipe schema` document: one branch +/// per invoke the registry behind the command knew. +fn schema_invoke_names(schema: &Value) -> Vec<&str> { + schema["$defs"]["step"]["oneOf"] + .as_array() + .expect("step variants") + .iter() + .filter(|branch| branch["properties"]["op"]["const"] == "invoke") + .map(|branch| { + branch["properties"]["name"]["const"] + .as_str() + .expect("every generated invoke branch pins its name") + }) + .collect() +} + +#[test] +fn schema_is_offline_without_a_target() { + let runtime = RuntimeRoot::new(); + let _live = Probe::spawn(None); + + // No --addr/--connect/--session and no --schema: nothing dials out, + // so no invoke branch exists at all — `probe.echo` least of all, + // although the host answering it is right there. + let output = cli(&runtime, &["recipe", "schema"]); + assert!( + output.status.success(), + "offline schema failed: {}", + stderr(&output) + ); + let schema: Value = serde_json::from_str(&stdout(&output)).expect("schema json"); + assert!( + schema_invoke_names(&schema).is_empty(), + "an invokeless registry replaces the generic branch with nothing: {}", + schema_invoke_names(&schema).join(", ") + ); +} + +#[test] +fn schema_reads_the_live_table_when_addr_is_supplied() { + let runtime = RuntimeRoot::new(); + let live = Probe::spawn(None); + + // The host's own table is the whole source: `probe.echo` is in no + // schema file anywhere, so only a live read can grow its branch. + let output = cli( + &runtime, + &["--addr", live.addr.as_str(), "recipe", "schema"], + ); + assert!( + output.status.success(), + "live schema failed: {}", + stderr(&output) + ); + let schema: Value = serde_json::from_str(&stdout(&output)).expect("schema json"); + let names = schema_invoke_names(&schema); + assert!( + names.contains(&PROBE_NAME), + "the live-only probe must be a branch: {}", + names.join(", ") + ); + let probe = schema["$defs"]["step"]["oneOf"] + .as_array() + .expect("step variants") + .iter() + .find(|branch| branch["properties"]["name"]["const"] == PROBE_NAME) + .expect("probe.echo branch"); + assert_eq!( + probe["properties"]["args"]["required"], + serde_json::json!(["note"]), + "the live table's required arg is the branch's: {probe}" + ); + assert_eq!( + probe["properties"]["args"]["properties"]["note"]["type"], + serde_json::json!("string"), + "{probe}" + ); +} + +#[test] +fn schema_takes_invoke_metadata_from_schema_files() { + let runtime = RuntimeRoot::new(); + let todo = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../examples/schemas/todo.json") + .canonicalize() + .expect("the workspace has examples/schemas/todo.json"); + + // Offline, the exported schema file is the invoke metadata source. + let output = cli( + &runtime, + &[ + "recipe", + "schema", + "--schema", + todo.to_str().expect("utf-8 path"), + ], + ); + assert!( + output.status.success(), + "file schema failed: {}", + stderr(&output) + ); + let schema: Value = serde_json::from_str(&stdout(&output)).expect("schema json"); + let names = schema_invoke_names(&schema); + for expected in ["todo.add", "todo.toggle", "todo.list"] { + assert!( + names.contains(&expected), + "{expected} must be a branch: {}", + names.join(", ") + ); + } + assert!( + !names.contains(&PROBE_NAME), + "the live-only probe is in no file: {}", + names.join(", ") + ); +} + +#[test] +fn ambient_target_env_vars_do_not_turn_schema_into_a_dial_out() { + let runtime = RuntimeRoot::new(); + + // GPUI_AGENT_ADDR/CONNECT/SESSION are ambient shell state, sometimes + // stale. Pointing them at a dead port, a missing app and a missing + // session, `recipe schema` stays offline exactly like validate: no + // dial-out, no failure, files only. + let output = Command::new(env!("CARGO_BIN_EXE_gpui-agent")) + .args(["recipe", "schema"]) + .env("GPUI_AGENT_RUNTIME_DIR", runtime.path()) + .env("GPUI_AGENT_ADDR", "127.0.0.1:9") + .env("GPUI_AGENT_CONNECT", "missing-app") + .env("GPUI_AGENT_SESSION", "missing") + .env_remove("GPUI_AGENT_TOKEN") + .env_remove("GPUI_AGENT_SCHEMA") + .env_remove("GPUI_AGENT_ALLOW_REMOTE") + .output() + .expect("spawn gpui-agent"); + assert!( + output.status.success(), + "ambient env must not dial out: {}", + stderr(&output) + ); + let schema: Value = serde_json::from_str(&stdout(&output)).expect("schema json"); + assert!( + schema_invoke_names(&schema).is_empty(), + "offline without files, no invoke branches: {}", + schema_invoke_names(&schema).join(", ") + ); +} diff --git a/crates/gpui-agent-recipe/schemas/recipe.v1.schema.json b/crates/gpui-agent-recipe/schemas/recipe.v1.schema.json new file mode 100644 index 0000000..de26986 --- /dev/null +++ b/crates/gpui-agent-recipe/schemas/recipe.v1.schema.json @@ -0,0 +1,2010 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://raw.githubusercontent.com/hexuria/gpui-agent/main/schemas/recipe.v1.schema.json", + "title": "gpui-agent recipe, format v1", + "description": "Structure of a recipe file. `gpui-agent recipe validate` additionally checks ids, needs, params, and invoke args against the app schema. See docs/RECIPES.md.", + "type": "object", + "properties": { + "$schema": { + "type": [ + "string", + "null" + ] + }, + "v": { + "const": 1, + "description": "Recipe format version. Defaults to 1." + }, + "name": { + "type": "string", + "minLength": 1 + }, + "app": { + "type": [ + "string", + "null" + ] + }, + "params": { + "type": "array", + "items": { + "oneOf": [ + { + "type": "string", + "pattern": "^[A-Za-z_][A-Za-z0-9_]*$", + "description": "A required string param." + }, + { + "type": "object", + "properties": { + "name": { + "type": "string", + "pattern": "^[A-Za-z_][A-Za-z0-9_]*$" + }, + "type": { + "enum": [ + "string", + "number", + "integer", + "bool", + "boolean" + ], + "description": "Defaults to string." + }, + "required": { + "type": "boolean", + "description": "Defaults to true, or false when `default` is set." + }, + "default": { + "type": [ + "string", + "number", + "boolean" + ] + }, + "enum": { + "type": "array", + "minItems": 1, + "items": { + "type": [ + "string", + "number", + "boolean" + ] + } + }, + "pattern": { + "type": "string", + "description": "Regular expression the value must match. String params only." + }, + "description": { + "type": "string" + } + }, + "required": [ + "name" + ], + "additionalProperties": false + } + ] + }, + "description": "Params bound by --set: bare names or typed entries. Each must be used as $name or ${name} in a step." + }, + "steps": { + "type": "array", + "minItems": 1, + "maxItems": 256, + "items": { + "$ref": "#/$defs/step" + } + } + }, + "required": [ + "name", + "steps" + ], + "additionalProperties": false, + "$defs": { + "step": { + "oneOf": [ + { + "title": "hello", + "type": "object", + "properties": { + "id": { + "type": "string", + "minLength": 1, + "description": "Unique step id. Never contains $params." + }, + "needs": { + "type": "array", + "items": { + "type": "string" + }, + "uniqueItems": true, + "description": "Ids of steps that must finish first." + }, + "screenshot": { + "type": "boolean", + "description": "Capture an app-surface PNG after this step when the run has a screenshot dir." + }, + "op": { + "const": "hello" + } + }, + "required": [ + "id", + "op" + ], + "additionalProperties": false + }, + { + "title": "snapshot", + "type": "object", + "properties": { + "id": { + "type": "string", + "minLength": 1, + "description": "Unique step id. Never contains $params." + }, + "needs": { + "type": "array", + "items": { + "type": "string" + }, + "uniqueItems": true, + "description": "Ids of steps that must finish first." + }, + "screenshot": { + "type": "boolean", + "description": "Capture an app-surface PNG after this step when the run has a screenshot dir." + }, + "op": { + "const": "snapshot" + }, + "since": { + "type": [ + "integer", + "null" + ], + "minimum": 0 + }, + "format": { + "type": [ + "string", + "null" + ], + "enum": [ + "json", + "compact", + null + ] + }, + "fingerprints": { + "type": [ + "boolean", + "null" + ] + } + }, + "required": [ + "id", + "op" + ], + "additionalProperties": false + }, + { + "title": "revision", + "type": "object", + "properties": { + "id": { + "type": "string", + "minLength": 1, + "description": "Unique step id. Never contains $params." + }, + "needs": { + "type": "array", + "items": { + "type": "string" + }, + "uniqueItems": true, + "description": "Ids of steps that must finish first." + }, + "screenshot": { + "type": "boolean", + "description": "Capture an app-surface PNG after this step when the run has a screenshot dir." + }, + "op": { + "const": "revision" + } + }, + "required": [ + "id", + "op" + ], + "additionalProperties": false + }, + { + "title": "invokes", + "type": "object", + "properties": { + "id": { + "type": "string", + "minLength": 1, + "description": "Unique step id. Never contains $params." + }, + "needs": { + "type": "array", + "items": { + "type": "string" + }, + "uniqueItems": true, + "description": "Ids of steps that must finish first." + }, + "screenshot": { + "type": "boolean", + "description": "Capture an app-surface PNG after this step when the run has a screenshot dir." + }, + "op": { + "const": "invokes" + } + }, + "required": [ + "id", + "op" + ], + "additionalProperties": false + }, + { + "title": "events", + "type": "object", + "properties": { + "id": { + "type": "string", + "minLength": 1, + "description": "Unique step id. Never contains $params." + }, + "needs": { + "type": "array", + "items": { + "type": "string" + }, + "uniqueItems": true, + "description": "Ids of steps that must finish first." + }, + "screenshot": { + "type": "boolean", + "description": "Capture an app-surface PNG after this step when the run has a screenshot dir." + }, + "op": { + "const": "events" + }, + "since": { + "type": [ + "integer", + "null" + ], + "minimum": 0 + }, + "limit": { + "type": [ + "integer", + "null" + ], + "minimum": 0, + "maximum": 4294967295 + } + }, + "required": [ + "id", + "op" + ], + "additionalProperties": false + }, + { + "title": "click", + "type": "object", + "properties": { + "id": { + "type": "string", + "minLength": 1, + "description": "Unique step id. Never contains $params." + }, + "needs": { + "type": "array", + "items": { + "type": "string" + }, + "uniqueItems": true, + "description": "Ids of steps that must finish first." + }, + "screenshot": { + "type": "boolean", + "description": "Capture an app-surface PNG after this step when the run has a screenshot dir." + }, + "op": { + "const": "click" + }, + "target": { + "type": "string" + }, + "delivery": { + "enum": [ + "semantic", + "virtual" + ] + }, + "expect_fingerprint": { + "type": [ + "integer", + "null" + ], + "minimum": 0, + "description": "Node fingerprint from a snapshot; the step fails if the node changed." + } + }, + "required": [ + "id", + "op", + "target" + ], + "additionalProperties": false + }, + { + "title": "type", + "type": "object", + "properties": { + "id": { + "type": "string", + "minLength": 1, + "description": "Unique step id. Never contains $params." + }, + "needs": { + "type": "array", + "items": { + "type": "string" + }, + "uniqueItems": true, + "description": "Ids of steps that must finish first." + }, + "screenshot": { + "type": "boolean", + "description": "Capture an app-surface PNG after this step when the run has a screenshot dir." + }, + "op": { + "const": "type" + }, + "target": { + "type": "string" + }, + "text": { + "type": "string" + }, + "delivery": { + "enum": [ + "semantic", + "virtual" + ] + }, + "expect_fingerprint": { + "type": [ + "integer", + "null" + ], + "minimum": 0, + "description": "Node fingerprint from a snapshot; the step fails if the node changed." + }, + "key_delay_ms": { + "anyOf": [ + { + "type": "integer", + "minimum": 1, + "maximum": 10000, + "description": "Type the text one character per request, this many milliseconds apart, as a person types (1 to 10000; the pauses together at most 120000)." + }, + { + "type": "string", + "pattern": "^\\$([A-Za-z_][A-Za-z0-9_]*|\\{[A-Za-z_][A-Za-z0-9_]*\\})$", + "description": "A $param bound before validation." + } + ] + }, + "at": { + "type": [ + "string", + "null" + ], + "description": "Editable value containing one ^ caret marker." + }, + "before": { + "type": [ + "string", + "null" + ], + "description": "Place the caret before this text occurrence." + }, + "after": { + "type": [ + "string", + "null" + ], + "description": "Place the caret after this text occurrence." + }, + "nth": { + "type": [ + "integer", + "null" + ], + "minimum": 1, + "description": "One-based occurrence for before/after." + }, + "start": { + "type": "boolean", + "description": "Type at the start of the value." + }, + "end": { + "type": "boolean", + "description": "Type at the end of the value (the default)." + }, + "replace_all": { + "type": "boolean", + "description": "Select all, then type over the selection." + } + }, + "required": [ + "id", + "op", + "target", + "text" + ], + "additionalProperties": false + }, + { + "title": "replace", + "type": "object", + "properties": { + "id": { + "type": "string", + "minLength": 1, + "description": "Unique step id. Never contains $params." + }, + "needs": { + "type": "array", + "items": { + "type": "string" + }, + "uniqueItems": true, + "description": "Ids of steps that must finish first." + }, + "screenshot": { + "type": "boolean", + "description": "Capture an app-surface PNG after this step when the run has a screenshot dir." + }, + "op": { + "const": "replace" + }, + "target": { + "type": "string" + }, + "delivery": { + "enum": [ + "semantic", + "virtual" + ] + }, + "expect_fingerprint": { + "type": [ + "integer", + "null" + ], + "minimum": 0, + "description": "Node fingerprint from a snapshot; the step fails if the node changed." + }, + "nth": { + "type": [ + "integer", + "null" + ], + "minimum": 1, + "description": "One-based occurrence for before/after." + }, + "old": { + "type": "string", + "description": "Text occurrence selected before typing." + }, + "new": { + "type": "string", + "description": "Replacement text typed over the selection." + } + }, + "required": [ + "id", + "op", + "target", + "old", + "new" + ], + "additionalProperties": false + }, + { + "title": "set_value", + "type": "object", + "properties": { + "id": { + "type": "string", + "minLength": 1, + "description": "Unique step id. Never contains $params." + }, + "needs": { + "type": "array", + "items": { + "type": "string" + }, + "uniqueItems": true, + "description": "Ids of steps that must finish first." + }, + "screenshot": { + "type": "boolean", + "description": "Capture an app-surface PNG after this step when the run has a screenshot dir." + }, + "op": { + "const": "set_value" + }, + "target": { + "type": "string" + }, + "value": { + "type": "string" + }, + "expect_fingerprint": { + "type": [ + "integer", + "null" + ], + "minimum": 0, + "description": "Node fingerprint from a snapshot; the step fails if the node changed." + } + }, + "required": [ + "id", + "op", + "target", + "value" + ], + "additionalProperties": false + }, + { + "title": "key", + "type": "object", + "properties": { + "id": { + "type": "string", + "minLength": 1, + "description": "Unique step id. Never contains $params." + }, + "needs": { + "type": "array", + "items": { + "type": "string" + }, + "uniqueItems": true, + "description": "Ids of steps that must finish first." + }, + "screenshot": { + "type": "boolean", + "description": "Capture an app-surface PNG after this step when the run has a screenshot dir." + }, + "op": { + "const": "key" + }, + "target": { + "type": "string" + }, + "key": { + "type": "string" + }, + "delivery": { + "enum": [ + "semantic", + "virtual" + ] + }, + "expect_fingerprint": { + "type": [ + "integer", + "null" + ], + "minimum": 0, + "description": "Node fingerprint from a snapshot; the step fails if the node changed." + } + }, + "required": [ + "id", + "op", + "target", + "key" + ], + "additionalProperties": false + }, + { + "title": "keybinding", + "type": "object", + "properties": { + "id": { + "type": "string", + "minLength": 1, + "description": "Unique step id. Never contains $params." + }, + "needs": { + "type": "array", + "items": { + "type": "string" + }, + "uniqueItems": true, + "description": "Ids of steps that must finish first." + }, + "screenshot": { + "type": "boolean", + "description": "Capture an app-surface PNG after this step when the run has a screenshot dir." + }, + "op": { + "const": "keybinding" + }, + "binding": { + "type": "string" + }, + "chord": { + "type": [ + "string", + "null" + ] + }, + "scope": { + "type": "string", + "enum": [ + "focused", + "global" + ] + }, + "confirm": { + "type": "boolean" + }, + "activate": { + "type": "boolean" + } + }, + "required": [ + "id", + "op", + "binding", + "scope" + ], + "additionalProperties": false + }, + { + "title": "keybindings", + "type": "object", + "properties": { + "id": { + "type": "string", + "minLength": 1, + "description": "Unique step id. Never contains $params." + }, + "needs": { + "type": "array", + "items": { + "type": "string" + }, + "uniqueItems": true, + "description": "Ids of steps that must finish first." + }, + "screenshot": { + "type": "boolean", + "description": "Capture an app-surface PNG after this step when the run has a screenshot dir." + }, + "op": { + "const": "keybindings" + } + }, + "required": [ + "id", + "op" + ], + "additionalProperties": false + }, + { + "title": "keybinding.list", + "type": "object", + "properties": { + "id": { + "type": "string", + "minLength": 1, + "description": "Unique step id. Never contains $params." + }, + "needs": { + "type": "array", + "items": { + "type": "string" + }, + "uniqueItems": true, + "description": "Ids of steps that must finish first." + }, + "screenshot": { + "type": "boolean", + "description": "Capture an app-surface PNG after this step when the run has a screenshot dir." + }, + "op": { + "const": "keybinding.list" + } + }, + "required": [ + "id", + "op" + ], + "additionalProperties": false, + "description": "Alias of `keybindings`." + }, + { + "title": "assert", + "type": "object", + "properties": { + "id": { + "type": "string", + "minLength": 1, + "description": "Unique step id. Never contains $params." + }, + "needs": { + "type": "array", + "items": { + "type": "string" + }, + "uniqueItems": true, + "description": "Ids of steps that must finish first." + }, + "screenshot": { + "type": "boolean", + "description": "Capture an app-surface PNG after this step when the run has a screenshot dir." + }, + "op": { + "const": "assert" + }, + "target": { + "type": "string" + }, + "name": { + "type": [ + "string", + "null" + ] + }, + "value": { + "type": [ + "string", + "null" + ] + }, + "role": { + "type": [ + "string", + "null" + ] + }, + "checked": { + "type": [ + "boolean", + "null" + ] + }, + "exists": { + "type": [ + "boolean", + "null" + ] + }, + "visible": { + "type": [ + "boolean", + "null" + ] + }, + "in_viewport": { + "type": [ + "boolean", + "null" + ] + }, + "state": { + "type": [ + "string", + "null" + ], + "description": "Exact UiNode.states entry that must be present." + }, + "states": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Exact UiNode.states entries; all must be present." + }, + "view": { + "type": [ + "string", + "null" + ], + "description": "Expected editable value with ^ caret and [ ] selection markers." + } + }, + "required": [ + "id", + "op", + "target" + ], + "additionalProperties": false + }, + { + "title": "invoke", + "type": "object", + "properties": { + "id": { + "type": "string", + "minLength": 1, + "description": "Unique step id. Never contains $params." + }, + "needs": { + "type": "array", + "items": { + "type": "string" + }, + "uniqueItems": true, + "description": "Ids of steps that must finish first." + }, + "screenshot": { + "type": "boolean", + "description": "Capture an app-surface PNG after this step when the run has a screenshot dir." + }, + "op": { + "const": "invoke" + }, + "name": { + "type": "string" + }, + "args": {} + }, + "required": [ + "id", + "op", + "name" + ], + "additionalProperties": false + }, + { + "title": "wait", + "type": "object", + "properties": { + "id": { + "type": "string", + "minLength": 1, + "description": "Unique step id. Never contains $params." + }, + "needs": { + "type": "array", + "items": { + "type": "string" + }, + "uniqueItems": true, + "description": "Ids of steps that must finish first." + }, + "screenshot": { + "type": "boolean", + "description": "Capture an app-surface PNG after this step when the run has a screenshot dir." + }, + "op": { + "const": "wait" + }, + "timeout_ms": { + "type": [ + "integer", + "null" + ], + "minimum": 0 + } + }, + "required": [ + "id", + "op" + ], + "additionalProperties": false + }, + { + "title": "wait_until", + "type": "object", + "properties": { + "id": { + "type": "string", + "minLength": 1, + "description": "Unique step id. Never contains $params." + }, + "needs": { + "type": "array", + "items": { + "type": "string" + }, + "uniqueItems": true, + "description": "Ids of steps that must finish first." + }, + "screenshot": { + "type": "boolean", + "description": "Capture an app-surface PNG after this step when the run has a screenshot dir." + }, + "op": { + "const": "wait_until" + }, + "timeout_ms": { + "type": "integer", + "minimum": 0 + }, + "target": { + "type": "string" + }, + "name": { + "type": [ + "string", + "null" + ] + }, + "value": { + "type": [ + "string", + "null" + ] + }, + "role": { + "type": [ + "string", + "null" + ] + }, + "checked": { + "type": [ + "boolean", + "null" + ] + }, + "exists": { + "type": [ + "boolean", + "null" + ] + }, + "visible": { + "type": [ + "boolean", + "null" + ] + }, + "in_viewport": { + "type": [ + "boolean", + "null" + ] + }, + "state": { + "type": [ + "string", + "null" + ], + "description": "Exact UiNode.states entry that must be present." + }, + "states": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Exact UiNode.states entries; all must be present." + }, + "view": { + "type": [ + "string", + "null" + ], + "description": "Expected editable value with ^ caret and [ ] selection markers." + } + }, + "required": [ + "id", + "op", + "timeout_ms", + "target" + ], + "additionalProperties": false + }, + { + "title": "shutdown", + "type": "object", + "properties": { + "id": { + "type": "string", + "minLength": 1, + "description": "Unique step id. Never contains $params." + }, + "needs": { + "type": "array", + "items": { + "type": "string" + }, + "uniqueItems": true, + "description": "Ids of steps that must finish first." + }, + "screenshot": { + "type": "boolean", + "description": "Capture an app-surface PNG after this step when the run has a screenshot dir." + }, + "op": { + "const": "shutdown" + } + }, + "required": [ + "id", + "op" + ], + "additionalProperties": false + }, + { + "title": "screenshot", + "type": "object", + "properties": { + "id": { + "type": "string", + "minLength": 1, + "description": "Unique step id. Never contains $params." + }, + "needs": { + "type": "array", + "items": { + "type": "string" + }, + "uniqueItems": true, + "description": "Ids of steps that must finish first." + }, + "screenshot": { + "type": "boolean", + "description": "Capture an app-surface PNG after this step when the run has a screenshot dir." + }, + "op": { + "const": "screenshot" + }, + "path": { + "type": [ + "string", + "null" + ] + }, + "mode": { + "type": "string", + "enum": [ + "viewport", + "scrolled" + ] + }, + "target": { + "type": [ + "string", + "null" + ] + }, + "max_height_px": { + "type": [ + "integer", + "null" + ], + "minimum": 0, + "maximum": 4294967295 + }, + "inline": { + "type": "boolean" + } + }, + "required": [ + "id", + "op" + ], + "additionalProperties": false + }, + { + "title": "blob", + "type": "object", + "properties": { + "id": { + "type": "string", + "minLength": 1, + "description": "Unique step id. Never contains $params." + }, + "needs": { + "type": "array", + "items": { + "type": "string" + }, + "uniqueItems": true, + "description": "Ids of steps that must finish first." + }, + "screenshot": { + "type": "boolean", + "description": "Capture an app-surface PNG after this step when the run has a screenshot dir." + }, + "op": { + "const": "blob" + }, + "blob": { + "type": "string" + }, + "index": { + "type": "integer", + "minimum": 0, + "maximum": 4294967295 + } + }, + "required": [ + "id", + "op", + "blob", + "index" + ], + "additionalProperties": false + }, + { + "title": "press", + "type": "object", + "properties": { + "id": { + "type": "string", + "minLength": 1, + "description": "Unique step id. Never contains $params." + }, + "needs": { + "type": "array", + "items": { + "type": "string" + }, + "uniqueItems": true, + "description": "Ids of steps that must finish first." + }, + "screenshot": { + "type": "boolean", + "description": "Capture an app-surface PNG after this step when the run has a screenshot dir." + }, + "op": { + "const": "press" + }, + "target": { + "type": [ + "string", + "null" + ] + }, + "x": { + "anyOf": [ + { + "type": [ + "number", + "null" + ] + }, + { + "type": "string", + "pattern": "^\\$([A-Za-z_][A-Za-z0-9_]*|\\{[A-Za-z_][A-Za-z0-9_]*\\})$", + "description": "A $param bound before validation." + } + ] + }, + "y": { + "anyOf": [ + { + "type": [ + "number", + "null" + ] + }, + { + "type": "string", + "pattern": "^\\$([A-Za-z_][A-Za-z0-9_]*|\\{[A-Za-z_][A-Za-z0-9_]*\\})$", + "description": "A $param bound before validation." + } + ] + }, + "expect_fingerprint": { + "type": [ + "integer", + "null" + ], + "minimum": 0, + "description": "Node fingerprint from a snapshot; the step fails if the node changed." + }, + "within": { + "type": [ + "object", + "null" + ], + "properties": { + "x": { + "anyOf": [ + { + "type": "number", + "minimum": 0 + }, + { + "type": "string", + "pattern": "^\\$([A-Za-z_][A-Za-z0-9_]*|\\{[A-Za-z_][A-Za-z0-9_]*\\})$", + "description": "A $param bound before validation." + } + ] + }, + "y": { + "anyOf": [ + { + "type": "number", + "minimum": 0 + }, + { + "type": "string", + "pattern": "^\\$([A-Za-z_][A-Za-z0-9_]*|\\{[A-Za-z_][A-Za-z0-9_]*\\})$", + "description": "A $param bound before validation." + } + ] + } + }, + "required": [ + "x", + "y" + ], + "additionalProperties": false, + "description": "Aim inside target, in points from its top-left. Requires host feature press_within." + } + }, + "required": [ + "id", + "op" + ], + "additionalProperties": false + }, + { + "title": "scroll", + "type": "object", + "properties": { + "id": { + "type": "string", + "minLength": 1, + "description": "Unique step id. Never contains $params." + }, + "needs": { + "type": "array", + "items": { + "type": "string" + }, + "uniqueItems": true, + "description": "Ids of steps that must finish first." + }, + "screenshot": { + "type": "boolean", + "description": "Capture an app-surface PNG after this step when the run has a screenshot dir." + }, + "op": { + "const": "scroll" + }, + "target": { + "type": [ + "string", + "null" + ] + }, + "x": { + "anyOf": [ + { + "type": [ + "number", + "null" + ] + }, + { + "type": "string", + "pattern": "^\\$([A-Za-z_][A-Za-z0-9_]*|\\{[A-Za-z_][A-Za-z0-9_]*\\})$", + "description": "A $param bound before validation." + } + ] + }, + "y": { + "anyOf": [ + { + "type": [ + "number", + "null" + ] + }, + { + "type": "string", + "pattern": "^\\$([A-Za-z_][A-Za-z0-9_]*|\\{[A-Za-z_][A-Za-z0-9_]*\\})$", + "description": "A $param bound before validation." + } + ] + }, + "dx": { + "anyOf": [ + { + "type": "number" + }, + { + "type": "string", + "pattern": "^\\$([A-Za-z_][A-Za-z0-9_]*|\\{[A-Za-z_][A-Za-z0-9_]*\\})$", + "description": "A $param bound before validation." + } + ] + }, + "dy": { + "anyOf": [ + { + "type": "number" + }, + { + "type": "string", + "pattern": "^\\$([A-Za-z_][A-Za-z0-9_]*|\\{[A-Za-z_][A-Za-z0-9_]*\\})$", + "description": "A $param bound before validation." + } + ] + } + }, + "required": [ + "id", + "op" + ], + "additionalProperties": false + }, + { + "title": "scroll_until", + "type": "object", + "properties": { + "id": { + "type": "string", + "minLength": 1, + "description": "Unique step id. Never contains $params." + }, + "needs": { + "type": "array", + "items": { + "type": "string" + }, + "uniqueItems": true, + "description": "Ids of steps that must finish first." + }, + "screenshot": { + "type": "boolean", + "description": "Capture an app-surface PNG after this step when the run has a screenshot dir." + }, + "op": { + "const": "scroll_until" + }, + "target": { + "type": "string", + "minLength": 1, + "description": "Container to scroll." + }, + "x": { + "anyOf": [ + { + "type": [ + "number", + "null" + ] + }, + { + "type": "string", + "pattern": "^\\$([A-Za-z_][A-Za-z0-9_]*|\\{[A-Za-z_][A-Za-z0-9_]*\\})$", + "description": "A $param bound before validation." + } + ] + }, + "y": { + "anyOf": [ + { + "type": [ + "number", + "null" + ] + }, + { + "type": "string", + "pattern": "^\\$([A-Za-z_][A-Za-z0-9_]*|\\{[A-Za-z_][A-Za-z0-9_]*\\})$", + "description": "A $param bound before validation." + } + ] + }, + "dx": { + "anyOf": [ + { + "type": "number", + "description": "Horizontal scroll delta. dx and dy may not both be zero for scroll_until; validation enforces this after defaults are applied." + }, + { + "type": "string", + "pattern": "^\\$([A-Za-z_][A-Za-z0-9_]*|\\{[A-Za-z_][A-Za-z0-9_]*\\})$", + "description": "A $param bound before validation." + } + ] + }, + "dy": { + "anyOf": [ + { + "type": "number", + "description": "Vertical scroll delta. dx and dy may not both be zero for scroll_until; validation enforces this after defaults are applied." + }, + { + "type": "string", + "pattern": "^\\$([A-Za-z_][A-Za-z0-9_]*|\\{[A-Za-z_][A-Za-z0-9_]*\\})$", + "description": "A $param bound before validation." + } + ] + }, + "until": { + "type": "string", + "minLength": 1, + "description": "regex-lite pattern matched against a visible node's id or visible text after each snapshot." + }, + "max_steps": { + "anyOf": [ + { + "type": "integer", + "minimum": 1, + "maximum": 50, + "description": "Maximum scroll requests after the initial snapshot. Defaults to 10." + }, + { + "type": "string", + "pattern": "^\\$([A-Za-z_][A-Za-z0-9_]*|\\{[A-Za-z_][A-Za-z0-9_]*\\})$", + "description": "A $param bound before validation." + } + ] + } + }, + "required": [ + "id", + "op", + "target", + "until" + ], + "additionalProperties": false + }, + { + "title": "hover", + "type": "object", + "properties": { + "id": { + "type": "string", + "minLength": 1, + "description": "Unique step id. Never contains $params." + }, + "needs": { + "type": "array", + "items": { + "type": "string" + }, + "uniqueItems": true, + "description": "Ids of steps that must finish first." + }, + "screenshot": { + "type": "boolean", + "description": "Capture an app-surface PNG after this step when the run has a screenshot dir." + }, + "op": { + "const": "hover" + }, + "target": { + "type": [ + "string", + "null" + ] + }, + "x": { + "anyOf": [ + { + "type": [ + "number", + "null" + ] + }, + { + "type": "string", + "pattern": "^\\$([A-Za-z_][A-Za-z0-9_]*|\\{[A-Za-z_][A-Za-z0-9_]*\\})$", + "description": "A $param bound before validation." + } + ] + }, + "y": { + "anyOf": [ + { + "type": [ + "number", + "null" + ] + }, + { + "type": "string", + "pattern": "^\\$([A-Za-z_][A-Za-z0-9_]*|\\{[A-Za-z_][A-Za-z0-9_]*\\})$", + "description": "A $param bound before validation." + } + ] + } + }, + "required": [ + "id", + "op" + ], + "additionalProperties": false + }, + { + "title": "drag", + "type": "object", + "properties": { + "id": { + "type": "string", + "minLength": 1, + "description": "Unique step id. Never contains $params." + }, + "needs": { + "type": "array", + "items": { + "type": "string" + }, + "uniqueItems": true, + "description": "Ids of steps that must finish first." + }, + "screenshot": { + "type": "boolean", + "description": "Capture an app-surface PNG after this step when the run has a screenshot dir." + }, + "op": { + "const": "drag" + }, + "from": { + "type": [ + "string", + "null" + ] + }, + "to": { + "type": [ + "string", + "null" + ] + }, + "target": { + "type": [ + "string", + "null" + ] + }, + "x": { + "anyOf": [ + { + "type": [ + "number", + "null" + ] + }, + { + "type": "string", + "pattern": "^\\$([A-Za-z_][A-Za-z0-9_]*|\\{[A-Za-z_][A-Za-z0-9_]*\\})$", + "description": "A $param bound before validation." + } + ] + }, + "y": { + "anyOf": [ + { + "type": [ + "number", + "null" + ] + }, + { + "type": "string", + "pattern": "^\\$([A-Za-z_][A-Za-z0-9_]*|\\{[A-Za-z_][A-Za-z0-9_]*\\})$", + "description": "A $param bound before validation." + } + ] + }, + "dx": { + "anyOf": [ + { + "type": [ + "number", + "null" + ] + }, + { + "type": "string", + "pattern": "^\\$([A-Za-z_][A-Za-z0-9_]*|\\{[A-Za-z_][A-Za-z0-9_]*\\})$", + "description": "A $param bound before validation." + } + ] + }, + "dy": { + "anyOf": [ + { + "type": [ + "number", + "null" + ] + }, + { + "type": "string", + "pattern": "^\\$([A-Za-z_][A-Za-z0-9_]*|\\{[A-Za-z_][A-Za-z0-9_]*\\})$", + "description": "A $param bound before validation." + } + ] + } + }, + "required": [ + "id", + "op" + ], + "additionalProperties": false + }, + { + "title": "swipe", + "type": "object", + "properties": { + "id": { + "type": "string", + "minLength": 1, + "description": "Unique step id. Never contains $params." + }, + "needs": { + "type": "array", + "items": { + "type": "string" + }, + "uniqueItems": true, + "description": "Ids of steps that must finish first." + }, + "screenshot": { + "type": "boolean", + "description": "Capture an app-surface PNG after this step when the run has a screenshot dir." + }, + "op": { + "const": "swipe" + }, + "target": { + "type": [ + "string", + "null" + ] + }, + "direction": { + "type": "string", + "enum": [ + "up", + "down", + "left", + "right" + ] + }, + "distance": { + "type": [ + "number", + "null" + ] + } + }, + "required": [ + "id", + "op", + "direction" + ], + "additionalProperties": false + }, + { + "title": "long_press", + "type": "object", + "properties": { + "id": { + "type": "string", + "minLength": 1, + "description": "Unique step id. Never contains $params." + }, + "needs": { + "type": "array", + "items": { + "type": "string" + }, + "uniqueItems": true, + "description": "Ids of steps that must finish first." + }, + "screenshot": { + "type": "boolean", + "description": "Capture an app-surface PNG after this step when the run has a screenshot dir." + }, + "op": { + "const": "long_press" + }, + "target": { + "type": [ + "string", + "null" + ] + }, + "x": { + "anyOf": [ + { + "type": [ + "number", + "null" + ] + }, + { + "type": "string", + "pattern": "^\\$([A-Za-z_][A-Za-z0-9_]*|\\{[A-Za-z_][A-Za-z0-9_]*\\})$", + "description": "A $param bound before validation." + } + ] + }, + "y": { + "anyOf": [ + { + "type": [ + "number", + "null" + ] + }, + { + "type": "string", + "pattern": "^\\$([A-Za-z_][A-Za-z0-9_]*|\\{[A-Za-z_][A-Za-z0-9_]*\\})$", + "description": "A $param bound before validation." + } + ] + }, + "duration_ms": { + "anyOf": [ + { + "type": [ + "integer", + "null" + ], + "minimum": 0 + }, + { + "type": "string", + "pattern": "^\\$([A-Za-z_][A-Za-z0-9_]*|\\{[A-Za-z_][A-Za-z0-9_]*\\})$", + "description": "A $param bound before validation." + } + ] + }, + "within": { + "type": [ + "object", + "null" + ], + "properties": { + "x": { + "anyOf": [ + { + "type": "number", + "minimum": 0 + }, + { + "type": "string", + "pattern": "^\\$([A-Za-z_][A-Za-z0-9_]*|\\{[A-Za-z_][A-Za-z0-9_]*\\})$", + "description": "A $param bound before validation." + } + ] + }, + "y": { + "anyOf": [ + { + "type": "number", + "minimum": 0 + }, + { + "type": "string", + "pattern": "^\\$([A-Za-z_][A-Za-z0-9_]*|\\{[A-Za-z_][A-Za-z0-9_]*\\})$", + "description": "A $param bound before validation." + } + ] + } + }, + "required": [ + "x", + "y" + ], + "additionalProperties": false, + "description": "Aim inside target, in points from its top-left. Requires host feature press_within." + } + }, + "required": [ + "id", + "op" + ], + "additionalProperties": false + }, + { + "title": "pinch", + "type": "object", + "properties": { + "id": { + "type": "string", + "minLength": 1, + "description": "Unique step id. Never contains $params." + }, + "needs": { + "type": "array", + "items": { + "type": "string" + }, + "uniqueItems": true, + "description": "Ids of steps that must finish first." + }, + "screenshot": { + "type": "boolean", + "description": "Capture an app-surface PNG after this step when the run has a screenshot dir." + }, + "op": { + "const": "pinch" + }, + "target": { + "type": [ + "string", + "null" + ] + }, + "scale": { + "type": "number" + } + }, + "required": [ + "id", + "op", + "scale" + ], + "additionalProperties": false + }, + { + "title": "viewport", + "type": "object", + "properties": { + "id": { + "type": "string", + "minLength": 1, + "description": "Unique step id. Never contains $params." + }, + "needs": { + "type": "array", + "items": { + "type": "string" + }, + "uniqueItems": true, + "description": "Ids of steps that must finish first." + }, + "screenshot": { + "type": "boolean", + "description": "Capture an app-surface PNG after this step when the run has a screenshot dir." + }, + "op": { + "const": "viewport" + }, + "width": { + "type": [ + "number", + "null" + ] + }, + "height": { + "type": [ + "number", + "null" + ] + }, + "preset": { + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "id", + "op" + ], + "additionalProperties": false + }, + { + "title": "paste", + "type": "object", + "properties": { + "id": { + "type": "string", + "minLength": 1, + "description": "Unique step id. Never contains $params." + }, + "needs": { + "type": "array", + "items": { + "type": "string" + }, + "uniqueItems": true, + "description": "Ids of steps that must finish first." + }, + "screenshot": { + "type": "boolean", + "description": "Capture an app-surface PNG after this step when the run has a screenshot dir." + }, + "op": { + "const": "paste" + }, + "target": { + "type": "string" + }, + "text": { + "type": "string" + } + }, + "required": [ + "id", + "op", + "target", + "text" + ], + "additionalProperties": false + }, + { + "title": "system", + "type": "object", + "properties": { + "id": { + "type": "string", + "minLength": 1, + "description": "Unique step id. Never contains $params." + }, + "needs": { + "type": "array", + "items": { + "type": "string" + }, + "uniqueItems": true, + "description": "Ids of steps that must finish first." + }, + "screenshot": { + "type": "boolean", + "description": "Capture an app-surface PNG after this step when the run has a screenshot dir." + }, + "op": { + "const": "system" + }, + "action": { + "type": "string", + "enum": [ + "back", + "home", + "rotate", + "keyboard_show", + "keyboard_hide", + "background", + "foreground", + "open_url" + ] + }, + "value": { + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "id", + "op", + "action" + ], + "additionalProperties": false + } + ] + } + } +} diff --git a/crates/gpui-agent-recipe/src/docschema.rs b/crates/gpui-agent-recipe/src/docschema.rs new file mode 100644 index 0000000..e89b5dd --- /dev/null +++ b/crates/gpui-agent-recipe/src/docschema.rs @@ -0,0 +1,623 @@ +//! The per-app recipe document schema: `schemas/recipe.v1.schema.json` +//! specialized with one `invoke` step branch per invoke the registry +//! knows, so an editor (or any JSON Schema validator) can check an +//! invoke step's `args` before `recipe validate` runs. +//! +//! [`recipe_schema_for_registry`] is a pure transformation: the invoke +//! metadata comes from the registry the caller built — schema files +//! offline, the live host's table merged in when a target was named — +//! and the output is the base document schema with the generic `invoke` +//! branch replaced. What the generated schema cannot say stays with +//! `recipe validate`, exactly as for the base schema: unknown `needs`, +//! cycles, undeclared or unused params, and everything only the running +//! app knows. The placeholder alternative is also deliberately +//! approximate. JSON Schema patterns cannot model the recipe escaping +//! rules — `"$$id"` is the literal text `$id`, yet it contains the +//! shape of a placeholder — nor `$.node` runtime references, so a +//! string the pattern matches is accepted even in the few cases +//! validation would later refuse it. A recursive generated probe mirrors +//! validation's nested-placeholder escape hatch at the same level of +//! approximation: a placeholder-shaped string anywhere inside an object or +//! array relaxes the embedded schema for that value. The schema is an +//! editor aid — one-directional soundness is the contract: what +//! `recipe validate` accepts, the generated schema accepts. + +use std::collections::BTreeSet; +use std::fmt::Write as _; + +use serde_json::{Map, Value, json}; + +use crate::error::{RecipeError, RecipeErrorCode, err}; +use crate::registry::Registry; +use crate::schema::{ArgSchema, ArgType, OpSchema, SchemaKind, compile_embedded_schema}; + +/// The crate's copy of `schemas/recipe.v1.schema.json`, embedded so the +/// published crate carries it. A byte-equality test keeps the two +/// synchronized; edit the workspace root file and copy it here. +const BASE_RECIPE_SCHEMA_JSON: &str = include_str!("../schemas/recipe.v1.schema.json"); + +/// Unanchored `$param` placeholder shape: `$name` or `${name}` anywhere +/// in the string. Deliberately simpler than the recipe's own scanner — +/// JSON Schema cannot model `$$` escaping or `$.node` references, +/// and an editor aid accepts the approximation (see the module docs). +const PARAM_PLACEHOLDER_PATTERN: &str = r"\$([A-Za-z_][A-Za-z0-9_]*|\{[A-Za-z_][A-Za-z0-9_]*\})"; + +/// The generated `$defs` entry detecting a placeholder-shaped string at +/// any depth inside a value. Validation scans object and array arguments +/// recursively and skips an embedded schema while such a value is still +/// unbound; JSON Schema has no built-in deep-search keyword, so the probe +/// uses recursive negation: an array/object matches when it is not the +/// case that every contained value fails the probe. The string pattern is +/// deliberately the same approximation as the top-level placeholder rule — +/// it also matches `$step.node` text and escaped-looking text JSON Schema +/// cannot model exactly — so embedded validation is relaxed rather than +/// inventing false positives on runtime-dynamic values. +const CONTAINS_PARAM_PLACEHOLDER_DEF: &str = "gpuiAgentContainsParamPlaceholder"; + +/// The base recipe document schema (`schemas/recipe.v1.schema.json`) as +/// a JSON value: the generic shape every per-app schema starts from. +/// +/// # Panics +/// +/// Never in practice — the schema is embedded at compile time and a +/// test proves it parses and compiles — but the conversion uses +/// `expect` rather than a lossy fallback. +#[must_use] +pub fn base_recipe_schema() -> Value { + serde_json::from_str(BASE_RECIPE_SCHEMA_JSON).expect("the embedded base recipe schema is JSON") +} + +/// True when an embedded-schema argument can hold a nested placeholder: +/// object and array values obviously can, and `any` is unconstrained. +/// Scalar arguments only need the top-level string alternative. +fn uses_deep_placeholder_probe(spec: &ArgSchema) -> bool { + spec.schema.is_some() + && matches!( + ArgType::parse(&spec.ty), + Some(ArgType::Object | ArgType::Array | ArgType::Any) + ) +} + +/// Specialize `base` (ordinarily [`base_recipe_schema`]) for the invokes +/// `registry` knows: the generic `invoke` step branch is replaced by one +/// branch per registered [`SchemaKind::Invoke`] schema, name-sorted. +/// Other rows (protocol ops, stable ids) produce no branches — the base +/// schema already covers the protocol, and ids are not invoke names. +/// +/// Each branch keeps the generic branch's step shell (`id`, `needs`, +/// `screenshot`, `op`, closed additional properties) and specializes the +/// invoke itself: +/// +/// - `name` is a `const`. A name no branch carries matches none, exactly +/// as `recipe validate` fails closed with `recipe_unknown_invoke`. +/// - `args` describes the invoke's argument object: properties from the +/// argument specs, `required` the union of the schema's `required` and +/// the specs marked required, closed additional properties when the +/// invoke lists its args (including `"args": {}`) and open when it +/// does not. A required name with no argument spec is declared untyped +/// so the closed object does not reject what validation accepts. When +/// the union is empty the schema also accepts `null` — validation +/// reads missing or null `args` as `{}` — and when it is not, the +/// branch requires the `args` key, because absent args can never hold +/// a required argument. An invoke that neither lists its args nor +/// requires any accepts any `args` value, exactly as validation does. +/// - every typed argument also admits a string holding a `$param` +/// placeholder, because `"id": "$id"` is valid before binding. The +/// exception is a `string` argument without an embedded schema, which +/// already admits every string. +/// - an object/array/`any` argument with an embedded schema also admits a +/// value containing a placeholder-shaped string at any depth, because +/// validation skips deep embedded validation until binding. A recursive +/// probe generated in `$defs` mirrors that rule. +/// - an embedded per-argument JSON Schema is reflected as it is, composed +/// with the top-level type in an `allOf` when both exist. Internal +/// `$ref` / `$dynamicRef` pointers would rebind to the recipe document +/// root, so an object schema that uses them keeps its `$id` when it +/// has one and gains a unique deterministic `urn:` `$id` when it does +/// not, preserving its resource semantics. Boolean schemas embed +/// unchanged. +/// +/// The generated schema is compiled offline before it is returned; a +/// schema that does not compile is never handed back. +/// +/// # Errors +/// +/// [`RecipeErrorCode::InvalidSchema`] when `base` lacks +/// `$defs.step.oneOf` or the generic invoke branch, when that branch is +/// not the object shape the transformation builds on, or when the +/// generated schema does not compile — for example because two embedded +/// argument schemas declare the same `$id`, which one document cannot +/// carry twice. +pub fn recipe_schema_for_registry(base: &Value, registry: &Registry) -> Result { + let invalid = |detail: &str| { + err( + RecipeErrorCode::InvalidSchema, + format!("base recipe schema: {detail}"), + ) + }; + let mut out = base.clone(); + let Some(one_of) = out + .pointer_mut("/$defs/step/oneOf") + .and_then(Value::as_array_mut) + else { + return Err(invalid("lacks $defs.step.oneOf")); + }; + let generic_positions: Vec = one_of + .iter() + .enumerate() + .filter_map(|(index, branch)| is_generic_invoke(branch).then_some(index)) + .collect(); + let [generic_index] = generic_positions.as_slice() else { + return Err(err( + RecipeErrorCode::InvalidSchema, + format!( + "base recipe schema: must have exactly one generic invoke step branch, found {}", + generic_positions.len() + ), + )); + }; + let generic_index = *generic_index; + let generic = one_of[generic_index].clone(); + let mut branches = Vec::new(); + for schema in registry + .iter() + .filter(|schema| matches!(schema.kind, SchemaKind::Invoke)) + { + branches.push(invoke_branch(&generic, schema)?); + } + one_of.splice(generic_index..=generic_index, branches); + if registry.iter().any(|schema| { + matches!(schema.kind, SchemaKind::Invoke) + && schema + .args + .iter() + .flatten() + .any(|(_, spec)| uses_deep_placeholder_probe(spec)) + }) { + let defs = out + .pointer_mut("/$defs") + .and_then(Value::as_object_mut) + .ok_or_else(|| invalid("lacks an object $defs"))?; + let probe_ref = format!("#/$defs/{CONTAINS_PARAM_PLACEHOLDER_DEF}"); + defs.insert( + CONTAINS_PARAM_PLACEHOLDER_DEF.into(), + json!({ + "anyOf": [ + { + "type": "string", + "pattern": PARAM_PLACEHOLDER_PATTERN, + }, + { + "type": "array", + "not": {"items": {"not": {"$ref": probe_ref}}}, + }, + { + "type": "object", + "not": {"additionalProperties": {"not": {"$ref": probe_ref}}}, + }, + ], + }), + ); + } + if let Err(error) = compile_embedded_schema(&out) { + return Err(err( + RecipeErrorCode::InvalidSchema, + format!("the generated recipe schema does not compile: {error}"), + )); + } + Ok(out) +} + +/// True for the base schema's open invoke branch: `op` is `invoke` and +/// `name` is any string, not yet pinned to one invoke. +fn is_generic_invoke(branch: &Value) -> bool { + branch["properties"]["op"]["const"] == "invoke" + && branch["properties"]["name"].get("const").is_none() +} + +/// One `invoke` step branch: the generic branch's shell with `name`, +/// `args` and — when the invoke has required arguments — the `required` +/// list specialized for `schema`. +fn invoke_branch(generic: &Value, schema: &OpSchema) -> Result { + let invalid = |detail: &str| { + err( + RecipeErrorCode::InvalidSchema, + format!("base recipe schema: the generic invoke branch {detail}"), + ) + }; + let mut branch = generic.clone(); + let object = branch + .as_object_mut() + .ok_or_else(|| invalid("is not an object"))?; + object.insert("title".into(), json!(format!("invoke {}", schema.name))); + object.insert( + "description".into(), + json!(format!("Invoke `{}`: {}", schema.name, schema.description)), + ); + let properties = object + .get_mut("properties") + .and_then(Value::as_object_mut) + .ok_or_else(|| invalid("lacks properties"))?; + properties.insert( + "name".into(), + json!({ + "const": schema.name, + "description": format!("Invoke `{}`.", schema.name), + }), + ); + properties.insert("args".into(), args_value_schema(schema)); + if !required_args(schema).is_empty() { + // Absent args read as `{}`, which can never hold a required + // argument — so the key itself is required, matching validation. + let required = object + .get_mut("required") + .and_then(Value::as_array_mut) + .ok_or_else(|| invalid("lacks its required list"))?; + if !required.iter().any(|entry| entry.as_str() == Some("args")) { + required.push(json!("args")); + } + } + Ok(branch) +} + +/// The union of the schema's `required` list and the argument specs +/// marked required — the same union [`crate::validate_recipe`] enforces. +fn required_args(schema: &OpSchema) -> BTreeSet { + schema.required_args().map(str::to_owned).collect() +} + +/// The JSON Schema for one invoke branch's `args` value, mirroring what +/// [`crate::validate_recipe`] accepts: missing or null reads as `{}`, +/// a non-object passes only when the invoke neither lists its args nor +/// requires any, and a listed invoke is closed exactly as validation is. +fn args_value_schema(schema: &OpSchema) -> Value { + let required = required_args(schema); + let required_list: Vec = required.iter().map(|name| json!(name)).collect(); + let Some(listed) = &schema.args else { + if required.is_empty() { + // Args neither listed nor required: validation accepts every + // value, object or not. + return json!({}); + } + // Unlisted but constrained: any object holding the required + // names passes, their values untyped, the rest open. + let properties: Map = required + .iter() + .map(|name| (name.clone(), json!({}))) + .collect(); + return json!({ + "type": "object", + "properties": properties, + "required": required_list, + }); + }; + let mut properties = Map::new(); + for (name, spec) in listed { + properties.insert(name.clone(), arg_value_schema(&schema.name, name, spec)); + } + for name in &required { + if !listed.contains_key(name) { + // A legacy required name with no argument spec is declared, + // untyped: validation accepts any value for it, and the + // closed object must not reject it. + properties.insert(name.clone(), json!({})); + } + } + let mut object_schema = json!({ + "type": "object", + "properties": properties, + "additionalProperties": false, + }); + if required_list.is_empty() { + // No argument is required, so null reads as the empty object + // exactly as validation treats it. (No keyword here constrains + // null either way, so the type union is the exact spelling.) + object_schema["type"] = json!(["object", "null"]); + } else { + object_schema["required"] = json!(required_list); + } + object_schema +} + +/// The JSON Schema for one argument's value: its top-level type, its +/// embedded schema reflected, and — where a string would otherwise be +/// refused — the `$param` placeholder alternative validation grants. +fn arg_value_schema(op_name: &str, arg_name: &str, spec: &ArgSchema) -> Value { + let type_schema: Option = match ArgType::parse(&spec.ty) { + // `any` constrains nothing, so there is no type schema to compose. + Some(ty) => ty.json_schema_type().map(|name| json!({"type": name})), + // `OpSchema::validate` refuses unknown spellings before a schema + // reaches the registry. Fail closed here too, exactly as + // validation's type check does: nothing passes but a placeholder. + None => Some(json!(false)), + }; + let mut parts = Vec::new(); + if let Some(type_schema) = type_schema { + parts.push(type_schema); + } + if let Some(embedded) = &spec.schema { + parts.push(embed_resource(embedded, op_name, arg_name)); + } + let composed = match parts.len() { + // `any` without an embedded schema accepts everything already, + // placeholder strings included. + 0 => return json!({}), + 1 => parts.pop().expect("one part"), + _ => json!({ "allOf": parts }), + }; + if spec.ty == "string" && spec.schema.is_none() { + // Every string passes the type check, placeholders included. + return composed; + } + let mut alternatives = vec![ + composed, + json!({ + "type": "string", + "pattern": PARAM_PLACEHOLDER_PATTERN, + "description": "A string holding a $param placeholder, bound before validation.", + }), + ]; + if uses_deep_placeholder_probe(spec) { + // Validation scans recursively: one unbound placeholder anywhere in + // an object/array skips the embedded schema for the whole value, + // while the outer top-level type still applies. Mirror that escape + // hatch so the editor schema does not reject runtime-dynamic values + // validation explicitly accepts before binding. + let probe = json!({"$ref": format!("#/$defs/{CONTAINS_PARAM_PLACEHOLDER_DEF}")}); + let deep = match ArgType::parse(&spec.ty).and_then(ArgType::json_schema_type) { + Some(name) => json!({"allOf": [{"type": name}, probe]}), + None => probe, + }; + alternatives.push(deep); + } + json!({ "anyOf": alternatives }) +} + +/// `schema` as embedded inside the generated document. Boolean schemas +/// embed unchanged. An object schema that uses `$ref` / `$dynamicRef` +/// anywhere inside keeps its resource semantics: its `#/...` pointers +/// are its own, not the recipe document root's, so it keeps an existing +/// `$id` and otherwise gains a unique deterministic one naming the +/// invoke argument it describes. +fn embed_resource(schema: &Value, op_name: &str, arg_name: &str) -> Value { + let Value::Object(object) = schema else { + return schema.clone(); + }; + let mut object = object.clone(); + if !object.contains_key("$id") && schema_uses_ref(schema) { + object.insert( + "$id".into(), + json!(format!( + "urn:gpui-agent:embedded:{}:{}", + urn_encode(op_name), + urn_encode(arg_name), + )), + ); + } + Value::Object(object) +} + +/// True when `$ref` or `$dynamicRef` appears anywhere inside `value`. +/// A key that is not a schema keyword at all (a property literally named +/// `$ref`) may over-count; the only cost is a harmless `$id`. +fn schema_uses_ref(value: &Value) -> bool { + match value { + Value::Object(map) => { + map.contains_key("$ref") + || map.contains_key("$dynamicRef") + || map.values().any(schema_uses_ref) + } + Value::Array(items) => items.iter().any(schema_uses_ref), + _ => false, + } +} + +/// Percent-encode `text` for a URN path segment, keeping the characters +/// invoke and argument names ordinarily use untouched. Deterministic and +/// injective, so two distinct names never share an `$id`. +fn urn_encode(text: &str) -> String { + let mut out = String::with_capacity(text.len()); + for byte in text.bytes() { + if byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'-' | b'~') { + out.push(char::from(byte)); + } else { + write!(out, "%{byte:02X}").expect("writing to a string cannot fail"); + } + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::registry::todo_registry; + use std::collections::BTreeMap; + + #[test] + fn base_schema_parses_and_compiles() { + let base = base_recipe_schema(); + compile_embedded_schema(&base).expect("the embedded base schema compiles offline"); + } + + #[test] + fn embedded_copy_matches_the_workspace_file_byte_for_byte() { + // Outside the workspace the published crate does not carry the + // root file; the embedded copy is the only one there is. + let workspace = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../.."); + if !workspace.join("Cargo.toml").exists() { + return; + } + let text = std::fs::read_to_string(workspace.join("schemas/recipe.v1.schema.json")) + .expect("the workspace has schemas/recipe.v1.schema.json"); + assert_eq!( + text, BASE_RECIPE_SCHEMA_JSON, + "schemas/recipe.v1.schema.json and the embedded copy drifted; copy the root file into crates/gpui-agent-recipe/schemas/" + ); + } + + #[test] + fn missing_step_one_of_is_invalid_schema() { + let err = recipe_schema_for_registry(&json!({}), &Registry::new()).unwrap_err(); + assert_eq!(err.code, RecipeErrorCode::InvalidSchema); + assert!(err.to_string().contains("$defs.step.oneOf"), "{err}"); + } + + #[test] + fn missing_generic_invoke_branch_is_invalid_schema() { + let err = recipe_schema_for_registry( + &json!({"$defs": {"step": {"oneOf": []}}}), + &Registry::new(), + ) + .unwrap_err(); + assert_eq!(err.code, RecipeErrorCode::InvalidSchema); + assert!(err.to_string().contains("generic invoke"), "{err}"); + } + + #[test] + fn empty_registry_drops_the_invoke_branch() { + let generated = recipe_schema_for_registry(&base_recipe_schema(), &Registry::new()) + .expect("generation succeeds"); + let branches = generated["$defs"]["step"]["oneOf"] + .as_array() + .expect("oneOf"); + assert!( + branches.iter().all(|branch| !is_generic_invoke(branch)), + "the generic invoke branch must be replaced, even by nothing" + ); + assert!( + branches + .iter() + .all(|branch| branch["properties"]["op"]["const"] != "invoke"), + "no invoke branch survives an invokeless registry" + ); + } + + #[test] + fn todo_registry_produces_one_branch_per_invoke_name_sorted() { + let generated = recipe_schema_for_registry(&base_recipe_schema(), &todo_registry()) + .expect("generation succeeds"); + let branches = generated["$defs"]["step"]["oneOf"] + .as_array() + .expect("oneOf"); + let invoke_names: Vec<&str> = branches + .iter() + .filter(|branch| branch["properties"]["op"]["const"] == "invoke") + .map(|branch| { + branch["properties"]["name"]["const"] + .as_str() + .expect("name const") + }) + .collect(); + assert_eq!( + invoke_names, + vec![ + "todo.add", + "todo.delete", + "todo.list", + "todo.toggle", + "todo.toggle_sidebar", + ], + ); + // Non-invoke rows (ids, protocol) grew no branches: the base + // schema has 31 variants, one of which is replaced by five. + assert_eq!(branches.len(), 31 - 1 + 5, "one branch per invoke"); + } + + #[test] + fn todo_add_branch_shape() { + let generated = recipe_schema_for_registry(&base_recipe_schema(), &todo_registry()) + .expect("generation succeeds"); + let branches = generated["$defs"]["step"]["oneOf"] + .as_array() + .expect("oneOf"); + let add = branches + .iter() + .find(|branch| branch["properties"]["name"]["const"] == "todo.add") + .expect("todo.add branch"); + assert_eq!(add["title"], json!("invoke todo.add")); + assert_eq!( + add["required"].as_array().expect("required"), + &vec![json!("id"), json!("op"), json!("name"), json!("args")], + "required args make the args key itself required" + ); + let args = &add["properties"]["args"]; + assert_eq!(args["type"], json!("object")); + assert_eq!(args["additionalProperties"], json!(false)); + assert_eq!(args["required"], json!(["title"])); + // `string` without an embedded schema needs no placeholder + // alternative: every string already passes. + assert_eq!(args["properties"]["title"], json!({"type": "string"})); + } + + #[test] + fn todo_list_branch_is_closed_with_no_args() { + let generated = recipe_schema_for_registry(&base_recipe_schema(), &todo_registry()) + .expect("generation succeeds"); + let branches = generated["$defs"]["step"]["oneOf"] + .as_array() + .expect("oneOf"); + let list = branches + .iter() + .find(|branch| branch["properties"]["name"]["const"] == "todo.list") + .expect("todo.list branch"); + // No required args: `args` itself stays optional. + assert_eq!( + list["required"].as_array().expect("required"), + &vec![json!("id"), json!("op"), json!("name")], + ); + let args = &list["properties"]["args"]; + // `"args": {}` is a closed empty object; null reads as `{}`. + assert_eq!(args["type"], json!(["object", "null"])); + assert_eq!(args["additionalProperties"], json!(false)); + assert!(args.get("required").is_none(), "empty required is omitted"); + } + + #[test] + fn integer_arg_admits_a_placeholder_string() { + let generated = recipe_schema_for_registry(&base_recipe_schema(), &todo_registry()) + .expect("generation succeeds"); + let branches = generated["$defs"]["step"]["oneOf"] + .as_array() + .expect("oneOf"); + let toggle = branches + .iter() + .find(|branch| branch["properties"]["name"]["const"] == "todo.toggle") + .expect("todo.toggle branch"); + let id = &toggle["properties"]["args"]["properties"]["id"]; + let any_of = id["anyOf"].as_array().expect("integer arg has anyOf"); + assert_eq!(any_of[0], json!({"type": "integer"})); + assert_eq!(any_of[1]["type"], json!("string")); + assert_eq!(any_of[1]["pattern"], json!(PARAM_PLACEHOLDER_PATTERN)); + } + + #[test] + fn internal_embedded_refs_keep_their_resource_root() { + let mut registry = Registry::new(); + let mut row = OpSchema::new("x.save", SchemaKind::Invoke, "save"); + row.args = Some(BTreeMap::from([( + "meta".into(), + ArgSchema::new("object").with_schema(json!({ + "type": "object", + "properties": {"owner": {"$ref": "#/$defs/owner"}}, + "$defs": {"owner": {"type": "string", "pattern": "^[a-z]+$"}}, + "required": ["owner"], + "additionalProperties": false, + })), + )])); + registry.insert(row).expect("fixture schema validates"); + let generated = recipe_schema_for_registry(&base_recipe_schema(), ®istry) + .expect("generation succeeds"); + let validator = compile_embedded_schema(&generated).expect("generated schema compiles"); + let recipe = |owner: Value| json!({"name":"r","steps":[{"id":"a","op":"invoke","name":"x.save","args":{"meta":{"owner":owner}}}]}); + assert!(validator.is_valid(&recipe(json!("me")))); + assert!(!validator.is_valid(&recipe(json!("ME")))); + } + + #[test] + fn urn_encode_is_injective_and_untouched_for_ordinary_names() { + assert_eq!(urn_encode("todo.add"), "todo.add"); + assert_eq!(urn_encode("title"), "title"); + assert_eq!(urn_encode("a b"), "a%20b"); + assert_ne!(urn_encode("a b"), urn_encode("a%20b")); + } +} diff --git a/crates/gpui-agent-recipe/src/lib.rs b/crates/gpui-agent-recipe/src/lib.rs index 6463718..dbd6f17 100644 --- a/crates/gpui-agent-recipe/src/lib.rs +++ b/crates/gpui-agent-recipe/src/lib.rs @@ -15,6 +15,8 @@ //! screenshot-capture waves stay one request at a time so a failed write //! never continues the wave. +/// The per-app recipe document schema (`recipe schema`). +pub mod docschema; /// Typed errors with stable codes. pub mod error; /// Recipe params: bare names or typed entries. @@ -34,6 +36,7 @@ pub mod run; /// Schema types (`OpSchema`, `Effect`, `SchemaKind`). pub mod schema; +pub use docschema::{base_recipe_schema, recipe_schema_for_registry}; pub use error::{RecipeError, RecipeErrorCode}; pub use param::{Param, ParamType}; pub use plan::{OrderCheck, PLAN_FORMAT_VERSION, Plan, PlannedStep, compile_plan, order_check}; diff --git a/crates/gpui-agent-recipe/src/recipe.rs b/crates/gpui-agent-recipe/src/recipe.rs index 17d2ce2..4101438 100644 --- a/crates/gpui-agent-recipe/src/recipe.rs +++ b/crates/gpui-agent-recipe/src/recipe.rs @@ -1375,14 +1375,7 @@ pub(crate) fn check_invoke_args( _ if schema.args.is_none() && schema.required.is_empty() => return Ok(()), _ => return Err(format!("invoke `{}` args must be an object", schema.name)), }; - let required = schema.required.iter().map(String::as_str).chain( - schema - .args - .iter() - .flatten() - .filter(|(_, spec)| spec.required) - .map(|(name, _)| name.as_str()), - ); + let required = schema.required_args(); for name in required { if !map.contains_key(name) { return Err(format!( @@ -1422,19 +1415,10 @@ pub(crate) fn check_invoke_args( if !bound && value.as_str().is_some_and(string_has_placeholder) { continue; } - let ok = match spec.ty.as_str() { - "string" => value.is_string(), - "number" => value.is_number(), - "integer" => value.is_i64() || value.is_u64(), - "bool" | "boolean" => value.is_boolean(), - "object" => value.is_object(), - "array" => value.is_array(), - "any" => true, - // `OpSchema::validate` refuses unknown spellings before a - // schema reaches the registry. Fail closed here too rather - // than silently disabling the check for a hand-built schema. - _ => false, - }; + // `OpSchema::validate` refuses unknown spellings before a schema + // reaches the registry. Fail closed here too rather than silently + // disabling the check for a hand-built schema. + let ok = crate::schema::ArgType::parse(&spec.ty).is_some_and(|ty| ty.accepts(value)); if !ok { return Err(format!( "invoke `{}` arg `{name}` must be {}, got {value}", @@ -1516,14 +1500,16 @@ pub(crate) fn coerce_invoke_args( let Some(Value::String(text)) = bound.get(name) else { continue; }; - let parsed = match spec.ty.as_str() { - "number" => text.parse::().ok().map(Value::Number), - "integer" => text + let parsed = match crate::schema::ArgType::parse(&spec.ty) { + Some(crate::schema::ArgType::Number) => { + text.parse::().ok().map(Value::Number) + } + Some(crate::schema::ArgType::Integer) => text .parse::() .map(Value::from) .or_else(|_| text.parse::().map(Value::from)) .ok(), - "bool" | "boolean" => text.parse::().ok().map(Value::Bool), + Some(crate::schema::ArgType::Boolean) => text.parse::().ok().map(Value::Bool), _ => continue, }; let value = parsed.ok_or_else(|| { diff --git a/crates/gpui-agent-recipe/src/schema.rs b/crates/gpui-agent-recipe/src/schema.rs index d9620f0..6ab9955 100644 --- a/crates/gpui-agent-recipe/src/schema.rs +++ b/crates/gpui-agent-recipe/src/schema.rs @@ -236,6 +236,66 @@ pub(crate) const SUPPORTED_ARG_TYPES: &[&str] = &[ "string", "number", "integer", "bool", "boolean", "object", "array", "any", ]; +/// The canonical meaning of one supported argument type spelling. The +/// public schema metadata keeps its original string (`bool` stays `bool`, +/// not `boolean`); this internal enum keeps every consumer from reparsing +/// — and potentially disagreeing about — the accepted spellings. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub(crate) enum ArgType { + String, + Number, + Integer, + Boolean, + Object, + Array, + Any, +} + +impl ArgType { + /// Parse a supported spelling, canonicalizing `bool` and `boolean` to + /// the one boolean meaning. Unknown spellings are schema errors. + pub(crate) fn parse(spelling: &str) -> Option { + match spelling { + "string" => Some(Self::String), + "number" => Some(Self::Number), + "integer" => Some(Self::Integer), + "bool" | "boolean" => Some(Self::Boolean), + "object" => Some(Self::Object), + "array" => Some(Self::Array), + "any" => Some(Self::Any), + _ => None, + } + } + + /// True when `value` satisfies this top-level type. `integer` means a + /// JSON integer literal, not a floating-point value such as `1.0`. + pub(crate) fn accepts(self, value: &serde_json::Value) -> bool { + match self { + Self::String => value.is_string(), + Self::Number => value.is_number(), + Self::Integer => value.is_i64() || value.is_u64(), + Self::Boolean => value.is_boolean(), + Self::Object => value.is_object(), + Self::Array => value.is_array(), + Self::Any => true, + } + } + + /// The JSON Schema type keyword for this type, except `any`, which + /// constrains nothing and therefore has no keyword to emit. + pub(crate) fn json_schema_type(self) -> Option<&'static str> { + match self { + Self::String => Some("string"), + Self::Number => Some("number"), + Self::Integer => Some("integer"), + Self::Boolean => Some("boolean"), + Self::Object => Some("object"), + Self::Array => Some("array"), + Self::Any => None, + } + } +} + /// Backtracking steps one embedded `pattern`/`patternProperties` match /// may take before the match is undecided (and validation errors when /// the outcome depends on it). JSON Schema patterns are full regexes on @@ -293,6 +353,19 @@ impl OpSchema { self.args.as_ref()?.get(name) } + /// Every required argument name: the legacy `required` list unioned + /// with the argument specs marked required. Iterating the union here + /// keeps validation and schema generation from drifting apart. + pub(crate) fn required_args(&self) -> impl Iterator { + self.required.iter().map(String::as_str).chain( + self.args + .iter() + .flatten() + .filter(|(_, spec)| spec.required) + .map(|(name, _)| name.as_str()), + ) + } + /// A schema with only its name, kind and description: no declared /// effects (treated as Write), args not listed, not idempotent, not /// verified. @@ -337,7 +410,7 @@ impl OpSchema { )); } for (arg_name, spec) in self.args.iter().flatten() { - if !SUPPORTED_ARG_TYPES.contains(&spec.ty.as_str()) { + if ArgType::parse(&spec.ty).is_none() { return Err(err( RecipeErrorCode::InvalidSchema, format!( diff --git a/crates/gpui-agent-recipe/tests/generated_schema.rs b/crates/gpui-agent-recipe/tests/generated_schema.rs new file mode 100644 index 0000000..438a954 --- /dev/null +++ b/crates/gpui-agent-recipe/tests/generated_schema.rs @@ -0,0 +1,419 @@ +//! The generated per-app recipe schema against `recipe validate`, on the +//! shapes the todo registry does not exercise: embedded argument schemas, +//! the required union, closed and open argument lists, null and absent +//! `args`, and internal `$ref` resources. +//! +//! The schema is an editor aid; `validate_recipe` is the authority. Every +//! case here states both verdicts where the two must agree. + +use std::collections::BTreeMap; + +use gpui_agent_recipe::{ + ArgSchema, OpSchema, Recipe, Registry, SchemaKind, base_recipe_schema, + recipe_schema_for_registry, validate_recipe, +}; +use serde_json::{Value, json}; + +/// A one-invoke registry, generated schema and compiled validator in one. +struct Generated { + validator: jsonschema::Validator, + registry: Registry, +} + +fn generated(schemas: impl IntoIterator) -> Generated { + let mut registry = Registry::new(); + for schema in schemas { + registry.insert(schema).expect("fixture schema validates"); + } + let schema = + recipe_schema_for_registry(&base_recipe_schema(), ®istry).expect("generation succeeds"); + Generated { + validator: jsonschema::validator_for(&schema).expect("the generated schema compiles"), + registry, + } +} + +fn invoke_schema( + name: &str, + args: Option>, + required: &[&str], +) -> OpSchema { + let mut schema = OpSchema::new(name, SchemaKind::Invoke, "fixture invoke"); + schema.args = args; + schema.required = required.iter().map(|name| (*name).to_string()).collect(); + schema +} + +fn doc(name: &str, args: Option) -> Value { + let mut step = json!({"id": "a", "op": "invoke", "name": name}); + if let Some(args) = args { + step["args"] = args; + } + json!({"name": "r", "steps": [step]}) +} + +/// The verdict pair for one recipe document. `validate` is the authority; +/// where it accepts, the generated schema must accept. +fn verdicts(generated: &Generated, doc: &Value) -> (bool, bool) { + let validates = Recipe::from_value(doc) + .is_ok_and(|recipe| validate_recipe(&recipe, &generated.registry).is_ok()); + (generated.validator.is_valid(doc), validates) +} + +/// Exact agreement is expected for these cases: none of the documented +/// JSON Schema gaps (params, escaping, node refs) is in play. +fn agree(generated: &Generated, doc: &Value) { + let (schema, validate) = verdicts(generated, doc); + assert_eq!( + schema, validate, + "schema {schema}, validate {validate} for {doc}" + ); +} + +#[test] +fn embedded_arg_schemas_are_reflected() { + let mut args = BTreeMap::new(); + args.insert( + "rows".into(), + ArgSchema::new("array").with_schema(json!({ + "type": "array", + "items": {"type": "integer"}, + })), + ); + let generated = generated([invoke_schema("x.save", Some(args), &[])]); + + for rows in [json!([1, 2]), json!([])] { + let document = doc("x.save", Some(json!({"rows": rows}))); + let (schema, validate) = verdicts(&generated, &document); + assert!(schema && validate, "{rows} must pass: {document}"); + } + // Embedded violations are refused by both. + let document = doc("x.save", Some(json!({"rows": ["x"]}))); + let (schema, validate) = verdicts(&generated, &document); + assert!(!schema && !validate, "a string item must fail: {document}"); + + // A string holding a $param skips the type and the embedded schema + // in validation, so the schema grants it too. (`rows` is undeclared + // as a param here, which validation reports as a param problem — the + // comparison is on the args shape, so the param is declared below.) + let document = json!({ + "name": "r", + "params": ["rows"], + "steps": [{"id": "a", "op": "invoke", "name": "x.save", "args": {"rows": "$rows"}}], + }); + let (schema, validate) = verdicts(&generated, &document); + assert!( + schema && validate, + "a placeholder string must pass: {document}" + ); +} + +#[test] +fn embedded_schemas_compose_with_the_top_level_type() { + let mut args = BTreeMap::new(); + args.insert( + "meta".into(), + ArgSchema::new("object").with_schema(json!({ + "type": "object", + "properties": {"owner": {"type": "string"}}, + "required": ["owner"], + })), + ); + let generated = generated([invoke_schema("x.save", Some(args), &[])]); + + // An array is inside no object schema: the top-level type fails even + // though the embedded schema's own type would fail it too. + agree( + &generated, + &doc("x.save", Some(json!({"meta": {"owner": "me"}}))), + ); + agree(&generated, &doc("x.save", Some(json!({"meta": []})))); + agree(&generated, &doc("x.save", Some(json!({"meta": {}})))); +} + +#[test] +fn internal_refs_survive_embedding_and_existing_ids_are_kept() { + let mut args = BTreeMap::new(); + args.insert( + "meta".into(), + ArgSchema::new("object").with_schema(json!({ + "type": "object", + "properties": {"owner": {"$ref": "#/$defs/owner"}}, + "$defs": {"owner": {"type": "string", "pattern": "^[a-z]+$"}}, + "required": ["owner"], + "additionalProperties": false, + })), + ); + args.insert( + "tagged".into(), + ArgSchema::new("object").with_schema(json!({ + "$id": "urn:fixture:kept", + "type": "object", + "properties": {"owner": {"$ref": "#/$defs/owner"}}, + "$defs": {"owner": {"type": "integer"}}, + })), + ); + let generated = generated([invoke_schema("x.save", Some(args), &[])]); + + // Both compile in one document — the generated `$id` and the kept + // one — and each internal ref means its own `$defs`. + let document = doc( + "x.save", + Some(json!({"meta": {"owner": "me"}, "tagged": {"owner": 1}})), + ); + let (schema, validate) = verdicts(&generated, &document); + assert!(schema && validate, "{document}"); + // `meta.owner` is the lowercase pattern, `tagged.owner` an integer: + // neither ref spilled into the other resource or the recipe root. + let document = doc( + "x.save", + Some(json!({"meta": {"owner": "ME"}, "tagged": {"owner": 1}})), + ); + assert!(!generated.validator.is_valid(&document), "{document}"); + let document = doc( + "x.save", + Some(json!({"meta": {"owner": "me"}, "tagged": {"owner": "me"}})), + ); + assert!(!generated.validator.is_valid(&document), "{document}"); +} + +#[test] +fn nested_placeholders_relax_embedded_validation_like_validate() { + let mut args = BTreeMap::new(); + args.insert( + "meta".into(), + ArgSchema::new("object").with_schema(json!({ + "type": "object", + "properties": {"owner": {"type": "integer"}}, + "required": ["owner"], + "additionalProperties": false, + })), + ); + let generated = generated([invoke_schema("x.save", Some(args), &[])]); + let document = |owner: Value, extra: Option, params: &[&str]| { + let mut meta = json!({"owner": owner}); + if let Some(extra) = extra { + meta["extra"] = extra; + } + json!({ + "name": "r", + "params": params, + "steps": [{"id": "a", "op": "invoke", "name": "x.save", "args": {"meta": meta}}], + }) + }; + + // Without a placeholder the embedded schema keeps its force. + let (schema, validate) = verdicts(&generated, &document(json!(1), None, &[])); + assert!(schema && validate); + let invalid = document(json!("not a placeholder"), None, &[]); + let (schema, validate) = verdicts(&generated, &invalid); + assert!(!schema && !validate, "{invalid}"); + + // A nested placeholder makes validation skip the embedded schema until + // binding. The generated recursive probe must accept the same shape + // rather than turning a valid unbound recipe into an editor error. + let dynamic = document(json!("$owner"), None, &["owner"]); + let (schema, validate) = verdicts(&generated, &dynamic); + assert!( + schema && validate, + "schema {schema}, validate {validate}: {dynamic}" + ); + + // The probe is genuinely recursive: validation scans arbitrary nested + // object/array positions too, even positions the closed embedded schema + // would otherwise reject while unbound. + let deeply_dynamic = document(json!(1), Some(json!({"nested": ["$owner"]})), &["owner"]); + let (schema, validate) = verdicts(&generated, &deeply_dynamic); + assert!( + schema && validate, + "schema {schema}, validate {validate}: {deeply_dynamic}" + ); +} + +#[test] +fn boolean_embedded_schemas_embed_unchanged() { + let mut args = BTreeMap::new(); + args.insert( + "anything".into(), + ArgSchema::new("any").with_schema(json!(true)), + ); + args.insert( + "nothing".into(), + ArgSchema::new("any").with_schema(json!(false)), + ); + let generated = generated([invoke_schema("x.gate", Some(args), &[])]); + + agree(&generated, &doc("x.gate", Some(json!({"anything": 5})))); + let document = doc("x.gate", Some(json!({"nothing": 5}))); + let (schema, validate) = verdicts(&generated, &document); + assert!(!schema && !validate, "`false` admits no value: {document}"); +} + +#[test] +fn required_is_the_union_of_required_and_required_specs() { + let mut args = BTreeMap::new(); + args.insert("title".into(), ArgSchema::new("string")); + let mut spec = ArgSchema::new("integer"); + spec.required = true; + args.insert("id".into(), spec); + // `title` comes from the schema's required list, `id` from its spec. + let generated = generated([invoke_schema("x.mixed", Some(args), &["title"])]); + + agree( + &generated, + &doc("x.mixed", Some(json!({"title": "t", "id": 1}))), + ); + for missing in [json!({"title": "t"}), json!({"id": 1}), json!({})] { + let document = doc("x.mixed", Some(missing)); + let (schema, validate) = verdicts(&generated, &document); + assert!( + !schema && !validate, + "missing half of the union: {document}" + ); + } + // Absent `args` can never hold a required argument: both refuse. + agree(&generated, &doc("x.mixed", None)); +} + +#[test] +fn a_legacy_required_name_is_declared_untyped_in_the_closed_object() { + let mut args = BTreeMap::new(); + args.insert("title".into(), ArgSchema::new("string")); + // `target` is one of the legacy names a schema may require without an + // args entry. Validation accepts any value for it; the closed object + // must not reject it as undeclared. + let generated = generated([invoke_schema("x.legacy", Some(args), &["target"])]); + + for value in [json!("todo-input"), json!(5), json!({"x": 1})] { + let document = doc("x.legacy", Some(json!({"title": "t", "target": value}))); + let (schema, validate) = verdicts(&generated, &document); + assert!(schema && validate, "target untyped: {document}"); + } + // …while a genuinely undeclared name still fails closed. + agree( + &generated, + &doc( + "x.legacy", + Some(json!({"title": "t", "target": "x", "zz": 1})), + ), + ); +} + +#[test] +fn closed_empty_args_and_open_unlisted_args() { + let closed = generated([invoke_schema("x.closed", Some(BTreeMap::new()), &[])]); + // `"args": {}` means the invoke takes none. + let document = doc("x.closed", Some(json!({"limit": 5}))); + let (schema, validate) = verdicts(&closed, &document); + assert!(!schema && !validate, "closed takes no args: {document}"); + agree(&closed, &doc("x.closed", Some(json!({})))); + agree(&closed, &doc("x.closed", None)); + + // Args left out of the schema entirely: names are unchecked. + let open = generated([invoke_schema("x.open", None, &[])]); + for args in [json!({"anything": 1}), json!({})] { + let document = doc("x.open", Some(args)); + let (schema, validate) = verdicts(&open, &document); + assert!(schema && validate, "open args: {document}"); + } +} + +#[test] +fn null_args_read_as_the_empty_object() { + // No required args: null is `{}`, and both accept it. + let open = generated([invoke_schema("x.none", Some(BTreeMap::new()), &[])]); + let document = doc("x.none", Some(Value::Null)); + let (schema, validate) = verdicts(&open, &document); + assert!(schema && validate, "null reads as {{}}: {document}"); + + // A required argument makes null a missing argument: both refuse. + let mut args = BTreeMap::new(); + args.insert("title".into(), ArgSchema::new("string")); + let required = generated([invoke_schema("x.need", Some(args), &["title"])]); + let document = doc("x.need", Some(Value::Null)); + let (schema, validate) = verdicts(&required, &document); + assert!( + !schema && !validate, + "null holds no required arg: {document}" + ); +} + +#[test] +fn non_object_args_pass_only_for_an_unlisted_invoke_without_required() { + // Neither listed nor required: validation knows nothing, so even a + // non-object passes — and the schema must not be stricter. + let open = generated([invoke_schema("x.open", None, &[])]); + for args in [json!(5), json!("text"), json!([1])] { + let document = doc("x.open", Some(args)); + let (schema, validate) = verdicts(&open, &document); + assert!(schema && validate, "unlisted accepts anything: {document}"); + } + + // Listed, even empty: a non-object fails both ways. + let closed = generated([invoke_schema("x.closed", Some(BTreeMap::new()), &[])]); + let document = doc("x.closed", Some(json!(5))); + let (schema, validate) = verdicts(&closed, &document); + assert!( + !schema && !validate, + "listed args must be an object: {document}" + ); + + // Unlisted but requiring a name: only an object can hold it. + let constrained = generated([invoke_schema("x.constrained", None, &["target"])]); + let document = doc("x.constrained", Some(json!(5))); + let (schema, validate) = verdicts(&constrained, &document); + assert!(!schema && !validate, "a number holds no target: {document}"); + let document = doc("x.constrained", Some(json!({"target": "x", "extra": true}))); + let (schema, validate) = verdicts(&constrained, &document); + assert!(schema && validate, "unlisted stays open: {document}"); +} + +#[test] +fn typed_args_admit_placeholder_strings() { + let mut args = BTreeMap::new(); + args.insert("id".into(), ArgSchema::new("integer")); + args.insert("ratio".into(), ArgSchema::new("number")); + args.insert("done".into(), ArgSchema::new("boolean")); + args.insert("meta".into(), ArgSchema::new("object")); + args.insert("rows".into(), ArgSchema::new("array")); + args.insert("anything".into(), ArgSchema::new("any")); + let generated = generated([invoke_schema("x.typed", Some(args), &[])]); + + for (name, value) in [ + ("id", json!("$id")), + ("id", json!("pre-${id}-post")), + ("ratio", json!("$ratio")), + ("done", json!("$done")), + ("meta", json!("$meta")), + ("rows", json!("$rows")), + ("anything", json!("$anything")), + ] { + // Each document declares exactly the one param its placeholder + // uses: validate refuses declared-but-unused params, which is one + // of the rules a JSON Schema cannot state. + let document = json!({ + "name": "r", + "params": [name], + "steps": [{"id": "a", "op": "invoke", "name": "x.typed", "args": {name: value}}], + }); + let (schema, validate) = verdicts(&generated, &document); + assert!(schema && validate, "{name} = {value}: {document}"); + } + + // Typed values pass; mistyped non-placeholder values fail both ways. + agree(&generated, &doc("x.typed", Some(json!({"id": 1})))); + let document = doc("x.typed", Some(json!({"id": "1"}))); + let (schema, validate) = verdicts(&generated, &document); + assert!( + !schema && !validate, + "a plain string is no integer: {document}" + ); +} + +#[test] +fn an_unknown_invoke_matches_no_branch() { + let generated = generated([invoke_schema("x.known", Some(BTreeMap::new()), &[])]); + let document = doc("x.unknown", Some(json!({}))); + let (schema, validate) = verdicts(&generated, &document); + assert!(!schema && !validate, "fail closed: {document}"); +} diff --git a/crates/gpui-agent-recipe/tests/schema_parity.rs b/crates/gpui-agent-recipe/tests/schema_parity.rs index 6f260a9..8e5a1c4 100644 --- a/crates/gpui-agent-recipe/tests/schema_parity.rs +++ b/crates/gpui-agent-recipe/tests/schema_parity.rs @@ -15,7 +15,9 @@ use std::path::Path; -use gpui_agent_recipe::{Recipe, todo_registry, validate_recipe}; +use gpui_agent_recipe::{ + Recipe, base_recipe_schema, recipe_schema_for_registry, todo_registry, validate_recipe, +}; use serde_json::{Map, Value, json}; /// The schema, or `None` outside the workspace: the published crate does @@ -276,6 +278,75 @@ fn schema_and_parser_agree_on_documents() { ); } +/// The generated per-app schema, specialized with the same todo registry +/// validation uses. Unlike the static file this is always available to the +/// published crate, so there is no workspace-only escape hatch. +fn generated_todo_schema() -> Value { + recipe_schema_for_registry(&base_recipe_schema(), &todo_registry()) + .expect("the todo registry generates a compilable schema") +} + +fn invoke_doc(name: &str, args: &Value, params: &[&str]) -> Value { + json!({ + "name": "probe", + "params": params, + "steps": [{"id": "invoke", "op": "invoke", "name": name, "args": args}], + }) +} + +#[test] +fn generated_schema_agrees_with_validate_on_the_issue_115_rows() { + let validator = jsonschema::validator_for(&generated_todo_schema()) + .expect("the generated todo schema compiles"); + let rows = [ + ("todo.add", json!({"title": "Buy milk"}), &[][..], true), + ("todo.add", json!({"title": 5}), &[][..], false), + ( + "todo.add", + json!({"title": "x", "colour": "red"}), + &[][..], + false, + ), + ("todo.add", json!({}), &[][..], false), + ("todo.list", json!({"limit": 5}), &[][..], false), + ("todo.nope", json!({"x": 1}), &[][..], false), + ("todo.toggle", json!({"id": "$id"}), &["id"][..], true), + ]; + for (name, args, params, expected) in rows { + let doc = invoke_doc(name, &args, params); + let schema_valid = validator.is_valid(&doc); + let validate_valid = Recipe::from_value(&doc) + .is_ok_and(|recipe| validate_recipe(&recipe, &todo_registry()).is_ok()); + assert_eq!( + schema_valid, validate_valid, + "{name} args must agree (schema {schema_valid}, validate {validate_valid})" + ); + assert_eq!(schema_valid, expected, "{name} issue-table verdict"); + } +} + +#[test] +fn generated_schema_accepts_every_valid_full_recipe_mutation() { + let validator = jsonschema::validator_for(&generated_todo_schema()) + .expect("the generated todo schema compiles"); + let full = full_recipe(); + let mut problems = Vec::new(); + for (what, doc) in + std::iter::once(("whole document".to_string(), full.clone())).chain(one_change_from(&full)) + { + let validates = Recipe::from_value(&doc) + .is_ok_and(|recipe| validate_recipe(&recipe, &todo_registry()).is_ok()); + if validates && !validator.is_valid(&doc) { + problems.push(what); + } + } + assert!( + problems.is_empty(), + "valid documents the generated schema rejects:\n{}", + problems.join("\n") + ); +} + /// The one difference a JSON Schema cannot state: its `integer` is any /// number with no fractional part, so it admits `1.0`; the parser reads a /// whole-number field only from a JSON integer. diff --git a/docs/RECIPES.md b/docs/RECIPES.md index da27650..18677f7 100644 --- a/docs/RECIPES.md +++ b/docs/RECIPES.md @@ -21,7 +21,7 @@ without a new format version or a new major crate version. | --- | --- | | Recipe file | Fields and rules in [Recipe format](#recipe-format); `schemas/recipe.v1.schema.json` | | `.wants` | Line grammar in [`.wants`](#wants) | -| CLI | `recipe validate`, `recipe plan`, `recipe run`, their flags, exit status, and what is printed on stdout | +| CLI | `recipe validate`, `recipe plan`, `recipe run`, `recipe schema`, their flags, exit status, and what is printed on stdout | | MCP | `recipe_validate`, `recipe_plan`, `recipe_run`, their arguments and results | | Plan JSON | Fields in [Plan](#plan), versioned by `v` | | Receipt JSON | Fields in [Receipt](#receipt), versioned by `v` | @@ -471,6 +471,57 @@ what keeps names like `nav.go` honest: the demo host declares it once in its table, and validation, the wire listing, and the pre-dispatch argument check all read that one row. +### A schema per app: `recipe schema` + +`schemas/recipe.v1.schema.json` leaves `invoke.args` untyped, because +what an invoke takes is defined by the app, not by the recipe format. +`gpui-agent recipe schema` prints that same schema specialized for one +app: the generic `invoke` step branch is replaced by one branch per +invoke the registry knows, so an editor — or any JSON Schema validator — +can check an invoke step's `args` before `recipe validate` runs. + +```bash +gpui-agent recipe schema --schema examples/schemas/todo.json > todo.recipe.schema.json +gpui-agent --session todo recipe schema > todo.recipe.schema.json # from the live table +``` + +The invoke metadata is exactly the registry validation uses: schema +files offline, the live host's table merged in when a target is named on +the command line — never from the ambient target environment variables +alone. Each branch: + +- pins `name` as a `const` — a name no branch carries matches none, + exactly as `recipe_unknown_invoke` fails closed; +- builds `args` from the invoke's argument specs: one property per + argument, `required` the union of the schema's `required` and the + specs marked required, an embedded per-argument `"schema": …` + reflected and composed with the top-level type, closed + `additionalProperties` when the invoke lists its args (including + `"args": {}`) and open when it does not. A required name with no + argument spec is declared untyped, so the closed object does not + reject what validation accepts; +- admits a string holding a `$param` placeholder for every typed + argument, because `"id": "$id"` is valid before binding; +- requires the `args` key itself when the invoke has required arguments + and accepts `null` when it has none — both mirror validation reading + missing or null `args` as `{}`. An invoke that neither lists its args + nor requires any accepts any `args` value at all, exactly as + validation does. + +The generated schema is compiled offline before it is printed; embedded +argument schemas that use internal `$ref` / `$dynamicRef` pointers keep +their meaning through a preserved or generated deterministic `$id`. When +an embedded object or array argument holds a placeholder-shaped string at +any depth, a recursive generated probe relaxes the embedded schema for +that value, mirroring validation's unbound-value rule. It stays an editor +aid, not the validator. Unknown `needs`, cycles, undeclared or unused +params, and the exact `$$` escaping and `$.node` runtime-reference +rules are all things a JSON Schema cannot state exactly, so +`recipe validate` remains the authority. The one-directional contract, +pinned by `crates/gpui-agent-recipe/tests/schema_parity.rs` against the +generated todo schema: what `recipe validate` accepts, the generated +schema accepts. + ### Confirmation - A plan containing `shutdown`, or a quit keybinding, has @@ -539,6 +590,7 @@ assert todo-item-1 checked=true | `recipe validate ` | Only with `--addr` / `--connect` / `--session` | No | Parse and check every rule above | | `recipe plan [--set k=v]… [--order-check]` | Only with `--addr` / `--connect` / `--session` | No | Validate, bind params, print the [plan](#plan) | | `recipe run [--set k=v]… [--yes] [--receipt-out FILE] [--screenshot-dir DIR [--screenshot-flagged]]` | Yes | Yes | Plan, run, print the [receipt](#receipt) | +| `recipe schema` | Only with `--addr` / `--connect` / `--session` | No | Print the recipe JSON Schema [specialized for the app's invokes](#a-schema-per-app-recipe-schema), for editors | | `recipe resolve ''` | Only with `--addr` / `--connect` / `--session` | No | Experimental. Map prose to a schema-backed op, or fail | All take `--schema PATH`. `recipe run` requires a non-empty @@ -565,6 +617,7 @@ Output contract: | --- | --- | --- | --- | | `validate` ok | 0 | `{"ok": true, "name", "steps", "params" (names), "input_schema", "explicit_needs"}` | | | `plan` ok | 0 | Plan JSON (or order-check JSON) | | +| `schema` ok | 0 | The generated recipe JSON Schema | | | `run` ok | 0 | Receipt JSON, `ok: true` | | | Rejected before running | 1 | Error envelope | `error: ` | | `run`, a step failed | 1 | Partial receipt JSON, `ok: false` | `error: ` |