Specification · TypeScript / Bun

red

2026-10-31 · SPEC.md

Coding agents write deployment code directly: the provider CLI and API calls, the ordering, the retries and the checks that Terraform and Ansible once had to declare. The colors are the foundation for that code: three workflow SDKs, Green, Red and Blue, that share one model in Clojure, TypeScript and Python.

red is the TypeScript/Bun color: DAG execution, composable subworkflows and layered advice. Applications own their CLI, validation, planning, progress and durable recovery. Build your own package on it, or start from PocketDeploy, the starter package built on Blue. Steps call cloud CLIs or APIs directly; red has no OpenTofu or Ansible integration.

greenClojure / Babashka · canonical redTypeScript / Bun bluePython / uv

1. Philosophy

2. The opts contract

All cross-step state is one plain object threaded through the graph. The type is open (interface Opts { [key: string]: any }); steps read the keys they need and pass everything else through untouched.

3. Steps and errors

A step is (opts) => Opts | Promise<Opts>, named by a namespaced string such as "app/node".

# A step that calls a CLI directly

async function sh(cmd: string[]): Promise<string> {
  const proc = Bun.spawn(cmd, { stdout: "pipe", stderr: "pipe", stdin: "ignore" });
  const [out, err, exit] = await Promise.all([
    new Response(proc.stdout).text(), new Response(proc.stderr).text(), proc.exited,
  ]);
  if (exit !== 0) throw new StepError(`${cmd.join(" ")} failed: ${err.trim()}`, { exit });
  return out.trim();
}

const host: StepFn = async (opts) => ({ ...opts, "hello/host": await sh(["uname", "-sm"]) });

4. Workflows: wireFn and nextFn

workflow({ start, end?, wireFn, nextFn? }) builds an immutable workflow value. Every constructor and advice function is pure, so workflows can be shared and branched freely.

const wf = workflow({
  start: "app/start",
  wireFn: (step) => {
    switch (step) {
      case "app/start": return [start, "app/node"];
      case "app/node": return [node, "app/join"];
      case "app/join": return [join];
    }
  },
  nextFn: (step, defaultNext, opts) => {
    if (failed(opts)) return [];
    if (step === "app/start") {
      return opts.servers.map((s: unknown) => ["app/node", { ...opts, "app/server": s }] as const);
    }
    return (defaultNext ?? []).map((s) => [s, opts] as const);
  },
});

5. Parallelism and joins

  1. Live branches are grouped by step. A step is blocked while another live branch could still reach it along static wireFn edges.
  2. Same-step entries from the same fan-out run individually; entries converging from different origins join: the step runs once with the fork-point opts plus "red/branches", the array of branch results.
  3. Multiple successors fork into real parallel promises.
  4. When a branch fails inside a fork, in-flight siblings finish their current step, then the fork collapses: the join is skipped and a terminal carries the worst exit, its error and trace, and "red/branches". Collapse cascades outward through nested forks. Equal exit codes select the first incoming branch.
  5. A join whose incoming branches already include a failure is skipped the same way.
  6. Final result: no terminals → {"red/exit": 0}; one → it; several → the first failed one, else the last successful one.

6. Subworkflows

step(subWorkflow, { inFn?, outFn? }) turns a workflow into an ordinary step. Wire it, advise it or fan it out like any other operation. inFn shapes child inputs; outFn(parentOpts, childResult) adapts the result back.

By default the child result, including failure keys, becomes the parent step result. A custom outFn must preserve or deliberately handle failures. Application context flows in opts; a rebuilding inFn must carry the keys its child needs. Parent advice is inherited even across that adapter. Subworkflows supply composition, not a persistent recovery journal.

const child = workflow({
  start: "child/prepare",
  wireFn: (name) => name === "child/prepare" ? [prepare] : undefined,
});
// Use inside the parent wireFn:
// case "app/prepare": return [step(child), "app/verify"];

7. Advice

Emacs nadvice-style combinators, scoped to a workflow value:

howbehaviour
aroundfn(base, opts) decides whether and how to call the step.
overridefn(opts) replaces the step.
before / afterfn(opts) runs before or after; its return is ignored.
before-whileRuns the step only if fn(opts) is truthy; otherwise returns that value.
before-untilReturns fn(opts) if truthy; otherwise runs the step.
after-whileIf the step succeeded, returns fn(opts); otherwise the step's result.
after-untilIf the step failed, returns fn(opts); otherwise the step's result.
filter-argsThe step receives fn(opts).
filter-returnThe result is fn(stepResult).

8. YAML config and COLORS_PAR_*

loadYaml(text) parses YAML with Bun.YAML.parse (YAML 1.2: no and dates remain strings; app/… keys parse unquoted). It returns an empty object for empty/null input and otherwise the parsed data. Applications read files, validate mappings and schemas, and resolve relative paths. Quote version-like values such as "3.10".

readPars(opts, env?) overlays COLORS_PAR_<UPPER_SNAKE> variables onto flat kebab-case keys: COLORS_PAR_DO_TOKEN → do-token. Existing booleans accept true/false, existing integers accept decimal integers, and other values remain strings. parName(key) maps keys to environment names. The namespace is shared by all colors; credentials stay outside YAML.

The historical red/cli import path remains for these helpers only. There is no generic CLI, file discovery, lifecycle preflight or bundled dry-run/progress policy. Applications can implement policies with advice. Engine-level start/end slicing remains available.

workdir: work      # relative to this file
message: hello
names:
  - alice
  - bob

9. The example

examples/hello is a small, offline package whose steps call local command-line tools:

hello/check  → hello/host → hello/greet (one branch per name) → hello/report
validation     uname -sm    create: write <name>.txt             create: cat the files
                            delete: rm -f <name>.txt             delete: rmdir the workdir

The application owns argument parsing, configuration and validation. hello/greet embeds a child workflow running hello/write then hello/verify, checking each write/removal before returning to the parent. Application-defined all-step advice logs both parent and child stages; preview advice skips hello/greet and hello/report. These policies live in the example, not the SDK.

cd examples/hello
./red create --dry-run
./red create
COLORS_PAR_MESSAGE=hi ./red create
./red delete

10. Testing

11. API index

Subpath exports: red, red/workflow, red/advice and red/cli. The root re-exports workflow and configuration APIs plus the advice namespace.

namecontract
workflow({start, end?, wireFn, nextFn?}) => Workflow
run(wf, opts) => Promise<Opts>
step(wf, {inFn?, outFn?}) => StepFn; embed a workflow.
failed(opts) => boolean; "red/exit" > 0.
StepErrornew StepError(message, {exit?}); choose the exit code.
adviceAdd(wf, step, how, id, fn, props?) => Workflow
adviceAddAll(wf, how, id, fn, props?) => Workflow
adviceRemove(wf, step, id) => Workflow
adviceRemoveAll(wf, id) => Workflow
advicePlan(wf | wf[], step) => PlanEntry[], outermost first.
typesOpts, StepFn, WireFn, WireDecl, NextFn, NextPair, Workflow, PlanEntry
advice.*Registry primitives: hows, add, removeId, addGlobal, removeGlobalId, mergeEntries, mergeRegistry, ordered, compose, truthy, AdviceError.
loadYaml(text) => Opts; parse YAML without file IO or overlays; application validates its schema.
readPars(opts, env?) => Opts; overlay COLORS_PAR_*.
parName(key) => string; do-token → COLORS_PAR_DO_TOKEN.