mod archetypes;
pub use archetypes::ARCHETYPES_GROUP_NAME;
mod authority;
pub use authority::{WorkflowAuthority, WorkflowBindings};
mod database;
mod diagnostics;
mod fixtures;
mod host;
mod ledger;
mod schema;
#[cfg(all(feature = "native", not(target_arch = "wasm32")))]
mod serve;
mod triggers;
use std::collections::BTreeMap;
use std::path::PathBuf;
use std::sync::{Arc, OnceLock};
use std::time::Duration;
use async_trait::async_trait;
use multicast::cli::Cli;
use multicast::command::{
CommandContext, CommandDef, CommandHandler, McpAnnotations, McpCommandOptions,
};
use multicast::output::CommandResult;
use multicast::schema::{FieldMeta, FieldType};
use multicast::tool::ToolCatalog;
#[cfg(all(feature = "native", not(target_arch = "wasm32")))]
use multicast_codemode::MulticastConnector;
use multicast_codemode::{
CodeModeRunOptions, CodeModeService, ExecutionState, ExecutionStatus, LogEntryState,
RetryPolicy, Snippet, normalize_code, sanitize_namespace,
};
#[cfg(all(feature = "native", not(target_arch = "wasm32")))]
use multicast_codemode_local::LocalExecutorOptions;
use serde_json::{Map, Value, json};
use tokio::sync::OnceCell;
pub use database::{WorkflowDatabase, WorkflowSql};
pub use fixtures::{FixtureCall, FixtureContract, MAX_FIXTURE_BYTES, WorkflowFixture};
pub use host::{WorkflowDatabaseKind, WorkflowHost};
pub use multicast_codemode::WorkflowLimits;
pub use schema::{check_supported as check_schema, validate as validate_input};
#[cfg(all(feature = "native", not(target_arch = "wasm32")))]
pub use serve::{
CODEMODE_FLAG, ServeWorkflows, codemode_service, is_codemode_request, serve, serve_attached,
};
pub use triggers::{TriggerReceipt, TriggerRequest, TriggerSchedule, WorkflowTriggers};
pub const PAUSED_EXIT_CODE: i32 = 75;
fn still_working(state: &ExecutionState) -> bool {
match state.status {
ExecutionStatus::Running => true,
ExecutionStatus::Paused => {
state.workflow_wait.is_some()
&& state
.workflow_children
.iter()
.all(|child| child.pending.is_empty())
}
_ => false,
}
}
pub const GROUP_NAME: &str = "workflows";
const POLL_INTERVAL: Duration = Duration::from_millis(20);
#[cfg(all(feature = "native", not(target_arch = "wasm32")))]
pub fn default_store_path(cli_name: &str) -> PathBuf {
let data_home = std::env::var("XDG_DATA_HOME")
.ok()
.filter(|value| !value.is_empty())
.map(PathBuf::from)
.unwrap_or_else(|| {
dirs::home_dir()
.unwrap_or_default()
.join(".local")
.join("share")
});
data_home
.join("incurs")
.join(cli_name)
.join("workflows.sqlite")
}
#[derive(Debug, Clone)]
struct ShippedWorkflow {
name: String,
description: String,
input_schema: Value,
code: String,
}
#[derive(Debug, Clone, Default)]
pub struct Workflows {
shipped: Vec<ShippedWorkflow>,
archetypes: Vec<archetypes::ShippedArchetype>,
store_path: Option<PathBuf>,
retry: RetryPolicy,
limits: multicast_codemode::WorkflowLimits,
approve_local: bool,
}
impl Workflows {
pub fn new() -> Self {
Self::default()
}
pub fn with_workflow_limits(
mut self,
limits: multicast_codemode::WorkflowLimits,
) -> Result<Self, String> {
limits.check()?;
self.limits = limits;
Ok(self)
}
pub fn shipped(
mut self,
name: impl Into<String>,
description: impl Into<String>,
input_schema: Value,
code: impl Into<String>,
) -> Self {
self.shipped.push(ShippedWorkflow {
name: name.into(),
description: description.into(),
input_schema,
code: code.into(),
});
self
}
pub fn archetype<I, S>(
mut self,
name: impl Into<String>,
summary: impl Into<String>,
instructions: impl Into<String>,
scope: I,
) -> Self
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
self.archetypes.push(archetypes::ShippedArchetype {
name: name.into(),
summary: summary.into(),
instructions: instructions.into(),
scope: scope.into_iter().map(Into::into).collect(),
});
self
}
pub fn store_path(mut self, path: impl Into<PathBuf>) -> Self {
self.store_path = Some(path.into());
self
}
pub fn retry_policy(mut self, policy: RetryPolicy) -> Self {
self.retry = policy;
self
}
pub fn approve_local_commands(mut self) -> Self {
self.approve_local = true;
self
}
pub fn attach(self, cli: Cli) -> Result<Cli, String> {
self.attach_with_triggers(cli).map(|(cli, _)| cli)
}
pub fn attach_with_triggers(self, cli: Cli) -> Result<(Cli, WorkflowTriggers), String> {
self.attach_inner(cli, None)
}
pub fn attach_hosted(
self,
cli: Cli,
host: Arc<dyn WorkflowHost>,
) -> Result<(Cli, WorkflowTriggers), String> {
self.attach_inner(cli, Some(host))
}
fn attach_inner(
self,
cli: Cli,
host: Option<Arc<dyn WorkflowHost>>,
) -> Result<(Cli, WorkflowTriggers), String> {
let catalog = cli.try_tool_catalog().map_err(|error| error.to_string())?;
let cli_name = catalog.name().to_string();
let namespace = sanitize_namespace(&cli_name);
for group_name in [GROUP_NAME, ARCHETYPES_GROUP_NAME] {
if cli.has_command(group_name) {
return Err(format!(
"CLI '{cli_name}' already has a '{group_name}' command"
));
}
}
let mut shipped = BTreeMap::new();
for workflow in &self.shipped {
if workflow.name == GROUP_NAME
|| workflow.name == ARCHETYPES_GROUP_NAME
|| cli.has_command(&workflow.name)
{
return Err(format!(
"Workflow '{}' collides with an existing command",
workflow.name
));
}
if shipped.contains_key(&workflow.name) {
return Err(format!("Workflow '{}' is shipped twice", workflow.name));
}
check_object_schema(&workflow.input_schema)
.map_err(|error| format!("Workflow '{}': {error}", workflow.name))?;
for method in referenced_methods(&workflow.code, &namespace) {
if catalog.get(&method).is_none() {
return Err(format!(
"Workflow '{}' calls {namespace}.{method}, which is not a command of '{cli_name}'",
workflow.name
));
}
}
shipped.insert(workflow.name.clone(), workflow.clone());
}
let mut shipped_archetypes = BTreeMap::new();
for archetype in &self.archetypes {
let name = &archetype.name;
if name == GROUP_NAME
|| name == ARCHETYPES_GROUP_NAME
|| cli.has_command(name)
|| shipped.contains_key(name)
{
return Err(format!(
"Archetype '{name}' collides with an existing command"
));
}
if shipped_archetypes.contains_key(name) {
return Err(format!("Archetype '{name}' is shipped twice"));
}
archetypes::check_definition(
name,
&archetype.summary,
&archetype.instructions,
&archetype.scope,
)?;
shipped_archetypes.insert(name.clone(), archetype.clone());
}
for archetype in shipped_archetypes.values() {
for entry in &archetype.scope {
if shipped_archetypes.contains_key(entry) {
return Err(format!(
"Archetype '{}' scopes archetype '{entry}'; an archetype scopes commands and workflows only",
archetype.name
));
}
if catalog.get(entry).is_none() && !shipped.contains_key(entry) {
return Err(format!(
"Archetype '{}' scopes '{entry}', which is not a command or shipped workflow of '{cli_name}'",
archetype.name
));
}
}
}
let store_path = if host.is_some() {
PathBuf::new()
} else {
#[cfg(all(feature = "native", not(target_arch = "wasm32")))]
{
self.store_path
.unwrap_or_else(|| default_store_path(&cli_name))
}
#[cfg(not(all(feature = "native", not(target_arch = "wasm32"))))]
{
return Err("A workflow host is required; use Workflows::attach_hosted".into());
}
};
let state = Arc::new(State {
catalog,
host,
store_path,
shipped,
archetypes: shipped_archetypes,
archetype_store: OnceLock::new(),
retry: self.retry,
limits: self.limits,
approve_local: self.approve_local,
service: OnceCell::new(),
ledger: OnceLock::new(),
});
let mut cli = cli;
for workflow in self.shipped {
let options_fields = schema_fields(&workflow.input_schema);
let mut def = CommandDef::build(
workflow.name.clone(),
ShippedHandler {
state: state.clone(),
name: workflow.name.clone(),
},
)
.description(workflow.description.clone())
.mcp_input_schema(workflow.input_schema.clone())
.done();
def.options_fields = options_fields;
cli = cli.command(workflow.name, def);
}
for archetype in &self.archetypes {
cli = cli
.command(
archetype.name.clone(),
archetypes::shipped_command(state.clone(), archetype),
)
.prompt_guide(multicast::prompt::PromptGuide::new(
archetype.name.clone(),
archetype.summary.clone(),
archetype.instructions.clone(),
archetype.scope.clone(),
));
}
let triggers = WorkflowTriggers::new(state.clone());
Ok((
cli.group(group(state.clone()))
.group(archetypes::group(state)),
triggers,
))
}
}
fn check_object_schema(schema: &Value) -> Result<(), String> {
check_schema(schema).map_err(|errors| errors.join("; "))?;
if schema.get("type").and_then(Value::as_str) != Some("object") {
return Err("input schema must have type 'object'".into());
}
Ok(())
}
fn referenced_methods(code: &str, namespace: &str) -> Vec<String> {
let mut methods = Vec::new();
let bytes = code.as_bytes();
let mut start = 0;
while let Some(offset) = code[start..].find(namespace) {
let index = start + offset;
start = index + namespace.len();
let before = code[..index].chars().next_back();
if before.is_some_and(|ch| is_identifier_char(ch) || ch == '.') {
continue;
}
let rest = &code[start..];
if let Some(after_dot) = rest.strip_prefix('.') {
let method: String = after_dot
.chars()
.take_while(|ch| is_identifier_char(*ch))
.collect();
if !method.is_empty() {
methods.push(method);
}
} else if let Some(after_bracket) = rest.strip_prefix('[') {
let Some(quote) = after_bracket
.chars()
.next()
.filter(|ch| *ch == '"' || *ch == '\'')
else {
continue;
};
let literal = &after_bracket[1..];
if let Some(end) = literal.find(quote)
&& literal[end + 1..].starts_with(']')
{
methods.push(literal[..end].to_string());
}
}
let _ = bytes;
}
methods
}
fn is_identifier_char(ch: char) -> bool {
ch == '_' || ch == '$' || ch.is_alphanumeric()
}
fn schema_fields(schema: &Value) -> Vec<FieldMeta> {
let required: Vec<&str> = schema
.get("required")
.and_then(Value::as_array)
.map(|names| names.iter().filter_map(Value::as_str).collect())
.unwrap_or_default();
schema
.get("properties")
.and_then(Value::as_object)
.map(|properties| {
properties
.iter()
.map(|(name, property)| {
let field_type = match primary_type(property) {
Some("boolean") => FieldType::Boolean,
Some("integer" | "number") => FieldType::Number,
Some("array") => FieldType::Array(Box::new(FieldType::Value)),
Some("object") => FieldType::Value,
_ => FieldType::String,
};
let mut meta = field(
name,
field_type,
required.contains(&name.as_str()),
property.get("description").and_then(Value::as_str),
);
meta.default = property.get("default").cloned();
meta
})
.collect()
})
.unwrap_or_default()
}
fn primary_type(schema: &Value) -> Option<&str> {
match schema.get("type")? {
Value::String(name) => Some(name),
Value::Array(names) => names
.iter()
.filter_map(Value::as_str)
.find(|name| *name != "null"),
_ => None,
}
}
fn field(
name: &str,
field_type: FieldType,
required: bool,
description: Option<&str>,
) -> FieldMeta {
let name: &'static str = Box::leak(name.to_string().into_boxed_str());
FieldMeta {
name,
cli_name: multicast::schema::to_kebab(name),
description: description.map(|text| &*Box::leak(text.to_string().into_boxed_str())),
field_type,
required,
default: None,
alias: None,
deprecated: false,
env_name: None,
}
}
struct State {
catalog: ToolCatalog,
#[cfg_attr(
not(all(feature = "native", not(target_arch = "wasm32"))),
allow(dead_code)
)]
store_path: PathBuf,
shipped: BTreeMap<String, ShippedWorkflow>,
archetypes: BTreeMap<String, archetypes::ShippedArchetype>,
archetype_store: OnceLock<Result<archetypes::ArchetypeStore, String>>,
retry: RetryPolicy,
limits: multicast_codemode::WorkflowLimits,
approve_local: bool,
host: Option<Arc<dyn WorkflowHost>>,
service: OnceCell<Arc<dyn CodeModeService>>,
ledger: OnceLock<Option<ledger::Ledger>>,
}
struct Resolved {
name: String,
description: String,
origin: &'static str,
input_schema: Option<Value>,
code: String,
}
impl Resolved {
fn version(&self) -> String {
ledger::version(&self.code, self.input_schema.as_ref())
}
fn summary(&self) -> Value {
json!({
"name": self.name,
"description": self.description,
"origin": self.origin,
"version": self.version(),
"inputSchema": self.input_schema,
})
}
}
struct RunTag {
workflow: String,
origin: &'static str,
version: String,
}
impl State {
async fn service(&self) -> Result<&dyn CodeModeService, String> {
self.service
.get_or_try_init(|| async {
let service: Arc<dyn CodeModeService> = if let Some(host) = &self.host {
host.service_with_limits(self.catalog.clone(), self.retry, self.limits.clone())
} else {
#[cfg(all(feature = "native", not(target_arch = "wasm32")))]
{
if let Some(parent) = self.store_path.parent() {
std::fs::create_dir_all(parent).map_err(|error| {
format!("Cannot create workflow store directory: {error}")
})?;
}
let service = multicast_codemode_local::spawn_codemode_with_limits(
&self.store_path,
LocalExecutorOptions::default(),
vec![Arc::new({
let connector = MulticastConnector::new(self.catalog.clone())
.with_retry_policy(self.retry);
if self.approve_local {
connector.with_policy_resolver(Arc::new(LocalApproval))
} else {
connector
}
})],
self.limits.clone(),
)?;
Ok(Arc::new(service) as Arc<dyn CodeModeService>)
}
#[cfg(not(all(feature = "native", not(target_arch = "wasm32"))))]
{
Err("A workflow host is required".into())
}
}?;
let definitions = self
.shipped
.iter()
.map(|(name, w)| {
(
name.clone(),
multicast_codemode::WorkflowDefinition {
source: multicast_codemode::normalize_code(&w.code),
input: w.input_schema.clone(),
output: Value::Bool(true),
bindings: serde_json::json!({}),
},
)
})
.collect();
service.install_workflows(definitions).await?;
Ok(service)
})
.await
.map(Arc::as_ref)
}
async fn sleep(&self, milliseconds: u64) {
if let Some(host) = &self.host {
host.sleep(milliseconds).await;
return;
}
#[cfg(all(feature = "native", not(target_arch = "wasm32")))]
tokio::time::sleep(Duration::from_millis(milliseconds)).await;
}
async fn settle(
&self,
service: &dyn CodeModeService,
mut state: ExecutionState,
) -> Result<ExecutionState, String> {
while still_working(&state) {
self.sleep(POLL_INTERVAL.as_millis() as u64).await;
state = service.execution(state.id.clone()).await?;
}
Ok(state)
}
fn ledger(&self) -> Option<&ledger::Ledger> {
self.ledger
.get_or_init(|| {
let opened = if let Some(host) = &self.host {
host.database(WorkflowDatabaseKind::Ledger)
.and_then(ledger::Ledger::from_database)
} else {
#[cfg(all(feature = "native", not(target_arch = "wasm32")))]
{
let path = ledger::ledger_path(&self.store_path);
path.parent()
.map_or(Ok(()), std::fs::create_dir_all)
.map_err(|error| {
format!("Cannot create workflow ledger directory: {error}")
})
.and_then(|()| ledger::Ledger::open(&path))
}
#[cfg(not(all(feature = "native", not(target_arch = "wasm32"))))]
{
Err("A workflow host is required".into())
}
};
match opened {
Ok(ledger) => Some(ledger),
Err(message) => {
eprintln!("warning: workflow ledger unavailable: {message}");
None
}
}
})
.as_ref()
}
fn record(&self, state: &ExecutionState) {
if let Some(ledger) = self.ledger() {
warn_ledger(ledger.record(state, state.updated_at));
}
}
async fn catalog_workflows(&self) -> Result<Vec<Resolved>, String> {
let mut workflows: Vec<Resolved> = self.shipped.values().map(shipped_resolved).collect();
for snippet in self.service().await?.snippets().await? {
if !self.shipped.contains_key(&snippet.name) {
workflows.push(saved_resolved(snippet));
}
}
Ok(workflows)
}
async fn resolve(&self, name: &str) -> Result<Option<Resolved>, String> {
if let Some(workflow) = self.shipped.get(name) {
return Ok(Some(shipped_resolved(workflow)));
}
let snippets = self.service().await?.snippets().await?;
Ok(snippets
.into_iter()
.find(|snippet| snippet.name == name)
.map(saved_resolved))
}
async fn run(&self, workflow: &Resolved, input: Value, ctx: &CommandContext) -> CommandResult {
let code = match program(workflow, input) {
Ok((_, code)) => code,
Err(message) => return error("INVALID_INPUT", message),
};
let tag = RunTag {
workflow: workflow.name.clone(),
origin: workflow.origin,
version: workflow.version(),
};
self.start(code, Some(tag), ctx).await
}
async fn start(
&self,
code: String,
tag: Option<RunTag>,
ctx: &CommandContext,
) -> CommandResult {
let result = async {
let service = self.service().await?;
let mut options = run_options(ctx);
options.workflow = tag
.as_ref()
.map(|tag| multicast_codemode::WorkflowIdentity {
name: tag.workflow.clone(),
version: tag.version.clone(),
});
let state = service.execute(code, options).await?;
if !result_only(ctx) {
eprintln!("workflow execution {} started", state.id);
}
if let Some(tag) = &tag
&& let Some(ledger) = self.ledger()
{
warn_ledger(ledger.start(&ledger::RunStart {
execution_id: &state.id,
workflow: &tag.workflow,
origin: tag.origin,
version: &tag.version,
at: state.created_at,
}));
}
let state = self.settle(service, state).await?;
self.record(&state);
Ok::<_, String>(state)
}
.await;
match result {
Ok(state) if result_only(ctx) && state.status == ExecutionStatus::Completed => {
ok(state.result.clone().unwrap_or(Value::Null))
}
Ok(state) => outcome(&state),
Err(message) => error("WORKFLOW_HOST_ERROR", message),
}
}
}
fn program(workflow: &Resolved, input: Value) -> Result<(Value, String), String> {
let input = match &workflow.input_schema {
Some(schema) => {
let input = normalize_input(schema, input);
validate_input(schema, &input).map_err(|errors| {
format!(
"Invalid input for workflow '{}': {}",
workflow.name,
errors.join("; ")
)
})?;
input
}
None => input,
};
let code = format!(
"async () => {{ const input = {input}; return await ({})(input); }}",
normalize_code(&workflow.code)
);
Ok((input, code))
}
fn warn_ledger(result: Result<(), String>) {
if let Err(message) = result {
eprintln!("warning: {message}");
}
}
fn shipped_resolved(workflow: &ShippedWorkflow) -> Resolved {
Resolved {
name: workflow.name.clone(),
description: workflow.description.clone(),
origin: "shipped",
input_schema: Some(workflow.input_schema.clone()),
code: workflow.code.clone(),
}
}
fn saved_resolved(snippet: Snippet) -> Resolved {
Resolved {
name: snippet.name,
description: snippet.description,
origin: "saved",
input_schema: snippet.input_schema,
code: snippet.code,
}
}
fn run_options(ctx: &CommandContext) -> CodeModeRunOptions {
CodeModeRunOptions {
request: ctx.request.clone(),
..CodeModeRunOptions::default()
}
}
fn normalize_input(schema: &Value, input: Value) -> Value {
let Value::Object(fields) = input else {
return input;
};
let properties = schema.get("properties").and_then(Value::as_object);
let required: Vec<&str> = schema
.get("required")
.and_then(Value::as_array)
.map(|names| names.iter().filter_map(Value::as_str).collect())
.unwrap_or_default();
let mut normalized = Map::new();
for (name, value) in fields {
let property = properties.and_then(|properties| properties.get(&name));
let Some(property) = property else {
normalized.insert(name, value);
continue;
};
if value.is_null() && !required.contains(&name.as_str()) && !accepts_null(property) {
continue;
}
normalized.insert(name, coerce(property, value));
}
Value::Object(normalized)
}
fn coerce(schema: &Value, value: Value) -> Value {
match (primary_type(schema), value) {
(Some("object" | "array"), Value::String(text)) => {
serde_json::from_str(&text).unwrap_or(Value::String(text))
}
(Some("array"), Value::Array(items)) => {
let item_schema = schema.get("items");
let parse = item_schema
.and_then(primary_type)
.is_some_and(|item_type| item_type != "string");
Value::Array(
items
.into_iter()
.map(|item| match item {
Value::String(text) if parse => {
serde_json::from_str(&text).unwrap_or(Value::String(text))
}
other => other,
})
.collect(),
)
}
(_, value) => value,
}
}
fn accepts_null(schema: &Value) -> bool {
match schema.get("type") {
Some(Value::String(name)) => name == "null",
Some(Value::Array(names)) => names.iter().any(|name| name == "null"),
_ => true,
}
}
fn pending(state: &ExecutionState) -> Vec<Value> {
let mut actions:Vec<Value>=state.log.iter().filter(|entry|entry.state==LogEntryState::Pending && entry.requires_approval).map(|entry|json!({"seq":entry.seq,"method":format!("{}.{}",entry.connector,entry.method),"arguments":entry.arguments})).collect();
for child in &state.workflow_children {
for seq in &child.pending {
actions.push(json!({"executionId":child.id,"seq":seq}));
}
}
actions
}
fn result_only(ctx: &CommandContext) -> bool {
ctx.options
.get("result_only")
.and_then(Value::as_bool)
.unwrap_or(false)
}
fn outcome(state: &ExecutionState) -> CommandResult {
let id = &state.id;
match state.status {
ExecutionStatus::Completed => {
let mut data = json!({
"executionId": id,
"status": "completed",
"result": state.result.clone().unwrap_or(Value::Null),
});
if !state.workflow_children.is_empty() {
data["children"] = json!(state.workflow_children);
}
ok(data)
}
ExecutionStatus::Paused => CommandResult::Ok {
data: json!({
"executionId": id,
"status": "paused",
"pending": pending(state),
"children":state.workflow_children,
"childWait":state.workflow_wait,
"error": state.error,
"recoveryRequired": state.log.iter().any(|entry| entry.state == LogEntryState::Executing),
}),
cta: None,
exit_code: Some(PAUSED_EXIT_CODE),
},
ExecutionStatus::Running => ok(json!({"executionId": id, "status": "running"})),
ExecutionStatus::Error => error(
"WORKFLOW_FAILED",
format!(
"Workflow execution {id} failed: {}",
state.error.as_deref().unwrap_or("unknown error")
),
),
ExecutionStatus::Rejected => error(
"WORKFLOW_REJECTED",
format!("Workflow execution {id} was rejected"),
),
ExecutionStatus::Cancelled => error(
"WORKFLOW_CANCELLED",
format!("Workflow execution {id} was cancelled"),
),
ExecutionStatus::RolledBack => error(
"WORKFLOW_ROLLED_BACK",
format!("Workflow execution {id} was rolled back"),
),
}
}
fn ok(data: Value) -> CommandResult {
CommandResult::Ok {
data,
cta: None,
exit_code: None,
}
}
fn error(code: &str, message: impl Into<String>) -> CommandResult {
CommandResult::Error {
code: code.into(),
message: message.into(),
retryable: false,
exit_code: None,
cta: None,
}
}
fn result_only_field() -> FieldMeta {
field(
"result_only",
FieldType::Boolean,
false,
Some("Return only the completed value; pauses and failures retain diagnostics"),
)
}
fn string_arg<'a>(values: &'a Value, name: &str) -> Option<&'a str> {
values.get(name).and_then(Value::as_str)
}
fn json_option(values: &Value, name: &str) -> Result<Option<Value>, String> {
match values.get(name) {
None | Some(Value::Null) => Ok(None),
Some(Value::String(text)) => serde_json::from_str(text)
.map(Some)
.map_err(|error| format!("--{name} is not valid JSON: {error}")),
Some(value) => Ok(Some(value.clone())),
}
}
struct ShippedHandler {
state: Arc<State>,
name: String,
}
#[async_trait]
impl CommandHandler for ShippedHandler {
async fn run(&self, ctx: CommandContext) -> CommandResult {
let Some(workflow) = self.state.shipped.get(&self.name) else {
return error("WORKFLOW_NOT_FOUND", format!("No workflow '{}'", self.name));
};
let input = match &ctx.options {
Value::Object(_) => ctx.options.clone(),
_ => json!({}),
};
self.state
.run(&shipped_resolved(workflow), input, &ctx)
.await
}
}
#[derive(Clone, Copy)]
enum Action {
List,
Show,
Run,
Exec,
Save,
Publish,
Delete,
Approve,
Reject,
Resume,
Cancel,
Status,
Doctor,
Stats,
Failures,
Trace,
Capture,
Check,
}
struct GroupHandler {
state: Arc<State>,
action: Action,
}
#[async_trait]
impl CommandHandler for GroupHandler {
async fn run(&self, ctx: CommandContext) -> CommandResult {
match self.dispatch(&ctx).await {
Ok(result) => result,
Err(message) => error("WORKFLOW_HOST_ERROR", message),
}
}
}
impl GroupHandler {
async fn dispatch(&self, ctx: &CommandContext) -> Result<CommandResult, String> {
let state = &self.state;
let args = &ctx.args;
let options = &ctx.options;
Ok(match self.action {
Action::List => ok(Value::Array(
state
.catalog_workflows()
.await?
.iter()
.map(Resolved::summary)
.collect(),
)),
Action::Show => {
let name = string_arg(args, "name").unwrap_or_default();
match state.resolve(name).await? {
Some(workflow) => {
let mut data = workflow.summary();
data["code"] = Value::String(workflow.code);
ok(data)
}
None => not_found(name),
}
}
Action::Run => {
let name = string_arg(args, "name").unwrap_or_default();
let input = match json_option(options, "input") {
Ok(input) => input.unwrap_or_else(|| json!({})),
Err(message) => return Ok(error("INVALID_INPUT", message)),
};
match state.resolve(name).await? {
Some(workflow) => state.run(&workflow, input, ctx).await,
None => not_found(name),
}
}
Action::Exec => {
let code = string_arg(args, "code").unwrap_or_default().to_string();
state.start(code, None, ctx).await
}
Action::Save | Action::Publish => {
let name = string_arg(args, "name").unwrap_or_default();
if state.shipped.contains_key(name) {
return Ok(error(
"WORKFLOW_SHIPPED",
format!("'{name}' is a shipped workflow and cannot be replaced"),
));
}
let input_schema = match json_option(options, "input_schema") {
Ok(schema) => schema,
Err(message) => return Ok(error("INVALID_SCHEMA", message)),
};
if let Some(schema) = &input_schema
&& let Err(errors) = check_schema(schema)
{
return Ok(error("INVALID_SCHEMA", errors.join("; ")));
}
if matches!(self.action, Action::Publish) {
let code = string_arg(options, "code").unwrap_or_default();
if name.trim().is_empty() || code.trim().is_empty() {
return Ok(error(
"INVALID_WORKFLOW",
"Name and callable code must not be empty",
));
}
let description = string_arg(options, "description").unwrap_or_default();
let snippet = state
.service()
.await?
.publish_snippet(
name.to_string(),
description.to_string(),
code.to_string(),
input_schema,
)
.await?;
return Ok(ok(saved_resolved(snippet).summary()));
}
let from = string_arg(options, "from").unwrap_or_default();
let description = string_arg(options, "description").unwrap_or_default();
let snippet = state
.service()
.await?
.save_snippet(
name.to_string(),
description.to_string(),
from.to_string(),
input_schema,
)
.await?;
ok(saved_resolved(snippet).summary())
}
Action::Delete => {
let name = string_arg(args, "name").unwrap_or_default();
if state.shipped.contains_key(name) {
return Ok(error(
"WORKFLOW_SHIPPED",
format!("'{name}' is a shipped workflow and cannot be deleted"),
));
}
let deleted = state
.service()
.await?
.delete_snippet(name.to_string())
.await?;
if deleted {
if let Some(ledger) = state.ledger() {
warn_ledger(ledger.forget(name));
}
ok(json!({"name": name, "deleted": true}))
} else {
not_found(name)
}
}
Action::Approve | Action::Reject => {
let id = string_arg(args, "execution_id")
.unwrap_or_default()
.to_string();
let service = state.service().await?;
let current = service.execution(id.clone()).await?;
let actions = pending(¤t);
let selected: Vec<&Value> = actions
.iter()
.filter(|action| {
options
.get("seq")
.and_then(Value::as_u64)
.is_none_or(|seq| action["seq"].as_u64() == Some(seq))
})
.collect();
let action = match selected.as_slice() {
[single] => *single,
[] => {
return Ok(error(
"NO_PENDING_ACTION",
format!("Workflow execution {id} has no matching pending action"),
));
}
_ => {
return Ok(error(
"AMBIGUOUS_PENDING_ACTION",
"Pass the child execution ID and --seq shown by status",
));
}
};
let seq = action["seq"].as_u64().unwrap_or_default();
let target = action["executionId"].as_str().unwrap_or(&id).to_string();
let next = if matches!(self.action, Action::Approve) {
service.approve(target, seq, run_options(ctx)).await?
} else {
service.reject(target, seq).await?
};
let _ = state.settle(service, next).await?;
let settled = service.execution(id).await?;
state.record(&settled);
outcome(&settled)
}
Action::Resume => {
let id = string_arg(args, "execution_id")
.unwrap_or_default()
.to_string();
let service = state.service().await?;
let next = service.resume(id, run_options(ctx)).await?;
let settled = state.settle(service, next).await?;
state.record(&settled);
outcome(&settled)
}
Action::Cancel => {
let id = string_arg(args, "execution_id")
.unwrap_or_default()
.to_string();
let cancelled = state.service().await?.cancel(id).await?;
state.record(&cancelled);
if cancelled.status == ExecutionStatus::Cancelled {
ok(json!({ "executionId": cancelled.id, "status": "cancelled" }))
} else {
outcome(&cancelled)
}
}
Action::Status => {
let id = string_arg(args, "execution_id")
.unwrap_or_default()
.to_string();
let current = state.service().await?.execution(id).await?;
state.record(¤t);
outcome(¤t)
}
Action::Doctor => state.doctor(options).await?,
Action::Stats => state.stats(string_arg(args, "name")).await?,
Action::Failures => {
let all = options.get("all").and_then(Value::as_bool).unwrap_or(false);
state.failures(string_arg(args, "name"), all).await?
}
Action::Trace => {
let id = string_arg(args, "execution_id").unwrap_or_default();
let full = options
.get("full")
.and_then(Value::as_bool)
.unwrap_or(false);
state.trace(id, full).await?
}
Action::Capture | Action::Check => {
let name = string_arg(args, "name").unwrap_or_default();
let Some(workflow) = state.resolve(name).await? else {
return Ok(not_found(name));
};
let result = if matches!(self.action, Action::Capture) {
let input = json_option(options, "input")?.unwrap_or_else(|| json!({}));
state
.capture_fixture(
&workflow,
input,
string_arg(options, "from").unwrap_or_default(),
)
.await
} else {
state
.check_fixture(
&workflow,
string_arg(options, "fixture").unwrap_or_default(),
)
.await
};
match result {
Ok(data) => ok(data),
Err(message) => error("WORKFLOW_FIXTURE_FAILED", message),
}
}
})
}
}
fn not_found(name: &str) -> CommandResult {
error("WORKFLOW_NOT_FOUND", format!("No workflow named '{name}'"))
}
fn group(state: Arc<State>) -> Cli {
let read_only = McpAnnotations {
read_only_hint: Some(true),
destructive_hint: Some(false),
idempotent_hint: Some(true),
open_world_hint: Some(false),
title: None,
};
let effectful = McpAnnotations {
read_only_hint: Some(false),
destructive_hint: Some(false),
idempotent_hint: Some(false),
open_world_hint: Some(false),
title: None,
};
let destructive = McpAnnotations {
destructive_hint: Some(true),
..effectful.clone()
};
let execution_arg = || {
field(
"execution_id",
FieldType::String,
true,
Some("Workflow execution identifier"),
)
};
let name_arg = || field("name", FieldType::String, true, Some("Workflow name"));
let optional_name_arg = || {
field(
"name",
FieldType::String,
false,
Some("Workflow name; omit for every workflow"),
)
};
let seq_option = || {
field(
"seq",
FieldType::Number,
false,
Some("Pending action sequence; defaults to the only pending action"),
)
};
let command = |action: Action,
description: &str,
annotations: &McpAnnotations,
args: Vec<FieldMeta>,
options: Vec<FieldMeta>| {
let mut def = CommandDef::build(
"",
GroupHandler {
state: state.clone(),
action,
},
)
.description(description)
.mcp(McpCommandOptions {
enabled: true,
annotations: Some(annotations.clone()),
..McpCommandOptions::default()
})
.destructive(annotations.destructive_hint == Some(true))
.done();
def.args_fields = args;
def.options_fields = options;
def
};
let named = |def: CommandDef, name: &str| {
let mut def = def;
def.name = name.to_string();
def
};
let commands = [
(
"capture",
command(
Action::Capture,
"Export a completed workflow's observations for review as a regression fixture",
&read_only,
vec![name_arg()],
vec![
field(
"from",
FieldType::String,
true,
Some("Completed execution identifier"),
),
field(
"input",
FieldType::Value,
false,
Some("Exact workflow input as a JSON object"),
),
],
),
),
(
"check",
command(
Action::Check,
"Check current workflow code against a reviewed fixture without invoking host commands",
&read_only,
vec![name_arg()],
vec![field(
"fixture",
FieldType::String,
true,
Some("Reviewed fixture JSON, or a file path on native hosts"),
)],
),
),
(
"list",
command(
Action::List,
"List shipped and saved workflows",
&read_only,
vec![],
vec![],
),
),
(
"show",
command(
Action::Show,
"Show a workflow's description, input schema, and program",
&read_only,
vec![name_arg()],
vec![],
),
),
(
"run",
command(
Action::Run,
"Run a shipped or saved workflow with JSON input",
&effectful,
vec![name_arg()],
vec![
field(
"input",
FieldType::Value,
false,
Some("Workflow input as a JSON object"),
),
result_only_field(),
],
),
),
(
"exec",
command(
Action::Exec,
"Run a Code Mode program in the workflow store so it can be saved",
&effectful,
vec![field(
"code",
FieldType::String,
true,
Some("Async JavaScript function calling this CLI's commands"),
)],
vec![result_only_field()],
),
),
(
"publish",
command(
Action::Publish,
"Publish a callable workflow without executing it",
&effectful,
vec![name_arg()],
vec![
field(
"code",
FieldType::String,
true,
Some("Async function accepting the run input"),
),
field(
"description",
FieldType::String,
true,
Some("What the workflow does"),
),
field(
"input_schema",
FieldType::Value,
false,
Some("JSON Schema checked before each run"),
),
],
),
),
(
"save",
command(
Action::Save,
"Save a completed execution's program as a workflow",
&effectful,
vec![name_arg()],
vec![
field(
"from",
FieldType::String,
true,
Some("Completed execution identifier"),
),
field(
"description",
FieldType::String,
true,
Some("What the workflow does"),
),
field(
"input_schema",
FieldType::Value,
false,
Some("JSON Schema for the workflow's input"),
),
],
),
),
(
"delete",
command(
Action::Delete,
"Delete a saved workflow",
&destructive,
vec![name_arg()],
vec![],
),
),
(
"approve",
command(
Action::Approve,
"Approve a paused workflow's pending action and continue it",
&effectful,
vec![execution_arg()],
vec![seq_option()],
),
),
(
"reject",
command(
Action::Reject,
"Reject a paused workflow's pending action",
&effectful,
vec![execution_arg()],
vec![seq_option()],
),
),
(
"resume",
command(
Action::Resume,
"Continue a workflow interrupted while running",
&effectful,
vec![execution_arg()],
vec![],
),
),
(
"cancel",
command(
Action::Cancel,
"Drop an interrupted or paused workflow run without running any more of it",
&destructive,
vec![execution_arg()],
vec![],
),
),
(
"status",
command(
Action::Status,
"Show a workflow execution's current status",
&read_only,
vec![execution_arg()],
vec![],
),
),
(
"doctor",
command(
Action::Doctor,
"Report workflows and runs that need action; exits 1 when any do",
&read_only,
vec![],
vec![
field(
"all",
FieldType::Boolean,
false,
Some("Also report informational notices"),
),
field(
"stale_days",
FieldType::Number,
false,
Some("Days without a run before a workflow is stale (default 30)"),
),
],
),
),
(
"stats",
command(
Action::Stats,
"Show run counts and success rate per workflow version",
&read_only,
vec![optional_name_arg()],
vec![],
),
),
(
"failures",
command(
Action::Failures,
"Group failed runs by cause; shows causes not yet followed by a success",
&read_only,
vec![optional_name_arg()],
vec![field(
"all",
FieldType::Boolean,
false,
Some("Include causes already followed by a success"),
)],
),
),
(
"trace",
command(
Action::Trace,
"Show an execution's steps, failure point, error, and console output",
&read_only,
vec![execution_arg()],
vec![field(
"full",
FieldType::Boolean,
false,
Some("Show arguments, results, and console output untruncated"),
)],
),
),
];
let mut group = Cli::create(GROUP_NAME)
.description("Run, save, and continue durable workflows built from this CLI's commands");
for (name, def) in commands {
group = group.command(name, named(def, name));
}
group
}
#[derive(Debug, Clone, Copy)]
struct LocalApproval;
impl multicast_codemode::ToolPolicyResolver for LocalApproval {
fn resolve(
&self,
origin: multicast_codemode::ToolOrigin,
annotations: &multicast_codemode::ToolAnnotations,
) -> multicast_codemode::ToolPolicy {
let policy = multicast_codemode::DefaultToolPolicyResolver.resolve(origin, annotations);
if origin == multicast_codemode::ToolOrigin::Local {
multicast_codemode::ToolPolicy {
requires_approval: false,
..policy
}
} else {
policy
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn local_approval_skips_only_local_commands() {
use multicast_codemode::{ReplayPolicy, ToolAnnotations, ToolOrigin, ToolPolicyResolver};
let write = ToolAnnotations {
read_only: Some(false),
destructive: Some(true),
..ToolAnnotations::default()
};
let local = LocalApproval.resolve(ToolOrigin::Local, &write);
assert!(!local.requires_approval);
assert_eq!(local.replay, ReplayPolicy::Log);
assert!(
LocalApproval
.resolve(ToolOrigin::RemoteMcp, &write)
.requires_approval
);
assert!(
LocalApproval
.resolve(ToolOrigin::OpenApi, &write)
.requires_approval
);
}
#[tokio::test]
async fn completed_outcome_retains_child_diagnostics() {
use multicast_codemode::RuntimeStore;
let store = Arc::new(multicast_codemode::MemoryStore::default());
let runtime = multicast_codemode::CodeModeRuntime::new(store.clone());
let id = runtime.begin("return 42", vec![], 1).await.unwrap();
let mut state = store.get_execution(&id).await.unwrap().unwrap();
state.status = ExecutionStatus::Completed;
state.result = Some(json!(42));
state
.workflow_children
.push(multicast_codemode::WorkflowChild {
id: "child-fixed".into(),
parent: id,
reference: None,
status: ExecutionStatus::Completed,
pending: vec![],
error: None,
});
let CommandResult::Ok { data, .. } = outcome(&state) else {
panic!("expected completion")
};
assert_eq!(data["result"], 42);
assert_eq!(data["children"][0]["id"], "child-fixed");
assert_eq!(data["children"][0]["status"], "completed");
}
#[test]
fn finds_dot_and_bracket_references() {
let code = r#"async (i) => { await math.sum(i); await math["product"](i); await math['x'](i); notmath.y(); a.math.z(); }"#;
assert_eq!(referenced_methods(code, "math"), ["sum", "product", "x"]);
}
#[test]
fn normalizes_cli_text_for_structured_properties() {
let schema = json!({
"type": "object",
"properties": {
"filter": {"type": "object"},
"ids": {"type": "array", "items": {"type": "integer"}},
"names": {"type": "array", "items": {"type": "string"}},
"label": {"type": "string"},
"note": {"type": ["string", "null"]}
},
"required": ["label"]
});
let input = json!({
"filter": "{\"a\":1}",
"ids": ["1", "2"],
"names": ["1"],
"label": "{\"a\":1}",
"note": null,
"absent": null
});
assert_eq!(
normalize_input(&schema, input),
json!({
"filter": {"a": 1},
"ids": [1, 2],
"names": ["1"],
"label": "{\"a\":1}",
"note": null,
"absent": null
})
);
let dropped = normalize_input(&schema, json!({"label": "x", "filter": null}));
assert_eq!(dropped, json!({"label": "x"}));
}
}
#[cfg(test)]
mod settle_tests {
use super::*;
fn state(status: &str, wait: bool, child_pending: Vec<u64>) -> ExecutionState {
let mut v = json!({
"id": "exec", "code": "", "status": status, "log": [], "result": null, "error": null,
"logs": [], "connectors": [], "created_at": 0, "updated_at": 0,
});
if wait {
v["workflow_wait"] = json!({"children": ["child"], "settle": false});
v["workflow_children"] = json!([{"id": "child", "parent": "exec", "reference": null,
"status": if child_pending.is_empty() { "running" } else { "paused" },
"pending": child_pending, "error": null}]);
}
serde_json::from_value(v).unwrap()
}
#[test]
fn a_run_waiting_on_its_child_workflow_is_still_working() {
assert!(still_working(&state("running", false, vec![])));
assert!(
still_working(&state("paused", true, vec![])),
"a child wait must not end the caller"
);
}
#[test]
fn approval_pauses_and_finished_runs_stop_the_wait() {
assert!(
!still_working(&state("paused", false, vec![])),
"a plain approval pause returns"
);
assert!(
!still_working(&state("paused", true, vec![3])),
"a child waiting for approval returns"
);
assert!(!still_working(&state("completed", false, vec![])));
}
}