multicast-workflows 2.0.0

Durable Code Mode workflows attached to multicast CLIs as first-party commands
Documentation

multicast workflows

multicast-workflows turns Code Mode programs into reusable commands of the CLI that runs them. A CLI author ships workflows in the binary; each one becomes an ordinary command, so it appears in help, skills, and MCP tools. Users and agents promote a completed Code Mode execution to a saved workflow at runtime.

Agent archetypes

An archetype bundles task guidance with references to this CLI's commands and workflows. Add .archetype("arithmetic", "Answer arithmetic questions", "Use sum or add-three for addition.", ["sum", "add-three"]) to the builder below to ship an arithmetic activation command. It returns guidance and scoped contracts without executing them; every other tool remains callable.

Operators can save their own definitions and activate them across process restarts:

math archetypes save addition --summary "Add operands" --instructions "Read the operands, then call sum." --tools sum,add-three
math archetypes activate addition --task "Add 1, 2, and 3"
math archetypes list
math archetypes show addition
math archetypes delete addition

Shipped definitions shadow saved ones with the same name and cannot be overwritten or deleted. Scope must name existing commands or workflows, excluding lifecycle commands and other archetypes. workflows doctor reports missing saved scopes. Only shipped guidance becomes MCP prompts and --llms-full sections; saved guidance is fetched through activation. Hosted builds store saved definitions in the SQL database supplied for WorkflowDatabaseKind::Archetypes.

use multicast_workflows::Workflows;

let cli = Workflows::new()
    .shipped(
        "add-three",
        "Add three integers",
        serde_json::json!({
            "type": "object",
            "properties": {
                "a": {"type": "integer"},
                "b": {"type": "integer"},
                "c": {"type": "integer"}
            },
            "required": ["a", "b", "c"],
            "additionalProperties": false
        }),
        "async (input) => {
            const first = await math.sum({ left: input.a, right: input.b });
            return math.sum({ left: first.sum, right: input.c });
        }",
    )
    .attach(cli)?;

Attaching fails when a shipped workflow calls a command the CLI does not have. Input is checked against the workflow's schema before any command runs. Executions are durable: a workflow that reaches a command needing approval exits with code 75 and waits for workflows approve, and an interrupted execution continues with workflows resume. Inside Code Mode, codemode.workflows defines and calls child workflows, composes pipelines, maps inputs, and supports bounded recursion. See the workflow composition guide for executable examples, limits, approvals, publication, and recovery.

math add-three --a 1 --b 2 --c 3
math workflows exec 'async () => math.sum({ left: 4, right: 5 })'
math workflows save nine --from EXECUTION_ID --description "Adds four and five"
math workflows run nine
math workflows list

Add --result-only to workflows run or workflows exec to return only a completed workflow's logical value. With global --format json, false, 0, null, and objects remain literal JSON. The workflow chooses how much detail to return; Multicast does not choose a projection or cache the execution. Failures retain diagnostics and a nonzero exit status; approval pauses retain their execution identifier and exit 75.

On native hosts, executions and saved workflows live in one SQLite store per CLI under the XDG data directory. See the example.

Every run is recorded in a run ledger beside the store, tagged with the workflow's version (a digest of its program and input schema). Four read-only commands keep a catalog maintainable without drowning in history:

Command Reports
workflows doctor Only what needs action: saved workflows calling commands the CLI no longer has, versions that keep failing, interrupted runs, and runs awaiting a decision. Each finding names the command that resolves it. Notices (never run, stale after --stale-days, duplicate, lost) need --all. Exits 1 on any error or warning.
workflows stats [NAME] Runs and success rate for the current version, kept apart from earlier versions.
workflows failures [NAME] Failed runs grouped by cause: the executing step plus the error with numbers, identifiers, and quoted text removed. A cause stays active until the workflow next succeeds; --all shows resolved causes.
workflows trace EXECUTION_ID One run's steps, the step where it stopped, its error, console tail, and status timeline. Large values are truncated unless --full.

Serving a CLI

Replace a CLI's serve() call with serve_workflows() (import multicast_workflows::ServeWorkflows), or multicast_workflows::serve(cli).await. Every invocation then has the workflows group, and cli --codemode serves the five Code Mode lifecycle tools over stdio, calling the CLI's own commands. Code Mode executions started this way live in memory, so several agent sessions can run a server for the same CLI at once.

Workflow telemetry

The host's OpenTelemetry providers observe each active Code Mode pass and connector call. Named runs include execution, workflow, and version attributes on spans. workflows trace returns the saved trace link; the ledger retains its identifiers when an execution is pruned from the store. Resuming a saved execution starts a new pass under the current request with a link to the previous pass, including after a host restart. Trace identifiers do not restore credentials or request authority.

Duration histogram Measures
incurs.codemode.pass.duration Active execution time per pass, excluding approval waits.
incurs.codemode.call.duration One connector dispatch, including approval checks and replay.
incurs.codemode.approval.duration Time paused until an approval, rejection, or cancellation wins.

Durations use seconds. Metric attributes contain only bounded outcomes or decisions; execution identifiers and workflow names stay on spans. Arguments, results, error messages, request headers, and baggage are not recorded by these instruments. Cli::open_telemetry(false) propagates across the execution boundary and suppresses these observations. The application owns SDK initialization, export, and shutdown.

Retry and recovery

Workflows::retry_policy(multicast_codemode::RetryPolicy { max_attempts: 3 }) opts trusted local read-only or idempotent commands into bounded transient retries. The default is one attempt, and the hard limit is eight. Attempts are committed before invocation and survive process restarts; changing the configured budget cannot replenish an existing call's budget.

An interrupted write without an authoritative receipt pauses with CALL_OUTCOME_UNCERTAIN, exit 75, and recoveryRequired: true. workflows doctor reports recovery-required; after the host can reconcile the outcome, workflows resume EXECUTION_ID checks it again. Approval grants no permission to repeat an uncertain write. Custom Code Mode connectors implement reconciliation against their remote idempotency contract or effect store.

Admit events and schedule workflows

Use Workflows::attach_with_triggers(cli) to obtain the CLI and a WorkflowTriggers handle for a native host. The host authenticates and authorizes incoming events, calls enqueue, and keeps calling tick during its lifetime. The handle supplies durable admission and delivery; the host supplies the HTTP server, authentication, and polling loop. See the executable host adapter.

Operation Behavior
enqueue(TriggerRequest) Validates input and persists an event without running commands. An identical event key returns its original receipt across restarts; changed request data returns TRIGGER_KEY_CONFLICT.
schedule(TriggerSchedule) Pins a workflow version and fixed interval. Missed intervals coalesce to the latest due occurrence. Identical registration preserves progress; changing settings or version requires removing the old schedule.
tick(limit) Refreshes unfinished receipts, then admits at most 1–100 due executions. One unfinished execution per workflow includes approval and uncertain-outcome pauses. Other workflows can progress.
receipt(source, key) Reads the persisted receipt from the webhook or schedule namespace.
remove_schedule(id) Stops future occurrences while retaining admitted work and deduplication records.

Request times are absolute Unix milliseconds; a schedule's deadline is a positive duration from each occurrence. Queued events past their deadline expire without starting. Running work is cancelled at its deadline while tick is alive; paused or stopped work needs another tick to enforce the deadline. Cancellation cannot undo an effect already committed by a destination.

Delivery persists an idle execution and binds its identifier before starting a pass. A restart recovers that execution rather than starting the workflow again. An interrupted write still requires authoritative reconciliation; triggers never approve actions automatically. A workflow changed after admission blocks before execution so the host can review a new event.

One host owns delivery and the execution store at a time. Keep approval and other lifecycle operations in that host through the attached CLI or its tool catalog. Receipts have no automatic pruning, preserving deduplication after completion. A crash before identifier binding can leave an idle execution with no command effects; a missing bound execution blocks delivery and retains its workflow slot instead of recreating it. Later ticks recheck the same identifier so restoring the execution store can recover it.

Cloudflare Workers

Build multicast-workflows with default-features = false. Use Workflows::attach_hosted(cli, host) with the standalone Cloudflare extension's CloudflareWorkflowHost; retain that host for the Durable Object's lifetime. The running Worker example shows constructor, child callback, MCP, and alarm wiring.

Shared behavior Cloudflare host
Shipped and saved workflows; schema validation; lifecycle commands Same ToolCatalog commands, with isolated call options
Executions, checkpoints, approvals, snippets, run ledger, trigger receipts Tenant's SQLite-backed Durable Object
JavaScript execution and fixture checks WorkerLoader child workers; fixture checks use an isolated in-memory runtime
Fixture source Inline reviewed JSON in the fixture option
Events, intervals, deadlines, concurrency slots, interrupted passes Durable Object alarms calling host.alarm(&triggers)
Tracing and duration metrics Shared instrumentation; the application supplies compatible providers and exporters

The host authenticates callers and partitions storage before invoking the shared catalog. Commands invoked by workflows must themselves support Workers; native processes, local files, and OS-only integrations still require a separate service. The default native feature retains local SQLite, filesystem fixtures, and CLI serving; those process adapters are excluded from the hosted build.

Alarms are committed before dispatching effects. Trigger delivery binds its execution identifier before recovery can run it; unbound preparations do not run from an alarm. Approval pauses retain the per-workflow concurrency slot until a decision or deadline. Destination idempotency or reconciliation remains necessary for an effect interrupted before its result was committed.

Resolve authority after restart

For authenticated durable execution, configure CloudflareWorkflowHost::with_authority with a host-owned WorkflowAuthority. Its capture method authenticates ingress and returns a stable, non-secret reference. Its resolve method supplies current credentials and policy. Reject missing or revoked references; never fall back to ambient credentials. The host persists the reference, resolves it before admission, approval, resume, and alarm recovery, and wraps connector calls to resolve it again before effects or recovery. An authority-resolution failure during alarm recovery terminates that pass without dispatching effects.

Native custom hosts can use WorkflowBindings with their workflow database and wrap their connector with bindings.connector(...). Call admit before driving an execution. These bindings do not replace tenant partitioning, command authorization, or approval policy. Legacy hosts remain supported; strict durable authority is opt-in. The Worker example's --authority-only verifier exercises restart, credential rotation, and revocation before approval and new effects.

Observation sharing is separate: a reviewed adapter can use multicast-observe while each workflow retains its own execution, journal, approval, and output. Neither durable authority nor a read-only annotation enables sharing automatically.

Publish reusable input-driven workflows

workflows publish NAME --description '...' --code 'async (input) => math.sum(input)' stores a callable without running it. Pass --input-schema to validate each run's input; workflows run NAME --input '{"left":2,"right":3}' supplies fresh values. Publication replaces a saved name, but cannot replace a shipped workflow. Syntax and connector calls are checked during execution. workflows save instead keeps the completed execution's exact program, including captured inputs.

Framework consumers can host the same commands and durable triggers on Workers: follow the Cloudflare application guide.