Cascada
Concurrency-first scripting and templating
for JavaScript and TypeScript
Cascada is in active development. APIs and syntax may change. Feedback and contributions are welcome.
Why Cascada?
Modern applications spend much of their time waiting - fetching pages, calling web APIs, prompting AI models, querying databases. Operations often take seconds, even minutes.
Normally, speeding that up means running tasks at the same time by hand - tangled code juggling what overlaps and what waits, while unpredictable timing breeds race conditions and bugs that are hard to reproduce.
With Cascada, you write plain sequential code instead - no async, no await, no promises. Your logic already shows what depends on what, so Cascada runs independent operations concurrently, each waiting only for the results it needs. The results are guaranteed to be identical to sequential execution - only much faster. (See a workflow in action ↓)
Orchestrate workflows with CascadaScript or generate prompts, HTML and other text with Cascada Template. Both run inside your existing JavaScript and TypeScript applications and AI agents.
Intentionally simple
Instantly familiar to JavaScript and Python developers.
Variables, functions, conditionals, loops - the building blocks you already know. CascadaScript keeps the syntax simple, while its engine handles the complexity of running operations concurrently.
function greet(user)
if user.isNew
return "Welcome, " + user.name
endif
return "Hello, " + user.name
endfunction
for user in users
sendEmail(user.email, greet(user))
endfor
Everything that can run concurrently, does
Across statements, within expressions, inside function calls, at each loop iteration, across composed scripts…
Every operation starts as soon as its inputs are ready, waiting only when it actually depends on another result.
Every step sees its own moment in time. You can change a variable or property while earlier operations are still using its previous version - earlier steps keep the old one, the change runs without waiting, and future reads see the new version as soon as it settles.
Streaming isn’t a special case. In Cascada, any regular for loop can process a stream - starting each item as it arrives, running independent iterations concurrently, and assembling the results in the intended order.
// Stream headphone model names as they arrive.
var products = findProducts({
productName: "headphones",
count: 4
}).elementStream
data summaries = []
// Start each product as the list arrives.
for product in products
// Run lookups concurrently, across products too.
var specs = fetchSpecs(product)
var reviews = fetchReviews(product)
var price = fetchPrice(product)
// Each summary waits only for its own inputs.
var summary = summarizeProduct({
product: product,
specs: specs,
reviews: reviews,
price: price
}).output
// Collect summaries in the original product order.
summaries.push(summary)
endfor
return summaries.snapshot()
Concurrent execution
Sequential results
Operations can start and finish in any order, but Cascada assembles their outputs exactly as if the script had run sequentially. Arrays, objects and text always come out in the order you wrote them.
The example demonstrates concurrency in three steps:
-
Find 4 headphones, streaming each result
Processing starts as soon as the search returns a headphone model, while the search continues.
-
Fetch specs, reviews and prices, then summarize
Fetched concurrently across headphones. Each summary waits only for its own three fetches to finish.
-
Return summaries in the original order
Summaries can finish in any order. Results keep the original search order.
// Stream headphone model names as they arrive.
var products = findProducts({
productName: "headphones",
count: 4
}).elementStream
data summaries = []
// Start each product as the list arrives.
for product in products
// Run lookups concurrently, across products too.
var specs = fetchSpecs(product)
var reviews = fetchReviews(product)
var price = fetchPrice(product)
// Each summary waits only for its own inputs.
var summary = summarizeProduct({
product: product,
specs: specs,
reviews: reviews,
price: price
}).output
// Collect summaries in the original product order.
summaries.push(summary)
endfor
return summaries.snapshot()
Errors flow like data
Errors don’t stop execution. They poison all variables that depend on them, while independent work continues unaffected.
The butterfly effect: Poison also spreads through control flow. When an if condition is poisoned, neither branch runs, and everything either branch can potentially write is poisoned. Repair early, before it spreads.
var user = getUser()
if user is error
showMessage("Failed to get user: "
+ user#message)
// Repair with a fallback
user = { name: "Guest" }
endif
Sequential by exception
Concurrency is the default, but sometimes order matters.
db!.write(data)- Add!to calls that modify external state, such as database writes, to run them in order.each item in items- Process loop iterations one by one.for item in items of 5- Limit a loop to five concurrent iterations.
// Mark the call side-effect with !
db!.write(data)
// The read will wait for the write
db.read(id)
// Process items one by one
each item in items
process(item)
endeach
// Process up to 5 items concurrently
for item in items of 5
process(item)
endfor
Built for JavaScript
and TypeScript
Cascada works inside your existing applications, not as a replacement for JavaScript or TypeScript.
Keep your libraries, APIs, and services in JavaScript or TypeScript. Pass them - along with your data, functions, and promises - to CascadaScript through the context object, and let CascadaScript orchestrate them into concurrent workflows.
Concurrency flows across the entire workflow - from your own functions to reusable CascadaScript functions, imported libraries, inherited scripts, and components - following only their logical dependencies.
import * as cascada from 'cascada-engine';
// Place your data, API and helpers
// in the context object
const context = {
topic: 'electric cars',
// Your functions:
searchWeb, getReviews, summarize
};
const env = new cascada.AsyncEnvironment();
// Run the script with the context object
const result = await env.renderScriptString(`
var pages = searchWeb(topic)
var reviews = getReviews(topic)
return summarize(pages, reviews)
`, context);
Templates that
run concurrently
Cascada Template brings the same engine to templates, using the popular Nunjucks syntax. Create AI prompts, HTML, emails, and more using familiar expressions, macros, conditionals, and loops.
Just like CascadaScript, everything that can run concurrently, does - even inside templates. Independent operations run in parallel, while the final output is assembled in the order you wrote it.
Write a research brief on {{ topic }}:
{% set urls = searchWeb(topic) %}
{% for url in urls %}
- {{ summarize(fetchPage(url)) }}
{% endfor %}
Casai - Cascada for AI workflows
Build AI agents and workflows with Casai, a TypeScript library built on Cascada and the Vercel AI SDK, with all of Cascada’s concurrency features.
Compose model calls, tools, and structured outputs into reusable components. Define your workflows in CascadaScript and your prompts in Cascada templates - real control flow instead of wiring loops, conditionals, and fan-out through graph APIs.
The same headphones example shown above, now with Casai components. Explore the components, orchestration code, and workflow in motion.
One agent streams headphone suggestions. Your product APIs fetch specs, reviews and prices, and another agent summarizes each model. Shared configuration gives both agents the same model.
import {
Config, LLMAgent, Script, FileSystemLoader, z
} from 'casai';
import { Output } from 'ai';
import { openai } from '@ai-sdk/openai';
// Your own catalog, reviews and pricing integrations.
import {
fetchSpecs, fetchReviews, fetchPrice
} from './product-api.js';
// Share a model across both agents.
const defaults = Config({
model: openai('gpt-4o-mini')
});
// Stream each complete model name as it arrives.
const findProducts = LLMAgent.withTemplate.asStream({
inputSchema: z.object({
productName: z.string(),
count: z.number().int().positive()
}),
prompt: `Suggest {{ count }} {{ productName }}
models to compare. Return only model names.`,
output: Output.array({ element: z.string() })
}, defaults);
// Build a prompt from each product's fetched data.
const summarizeProduct = LLMAgent.withTemplate({
inputSchema: z.object({
product: z.string(),
specs: z.record(z.string(), z.string()),
reviews: z.array(z.string()),
price: z.number().nonnegative()
}),
prompt: `Summarize this headphone.
Use only the supplied information.
Model: {{ product }}
Specs: {{ specs | dump }}
Reviews: {{ reviews | dump }}
Price: {{ price | dump }}`
}, defaults);
// Save the CascadaScript example as headphones.cas.
const compare = Script.loadsScript({
loader: new FileSystemLoader('./'),
script: 'headphones.cas',
// Make these components and APIs available to the script.
context: {
findProducts, summarizeProduct,
fetchSpecs, fetchReviews, fetchPrice
}
});
const summaries = await compare();
console.log(summaries);
// Stream headphone model names as they arrive.
var products = findProducts({
productName: "headphones",
count: 4
}).elementStream
data summaries = []
// Start each product as the list arrives.
for product in products
// Run lookups concurrently, across products too.
var specs = fetchSpecs(product)
var reviews = fetchReviews(product)
var price = fetchPrice(product)
// Each summary waits only for its own inputs.
var summary = summarizeProduct({
product: product,
specs: specs,
reviews: reviews,
price: price
}).output
// Collect summaries in the original product order.
summaries.push(summary)
endfor
return summaries.snapshot()
Build your first workflow
Start with a script and the functions you already use.
Install Cascada, then pass your functions and data to a script.
npm install cascada-engine
Fetch a user's profile and posts concurrently, then combine the results. This example uses JSONPlaceholder, a public demo API. Replace the helper with your own API calls when you're ready.
import { AsyncEnvironment } from 'cascada-engine';
async function fetchJson(path: string) {
const response = await fetch(
`https://jsonplaceholder.typicode.com${path}`
);
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
return response.json();
}
const env = new AsyncEnvironment();
const result = await env.renderScriptString(`
var user = fetchJson("/users/1")
var posts = fetchJson("/posts?userId=1")
return { name: user.name, postCount: posts.length }
`, { fetchJson });
console.log(result);