mirror of
https://github.com/storytold/soundcraft.git
synced 2026-12-06 12:37:59 -06:00
Compare commits
15
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e8f3e0c0df | ||
|
|
eaf55efc9d | ||
|
|
5edc45fcf7 | ||
|
|
bebeea7bf9 | ||
|
|
2e128a011d | ||
|
|
0eff297515 | ||
|
|
9770cd10f3 | ||
|
|
3ffb142fc4 | ||
|
|
ea87d226da | ||
|
|
555488b9cf | ||
|
|
ce4390ef7b | ||
|
|
22c039f8ca | ||
|
|
bf838221ca | ||
|
|
94544a9a5f | ||
|
|
26bdcdf6fb |
@@ -90,7 +90,7 @@ For the crates you changed: `cargo fmt`, `cargo clippy -p <crate> --all-targets`
|
||||
### Paths and conventions
|
||||
- `unsafe` is allowed only in `crates/clap-host`, `crates/vst3-host` and `crates/au-host`.
|
||||
- Attribution file: [`ATTRIBUTION.md`](ATTRIBUTION.md) (path, author, source, license per asset); `cargo xtask assets` checks it. Icons are drawn in code (`crates/ui-egui/src/icons.rs`); demo audio is synthesised (`crates/engine/src/demo.rs`). The ArtCraft marks in `docs/brand/` are under `docs/brand/LICENSE-brand.txt`.
|
||||
- Run: `cargo run --release -p soundcraft -- --demo --control 0` (the control port is printed); drive it with JSON lines (`engine.execute`, `ui.screenshot`; methods in `crates/ui-egui/src/control.rs`). Offscreen render: `cargo run -p soundcraft-ui-egui --example ui_shot -- out.png [script.jsonl]`. Headless: `soundcraft-cli run --demo --cmd '...' --bounce out.wav`; MCP: `soundcraft-cli mcp [--connect PORT]`.
|
||||
- Run: `cargo run --release -p soundcraft -- --demo --control 0` (the control port and the launch's `SOUNDCRAFT_CONTROL_TOKEN` are printed; every request carries it as `"token"`); drive it with JSON lines (`engine.execute`, `ui.screenshot`; methods in `crates/ui-egui/src/control.rs`). Offscreen render: `cargo run -p soundcraft-ui-egui --example ui_shot -- out.png [script.jsonl]`. Headless: `soundcraft-cli run --demo --cmd '...' --bounce out.wav`; MCP: `soundcraft-cli mcp [--headless]` (the open window while the ArtCraft Launcher's AI agents switch names SoundCraft, otherwise headless; `crates/automation/src/agents.rs`, `crates/ui-egui/src/agents.rs`).
|
||||
- Interface language: `Setup > Appearance > Language` or the `ui.language` command (English by default); catalogs are checked for placeholder parity and unique keys.
|
||||
- Contributor credits: `docs/contributors.md`.
|
||||
- `plan/` is an optional gitignored notebook.
|
||||
|
||||
Generated
+100
-11
@@ -315,7 +315,7 @@ dependencies = [
|
||||
"objc2-foundation 0.3.2",
|
||||
"parking_lot",
|
||||
"percent-encoding",
|
||||
"windows-sys 0.52.0",
|
||||
"windows-sys 0.61.2",
|
||||
"wl-clipboard-rs",
|
||||
"x11rb",
|
||||
]
|
||||
@@ -1284,6 +1284,16 @@ dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-ai-agents"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-ai-integrations?rev=d94a3593adcff504eaaad9e5aee4c84fd2f07a72#d94a3593adcff504eaaad9e5aee4c84fd2f07a72"
|
||||
dependencies = [
|
||||
"dirs",
|
||||
"serde",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-appkit"
|
||||
version = "0.1.0"
|
||||
@@ -1315,6 +1325,31 @@ dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-automation"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21"
|
||||
dependencies = [
|
||||
"base64",
|
||||
"craft-behavior",
|
||||
"craft-control",
|
||||
"craft-host",
|
||||
"craft-keymap",
|
||||
"craft-platform",
|
||||
"craft-theme",
|
||||
"craft-ui",
|
||||
"egui",
|
||||
"getrandom 0.3.4",
|
||||
"hmac",
|
||||
"log",
|
||||
"png 0.17.16",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2",
|
||||
"thiserror 2.0.21",
|
||||
"web-time",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-behavior"
|
||||
version = "0.1.0"
|
||||
@@ -1351,6 +1386,21 @@ name = "craft-codepage"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21"
|
||||
|
||||
[[package]]
|
||||
name = "craft-control"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21"
|
||||
dependencies = [
|
||||
"craft-ai-agents",
|
||||
"craft-atomic",
|
||||
"craft-flags",
|
||||
"dirs",
|
||||
"getrandom 0.3.4",
|
||||
"log",
|
||||
"serde",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-docpath"
|
||||
version = "0.1.0"
|
||||
@@ -1359,6 +1409,16 @@ dependencies = [
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-flags"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21"
|
||||
dependencies = [
|
||||
"craft-atomic",
|
||||
"dirs",
|
||||
"toml_edit",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-font-catalog"
|
||||
version = "0.1.0"
|
||||
@@ -1997,6 +2057,7 @@ checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
|
||||
dependencies = [
|
||||
"block-buffer",
|
||||
"crypto-common",
|
||||
"subtle",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2017,7 +2078,7 @@ dependencies = [
|
||||
"libc",
|
||||
"option-ext",
|
||||
"redox_users",
|
||||
"windows-sys 0.59.0",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2055,7 +2116,7 @@ version = "0.5.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ab8ecd87370524b461f8557c119c405552c396ed91fc0a8eec68679eab26f94a"
|
||||
dependencies = [
|
||||
"libloading 0.8.9",
|
||||
"libloading 0.7.4",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2455,7 +2516,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"windows-sys 0.52.0",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -3020,6 +3081,15 @@ version = "0.4.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"
|
||||
|
||||
[[package]]
|
||||
name = "hmac"
|
||||
version = "0.12.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e"
|
||||
dependencies = [
|
||||
"digest",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "http"
|
||||
version = "1.5.0"
|
||||
@@ -3344,7 +3414,7 @@ dependencies = [
|
||||
"byteorder-lite",
|
||||
"moxcms",
|
||||
"num-traits",
|
||||
"png",
|
||||
"png 0.18.1",
|
||||
"tiff",
|
||||
]
|
||||
|
||||
@@ -3908,7 +3978,7 @@ dependencies = [
|
||||
"objc2-app-kit 0.3.2",
|
||||
"objc2-core-foundation",
|
||||
"objc2-foundation 0.3.2",
|
||||
"png",
|
||||
"png 0.18.1",
|
||||
"thiserror 2.0.21",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
@@ -4906,6 +4976,19 @@ dependencies = [
|
||||
"time",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "png"
|
||||
version = "0.17.16"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "82151a2fc869e011c153adc57cf2789ccb8d9906ce52c0b39a6b5697749d7526"
|
||||
dependencies = [
|
||||
"bitflags 1.3.2",
|
||||
"crc32fast",
|
||||
"fdeflate",
|
||||
"flate2",
|
||||
"miniz_oxide 0.8.9",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "png"
|
||||
version = "0.18.1"
|
||||
@@ -5538,7 +5621,7 @@ dependencies = [
|
||||
"errno",
|
||||
"libc",
|
||||
"linux-raw-sys 0.12.1",
|
||||
"windows-sys 0.52.0",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -5595,7 +5678,7 @@ dependencies = [
|
||||
"security-framework",
|
||||
"security-framework-sys",
|
||||
"webpki-root-certs",
|
||||
"windows-sys 0.52.0",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -5984,10 +6067,12 @@ dependencies = [
|
||||
"chrono",
|
||||
"clap",
|
||||
"craft-audio",
|
||||
"craft-control",
|
||||
"craft-nightly",
|
||||
"craft-update",
|
||||
"eframe",
|
||||
"egui",
|
||||
"getrandom 0.3.4",
|
||||
"log",
|
||||
"muda",
|
||||
"objc2 0.6.5",
|
||||
@@ -6019,6 +6104,8 @@ version = "0.21.0"
|
||||
dependencies = [
|
||||
"clap",
|
||||
"craft-audio",
|
||||
"craft-automation",
|
||||
"craft-control",
|
||||
"craft-mcp-server",
|
||||
"log",
|
||||
"serde_json",
|
||||
@@ -6173,7 +6260,9 @@ name = "soundcraft-ui-egui"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"craft-audio",
|
||||
"craft-automation",
|
||||
"craft-behavior",
|
||||
"craft-control",
|
||||
"craft-host",
|
||||
"craft-keymap",
|
||||
"craft-mime",
|
||||
@@ -6593,7 +6682,7 @@ dependencies = [
|
||||
"getrandom 0.4.3",
|
||||
"once_cell",
|
||||
"rustix 1.1.6",
|
||||
"windows-sys 0.52.0",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -6714,7 +6803,7 @@ dependencies = [
|
||||
"bytemuck",
|
||||
"cfg-if",
|
||||
"log",
|
||||
"png",
|
||||
"png 0.18.1",
|
||||
"tiny-skia-path 0.12.0",
|
||||
]
|
||||
|
||||
@@ -7640,7 +7729,7 @@ version = "0.1.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
|
||||
dependencies = [
|
||||
"windows-sys 0.52.0",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
||||
@@ -80,6 +80,10 @@ craft-scraft-format = { version = "0.1.0", git = "https://github.com/storytold/c
|
||||
craft-update = { version = "=0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", features = ["ui"] }
|
||||
craft-mcp-server = { version = "=0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "1f6c3a21f85ed96f8fd4ddd5a959d4e1edbedb24" }
|
||||
# Agents in the open window through the ArtCraft Launcher's switch: the link host and the Agents
|
||||
# page (`craft-automation`), and the CLI's live client and agent settings (`craft-control`).
|
||||
craft-automation = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
craft-control = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
|
||||
# ui
|
||||
craft-ui = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
|
||||
@@ -227,7 +227,8 @@ soundcraft-cli run --demo \
|
||||
--cmd 'mix.insert={"track":"Bass","plugin":"eq_7band"}' \
|
||||
--bounce mix.wav
|
||||
|
||||
# Drive the running app.
|
||||
# Drive the running app (the token keeps other local accounts off the loopback port).
|
||||
export SOUNDCRAFT_CONTROL_TOKEN=$(head -c 32 /dev/urandom | od -An -tx1 | tr -d ' \n')
|
||||
soundcraft --demo --control 7801 &
|
||||
soundcraft-cli app --port 7801 transport.play
|
||||
soundcraft-cli app --port 7801 ui.screenshot '{"path":"shot.png"}'
|
||||
@@ -334,7 +335,7 @@ DirectX 12 shaders are compiled with FXC, which is part of Windows, so no `dxcom
|
||||
| Build | File | Notes |
|
||||
|---|---|---|
|
||||
| App, universal (Apple silicon + Intel) | `soundcraft-<ver>-macos-universal.dmg` | Signed and notarized |
|
||||
| Command-line tool, universal | `soundcraft-cli-<ver>-macos-universal.zip` | Signed and notarized |
|
||||
| Command-line tool, universal | `soundcraft-cli-<ver>-macos-universal.zip` | Signed and notarized; the app also carries it as `SoundCraft.app/Contents/MacOS/soundcraft-cli` |
|
||||
|
||||
### Linux
|
||||
|
||||
|
||||
@@ -14,6 +14,7 @@ use clap::{ArgAction, Args, CommandFactory, FromArgMatches, Parser, Subcommand,
|
||||
use craft_audio::{DECODE_EXTENSIONS, ENCODE_EXTENSIONS};
|
||||
use serde_json::{Value, json};
|
||||
use soundcraft_automation::ControlTarget;
|
||||
use soundcraft_automation::agents::WhenAppClosed;
|
||||
use soundcraft_automation::args::{AutomationArgs, ControlClientArgs, blank_env_is_unset, control_target, long_version, name_env_vars};
|
||||
|
||||
/// Help text that names the extensions in `list`, built once from craft-audio's
|
||||
@@ -207,23 +208,47 @@ pub(crate) struct AppArgs {
|
||||
|
||||
/// Serve MCP on stdin and stdout
|
||||
///
|
||||
/// Plain `mcp` works in the open SoundCraft window while the ArtCraft Launcher's Settings › AI
|
||||
/// agents switch lets agents in, and otherwise in an in-process engine (headless). While SoundCraft
|
||||
/// is closed, a call follows the choice on Preferences › AI Agents (start SoundCraft, work headless
|
||||
/// in the agent folders, or say SoundCraft isn't running) unless --when-closed overrides it. In the
|
||||
/// window, files stay inside the agent folders set on that page.
|
||||
///
|
||||
/// The automation roots confine every file the agent's commands read (open, import, presets) and
|
||||
/// write (save, bounce, export) to those folders, links followed. Each root flag may be given more
|
||||
/// than once, a path inside any of its folders being allowed, and a kind left out grants none of
|
||||
/// its access. The roots confine the in-process server, so they, like --demo, conflict with --connect.
|
||||
/// write (save, bounce, export) in the in-process engine to those folders, links followed, and
|
||||
/// imply --headless. Each root flag may be given more than once, a path inside any of its folders
|
||||
/// being allowed, and a kind left out grants none of its access. The roots, like --demo, --headless and --when-closed,
|
||||
/// conflict with --connect.
|
||||
#[derive(Args)]
|
||||
pub(crate) struct McpArgs {
|
||||
/// Serve a running app's control channel at this port or host:port instead of an in-process
|
||||
/// engine; conflicts with --demo, which starts only that engine
|
||||
#[arg(long, value_name = "PORT", value_parser = control_target, conflicts_with_all = ["demo", "automation_read_root", "automation_write_root"])]
|
||||
pub(crate) connect: Option<ControlTarget>,
|
||||
/// Start the in-process engine from the demo session
|
||||
/// Always serve an in-process engine, never the open window
|
||||
#[arg(long)]
|
||||
pub(crate) headless: bool,
|
||||
/// What a call does while SoundCraft is closed: launch (start it), headless or error; overrides
|
||||
/// the choice on Preferences › AI Agents
|
||||
#[arg(long, value_name = "WHAT", value_parser = when_closed, conflicts_with = "headless")]
|
||||
pub(crate) when_closed: Option<WhenAppClosed>,
|
||||
/// Deprecated, removed in a later release: serve a running app's --control channel at this port
|
||||
/// or host:port. Plain `mcp` finds the open window itself
|
||||
#[arg(long, value_name = "PORT", value_parser = control_target, conflicts_with_all = ["demo", "headless", "when_closed", "automation_read_root", "automation_write_root"])]
|
||||
pub(crate) connect: Option<ControlTarget>,
|
||||
/// Start the in-process engine from the demo session (implies --headless)
|
||||
#[arg(long, conflicts_with = "when_closed")]
|
||||
pub(crate) demo: bool,
|
||||
#[command(flatten)]
|
||||
pub(crate) automation: AutomationArgs,
|
||||
}
|
||||
|
||||
/// `launch`, `headless` or `error`, for `mcp --when-closed`.
|
||||
fn when_closed(s: &str) -> Result<WhenAppClosed, NotAWhenClosed> {
|
||||
WhenAppClosed::parse(s.trim()).ok_or(NotAWhenClosed)
|
||||
}
|
||||
|
||||
/// A `mcp --when-closed` value that is none of the three.
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
#[error("expected launch, headless or error")]
|
||||
pub(crate) struct NotAWhenClosed;
|
||||
|
||||
/// Print the parity report (markdown)
|
||||
#[derive(Args)]
|
||||
pub(crate) struct ParityArgs {
|
||||
|
||||
@@ -1,34 +1,58 @@
|
||||
use super::args::McpArgs;
|
||||
use super::error::CliError;
|
||||
use soundcraft_automation::agents::{self, LiveConfig};
|
||||
use soundcraft_automation::{ControlTarget, Headless, Remote, mcp::Server};
|
||||
use soundcraft_engine::Engine;
|
||||
use soundcraft_engine::file_access::{self, AutomationRoots};
|
||||
use std::io::Write;
|
||||
use std::path::PathBuf;
|
||||
|
||||
/// What `mcp` serves.
|
||||
struct Setup {
|
||||
connect: Option<ControlTarget>,
|
||||
demo: bool,
|
||||
roots: Option<std::sync::Arc<AutomationRoots>>,
|
||||
/// The app's settings folder plain `mcp` finds the open window through; `None` with
|
||||
/// --headless (or --demo or automation roots, which imply it), without the suite's `AI-MCP`
|
||||
/// flag, or when there is no settings folder.
|
||||
live: Option<PathBuf>,
|
||||
}
|
||||
|
||||
/// Open the roots before the server starts: a folder that can't be opened must not leave the
|
||||
/// server running unconfined.
|
||||
fn setup(args: &McpArgs) -> Result<Setup, CliError> {
|
||||
let read: Vec<&std::path::Path> = args.automation.automation_read_root.iter().map(std::path::PathBuf::as_path).collect();
|
||||
let write: Vec<&std::path::Path> = args.automation.automation_write_root.iter().map(std::path::PathBuf::as_path).collect();
|
||||
let read: Vec<&std::path::Path> = args.automation.automation_read_root.iter().map(PathBuf::as_path).collect();
|
||||
let write: Vec<&std::path::Path> = args.automation.automation_write_root.iter().map(PathBuf::as_path).collect();
|
||||
let roots = AutomationRoots::new(&read, &write)?;
|
||||
Ok(Setup { connect: args.connect.clone(), demo: args.demo, roots })
|
||||
// Without the suite's `AI-MCP` flag there is no launcher switch to follow: headless, as `mcp`
|
||||
// always was. Explicit automation roots keep every call inside them, so they imply headless
|
||||
// too: the open window keeps agents to its own agent folders, not to the command's roots.
|
||||
let headless = args.headless || args.demo || args.connect.is_some() || roots.is_some() || !agents::mcp_flag();
|
||||
let live = if headless { None } else { soundcraft_automation::profile::config_dir() };
|
||||
Ok(Setup { connect: args.connect.clone(), demo: args.demo, roots, live })
|
||||
}
|
||||
|
||||
/// The note `--connect` prints: it still works for one release.
|
||||
pub(crate) const CONNECT_DEPRECATED: &str = "soundcraft-cli: --connect is deprecated and will be removed in a later release: \
|
||||
plain `soundcraft-cli mcp` works in the open SoundCraft window while the ArtCraft Launcher's Settings › AI agents switch lets agents in";
|
||||
|
||||
/// Serves on the process's real stdin and stdout; only the notes go to `err`.
|
||||
pub(crate) fn mcp(args: &McpArgs, err: &mut dyn Write) -> Result<(), CliError> {
|
||||
let Setup { connect, demo, roots } = setup(args)?;
|
||||
let Setup { connect, demo, roots, live } = setup(args)?;
|
||||
let stdin = std::io::stdin();
|
||||
let stdout = std::io::stdout();
|
||||
let served = if let Some(target) = connect {
|
||||
outln!(err, "{CONNECT_DEPRECATED}");
|
||||
let mut s = Server::new(Remote::new(&target));
|
||||
s.serve(stdin.lock(), stdout.lock())
|
||||
} else if let Some(config_dir) = live {
|
||||
// Every call looks for the open window first; a headless session on the way is confined
|
||||
// per call (to the agent folders while agents are let in), never the whole process.
|
||||
let mut cfg = LiveConfig::new(config_dir, Box::new(|| Ok(Headless::new(Engine::default()))));
|
||||
cfg.when_closed = args.when_closed;
|
||||
cfg.launch = agents::launcher();
|
||||
let mut s = Server::new(agents::live(cfg));
|
||||
s.serve(stdin.lock(), stdout.lock())
|
||||
} else {
|
||||
// `--demo` is the operator's own choice, made before the roots come into force.
|
||||
let e = if demo { soundcraft_engine::demo::demo_engine() } else { Engine::default() };
|
||||
|
||||
@@ -20,7 +20,9 @@ fn invoke(dir: &Path, args: &[&str]) -> Invoke {
|
||||
|
||||
fn invoke_env(dir: &Path, args: &[&str], control_port: Option<&str>) -> Invoke {
|
||||
let mut cmd = Command::new(crate::common::soundcraft_cli_binary());
|
||||
cmd.env("SOUNDCRAFT_NO_PREFS", "1").env_remove("SOUNDCRAFT_CONTROL_PORT");
|
||||
// No settings folder: plain `mcp` serves the in-process engine whatever this machine's
|
||||
// ArtCraft Launcher switch says.
|
||||
cmd.env("SOUNDCRAFT_NO_PREFS", "1").env("SOUNDCRAFT_CONFIG_DIR", "").env_remove("SOUNDCRAFT_CONTROL_PORT");
|
||||
if let Some(port) = control_port {
|
||||
cmd.env("SOUNDCRAFT_CONTROL_PORT", port);
|
||||
}
|
||||
@@ -502,9 +504,15 @@ fn app_help_names_the_port_variable() {
|
||||
#[test]
|
||||
fn mcp_accepts_its_flags_in_both_spellings_and_exits_cleanly_on_empty_stdin() {
|
||||
let dir = sandbox("mcp-ok");
|
||||
for args in [vec!["mcp"], vec!["mcp", "--demo"], vec!["mcp", "--connect", "1"], vec!["mcp", "--connect=1"]] {
|
||||
for args in [vec!["mcp"], vec!["mcp", "--demo"], vec!["mcp", "--headless"], vec!["mcp", "--when-closed", "error"]] {
|
||||
assert_silent_success(&invoke(&dir, &args));
|
||||
}
|
||||
// `--connect` still works for one release and says so on stderr.
|
||||
for args in [vec!["mcp", "--connect", "1"], vec!["mcp", "--connect=1"]] {
|
||||
let got = invoke(&dir, &args);
|
||||
assert_eq!((got.code, got.stdout.as_str()), (0, ""));
|
||||
assert!(got.stderr.contains("--connect is deprecated"), "{}", got.stderr);
|
||||
}
|
||||
// A root prints the confinement line to stderr (never stdout).
|
||||
for args in [&["mcp", "--automation-read-root", "."][..], &["mcp", "--automation-read-root=."][..]] {
|
||||
let got = invoke(&dir, args);
|
||||
|
||||
@@ -9,7 +9,9 @@ use serde_json::Value;
|
||||
|
||||
fn bin() -> Command {
|
||||
let mut cmd = Command::new(crate::common::soundcraft_cli_binary());
|
||||
cmd.env("SOUNDCRAFT_NO_PREFS", "1");
|
||||
// No settings folder: plain `mcp` serves the in-process engine whatever this machine's
|
||||
// ArtCraft Launcher switch says.
|
||||
cmd.env("SOUNDCRAFT_NO_PREFS", "1").env("SOUNDCRAFT_CONFIG_DIR", "");
|
||||
cmd
|
||||
}
|
||||
|
||||
@@ -46,10 +48,16 @@ fn mcp_session(args: &[&str], calls: &[(&str, Value)]) -> (bool, String, Vec<Val
|
||||
|
||||
/// [`mcp_session`] with the server started in the working directory `cwd`.
|
||||
fn mcp_session_in(cwd: Option<&Path>, args: &[&str], calls: &[(&str, Value)]) -> (bool, String, Vec<Value>) {
|
||||
mcp_session_with(cwd, &[], args, calls)
|
||||
}
|
||||
|
||||
/// [`mcp_session_in`] with the variables `env` set.
|
||||
fn mcp_session_with(cwd: Option<&Path>, env: &[(&str, &str)], args: &[&str], calls: &[(&str, Value)]) -> (bool, String, Vec<Value>) {
|
||||
let mut cmd = bin();
|
||||
if let Some(cwd) = cwd {
|
||||
cmd.current_dir(cwd);
|
||||
}
|
||||
cmd.envs(env.iter().copied());
|
||||
let mut child = cmd.arg("mcp").args(args).stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped()).spawn().unwrap();
|
||||
{
|
||||
let stdin = child.stdin.as_mut().unwrap();
|
||||
@@ -222,6 +230,76 @@ fn mcp_automation_root_flags_are_checked_up_front() {
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// Plain `mcp` follows the ArtCraft Launcher's switch: off, a session without a window and with
|
||||
/// no folders of its own; on (the suite's `AI-MCP` flag and the launcher's list naming
|
||||
/// `soundcraft`) with SoundCraft closed and set to work headless, a session kept to the agent
|
||||
/// folders of the app's settings.
|
||||
#[test]
|
||||
fn plain_mcp_follows_the_launchers_switch() {
|
||||
let base = tmpdir("switch");
|
||||
let (settings, launcher, agents, elsewhere) = (base.join("settings"), base.join("mcp"), base.join("agents"), base.join("elsewhere"));
|
||||
for dir in [&settings, &launcher, &agents, &elsewhere] {
|
||||
std::fs::create_dir_all(dir).unwrap();
|
||||
}
|
||||
let agents_s = agents.to_str().unwrap();
|
||||
std::fs::write(
|
||||
settings.join("agents.json"),
|
||||
serde_json::json!({"whenAppClosed": "headless", "readRoot": agents_s, "writeRoot": agents_s}).to_string(),
|
||||
)
|
||||
.unwrap();
|
||||
let cli_path = crate::common::soundcraft_cli_binary().to_string_lossy().into_owned();
|
||||
let apps = serde_json::json!({"version": 1, "apps": [{"id": "soundcraft", "name": "SoundCraft", "command": cli_path, "args": ["mcp"]}]});
|
||||
std::fs::write(launcher.join("apps.json"), apps.to_string()).unwrap();
|
||||
let (settings_s, launcher_s) = (settings.to_str().unwrap(), launcher.to_str().unwrap());
|
||||
let env = |flags: &'static str| [("SOUNDCRAFT_CONFIG_DIR", settings_s), ("CRAFT_FLAGS", flags), ("CRAFT_MCP_DIR", launcher_s)];
|
||||
let calls = [
|
||||
("agent_folders", serde_json::json!({})),
|
||||
("save_session", serde_json::json!({"path": elsewhere.join("a.scraft").to_str().unwrap()})),
|
||||
("save_session", serde_json::json!({"path": agents.join("a.scraft").to_str().unwrap()})),
|
||||
];
|
||||
|
||||
let (success, stderr, replies) = mcp_session_with(None, &env("-AI-MCP"), &[], &calls[..1]);
|
||||
assert!(success, "{stderr}");
|
||||
assert!(text(&replies[0]).contains("unrestricted"), "switch off: {}", text(&replies[0]));
|
||||
|
||||
let (success, stderr, replies) = mcp_session_with(None, &env("AI-MCP"), &[], &calls);
|
||||
assert!(success, "{stderr}");
|
||||
let folders: Value = serde_json::from_str(text(&replies[0])).unwrap();
|
||||
assert!(folders["write_folder"].as_str().is_some_and(|f| f.ends_with("agents")), "switch on: {folders}");
|
||||
assert_eq!(replies[1]["result"]["isError"], true, "saved outside the agent folder: {}", replies[1]);
|
||||
assert_eq!(replies[2]["result"]["isError"], false, "{}", replies[2]);
|
||||
assert!(std::fs::read_dir(&agents).unwrap().next().is_some() && std::fs::read_dir(&elsewhere).unwrap().next().is_none());
|
||||
|
||||
// Explicit roots keep every call inside them: the server is headless and never asks for the
|
||||
// window (closed and set to `error`, a window lookup would say SoundCraft isn't running).
|
||||
std::fs::write(settings.join("agents.json"), serde_json::json!({"whenAppClosed": "error"}).to_string()).unwrap();
|
||||
let elsewhere_s = elsewhere.to_str().unwrap();
|
||||
let rooted = ["--automation-read-root", elsewhere_s, "--automation-write-root", elsewhere_s];
|
||||
let (success, stderr, replies) = mcp_session_with(None, &env("AI-MCP"), &rooted, &calls[..1]);
|
||||
assert!(success, "{stderr}");
|
||||
let folders: Value = serde_json::from_str(text(&replies[0])).unwrap();
|
||||
assert!(folders["write_folder"].as_str().is_some_and(|f| f.ends_with("elsewhere")), "rooted: {folders}");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// `mcp --connect` still works for one release and says it is deprecated; `--headless` and
|
||||
/// `--when-closed` don't mix, and neither goes with `--connect`.
|
||||
#[test]
|
||||
fn mcp_options_for_the_window() {
|
||||
let (success, stderr, replies) = mcp_session(&["--connect", "127.0.0.1:1"], &[("inspect_session", serde_json::json!({}))]);
|
||||
assert!(success && stderr.contains("deprecated"), "{stderr}");
|
||||
assert!(text(&replies[0]).contains("cannot reach SoundCraft"), "{}", text(&replies[0]));
|
||||
for (args, needle) in [
|
||||
(&["mcp", "--headless", "--when-closed", "launch"][..], "--headless"),
|
||||
(&["mcp", "--when-closed", "sometimes"][..], "launch, headless or error"),
|
||||
(&["mcp", "--connect", "7979", "--headless"][..], "--connect"),
|
||||
] {
|
||||
let o = run(args);
|
||||
let err = String::from_utf8_lossy(&o.stderr);
|
||||
assert!(!o.status.success() && err.contains(needle), "{args:?}: {err}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn usage_lists_the_root_flags() {
|
||||
let o = run(&["mcp", "--help"]);
|
||||
|
||||
@@ -177,7 +177,15 @@ fn every_subcommand_has_help_listing_its_arguments() {
|
||||
(
|
||||
"mcp",
|
||||
"mcp [OPTIONS]",
|
||||
&["--connect <PORT>", "--demo", "--automation-read-root <DIR>", "--automation-write-root <DIR>", "conflict with --connect"],
|
||||
&[
|
||||
"--connect <PORT>",
|
||||
"--demo",
|
||||
"--headless",
|
||||
"--when-closed <WHAT>",
|
||||
"--automation-read-root <DIR>",
|
||||
"--automation-write-root <DIR>",
|
||||
"conflict with --connect",
|
||||
],
|
||||
),
|
||||
("parity", "parity [OPTIONS]", &["--write <PATH>"]),
|
||||
("plugins", "plugins", &[]),
|
||||
|
||||
@@ -27,6 +27,8 @@ egui = { workspace = true, features = ["default_fonts", "monochrome_emoji_fonts"
|
||||
serde_json.workspace = true
|
||||
log.workspace = true
|
||||
chrono.workspace = true
|
||||
# The per-launch control token (already in the graph through egui's ahash).
|
||||
getrandom = "0.3"
|
||||
|
||||
[target.'cfg(all(unix, not(any(target_os = "macos", target_os = "linux"))))'.dependencies]
|
||||
winit = { version = "0.30", default-features = false, features = ["x11"] }
|
||||
@@ -37,6 +39,8 @@ winit = { version = "0.30", default-features = false, features = ["x11", "waylan
|
||||
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
|
||||
rfd.workspace = true
|
||||
# The launcher's switch and the stale connection file at start.
|
||||
craft-control = { workspace = true, features = ["agents"] }
|
||||
|
||||
[build-dependencies]
|
||||
# Icon + VERSIONINFO for soundcraft.exe; build.rs only uses it when the target is Windows.
|
||||
|
||||
@@ -5,36 +5,18 @@ use std::path::{Path, PathBuf};
|
||||
|
||||
use soundcraft_ui_egui::docking;
|
||||
|
||||
/// Portable mode (#268): this file beside the executable keeps settings, autosaves, presets and
|
||||
/// logs in [`PORTABLE_DATA_DIR`] next to it instead of the user profile.
|
||||
pub(crate) const PORTABLE_MARKER: &str = "portable.txt";
|
||||
pub(crate) const PORTABLE_DATA_DIR: &str = "SoundCraftData";
|
||||
pub(crate) use soundcraft_automation::profile::PORTABLE_MARKER;
|
||||
use soundcraft_automation::profile::Platform;
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum Platform {
|
||||
Mac,
|
||||
Windows,
|
||||
Other,
|
||||
}
|
||||
|
||||
/// SoundCraft's settings folder, resolved from the variable lookup `get` (see `Env::from_lookup`).
|
||||
/// A nonempty `$SOUNDCRAFT_CONFIG_DIR` overrides the platform default and is the complete
|
||||
/// directory; no application-name suffix is appended. An explicitly empty value means no settings
|
||||
/// folder instead of a fallback to a personal profile (the documented exception to RFC-0012 rule
|
||||
/// 1.7). Otherwise `portable.txt` beside the executable selects `<exe dir>/SoundCraftData`, when
|
||||
/// that folder can be written (a read-only medium falls back to the platform default).
|
||||
/// SoundCraft's settings folder, resolved from the variable lookup `get` (see `Env::from_lookup`):
|
||||
/// a validated Nightly profile, otherwise the Stable folder `soundcraft-cli mcp` also finds
|
||||
/// (`soundcraft_automation::profile::config_dir_with`: `$SOUNDCRAFT_CONFIG_DIR`, `portable.txt`
|
||||
/// beside the executable, the platform default).
|
||||
pub fn resolve_config_dir(get: impl Fn(&str) -> Option<OsString>) -> Option<PathBuf> {
|
||||
let platform = if cfg!(target_os = "macos") {
|
||||
Platform::Mac
|
||||
} else if cfg!(windows) {
|
||||
Platform::Windows
|
||||
} else {
|
||||
Platform::Other
|
||||
};
|
||||
let exe = std::env::current_exe().ok();
|
||||
// The one place a validated Nightly profile replaces every data root: ui.json, Autosave/,
|
||||
// Presets/ and logs/ all hang off this folder, before any of them is first used.
|
||||
config_dir_with(platform, get, exe.as_deref().and_then(Path::parent), crate::launch_profile::current().root())
|
||||
config_dir_with(Platform::current(), get, exe.as_deref().and_then(Path::parent), crate::launch_profile::current().root())
|
||||
}
|
||||
|
||||
fn config_dir_with(platform: Platform, env: impl Fn(&str) -> Option<OsString>, exe_dir: Option<&Path>, nightly: Option<&Path>) -> Option<PathBuf> {
|
||||
@@ -43,45 +25,7 @@ fn config_dir_with(platform: Platform, env: impl Fn(&str) -> Option<OsString>, e
|
||||
if let Some(root) = nightly {
|
||||
return Some(root.to_path_buf());
|
||||
}
|
||||
if let Some(dir) = env(crate::env::CONFIG_DIR) {
|
||||
return (!dir.is_empty()).then(|| PathBuf::from(dir));
|
||||
}
|
||||
if let Some(exe_dir) = exe_dir.filter(|d| d.join(PORTABLE_MARKER).is_file()) {
|
||||
let data = exe_dir.join(PORTABLE_DATA_DIR);
|
||||
match writable(&data) {
|
||||
Ok(()) => return Some(data),
|
||||
Err(e) => log::warn!("portable mode: {} can't be written ({e}); using the user profile instead", data.display()),
|
||||
}
|
||||
}
|
||||
match platform {
|
||||
Platform::Mac => env("HOME").map(|h| PathBuf::from(h).join("Library/Application Support/SoundCraft")),
|
||||
Platform::Windows => env("APPDATA").map(|a| PathBuf::from(a).join("SoundCraft")),
|
||||
Platform::Other => {
|
||||
env("XDG_CONFIG_HOME").map(PathBuf::from).or_else(|| env("HOME").map(|h| PathBuf::from(h).join(".config"))).map(|c| c.join("soundcraft"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Create `dir` if needed and prove a file can be written in it. The Nightly profile validator
|
||||
/// injects this same exclusive probe.
|
||||
///
|
||||
/// The probe never replaces an existing entry: `create_new` cannot truncate one, and a name that is
|
||||
/// already taken (an interrupted run, or a file someone else made) is left untouched while the next
|
||||
/// name is tried. Only a file this call created is removed again.
|
||||
pub(crate) fn writable(dir: &Path) -> std::io::Result<()> {
|
||||
std::fs::create_dir_all(dir)?;
|
||||
for attempt in 0..8u32 {
|
||||
let probe = dir.join(format!(".write-test-{}-{attempt}", std::process::id()));
|
||||
match std::fs::OpenOptions::new().write(true).create_new(true).open(&probe) {
|
||||
Ok(file) => {
|
||||
drop(file);
|
||||
return std::fs::remove_file(probe);
|
||||
}
|
||||
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue,
|
||||
Err(error) => return Err(error),
|
||||
}
|
||||
}
|
||||
Err(std::io::Error::new(std::io::ErrorKind::AlreadyExists, "no free write-probe name"))
|
||||
soundcraft_automation::profile::config_dir_with(platform, env, exe_dir)
|
||||
}
|
||||
|
||||
/// Read bounded settings, recovering unreadable docking metadata independently of other settings.
|
||||
|
||||
@@ -5,8 +5,13 @@
|
||||
//!
|
||||
//! Lines are bounded ([`MAX_LINE`]): a longer one is refused and the connection closed, without
|
||||
//! buffering the rest. So is the number of connections served at once ([`MAX_CONNECTIONS`]).
|
||||
//!
|
||||
//! Every request carries the launch's secret as `"token"` (`SOUNDCRAFT_CONTROL_TOKEN`, or one made
|
||||
//! here and printed after the port): the port is loopback, which any local account can reach, and
|
||||
//! a request acts with this process's authority.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use soundcraft_automation::CONTROL_TOKEN_VAR;
|
||||
use soundcraft_ui_egui::ControlRequest;
|
||||
use std::io::{BufRead, BufReader, Read, Write};
|
||||
use std::net::{TcpListener, TcpStream};
|
||||
@@ -30,9 +35,25 @@ const MAX_CONNECTIONS: usize = 16;
|
||||
const MAX_QUEUED_REQUESTS: usize = MAX_CONNECTIONS;
|
||||
|
||||
/// Bind the loopback control listener and return the request receiver. Port 0 picks a free one and the actual port is
|
||||
/// printed; bind or spawn failures are logged instead of panicking.
|
||||
pub fn start(port: u16, ctx: egui::Context) -> Receiver<ControlRequest> {
|
||||
/// printed; bind or spawn failures are logged instead of panicking. Requests must carry `token`; with `None` one is
|
||||
/// made for this launch and printed after the port, so only the launching process learns it.
|
||||
pub fn start(port: u16, token: Option<String>, ctx: egui::Context) -> Receiver<ControlRequest> {
|
||||
let (tx, rx) = sync_channel::<ControlRequest>(MAX_QUEUED_REQUESTS);
|
||||
let (token, made) = match token {
|
||||
Some(t) if t.len() >= MIN_TOKEN_LEN => (t, false),
|
||||
weak => {
|
||||
if weak.is_some() {
|
||||
log::warn!("{CONTROL_TOKEN_VAR} is shorter than {MIN_TOKEN_LEN} characters; using a random token for this launch instead");
|
||||
}
|
||||
match new_token() {
|
||||
Ok(t) => (t, true),
|
||||
Err(e) => {
|
||||
log::error!("control server not started: no usable {CONTROL_TOKEN_VAR} and no random token: {e}");
|
||||
return rx;
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
let listener = match TcpListener::bind(("127.0.0.1", port)) {
|
||||
Ok(l) => l,
|
||||
Err(e) => {
|
||||
@@ -43,13 +64,33 @@ pub fn start(port: u16, ctx: egui::Context) -> Receiver<ControlRequest> {
|
||||
let actual = listener.local_addr().map(|a| a.port()).unwrap_or(port);
|
||||
log::info!("control server listening on 127.0.0.1:{actual}");
|
||||
println!("SOUNDCRAFT_CONTROL_PORT={actual}");
|
||||
let spawned = std::thread::Builder::new().name("soundcraft-control".into()).spawn(move || accept_loop(listener, tx, ctx));
|
||||
if made {
|
||||
println!("{CONTROL_TOKEN_VAR}={token}");
|
||||
}
|
||||
let spawned = std::thread::Builder::new().name("soundcraft-control".into()).spawn(move || accept_loop(listener, tx, ctx, Arc::from(token)));
|
||||
if let Err(e) = spawned {
|
||||
log::error!("control thread failed: {e}");
|
||||
}
|
||||
rx
|
||||
}
|
||||
|
||||
/// Shortest configured token accepted: a shorter one could be guessed by retrying connections, so
|
||||
/// a random one (printed) is used instead.
|
||||
const MIN_TOKEN_LEN: usize = 32;
|
||||
|
||||
/// 32 random bytes as hex, from the OS.
|
||||
fn new_token() -> Result<String, getrandom::Error> {
|
||||
let mut bytes = [0u8; 32];
|
||||
getrandom::fill(&mut bytes)?;
|
||||
Ok(bytes.iter().map(|b| format!("{b:02x}")).collect())
|
||||
}
|
||||
|
||||
/// `token` equals `expected`, compared in time that doesn't depend on where they differ.
|
||||
fn token_matches(token: Option<&str>, expected: &str) -> bool {
|
||||
let Some(token) = token else { return false };
|
||||
token.len() == expected.len() && token.bytes().zip(expected.bytes()).fold(0u8, |acc, (a, b)| acc | (a ^ b)) == 0
|
||||
}
|
||||
|
||||
/// A connection's place among [`MAX_CONNECTIONS`], given back when the connection ends (also when
|
||||
/// its thread can't be started, or panics).
|
||||
struct Slot(Arc<AtomicUsize>);
|
||||
@@ -62,7 +103,7 @@ impl Drop for Slot {
|
||||
|
||||
/// Accept until the listener closes, admitting at most [`MAX_CONNECTIONS`] peers; excess peers get one error line.
|
||||
/// Each admitted connection is served on its own thread, releasing its slot on exit.
|
||||
fn accept_loop(listener: TcpListener, tx: SyncSender<ControlRequest>, ctx: egui::Context) {
|
||||
fn accept_loop(listener: TcpListener, tx: SyncSender<ControlRequest>, ctx: egui::Context, token: Arc<str>) {
|
||||
let open = Arc::new(AtomicUsize::new(0));
|
||||
for mut stream in listener.incoming().flatten() {
|
||||
if open.fetch_add(1, Ordering::SeqCst) >= MAX_CONNECTIONS {
|
||||
@@ -73,9 +114,10 @@ fn accept_loop(listener: TcpListener, tx: SyncSender<ControlRequest>, ctx: egui:
|
||||
let slot = Slot(Arc::clone(&open));
|
||||
let tx = tx.clone();
|
||||
let ctx = ctx.clone();
|
||||
let token = Arc::clone(&token);
|
||||
let _ = std::thread::Builder::new().name("soundcraft-control-conn".into()).spawn(move || {
|
||||
let _slot = slot;
|
||||
serve(stream, tx, ctx);
|
||||
serve(stream, tx, ctx, &token);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -104,10 +146,11 @@ fn read_bounded_line(reader: &mut impl BufRead, buf: &mut Vec<u8>, max: usize) -
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// Answer newline-delimited JSON requests for one connection: bound each line, forward it to the UI thread with a 90
|
||||
/// Answer newline-delimited JSON requests for one connection: bound each line, forward it to the UI thread with a 90
|
||||
/// s reply deadline, and stop at EOF, invalid UTF-8, a closed request queue or a line that isn't a request (see
|
||||
/// [`parse_request`]). That line gets one error reply first.
|
||||
fn serve(stream: TcpStream, tx: SyncSender<ControlRequest>, ctx: egui::Context) {
|
||||
/// [`parse_request`]). A request that is not a request, a wrong `token`, or bad JSON gets one error reply first.
|
||||
fn serve(stream: TcpStream, tx: SyncSender<ControlRequest>, ctx: egui::Context, token: &str) {
|
||||
let Ok(read) = stream.try_clone() else { return };
|
||||
let mut out = stream;
|
||||
let mut reader = BufReader::new(read);
|
||||
@@ -126,7 +169,7 @@ fn serve(stream: TcpStream, tx: SyncSender<ControlRequest>, ctx: egui::Context)
|
||||
if line.trim().is_empty() {
|
||||
continue;
|
||||
}
|
||||
let reply = match parse_request(line) {
|
||||
let reply = match parse_request(line, token) {
|
||||
Ok((id, method, params)) => {
|
||||
let (req, rrx) = ControlRequest::new(method, params);
|
||||
match tx.try_send(req) {
|
||||
@@ -145,8 +188,12 @@ fn serve(stream: TcpStream, tx: SyncSender<ControlRequest>, ctx: egui::Context)
|
||||
}
|
||||
// Control clients send one request object per line. A peer that sends anything else isn't
|
||||
// one: answer once and close, so nothing it sends after that line runs.
|
||||
Err(e) => {
|
||||
let _ = writeln!(out, "{}", json!({"ok": false, "error": format!("{e}; closing the connection")}));
|
||||
Err((id, e)) => {
|
||||
let mut r = json!({"ok": false, "error": format!("{e}; closing the connection")});
|
||||
if !id.is_null() {
|
||||
r["id"] = id;
|
||||
}
|
||||
let _ = writeln!(out, "{r}");
|
||||
break;
|
||||
}
|
||||
};
|
||||
@@ -157,11 +204,15 @@ fn serve(stream: TcpStream, tx: SyncSender<ControlRequest>, ctx: egui::Context)
|
||||
}
|
||||
|
||||
/// A request line's `(id, method, params)`. The line must be a JSON object with a string `method`;
|
||||
/// otherwise the error says what it is instead.
|
||||
fn parse_request(line: &str) -> Result<(Value, String, Value), String> {
|
||||
let msg = serde_json::from_str::<Value>(line).map_err(|e| format!("bad JSON: {e}"))?;
|
||||
let Some(msg) = msg.as_object() else { return Err("not a request: expected a JSON object".into()) };
|
||||
let Some(method) = msg.get("method").and_then(Value::as_str) else { return Err("not a request: no string `method`".into()) };
|
||||
/// otherwise the error says what it is instead, with the request's `id` when it has one.
|
||||
fn parse_request(line: &str, token: &str) -> Result<(Value, String, Value), (Value, String)> {
|
||||
let msg = serde_json::from_str::<Value>(line).map_err(|e| (Value::Null, format!("bad JSON: {e}")))?;
|
||||
let Some(msg) = msg.as_object() else { return Err((Value::Null, "not a request: expected a JSON object".into())) };
|
||||
let id = msg.get("id").cloned().unwrap_or(Value::Null);
|
||||
if !token_matches(msg.get("token").and_then(Value::as_str), token) {
|
||||
return Err((id, format!("unauthorized: the request's `token` is not this app's {CONTROL_TOKEN_VAR}")));
|
||||
}
|
||||
let Some(method) = msg.get("method").and_then(Value::as_str) else { return Err((id, "not a request: no string `method`".into())) };
|
||||
Ok((msg.get("id").cloned().unwrap_or(Value::Null), method.to_string(), msg.get("params").cloned().unwrap_or(json!({}))))
|
||||
}
|
||||
|
||||
@@ -199,12 +250,14 @@ mod tests {
|
||||
assert!(state + request.to_string().len() <= MAX_LINE);
|
||||
}
|
||||
|
||||
const TOKEN: &str = "s3cret";
|
||||
|
||||
/// The control server on a loopback port, with a stand-in UI that echoes each method.
|
||||
fn serve_echo() -> std::net::SocketAddr {
|
||||
let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap();
|
||||
let addr = listener.local_addr().unwrap();
|
||||
let (tx, rx) = sync_channel::<ControlRequest>(MAX_QUEUED_REQUESTS);
|
||||
std::thread::spawn(move || accept_loop(listener, tx, egui::Context::default()));
|
||||
std::thread::spawn(move || accept_loop(listener, tx, egui::Context::default(), Arc::from(TOKEN)));
|
||||
std::thread::spawn(move || {
|
||||
for req in rx {
|
||||
let _ = req.reply.send(json!({"ok": true, "method": req.method}));
|
||||
@@ -218,7 +271,7 @@ mod tests {
|
||||
let addr = serve_echo();
|
||||
let mut c = TcpStream::connect(addr).unwrap();
|
||||
c.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
|
||||
c.write_all(b"{\"id\":3,\"method\":\"ping\"}\r\n\n{\"id\":4,\"method\":\"pong\"}\n").unwrap();
|
||||
c.write_all(b"{\"id\":3,\"method\":\"ping\",\"token\":\"s3cret\"}\r\n\n{\"id\":4,\"method\":\"pong\",\"token\":\"s3cret\"}\n").unwrap();
|
||||
let mut r = BufReader::new(c);
|
||||
for (id, method) in [(3, "ping"), (4, "pong")] {
|
||||
let mut line = String::new();
|
||||
@@ -228,6 +281,29 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_request_without_the_token_is_refused_and_the_connection_closed() {
|
||||
let addr = serve_echo();
|
||||
for request in [r#"{"id":1,"method":"ping"}"#, r#"{"id":1,"method":"ping","token":"s3cre"}"#, r#"{"id":1,"method":"ping","token":"S3CRET"}"#]
|
||||
{
|
||||
let mut c = TcpStream::connect(addr).unwrap();
|
||||
c.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
|
||||
writeln!(c, "{request}").unwrap();
|
||||
let mut r = BufReader::new(c);
|
||||
let mut line = String::new();
|
||||
r.read_line(&mut line).unwrap();
|
||||
let v: Value = serde_json::from_str(&line).unwrap();
|
||||
assert_eq!((v["id"].as_i64(), v["ok"].as_bool()), (Some(1), Some(false)), "{line}");
|
||||
assert!(v["error"].as_str().unwrap_or("").starts_with("unauthorized"), "{line}");
|
||||
assert!(v.get("method").is_none(), "the request was not forwarded: {line}");
|
||||
line.clear();
|
||||
assert_eq!(r.read_line(&mut line).unwrap(), 0, "the connection is closed after a refusal");
|
||||
}
|
||||
assert!(token_matches(Some(TOKEN), TOKEN));
|
||||
assert!(!token_matches(None, TOKEN));
|
||||
assert_eq!(new_token().unwrap().len(), 64);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extra_connections_are_refused() {
|
||||
let addr = serve_echo();
|
||||
|
||||
@@ -3,8 +3,9 @@
|
||||
//! Usage: `soundcraft [--demo] [--control <port>] [--no-audio] [session.scraft | audio files…]`; `soundcraft --help` lists the flags and `SOUNDCRAFT_CONTROL_PORT`.
|
||||
//!
|
||||
//! `--control <port>` (or `SOUNDCRAFT_CONTROL_PORT`) starts a localhost JSON-lines control server
|
||||
//! (`0` picks a free port and prints it): `{"id":1,"method":"ui.inspect","params":{}}` →
|
||||
//! `{"id":1,"ok":true,"result":…}`. See `soundcraft_ui_egui::control` for the methods.
|
||||
//! (`0` picks a free port and prints it): `{"id":1,"method":"ui.inspect","params":{},"token":"…"}` →
|
||||
//! `{"id":1,"ok":true,"result":…}`, where `token` is `SOUNDCRAFT_CONTROL_TOKEN` (or the one made for
|
||||
//! this launch, printed after the port). See `soundcraft_ui_egui::control` for the methods.
|
||||
//!
|
||||
//! `log` records go to standard error and `<settings dir>/logs/soundcraft.log` (`RUST_LOG` sets the
|
||||
//! levels); see [`logging`].
|
||||
@@ -187,6 +188,45 @@ fn services() -> Services {
|
||||
}
|
||||
}
|
||||
|
||||
/// The window's agents link: the ArtCraft Launcher's switch, the agent settings saved in the
|
||||
/// settings folder `dir` (where `soundcraft-cli mcp` reads them) and the folders agent requests run
|
||||
/// in. With `--control` the launch options manage the control channel for the whole run instead.
|
||||
fn agents(ctx: &egui::Context, dir: Option<std::path::PathBuf>, control_port: Option<u16>) -> soundcraft_ui_egui::agents::Agents {
|
||||
use soundcraft_automation::agents as cli;
|
||||
// A file a crashed (or, on macOS, quit) launch left behind names a port nothing serves.
|
||||
if let Some(dir) = &dir {
|
||||
craft_control::agents::remove_stale_connection(dir);
|
||||
}
|
||||
let switch = craft_control::agents::AgentSwitch::watch(cli::LAUNCHER_APP_ID, {
|
||||
let ctx = ctx.clone();
|
||||
move || ctx.request_repaint()
|
||||
});
|
||||
let settings = dir.as_deref().map(cli::read_settings).unwrap_or_default();
|
||||
let save_dir = dir.clone();
|
||||
let save: soundcraft_ui_egui::agents::SaveFn = Box::new(move |settings| match &save_dir {
|
||||
Some(dir) => cli::write_settings(dir, settings).map_err(|e| format!("couldn't save the agent settings: {e}")),
|
||||
None => Err("SoundCraft has no settings folder, so the agent settings can't be saved".into()),
|
||||
});
|
||||
let app = format!("SoundCraft {}", env!("SOUNDCRAFT_BUILT_VERSION"));
|
||||
let scope_dir = dir.clone();
|
||||
let scope: soundcraft_ui_egui::agents::ScopeFn = Box::new(move |folders| agent_scope(folders, scope_dir.as_deref()));
|
||||
let agents = soundcraft_ui_egui::agents::Agents::new(dir, app, switch, settings, save, scope);
|
||||
match control_port {
|
||||
Some(port) => agents.launched_with_control(port),
|
||||
None => agents,
|
||||
}
|
||||
}
|
||||
|
||||
/// What agent requests in the window may do with `folders`: the folder checks a headless agent
|
||||
/// session runs under (`soundcraft-cli mcp`), nothing writable in the settings folder `settings`.
|
||||
fn agent_scope(
|
||||
folders: &craft_control::agents::AgentFolders,
|
||||
settings: Option<&std::path::Path>,
|
||||
) -> Result<soundcraft_ui_egui::control::AgentScope, soundcraft_engine::file_access::RootError> {
|
||||
let roots = soundcraft_automation::agents::roots_for(folders, settings)?;
|
||||
Ok(soundcraft_ui_egui::control::AgentScope { folders: soundcraft_automation::agents::folders_answer(Some(&roots)), roots })
|
||||
}
|
||||
|
||||
/// The window, Dock, taskbar and Alt-Tab icon. macOS gets Apple's icon grid (transparent margin);
|
||||
/// elsewhere the full tile. Regenerate with `packaging/icons.sh`.
|
||||
fn app_icon() -> Option<egui::IconData> {
|
||||
@@ -395,9 +435,15 @@ fn main() -> eframe::Result {
|
||||
app.ui = prefs;
|
||||
// The Nightly window has no control server: no inherited port, no stable token file.
|
||||
if let Some(port) = control_port.filter(|_| !launch_profile::current().is_nightly()) {
|
||||
let rx = control_server::start(port, cc.egui_ctx.clone());
|
||||
let rx = control_server::start(port, soundcraft_automation::control_token(), cc.egui_ctx.clone());
|
||||
app = app.with_control(rx);
|
||||
}
|
||||
// Agents in the open window: while the ArtCraft Launcher's switch (Settings › AI agents)
|
||||
// names SoundCraft, the window serves agents and publishes where. Not in a Nightly
|
||||
// session, which the launcher doesn't list, nor in a run without preferences.
|
||||
if !launch_profile::current().is_nightly() && env.prefs_enabled() {
|
||||
app = app.with_agents(agents(&cc.egui_ctx, env.config_dir.clone(), control_port));
|
||||
}
|
||||
if previous_nightly_unclean || session_health_warning {
|
||||
app.ui.status = if previous_nightly_unclean {
|
||||
"The previous SoundCraft Nightly session did not finish normally. You can report a problem from About. No diagnostics have been sent.".to_owned()
|
||||
|
||||
@@ -19,6 +19,10 @@ thiserror.workspace = true
|
||||
# The launch flags (`args`): the web build has none.
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
|
||||
clap.workspace = true
|
||||
# `soundcraft-cli mcp` in the open window: the shared live client and agent settings
|
||||
# (`craft-control`), and the challenge handshake of the window's control server (`craft-automation`).
|
||||
craft-control = { workspace = true, features = ["agents"] }
|
||||
craft-automation = { workspace = true, features = ["agents"] }
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
@@ -0,0 +1,278 @@
|
||||
//! Agents in the open window: SoundCraft's side of the ArtCraft Launcher's switch.
|
||||
//!
|
||||
//! While the launcher's *Settings › AI agents* switch names SoundCraft (behind the suite's
|
||||
//! `AI-MCP` flag), the desktop app serves agents on loopback and publishes where in its settings
|
||||
//! folder (`craft_automation::agents::AgentLink`). Plain `soundcraft-cli mcp` reads that file
|
||||
//! before every tool call ([`live`], over the shared `craft_control::agents::Live`), so an MCP
|
||||
//! client's configuration holds no port and no token, and the app may start, quit or move to
|
||||
//! another port while the client stays connected. Adding SoundCraft to MCP clients is the
|
||||
//! launcher's job (one entry for every Craft app); SoundCraft writes no client configuration.
|
||||
//!
|
||||
//! What is SoundCraft's here: its launcher id, its agent settings file ([`SETTINGS_FILE`], which
|
||||
//! the app writes and the CLI reads), the folders a session is confined to ([`roots_for`]) and
|
||||
//! the `agent_folders` answer ([`folders_answer`]).
|
||||
|
||||
use std::cell::{RefCell, RefMut};
|
||||
use std::io::Read;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::rc::Rc;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use craft_control::agents::{self as shared, AgentFolders, AgentSettings, Consent, HeadlessFolders, Route};
|
||||
pub use craft_control::agents::{WhenAppClosed, mcp_flag};
|
||||
use serde_json::{Value, json};
|
||||
use soundcraft_engine::file_access::{self, AutomationRoots};
|
||||
|
||||
use crate::{Backend, Headless, Remote};
|
||||
|
||||
/// The id the ArtCraft Launcher's app list names SoundCraft by (its catalog id).
|
||||
pub const LAUNCHER_APP_ID: &str = "soundcraft";
|
||||
/// The app's name in messages and its default agent folder (`Documents/ArtCraft/Agents/SoundCraft`).
|
||||
pub const APP_NAME: &str = "SoundCraft";
|
||||
/// The desktop app's file name beside the CLI (without `.exe`).
|
||||
pub const APP_EXE: &str = "soundcraft";
|
||||
/// The agent settings in the settings folder: `{"controlPort", "readRoot", "writeRoot",
|
||||
/// "whenAppClosed", "allowAgentControl"}` (`craft_control::agents::AgentSettings`). The app writes it
|
||||
/// when they change, so `soundcraft-cli mcp` reads the current choice before every tool call.
|
||||
pub const SETTINGS_FILE: &str = "agents.json";
|
||||
/// The control method the `agent_folders` tool calls.
|
||||
pub const FOLDERS_METHOD: &str = "agent.folders";
|
||||
|
||||
/// The largest settings file read; the settings are a few short strings.
|
||||
const MAX_SETTINGS_FILE: u64 = 64 * 1024;
|
||||
|
||||
/// The agent settings saved in `dir`; the defaults when nothing is saved or the file can't be
|
||||
/// read, so neither the app nor the CLI fails over them. One bad value resets only itself.
|
||||
pub fn read_settings(dir: &Path) -> AgentSettings {
|
||||
// The app's own file: read whatever folders an agent request is confined to.
|
||||
let text = file_access::unconfined(|| {
|
||||
let file = std::fs::File::open(dir.join(SETTINGS_FILE)).ok()?;
|
||||
let mut text = String::new();
|
||||
file.take(MAX_SETTINGS_FILE + 1).read_to_string(&mut text).ok()?;
|
||||
(text.len() as u64 <= MAX_SETTINGS_FILE).then_some(text)
|
||||
});
|
||||
let Some(Value::Object(saved)) = text.and_then(|text| serde_json::from_str::<Value>(&text).ok()) else { return AgentSettings::default() };
|
||||
let mut settings = AgentSettings::default();
|
||||
for (key, value) in saved {
|
||||
let mut one = serde_json::to_value(&settings).unwrap_or_default();
|
||||
if let Some(o) = one.as_object_mut()
|
||||
&& o.contains_key(&key)
|
||||
{
|
||||
o.insert(key, value);
|
||||
if let Ok(next) = serde_json::from_value(one) {
|
||||
settings = next;
|
||||
}
|
||||
}
|
||||
}
|
||||
settings
|
||||
}
|
||||
|
||||
/// Saves `settings` in `dir` (created when missing), replacing the file in one step so a
|
||||
/// `soundcraft-cli mcp` reading it at the same time sees the old or the new settings, never half.
|
||||
pub fn write_settings(dir: &Path, settings: &AgentSettings) -> Result<(), String> {
|
||||
let text = serde_json::to_vec_pretty(settings).map_err(|e| e.to_string())?;
|
||||
// The app's own file: written whatever folders an agent request is confined to.
|
||||
file_access::unconfined(|| {
|
||||
std::fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?;
|
||||
let file = dir.join(SETTINGS_FILE);
|
||||
soundcraft_engine::io::replace_file(&file.with_extension("json.tmp"), &file, &text).map_err(|e| e.to_string())
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether the person lets agents use SoundCraft now: with the suite's `AI-MCP` flag, the
|
||||
/// launcher's switch. SoundCraft had no agent consent of its own before the switch, so without
|
||||
/// the flag agents get a session without a window, as `mcp` always gave them.
|
||||
pub fn allowed_now() -> bool {
|
||||
shared::agents_allowed(shared::mcp_flag(), shared::launcher_allows(LAUNCHER_APP_ID), false)
|
||||
}
|
||||
|
||||
/// What a session with these folders may read and write: the read folder, and the write folder,
|
||||
/// which may be read too. No folder at all grants nothing ([`AutomationRoots::none`]), never
|
||||
/// everything. Nothing may be written in the settings folder `settings` (the agent settings
|
||||
/// there choose these folders), even when a write folder holds it.
|
||||
pub fn roots_for(folders: &AgentFolders, settings: Option<&Path>) -> Result<Arc<AutomationRoots>, file_access::RootError> {
|
||||
let read: Vec<&Path> = folders.read.iter().chain(folders.write.iter()).map(PathBuf::as_path).collect();
|
||||
let write: Vec<&Path> = folders.write.iter().map(PathBuf::as_path).collect();
|
||||
let roots = AutomationRoots::new(&read, &write)?.unwrap_or_else(AutomationRoots::none);
|
||||
Ok(guarded(roots, settings))
|
||||
}
|
||||
|
||||
/// `roots`, with nothing writable in the settings folder `settings`.
|
||||
fn guarded(roots: Arc<AutomationRoots>, settings: Option<&Path>) -> Arc<AutomationRoots> {
|
||||
match settings {
|
||||
Some(dir) => AutomationRoots::denying_writes_in(&roots, dir),
|
||||
None => roots,
|
||||
}
|
||||
}
|
||||
|
||||
/// The `agent_folders` answer for a session confined to `roots`, or for one that isn't (`None`:
|
||||
/// started without automation roots, or the person's own `--control` channel), which says so
|
||||
/// rather than claim it has no folder.
|
||||
pub fn folders_answer(roots: Option<&AutomationRoots>) -> Value {
|
||||
match roots {
|
||||
Some(r) => {
|
||||
let mut folders = AgentFolders::default();
|
||||
// The write folder is also a read root (see `roots_for`): the first read root is the
|
||||
// person's read folder.
|
||||
folders.read = r.read_folders().next().map(Path::to_path_buf);
|
||||
folders.write = r.write_folders().next().map(Path::to_path_buf);
|
||||
let mut answer = shared::folders_answer(&folders);
|
||||
// Several roots of a kind (repeated `--automation-*-root` flags): list them all, beside
|
||||
// the shared single fields.
|
||||
for (key, list) in [("read_folders", r.read_folders().collect::<Vec<_>>()), ("write_folders", r.write_folders().collect())] {
|
||||
if list.len() > 1
|
||||
&& let Some(o) = answer.as_object_mut()
|
||||
{
|
||||
o.insert(key.into(), json!(list));
|
||||
}
|
||||
}
|
||||
answer
|
||||
}
|
||||
None => json!({
|
||||
"read_folder": null,
|
||||
"write_folder": null,
|
||||
"unrestricted": true,
|
||||
"note": "This session was started without automation roots: its file commands open and save wherever the user can.",
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
/// Starts the desktop app beside this executable (`soundcraft-cli` and `soundcraft` ship
|
||||
/// together); `None` when this install has none.
|
||||
pub fn launcher() -> Option<shared::LaunchFn> {
|
||||
let cli = std::env::current_exe().ok()?;
|
||||
shared::launcher(&cli, APP_EXE)
|
||||
}
|
||||
|
||||
/// Makes a fresh headless session, with the CLI's own options applied.
|
||||
pub type HeadlessFn = Box<dyn Fn() -> Result<Headless, String> + Send + Sync>;
|
||||
|
||||
/// What plain `soundcraft-cli mcp` needs to find the window.
|
||||
pub struct LiveConfig {
|
||||
/// The app's settings folder: connection file, token file and agent settings.
|
||||
pub config_dir: PathBuf,
|
||||
/// Overrides the app's closed-app choice (`--when-closed`).
|
||||
pub when_closed: Option<WhenAppClosed>,
|
||||
/// The command's folders (`--automation-read-root`, `--automation-write-root`).
|
||||
pub read_roots: Vec<PathBuf>,
|
||||
pub write_root: Option<PathBuf>,
|
||||
/// All the command's roots, opened: a headless session on the command's folders uses them,
|
||||
/// so a second write root given to the command still counts.
|
||||
pub command_roots: Option<Arc<AutomationRoots>>,
|
||||
/// Starts the app; `None` when this install can't.
|
||||
pub launch: Option<shared::LaunchFn>,
|
||||
pub launch_timeout: Duration,
|
||||
/// Whether agents may use the app now ([`allowed_now`]); tests replace it.
|
||||
pub allowed: fn() -> bool,
|
||||
/// The default agent folder for an empty folder setting; tests replace it.
|
||||
pub default_folder: Option<PathBuf>,
|
||||
/// Makes each new headless session.
|
||||
pub headless: HeadlessFn,
|
||||
}
|
||||
|
||||
impl LiveConfig {
|
||||
/// The settings in `config_dir`, the launcher's switch, the default agent folder.
|
||||
pub fn new(config_dir: PathBuf, headless: HeadlessFn) -> Self {
|
||||
Self {
|
||||
config_dir,
|
||||
when_closed: None,
|
||||
read_roots: vec![],
|
||||
write_root: None,
|
||||
command_roots: None,
|
||||
launch: None,
|
||||
launch_timeout: shared::LAUNCH_TIMEOUT,
|
||||
allowed: allowed_now,
|
||||
default_folder: shared::default_folder(APP_NAME),
|
||||
headless,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A route's backend, whichever call used it last (the server runs one call at a time).
|
||||
type Shared = Rc<RefCell<Box<dyn Backend>>>;
|
||||
|
||||
/// Plain `soundcraft-cli mcp`: every call goes to the open window while the person lets agents
|
||||
/// use it, otherwise to a headless session; a closed app follows the closed-app choice. The lookup
|
||||
/// is the shared `craft_control::agents::Live`; a session that went headless stays headless.
|
||||
pub struct Live {
|
||||
live: shared::Live<Shared, Shared>,
|
||||
}
|
||||
|
||||
/// Builds plain `mcp`'s backend from `cfg`.
|
||||
pub fn live(cfg: LiveConfig) -> Live {
|
||||
let LiveConfig { config_dir, when_closed, read_roots, write_root, command_roots, launch, launch_timeout, allowed, default_folder, headless } =
|
||||
cfg;
|
||||
let consent = move |dir: &Path| Consent::new(allowed(), read_settings(dir));
|
||||
let connect = |w: &shared::Window| -> Result<Shared, String> {
|
||||
// Signs in now, so a listener that can't prove it holds the token is never used.
|
||||
let remote = Remote::agents(w.port, w.token.clone()).map_err(|e| e.to_string())?;
|
||||
Ok(Rc::new(RefCell::new(Box::new(remote) as Box<dyn Backend>)))
|
||||
};
|
||||
let settings_dir = config_dir.clone();
|
||||
let (command_read, command_write) = (read_roots.clone(), write_root.clone());
|
||||
let make_headless = move |folders: &HeadlessFolders| -> Result<Shared, String> {
|
||||
let session = headless()?;
|
||||
// The write folder is read too, as in the window (`roots_for`): the agent reopens what it saved.
|
||||
let read: Vec<&Path> = folders.read.iter().chain(folders.write.iter()).map(PathBuf::as_path).collect();
|
||||
let write: Vec<&Path> = folders.write.iter().map(PathBuf::as_path).collect();
|
||||
let commands_own = folders.read == command_read && folders.write == command_write;
|
||||
let opened = match command_roots.as_ref().filter(|_| commands_own) {
|
||||
Some(roots) => Some(roots.clone()),
|
||||
None => AutomationRoots::new(&read, &write).map_err(|e| e.to_string())?,
|
||||
};
|
||||
let roots = match opened {
|
||||
Some(roots) => Some(roots),
|
||||
// No folder at all. With agents let in, that is an agent folder that couldn't be made:
|
||||
// nothing may be opened or saved. Only with agents not let in does the session keep
|
||||
// `mcp`'s old unconfined behaviour without automation roots.
|
||||
None if allowed() && read_settings(&settings_dir).allow_agent_control => Some(AutomationRoots::none()),
|
||||
None => None,
|
||||
};
|
||||
let roots = roots.map(|roots| guarded(roots, Some(&settings_dir)));
|
||||
let session = session.with_automation_roots(roots).without_window();
|
||||
Ok(Rc::new(RefCell::new(Box::new(session) as Box<dyn Backend>)))
|
||||
};
|
||||
let mut shared_cfg = shared::LiveConfig::new(APP_NAME, config_dir, consent, connect, make_headless);
|
||||
shared_cfg.when_closed = when_closed;
|
||||
shared_cfg.read_roots = read_roots;
|
||||
shared_cfg.write_root = write_root;
|
||||
shared_cfg.launch = launch;
|
||||
shared_cfg.launch_timeout = launch_timeout;
|
||||
shared_cfg.default_folder = default_folder;
|
||||
Live { live: shared::Live::new(shared_cfg) }
|
||||
}
|
||||
|
||||
impl Live {
|
||||
/// The backend this call goes to.
|
||||
fn route(&self) -> Result<Shared, String> {
|
||||
Ok(match self.live.resolve()? {
|
||||
Route::Window(w) => w,
|
||||
Route::Headless(h) => h,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn lock(shared: &Shared) -> RefMut<'_, Box<dyn Backend>> {
|
||||
shared.borrow_mut()
|
||||
}
|
||||
|
||||
impl Backend for Live {
|
||||
fn call(&mut self, method: &str, params: Value) -> Result<Value, String> {
|
||||
let route = self.route()?;
|
||||
lock(&route).call(method, params)
|
||||
}
|
||||
|
||||
/// The open window may answer the window's tools; a headless route says it has no window.
|
||||
fn has_ui(&self) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
fn describe(&self) -> String {
|
||||
match self.live.current() {
|
||||
Some(Route::Window(w)) => lock(&w).describe(),
|
||||
Some(Route::Headless(h)) => lock(&h).describe(),
|
||||
None => format!("the open {APP_NAME} window while the ArtCraft Launcher's switch lets agents in, otherwise headless"),
|
||||
}
|
||||
}
|
||||
}
|
||||
+149
-15
@@ -2,16 +2,22 @@
|
||||
//!
|
||||
//! - [`Backend`]: something that answers control-protocol methods (`engine.execute`,
|
||||
//! `session.inspect`, `ui.*`…). [`Headless`] runs an in-process engine; [`Remote`] talks to a
|
||||
//! running app's `--control` port.
|
||||
//! running app's `--control` port, or the agents channel of the open window ([`Remote::agents`]).
|
||||
//! - [`agents::Live`]: plain `soundcraft-cli mcp`. Before every call it looks for the open window
|
||||
//! the ArtCraft Launcher's switch lets agents into, and otherwise uses a [`Headless`] engine.
|
||||
//! - [`mcp::Server`]: a Model Context Protocol server over stdio (newline-delimited JSON-RPC 2.0)
|
||||
//! exposing SoundCraft as tools and resources.
|
||||
//! - [`args`]: the control and automation launch flags and their environment variables, as clap
|
||||
//! types.
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub mod agents;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub mod args;
|
||||
pub mod mcp;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub mod profile;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use soundcraft_engine::Engine;
|
||||
@@ -34,11 +40,27 @@ pub trait Backend {
|
||||
pub struct Headless {
|
||||
pub engine: Engine,
|
||||
roots: Option<Arc<AutomationRoots>>,
|
||||
/// Plain `soundcraft-cli mcp` went headless: a method that needs the window says there is none
|
||||
/// here rather than how to start one by hand.
|
||||
no_window: bool,
|
||||
}
|
||||
|
||||
/// What a `ui.*` method answers headless.
|
||||
const NEEDS_APP: &str = "needs the open SoundCraft window: open SoundCraft and turn on the ArtCraft Launcher's \
|
||||
Settings › AI agents switch, then run plain `soundcraft-cli mcp`";
|
||||
/// The same for plain `mcp`'s headless session, which looked for the window and found none.
|
||||
const NO_WINDOW: &str = "needs the open SoundCraft window, and this session has none: open SoundCraft and turn on \
|
||||
the ArtCraft Launcher's Settings › AI agents switch, or start `soundcraft-cli mcp --when-closed launch`";
|
||||
|
||||
impl Headless {
|
||||
pub fn new(engine: Engine) -> Self {
|
||||
Headless { engine, roots: None }
|
||||
Headless { engine, roots: None, no_window: false }
|
||||
}
|
||||
|
||||
/// Plain `mcp`'s headless session: the window's methods say this session has none.
|
||||
pub fn without_window(mut self) -> Self {
|
||||
self.no_window = true;
|
||||
self
|
||||
}
|
||||
|
||||
/// Confine every file the session's commands read and write to `roots`
|
||||
@@ -63,9 +85,9 @@ impl Headless {
|
||||
"session.inspect" | "document.inspect" => {
|
||||
Ok(soundcraft_engine::inspect::session(&self.engine, params.get("detail").and_then(Value::as_str) == Some("full")))
|
||||
}
|
||||
m if m.starts_with("ui.") => {
|
||||
Err(format!("`{m}` needs the desktop app: start `soundcraft --control 0` and use `soundcraft-cli mcp --connect PORT`"))
|
||||
}
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
agents::FOLDERS_METHOD => Ok(agents::folders_answer(self.roots.as_deref())),
|
||||
m if m.starts_with("ui.") => Err(format!("`{m}` {}", if self.no_window { NO_WINDOW } else { NEEDS_APP })),
|
||||
other => Err(format!("unknown method `{other}`")),
|
||||
}
|
||||
}
|
||||
@@ -80,7 +102,10 @@ impl Backend for Headless {
|
||||
false
|
||||
}
|
||||
fn describe(&self) -> String {
|
||||
format!("headless engine, session `{}`", self.engine.session().name)
|
||||
match &self.roots {
|
||||
Some(roots) => format!("headless engine, session `{}`, files: {}", self.engine.session().name, roots.describe()),
|
||||
None => format!("headless engine, session `{}`", self.engine.session().name),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -139,6 +164,12 @@ pub enum RemoteError {
|
||||
/// The reply answers another request, so it isn't returned.
|
||||
#[error("the reply does not answer this request (its id is {got}, not {expected})")]
|
||||
OutOfStep { expected: u64, got: String },
|
||||
/// The request is longer than the agents channel accepts; it wasn't sent.
|
||||
#[error("the request is larger than the {max} bytes the SoundCraft window accepts from agents; nothing was sent: split it into smaller calls")]
|
||||
TooLarge { max: usize },
|
||||
/// The challenge sign-in on the agents channel failed; the request wasn't sent.
|
||||
#[error("{0}")]
|
||||
SignIn(String),
|
||||
}
|
||||
|
||||
impl RemoteError {
|
||||
@@ -165,14 +196,31 @@ impl RemoteError {
|
||||
|
||||
type Connection = (TcpStream, BufReader<TcpStream>);
|
||||
|
||||
/// The variable carrying the control channel's secret: the app refuses every request whose
|
||||
/// `token` differs from it, so another local account can't drive the app through the loopback
|
||||
/// port. The app makes one per launch when the variable is unset (printed after the port line).
|
||||
pub const CONTROL_TOKEN_VAR: &str = "SOUNDCRAFT_CONTROL_TOKEN";
|
||||
|
||||
/// [`CONTROL_TOKEN_VAR`] from the environment; a blank value counts as unset.
|
||||
pub fn control_token() -> Option<String> {
|
||||
std::env::var(CONTROL_TOKEN_VAR).ok().map(|t| t.trim().to_owned()).filter(|t| !t.is_empty())
|
||||
}
|
||||
|
||||
/// A TCP client for a running app's control channel.
|
||||
pub struct Remote {
|
||||
/// The target as `host:port`, for connecting and for messages.
|
||||
addr: String,
|
||||
/// The `--control` channel's secret ([`control_token`]), sent with every request; without one
|
||||
/// that channel refuses, naming the variable. `None` on the agents channel, which signs in.
|
||||
control_token: Option<String>,
|
||||
conn: Option<Connection>,
|
||||
next_id: u64,
|
||||
/// How long a request waits for its reply.
|
||||
read_timeout: Duration,
|
||||
/// The agent token of the window's agents channel; `None` for `--control`, which sends `control_token`.
|
||||
token: Option<String>,
|
||||
/// The longest request line the app accepts; `None`: the app's own limit decides.
|
||||
max_request: Option<usize>,
|
||||
}
|
||||
|
||||
/// The app answers within 90 s (it replies `timeout` itself after that), so a longer silence
|
||||
@@ -180,17 +228,50 @@ pub struct Remote {
|
||||
const READ_TIMEOUT: Duration = Duration::from_secs(120);
|
||||
|
||||
impl Remote {
|
||||
/// A client for the app at `target`; it connects on the first request.
|
||||
/// A client for the app at `target`, authenticating with [`control_token`]; it connects on the
|
||||
/// first request.
|
||||
pub fn new(target: &ControlTarget) -> Self {
|
||||
Remote { addr: target.to_string(), conn: None, next_id: 1, read_timeout: READ_TIMEOUT }
|
||||
Remote {
|
||||
addr: target.to_string(),
|
||||
control_token: control_token(),
|
||||
conn: None,
|
||||
next_id: 1,
|
||||
read_timeout: READ_TIMEOUT,
|
||||
token: None,
|
||||
max_request: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The open connection, connecting first when there is none.
|
||||
/// The open window's agents channel on `127.0.0.1:port`, signed in with `token` (from the
|
||||
/// connection file's token file) through the challenge handshake, now and on every reconnect.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub fn agents(port: u16, token: String) -> Result<Self, RemoteError> {
|
||||
let mut r = Remote {
|
||||
addr: format!("127.0.0.1:{port}"),
|
||||
control_token: None,
|
||||
conn: None,
|
||||
next_id: 1,
|
||||
read_timeout: READ_TIMEOUT,
|
||||
token: Some(token),
|
||||
max_request: Some(craft_automation::security::MAX_REQUEST_BYTES),
|
||||
};
|
||||
r.connection()?;
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
/// The open connection, connecting (and on the agents channel signing in) first when there is
|
||||
/// none.
|
||||
fn connection(&mut self) -> Result<&mut Connection, RemoteError> {
|
||||
match self.conn {
|
||||
Some(ref mut conn) => Ok(conn),
|
||||
None => Ok(self.conn.insert(connect(&self.addr, self.read_timeout)?)),
|
||||
if self.conn.is_none() {
|
||||
#[cfg_attr(target_arch = "wasm32", allow(unused_mut))]
|
||||
let mut conn = connect(&self.addr, self.read_timeout)?;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if let Some(token) = &self.token {
|
||||
sign_in(&mut conn, &self.addr, token)?;
|
||||
}
|
||||
self.conn = Some(conn);
|
||||
}
|
||||
self.conn.as_mut().ok_or(RemoteError::Closed)
|
||||
}
|
||||
|
||||
/// One request/reply exchange. On failure the flag says whether the request line was already
|
||||
@@ -198,7 +279,14 @@ impl Remote {
|
||||
fn roundtrip(&mut self, method: &str, params: &Value) -> Result<Value, (RemoteError, bool)> {
|
||||
let id = self.next_id;
|
||||
self.next_id += 1;
|
||||
let line = json!({"id": id, "method": method, "params": params}).to_string();
|
||||
let mut line = json!({"id": id, "method": method, "params": params});
|
||||
if let Some(token) = &self.control_token {
|
||||
line["token"] = json!(token);
|
||||
}
|
||||
let line = line.to_string();
|
||||
if let Some(max) = self.max_request.filter(|max| line.len() > *max) {
|
||||
return Err((RemoteError::TooLarge { max }, false));
|
||||
}
|
||||
let (w, r) = self.connection().map_err(|e| (e, false))?;
|
||||
writeln!(w, "{line}").map_err(|e| (e.into(), false))?;
|
||||
let mut buf = String::new();
|
||||
@@ -273,9 +361,51 @@ fn connect(addr: &str, read_timeout: Duration) -> Result<Connection, RemoteError
|
||||
})
|
||||
}
|
||||
|
||||
/// The challenge handshake on a fresh agents-channel connection: `auth.challenge` with our nonce,
|
||||
/// check the app's proof, then send ours. Nothing derived from the token goes to a listener that
|
||||
/// can't prove it holds it.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn sign_in(conn: &mut Connection, addr: &str, token: &str) -> Result<(), RemoteError> {
|
||||
use craft_automation::security::{self, ProofRole};
|
||||
let failed = |e: security::AutomationError| RemoteError::SignIn(e.to_string());
|
||||
let client_nonce = security::generate_nonce().map_err(failed)?;
|
||||
let challenge = handshake_step(conn, security::CHALLENGE_METHOD, json!({"clientNonce": client_nonce}))?
|
||||
.map_err(|e| RemoteError::SignIn(format!("{addr} refused challenge authentication ({e}); the agent token was not used")))?;
|
||||
let field = |key: &str| challenge.get(key).and_then(Value::as_str).filter(|v| security::is_hex256(v)).map(str::to_owned);
|
||||
let (Some(server_nonce), Some(server_proof)) = (field("serverNonce"), field("serverProof")) else {
|
||||
return Err(RemoteError::SignIn(format!("{addr} answered the challenge without a proof; the agent token was not used")));
|
||||
};
|
||||
if !security::proof_matches(token, ProofRole::Server, &client_nonce, &server_nonce, &server_proof) {
|
||||
return Err(RemoteError::SignIn(format!("{addr} could not prove it holds SoundCraft's agent token; nothing was sent to it")));
|
||||
}
|
||||
let proof = security::handshake_proof(token, ProofRole::Client, &client_nonce, &server_nonce).map_err(failed)?;
|
||||
handshake_step(conn, security::AUTH_METHOD, json!({"proof": proof}))?
|
||||
.map_err(|e| RemoteError::SignIn(format!("SoundCraft refused the agent token: {e}")))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// One handshake request (id 0) and its reply: `Err` when the connection failed, `Ok(Err)` when
|
||||
/// the app answered with an error.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn handshake_step(conn: &mut Connection, method: &str, params: Value) -> Result<Result<Value, String>, RemoteError> {
|
||||
let (w, r) = conn;
|
||||
writeln!(w, "{}", json!({"id": 0, "method": method, "params": params}))?;
|
||||
let mut buf = String::new();
|
||||
r.read_line(&mut buf)?;
|
||||
if buf.is_empty() {
|
||||
return Err(RemoteError::Closed);
|
||||
}
|
||||
let v: Value = serde_json::from_str(&buf)?;
|
||||
Ok(if v.get("ok").and_then(Value::as_bool) == Some(true) {
|
||||
Ok(v.get("result").cloned().unwrap_or(Value::Null))
|
||||
} else {
|
||||
Err(v.get("error").and_then(Value::as_str).unwrap_or("error").to_string())
|
||||
})
|
||||
}
|
||||
|
||||
/// Methods that only read state, so repeating them after a lost reply is harmless.
|
||||
fn is_read_only(method: &str) -> bool {
|
||||
matches!(method, "session.inspect" | "document.inspect" | "engine.commands" | "engine.parity" | "ui.inspect" | "ui.menu.list")
|
||||
matches!(method, "session.inspect" | "document.inspect" | "engine.commands" | "engine.parity" | "ui.inspect" | "ui.menu.list" | "agent.folders")
|
||||
}
|
||||
|
||||
impl Backend for Remote {
|
||||
@@ -286,7 +416,11 @@ impl Backend for Remote {
|
||||
true
|
||||
}
|
||||
fn describe(&self) -> String {
|
||||
format!("SoundCraft app at {}", self.addr)
|
||||
if self.token.is_some() {
|
||||
format!("the open SoundCraft window (agents channel at {})", self.addr)
|
||||
} else {
|
||||
format!("SoundCraft app at {}", self.addr)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -8,13 +8,23 @@ use std::io::{BufRead, Write};
|
||||
|
||||
pub use craft_mcp_server::PROTOCOL_VERSION;
|
||||
const MAX_BATCH_CALLS: usize = 1000;
|
||||
/// The tool that says which folders this session may open and save files in (the shared name and
|
||||
/// description of every Craft app's MCP server).
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
const AGENT_FOLDERS_TOOL: &str = craft_control::agents::FOLDERS_TOOL;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
const AGENT_FOLDERS_DESCRIPTION: &str = craft_control::agents::FOLDERS_TOOL_DESCRIPTION;
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
const AGENT_FOLDERS_TOOL: &str = "agent_folders";
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
const AGENT_FOLDERS_DESCRIPTION: &str = "The folders this session may open and save files in.";
|
||||
const MAX_LINE_BYTES: usize = 16 * 1024 * 1024;
|
||||
|
||||
const INSTRUCTIONS: &str = "SoundCraft is a digital audio workstation (Pro Tools-class). Everything a user can do is a \
|
||||
command: call `list_commands` to discover ids and their params, then `execute` (or `batch`). Positions are samples \
|
||||
(integers), `{\"seconds\": x}`, or time strings like \"bars_beats:5|1|000\" / \"0:12.500\". Tracks are referenced by id \
|
||||
or name. Verify your work with `inspect_session` (tracks, clips, mixer, automation, markers, selection). Programmatic \
|
||||
calls never open dialogs. Tools marked APP_ONLY need the desktop app (`soundcraft --control 0` + `soundcraft-cli mcp --connect PORT`).";
|
||||
calls never open dialogs. Tools marked APP_ONLY need the open SoundCraft window (plain `soundcraft-cli mcp` while the ArtCraft Launcher's Settings › AI agents switch lets agents in). `agent_folders` says where files may be opened and saved.";
|
||||
|
||||
struct SoundcraftTools<B: Backend> {
|
||||
backend: B,
|
||||
@@ -80,6 +90,7 @@ pub fn tool_definitions() -> Vec<Value> {
|
||||
&["path"],
|
||||
),
|
||||
tool("parity", "Feature-parity report against the incumbent's menu catalog.", json!({}), &[]),
|
||||
tool(AGENT_FOLDERS_TOOL, AGENT_FOLDERS_DESCRIPTION, json!({}), &[]),
|
||||
tool("screenshot", "APP_ONLY. Screenshot the app window (PNG).", json!({"path": {"type": "string"}}), &[]),
|
||||
tool("ui_inspect", "APP_ONLY. UI state: front window, panels, layout rectangles of tracks, dialogs.", json!({}), &[]),
|
||||
tool("ui_set", "APP_ONLY. Set UI state fields, e.g. {\"window\": \"Mix\"}.", json!({"state": {"type": "object"}}), &["state"]),
|
||||
@@ -174,6 +185,7 @@ impl<B: Backend> SoundcraftTools<B> {
|
||||
"import_audio" => self.exec("file.import_audio", args.clone()),
|
||||
"bounce_mix" => self.exec("file.bounce_mix", args.clone()),
|
||||
"parity" => self.backend.call("engine.parity", json!({})),
|
||||
AGENT_FOLDERS_TOOL => self.backend.call("agent.folders", json!({})),
|
||||
"screenshot" => {
|
||||
let r = self.backend.call("ui.screenshot", args.clone());
|
||||
if let Ok(v) = &r
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
//! SoundCraft's settings folder, found the same way by the desktop app and by `soundcraft-cli mcp`:
|
||||
//! the CLI reads the agent settings and the connection file the app keeps there
|
||||
//! ([`crate::agents`]). A validated Nightly profile, which only the app knows about, comes first
|
||||
//! in the app (`apps/soundcraft/src/config.rs`); the CLI serves the Stable app.
|
||||
|
||||
use std::ffi::OsString;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// Portable mode (#268): this file beside the executable keeps settings, autosaves, presets and
|
||||
/// logs in [`PORTABLE_DATA_DIR`] next to it instead of the user profile.
|
||||
pub const PORTABLE_MARKER: &str = "portable.txt";
|
||||
pub const PORTABLE_DATA_DIR: &str = "SoundCraftData";
|
||||
/// The variable that overrides the settings folder.
|
||||
pub const CONFIG_DIR_VAR: &str = "SOUNDCRAFT_CONFIG_DIR";
|
||||
|
||||
/// The platform whose default settings folder applies.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub enum Platform {
|
||||
Mac,
|
||||
Windows,
|
||||
Other,
|
||||
}
|
||||
|
||||
impl Platform {
|
||||
/// The platform this binary was built for.
|
||||
pub fn current() -> Self {
|
||||
if cfg!(target_os = "macos") {
|
||||
Platform::Mac
|
||||
} else if cfg!(windows) {
|
||||
Platform::Windows
|
||||
} else {
|
||||
Platform::Other
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The Stable settings folder from the process environment, beside this executable: what
|
||||
/// `soundcraft-cli mcp` reads the app's agent settings and connection file from.
|
||||
pub fn config_dir() -> Option<PathBuf> {
|
||||
let exe = std::env::current_exe().ok();
|
||||
config_dir_with(Platform::current(), |name| std::env::var_os(name), exe.as_deref().and_then(Path::parent))
|
||||
}
|
||||
|
||||
/// The Stable settings folder, resolved from the variable lookup `env`. A nonempty
|
||||
/// `$SOUNDCRAFT_CONFIG_DIR` overrides the platform default and is the complete directory; no
|
||||
/// application-name suffix is appended. An explicitly empty value means no settings folder instead
|
||||
/// of a fallback to a personal profile (the documented exception to RFC-0012 rule 1.7). Otherwise
|
||||
/// `portable.txt` beside the executable (in `exe_dir`) selects `<exe dir>/SoundCraftData`, when
|
||||
/// that folder can be written (a read-only medium falls back to the platform default).
|
||||
pub fn config_dir_with(platform: Platform, env: impl Fn(&str) -> Option<OsString>, exe_dir: Option<&Path>) -> Option<PathBuf> {
|
||||
if let Some(dir) = env(CONFIG_DIR_VAR) {
|
||||
return (!dir.is_empty()).then(|| PathBuf::from(dir));
|
||||
}
|
||||
if let Some(exe_dir) = exe_dir.filter(|d| d.join(PORTABLE_MARKER).is_file()) {
|
||||
let data = exe_dir.join(PORTABLE_DATA_DIR);
|
||||
match writable(&data) {
|
||||
Ok(()) => return Some(data),
|
||||
Err(e) => log::warn!("portable mode: {} can't be written ({e}); using the user profile instead", data.display()),
|
||||
}
|
||||
}
|
||||
match platform {
|
||||
Platform::Mac => env("HOME").map(|h| PathBuf::from(h).join("Library/Application Support/SoundCraft")),
|
||||
Platform::Windows => env("APPDATA").map(|a| PathBuf::from(a).join("SoundCraft")),
|
||||
Platform::Other => {
|
||||
env("XDG_CONFIG_HOME").map(PathBuf::from).or_else(|| env("HOME").map(|h| PathBuf::from(h).join(".config"))).map(|c| c.join("soundcraft"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Create `dir` if needed and prove a file can be written in it. The Nightly profile validator
|
||||
/// injects this same exclusive probe.
|
||||
///
|
||||
/// The probe never replaces an existing entry: `create_new` cannot truncate one, and a name that is
|
||||
/// already taken (an interrupted run, or a file someone else made) is left untouched while the next
|
||||
/// name is tried. Only a file this call created is removed again.
|
||||
pub fn writable(dir: &Path) -> std::io::Result<()> {
|
||||
std::fs::create_dir_all(dir)?;
|
||||
for attempt in 0..8u32 {
|
||||
let probe = dir.join(format!(".write-test-{}-{attempt}", std::process::id()));
|
||||
match std::fs::OpenOptions::new().write(true).create_new(true).open(&probe) {
|
||||
Ok(file) => {
|
||||
drop(file);
|
||||
return std::fs::remove_file(probe);
|
||||
}
|
||||
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue,
|
||||
Err(error) => return Err(error),
|
||||
}
|
||||
}
|
||||
Err(std::io::Error::new(std::io::ErrorKind::AlreadyExists, "no free write-probe name"))
|
||||
}
|
||||
@@ -0,0 +1,241 @@
|
||||
//! Plain `soundcraft-cli mcp` in the open window: the agents channel is signed in with the
|
||||
//! window's token through the challenge handshake (a listener without the token gets nothing), the
|
||||
//! live backend goes to the window the connection file names and to a headless session otherwise,
|
||||
//! and a headless session made with the app's agent folders stays inside them.
|
||||
|
||||
use std::io::{BufRead, BufReader, Write};
|
||||
use std::net::TcpListener;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::mpsc::{Receiver, channel};
|
||||
|
||||
use craft_automation::security::{self, AuthStep, ServerHandshake};
|
||||
use craft_control::agents::{AgentSettings, Connection, TOKEN_FILE, WhenAppClosed, write_connection};
|
||||
use serde_json::{Value, json};
|
||||
use soundcraft_automation::agents::{self, LiveConfig};
|
||||
use soundcraft_automation::mcp::Server;
|
||||
use soundcraft_automation::{Backend, Headless, Remote};
|
||||
use soundcraft_engine::Engine;
|
||||
|
||||
/// A fresh, empty folder for one test.
|
||||
/// Writes `token` to `path` readable by its owner only, as the window writes it: a token others
|
||||
/// can read is refused.
|
||||
fn write_token(path: &Path, token: &str) {
|
||||
let mut options = std::fs::OpenOptions::new();
|
||||
options.write(true).create(true).truncate(true);
|
||||
#[cfg(unix)]
|
||||
std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600);
|
||||
options.open(path).unwrap().write_all(token.as_bytes()).unwrap();
|
||||
}
|
||||
|
||||
fn folder(tag: &str) -> PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!("sc-automation-agents-{tag}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
dir
|
||||
}
|
||||
|
||||
/// A window stand-in on a loopback port: it authenticates each connection with `token` as the
|
||||
/// app's agents channel does, answers `agent.folders` with `folders` and everything else with
|
||||
/// `{"window": true}`, and reports every control method it was sent after authenticating.
|
||||
fn fake_window(token: String, folders: Value) -> (u16, Receiver<String>) {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
let (tx, rx) = channel();
|
||||
std::thread::spawn(move || {
|
||||
for stream in listener.incoming() {
|
||||
let Ok(stream) = stream else { return };
|
||||
let (token, folders, tx) = (token.clone(), folders.clone(), tx.clone());
|
||||
std::thread::spawn(move || {
|
||||
let mut out = stream.try_clone().unwrap();
|
||||
let mut handshake = ServerHandshake::new();
|
||||
let mut authenticated = false;
|
||||
for line in BufReader::new(stream).lines() {
|
||||
let Ok(line) = line else { return };
|
||||
if !authenticated {
|
||||
let (reply, step) = handshake.reply(&line, &token);
|
||||
authenticated = step == AuthStep::Authenticated;
|
||||
if writeln!(out, "{reply}").is_err() || step == AuthStep::Rejected {
|
||||
return;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let req: Value = serde_json::from_str(&line).unwrap();
|
||||
let method = req["method"].as_str().unwrap_or("").to_string();
|
||||
let result = match method.as_str() {
|
||||
"agent.folders" => folders.clone(),
|
||||
_ => json!({"window": true}),
|
||||
};
|
||||
let _ = tx.send(method);
|
||||
if writeln!(out, "{}", json!({"id": req["id"], "ok": true, "result": result})).is_err() {
|
||||
return;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
(port, rx)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_agents_channel_signs_in_only_with_the_windows_token() {
|
||||
let token = security::generate_token().unwrap();
|
||||
let (port, seen) = fake_window(token.clone(), json!({}));
|
||||
let mut remote = Remote::agents(port, token).unwrap();
|
||||
assert_eq!(remote.call("session.inspect", json!({})).unwrap()["window"], true);
|
||||
assert_eq!(seen.recv().unwrap(), "session.inspect");
|
||||
|
||||
// A listener that holds another token can't prove it holds this one: nothing is sent to it.
|
||||
let other = security::generate_token().unwrap();
|
||||
let (port, seen) = fake_window(other, json!({}));
|
||||
let refused = Remote::agents(port, security::generate_token().unwrap()).err().expect("a stranger's listener was trusted");
|
||||
assert!(refused.to_string().contains("could not prove"), "{refused}");
|
||||
assert!(seen.try_recv().is_err(), "a method reached a listener without the token");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_request_too_large_for_the_agents_channel_is_not_sent() {
|
||||
let token = security::generate_token().unwrap();
|
||||
let (port, seen) = fake_window(token.clone(), json!({}));
|
||||
let mut remote = Remote::agents(port, token).unwrap();
|
||||
let big = "x".repeat(security::MAX_REQUEST_BYTES + 1);
|
||||
let refused = remote.call("engine.execute", json!({"command": "session.rename", "params": {"name": big}})).unwrap_err();
|
||||
assert!(refused.contains("nothing was sent"), "{refused}");
|
||||
assert!(seen.try_recv().is_err(), "the oversized request went out");
|
||||
}
|
||||
|
||||
fn yes() -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
fn no() -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
/// The live backend for the settings folder `dir`, with the switch `allowed`.
|
||||
fn live(dir: &Path, allowed: fn() -> bool, default: Option<PathBuf>) -> Server<agents::Live> {
|
||||
let mut cfg = LiveConfig::new(dir.to_path_buf(), Box::new(|| Ok(Headless::new(Engine::default()))));
|
||||
cfg.allowed = allowed;
|
||||
cfg.default_folder = default;
|
||||
Server::new(agents::live(cfg))
|
||||
}
|
||||
|
||||
fn tool(server: &mut Server<agents::Live>, name: &str, arguments: Value) -> (bool, String) {
|
||||
let reply = server.handle(&json!({"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": name, "arguments": arguments}})).unwrap();
|
||||
(reply["result"]["isError"] == true, reply["result"]["content"][0]["text"].as_str().unwrap_or_default().to_string())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plain_mcp_works_in_the_window_the_connection_file_names() {
|
||||
let dir = folder("window");
|
||||
let token = security::generate_token().unwrap();
|
||||
write_token(&dir.join(TOKEN_FILE), &token);
|
||||
let (port, seen) = fake_window(token, json!({"read_folder": "R", "write_folder": "W"}));
|
||||
write_connection(&dir, &Connection::new(port, dir.join(TOKEN_FILE), "SoundCraft test")).unwrap();
|
||||
let mut server = live(&dir, yes, None);
|
||||
let (failed, text) = tool(&mut server, "inspect_session", json!({}));
|
||||
assert!(!failed, "{text}");
|
||||
assert_eq!(seen.recv().unwrap(), "session.inspect");
|
||||
let (_, folders) = tool(&mut server, "agent_folders", json!({}));
|
||||
assert!(folders.contains("\"W\""), "the window answers agent_folders: {folders}");
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn without_a_window_plain_mcp_works_headless() {
|
||||
// The switch off: a session without a window, with the command's folders (none: unconfined, as
|
||||
// `mcp` always was), whose window tools say there is no window.
|
||||
let dir = folder("off");
|
||||
let mut server = live(&dir, no, None);
|
||||
let (failed, text) = tool(&mut server, "inspect_session", json!({}));
|
||||
assert!(!failed, "{text}");
|
||||
let (_, folders) = tool(&mut server, "agent_folders", json!({}));
|
||||
assert!(folders.contains("unrestricted"), "{folders}");
|
||||
let (failed, text) = tool(&mut server, "ui_inspect", json!({}));
|
||||
assert!(failed && text.contains("this session has none"), "{text}");
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_closed_app_set_to_headless_keeps_agents_in_its_agent_folder() {
|
||||
let dir = folder("closed");
|
||||
let (config, agent_folder, outside) = (dir.join("settings"), dir.join("Agents"), dir.join("elsewhere"));
|
||||
std::fs::create_dir_all(&outside).unwrap();
|
||||
let mut settings = AgentSettings::default();
|
||||
settings.when_app_closed = WhenAppClosed::Headless;
|
||||
agents::write_settings(&config, &settings).unwrap();
|
||||
let mut server = live(&config, yes, Some(agent_folder.clone()));
|
||||
let (_, folders) = tool(&mut server, "agent_folders", json!({}));
|
||||
assert!(folders.contains("Agents") && !folders.contains("unrestricted"), "{folders}");
|
||||
let (failed, text) = tool(&mut server, "save_session", json!({"path": outside.join("a.scraft")}));
|
||||
assert!(failed && text.contains("outside the write root"), "{text}");
|
||||
let (failed, text) = tool(&mut server, "save_session", json!({"path": agent_folder.join("a.scraft")}));
|
||||
assert!(!failed, "{text}");
|
||||
assert!(std::fs::read_dir(&outside).unwrap().next().is_none(), "the session was saved outside the agent folder");
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_agent_folder_reaches_the_agent_settings() {
|
||||
// The person made their home folder (here `base`) the write folder: the settings folder inside
|
||||
// it, which holds the agent settings and token, still takes no agent write, made yet or not.
|
||||
let base = folder("guard");
|
||||
let settings = base.join("settings");
|
||||
let mut folders = craft_control::agents::AgentFolders::default();
|
||||
folders.write = Some(base.clone());
|
||||
let roots = agents::roots_for(&folders, Some(&settings)).unwrap();
|
||||
let write = soundcraft_engine::file_access::Access::Write;
|
||||
let refused = roots.check(settings.join(agents::SETTINGS_FILE), write).unwrap_err();
|
||||
assert!(refused.contains("settings folder"), "{refused}");
|
||||
assert!(roots.check(base.join("song.scraft"), write).is_ok());
|
||||
std::fs::create_dir_all(&settings).unwrap();
|
||||
assert!(roots.check(settings.join(TOKEN_FILE), write).is_err());
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_headless_agent_reopens_what_it_saved_in_its_write_folder() {
|
||||
// Separate read and write folders: the write folder is read too, as in the window.
|
||||
let dir = folder("reopen");
|
||||
let (config, read, write) = (dir.join("settings"), dir.join("in"), dir.join("out"));
|
||||
for d in [&read, &write] {
|
||||
std::fs::create_dir_all(d).unwrap();
|
||||
}
|
||||
let mut settings = AgentSettings::default();
|
||||
settings.when_app_closed = WhenAppClosed::Headless;
|
||||
settings.read_root = read.to_string_lossy().into_owned();
|
||||
settings.write_root = write.to_string_lossy().into_owned();
|
||||
agents::write_settings(&config, &settings).unwrap();
|
||||
let mut server = live(&config, yes, None);
|
||||
let saved = write.join("a.scraft");
|
||||
let (failed, text) = tool(&mut server, "save_session", json!({"path": saved}));
|
||||
assert!(!failed, "{text}");
|
||||
let (failed, text) = tool(&mut server, "open_session", json!({"path": saved}));
|
||||
assert!(!failed, "the agent can't reopen what it saved: {text}");
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn agent_folders_lists_every_root_of_a_kind() {
|
||||
let dir = folder("roots");
|
||||
let (a, b) = (dir.join("a"), dir.join("b"));
|
||||
for d in [&a, &b] {
|
||||
std::fs::create_dir_all(d).unwrap();
|
||||
}
|
||||
let roots = soundcraft_engine::file_access::AutomationRoots::new(&[], &[a.as_path(), b.as_path()]).unwrap().unwrap();
|
||||
let answer = agents::folders_answer(Some(&roots));
|
||||
assert_eq!(answer["write_folders"].as_array().map(Vec::len), Some(2), "{answer}");
|
||||
assert!(answer["write_folder"].is_string(), "{answer}");
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_closed_app_set_to_error_says_so() {
|
||||
let dir = folder("error");
|
||||
let mut settings = AgentSettings::default();
|
||||
settings.when_app_closed = WhenAppClosed::Error;
|
||||
agents::write_settings(&dir, &settings).unwrap();
|
||||
let mut server = live(&dir, yes, None);
|
||||
let (failed, text) = tool(&mut server, "inspect_session", json!({}));
|
||||
assert!(failed && text.contains("isn't running"), "{text}");
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
@@ -2,4 +2,6 @@
|
||||
|
||||
mod agent_tasks;
|
||||
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
mod agents;
|
||||
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
mod automation_roots;
|
||||
|
||||
@@ -35,13 +35,15 @@ pub enum Access {
|
||||
}
|
||||
|
||||
/// The folders automation may read and write; a kind with no root grants no access of its kind.
|
||||
#[derive(Debug)]
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct AutomationRoots {
|
||||
read: Vec<Root>,
|
||||
write: Vec<Root>,
|
||||
/// Folders nothing may be written in, even inside a write root ([`AutomationRoots::denying_writes_in`]).
|
||||
no_write: Vec<PathBuf>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
#[derive(Clone, Debug)]
|
||||
struct Root {
|
||||
/// The folder made absolute, links followed: what paths are compared with.
|
||||
resolved: PathBuf,
|
||||
@@ -92,7 +94,33 @@ impl AutomationRoots {
|
||||
}
|
||||
Ok(roots)
|
||||
};
|
||||
Ok(Some(Arc::new(Self { read: open(read, Access::Read)?, write: open(write, Access::Write)? })))
|
||||
Ok(Some(Arc::new(Self { read: open(read, Access::Read)?, write: open(write, Access::Write)?, no_write: Vec::new() })))
|
||||
}
|
||||
|
||||
/// Roots that grant nothing: every read and every write is refused. An agent whose folders
|
||||
/// couldn't be opened gets these, never no roots at all (which would grant everything).
|
||||
pub fn none() -> Arc<Self> {
|
||||
Arc::new(Self { read: Vec::new(), write: Vec::new(), no_write: Vec::new() })
|
||||
}
|
||||
|
||||
/// These roots, with nothing writable inside `dir` (the app's settings folder: the agent
|
||||
/// settings that choose these roots, the agent token), even when a write root holds it. The
|
||||
/// app's own writes there run [`unconfined`].
|
||||
pub fn denying_writes_in(roots: &Arc<Self>, dir: &Path) -> Arc<Self> {
|
||||
let mut next = Self::clone(roots);
|
||||
// A folder that doesn't exist yet is compared as it would be once made.
|
||||
next.no_write.push(resolve(dir).unwrap_or_else(|_| dir.to_path_buf()));
|
||||
Arc::new(next)
|
||||
}
|
||||
|
||||
/// The folders files may be read from, as people read them (absolute, links followed).
|
||||
pub fn read_folders(&self) -> impl Iterator<Item = &Path> {
|
||||
self.read.iter().map(|r| r.shown.as_path())
|
||||
}
|
||||
|
||||
/// The folders files may be written to, as people read them (absolute, links followed).
|
||||
pub fn write_folders(&self) -> impl Iterator<Item = &Path> {
|
||||
self.write.iter().map(|r| r.shown.as_path())
|
||||
}
|
||||
|
||||
/// The roots for people: `read A, B; write C` (`none` for a kind without any).
|
||||
@@ -122,6 +150,9 @@ impl AutomationRoots {
|
||||
};
|
||||
}
|
||||
let resolved = resolve(path)?;
|
||||
if access == Access::Write && self.no_write.iter().any(|dir| inside(&resolved, dir)) {
|
||||
return Err(format!("automation path rejected: inside the app's settings folder, which holds the agent settings: {shown_path}"));
|
||||
}
|
||||
if roots.iter().any(|r| inside(&resolved, &r.resolved)) {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
@@ -42,6 +42,10 @@ zbus = "5"
|
||||
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
|
||||
craft-update = { workspace = true }
|
||||
# Agents in the open window: the ArtCraft Launcher's switch, the link host (control server, token,
|
||||
# connection file) and the Agents page of Preferences.
|
||||
craft-automation = { workspace = true, features = ["agents", "ui"] }
|
||||
craft-control = { workspace = true, features = ["agents"] }
|
||||
|
||||
[dev-dependencies]
|
||||
egui_kittest = { workspace = true, features = ["wgpu", "snapshot"] }
|
||||
|
||||
@@ -790,6 +790,13 @@ fn menu_translate(source: &str) -> Option<&'static str> {
|
||||
"Strip Silence" => "Remover silêncio",
|
||||
"Sync Point" => "Ponto de sincronização",
|
||||
"Synchronization" => "Sincronização",
|
||||
"AI Agents" => "Agentes de IA",
|
||||
"These settings are saved as you change them; Cancel doesn't undo them." => {
|
||||
"Estas configurações são salvas assim que você as altera; Cancelar não as desfaz."
|
||||
}
|
||||
"Browse… isn't available on this page yet: type the folder's path." => {
|
||||
"Procurar… ainda não está disponível nesta página: digite o caminho da pasta."
|
||||
}
|
||||
"System Usage" => "Uso do sistema",
|
||||
"TCE Edit to Timeline Selection" => "Edição TCE para seleção da linha do tempo",
|
||||
"Tab to Transient" => "Tabulação até o transiente",
|
||||
|
||||
@@ -1067,6 +1067,9 @@ pub(super) fn translate(source: &str) -> Option<&'static str> {
|
||||
"Swing %" => "摇摆 %",
|
||||
"Sync Point" => "同步点",
|
||||
"Synchronization" => "同步",
|
||||
"AI Agents" => "AI 代理",
|
||||
"These settings are saved as you change them; Cancel doesn't undo them." => "这些设置在更改时即被保存;“取消”不会撤销它们。",
|
||||
"Browse… isn't available on this page yet: type the folder's path." => "此页面暂不支持“浏览…”:请输入文件夹路径。",
|
||||
"System" => "跟随系统",
|
||||
"System Usage" => "系统使用情况",
|
||||
"TCE Edit to Timeline Selection" => "TCE 编辑到时间线选区",
|
||||
|
||||
@@ -0,0 +1,342 @@
|
||||
//! Agents in the open window: the ArtCraft Launcher's switch lets agents into this window.
|
||||
//!
|
||||
//! The switch, the control server, its token and the connection file `soundcraft-cli mcp` finds
|
||||
//! the window by are the framework's (`craft_automation::agents::AgentSwitch` and `AgentLink`).
|
||||
//! SoundCraft supplies its agent settings (saved by the desktop app, [`SETTINGS_COMMAND`]), runs
|
||||
//! the requests that arrive through its own control methods ([`crate::control`]), and keeps them
|
||||
//! inside the agent folders: the folders set on the AI Agents page of Preferences, or
|
||||
//! `Documents/ArtCraft/Agents/SoundCraft` for an empty one ([`AgentScope`], made by the desktop
|
||||
//! app with the same folder checks a headless agent session runs under).
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
|
||||
use craft_automation::agents::{AgentLink, AgentLinkStatus, AgentSettings, AgentSwitch, LinkProblem};
|
||||
use craft_automation::control::ControlChannel;
|
||||
use craft_control::agents::AgentFolders;
|
||||
use craft_ui::runtime::windows::WindowHost;
|
||||
use serde_json::{Value, json};
|
||||
use soundcraft_engine::file_access::RootError;
|
||||
|
||||
use crate::control::{AgentScope, ControlRequest};
|
||||
|
||||
/// The UI command the AI Agents page runs to change the agent settings.
|
||||
pub const SETTINGS_COMMAND: &str = "ui.agent_settings";
|
||||
|
||||
/// Saves the agent settings where `soundcraft-cli mcp` reads them; `Err` says why it couldn't.
|
||||
pub type SaveFn = Box<dyn Fn(&AgentSettings) -> Result<(), String>>;
|
||||
/// The scope agent requests run in for these folders; `Err` when they can't be used.
|
||||
pub type ScopeFn = Box<dyn Fn(&AgentFolders) -> Result<AgentScope, RootError>>;
|
||||
|
||||
/// The agents link of the open window.
|
||||
pub struct Agents {
|
||||
/// The link; `None` while the launch options (`--control`) manage the control channel.
|
||||
link: Option<AgentLink>,
|
||||
/// The status shown while the launch options manage the control channel.
|
||||
launch: AgentLinkStatus,
|
||||
switch: AgentSwitch,
|
||||
settings: AgentSettings,
|
||||
save: SaveFn,
|
||||
scope_for: ScopeFn,
|
||||
channel: Option<ControlChannel>,
|
||||
/// What agent requests may do now; `None` until the link runs.
|
||||
scope: Option<Arc<AgentScope>>,
|
||||
default_folder: Option<PathBuf>,
|
||||
}
|
||||
|
||||
impl Agents {
|
||||
/// The link for the window, keeping its token and connection file in `settings_dir`, naming
|
||||
/// `app` (the version string) in the connection file, following `switch` with the saved
|
||||
/// `settings`; `save` stores the settings when the AI Agents page changes them, `scope_for`
|
||||
/// makes what agent requests may do with the agent folders.
|
||||
pub fn new(settings_dir: Option<PathBuf>, app: String, switch: AgentSwitch, settings: AgentSettings, save: SaveFn, scope_for: ScopeFn) -> Self {
|
||||
Self {
|
||||
link: Some(AgentLink::new(settings_dir, app)),
|
||||
launch: AgentLinkStatus::default(),
|
||||
switch,
|
||||
settings,
|
||||
save,
|
||||
scope_for,
|
||||
channel: None,
|
||||
scope: None,
|
||||
default_folder: craft_control::agents::default_folder("SoundCraft"),
|
||||
}
|
||||
}
|
||||
|
||||
/// The window was started with `--control port`: that channel stays as it is for the whole run
|
||||
/// and the AI Agents page says the launch options manage it.
|
||||
pub fn launched_with_control(mut self, port: u16) -> Self {
|
||||
self.link = None;
|
||||
self.launch.port = Some(port);
|
||||
self.launch.launch_flags = true;
|
||||
self
|
||||
}
|
||||
|
||||
/// `default` replaces the default agent folder (tests).
|
||||
pub fn with_default_folder(mut self, default: Option<PathBuf>) -> Self {
|
||||
self.default_folder = default;
|
||||
self
|
||||
}
|
||||
|
||||
/// The saved agent settings.
|
||||
pub fn settings(&self) -> &AgentSettings {
|
||||
&self.settings
|
||||
}
|
||||
|
||||
/// Where the link stands, for the AI Agents page and `ui.agent_settings`.
|
||||
pub fn status(&self) -> &AgentLinkStatus {
|
||||
self.link.as_ref().map_or(&self.launch, AgentLink::status)
|
||||
}
|
||||
|
||||
/// The suite's `AI-MCP` flag: the launcher's switch decides, and Preferences shows the page.
|
||||
pub fn mcp_flag(&self) -> bool {
|
||||
self.switch.mcp_flag()
|
||||
}
|
||||
|
||||
/// Whether the launcher's switch lets agents use SoundCraft now.
|
||||
pub fn allowed(&self) -> bool {
|
||||
// SoundCraft had no agent consent of its own before the switch.
|
||||
self.switch.allows(false)
|
||||
}
|
||||
|
||||
/// Saves `settings` and applies them on the next [`Self::sync`].
|
||||
pub fn set(&mut self, settings: AgentSettings) -> Result<(), String> {
|
||||
(self.save)(&settings)?;
|
||||
self.settings = settings;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Brings the link in line with the switch and the settings: the control server starts, moves
|
||||
/// or stops, and the agent folders are opened again when they changed.
|
||||
pub fn sync(&mut self, host: &WindowHost) {
|
||||
let allowed = self.allowed();
|
||||
let Some(link) = self.link.as_mut() else { return };
|
||||
let update = link.sync(allowed.then_some(&self.settings), host);
|
||||
if update.stopped {
|
||||
self.channel = None;
|
||||
}
|
||||
if let Some(requests) = update.requests {
|
||||
self.channel = Some(ControlChannel::new(requests));
|
||||
}
|
||||
if !update.changed {
|
||||
return;
|
||||
}
|
||||
if link.status().port.is_none() {
|
||||
self.scope = None;
|
||||
return;
|
||||
}
|
||||
let folders = self.settings.folders_with(self.default_folder.as_deref());
|
||||
let scope = (self.scope_for)(&folders).or_else(|e| {
|
||||
link.note(LinkProblem::App(format!("Agents can't open or save files: {e}")));
|
||||
(self.scope_for)(&AgentFolders::default())
|
||||
});
|
||||
// Without a scope nothing an agent sends may run: the link stops taking requests.
|
||||
self.scope = scope.ok().map(Arc::new);
|
||||
if self.scope.is_none() {
|
||||
self.channel = None;
|
||||
}
|
||||
}
|
||||
|
||||
/// The next agent request to run, with what it may do. Requests whose client stopped waiting
|
||||
/// are answered and skipped.
|
||||
pub fn next_request(&mut self) -> Option<ControlRequest> {
|
||||
let scope = self.scope.clone()?;
|
||||
let request = self.channel.as_mut()?.next_request()?;
|
||||
Some(ControlRequest::for_agent(request.method, request.params, request.reply, scope))
|
||||
}
|
||||
|
||||
/// `ui.agent_settings`: without params, the settings and where the link stands; with params,
|
||||
/// saves those settings (`controlPort`, `readRoot`, `writeRoot`, `whenAppClosed`).
|
||||
pub fn command(&mut self, params: &Value) -> Result<Value, String> {
|
||||
let given = params.as_object().filter(|p| !p.is_empty());
|
||||
if let Some(given) = given {
|
||||
let mut next = serde_json::to_value(&self.settings).map_err(|e| e.to_string())?;
|
||||
for (key, value) in given {
|
||||
if !matches!(key.as_str(), "controlPort" | "readRoot" | "writeRoot" | "whenAppClosed") {
|
||||
return Err(format!("`{SETTINGS_COMMAND}`: unknown setting `{key}` (controlPort, readRoot, writeRoot, whenAppClosed)"));
|
||||
}
|
||||
next[key] = value.clone();
|
||||
}
|
||||
let next: AgentSettings = serde_json::from_value(next).map_err(|e| format!("`{SETTINGS_COMMAND}`: {e}"))?;
|
||||
self.set(next)?;
|
||||
}
|
||||
Ok(json!({"settings": self.settings, "status": self.status(), "allowed": self.allowed(), "mcpFlag": self.mcp_flag()}))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use craft_control::agents::CONNECTION_FILE;
|
||||
use soundcraft_engine::file_access::AutomationRoots;
|
||||
use std::path::Path;
|
||||
|
||||
/// A fresh, empty folder for one test.
|
||||
fn folder(tag: &str) -> PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!("sc-agents-{tag}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
dir
|
||||
}
|
||||
|
||||
fn context() -> egui::Context {
|
||||
let ctx = egui::Context::default();
|
||||
crate::framework::install_headless(&ctx);
|
||||
ctx
|
||||
}
|
||||
|
||||
fn no_folders(_: &AgentFolders) -> Result<AgentScope, RootError> {
|
||||
Ok(AgentScope { roots: AutomationRoots::none(), folders: json!({}) })
|
||||
}
|
||||
|
||||
fn agents(dir: &Path, switch: AgentSwitch, scope_for: ScopeFn) -> Agents {
|
||||
let mut settings = AgentSettings::default();
|
||||
settings.control_port = 0;
|
||||
Agents::new(Some(dir.to_path_buf()), "SoundCraft test".into(), switch, settings, Box::new(|_| Ok(())), scope_for)
|
||||
.with_default_folder(Some(dir.join("Agents")))
|
||||
}
|
||||
|
||||
fn app() -> crate::SoundApp {
|
||||
crate::SoundApp::new(soundcraft_engine::Engine::default(), None, crate::Services::default())
|
||||
}
|
||||
|
||||
/// One logic tick, as the host runs it.
|
||||
fn tick(app: &mut crate::SoundApp, ctx: &egui::Context) {
|
||||
let raw = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))), ..Default::default() };
|
||||
let _ = ctx.run_logic(&raw, |ctx| app.logic(ctx));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_window_serves_agents_only_while_the_launcher_switch_names_it() {
|
||||
let ctx = context();
|
||||
let host = WindowHost::of(&ctx);
|
||||
let dir = folder("switch");
|
||||
let mut off = agents(&dir, AgentSwitch::fixed(true, false), Box::new(no_folders));
|
||||
off.sync(&host);
|
||||
assert!(off.status().port.is_none() && !dir.join(CONNECTION_FILE).exists(), "listening with the switch off");
|
||||
assert!(off.next_request().is_none());
|
||||
let mut on = agents(&dir, AgentSwitch::fixed(true, true), Box::new(no_folders));
|
||||
on.sync(&host);
|
||||
assert!(on.status().port.is_some(), "{:?}", on.status());
|
||||
assert!(dir.join(CONNECTION_FILE).exists(), "the CLI finds the window through the connection file");
|
||||
drop(on);
|
||||
assert!(!dir.join(CONNECTION_FILE).exists(), "a closed window leaves no connection file");
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
type Conn = (std::io::BufReader<std::net::TcpStream>, std::net::TcpStream);
|
||||
|
||||
/// One line out, one line back.
|
||||
fn round_trip(conn: &mut Conn, request: Value) -> Value {
|
||||
use std::io::{BufRead, Write};
|
||||
writeln!(conn.1, "{request}").unwrap();
|
||||
let mut line = String::new();
|
||||
conn.0.read_line(&mut line).unwrap();
|
||||
serde_json::from_str(&line).unwrap_or(Value::Null)
|
||||
}
|
||||
|
||||
/// A connection to the window's agents channel, signed in through the challenge handshake
|
||||
/// with `token`; `Err` with the refusal when the window doesn't accept the proof.
|
||||
fn signed_in(port: u16, token: &str) -> Result<Conn, Value> {
|
||||
use craft_automation::security::{self, ProofRole};
|
||||
let stream = std::net::TcpStream::connect(("127.0.0.1", port)).unwrap();
|
||||
stream.set_read_timeout(Some(std::time::Duration::from_secs(20))).unwrap();
|
||||
let mut conn = (std::io::BufReader::new(stream.try_clone().unwrap()), stream);
|
||||
let client_nonce = security::generate_nonce().unwrap();
|
||||
let challenge = round_trip(&mut conn, json!({"id": 0, "method": security::CHALLENGE_METHOD, "params": {"clientNonce": client_nonce}}));
|
||||
let server_nonce = challenge["result"]["serverNonce"].as_str().unwrap().to_string();
|
||||
let proof = security::handshake_proof(token, ProofRole::Client, &client_nonce, &server_nonce).unwrap();
|
||||
let auth = round_trip(&mut conn, json!({"id": 0, "method": security::AUTH_METHOD, "params": {"proof": proof}}));
|
||||
if auth["ok"] == true { Ok(conn) } else { Err(auth) }
|
||||
}
|
||||
|
||||
fn is_empty(dir: &Path) -> bool {
|
||||
std::fs::read_dir(dir).unwrap().next().is_none()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_agent_reaches_the_window_only_with_its_token_and_only_inside_its_folders() {
|
||||
let ctx = context();
|
||||
let dir = folder("token");
|
||||
let (inside, outside) = (dir.join("Agents"), dir.join("elsewhere"));
|
||||
std::fs::create_dir_all(&inside).unwrap();
|
||||
std::fs::create_dir_all(&outside).unwrap();
|
||||
let scope_for: ScopeFn = Box::new(|folders: &AgentFolders| {
|
||||
let write: Vec<&Path> = folders.write.iter().map(PathBuf::as_path).collect();
|
||||
let roots = AutomationRoots::new(&write, &write)?.unwrap_or_else(AutomationRoots::none);
|
||||
Ok(AgentScope { roots, folders: json!({"write_folder": folders.write}) })
|
||||
});
|
||||
let mut app = app().with_agents(agents(&dir, AgentSwitch::fixed(true, true), scope_for));
|
||||
tick(&mut app, &ctx);
|
||||
let connection = craft_control::agents::read_connection(&dir).unwrap().expect("the window publishes where agents connect");
|
||||
let token = std::fs::read_to_string(dir.join(craft_control::agents::TOKEN_FILE)).unwrap().trim().to_string();
|
||||
|
||||
let (save_in, save_out) = (inside.join("a.scraft"), outside.join("a.scraft"));
|
||||
let shot_out = outside.join("shot.png").to_string_lossy().into_owned();
|
||||
let (save_in_c, save_out_c) = (save_in.clone(), save_out.clone());
|
||||
let client = std::thread::spawn(move || {
|
||||
let port = connection.port;
|
||||
let stranger = signed_in(port, &craft_automation::security::generate_token().unwrap()).expect_err("a wrong token was accepted");
|
||||
let mut conn = signed_in(port, &token).expect("the window's own token was refused");
|
||||
let mut call = |method: &str, params: Value| round_trip(&mut conn, json!({"id": 1, "method": method, "params": params}));
|
||||
let save = |path: &PathBuf| json!({"command": "session.save", "params": {"path": path}});
|
||||
(
|
||||
stranger,
|
||||
call("engine.execute", save(&save_out_c)),
|
||||
call("engine.execute", save(&save_in_c)),
|
||||
call("ui.screenshot", json!({"path": shot_out})),
|
||||
call("agent.folders", json!({})),
|
||||
call("engine.execute", json!({"command": SETTINGS_COMMAND, "params": {"writeRoot": "/"}})),
|
||||
)
|
||||
});
|
||||
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30);
|
||||
while !client.is_finished() && std::time::Instant::now() < deadline {
|
||||
tick(&mut app, &ctx);
|
||||
std::thread::sleep(std::time::Duration::from_millis(5));
|
||||
}
|
||||
let (stranger, outside_save, inside_save, shot, folders, settings) = client.join().unwrap();
|
||||
assert_eq!(stranger["ok"], false, "{stranger}");
|
||||
assert_eq!(outside_save["ok"], false, "saved outside the agent folder: {outside_save}");
|
||||
assert!(outside_save["error"].as_str().unwrap_or_default().contains("outside the write root"), "{outside_save}");
|
||||
assert_eq!(inside_save["ok"], true, "{inside_save}");
|
||||
assert!(!is_empty(&inside) && is_empty(&outside), "the save landed outside the agent folder");
|
||||
assert_eq!(shot["ok"], false, "a screenshot was let out of the agent folder: {shot}");
|
||||
assert!(folders["result"]["write_folder"].as_str().is_some_and(|f| f.ends_with("Agents")), "{folders}");
|
||||
assert_eq!(settings["ok"], false, "an agent changed its own folders: {settings}");
|
||||
// The person's own runs are not confined.
|
||||
assert!(app.run("session.save", json!({"path": save_out})).is_ok());
|
||||
let _ = save_in;
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_the_person_changes_the_agent_settings() {
|
||||
let dir = folder("person");
|
||||
let mut app = app().with_agents(agents(&dir, AgentSwitch::fixed(true, true), Box::new(no_folders)));
|
||||
let change = json!({"writeRoot": dir});
|
||||
// Under an agent's folders (its request, or a click it queued on Preferences) the change is refused.
|
||||
let none = AutomationRoots::none();
|
||||
assert!(soundcraft_engine::file_access::confine(Some(&none), || app.run(SETTINGS_COMMAND, change.clone())).is_err());
|
||||
assert!(app.agents().unwrap().settings().write_root.is_empty());
|
||||
app.run(SETTINGS_COMMAND, change).unwrap();
|
||||
assert!(!app.agents().unwrap().settings().write_root.is_empty(), "the person's change was not saved");
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn input_an_agent_queues_stays_in_its_folders_until_it_is_applied() {
|
||||
let ctx = context();
|
||||
let mut app = app();
|
||||
let scope = Arc::new(AgentScope { roots: AutomationRoots::none(), folders: json!({}) });
|
||||
let (tx, _rx) = std::sync::mpsc::channel();
|
||||
let text = ControlRequest::for_agent("ui.text".into(), json!({"text": "a"}), tx, scope);
|
||||
crate::control::run_request(&mut app, &ctx, &text);
|
||||
assert!(app.agent_input_roots.is_some(), "the agent's typing would run outside its folders");
|
||||
app.release_agent_input();
|
||||
assert!(app.agent_input_roots.is_some(), "released before the input was applied");
|
||||
app.synthetic.clear();
|
||||
app.gesture_acks.clear();
|
||||
app.release_agent_input();
|
||||
assert!(app.agent_input_roots.is_none(), "the person's input stays confined after the agent's was applied");
|
||||
}
|
||||
}
|
||||
@@ -96,6 +96,9 @@ impl SoundApp {
|
||||
sample_reads: Vec::new(),
|
||||
synthetic_grace: 0,
|
||||
control_rx: None,
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
agents: None,
|
||||
agent_input_roots: None,
|
||||
gesture_acks: VecDeque::new(),
|
||||
pending_shots: Vec::new(),
|
||||
doc_epoch: 0,
|
||||
@@ -145,6 +148,32 @@ impl SoundApp {
|
||||
self
|
||||
}
|
||||
|
||||
/// Lets agents into this window while the ArtCraft Launcher's switch names SoundCraft.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub fn with_agents(mut self, agents: crate::agents::Agents) -> Self {
|
||||
self.agents = Some(agents);
|
||||
self
|
||||
}
|
||||
|
||||
/// The agents link, for the AI Agents page of Preferences.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub fn agents(&self) -> Option<&crate::agents::Agents> {
|
||||
self.agents.as_ref()
|
||||
}
|
||||
|
||||
/// The agents link, for `ui.agent_settings`.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) fn agents_mut(&mut self) -> Option<&mut crate::agents::Agents> {
|
||||
self.agents.as_mut()
|
||||
}
|
||||
|
||||
/// Agent input has all been applied: what runs next is the person's again.
|
||||
pub(crate) fn release_agent_input(&mut self) {
|
||||
if self.agent_input_roots.is_some() && !crate::control::gesture_pending(self) {
|
||||
self.agent_input_roots = None;
|
||||
}
|
||||
}
|
||||
|
||||
/// Per-frame logic: control channel, transport, document sync.
|
||||
///
|
||||
/// eframe calls this once per layout pass and also on logic-only ticks while hidden. Consumed
|
||||
@@ -261,8 +290,15 @@ impl SoundApp {
|
||||
(elapsed as f32).clamp(0.0, 0.25)
|
||||
}
|
||||
|
||||
/// Lay out the whole window.
|
||||
/// Lay out the whole window. While an agent's queued input is applied, the commands it runs
|
||||
/// (shortcuts, clicks on menus and dialogs) stay inside the agent's folders.
|
||||
pub fn ui(&mut self, ui: &mut egui::Ui) {
|
||||
let roots = self.agent_input_roots.clone();
|
||||
soundcraft_engine::file_access::confine(roots.as_ref(), || self.ui_pass(ui));
|
||||
self.release_agent_input();
|
||||
}
|
||||
|
||||
fn ui_pass(&mut self, ui: &mut egui::Ui) {
|
||||
let _language = crate::localization::enter(self.ui.language);
|
||||
let ctx = ui.ctx().clone();
|
||||
// egui just processed the scripted key events. A scripted release while the host still
|
||||
|
||||
+114
-15
@@ -11,6 +11,12 @@
|
||||
//! - `ui.key {key, cmd?, shift?, alt?, ctrl?}`, `ui.text {text}`
|
||||
//! - `ui.screenshot {path?}` (PNG; base64 when no path), `ui.set {...UiState fields}`
|
||||
//! - `app.quit`
|
||||
//! - `agent.folders`: the folders an agent's requests may open and save files in (`crate::agents`)
|
||||
//!
|
||||
//! An agent's request (through the ArtCraft Launcher's switch, `crate::agents`) runs inside its
|
||||
//! agent folders: every file its commands read or write goes through the engine's folder checks
|
||||
//! (`soundcraft_engine::file_access`), and so does what the input it queues runs until a UI pass
|
||||
//! has applied it. A screenshot path is checked before the capture, which writes it later.
|
||||
//!
|
||||
//! Scripted-input methods reply only after a UI pass applied their events, and later requests wait
|
||||
//! behind that gesture. The connection's one-request-at-a-time reply order therefore also orders an
|
||||
@@ -20,6 +26,8 @@ use crate::SoundApp;
|
||||
use crate::capture::CaptureSlot;
|
||||
use craft_ui::runtime::windows::WindowHost;
|
||||
use serde_json::{Value, json};
|
||||
use soundcraft_engine::file_access::{self, AutomationRoots};
|
||||
use std::sync::Arc;
|
||||
use std::sync::mpsc::{Receiver, Sender, channel};
|
||||
use web_time::Instant;
|
||||
|
||||
@@ -27,13 +35,64 @@ pub struct ControlRequest {
|
||||
pub method: String,
|
||||
pub params: Value,
|
||||
pub reply: Sender<Value>,
|
||||
/// An agent's request through the ArtCraft Launcher's switch (`crate::agents`): what it may
|
||||
/// do. `None` for the person's own channel (`--control`).
|
||||
pub agent: Option<Arc<AgentScope>>,
|
||||
}
|
||||
|
||||
/// What an agent's requests may do in the open window: the files they, and the input they queue
|
||||
/// while it is applied, read and write stay inside `roots` (the agent folders, checked as a
|
||||
/// headless agent session checks them).
|
||||
pub struct AgentScope {
|
||||
pub roots: Arc<AutomationRoots>,
|
||||
/// The `agent_folders` answer: the folders the requests may use.
|
||||
pub folders: Value,
|
||||
}
|
||||
|
||||
/// The control method `soundcraft-cli mcp`'s `agent_folders` tool calls.
|
||||
pub const AGENT_FOLDERS_METHOD: &str = "agent.folders";
|
||||
|
||||
/// The UI commands an agent's request may not run: the agent settings choose the agent folders.
|
||||
const NOT_FOR_AGENTS: &[&str] = &["ui.agent_settings"];
|
||||
|
||||
impl ControlRequest {
|
||||
pub fn new(method: impl Into<String>, params: Value) -> (Self, Receiver<Value>) {
|
||||
let (tx, rx) = channel();
|
||||
(ControlRequest { method: method.into(), params, reply: tx }, rx)
|
||||
(ControlRequest { method: method.into(), params, reply: tx, agent: None }, rx)
|
||||
}
|
||||
|
||||
/// An agent's request answered on `reply`, which may do what `scope` allows.
|
||||
pub fn for_agent(method: String, params: Value, reply: Sender<Value>, scope: Arc<AgentScope>) -> Self {
|
||||
ControlRequest { method, params, reply, agent: Some(scope) }
|
||||
}
|
||||
}
|
||||
|
||||
/// The `agent_folders` answer on the person's own channel (`--control`), which isn't confined.
|
||||
fn unrestricted_folders() -> Value {
|
||||
json!({
|
||||
"read_folder": null,
|
||||
"write_folder": null,
|
||||
"unrestricted": true,
|
||||
"note": "This channel was opened with --control: its file commands open and save wherever the user can.",
|
||||
})
|
||||
}
|
||||
|
||||
/// An agent's request that names a file to write or a command it may not run: `Err` says why.
|
||||
/// `ui.screenshot` writes its file after the frame, outside the request, so its path is checked
|
||||
/// here; the other methods' files go through the engine's checks while the request runs.
|
||||
fn agent_refuses(method: &str, p: &Value, scope: &AgentScope) -> Result<(), String> {
|
||||
let command = p.get("command").or_else(|| p.get("id")).and_then(Value::as_str);
|
||||
if matches!(method, "engine.execute" | "command" | "ui.menu.invoke")
|
||||
&& let Some(id) = command.filter(|id| NOT_FOR_AGENTS.contains(id))
|
||||
{
|
||||
return Err(format!("`{id}` changes what agents may do; only the person can change it, in Preferences › AI Agents"));
|
||||
}
|
||||
if method == "ui.screenshot"
|
||||
&& let Some(path) = p.get("path").and_then(Value::as_str)
|
||||
{
|
||||
scope.roots.check(path, file_access::Access::Write)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// One admitted `ui.screenshot` request. The app owns the strong completion slot; the callback the
|
||||
@@ -393,7 +452,12 @@ fn err(e: impl std::fmt::Display) -> Value {
|
||||
/// Run at most 65 queued control requests on the UI thread, stopping while a scripted gesture is undelivered so later
|
||||
/// requests observe its result. A panicking handler still gets one error reply.
|
||||
pub fn drain(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
let Some(rx) = app.control_rx.take() else { return };
|
||||
// The launcher's switch and the agent settings: the agents channel starts, moves or stops.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if let Some(agents) = app.agents.as_mut() {
|
||||
agents.sync(&WindowHost::of(ctx));
|
||||
}
|
||||
let rx = app.control_rx.take();
|
||||
let mut n = 0;
|
||||
loop {
|
||||
// Do not let a request behind an undelivered gesture observe or mutate the state the
|
||||
@@ -401,29 +465,56 @@ pub fn drain(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
if gesture_pending(app) {
|
||||
break;
|
||||
}
|
||||
let Ok(req) = rx.try_recv() else { break };
|
||||
let req = match rx.as_ref().and_then(|rx| rx.try_recv().ok()) {
|
||||
Some(req) => req,
|
||||
None => match next_agent_request(app) {
|
||||
Some(req) => req,
|
||||
None => break,
|
||||
},
|
||||
};
|
||||
n += 1;
|
||||
// A handler that panics must not take the receiver with it: the UI pass catches the panic
|
||||
// one level up, and a dead control channel afterwards would be a second failure.
|
||||
match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| handle(app, ctx, &req))) {
|
||||
Ok(Some(v)) => {
|
||||
let _ = req.reply.send(v);
|
||||
}
|
||||
Ok(None) => {}
|
||||
Err(_) => {
|
||||
let _ = req.reply.send(err("control request failed"));
|
||||
}
|
||||
}
|
||||
run_request(app, ctx, &req);
|
||||
if n > 64 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
app.control_rx = Some(rx);
|
||||
app.control_rx = rx;
|
||||
if n > 0 {
|
||||
ctx.request_repaint();
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn next_agent_request(app: &mut SoundApp) -> Option<ControlRequest> {
|
||||
app.agents.as_mut()?.next_request()
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn next_agent_request(_: &mut SoundApp) -> Option<ControlRequest> {
|
||||
None
|
||||
}
|
||||
|
||||
/// Run one request and send its reply, unless it replies later. An agent's request runs inside its
|
||||
/// agent folders, and input it queues keeps them until a UI pass has applied it.
|
||||
pub(crate) fn run_request(app: &mut SoundApp, ctx: &egui::Context, req: &ControlRequest) {
|
||||
let roots = req.agent.as_ref().map(|scope| scope.roots.clone());
|
||||
// A handler that panics must not take the receiver with it: the UI pass catches the panic
|
||||
// one level up, and a dead control channel afterwards would be a second failure.
|
||||
let outcome = file_access::confine(roots.as_ref(), || std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| handle(app, ctx, req))));
|
||||
if roots.is_some() && gesture_pending(app) {
|
||||
app.agent_input_roots = roots;
|
||||
}
|
||||
match outcome {
|
||||
Ok(Some(v)) => {
|
||||
let _ = req.reply.send(v);
|
||||
}
|
||||
Ok(None) => {}
|
||||
Err(_) => {
|
||||
let _ = req.reply.send(err("control request failed"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn key_from(name: &str) -> Option<egui::Key> {
|
||||
egui::Key::from_name(name).or(match name.to_ascii_lowercase().as_str() {
|
||||
"space" => Some(egui::Key::Space),
|
||||
@@ -470,6 +561,14 @@ fn command_list(app: &mut SoundApp, p: &Value) -> Value {
|
||||
/// Dispatch one control method to commands, inspection, menus or queued scripted input. Methods that need a UI pass
|
||||
/// return `None` and reply later; everything else returns the reply for [`drain`] to send.
|
||||
fn handle(app: &mut SoundApp, ctx: &egui::Context, req: &ControlRequest) -> Option<Value> {
|
||||
if req.method == AGENT_FOLDERS_METHOD {
|
||||
return Some(ok(req.agent.as_ref().map_or_else(unrestricted_folders, |scope| scope.folders.clone())));
|
||||
}
|
||||
if let Some(scope) = &req.agent
|
||||
&& let Err(e) = agent_refuses(&req.method, &req.params, scope)
|
||||
{
|
||||
return Some(err(e));
|
||||
}
|
||||
let p = &req.params;
|
||||
let f = |k: &str| p.get(k).and_then(Value::as_f64).unwrap_or(0.0) as f32;
|
||||
let pos = egui::pos2(f("x"), f("y"));
|
||||
|
||||
@@ -1426,3 +1426,6 @@ automation trim 微调
|
||||
The device did not take {} samples; it runs at its default buffer. 设备未接受 {} 个采样;它以默认缓冲区运行。
|
||||
The device runs at {} samples, not {}. 设备以 {} 个采样运行,而不是 {}。
|
||||
The device runs only at {} samples. 设备只能以 {} 个采样运行。
|
||||
AI Agents AI 代理
|
||||
These settings are saved as you change them; Cancel doesn't undo them. 这些设置在更改时即被保存;“取消”不会撤销它们。
|
||||
Browse… isn't available on this page yet: type the folder's path. 此页面暂不支持“浏览…”:请输入文件夹路径。
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 799 and column 11.
|
@@ -14,6 +14,8 @@ pub const UPDATE_APP: craft_update::app::App = craft_update::app::App {
|
||||
};
|
||||
|
||||
pub mod aaf_import;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub mod agents;
|
||||
pub mod appearance;
|
||||
pub mod bounce;
|
||||
pub mod channel_titles;
|
||||
@@ -434,6 +436,12 @@ pub struct SoundApp {
|
||||
sample_reads: Vec<sampler_window::SampleRead>,
|
||||
synthetic_grace: u32,
|
||||
control_rx: Option<Receiver<ControlRequest>>,
|
||||
/// Agents in the open window through the ArtCraft Launcher's switch ([`agents::Agents`]).
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
agents: Option<agents::Agents>,
|
||||
/// The folders of the agent whose queued input is still being applied: what that input runs is
|
||||
/// the agent's, and stays inside them ([`SoundApp::ui`]).
|
||||
agent_input_roots: Option<std::sync::Arc<soundcraft_engine::file_access::AutomationRoots>>,
|
||||
/// Gestures whose reply waits for their events to be applied by a UI pass, in request order.
|
||||
gesture_acks: VecDeque<control::GestureAck>,
|
||||
pending_shots: Vec<control::PendingShot>,
|
||||
|
||||
@@ -83,6 +83,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, Option<&str>)] = &[
|
||||
("ui.reduce_visual_effects", "Reduce Visual Effects", "", None),
|
||||
("ui.undo_levels", "Levels of Undo", "", None),
|
||||
("ui.sends_default", "Sends Default to", "", None),
|
||||
("ui.agent_settings", "Agent Settings", "", None),
|
||||
];
|
||||
|
||||
/// Extra catalog mappings handled by the UI layer.
|
||||
@@ -533,6 +534,27 @@ fn params_for(path: &str, id: &str) -> Value {
|
||||
}
|
||||
}
|
||||
|
||||
/// `ui.agent_settings`: the agent settings of Preferences › AI Agents
|
||||
/// (`{controlPort?, readRoot?, writeRoot?, whenAppClosed?: launch|headless|error}`); without params,
|
||||
/// the settings and where the agents link stands.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn agent_settings(app: &mut SoundApp, p: &Value) -> Result<Value, String> {
|
||||
// Agent folders in force: an agent's request, or input it queued (clicks through Preferences).
|
||||
// The agent settings choose those folders, so only the person changes them.
|
||||
if p.as_object().is_some_and(|p| !p.is_empty()) && soundcraft_engine::file_access::current().is_some() {
|
||||
return Err("the agent settings choose the folders agents may use; only the person can change them, in Preferences › AI Agents".into());
|
||||
}
|
||||
match app.agents_mut() {
|
||||
Some(agents) => agents.command(p),
|
||||
None => Err("this window doesn't take agents: the ArtCraft Launcher lets agents into a Stable SoundCraft window".into()),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn agent_settings(_: &mut SoundApp, _: &Value) -> Result<Value, String> {
|
||||
Err("agents work in the desktop app, not in the browser".into())
|
||||
}
|
||||
|
||||
/// Menu items that open a SoundCraft window when clicked (programmatic calls still run the command).
|
||||
const MENU_WINDOWS: &[(&str, &str)] = &[
|
||||
("Setup > Appearance", "window.ui_customization"),
|
||||
@@ -625,6 +647,9 @@ fn wants_dialog(id: &str) -> bool {
|
||||
|
||||
/// Handle UI-layer commands. Returns None when `id` is not a UI command.
|
||||
pub fn run_ui_command(app: &mut SoundApp, id: &str, p: &Value) -> Option<Result<Value, String>> {
|
||||
if id == "ui.agent_settings" {
|
||||
return Some(agent_settings(app, p));
|
||||
}
|
||||
if id == "window.import_aaf" {
|
||||
return Some(crate::aaf_import::command(app, p));
|
||||
}
|
||||
|
||||
@@ -27,6 +27,10 @@ pub enum PreferencesPage {
|
||||
Midi,
|
||||
Collaboration,
|
||||
Synchronization,
|
||||
/// AI Agents: the shared Agents page of the Craft apps, listed after the reference pages while
|
||||
/// this window takes agents and the suite's `AI-MCP` flag is on (the ArtCraft Launcher's switch
|
||||
/// decides; the page has no switch of its own). Not in [`Self::ALL`]: it has no page shortcut.
|
||||
Agents,
|
||||
}
|
||||
|
||||
/// Controls when optional interface animation and decoration are reduced.
|
||||
@@ -144,6 +148,7 @@ impl PreferencesPage {
|
||||
Self::Midi => "MIDI",
|
||||
Self::Collaboration => "Collaboration",
|
||||
Self::Synchronization => "Synchronization",
|
||||
Self::Agents => "AI Agents",
|
||||
}
|
||||
}
|
||||
|
||||
@@ -159,6 +164,8 @@ impl PreferencesPage {
|
||||
Self::Midi => MIDI,
|
||||
Self::Collaboration => COLLABORATION,
|
||||
Self::Synchronization => SYNCHRONIZATION,
|
||||
// Drawn whole by the shared Agents page (`agents_page`).
|
||||
Self::Agents => &[],
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -777,7 +784,12 @@ pub fn show(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
draft.sync_unedited_from_live(app);
|
||||
let draft_before_ui = draft;
|
||||
let mut search = std::mem::take(&mut app.preferences.search);
|
||||
let agents_shown = agents_page_shown(app);
|
||||
let mut page = app.ui.preferences_page;
|
||||
// A saved AI Agents page while the window doesn't list it shows the first page.
|
||||
if page == PreferencesPage::Agents && !agents_shown {
|
||||
page = PreferencesPage::Display;
|
||||
}
|
||||
let mut action = None;
|
||||
select_page_from_keyboard(ctx, &mut page);
|
||||
// A single-line text edit releases focus on Enter in the frame that receives the key. Capture
|
||||
@@ -822,14 +834,22 @@ pub fn show(app: &mut SoundApp, ctx: &egui::Context) {
|
||||
}
|
||||
});
|
||||
ui.add_space(4.0);
|
||||
tabs(ui, &mut page, &search);
|
||||
tabs(ui, &mut page, &search, agents_shown);
|
||||
ui.separator();
|
||||
|
||||
// Reserve the same body height on every page. Only screens shorter than the normal window
|
||||
// get an emergency scroll area, keeping the footer reachable without changing tall-screen
|
||||
// layout or making the window resizable.
|
||||
let body_top = ui.cursor().top();
|
||||
if window_height < PREFERENCES_WINDOW_HEIGHT {
|
||||
if page == PreferencesPage::Agents {
|
||||
// The shared page has no scroller of its own: keep the footer reachable on short screens.
|
||||
egui::ScrollArea::vertical()
|
||||
.id_salt("preferences_agents_body")
|
||||
.max_height(body_height)
|
||||
.min_scrolled_height(body_height)
|
||||
.auto_shrink([false, false])
|
||||
.show(ui, |ui| agents_page(app, ui));
|
||||
} else if window_height < PREFERENCES_WINDOW_HEIGHT {
|
||||
egui::ScrollArea::vertical()
|
||||
.id_salt("preferences_body")
|
||||
.max_height(body_height)
|
||||
@@ -898,12 +918,64 @@ fn preferences_window_height(screen_height: f32) -> f32 {
|
||||
(screen_height - PREFERENCES_SCREEN_MARGIN).clamp(PREFERENCES_MIN_HEIGHT, PREFERENCES_WINDOW_HEIGHT)
|
||||
}
|
||||
|
||||
/// Draws the fixed-order page tabs and highlights pages containing a search match.
|
||||
fn tabs(ui: &mut egui::Ui, page: &mut PreferencesPage, search: &str) {
|
||||
/// Whether Preferences lists the AI Agents page: this window takes agents and the suite's `AI-MCP`
|
||||
/// flag is on.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn agents_page_shown(app: &SoundApp) -> bool {
|
||||
app.agents().is_some_and(crate::agents::Agents::mcp_flag)
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn agents_page_shown(_: &SoundApp) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
/// The AI Agents page over the saved agent settings. A change runs `ui.agent_settings`, which saves
|
||||
/// it where `soundcraft-cli mcp` reads it, at once: OK and Cancel don't apply to it, and the page
|
||||
/// says so.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn agents_page(app: &mut SoundApp, ui: &mut egui::Ui) {
|
||||
use craft_automation::agents::AgentSettings;
|
||||
use craft_automation::ui::agents::AgentsPage;
|
||||
use craft_ui::patterns::preferences::SettingsDraft;
|
||||
const KEY: &str = "agents";
|
||||
let Some(agents) = app.agents() else { return };
|
||||
let (settings, status) = (agents.settings().clone(), agents.status().clone());
|
||||
ui.label(
|
||||
RichText::new(crate::localization::text("These settings are saved as you change them; Cancel doesn't undo them."))
|
||||
.color(Tokens::current().text_dim),
|
||||
);
|
||||
ui.add_space(4.0);
|
||||
let mut draft = SettingsDraft::default();
|
||||
if draft.replace(&json!({ KEY: &settings })).is_err() {
|
||||
return;
|
||||
}
|
||||
let out = AgentsPage::new(KEY, &mut draft, &status).mcp_flag(true).show(ui);
|
||||
if out.browsing.is_some() {
|
||||
// SoundCraft gives the shared page no file service: say so rather than do nothing.
|
||||
app.ui.status = crate::localization::text("Browse… isn't available on this page yet: type the folder's path.").to_owned();
|
||||
}
|
||||
if !out.changed {
|
||||
return;
|
||||
}
|
||||
let Some(next) = draft.get::<AgentSettings>(KEY).filter(|next| *next != settings) else { return };
|
||||
let params =
|
||||
json!({"controlPort": next.control_port, "readRoot": next.read_root, "writeRoot": next.write_root, "whenAppClosed": next.when_app_closed});
|
||||
if let Err(e) = app.run(crate::agents::SETTINGS_COMMAND, params) {
|
||||
app.ui.status = e;
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn agents_page(_: &mut SoundApp, _: &mut egui::Ui) {}
|
||||
|
||||
/// Draws the fixed-order page tabs and highlights pages containing a search match; the AI Agents
|
||||
/// page follows them when `agents` is set.
|
||||
fn tabs(ui: &mut egui::Ui, page: &mut PreferencesPage, search: &str, agents: bool) {
|
||||
let t = Tokens::current();
|
||||
egui::ScrollArea::horizontal().id_salt("preferences_tabs").show(ui, |ui| {
|
||||
ui.horizontal(|ui| {
|
||||
for candidate in PreferencesPage::ALL {
|
||||
for candidate in PreferencesPage::ALL.into_iter().chain(agents.then_some(PreferencesPage::Agents)) {
|
||||
let hit = page_matches(candidate, search);
|
||||
let text = if !search.is_empty() && hit {
|
||||
RichText::new(crate::localization::text(candidate.label())).color(t.meter_yellow)
|
||||
|
||||
@@ -80,6 +80,8 @@ link stays. An existing file that is not an input is replaced without asking.
|
||||
|---|---|---|
|
||||
| `SOUNDCRAFT_CONTROL_PORT` | `app --port` (CLI), `--control` (desktop app) | A port or `host:port`, an IPv6 host in brackets (`[::1]:7979`). The desktop app takes the port of a loopback `host:port` (`127.0.0.1`, `localhost`). Its control server listens on `127.0.0.1` only, so it ignores another host from the variable, with a log warning, and starts no control server; given to `--control`, another host is a usage error |
|
||||
|
||||
| `SOUNDCRAFT_CONTROL_TOKEN` | none | The secret every control request carries as `token`. The desktop app refuses requests without it; unset or shorter than 32 characters, it makes one per launch and prints it after the port line (`SOUNDCRAFT_CONTROL_TOKEN=…`). `app` and `mcp --connect` send the variable's value |
|
||||
|
||||
- A flag wins over its variable.
|
||||
- An empty variable counts as unset.
|
||||
- A bad value is a usage error that names the variable.
|
||||
|
||||
@@ -6,11 +6,23 @@ input), and every command is reachable from:
|
||||
|
||||
| Surface | How |
|
||||
|---|---|
|
||||
| Desktop app control channel | `soundcraft --control <port>` (`0` = pick a free port; printed as `SOUNDCRAFT_CONTROL_PORT=…`) |
|
||||
| Desktop app control channel | `soundcraft --control <port>` (`0` = pick a free port; printed as `SOUNDCRAFT_CONTROL_PORT=…`, then the launch's `SOUNDCRAFT_CONTROL_TOKEN=…` unless the variable was set) |
|
||||
| CLI against a running app | `soundcraft-cli app --port <port> <method or command id> [JSON]` (see [cli.md](cli.md)) |
|
||||
| Headless CLI | `soundcraft-cli run --demo --cmd 'mix.volume={"track":"Kick","db":-6}' --bounce out.wav` |
|
||||
| MCP (headless) | `soundcraft-cli mcp [--demo]` |
|
||||
| MCP (bridged to the app) | `soundcraft-cli mcp --connect <port>` |
|
||||
| MCP | `soundcraft-cli mcp`: the open window while the ArtCraft Launcher lets agents in, otherwise headless ([mcp.md](mcp.md)) |
|
||||
| MCP (headless) | `soundcraft-cli mcp --headless [--demo]` |
|
||||
| MCP (bridged to `--control`, deprecated) | `soundcraft-cli mcp --connect <port>` |
|
||||
|
||||
## The agents channel
|
||||
|
||||
While the ArtCraft Launcher's *Settings › AI agents* switch names SoundCraft, the window serves a
|
||||
second control channel for agents (the shared Craft agents server): loopback only, on the Control
|
||||
Port of *Preferences › AI Agents*, published in the settings folder as `agent-connection.json`. Each
|
||||
connection signs in first with the challenge handshake (`auth.challenge` with a client nonce; the
|
||||
window proves it holds the token in the settings folder, then the client sends its proof with
|
||||
`auth`); requests are limited to 1 MiB. The methods are the ones below. Every request runs inside
|
||||
the agent folders (see [mcp.md](mcp.md)); `agent.folders` returns them, and `ui.agent_settings` is
|
||||
refused. `soundcraft-cli mcp` is the client; nothing else needs to speak it.
|
||||
|
||||
## Isolated automation profiles
|
||||
|
||||
@@ -29,12 +41,17 @@ input delivery or screen-reader acceptance. Native screenshots use the presented
|
||||
Newline-delimited JSON over TCP on `127.0.0.1`. One request per line, one reply per line:
|
||||
|
||||
```json
|
||||
{"id": 1, "method": "engine.execute", "params": {"command": "track.new", "params": {"count": 2, "format": "Stereo"}}}
|
||||
{"id": 1, "method": "engine.execute", "params": {"command": "track.new", "params": {"count": 2, "format": "Stereo"}}, "token": "…"}
|
||||
{"id": 1, "ok": true, "result": {"tracks": [12, 13]}}
|
||||
```
|
||||
|
||||
Errors: `{"id": 1, "ok": false, "error": "bad parameters for `mix.volume`: no track named `Nope`"}`. A line that is not a JSON object with a string `method` gets one error reply, and the connection is closed.
|
||||
|
||||
`token` is the launch's secret: `SOUNDCRAFT_CONTROL_TOKEN` when the app was started with it, otherwise
|
||||
the one the app made and printed after the port line. Any local account can reach the loopback port,
|
||||
so a request without the right token is refused (`"error": "unauthorized: …"`) and its connection
|
||||
closed. `soundcraft-cli app` and `mcp --connect` read the variable.
|
||||
|
||||
## Methods
|
||||
|
||||
| Method | Params | What it does |
|
||||
@@ -57,6 +74,8 @@ Errors: `{"id": 1, "ok": false, "error": "bad parameters for `mix.volume`: no tr
|
||||
| `ui.text` | `{text}` | Type text into the focused field. At most 64 KiB of UTF-8 text per request. |
|
||||
| `ui.screenshot` | `{path?}` | PNG of the window (base64 in `png_base64` when no path). Exactly one reply per request. A request is bound to the window geometry, focus state and open session it was admitted for. A geometry or DPI change is retried within its 8 s deadline, then fails `screenshot stale`; a change of focused window or of the open document cancels it (`screenshot canceled: focus changed` / `... the session changed`) because those pixels must not be reported as a capture of the new state. It can also fail `screenshot queue full` (8 pending, 4 in flight), `screenshot too large` (64 MiB per image, 192 MiB aggregate **encoding peak**), `screenshot path longer than 4096 bytes`, or `screenshot unavailable: the window has no capturable size yet` (a first request before any window geometry is known, e.g. minimised before the first paint). Each request reserves its own worst-case encode peak — the captured RGBA image plus the raw copy, PNG buffer and base64 text built during encoding — so several small captures cannot retain or encode full-size images past the aggregate. The callback never writes a file: encoding and writing happen after collection, and a result arriving after the deadline returns `screenshot timed out` without creating the file. A native hidden/minimised window is asked for an explicit paint; browser hidden tabs cannot paint on request and time out. |
|
||||
| `app.quit` | `{}` | Quit. |
|
||||
| `agent.folders` | `{}` | The folders an agent request may open (`read_folder`) and save (`write_folder`) files in; on `--control`, `unrestricted: true`. |
|
||||
| `engine.execute {command: "ui.agent_settings"}` | `{controlPort?, readRoot?, writeRoot?, whenAppClosed?}` | The agent settings of Preferences › AI Agents and where the agents channel stands; with params, saves them. Refused for agents. |
|
||||
|
||||
Scripted input (`ui.click`, `ui.drag`, `ui.scroll`, `ui.zoom`, `ui.key`, `ui.text`, `ui.move`) queues at most 4096 waiting events; a request that would exceed that bound fails with `synthetic input queue full` instead of growing the queue. A gesture's reply is delivered only after a UI pass has applied all of its events. Requests that follow it on the same connection (inspect, engine commands, screenshots) are therefore ordered after the gesture; requests already queued behind an undelivered gesture wait as well. If no UI pass can deliver the gesture within 15 s, it is canceled with `synthetic input was not delivered` and the request chain continues. Scripted input is automation, not a clipboard action: copy/selection commands it triggers are not published to the OS clipboard or PRIMARY selection.
|
||||
|
||||
@@ -72,6 +91,7 @@ Scripted input (`ui.click`, `ui.drag`, `ui.scroll`, `ui.zoom`, `ui.key`, `ui.tex
|
||||
## Examples
|
||||
|
||||
```sh
|
||||
export SOUNDCRAFT_CONTROL_TOKEN=$(head -c 32 /dev/urandom | od -An -tx1 | tr -d ' \n')
|
||||
P=$(soundcraft --demo --control 0 | sed -n 's/SOUNDCRAFT_CONTROL_PORT=//p') # or read stderr
|
||||
soundcraft-cli app --port $P mix.solo '{"track":"Bass"}'
|
||||
soundcraft-cli app --port $P transport.play
|
||||
|
||||
+56
-11
@@ -5,19 +5,62 @@ Claude and other agents can make music with it. The server is the `mcp` subcomma
|
||||
`soundcraft-cli`, which [docs/cli.md](cli.md) describes.
|
||||
|
||||
```sh
|
||||
soundcraft-cli mcp # headless engine (no window, no audio device)
|
||||
soundcraft-cli mcp # the open SoundCraft window while the ArtCraft Launcher lets agents in, otherwise headless
|
||||
soundcraft-cli mcp --headless # always the headless engine (no window, no audio device)
|
||||
soundcraft-cli mcp --demo # headless, starting from the demo session
|
||||
soundcraft-cli mcp --automation-read-root DIR --automation-write-root DIR # headless, confined to folders
|
||||
soundcraft --control 7801 & # the desktop app…
|
||||
soundcraft-cli mcp --connect 7801 # …driven over MCP: same tools plus screenshots and clicks
|
||||
soundcraft-cli mcp --automation-read-root DIR --automation-write-root DIR # headless sessions confined to folders
|
||||
```
|
||||
|
||||
Claude Code:
|
||||
The ArtCraft Launcher adds every Craft app to Claude Desktop, Claude Code, Cursor and LM Studio as
|
||||
one `ArtCraft` entry (*Settings › AI agents*); SoundCraft writes no MCP client configuration of its
|
||||
own. To add it by hand, for example to Claude Code:
|
||||
|
||||
```sh
|
||||
claude mcp add soundcraft -- soundcraft-cli mcp --demo
|
||||
claude mcp add soundcraft -- soundcraft-cli mcp
|
||||
```
|
||||
|
||||
## Agents in the open SoundCraft window
|
||||
|
||||
One switch serves every Craft app: the ArtCraft Launcher's *Settings › AI agents › Let AI agents
|
||||
use Craft apps* (behind the suite's `AI-MCP` flag). While it names SoundCraft, the open SoundCraft
|
||||
window (Stable, not Nightly) serves agents on a loopback port with a token and a challenge
|
||||
handshake, and writes where in its settings folder (`agent-connection.json`, beside `agents.json`
|
||||
and the token file). When the switch turns off, the window stops serving and removes the file; no
|
||||
restart is needed. SoundCraft has no agents switch of its own.
|
||||
|
||||
Plain `soundcraft-cli mcp` reads that file before every tool call, so a client configuration holds
|
||||
no port and no token:
|
||||
|
||||
- **SoundCraft open, switch on:** the call goes to the open window, signed in with the token (a
|
||||
program that took a stale port can't prove it holds it, and gets nothing). The window's tools
|
||||
(`screenshot`, `click`, `key`, …) work.
|
||||
- **SoundCraft closed, switch on:** the choice under *Preferences › AI Agents › When SoundCraft Is
|
||||
Closed*: start SoundCraft and wait for it, work headless inside the agent folders, or answer that
|
||||
SoundCraft isn't running. `--when-closed launch|headless|error` overrides it for one server.
|
||||
A session that went headless stays headless.
|
||||
- **Switch off (or no `AI-MCP` flag):** headless, as `mcp` always was.
|
||||
- `--headless` always serves the in-process engine. `--demo` and the automation root flags imply
|
||||
it: the window keeps agents to its own agent folders, so a server given roots never uses it.
|
||||
|
||||
In the window an agent's files stay inside the **agent folders**: the read and write folders set on
|
||||
*Preferences › AI Agents*, or `Documents/ArtCraft/Agents/SoundCraft` when they are empty. Every file a
|
||||
command reads or writes goes through the same checks as the automation roots below; so does what
|
||||
input the agent queued (keys, clicks, text) runs until a UI pass has applied it, and a screenshot
|
||||
path. Nothing is written in SoundCraft's settings folder, even when a write folder holds it. An agent
|
||||
can't change the agent settings (`ui.agent_settings` is refused for it). The `agent_folders` tool
|
||||
says which folders apply (the person's own `--control` channel answers that it isn't confined).
|
||||
|
||||
*Preferences › AI Agents* is listed while the `AI-MCP` flag is on. It shows whether agents can connect
|
||||
and on which port, the Control Port (0 picks a free one), the two folders and the closed-app choice.
|
||||
Changes are saved at once (OK and Cancel don't apply to them) to `agents.json`, where
|
||||
`soundcraft-cli mcp` reads them. Browse… isn't available on this page yet: type the folder's path.
|
||||
A window started with `--control` keeps that channel for the whole run and doesn't take agents
|
||||
through the switch.
|
||||
|
||||
`mcp --connect PORT` still works for one release and prints that it is deprecated: it talks to a
|
||||
`soundcraft --control` channel, which isn't confined; it sends `SOUNDCRAFT_CONTROL_TOKEN`, the
|
||||
channel's secret (see [control-protocol.md](control-protocol.md)).
|
||||
|
||||
## Confining file access
|
||||
|
||||
```sh
|
||||
@@ -70,10 +113,11 @@ works across the suite) keep the agent to the folders you give it:
|
||||
one folder per use (`--flag <dir>` or `--flag=<dir>`) and may be used again for more, and a
|
||||
misspelled `--automation-...` flag is an error rather than an unconfined server.
|
||||
|
||||
The flags confine the in-process server, so `--connect` together with them is an error: the server
|
||||
would otherwise talk to an app that isn't confined. SoundCraft's desktop app has no equivalent flags
|
||||
yet, so a running app (`soundcraft --control`) is not confined. `--demo` is the operator's own
|
||||
choice and is built before the roots apply.
|
||||
The flags confine the in-process server (and make plain `mcp` headless), so
|
||||
`--connect` together with them is an error: the server would otherwise talk to an app that isn't
|
||||
confined. The open window keeps agents to the agent folders instead (see above); a running app
|
||||
started with `soundcraft --control` is not confined. `--demo` is the operator's own choice and is
|
||||
built before the roots apply.
|
||||
|
||||
Playback and bounce need no check of their own. SoundCraft decodes audio into the session when it
|
||||
enters it (import, open, sampler load), so rendering reads nothing from disk afterwards. Movies are
|
||||
@@ -104,7 +148,8 @@ files it was given rather than guarding against other software on the computer.
|
||||
| `import_audio` | WAV, AIFF, FLAC, MP3, OGG, AAC/M4A, ALAC, CAF onto a new or existing track. |
|
||||
| `bounce_mix` | Render to WAV/AIFF/FLAC; returns peak dBFS and integrated LUFS. |
|
||||
| `parity` | Feature-parity report. |
|
||||
| `screenshot`, `ui_inspect`, `ui_set`, `menu_invoke`, `click`, `drag`, `key` | App only (with `--connect`). |
|
||||
| `agent_folders` | The folders this session may open and save files in (`read_folder`, `write_folder`), or that it isn't confined. |
|
||||
| `screenshot`, `ui_inspect`, `ui_set`, `menu_invoke`, `click`, `drag`, `key` | The open window only (plain `mcp` while the launcher lets agents in). A screenshot without `path` comes back in the reply. |
|
||||
|
||||
Resources: `soundcraft://session` (full session JSON), `soundcraft://commands`.
|
||||
|
||||
|
||||
@@ -116,6 +116,9 @@ echo "==> assembling $APP"
|
||||
mkdir -p "$APP/Contents/MacOS" "$APP/Contents/Resources"
|
||||
# Executable and icon carry the display name (CFBundleExecutable / CFBundleIconFile).
|
||||
cp "$WORK/bin/soundcraft" "$APP/Contents/MacOS/SoundCraft"
|
||||
# The CLI too, beside the app: the ArtCraft Launcher finds `soundcraft-cli` next to the app's
|
||||
# executable and registers `soundcraft-cli mcp` for agents.
|
||||
cp "$WORK/bin/soundcraft-cli" "$APP/Contents/MacOS/soundcraft-cli"
|
||||
cp "$ROOT/assets/app-icon/soundcraft.icns" "$APP/Contents/Resources/SoundCraft.icns"
|
||||
# Required embedded-font notices are independent of optional font inputs.
|
||||
cp "$ROOT/NOTICE" "$APP/Contents/Resources/NOTICE"
|
||||
@@ -130,7 +133,9 @@ printf 'APPL????' >"$APP/Contents/PkgInfo"
|
||||
xattr -cr "$APP"
|
||||
|
||||
# Sign inside-out: nested code first, then the bundle itself (no --deep on the final signature).
|
||||
# Today the only nested code is the main executable; frameworks/helpers would be signed here too.
|
||||
# The bundled CLI is nested executable code; sign it before sealing the app bundle, with the same
|
||||
# entitlements as the standalone CLI (it hosts plugins too).
|
||||
sign --options runtime --entitlements "$HERE/entitlements.plist" --identifier ai.storyteller.soundcraft-cli "$APP/Contents/MacOS/soundcraft-cli"
|
||||
sign --options runtime --entitlements "$HERE/entitlements.plist" "$APP/Contents/MacOS/SoundCraft"
|
||||
sign --options runtime --entitlements "$HERE/entitlements.plist" "$APP"
|
||||
codesign --verify --strict --deep --verbose=2 "$APP"
|
||||
|
||||
Reference in New Issue
Block a user