diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json new file mode 100644 index 0000000..447e440 --- /dev/null +++ b/.claude-plugin/marketplace.json @@ -0,0 +1,12 @@ +{ + "name": "coreinfra-wizard", + "metadata": { "description": "Skills for Claude connected through CoreInfra Wizard." }, + "owner": { "name": "CoreInfra" }, + "plugins": [ + { + "name": "coreinfra-video", + "source": "./plugins/coreinfra-video", + "description": "Generate and retrieve videos through CoreInfra Wizard." + } + ] +} diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e81e8a7..1f1e8c7 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -62,13 +62,23 @@ jobs: - name: Install Codex for the video skill E2E run: npm install --prefix "${{ runner.temp }}/video-codex" --no-save --no-package-lock --no-audit --no-fund "@openai/codex@0.160.0" - - name: Verify the installed skill can list live video models + - name: Verify the installed Codex skill can list live video models timeout-minutes: 5 env: WIZARD_VIDEO_TEST_CODEX: ${{ runner.temp }}/video-codex/node_modules/@openai/codex/bin/codex.js WIZARD_VIDEO_TEST_PYTHON: python run: cargo test --locked -p wizard-core --lib video::tests::codex_skill_lists_public_video_models -- --exact --ignored --nocapture + - name: Install Claude Code for the video skill E2E + run: npm install --prefix "${{ runner.temp }}/video-claude" --no-save --no-package-lock --no-audit --no-fund "@anthropic-ai/claude-code@2.1.259" + + - name: Verify the installed Claude Code skill can list live video models + timeout-minutes: 5 + env: + WIZARD_VIDEO_TEST_CLAUDE: ${{ runner.temp }}/video-claude/node_modules/@anthropic-ai/claude-code/bin/claude.exe + WIZARD_VIDEO_TEST_PYTHON: python + run: cargo test --locked -p wizard-core --lib agents::claude::video_e2e::claude_code_skill_lists_public_video_models -- --exact --ignored --nocapture + frontend: name: Frontend runs-on: ubuntu-latest diff --git a/README.md b/README.md index bf0a357..e7f0f61 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ An application for configuring agents to use CoreInfra. -## Video in ChatGPT Work and Codex +## Video in ChatGPT Work, Codex and Claude Code Start Wizard, sign in to CoreInfra Hub and select the Hub to charge. Keep Wizard running and ask for a video in a new ChatGPT Work or Codex chat, or invoke `$coreinfra-video`. Wizard automatically installs the skill and registers its MCP server at startup. @@ -12,6 +12,14 @@ The bundled skill and the `coreinfra_video` MCP registration live in the profile For new jobs Wizard uses the oldest active key named `agent-codex` in the selected Hub, the same default that Wizard provisions for Codex. If it is missing, Wizard issues one as part of the generation request. Only Wizard adds the Hub key to the outgoing `Authorization` header. A job records its Hub ID, key fingerprint, provider, model and upstream ID so Wizard can poll with the original key. Wizard keeps no job table or MCP session. A Python MCP client with permission to reach loopback can use the URL and current local `http_headers` from the registration. +### Claude Code + +In Wizard choose **Claude Code → API-доступ → Применить** and confirm the configuration plan. Start a new local Claude Code session and ask «Какие видеомодели доступны?» or invoke `/coreinfra-video`. Keep Wizard running. The CLI routing command applies the same configuration. + +Wizard installs the bundled skill under `~/.claude/skills/coreinfra-video` and registers the HTTP MCP server `coreinfra_video` in the user’s `~/.claude.json`. Both locations follow `CLAUDE_CONFIG_DIR` when set. Claude Code reads the current local bearer through its native `headersHelper`. Wizard rotates the bearer on startup and removes the headers file when video is disabled. Generation uses Wizard’s `agent-codex` key in the selected Hub. The video connection switch is shared across Claude Code and Codex. Switching Claude Code away from API access removes its managed MCP entry and unmodified skill. Reapplying API access installs the version shipped with Wizard. + +The Claude Code E2E in the Linux, macOS and Windows CI matrix configures a fresh profile, launches native Claude Code, asks it to read the installed skill, and verifies that the next inference request and the final answer receive live catalog data. Chat inference is a local Messages fixture. To run it locally, set `WIZARD_VIDEO_TEST_CLAUDE` to a Claude Code executable and run `cargo test -p wizard-core claude_code_skill_lists_public_video_models -- --ignored --nocapture` with Python 3 available. + ### Custom video fields Put provider-specific JSON in `fields`. Wizard merges its entries into the outgoing JSON body and preserves nested objects, arrays, numbers, booleans and nulls. For clients that cannot express open-ended object arguments, `fields_json` accepts the same object as a JSON string. Use one representation per request. `model` and `prompt` are reserved tool arguments. The destination, authentication and HTTP headers are controlled by Wizard. @@ -33,7 +41,7 @@ For OpenRouter, put per-provider options under `fields.provider.options` and inl The [client compatibility test](crates/wizard-core/tests/video_clients.py) includes a Python SDK 2.x example using `streamable_http_client`. To repeat the end-to-end test, set `WIZARD_VIDEO_TEST_PYTHON` to a Python with `mcp` 2.x installed and `WIZARD_VIDEO_TEST_CODEX` to a Codex executable. Run `cargo test -p wizard-core native_and_python_clients -- --ignored --nocapture`. All submissions in this test go to its temporary local Hub. -CI also runs a catalog E2E on Linux, macOS and Windows. Wizard installs the bundled skill and MCP registration into a fresh profile. A native Codex turn uses the installed skill to call `video_models` and receives model IDs from the public Hub. A local Responses fixture requests that single read-only tool call. To run it locally, set `WIZARD_VIDEO_TEST_CODEX` to a Codex executable or its npm `bin/codex.js` launcher and run `cargo test -p wizard-core codex_skill_lists_public_video_models -- --ignored --nocapture` with Python 3 available and port 33789 free. +CI also runs a catalog E2E on Linux, macOS and Windows. Wizard installs the bundled skill and MCP registration into a fresh profile. A native Codex turn uses the installed skill to call `video_models` and receives model IDs from the public Hub. A local Responses fixture requests that single read-only tool call. To run it locally, set `WIZARD_VIDEO_TEST_CODEX` to a Codex executable or its npm `bin/codex.js` launcher and run `cargo test -p wizard-core codex_skill_lists_public_video_models -- --ignored --nocapture` with Python 3 available. The test uses its own loopback listener. ## How to build diff --git a/crates/wizard-core/Cargo.toml b/crates/wizard-core/Cargo.toml index d6d47c5..944b379 100644 --- a/crates/wizard-core/Cargo.toml +++ b/crates/wizard-core/Cargo.toml @@ -23,7 +23,7 @@ dirs.workspace = true ed25519-dalek.workspace = true log.workspace = true regex.workspace = true -rmcp.workspace = true +rmcp = { workspace = true, features = ["transport-io"] } quick-xml.workspace = true reqwest.workspace = true serde.workspace = true diff --git a/crates/wizard-core/src/agents/claude.rs b/crates/wizard-core/src/agents/claude.rs index 3abfebc..d96243f 100644 --- a/crates/wizard-core/src/agents/claude.rs +++ b/crates/wizard-core/src/agents/claude.rs @@ -1,3 +1,7 @@ +mod video; +#[cfg(test)] +mod video_e2e; + use super::{ AgentDetection, AgentToken, RoutingMode, detection::{self, Agent, AgentInfo}, @@ -32,6 +36,7 @@ pub(crate) struct Claude { pub info: AgentInfo, pub routing_mode: RoutingMode, pub token: Option, + pub video_needs_apply: bool, } pub(super) fn detect(settings: &Settings) -> AgentDetection { @@ -40,7 +45,7 @@ pub(super) fn detect(settings: &Settings) -> AgentDetection { AgentDetection::NotFound => return AgentDetection::NotFound, AgentDetection::Error(error) => return AgentDetection::Error(error), }; - let (routing_mode, token) = match read_routing() { + let (routing_mode, token, video_needs_apply) = match read_routing() { Ok(routing) => routing, Err(error) => return AgentDetection::Error(format!("{error:#}")), }; @@ -48,6 +53,7 @@ pub(super) fn detect(settings: &Settings) -> AgentDetection { info, routing_mode, token, + video_needs_apply, }) } @@ -75,11 +81,20 @@ pub fn configured_token() -> Result> { Ok(read_routing()?.1.map(AgentToken::into_secret)) } -fn read_routing() -> Result<(RoutingMode, Option)> { +fn read_routing() -> Result<(RoutingMode, Option, bool)> { let _guard = PreparedAgent::Claude.lock()?; - let settings = config_files::json::read(&config_dir()?.join("settings.json"))?; + let dir = config_dir()?; + let settings = config_files::json::read(&dir.join("settings.json"))?; let mode = mode_from_config(&settings); - Ok((mode, token_from_config(&settings, mode))) + let video_needs_apply = if mode == RoutingMode::Hub { + let mut global = FileChange::read(global_config_path()?)?; + video::configure(&dir, &mut global, &video_server()?, true).map_or(true, |files| { + global.is_changed() || files.iter().any(FileChange::is_changed) + }) + } else { + false + }; + Ok((mode, token_from_config(&settings, mode), video_needs_apply)) } /// Reads only keys owned by the active mode: a disabled API key may belong to the user. @@ -109,19 +124,77 @@ pub fn get_backups() -> Result> { } pub fn restore_backup(id: u32) -> Result<()> { - let _guard = PreparedAgent::Claude.lock()?; - BackupManager::new(AgentKind::Claude)?.load_backup(id) + let manager = BackupManager::new(AgentKind::Claude)?; + let plan = { + let _guard = PreparedAgent::Claude.lock()?; + prepare_restore_at( + &config_dir()?, + &global_config_path()?, + &video_server()?, + &manager, + id, + )? + }; + plan.apply_with_backup( + Some(manager), + |_| bail!("Unexpected desktop proxy"), + |_| bail!("Unexpected Codex proxy"), + ) +} + +fn prepare_restore_at( + dir: &Path, + global_path: &Path, + server: &Value, + manager: &BackupManager, + id: u32, +) -> Result { + let mut changes = manager.restore_changes(id)?; + let path = dir.join("settings.json"); + let settings = if let Some(change) = changes.iter().find(|change| change.path() == &path) { + config_files::json::parse(&change.after)? + } else { + config_files::json::read(&path)? + }; + let mut global = FileChange::read(global_path.to_owned())?; + changes.extend(video::configure( + dir, + &mut global, + server, + mode_from_config(&settings) == RoutingMode::Hub, + )?); + changes.push(global); + Ok(prepare_plan(changes)) } /// `token` is ignored when disabled. pub fn prepare_routing(mode: RoutingMode, token: &str) -> Result { let _guard = PreparedAgent::Claude.lock()?; - let dir = config_dir()?; + prepare_routing_at( + &config_dir()?, + &global_config_path()?, + &video_server()?, + mode, + token, + ) +} + +fn video_server() -> Result { + video::server(crate::video::URL, &crate::video::install::headers_path()?) +} + +fn prepare_routing_at( + dir: &Path, + global_path: &Path, + server: &Value, + mode: RoutingMode, + token: &str, +) -> Result { let script_path = dir.join("no-proxy.sh"); let mut settings = FileChange::read(dir.join("settings.json"))?; - let mut global = FileChange::read(global_config_path()?)?; + let mut global = FileChange::read(global_path.to_owned())?; let mut script = FileChange::read(script_path.clone())?; let current_mode = mode_from_config(&config_files::json::parse(&settings.after)?); @@ -158,12 +231,13 @@ pub fn prepare_routing(mode: RoutingMode, token: &str) -> Result { } // Keep preparation files before activation, and script deletion after it. - let changes = if mode == RoutingMode::Sub { + let mut changes = video::configure(dir, &mut global, server, mode == RoutingMode::Hub)?; + changes.extend(if mode == RoutingMode::Sub { [global, script, settings] } else { [global, settings, script] - }; - Ok(prepare_plan(changes.into())) + }); + Ok(prepare_plan(changes)) } fn prepare_plan(changes: Vec) -> PreparedPlan { @@ -319,6 +393,90 @@ fn approve_key(after: &mut FileSnapshot, suffix: &str) -> Result<()> { mod tests { use super::*; + #[test] + fn video_follows_gateway_mode_and_backup_restores_preserve_other_servers() -> Result<()> { + let temp = tempfile::tempdir()?; + let dir = temp.path().join(".claude"); + let global = temp.path().join(".claude.json"); + let skill = dir.join("skills/coreinfra-video/SKILL.md"); + let registration = + video::server(crate::video::URL, &temp.path().join("video headers.json"))?; + let manager = + || BackupManager::in_directory(AgentKind::Claude, temp.path().join("backups")); + let apply = |plan: PreparedPlan| { + plan.apply_with_backup( + Some(manager()), + |_| bail!("Unexpected desktop proxy"), + |_| bail!("Unexpected Codex proxy"), + ) + }; + let prepare = + |mode| prepare_routing_at(&dir, &global, ®istration, mode, "inference-key"); + let read_global = || config_files::json::read(&global); + let foreign = json!({"type":"http","url":"https://example.org/mcp"}); + std::fs::write( + &global, + json!({"mcpServers":{"other":foreign},"theme":"dark"}).to_string(), + )?; + + let first = prepare(RoutingMode::Hub)?; + assert!(!skill.exists()); + apply(first)?; + assert!(skill.is_file()); + assert_eq!( + read_global()?["mcpServers"]["coreinfra_video"], + registration + ); + assert!(!registration.to_string().contains("inference-key")); + assert!(prepare(RoutingMode::Hub)?.steps().iter().all( + |step| matches!(step, PreparedStep::ChangeFile { change } if !change.is_changed()) + )); + assert_eq!(manager().get_backups()?.len(), 1); + + // Claude itself can change its global state between configuration and restore. + let mut updated = read_global()?; + updated["theme"] = json!("light"); + std::fs::write(&global, updated.to_string())?; + apply(prepare_restore_at( + &dir, + &global, + ®istration, + &manager(), + 1, + )?)?; + assert!(!skill.exists()); + assert_eq!(read_global()?["theme"], "light"); + assert_eq!(read_global()?["mcpServers"], json!({"other":foreign})); + + apply(prepare(RoutingMode::Hub)?)?; + std::fs::write(&skill, "my edited skill")?; + assert!(prepare(RoutingMode::Hub).is_err()); + for mode in [RoutingMode::Sub, RoutingMode::Disabled] { + apply(prepare(mode)?)?; + assert_eq!(std::fs::read_to_string(&skill)?, "my edited skill"); + assert_eq!(read_global()?["mcpServers"], json!({"other":foreign})); + } + Ok(()) + } + + #[test] + fn foreign_video_entries_block_install_without_changing_any_files() -> Result<()> { + let temp = tempfile::tempdir()?; + let dir = temp.path().join("claude"); + let global = temp.path().join("global.json"); + let server = video::server(crate::video::URL, &temp.path().join("headers.json"))?; + let existing = json!({"mcpServers":{"coreinfra_video":{"type":"http","url":crate::video::URL,"headersHelper":"user-helper"}}}); + std::fs::write(&global, existing.to_string())?; + assert!(prepare_routing_at(&dir, &global, &server, RoutingMode::Hub, "key").is_err()); + assert!(!dir.exists()); + assert_eq!(config_files::json::read(&global)?, existing); + let plan = prepare_routing_at(&dir, &global, &server, RoutingMode::Disabled, "")?; + assert!(plan.steps().iter().all( + |step| matches!(step, PreparedStep::ChangeFile { change } if !change.is_changed()) + )); + Ok(()) + } + #[test] fn user_credentials_that_override_a_mode_are_rejected() { let env = |key: &str| { diff --git a/crates/wizard-core/src/agents/claude/video.rs b/crates/wizard-core/src/agents/claude/video.rs new file mode 100644 index 0000000..5fb344c --- /dev/null +++ b/crates/wizard-core/src/agents/claude/video.rs @@ -0,0 +1,79 @@ +//! User-scoped skill and MCP registration for Claude Code gateway profiles. +use crate::{ + config_files::{changes::FileChange, json}, + video::install, +}; +use anyhow::{Context as _, Result, ensure}; +use serde_json::{Value, json}; +use std::path::Path; + +const SERVER: &str = "coreinfra_video"; +const FILES: &[(&str, &str)] = &[( + "SKILL.md", + include_str!("../../../../../plugins/coreinfra-video/skills/coreinfra-video/SKILL.md"), +)]; + +pub(super) fn server(url: &str, headers: &Path) -> Result { + let path = headers + .to_str() + .context("Video headers path must be Unicode")?; + // No runtime dependencies. The path is data, including spaces and shell metacharacters. + #[cfg(unix)] + let helper = format!("/bin/cat '{}'", path.replace('\'', "'\\''")); + #[cfg(windows)] + let helper = { + use base64::{Engine as _, engine::general_purpose::STANDARD}; + let script = format!( + "[Console]::Write([IO.File]::ReadAllText('{}'))", + path.replace('\'', "''") + ); + let encoded = STANDARD.encode( + script + .encode_utf16() + .flat_map(u16::to_le_bytes) + .collect::>(), + ); + format!("powershell.exe -NoProfile -NonInteractive -EncodedCommand {encoded}") + }; + Ok(json!({"type":"http", "url":url, "headersHelper":helper})) +} + +pub(super) fn configure( + dir: &Path, + global: &mut FileChange, + server: &Value, + enable: bool, +) -> Result> { + json::update(&mut global.after, |config| { + let existing = config["mcpServers"].get(SERVER); + let owned = existing.is_some_and(|entry| { + ["type", "url", "headersHelper"] + .iter() + .all(|&key| entry[key] == server[key]) + }); + if enable { + ensure!( + owned || existing.is_none(), + "В Claude Code уже зарегистрирован другой MCP-сервер coreinfra_video" + ); + if !owned { + config + .as_object_mut() + .context("Invalid Claude Code config")? + .entry("mcpServers") + .or_insert_with(|| json!({})) + .as_object_mut() + .context("Claude Code mcpServers must be an object")? + .insert(SERVER.into(), server.clone()); + } + } else if owned && let Some(servers) = config["mcpServers"].as_object_mut() { + servers.shift_remove(SERVER); + } + Ok(()) + })?; + let root = dir.join("skills/coreinfra-video"); + if !enable && !root.join(".wizard-managed.json").exists() { + return Ok(Vec::new()); + } + install::skill_changes(&root, FILES, enable) +} diff --git a/crates/wizard-core/src/agents/claude/video_e2e.rs b/crates/wizard-core/src/agents/claude/video_e2e.rs new file mode 100644 index 0000000..67bc953 --- /dev/null +++ b/crates/wizard-core/src/agents/claude/video_e2e.rs @@ -0,0 +1,63 @@ +use super::*; +use crate::video::{Job, VideoHub, VideoKey, install, server}; +use core::{ + future::{self, Future}, + time::Duration, +}; +use tokio::{net::TcpListener, process::Command}; + +struct CatalogOnly; +impl server::VideoAccess for CatalogOnly { + fn token<'a>( + &'a self, + _: Option<&'a Job>, + ) -> impl Future> + Send + 'a { + future::ready(Err(anyhow::anyhow!( + "Public catalog requested a generation key" + ))) + } +} + +#[tokio::test] +#[ignore = "requires native Claude Code, Python and the public Hub catalog"] +async fn claude_code_skill_lists_public_video_models() -> Result<()> { + let _ = crate::hub::install_crypto_provider(); + let temp = tempfile::tempdir()?; + let root = std::path::absolute(temp.path())?; + let profile = root.join("claude config"); + let global = profile.join(".claude.json"); + let headers = root.join("wizard's app data & ${HOME}/video-mcp-headers.json"); + let listener = TcpListener::bind("127.0.0.1:0").await?; + let url = format!("http://{}/mcp", listener.local_addr()?); + let registration = video::server(&url, &headers)?; + let config = root.join("codex/config.toml"); + let broker = server::start(listener, VideoHub::new()?, CatalogOnly, move |bearer| { + install::sync_with_headers(&config, &headers, None, Some(bearer)) + }) + .await?; + prepare_routing_at( + &profile, + &global, + ®istration, + RoutingMode::Hub, + "fixture-inference-key", + )? + .apply_with_backup( + None, + |_| bail!("Unexpected desktop proxy"), + |_| bail!("Unexpected Codex proxy"), + )?; + let python = std::env::var_os("WIZARD_VIDEO_TEST_PYTHON") + .unwrap_or_else(|| if cfg!(windows) { "python" } else { "python3" }.into()); + let mut child = Command::new(python) + .args(["-E", "-B"]) + .arg(Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/claude_video_e2e.py")) + .arg(&profile) + .current_dir(root) + .kill_on_drop(true) + .spawn()?; + let status = tokio::time::timeout(Duration::from_secs(120), child.wait()).await??; + broker.abort(); + ensure!(status.success(), "Claude Code video E2E failed ({status})"); + Ok(()) +} diff --git a/crates/wizard-core/src/agents/claude_desktop.rs b/crates/wizard-core/src/agents/claude_desktop.rs index 11e0e21..e4d4b34 100644 --- a/crates/wizard-core/src/agents/claude_desktop.rs +++ b/crates/wizard-core/src/agents/claude_desktop.rs @@ -1,3 +1,5 @@ +mod video; + use super::{ AgentDetection, AgentToken, RoutingMode, detection::{self, AgentInfo, DesktopAgent}, @@ -199,7 +201,18 @@ fn read_routing_at(dir: &Path) -> Result<(RoutingMode, Option, bool) let token = config["inferenceGatewayApiKey"] .as_str() .and_then(|token| AgentToken::new(token.to_owned())); - Ok((RoutingMode::Hub, token, proxy_needs_apply)) + let mut updated = config.clone(); + let registration = video::Registration::for_wizard()?; + let needs_video = registration + .update( + updated + .as_object_mut() + .context("Invalid Claude Desktop profile")?, + true, + ) + .is_err() + || updated != config; + Ok((RoutingMode::Hub, token, proxy_needs_apply || needs_video)) } else { Ok((RoutingMode::Disabled, None, false)) } @@ -214,6 +227,15 @@ pub fn prepare_routing(mode: RoutingMode, token: &str) -> Result { } fn prepare_routing_at(dir: &Path, mode: RoutingMode, token: &str) -> Result { + prepare_with_video(dir, mode, token, &video::Registration::for_wizard()?) +} + +fn prepare_with_video( + dir: &Path, + mode: RoutingMode, + token: &str, + video: &video::Registration, +) -> Result { let mut meta = FileChange::read(dir.join("_meta.json"))?; let metadata = json::parse(&meta.after)?; let selected = applied_id(&metadata)?; @@ -254,6 +276,7 @@ fn prepare_routing_at(dir: &Path, mode: RoutingMode, token: &str) -> Result Result { + let command = std::env::current_exe()?; + // AppImage remounts its contents at a new temporary path on every launch. + #[cfg(target_os = "linux")] + let command = std::env::var_os("APPIMAGE") + .map(PathBuf::from) + .filter(|path| { + path.is_absolute() + && std::env::var_os("APPDIR").is_some_and(|dir| command.starts_with(dir)) + }) + .unwrap_or(command); + Ok(Self { + command, + headers: crate::video::install::headers_path()?, + port: crate::video::ADDRESS.port(), + }) + } + + pub(super) fn update(&self, profile: &mut Map, enable: bool) -> Result<()> { + reconcile( + profile, + "allowedPluginMarketplaces", + enable, + json!({ + "source":"github", "repo":REPO, "expectedName":MARKET, "ref":REVISION, + "credentialKind":"anonymous", "installationPreference":"auto_install" + }), + |entry| { + entry["expectedName"] == MARKET + || entry["repo"] + .as_str() + .is_some_and(|repo| repo.eq_ignore_ascii_case(REPO)) + }, + |entry| { + entry["source"] == "github" + && entry["repo"] == REPO + && entry["expectedName"] == MARKET + && entry["credentialKind"] == "anonymous" + && entry["installationPreference"] == "auto_install" + && entry.get("path").is_none() + }, + "ref", + )?; + let args = json!([stdio::ARG, self.port.to_string(), self.headers]); + reconcile( + profile, + "managedMcpServers", + enable, + json!({ + "name":SERVER, "transport":"stdio", "command":self.command, "args":args, + "toolTimeoutSec":240, "toolPolicy":{"video_models":"allow"} + }), + |entry| entry["name"] == SERVER, + |entry| entry["transport"] == "stdio" && entry["args"] == args, + "command", + ) + } +} + +// Only refresh the pin or executable when a registration already belongs to Wizard. +// In particular, keep a user's stricter tool policies and other servers in place. +fn reconcile( + profile: &mut Map, + key: &str, + enable: bool, + desired: Value, + matches: impl Fn(&Value) -> bool, + owned: impl Fn(&Value) -> bool, + refresh: &str, +) -> Result<()> { + if !enable { + if let Some(entries) = profile.get_mut(key).and_then(Value::as_array_mut) { + let previous_len = entries.len(); + entries.retain(|entry| !(matches(entry) && owned(entry))); + if previous_len != 0 && entries.is_empty() { + profile.shift_remove(key); + } + } + return Ok(()); + } + + let entries = profile + .entry(key) + .or_insert_with(|| json!([])) + .as_array_mut() + .with_context(|| format!("В профиле Claude Desktop поле {key} должно быть массивом"))?; + let mut existing = entries.iter_mut().filter(|entry| matches(entry)); + if let Some(entry) = existing.next() { + ensure!( + owned(entry) && existing.next().is_none(), + "Конфликт регистрации CoreInfra Video в поле {key} профиля Claude Desktop" + ); + entry[refresh] = desired[refresh].clone(); + } else { + entries.push(desired); + } + Ok(()) +} diff --git a/crates/wizard-core/src/config_files/backups.rs b/crates/wizard-core/src/config_files/backups.rs index c4f20f8..b891875 100644 --- a/crates/wizard-core/src/config_files/backups.rs +++ b/crates/wizard-core/src/config_files/backups.rs @@ -164,11 +164,6 @@ impl BackupManager { state.save(self) } - pub fn load_backup(&self, id: u32) -> Result<()> { - self.apply_changes(&self.restore_changes(id)?) - .context("failed to restore backup") - } - pub(crate) fn restore_changes(&self, id: u32) -> Result> { let backup = Backup::load(&self.directory, id)?; diff --git a/crates/wizard-core/src/video/install.rs b/crates/wizard-core/src/video/install.rs index 32db4a9..6a3e533 100644 --- a/crates/wizard-core/src/video/install.rs +++ b/crates/wizard-core/src/video/install.rs @@ -9,7 +9,7 @@ use crate::{ }; use alloc::collections::BTreeMap; use anyhow::{Context as _, Result, ensure}; -use std::path::Path; +use std::path::{Path, PathBuf}; use toml_edit::DocumentMut; const SERVER: &str = "coreinfra_video"; @@ -26,26 +26,72 @@ const SKILL: &[(&str, &str)] = &[ pub fn sync(previous: Option<&str>, next: Option<&str>) -> Result<()> { let _guard = PreparedAgent::Codex.lock()?; - sync_at(&codex::config_path()?, previous, next) + sync_with_headers(&codex::config_path()?, &headers_path()?, previous, next) } +pub(crate) fn headers_path() -> Result { + Ok(wizard_settings::paths::config_dir()?.join("video-mcp-headers.json")) +} + +#[cfg(test)] pub(super) fn sync_at(path: &Path, previous: Option<&str>, next: Option<&str>) -> Result<()> { + sync_with_headers( + path, + &path.with_file_name("test-video-headers.json"), + previous, + next, + ) +} + +pub(crate) fn sync_with_headers( + path: &Path, + headers: &Path, + previous: Option<&str>, + next: Option<&str>, +) -> Result<()> { let mut config = FileChange::read(path.to_owned())?; update_config(&mut config.after, previous, next)?; - if next.is_none() { - // Revoke the registration even when a user-edited skill cannot be cleaned up. - FileChange::apply_all(core::slice::from_ref(&config))?; - } + // Claude Code reads just these local MCP headers on connection. The Hub key stays in Wizard. + let mut grant = FileChange::read(headers.to_owned())?; + grant.after = match next { + Some(bearer) => FileSnapshot::new( + serde_json::json!({"Authorization": format!("Bearer {bearer}")}).to_string(), + 0o600, + ), + None => FileSnapshot::Missing, + }; let root = path .parent() .context("Missing Codex home")? .join("skills/coreinfra-video"); - for dir in [&root, &root.join("agents")] { - ensure!( - !dir.is_symlink(), - "Video skill directory is a symlink: {}", - dir.display() - ); + if next.is_none() { + // Revoke both clients even if a user-edited skill cannot be cleaned up. + FileChange::apply_all(&[grant, config])?; + return FileChange::apply_all(&skill_changes(&root, SKILL, false)?); + } + let mut changes = skill_changes(&root, SKILL, true)?; + changes.extend([config, grant]); + FileChange::apply_all(&changes) +} + +pub(crate) fn skill_changes( + root: &Path, + files: &[(&str, &str)], + enable: bool, +) -> Result> { + for &(name, _) in files { + let path = root.join(name); + for dir in path + .ancestors() + .skip(1) + .take_while(|dir| dir.starts_with(root)) + { + ensure!( + !dir.is_symlink(), + "Video skill directory is a symlink: {}", + dir.display() + ); + } } let mut manifest = FileChange::read(root.join(".wizard-managed.json"))?; let old: BTreeMap = manifest @@ -57,13 +103,13 @@ pub(super) fn sync_at(path: &Path, previous: Option<&str>, next: Option<&str>) - .unwrap_or_default(); let mut new = BTreeMap::new(); let mut changes = Vec::new(); - for &(name, text) in SKILL { + for &(name, text) in files { let mut file = FileChange::read(root.join(name))?; let owned = file .before() .content() .is_some_and(|v| old.get(name) == Some(&super::fingerprint(v))); - if next.is_some() { + if enable { ensure!( owned || file.before().content().is_none() @@ -78,21 +124,18 @@ pub(super) fn sync_at(path: &Path, previous: Option<&str>, next: Option<&str>) - } changes.push(file); } - manifest.after = if next.is_some() { + manifest.after = if enable { FileSnapshot::new(serde_json::to_string_pretty(&new)?, 0o600) } else { FileSnapshot::Missing }; - if next.is_some() && manifest.before().content().is_none() { + if enable && manifest.before().content().is_none() { // A retry can recognize documents written before a first install was interrupted. changes.insert(0, manifest); } else { changes.push(manifest); } - if next.is_some() { - changes.push(config); - } - FileChange::apply_all(&changes) + Ok(changes) } pub(crate) fn update_config( diff --git a/crates/wizard-core/src/video/mod.rs b/crates/wizard-core/src/video/mod.rs index f8873e1..7906449 100644 --- a/crates/wizard-core/src/video/mod.rs +++ b/crates/wizard-core/src/video/mod.rs @@ -1,10 +1,14 @@ //! Stateless video tools. Job references are carried by the caller and contain no credential. pub mod install; pub mod server; +pub mod stdio; use alloc::collections::BTreeMap; use anyhow::{Context as _, Result, anyhow, bail, ensure}; -use core::time::Duration; +use core::{ + net::{Ipv4Addr, SocketAddrV4}, + time::Duration, +}; use reqwest::{Client, RequestBuilder, Response, Url}; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; @@ -14,7 +18,8 @@ use sha2::{Digest as _, Sha256}; use std::path::{Path, PathBuf}; use tokio::io::AsyncWriteExt as _; -pub const ADDRESS: &str = "127.0.0.1:33789"; +pub const ADDRESS: SocketAddrV4 = SocketAddrV4::new(Ipv4Addr::LOCALHOST, 33789); +const MAX_REQUEST_BYTES: usize = 32 * 1024 * 1024; pub const URL: &str = "http://127.0.0.1:33789/mcp"; const OPENROUTER: &str = "/openrouter/api/v1/videos"; const FAL: &str = "/fal/api"; diff --git a/crates/wizard-core/src/video/server.rs b/crates/wizard-core/src/video/server.rs index 18c2a67..38d3531 100644 --- a/crates/wizard-core/src/video/server.rs +++ b/crates/wizard-core/src/video/server.rs @@ -72,11 +72,15 @@ impl Tools { } } +pub(super) fn server_info() -> ServerConfig { + ServerConfig::new(ServerCapabilities::builder().enable_tools().build()).with_server_info( + Implementation::new("CoreInfra Wizard Video", env!("CARGO_PKG_VERSION")), + ) +} + impl ServerHandler for Tools { fn get_info(&self) -> ServerConfig { - ServerConfig::new(ServerCapabilities::builder().enable_tools().build()).with_server_info( - Implementation::new("CoreInfra Wizard Video", env!("CARGO_PKG_VERSION")), - ) + server_info() } fn list_tools( @@ -174,7 +178,7 @@ async fn serve( .enforce_origin_validation() .with_legacy_session_mode(false) .with_json_response(true) - .with_max_request_body_bytes(32 * 1024 * 1024); + .with_max_request_body_bytes(super::MAX_REQUEST_BYTES); let service = StreamableHttpService::new( move || { Ok(Tools { diff --git a/crates/wizard-core/src/video/stdio.rs b/crates/wizard-core/src/video/stdio.rs new file mode 100644 index 0000000..9e40429 --- /dev/null +++ b/crates/wizard-core/src/video/stdio.rs @@ -0,0 +1,119 @@ +//! Claude Desktop launches this stdio connector. Only Wizard receives Hub credentials. +use anyhow::{Context as _, Result, ensure}; +use core::time::Duration; +use rmcp::{ + ErrorData, RoleServer, ServerHandler, ServiceExt as _, + model::{ + CallToolRequestParams, CallToolResponse, CallToolResult, ListToolsResult, + PaginatedRequestParams, ServerConfig, + }, + service::RequestContext, + transport::{async_rw::AsyncRwTransport, io::stdio_pipes}, +}; +use serde::{Deserialize, Serialize, de::DeserializeOwned}; +use serde_json::json; +use std::path::PathBuf; + +pub const ARG: &str = "--video-mcp-stdio"; + +// Shares the Code client's owner-only HTTP headers file. This is a loopback credential. +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct Headers { + #[serde(rename = "Authorization")] + authorization: String, +} + +struct Connector { + headers: PathBuf, + port: u16, + client: reqwest::Client, +} + +impl Connector { + async fn request( + &self, + method: &str, + params: impl Serialize, + ) -> Result { + // Read for every call so an open Claude session follows a restarted Wizard. + let bytes = tokio::fs::read(&self.headers).await.map_err(|_| { + ErrorData::internal_error("Open CoreInfra Wizard and enable video models", None) + })?; + let headers: Headers = serde_json::from_slice(&bytes) + .map_err(|_| ErrorData::internal_error("Invalid Wizard video connection", None))?; + let request = self + .client + .post(format!("http://127.0.0.1:{}/mcp", self.port)) + .header(reqwest::header::AUTHORIZATION, headers.authorization) + .header("Accept", "application/json, text/event-stream") + .header("Content-Type", "application/json") + .header("MCP-Protocol-Version", "2025-11-25") + .body(json!({"jsonrpc":"2.0","id":1,"method":method,"params":params}).to_string()); + // Each POST is independent. Never replay a paid submission on a transport error. + let mut reply = super::read_json(request).await.map_err(|_| { + ErrorData::internal_error( + "Wizard video request failed; an interrupted submission may have been accepted", + None, + ) + })?; + if let Some(error) = reply.get_mut("error") + && let Ok(error) = serde_json::from_value(error.take()) + { + return Err(error); + } + serde_json::from_value(reply["result"].take()) + .map_err(|_| ErrorData::internal_error("Invalid Wizard video response", None)) + } +} + +impl ServerHandler for Connector { + fn get_info(&self) -> ServerConfig { + super::server::server_info() + } + + async fn list_tools( + &self, + params: Option, + _: RequestContext, + ) -> Result { + self.request("tools/list", params.unwrap_or_default()).await + } + + async fn call_tool( + &self, + params: CallToolRequestParams, + _: RequestContext, + ) -> Result { + self.request::("tools/call", params) + .await + .map(Into::into) + } +} + +pub async fn run(port: u16, headers: PathBuf) -> Result<()> { + ensure!( + port != 0 && headers.is_absolute(), + "Expected an absolute video connection path" + ); + crate::hub::install_crypto_provider()?; + let client = reqwest::Client::builder() + .no_proxy() + .redirect(reqwest::redirect::Policy::none()) + .retry(reqwest::retry::never()) + .connect_timeout(Duration::from_secs(3)) + .timeout(Duration::from_secs(240)) + .build()?; + let (input, output) = stdio_pipes(); + Connector { + headers, + port, + client, + } + .serve(AsyncRwTransport::new(input, output).with_max_line_length(super::MAX_REQUEST_BYTES)) + .await + .context("Could not initialize Claude video MCP")? + .waiting() + .await?; + Ok(()) +} diff --git a/crates/wizard-core/src/video/tests.rs b/crates/wizard-core/src/video/tests.rs index 237a6ab..fb13793 100644 --- a/crates/wizard-core/src/video/tests.rs +++ b/crates/wizard-core/src/video/tests.rs @@ -455,6 +455,35 @@ async fn validates_before_billing_and_confines_credentials() -> Result<()> { Ok(()) } +#[test] +fn claude_headers_rotate_with_the_listener_and_are_revoked_on_disable() -> Result<()> { + let temp = tempfile::tempdir()?; + let config = temp.path().join("codex/config.toml"); + let headers = temp.path().join("wizard/video-mcp-headers.json"); + let sync = |previous, next| install::sync_with_headers(&config, &headers, previous, next); + let mut previous = None; + for grant in ["first-test-grant", "second-test-grant"] { + sync(previous, Some(grant))?; + let published: Value = serde_json::from_slice(&std::fs::read(&headers)?)?; + assert_eq!( + published, + json!({"Authorization": format!("Bearer {grant}")}) + ); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt as _; + assert_eq!( + std::fs::metadata(&headers)?.permissions().mode() & 0o777, + 0o600 + ); + } + previous = Some(grant); + } + sync(previous, None)?; + assert!(!headers.exists()); + Ok(()) +} + #[test] fn install_upgrade_disable_and_collisions() -> Result<()> { use std::fs; @@ -608,11 +637,20 @@ async fn codex_skill_lists_public_video_models() -> Result<()> { let profile = dir.path().join("codex"); let config = profile.join("config.toml"); let access = SignedOut::default(); - let listener = TcpListener::bind(ADDRESS) - .await - .with_context(|| format!("bind the Wizard video MCP port at {ADDRESS}"))?; + let listener = TcpListener::bind("127.0.0.1:0").await?; + let url = format!("http://{}/mcp", listener.local_addr()?); let server = server::start(listener, VideoHub::new()?, access.clone(), move |bearer| { - install::sync_at(&config, None, Some(bearer)) + install::sync_at(&config, None, Some(bearer))?; + // Verify the production registration, then point this isolated profile at its own listener. + let mut doc = toml::read(&config)?; + let key = ["mcp_servers", "coreinfra_video", "url"]; + ensure!( + toml::get_string(&doc, &key) == Some(URL), + "Wrong installed video endpoint" + ); + toml::set_value(&mut doc, &key, url)?; + std::fs::write(config, doc.to_string())?; + Ok(()) }) .await?; let python = std::env::var_os("WIZARD_VIDEO_TEST_PYTHON") diff --git a/crates/wizard-core/tests/claude_video_e2e.py b/crates/wizard-core/tests/claude_video_e2e.py new file mode 100644 index 0000000..0d25a52 --- /dev/null +++ b/crates/wizard-core/tests/claude_video_e2e.py @@ -0,0 +1,133 @@ +"""Run a native Claude Code turn with the user skill and MCP installed by Wizard.""" +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +import json +import os +from pathlib import Path +import subprocess +import sys +import threading + +MODEL = "claude-sonnet-4-6" +TOOL = "mcp__coreinfra_video__video_models" + + +def content_blocks(request): + return [b for m in request["messages"] if isinstance(m["content"], list) for b in m["content"]] + + +def catalog(result): + assert not result.get("is_error"), result + blocks = result["content"] + texts = [blocks] if isinstance(blocks, str) else [b["text"] for b in blocks if b["type"] == "text"] + for text in texts: + try: + # Claude can append a system reminder to the tool output. + value, _ = json.JSONDecoder().raw_decode(text.lstrip()) + except ValueError: + continue + if isinstance(value, dict) and "models" in value: + return value["models"] + raise AssertionError("Claude did not deliver the catalog JSON to inference") + + +class Messages(BaseHTTPRequestHandler): + """Ask for the skill and catalog. Only the native agent executes those tools.""" + def do_POST(self): + path = self.path.split("?")[0] + req = json.loads(self.rfile.read(int(self.headers["Content-Length"]))) + if path == "/v1/messages/count_tokens": + self.reply("application/json", b'{"input_tokens":12}') + return + if path != "/v1/messages": + self.send_error(404) + return + tools = {t["name"] for t in req.get("tools", [])} + result = next((b for b in content_blocks(req) if b.get("tool_use_id") == "toolu_catalog"), None) + block = {"type": "text", "text": "Requested skill or MCP tool unavailable"} + try: + if result: + self.server.models = catalog(result) + assert self.server.models and all(isinstance(m["id"], str) and m["id"].strip() + for m in self.server.models) + block["text"] = self.server.models[0]["id"] + elif self.server.skill_line in json.dumps(req["messages"], ensure_ascii=False) and TOOL in tools: + block = {"type": "tool_use", "id": "toolu_catalog", "name": TOOL, "input": {}} + elif "Skill" in tools and not any(b.get("id") == "toolu_skill" for b in content_blocks(req)): + block = {"type": "tool_use", "id": "toolu_skill", "name": "Skill", "input": {"skill": "coreinfra-video"}} + except (AssertionError, KeyError, TypeError, ValueError) as error: + self.server.failure = str(error) or "Invalid catalog" + self.stream(block) + + def stream(self, block): + message = {"id": "msg_test", "type": "message", "role": "assistant", "model": MODEL, + "content": [], "stop_reason": None, "stop_sequence": None, + "usage": {"input_tokens": 12, "output_tokens": 0}} + if block["type"] == "tool_use": + start, delta = {**block, "input": {}}, {"type": "input_json_delta", "partial_json": json.dumps(block["input"])} + reason = "tool_use" + else: + start, delta = {"type": "text", "text": ""}, {"type": "text_delta", "text": block["text"]} + reason = "end_turn" + events = [ + {"type": "message_start", "message": message}, + {"type": "content_block_start", "index": 0, "content_block": start}, + {"type": "content_block_delta", "index": 0, "delta": delta}, + {"type": "content_block_stop", "index": 0}, + {"type": "message_delta", "delta": {"stop_reason": reason, "stop_sequence": None}, "usage": {"output_tokens": 8}}, + {"type": "message_stop"}, + ] + self.reply("text/event-stream", "".join(f"event: {e['type']}\ndata: {json.dumps(e)}\n\n" for e in events).encode()) + + def reply(self, mime, data): + self.send_response(200) + self.send_header("Content-Type", mime) + self.send_header("Content-Length", str(len(data))) + self.end_headers() + self.wfile.write(data) + + def log_message(self, *_): + pass + + +def run(profile, server): + skill = profile / "skills/coreinfra-video/SKILL.md" + source = Path(__file__).resolve().parents[3] / "plugins/coreinfra-video/skills/coreinfra-video/SKILL.md" + assert skill.read_text(encoding="utf-8") == source.read_text(encoding="utf-8") + server.skill_line = next(line for line in skill.read_text(encoding="utf-8").splitlines() if line.startswith("Use the ")) + server.models, server.failure = [], None + # Replace only chat inference. Claude loads the installed skill and user MCP from its normal profile. + settings_file = profile / "settings.json" + settings = json.loads(settings_file.read_text(encoding="utf-8")) + assert settings["env"]["ANTHROPIC_BASE_URL"] == "https://hub.coreinfra.ai/claude/api" + settings["env"]["ANTHROPIC_BASE_URL"] = f"http://127.0.0.1:{server.server_port}" + settings_file.write_text(json.dumps(settings), encoding="utf-8") + env = {k: v for k, v in os.environ.items() if not k.startswith(("ANTHROPIC_", "CLAUDE", "COREINFRA_", "WIZARD_"))} + home = profile.parent / "home" + home.mkdir() + env.update(HOME=str(home), USERPROFILE=str(home), CLAUDE_CONFIG_DIR=str(profile), + CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC="1", ENABLE_TOOL_SEARCH="false") + # Limit this catalog test to the two tools that the deterministic Messages provider requests. + command = [os.environ["WIZARD_VIDEO_TEST_CLAUDE"], "-p", "--no-session-persistence", "--model", MODEL, + "--tools", "Skill", "--allowedTools", TOOL, "--permission-mode", "dontAsk", + "--verbose", "--output-format", "stream-json", "--", "Какие видеомодели доступны в CoreInfra?"] + reply = subprocess.run(command, env=env, cwd=profile.parent, capture_output=True, text=True, encoding="utf-8", timeout=90) + assert reply.returncode == 0, (reply.stderr + reply.stdout)[-2000:] + events = [json.loads(line) for line in reply.stdout.splitlines()] + init = next(event for event in events if event.get("subtype") == "init") + assert "coreinfra-video" in init["skills"] and TOOL in init["tools"], "Installed skill or MCP missing in native Claude" + calls = [b["name"] for e in events if e["type"] == "assistant" for b in e["message"]["content"] if b["type"] == "tool_use"] + assert calls == ["Skill", TOOL], calls + assert server.failure is None, server.failure + assert server.models and server.models[0]["id"] in events[-1]["result"], "Empty catalog or missing model ID in reply" + print(f"Claude Code loaded /coreinfra-video and received {len(server.models)} video models.") + + +if __name__ == "__main__": + with ThreadingHTTPServer(("127.0.0.1", 0), Messages) as provider: + worker = threading.Thread(target=provider.serve_forever, daemon=True) + worker.start() + try: + run(Path(sys.argv[1]).resolve(), provider) + finally: + provider.shutdown() + worker.join() diff --git a/crates/wizard-gui/src/main.rs b/crates/wizard-gui/src/main.rs index 9a85bdf..60254c7 100644 --- a/crates/wizard-gui/src/main.rs +++ b/crates/wizard-gui/src/main.rs @@ -4,6 +4,26 @@ use std::process::ExitCode; fn main() -> ExitCode { + let mut args = std::env::args_os().skip(1); + if args.next().as_deref() == Some(wizard_core::video::stdio::ARG.as_ref()) { + let port = args + .next() + .and_then(|arg| arg.to_str()?.parse::().ok()); + let (Some(port), Some(path), None) = (port, args.next(), args.next()) else { + eprintln!("Expected the Wizard port and video headers file"); + return ExitCode::FAILURE; + }; + return match tauri::async_runtime::block_on(wizard_core::video::stdio::run( + port, + path.into(), + )) { + Ok(()) => ExitCode::SUCCESS, + Err(error) => { + eprintln!("Video MCP: {error:#}"); + ExitCode::FAILURE + } + }; + } if let Some(arg1) = std::env::args_os().nth(1) && arg1 == "--proxy" { diff --git a/crates/wizard-gui/wizard-ui/src/agents/AgentConfiguration.tsx b/crates/wizard-gui/wizard-ui/src/agents/AgentConfiguration.tsx index 9866f56..7f09368 100644 --- a/crates/wizard-gui/wizard-ui/src/agents/AgentConfiguration.tsx +++ b/crates/wizard-gui/wizard-ui/src/agents/AgentConfiguration.tsx @@ -339,6 +339,12 @@ export function RoutingFieldset({ ) )} + {agent === "claude" && selected === "hub" && ( + При применении настроек Wizard установит скилл /coreinfra-video и подключит видеомодели через MCP. + )} + {agent === "claude_desktop" && selected === "hub" && ( + После применения настроек Claude Desktop автоматически установит скилл CoreInfra Video. Для работы с видеомоделями оставьте Wizard открытым. + )}