multicast-workflows 2.0.0

Durable Code Mode workflows attached to multicast CLIs as first-party commands
Documentation
//! Host adapter for durable authenticated-event admission and interval polling.
//!
//! Pass `enqueue REQUEST_JSON`, `schedule SCHEDULE_JSON`, `tick`, or
//! `receipt SOURCE KEY`. Other arguments enter the ordinary workflow CLI.
//! A real webhook adapter authenticates and authorizes before calling enqueue.
//! `TRIGGER_STORE` selects the store; `TRIGGER_CALL_LOG` records observed calls.

use multicast::cli::{Cli, Runtime};
use multicast::command::{
    CommandContext, CommandDef, CommandHandler, McpAnnotations, McpCommandOptions,
};
use multicast::output::CommandResult;
use multicast_workflows::Workflows;
use serde_json::json;
use std::io::Write;

struct Observe(&'static str);

#[async_trait::async_trait]
impl CommandHandler for Observe {
    async fn run(&self, _: CommandContext) -> CommandResult {
        if let Ok(path) = std::env::var("TRIGGER_CALL_LOG") {
            let mut file = std::fs::OpenOptions::new()
                .create(true)
                .append(true)
                .open(path)
                .unwrap();
            writeln!(file, "{}", self.0).unwrap();
            file.sync_all().unwrap();
        }
        if self.0 == "slow"
            || (self.0 == "write" && std::env::var_os("TRIGGER_HOLD_REPLY").is_some())
        {
            std::future::pending::<()>().await;
        }
        CommandResult::Ok {
            data: json!(73),
            cta: None,
            exit_code: None,
        }
    }
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut cli = Cli::create("trigger");
    for (name, safe) in [("observe", true), ("commit", false), ("wait", true)] {
        let label = match name {
            "observe" => "read",
            "commit" => "write",
            _ => "slow",
        };
        cli = cli.command(
            name,
            CommandDef::build(name, Observe(label))
                .mcp(McpCommandOptions {
                    annotations: Some(McpAnnotations {
                        read_only_hint: Some(safe),
                        destructive_hint: Some(false),
                        open_world_hint: Some(false),
                        ..Default::default()
                    }),
                    ..Default::default()
                })
                .done(),
        );
    }
    let store =
        std::env::var("TRIGGER_STORE").unwrap_or_else(|_| "trigger-workflows.sqlite".into());
    let (cli, triggers) = Workflows::new()
        .store_path(store)
        .shipped(
            "read-job",
            "Observe a value",
            json!({"type":"object"}),
            "async () => trigger.observe({})",
        )
        .shipped(
            "write-job",
            "Commit a value after approval",
            json!({"type":"object"}),
            "async () => trigger.commit({})",
        )
        .shipped(
            "slow-job",
            "Wait until cancelled",
            json!({"type":"object"}),
            "async () => trigger.wait({})",
        )
        .attach_with_triggers(cli)?;
    let args = std::env::args().skip(1).collect::<Vec<_>>();
    let value = match args.first().map(String::as_str) {
        Some("enqueue") => serde_json::to_value(
            triggers
                .enqueue(serde_json::from_str(
                    args.get(1).ok_or("Missing request JSON")?,
                )?)
                .await?,
        )?,
        Some("schedule") => {
            triggers
                .schedule(serde_json::from_str(
                    args.get(1).ok_or("Missing schedule JSON")?,
                )?)
                .await?;
            json!({"scheduled":true})
        }
        Some("tick") => serde_json::to_value(triggers.tick(10).await?)?,
        Some("receipt") => serde_json::to_value(triggers.receipt(
            args.get(1).ok_or("Missing source")?,
            args.get(2).ok_or("Missing key")?,
        )?)?,
        _ => {
            let code = cli
                .run_to(
                    args,
                    &mut std::io::stdout(),
                    Runtime::process("trigger", false),
                )
                .await?;
            return if code.unwrap_or(0) == 0 {
                Ok(())
            } else {
                Err("Command failed".into())
            };
        }
    };
    println!("{value}");
    Ok(())
}