Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 `$<step>.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
Expand Down
24 changes: 19 additions & 5 deletions crates/gpui-agent-cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -814,6 +814,7 @@ fn run() -> Result<()> {
Command::Recipe {
action: RecipeCommand::Validate { .. }
| RecipeCommand::Plan { .. }
| RecipeCommand::Schema
| RecipeCommand::Resolve { .. },
..
}
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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}"
);
}
Expand Down Expand Up @@ -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");
Expand Down Expand Up @@ -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",
Expand Down
23 changes: 17 additions & 6 deletions crates/gpui-agent-cli/src/recipe_cmd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)]
Expand Down Expand Up @@ -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 },
}
Expand Down Expand Up @@ -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(), &registry)
.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, &registry).map_err(anyhow::Error::new)?;
Expand Down
150 changes: 150 additions & 0 deletions crates/gpui-agent-cli/tests/recipe_live_schema.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(", ")
);
}
Loading
Loading