multicast-workflows 2.0.0

Durable Code Mode workflows attached to multicast CLIs as first-party commands
Documentation
//! One process entry point that gives a CLI workflows and a Code Mode server.

use std::sync::Arc;

use multicast::cli::Cli;
use multicast_codemode::{CodeMode, MemoryStore, MulticastConnector};
use multicast_codemode_local::{LocalCodeModeService, LocalExecutor};

use crate::Workflows;

/// The only argument that starts the Code Mode MCP server over stdio.
pub const CODEMODE_FLAG: &str = "--codemode";

/// Returns whether `argv` (without the program name) requests the Code Mode
/// server: exactly [`CODEMODE_FLAG`] and nothing else.
pub fn is_codemode_request(argv: &[String]) -> bool {
    matches!(argv, [flag] if flag == CODEMODE_FLAG)
}

/// Starts a Code Mode service whose only connector is the CLI's own commands.
///
/// Executions are held in memory, so several agent sessions can each run a
/// server for the same CLI at once; an execution does not survive its server.
/// Workflows keep their own durable store.
pub fn codemode_service(cli: &Cli) -> Result<LocalCodeModeService, String> {
    codemode_service_with_limits(cli, multicast_codemode::WorkflowLimits::default(), false)
}
fn codemode_service_with_limits(
    cli: &Cli,
    limits: multicast_codemode::WorkflowLimits,
    approve_local: bool,
) -> Result<LocalCodeModeService, String> {
    limits.check()?;
    let catalog = cli.try_tool_catalog().map_err(|error| error.to_string())?;
    let connector = MulticastConnector::new(catalog);
    // Honor Workflows::approve_local_commands here too, so the stdio Code Mode
    // server and `workflows exec` agree on which commands pause.
    let connector = Arc::new(if approve_local {
        connector.with_policy_resolver(Arc::new(crate::LocalApproval))
    } else {
        connector
    });
    LocalCodeModeService::spawn(move || {
        CodeMode::new(
            Arc::new(MemoryStore::default()),
            LocalExecutor::default(),
            vec![connector],
        )
        .with_workflow_limits(limits)
        .expect("validated limits on unshared runtime")
    })
}

/// Serves a CLI from process argv with workflows attached.
///
/// `cli --codemode` serves the five Code Mode lifecycle tools over stdio,
/// calling the CLI's commands. Every other invocation attaches the default
/// [`Workflows`] and runs [`Cli::serve`], so `--mcp`, `--llms`, and ordinary
/// commands behave as before plus the `workflows` group.
pub async fn serve(cli: Cli) -> Result<(), Box<dyn std::error::Error>> {
    serve_attached(cli, Workflows::new()).await
}

/// Method form of [`serve`], so a CLI's entry point changes one word:
/// `cli.serve().await` becomes `cli.serve_workflows().await`.
pub trait ServeWorkflows {
    /// Serves this CLI as [`serve`] does.
    fn serve_workflows(
        self,
    ) -> impl std::future::Future<Output = Result<(), Box<dyn std::error::Error>>>;
}

impl ServeWorkflows for Cli {
    fn serve_workflows(
        self,
    ) -> impl std::future::Future<Output = Result<(), Box<dyn std::error::Error>>> {
        serve(self)
    }
}

/// [`serve`] with an author-configured [`Workflows`] builder.
pub async fn serve_attached(
    cli: Cli,
    workflows: Workflows,
) -> Result<(), Box<dyn std::error::Error>> {
    let argv: Vec<String> = std::env::args().skip(1).collect();
    if is_codemode_request(&argv) {
        let service =
            codemode_service_with_limits(&cli, workflows.limits.clone(), workflows.approve_local)?;
        use multicast_codemode::CodeModeService as _;
        let definitions = workflows
            .shipped
            .iter()
            .map(|w| {
                (
                    w.name.clone(),
                    multicast_codemode::WorkflowDefinition {
                        source: multicast_codemode::normalize_code(&w.code),
                        input: w.input_schema.clone(),
                        output: serde_json::Value::Bool(true),
                        bindings: serde_json::json!({}),
                    },
                )
            })
            .collect();
        service.install_workflows(definitions).await?;
        multicast_codemode_mcp::serve_stdio_with(
            Arc::new(service),
            cli.mcp_serve_options().custom_methods.clone(),
        )
        .await?;
        return Ok(());
    }
    workflows.attach(cli)?.serve().await
}

#[cfg(all(test, feature = "native", not(target_arch = "wasm32")))]
mod tests {
    use super::*;
    use multicast::command::{
        CommandContext, CommandDef, CommandHandler, McpAnnotations, McpCommandOptions,
    };
    use multicast::output::CommandResult;
    use multicast_codemode::CodeModeService as _;

    struct Act;
    #[async_trait::async_trait]
    impl CommandHandler for Act {
        async fn run(&self, _: CommandContext) -> CommandResult {
            CommandResult::Ok {
                data: serde_json::json!(1),
                exit_code: None,
                cta: None,
            }
        }
    }

    fn cli() -> Cli {
        Cli::create("host").command(
            "act",
            CommandDef::build("act", Act)
                .mcp(McpCommandOptions {
                    annotations: Some(McpAnnotations {
                        read_only_hint: Some(false),
                        destructive_hint: Some(true),
                        ..Default::default()
                    }),
                    ..Default::default()
                })
                .done(),
        )
    }

    async fn act_needs_approval(approve_local: bool) -> bool {
        let service = codemode_service_with_limits(
            &cli(),
            multicast_codemode::WorkflowLimits::default(),
            approve_local,
        )
        .unwrap();
        let found = service.search("act".into()).await.unwrap();
        found
            .results
            .iter()
            .find(|r| r.method == "act")
            .expect("act listed")
            .requires_approval
    }

    #[tokio::test]
    async fn stdio_server_honors_approve_local_commands() {
        assert!(!act_needs_approval(true).await);
        assert!(act_needs_approval(false).await);
    }
}