Skip to content

LightCraft: An open-source non-destructive photo editor written by scratch in pure Rust

M0.9: lightcraft-cli run — one-shot command chains for agents

Brandon Thomas80dfb437c1ac
diff --git a/README.md b/README.md
index acb6ac88a..ac8ee6e73 100644
--- a/README.md
+++ b/README.md
@@ -244,7 +244,9 @@ lightcraft --control 7980 ~/Pictures/trip
claude mcp add lightcraft -- "$PWD/target/release/lightcraft-cli" mcp ~/Pictures/shoot # headless
claude mcp add lightcraft-app -- "$PWD/target/release/lightcraft-cli" mcp --connect 127.0.0.1:7980 # live app
```
-- **Scriptable CLI:** `lightcraft-cli render in.dng -o out.jpg --set light.exposure=0.7 --preset …`.
+- **Scriptable CLI:** `lightcraft-cli run --import in.dng develop.set control=light.exposure value=0.7 app.export
+ path=out.jpg longEdge=2048` runs any chain of commands (headless, on a saved library, or against the running app)
+ and prints one JSON result per command; `lightcraft-cli render in.dng -o out.jpg --set light.exposure=0.7 --preset …`.
- **Undo for everything**, including agent actions: a slider drag (or a scripted burst of updates) is one undo step.
- **Every widget is addressable** (`ui.widgets`) and clickable by name, so agents operate the real UI, not a
side door.
diff --git a/apps/lightcraft-cli/src/main.rs b/apps/lightcraft-cli/src/main.rs
index 469906a7b..77fb2fc2d 100644
--- a/apps/lightcraft-cli/src/main.rs
+++ b/apps/lightcraft-cli/src/main.rs
@@ -1,6 +1,7 @@
//! `lightcraft-cli`: headless LightCraft.
//!
//! ```text
+//! lightcraft-cli run [--demo | --library DIR | --connect [ADDR]] [--import PATH]… CMD [key=value…]…
//! lightcraft-cli mcp [--connect [ADDR]] [--demo] [--compact] [FILES/FOLDERS…]
//! lightcraft-cli render <in> -o <out> [--set control=value]… [--settings FILE.json] [--preset ID] [--size N] [--quality Q]
//! lightcraft-cli snapshot [--library DIR | --demo] [--script FILE.jsonl] [-o OUT.png] [--size WxH] [--scale S] [FILES…]
@@ -24,6 +25,21 @@ const USAGE: &str = "\
lightcraft-cli — headless LightCraft (photo library + raw developer)
USAGE:
+ lightcraft-cli run [OPTIONS] COMMAND [key=value | '{json}']… [COMMAND …]…
+ Run one or more commands (ids from `commands`, or control-protocol methods such as
+ engine.commands / ui.inspect / ui.screenshot) and print one JSON line per command:
+ {\"command\", \"ok\", \"result\" | \"error\", \"ms\"}. A word without `=` starts the next
+ command; values are JSON when they parse (1, true, [1,2], {…}), else strings. Exit status
+ is non-zero when a command fails. Example:
+ lightcraft-cli run --import ~/Photos/a.jpg develop.set control=light.exposure value=0.7 \\
+ develop.auto app.export path=/tmp/a.jpg longEdge=1600
+ Options:
+ --demo headless, the procedural demo library
+ --library DIR headless, open (or create) a LightCraft library; edits are saved
+ --import PATH headless, import a file or folder first (repeatable)
+ --connect [ADDR] drive the running app (`lightcraft --control 7980`; default 127.0.0.1:7980)
+ --script FILE|- also run JSON lines {\"command\": id, \"params\": {…}} (or {\"method\": …})
+ --keep-going continue after a failed command
lightcraft-cli mcp [OPTIONS] [FILES/FOLDERS…]
MCP server (JSON-RPC 2.0 over stdio). Headless by default: an in-process session with the
given files imported. Options:
@@ -88,6 +104,7 @@ fn main() -> ExitCode {
alloc_release::install();
let args: Vec<String> = std::env::args().skip(1).collect();
let r = match args.first().map(String::as_str) {
+ Some("run") => run(&args[1..]),
Some("mcp") => mcp(&args[1..]),
Some("render") => render(&args[1..]),
Some("snapshot") => snapshot(&args[1..]),
@@ -290,6 +307,151 @@ fn synth_merge(args: &[String]) -> Result<(), String> {
Ok(())
}
+/// One step of `lightcraft-cli run`: a command id (or control-protocol method) and its params.
+#[derive(Debug, PartialEq)]
+struct Step {
+ id: String,
+ params: Value,
+}
+
+/// Parse `CMD [key=value | {json}]… CMD …` into steps. A token without `=` that doesn't start
+/// with `{` begins a new command; values are JSON when they parse, else strings.
+fn parse_steps(tokens: &[String]) -> Result<Vec<Step>, String> {
+ let mut steps: Vec<Step> = Vec::new();
+ for t in tokens {
+ if t.starts_with('{') {
+ let v: Value = serde_json::from_str(t).map_err(|e| format!("bad JSON params `{t}`: {e}"))?;
+ let step = steps.last_mut().ok_or_else(|| format!("params `{t}` before any command"))?;
+ match (step.params.as_object_mut(), v) {
+ (Some(o), Value::Object(m)) => o.extend(m),
+ _ => return Err(format!("params `{t}` must be a JSON object")),
+ }
+ } else if let Some((k, v)) = t.split_once('=') {
+ let step = steps.last_mut().ok_or_else(|| format!("param `{t}` before any command"))?;
+ let v = serde_json::from_str(v).unwrap_or_else(|_| json!(v));
+ step.params[k.trim()] = v;
+ } else {
+ steps.push(Step { id: t.clone(), params: json!({}) });
+ }
+ }
+ Ok(steps)
+}
+
+/// Run one step: control-protocol methods (`ui.*`, `engine.*`) directly, everything else as a
+/// command through `engine.execute`.
+fn run_step(b: &mut dyn Backend, s: &Step) -> Result<Value, String> {
+ let direct = s.id.starts_with("ui.") || s.id.starts_with("engine.") || s.id == "app.quit";
+ if direct { b.call(&s.id, s.params.clone()) } else { b.call("engine.execute", json!({"command": s.id, "params": s.params})) }
+}
+
+fn run(args: &[String]) -> Result<(), String> {
+ let mut connect: Option<String> = None;
+ let mut demo = false;
+ let mut library: Option<String> = None;
+ let mut imports = Vec::new();
+ let mut script: Option<String> = None;
+ let mut keep_going = false;
+ let mut i = 0;
+ while i < args.len() && args[i].starts_with("--") {
+ match args[i].as_str() {
+ "--" => {
+ i += 1;
+ break;
+ }
+ "--connect" => match args.get(i + 1).filter(|a| a.contains(':') && !a.contains('=')) {
+ Some(a) => {
+ connect = Some(a.clone());
+ i += 1;
+ }
+ None => connect = Some(DEFAULT_ADDR.to_string()),
+ },
+ a if a.starts_with("--connect=") => connect = Some(a["--connect=".len()..].to_string()),
+ "--demo" => demo = true,
+ "--library" => library = Some(take_value(args, &mut i, "--library")?.to_string()),
+ "--import" => imports.push(take_value(args, &mut i, "--import")?.to_string()),
+ "--script" => script = Some(take_value(args, &mut i, "--script")?.to_string()),
+ "--keep-going" => keep_going = true,
+ a => return Err(format!("unknown option `{a}`")),
+ }
+ i += 1;
+ }
+ let mut steps = parse_steps(&args[i..])?;
+ if let Some(path) = &script {
+ let text = if path == "-" {
+ let mut s = String::new();
+ std::io::Read::read_to_string(&mut std::io::stdin(), &mut s).map_err(|e| e.to_string())?;
+ s
+ } else {
+ std::fs::read_to_string(path).map_err(|e| format!("{path}: {e}"))?
+ };
+ for (n, line) in text.lines().enumerate().filter(|(_, l)| !l.trim().is_empty() && !l.trim_start().starts_with('#')) {
+ let v: Value = serde_json::from_str(line).map_err(|e| format!("{path}:{}: {e}", n + 1))?;
+ // `{"command": id, "params": …}` or a control request `{"method": m, "params": …}`
+ let id = v
+ .get("command")
+ .or(v.get("method"))
+ .and_then(Value::as_str)
+ .ok_or_else(|| format!("{path}:{}: needs `command` or `method`", n + 1))?;
+ let params = v.get("params").cloned().filter(|p| p.is_object()).unwrap_or_else(|| json!({}));
+ steps.push(Step { id: id.to_string(), params });
+ }
+ }
+ if steps.is_empty() {
+ return Err("run: no command given (see `lightcraft-cli commands`)".into());
+ }
+ let mut backend: Box<dyn Backend> = match connect {
+ Some(addr) => {
+ if demo || library.is_some() || !imports.is_empty() {
+ return Err("--demo, --library and --import apply to headless mode only".into());
+ }
+ Box::new(
+ Remote::connect(&addr)
+ .map_err(|e| format!("LightCraft is not reachable at {addr} ({e}); start it with `lightcraft --control 7980`"))?,
+ )
+ }
+ None => {
+ let mut h = match &library {
+ Some(dir) => {
+ let mut h = Headless::default();
+ h.session.open_library(dir, demo).map_err(|e| e.to_string())?;
+ h
+ }
+ None if demo => Headless::demo(),
+ None => Headless::default(),
+ };
+ if !imports.is_empty() {
+ let paths = expand_paths(&imports);
+ let r = h.session.execute("library.import", &json!({"paths": paths})).map_err(|e| e.to_string())?;
+ // what follows acts on the imported photos (already-known files are reported as duplicates)
+ let mut ids: Vec<Value> = r["imported"].as_array().cloned().unwrap_or_default();
+ ids.extend(r["duplicates"].as_array().into_iter().flatten().filter_map(|d| d.get("existing").filter(|v| v.is_u64()).cloned()));
+ if let Some(first) = ids.first().cloned() {
+ h.session.execute("library.select", &json!({"ids": ids, "active": first})).map_err(|e| e.to_string())?;
+ }
+ }
+ Box::new(h)
+ }
+ };
+ let mut out = std::io::stdout().lock();
+ let mut failed = 0;
+ for s in &steps {
+ let t = std::time::Instant::now();
+ let line = match run_step(backend.as_mut(), s) {
+ Ok(r) => json!({"command": s.id, "ok": true, "result": r, "ms": (t.elapsed().as_secs_f64() * 1e4).round() / 10.0}),
+ Err(e) => {
+ failed += 1;
+ json!({"command": s.id, "ok": false, "error": e})
+ }
+ };
+ writeln!(out, "{line}").map_err(|e| e.to_string())?;
+ if failed > 0 && !keep_going {
+ break;
+ }
+ }
+ drop(backend); // a library session is flushed here
+ if failed > 0 { Err(format!("{failed} command(s) failed")) } else { Ok(()) }
+}
+
fn take_value<'a>(args: &'a [String], i: &mut usize, flag: &str) -> Result<&'a str, String> {
*i += 1;
args.get(*i).map(String::as_str).ok_or_else(|| format!("{flag} needs a value"))
diff --git a/apps/lightcraft-cli/tests/cli.rs b/apps/lightcraft-cli/tests/cli.rs
index 0ee59fa88..ab91901d5 100644
--- a/apps/lightcraft-cli/tests/cli.rs
+++ b/apps/lightcraft-cli/tests/cli.rs
@@ -164,3 +164,63 @@ fn snapshot_subcommand_renders_the_ui_headlessly() {
let d = lightcraft_codecs::decode(&std::fs::read(&a).unwrap(), Default::default()).unwrap();
assert_eq!((d.width, d.height), (640, 480));
}
+
+fn run_cli(args: &[&str], stdin: Option<&str>) -> (bool, Vec<Value>, String) {
+ let mut child = Command::new(BIN).arg("run").args(args).stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped()).spawn().unwrap();
+ if let Some(text) = stdin {
+ child.stdin.take().unwrap().write_all(text.as_bytes()).unwrap();
+ }
+ drop(child.stdin.take());
+ let o = child.wait_with_output().unwrap();
+ let lines = String::from_utf8_lossy(&o.stdout).lines().map(|l| serde_json::from_str(l).unwrap()).collect();
+ (o.status.success(), lines, String::from_utf8_lossy(&o.stderr).to_string())
+}
+
+#[test]
+fn run_subcommand_chains_commands_and_persists_a_library() {
+ let input = tmp("run-in.png");
+ gradient_png(&input);
+ let lib = tmp("run-lib");
+ let _ = std::fs::remove_dir_all(&lib);
+ let out = tmp("run-out.jpg");
+ let (lib_s, in_s, out_s) = (lib.to_str().unwrap(), input.to_str().unwrap(), out.to_str().unwrap());
+ // import into a library, edit, export, in one invocation
+ let (ok, lines, err) = run_cli(
+ &[
+ "--library",
+ lib_s,
+ "--import",
+ in_s,
+ "develop.set",
+ "control=light.exposure",
+ "value=0.75",
+ "app.export",
+ &format!("path={out_s}"),
+ "width=60",
+ ],
+ None,
+ );
+ assert!(ok, "{err}");
+ assert_eq!(lines.len(), 2);
+ assert!(lines.iter().all(|l| l["ok"] == true), "{lines:?}");
+ assert_eq!(lines[1]["result"]["width"], 60);
+ assert!(out.exists());
+ // a second invocation sees the saved edit (same file: selected again, not re-imported)
+ let (ok, lines, err) = run_cli(&["--library", lib_s, "--import", in_s, "develop.get"], None);
+ assert!(ok, "{err}");
+ assert_eq!(lines[0]["result"]["light"]["exposure"], 0.75);
+ // JSON-lines script from stdin, a failing command stops the run with a non-zero status
+ let script = "{\"command\": \"library.info\"}\n# comment\n{\"command\": \"no.such\"}\n{\"command\": \"library.info\"}\n";
+ let (ok, lines, _) = run_cli(&["--demo", "--script", "-"], Some(script));
+ assert!(!ok);
+ assert_eq!(lines.len(), 2, "stopped after the failure: {lines:?}");
+ assert_eq!(lines[1]["ok"], false);
+ let (ok, lines, _) = run_cli(&["--demo", "--keep-going", "--script", "-"], Some(script));
+ assert!(!ok);
+ assert_eq!(lines.len(), 3);
+ // control-protocol methods work headlessly too; bad usage is reported
+ let (ok, lines, _) = run_cli(&["--demo", "engine.commands"], None);
+ assert!(ok && lines[0]["result"].as_array().is_some_and(|a| a.len() > 50));
+ let (ok, _, err) = run_cli(&["--demo", "x=1"], None);
+ assert!(!ok && err.contains("before any command"), "{err}");
+}
diff --git a/crates/mcp/src/headless.rs b/crates/mcp/src/headless.rs
index c35c7a519..ed602ff66 100644
--- a/crates/mcp/src/headless.rs
+++ b/crates/mcp/src/headless.rs
@@ -114,7 +114,7 @@ impl Backend for Headless {
"engine.commands" => {
let mut v: Vec<Value> = self.session.commands().into_iter().map(|c| serde_json::to_value(c).unwrap_or_default()).collect();
v.push(json!({"id": "app.export", "label": "Export Now", "menu": [], "shortcut": null,
- "params": "{path?: output file (.png/.jpg/.tif/.webp), longEdge?: pixels (3000), quality?: 1..100 (JPEG)}",
+ "params": "{path?: output file (.jpg/.png/.tif/.webp/.avif/.dng) | dir?, ids?, format?: jpeg|png|tiff|webp|avif|dng|original, longEdge?|shortEdge?|width?|height?|megapixels?|percent? (default longEdge 3000; longEdge 0 = full size), dontEnlarge?, ppi?, quality?, limitKb?, colorSpace?, bitDepth?, sharpen?, metadata?, watermark?, naming?}",
"enabled": self.session.active().is_some()}));
Ok(Value::Array(v))
}
diff --git a/docs/mcp.md b/docs/mcp.md
index 780d9bf89..01ddbafd6 100644
--- a/docs/mcp.md
+++ b/docs/mcp.md
@@ -141,9 +141,30 @@ results with `isError: true` so the model can read and correct them; malformed J
standard error codes (-32700 parse, -32600 invalid request, -32601 method not found, -32602
invalid params, -32002 resource not found).
+## One-shot commands: `lightcraft-cli run`
+
+For agents that prefer a shell over an MCP session: run any chain of commands in one process and read one JSON
+line per command (`{"command", "ok", "result" | "error", "ms"}`; non-zero exit status on failure). A word without
+`=` starts the next command; `key=value` values are JSON when they parse, else strings; a `'{…}'` argument merges a
+JSON object into the params.
+
+```sh
+# headless: import, edit, export
+lightcraft-cli run --import ~/Pictures/a.dng develop.set control=light.exposure value=0.7 \
+ develop.auto app.export path=/tmp/a.jpg shortEdge=1080 colorSpace=displayP3
+# a persistent library: edits are saved, later invocations see them
+lightcraft-cli run --library ~/lc-lib --import ~/Pictures/shoot library.info
+lightcraft-cli run --library ~/lc-lib library.select ids=[3] develop.get
+# the running app (same commands, plus ui.* methods)
+lightcraft-cli run --connect ui.set view=detail ui.screenshot path=/tmp/ui.png
+# JSON lines from a file or stdin: {"command": id, "params": {…}} or {"method": "ui.inspect"}
+lightcraft-cli run --demo --script steps.jsonl --keep-going
+```
+
## Other CLI subcommands
```sh
+lightcraft-cli render in.dng -o out.tif --opt colorSpace=displayP3 --opt bitDepth=16 --opt percent=50
lightcraft-cli render in.dng -o out.jpg --set light.exposure=0.5 --set light.contrast=20 --size 2048
lightcraft-cli render in.jpg -o out.png --settings look.json --preset <presetId>
lightcraft-cli commands [--json] # the command registry