Specification · TypeScript / Bun
red
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.
1. Philosophy
- One model, three languages. Green is canonical; red and blue implement the same execution, composition and advice semantics. Application code still uses each language’s APIs and tools.
- Plain data, plain functions. State is one open object; a step is a function from it to it. No class hierarchy, no resource DSL, no state engine.
- Code, written by agents. A step calls the provider's CLI or API itself. The program is cheap to write and readable to review; nothing is hidden behind a second language.
- Cross-cutting behaviour is advice. Applications can attach reporting, guards and other policies without changing steps. These policies are application code, not bundled SDK helpers.
- Errors are values. Failures flow through the graph as data and can be routed, not thrown past the caller.
- No runtime dependencies. red needs Bun and nothing else.
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.
- The engine owns
red/*and privatered.*/*keys:"red/exit","red/err","red/trace","red/step","red/branches", and the private"red.workflow/inherited". - Project data uses its own namespace-like keys (
"app/servers"). Desired-state inputs that may be overridden from the environment stay flat and kebab-case (do-token). - Step input is recursively frozen at each step boundary. Map, Set, Date, typed arrays, class instances and accessor properties fail before the step runs. Steps return new objects with spread syntax.
3. Steps and errors
A step is (opts) => Opts | Promise<Opts>, named by a namespaced string such as "app/node".
"red/exit":0succeeded,>0failed;failed(opts)tests it. A successful step that sets no exit gets0stamped.- The step boundary is the exception firewall: any throw or awaited rejection becomes
"red/exit","red/err"and"red/trace"on the step's input opts. throw new StepError(message, { exit })chooses the exit code; any other throw is exit 1.- A non-object return (a forgotten
return) fails through the same contract. - Without a
nextFn, a failed step has no successors and its branch halts. With one, routing a failure to cleanup or retry is user logic. - Steps must await everything they start; applications own process-level error handling and command exit policies.
# 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.
wireFn(step, runOpts) => [fn, ...nextSteps] | undefinedis the static happy-path graph.runOptsis the run's initial opts, stable for the whole run, so the graph may depend on"app/event"without flapping.nextFn(step, defaultNext, opts) => [[nextStep, opts], ...]routes dynamically: fan-out, conditional branches, error paths. Returning[]ornullends the branch.endis an inclusive slice boundary: the step runs, then the workflow stops.run(wf, opts)runs a workflow and returns the final opts.
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
- Live branches are grouped by step. A step is blocked while another live branch could still reach it along static
wireFnedges. - 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. - Multiple successors fork into real parallel promises.
- 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. - A join whose incoming branches already include a failure is skipped the same way.
- 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:
| how | behaviour |
|---|---|
around | fn(base, opts) decides whether and how to call the step. |
override | fn(opts) replaces the step. |
before / after | fn(opts) runs before or after; its return is ignored. |
before-while | Runs the step only if fn(opts) is truthy; otherwise returns that value. |
before-until | Returns fn(opts) if truthy; otherwise runs the step. |
after-while | If the step succeeded, returns fn(opts); otherwise the step's result. |
after-until | If the step failed, returns fn(opts); otherwise the step's result. |
filter-args | The step receives fn(opts). |
filter-return | The result is fn(stepResult). |
adviceAdd(wf, step, how, id, fn, props?)targets one step;adviceAddAll(wf, how, id, fn, props?)targets every step.adviceRemove/adviceRemoveAllremove by id.- Stacking: most recently added is outermost, across both registries, unless
depth(−100..100, default 0) overrides; lower depth is more outward. Re-adding an id replaces it. - Truthiness is Clojure's: only
null,undefinedandfalseare falsy. Forafter-while/after-untila step result is true when its"red/exit"is 0 or absent. - Advice is inherited through
stepembeds by flat step name; ancestor advice stacks outside child advice at equal depth, and an ancestor entry with the same id replaces the child's. advicePlan(wfOrChain, step)lists the composed stack outermost-first with{id, how, depth, seq, scope, level}.
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
bun testdiscoverstest/*.test.ts: graph execution, failures, composition, slicing, advice ordering/inheritance and configuration helpers.test/hello-example.test.tsruns the application CLI in temporary directories, checking create/delete, preview, child advice, environment overrides and failures.bun run typecheckchecks source and tests. The extensionless example launcher is exercised by subprocess tests.
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.
| name | contract |
|---|---|
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. |
StepError | new 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. |
| types | Opts, 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. |