Skip to content

Durable workflows

Experimental. task, workflow, Experimental.Durable and Experimental.Human need { "vibe": { "experimental": ["builtins"] } } in tsconfig.json or vibe.config.json. Both files take the same "vibe" object. Without it, the compiler reports EK3013. A release can change or remove them.

A durable workflow is a function whose progress is saved after every step. If the process stops part way, because it crashed, was deployed over, or was killed, the next process continues the run from the last finished step. Finished steps do not run again. Use a workflow for work that takes longer than one process can be trusted to live: an agent run with many model calls, a release that waits a day for an approval, or an order that charges a card and then ships.

You write two declarations. A task is one step: it does the work that touches the outside world. A workflow is the plan: it calls tasks in order and holds no side effects of its own.

Turn on the feature

Add the experimental setting to the "vibe" section of tsconfig.json:

{
  "compilerOptions": { "strict": true, "module": "NodeNext", "outDir": "dist" },
  "include": ["src/**/*.vibe"],
  "vibe": { "experimental": ["builtins"] }
}

A project that keeps its settings in vibe.config.json adds the same "vibe" object there: { "vibe": { "experimental": ["builtins"] } }. An experimental key at the root of either file has no effect, and the compiler still reports EK3013. This one setting is the only switch that workflows need. The engine is part of vibelang-runtime, which every Vibe project already installs.

Write your first workflow

The following program declares two tasks and one workflow, then runs the workflow twice with the same input.

schema Issue { number: number; title: string }
 
task FetchIssues {
  effect call(repo: string): ReadonlyArray<Issue>!string {
    try Console.log(`fetching ${repo}`)
    if (repo === "") throw "no repository"
    return [{ number: 1, title: "Crash on start" }, { number: 2, title: "Typo in README" }]
  }
}
 
task Label {
  effect call(issue: Issue): string!never {
    const label = issue.title.includes("Crash") ? "bug" : "docs"
    return `#${issue.number} ${label}`
  }
}
 
export workflow Triage {
  effect call(repo: string) {
    const issues = try FetchIssues(repo)
    const first = try Label(issues[0]!)
    const second = try Label(issues[1]!)
    return [first, second]
  }
}
 
export effect function main() {
  provide Layer.provideMerge(Triage.layer, Experimental.Durable.memory) {
    const labels = try Triage("acme/app")
    try Console.log(labels.join(", "))
    const again = try Triage("acme/app")
    try Console.log(again.join(", "))
  }
}
 
await runPromise(main())
// Output: fetching acme/app
// Output: #1 bug, #2 docs
// Output: #1 bug, #2 docs

Read the program from the top:

  • effect call(...) is the body of a task or workflow. effect marks a function that returns a description of work instead of running at once, and try runs such a function and gives you its result. Inside a workflow, each try of a task is one recorded step.
  • ReadonlyArray<Issue>!string is the task's return type: it succeeds with an array of Issue or fails with a string. throw fails the task with a typed error.
  • provide ... { } supplies what the block needs. Triage.layer is the workflow with its tasks, and Experimental.Durable.memory is an engine that keeps runs in this process's memory.
  • await runPromise(main()) starts the program. The top level of a module is ordinary code, where try is not available, so runPromise runs the function and await waits for it. Declaring main does not call it.
  • fetching acme/app prints once. The second Triage("acme/app") has equal input, so it joins the finished run and returns the recorded result. No task runs again.

To run the program, save it as src/main.vibe and use vibe run:

vibe run src/main.vibe

For the project layout and the entry file, see the approval example.

How a run is recorded

The engine keeps one append-only journal per run. A step writes StepStarted before its body runs and StepCompleted, with the encoded result, after. When a run resumes, the workflow body runs again from the top, and each step that the journal finished returns its recorded result instead of running. A recorded failure is replayed the same way.

Two consequences follow, and the rest of this page builds on them:

  • A workflow body must be deterministic. It runs once per resume, so it must make the same calls in the same order every time. The compiler enforces this. See Workflows.
  • A step that did not finish can run again. A crash after a task's outside effect and before StepCompleted repeats the task. Delivery is at-least-once. See Make a task safe to repeat.

Tasks

A task is the unit that the journal records. Put every side effect in a task: network calls, model calls, file writes, the clock, and random numbers.

The journal records a task as one step, and it does not record ordinary code inside the task. A task that a crash interrupts runs its body again from the top. Two kinds of call are the exception. Inside a task, a call of Experimental.Model and each tool call that Experimental.Agent.run makes are recorded as steps of their own under the task. When the task runs again, each of these calls that finished returns its recorded result, and the call that the crash interrupted runs again. See Build agents.

schema Order { id: string; placedAt: Date; cents: bigint; tags: ReadonlySet<string> }
schema Receipt { id: string }
schema error Declined { reason: string }
 
task Charge {
  static readonly tier = "irreversible"
  static readonly idempotencyKey = (order: Order) => `charge:${order.id}`
  static readonly retryPolicy = { initialMs: 500, factor: 2, maxMs: 8000, maxAttempts: 4 }
  effect call(order: Order): Receipt!Declined {
    if (order.cents <= 0n) throw new Declined({ reason: "empty order" })
    return { id: `receipt-${order.id}` }
  }
}

A task follows these rules:

  • Write every type. Annotate each parameter and write the return type as Success!Error. Use never for a task that cannot fail: string!never. The compiler derives a schema from these types and uses it to store the values.
  • Use types that can be stored. A parameter, result, or error type must have a schema form. See Durable values.
  • Call a task only from a workflow. A task call anywhere else reports EK5502.
  • Set options with static readonly members. The following table lists the options that this page uses.
MemberValueDefault
retryPolicy{ initialMs, factor, maxMs, maxAttempts?, expirationMs?, jitterRatio? }. See Retry a failing task.No retries
tier"sealed" (no outside change), "compensable" (a change that can be undone) or "irreversible" (a change that cannot, such as a sent email)"sealed"
idempotencyKeyA string, or a function of the parameters that returns oneNone
attemptTimeoutMsThe time limit for one attempt, in millisecondsNone
cache{ ttlMs?, scope? }: reuse a successful result for an equal call. Only a "sealed" task can cache.None
keyThe name the journal stores for the taskThe declaration's name

The stored name is the declaration's name, so a run stays valid when you move the file. Post.plan and Experimental.Durable.runs print this name, as the samples on this page show. If you rename a task while runs that used it are stored, set static readonly key to the old name.

Not in this release. VIP-55 specifies the stored name <package name>#<Name>. This release stores the name without the package name, in a package that has a name and in one that has none. If two packages that share one store declare a task or workflow of the same name, give one of them a key.

Make a task safe to repeat

A task can run more than once when the process dies between the task's effect and the journal write. For a task that changes something outside the program, set idempotencyKey and send that key to the destination, so that the destination can drop the duplicate. Payment and email APIs accept such a key. Mark the task tier = "irreversible" so that tools that rewind a run refuse to remove its step.

Workflows

A workflow's call reads like ordinary code, with branches and early returns. It can omit its return type. Inside it, try can run only a step:

  • a task
  • another workflow, or Other.child(...) to run one as a separate run and wait for it
  • a durable wait: see Wait without holding a process
  • try.all, try.race or try.any over steps

The compiler rejects the code that would make a resume diverge from the first run. The following table lists the rules.

CodeThe workflow body
EK5504runs something with try that is not a step
EK5505reads the clock, a random number, or a module-level let
EK5506contains a loop or reassigns a variable
EK5507reaches itself through its steps

To loop, move the loop into a task, or end the round and start the next one with a handoff: return Fix.to(issue, attempt + 1). A handoff continues the same run, and static readonly maxRounds bounds the number of rounds. For the complete rules and every diagnostic, see Durable tasks and workflows.

Durable values

Every value that enters or leaves a task or workflow is saved to the journal, so its type must have a schema form. The compiler derives the schema from the types you wrote.

You can useYou cannot use (EK2109)
string, number, boolean, bigint, null, undefined, literal types and unions of themunknown, any
schema, schema error and schema data declarationsa plain type alias or interface
Arrays, tuples and ReadonlyArray<T> of the preceding typesSet<T> and Map<K, V>: use the read-only forms
Date, URL, RegExp, Uint8Array, Error, ReadonlySet<T>, ReadonlyMap<K, V>functions and class instances

A workflow's input also names its run. Two calls with equal input are the same run: the second call joins the first, or returns its recorded result. Equality is computed on the stored form, so new Set(["a", "b"]) and new Set(["b", "a"]) are equal, and ["a", "b"] and ["b", "a"] are not. To run the same input again as separate work, add a field that differs, such as a date or a request ID, or start the run with Experimental.Durable.start.

Do not pass a secret through a durable boundary. The engine refuses a payload, result, or failure that holds a Redacted value before anything is written. Pass the secret's name, and read the secret inside the task that uses it.

Retry a failing task

A task with a retryPolicy runs again after a typed failure. Without a policy, the failure is recorded and returned to the workflow.

let calls = 0
 
task CallModel {
  static readonly retryPolicy = { initialMs: 10, factor: 2, maxMs: 40, maxAttempts: 3 }
  effect call(prompt: string): string!string {
    calls += 1
    try Console.log(`attempt ${calls}`)
    if (calls < 3) throw "rate limited"
    return `answer to ${prompt}`
  }
}
 
export workflow Ask {
  effect call(prompt: string) { return try CallModel(prompt) }
}
 
export effect function main() {
  provide Layer.provideMerge(Ask.layer, Experimental.Durable.memory) {
    try Console.log(try Ask("why"))
  }
}
 
await runPromise(main())
// Output: attempt 1
// Output: attempt 2
// Output: attempt 3
// Output: answer to why

The delay before attempt n is initialMs * factor ** (n - 2), capped at maxMs. Each attempt is its own journaled step. After a restart, the engine replays every attempt that the journal finished, with its result or its failure, and continues with the next attempt. An attempt that a crash interrupts before its StepCompleted entry runs again. If that attempt already sent a payment, the repeat sends it a second time, so a task with an outside effect needs an idempotency key even when it has a retry policy. See Make a task safe to repeat. maxAttempts bounds the number of attempts and expirationMs bounds the total delay. A policy with neither bound draws the warning EK5509.

Wait without holding a process

A workflow that waits a week for an approval must not keep a process alive for a week. The following calls park the run: the engine stores it as suspended, and a timer, a delivery, or an answer wakes it, on any process that uses the same store.

CallThe run parks until
try Experimental.Durable.sleep("7 days")the duration passes
try Experimental.Durable.until(date)the instant arrives
try signal.wait()signal.send(Workflow, run, value) or handle.send(signal, value) delivers a value
try Experimental.Human.confirm(name, prompt) and ask, select, jsonExperimental.Human.answer(Workflow, run, name, value) records an answer

The following workflow uses a timer and a signal. A signal is a typed value that enters a run from outside, such as a webhook payload.

schema Payment { cents: number }
export const paid = Experimental.Durable.signal("paid", Payment)
 
task ShipPaid {
  effect call(order: string, cents: number): string!never { return `${order} shipped, ${cents} cents paid` }
}
 
export workflow Fulfil {
  effect call(order: string) {
    const payment = try paid.wait()
    try Experimental.Durable.sleep("20 millis")
    return try ShipPaid(order, payment.cents)
  }
}
 
export effect function main() {
  provide Layer.provideMerge(Fulfil.layer, Experimental.Durable.memory) {
    const handle = try Experimental.Durable.spawn(Fulfil, { order: "A-1" })
    try handle.send(paid, { cents: 1200 })
    try Console.log(try handle.result)
  }
}
 
await runPromise(main())
// Output: A-1 shipped, 1200 cents paid

Experimental.Durable.spawn starts the run and returns a handle at once. Its second argument is the workflow's input as an object keyed by parameter name. handle.send delivers the signal, and handle.result waits for the run to finish. A value sent before the run reaches the wait is kept and returned when the run gets there. The first delivery to a wait wins.

Use Experimental.Durable.sleep in a workflow, not sleep. A plain sleep holds the process and is lost on a restart. A durable timer records its wake time before the run parks, so a restarted run waits only for the time that is left.

Ask a person

Experimental.Human.confirm parks the run on a yes-or-no question. Each question has a name, which addresses it within the run, and a prompt.

task Deploy {
  static readonly tier = "irreversible"
  static readonly idempotencyKey = (version: string) => `deploy:${version}`
  effect call(version: string): string!never { return `released ${version}` }
}
 
export workflow Release {
  effect call(version: string) {
    const approved = try Experimental.Human.confirm("production", `Deploy ${version} to production?`, { timeout: "6 hours" })
    if (!approved) return "declined"
    return try Deploy(version)
  }
}
 
// Reads the run's open waits until the named question is open.
effect function openQuestion(run: string, name: string) {
  while (true) {
    const waits = try Experimental.Durable.waiting(run)
    const found = waits.find((wait) => wait.reason === "approval" && wait.name === name)
    if (found !== undefined) return found
    try sleep("2 millis")
  }
}
 
export effect function main() {
  provide Layer.provideMerge(Release.layer, Experimental.Durable.memory) {
    const handle = try Experimental.Durable.spawn(Release, { version: "v1" })
    const question = try openQuestion(handle.id, "production")
    try Console.log((question.request as Experimental.Human.Question).prompt)
    try Experimental.Human.answer(Release, handle.id, "production", true)
    try Console.log(try handle.result)
  }
}
 
await runPromise(main())
// Output: Deploy v1 to production?
// Output: released v1

The code that answers is ordinary code outside the run: an inbox page, a chat command, or a command-line tool. It needs the workflow, the run ID, and the question's name. Experimental.Durable.waiting(run) lists what a parked run waits for, with the prompt, so an inbox can show the question. The timeout deadline is recorded when the question is first asked, and a restart does not extend it. A question that times out fails with Experimental.Human.Failed.

The other question forms return typed answers: ask returns a string, select returns one of the choices you list, and json returns a value that a schema accepts. An answer that does not fit is refused, and the run asks again, up to maxAttempts times.

Bound a whole run

To bound a run across all of its waits, set static readonly deadline = "2 days" on the workflow. A run that passes its deadline stops with Experimental.Durable.DeadlineExceeded.

Resume after a crash

Nothing in a workflow's code handles a crash. To see a run resume, the following program shares one store between two engines. It interrupts the first engine while Dispatch is running, which is what a process that dies looks like to the store, and then runs the same input on a second engine.

let crashing = true
let shipStarted: Deferred.Deferred<void> | undefined = undefined
 
task Reserve {
  effect call(order: string): number!never {
    try Console.log(`reserve ${order}`)
    return 1
  }
}
 
task Dispatch {
  effect call(order: string): string!never {
    try Console.log(`ship ${order}`)
    if (crashing) {
      try Deferred.succeed(shipStarted!, undefined)
      return try never
    }
    return `${order} shipped`
  }
}
 
export workflow Shipment {
  effect call(order: string) {
    try Reserve(order)
    return try Dispatch(order)
  }
}
 
export effect function main() {
  const store = Experimental.Durable.makeMemoryStore()
  const engine = () => Layer.provideMerge(Shipment.layer, Experimental.Durable.layerStore(store))
 
  shipStarted = try Deferred.make<void>()
  const first = fork Effect.provide(Shipment("o1"), engine())
  try Deferred.await(shipStarted!)
  try Fiber.interrupt(first)
  try Console.log("-- crashed, starting again --")
 
  crashing = false
  provide engine() {
    try Console.log(try Shipment("o1"))
  }
}
 
await runPromise(main())
// Output: reserve o1
// Output: ship o1
// Output: -- crashed, starting again --
// Output: ship o1
// Output: o1 shipped

reserve o1 prints once. Reserve finished before the crash, so the second engine reads its result from the journal. ship o1 prints twice, because Dispatch started and never finished: this is the at-least-once case that an idempotencyKey covers. The second call passes no run ID. Equal input names the run, so a program that starts again with the same input resumes its own work.

Keep runs in a database

Experimental.Durable.memory forgets every run when the process exits. To keep runs across processes, provide Experimental.Durable.layerSql over a SQL client. Nothing else in the program changes. The following fragment stores runs in one SQLite file:

// fragment
import { SqliteClient } from "@effect/sql-sqlite-node"
 
const engine = Layer.provide(Experimental.Durable.layerSql, SqliteClient.layer({ filename: "runs.db" }))
 
export effect function main() {
  provide Layer.provideMerge(Triage.layer, engine) {
    try Console.log((try Triage("acme/app")).join(", "))
  }
}

Install the client that matches your runtime and database, at the Effect version that your project pins:

PackageUse it for
@effect/sql-sqlite-nodeSQLite on Node.js
@effect/sql-sqlite-bunSQLite on Bun
@effect/sql-pgPostgreSQL, when more than one machine runs workflows

layerSql creates the tables durable_runs, durable_journal and durable_cache if they are missing. Each engine that loads a run claims it, and the claim fences the run's journal: when a second process claims the run, the first process stops at its next journal write with Experimental.Durable.FenceLost. The journal therefore records each step once.

The fence covers journal writes. It does not cover what a task does outside the journal. Suppose that one process has sent a payment request and has not yet journaled StepCompleted when a second process claims the run. The second process runs the unfinished step again, and the first process learns that it lost the run only at its next journal write, so both requests can reach the payment service. For a task that changes something outside the program, set idempotencyKey and make the task send that key to the destination. Both processes then send the same key, and the destination refuses the second request.

A parked run does not wake by itself in a process that is not running. Something must execute it again: the program on its next start, a scheduler, or the send or answer call that the run waits for.

Read the plan

The compiler derives a plan from each workflow: the tasks that its body can reach, each with its declared tier and capabilities. Read it from Workflow.plan before anything runs, for example to show a reviewer which irreversible steps a run can take.

task WriteDraft {
  effect call(topic: string): string!never { return `draft about ${topic}` }
}
 
task PublishPost {
  static readonly tier = "irreversible"
  static readonly idempotencyKey = (text: string) => `publish:${text}`
  effect call(text: string): string!never { return `published ${text}` }
}
 
export workflow Post {
  effect call(topic: string) { return try PublishPost(try WriteDraft(topic)) }
}
 
export effect function main() {
  for (const node of Post.plan.nodes) {
    try Console.log(`${node.key}: ${node.tier}`)
  }
}
 
await runPromise(main())
// Output: PublishPost: irreversible
// Output: WriteDraft: sealed

The plan lists tasks, not the order or the conditions under which they run. When a run starts, the engine journals a digest of the workflow's plan. A resume under code whose plan has a different digest stops with Experimental.Durable.PlanChanged. To continue the work under the changed plan, start a new run.

The digest covers the plan and nothing else: the workflow's key and the task list. The task list holds each task that the body names, once, in the order in which the body's source text first names it, with the task's key, tier and capabilities. A change keeps the digest only when the entire ordered list stays the same. The following table lists what a change to the workflow does to a run that started before the change.

ChangeDigestResume of an old run
Add or remove a task, or change a task's tier, capabilities or keyChangesStops with PlanChanged
Change the order in which the body first names its tasks, for example by swapping the first calls of two tasksChangesStops with PlanChanged
Move a call into a condition, when the entire ordered list stays the sameSameContinues under the new code
Call a task one more time, when the entire ordered list stays the sameSameContinues under the new code
Change the arguments of a callSameContinues under the new code

One more call of a task can change the list. Suppose that the body calls A, B and C in that order. A second call of C after the first one keeps the list A, B, C. A call of C between A and B makes the list A, C, B, so an old run stops with PlanChanged.

PlanChanged does not protect a run from a change in the last three rows. The run continues: it reads the results of its finished steps from the journal and follows the new code from there. The journal holds a step's result for the arguments that the step ran with. A call whose arguments changed is a new step and runs, even when the old call had finished, so an outside effect that the old call made can happen a second time. Before you deploy such a change, let the runs that are in flight finish.

Not in this release. VIP-55 specifies a plan that includes the order of steps, branches and waits, compiled from the workflow body. This release derives the task list only.

Inspect a run

Every function in the following table reads from the engine's store, so it works from any process that provides the same engine, including one that did not start the run.

CallReturns
Experimental.Durable.spawn(W, input)A handle to the run that this input names. Starts the run if it does not exist.
Experimental.Durable.start(W, input)A handle to a new run, even when an equal input ran before.
Experimental.Durable.run(W, id)A handle to a run by ID.
handle.resultThe run's result. Waits for the run, and resumes it if it stopped.
handle.pollThe result if the run finished, without waiting.
handle.cancelCancels the run.
Experimental.Durable.waiting(id)The open waits of a parked run: timers, signals and questions.
Experimental.Durable.history(id)The run's journal, as a stream of { run, seq, eventType, payload, at }.
Experimental.Durable.runs({ status?, workflow? })The stored runs, oldest first, as a stream.
task Greet {
  effect call(name: string): string!never { return `Hello, ${name}` }
}
 
export workflow Welcome {
  effect call(name: string) { return try Greet(name) }
}
 
export effect function main() {
  provide Layer.provideMerge(Welcome.layer, Experimental.Durable.memory) {
    const handle = try Experimental.Durable.spawn(Welcome, { name: "Ada" })
    try Console.log(try handle.result)
    for try (const entry of Experimental.Durable.history(handle.id)) {
      try Console.log(`${entry.seq} ${entry.eventType}`)
    }
    for try (const run of Experimental.Durable.runs({ workflow: "Welcome" })) {
      try Console.log(`${run.workflow} ${run.status}`)
    }
  }
}
 
await runPromise(main())
// Output: Hello, Ada
// Output: 1 RunStarted
// Output: 2 PlanRecorded
// Output: 3 StepStarted
// Output: 4 StepCompleted
// Output: 5 RunCompleted
// Output: Welcome succeeded

for try reads a stream one item at a time. The journal is the record of what a run did: to debug a run, read its history first. Experimental.Durable.fork copies a run up to a journal position so that you can replay the rest under a debugger, and Experimental.Durable.rewind truncates a run to a position. For both, see Runs and time travel.

This release has no command-line tool or dashboard for runs. To list or inspect runs from a terminal, write a small entry program that calls the functions in the preceding table.

Complete example: an agent run that survives a restart

The following workflow is the shape of a long agent run: three tasks, a retry, a durable timer, a wait for a human review, and one irreversible step at the end. Each task prints one line when it really runs.

schema Review { reviewer: string; approved: boolean }
export const reviewed = Experimental.Durable.signal("reviewed", Review)
 
let researchCalls = 0
 
task Outline {
  effect call(goal: string): ReadonlyArray<string>!never {
    try Console.log(`  outline: ${goal}`)
    return ["context", "risks", "next steps"]
  }
}
 
// The first attempt fails, as a rate-limited model call does. The engine retries it.
task Research {
  static readonly retryPolicy = { initialMs: 10, factor: 2, maxMs: 100, maxAttempts: 3 }
  effect call(goal: string, sections: ReadonlyArray<string>): string!string {
    researchCalls += 1
    if (researchCalls === 1) {
      try Console.log("  research: rate limited")
      throw "rate limited"
    }
    try Console.log(`  research: ${sections.length} sections`)
    return `${goal}: ${sections.join(", ")}`
  }
}
 
task Draft {
  effect call(notes: string): string!never {
    try Console.log("  draft: written")
    return `Report on ${notes}`
  }
}
 
task Publish {
  static readonly tier = "irreversible"
  static readonly idempotencyKey = (report: string, reviewer: string) => `publish:${report}`
  effect call(report: string, reviewer: string): string!never {
    try Console.log(`  publish: approved by ${reviewer}`)
    return `published "${report}" (approved by ${reviewer})`
  }
}
 
export workflow AgentRun {
  effect call(goal: string, cooldownMs: number) {
    const sections = try Outline(goal)
    const notes = try Research(goal, sections)
    try Experimental.Durable.sleep(cooldownMs)
    const report = try Draft(notes)
    const review = try reviewed.wait()
    if (!review.approved) return `held by ${review.reviewer}`
    return try Publish(report, review.reviewer)
  }
}
 
// Waits until the run is parked on a wait with this reason.
effect function parkedOn(run: string, reason: string) {
  while (!(try Experimental.Durable.waiting(run)).some((wait) => wait.reason === reason)) {
    try sleep("5 millis")
  }
  try Console.log(`waiting: ${reason}`)
}
 
export effect function main() {
  provide Layer.provideMerge(AgentRun.layer, Experimental.Durable.memory) {
    const handle = try Experimental.Durable.spawn(AgentRun, { goal: "ship the alpha", cooldownMs: 200 })
    try parkedOn(handle.id, "event")
    try handle.send(reviewed, { reviewer: "ada", approved: true })
    try Console.log(`result: ${try handle.result}`)
  }
}
 
await runPromise(main())
// Output:   outline: ship the alpha
// Output:   research: rate limited
// Output:   research: 3 sections
// Output:   draft: written
// Output: waiting: event
// Output:   publish: approved by ada
// Output: result: published "Report on ship the alpha: context, risks, next steps" (approved by ada)

The repository holds this workflow as a project that you can kill and resume:

  • examples/agent-workflow keeps its runs in a SQLite file. Its test stops the process with SIGKILL three times: while the run waits on the timer, while it waits on the signal, and inside Publish after the publication is written. A task that finished before a stop does not run again. Publish, which the third stop interrupts, runs a second time, and its destination keeps one publication because it refuses a second delivery under the same idempotency key.
  • examples/approval parks a release on Experimental.Human.confirm for staging and for production.

From examples/agent-workflow, with vibelang installed:

bun install
bun run build
node dist/entry.js run "write the release notes"             # press Ctrl-C after the "ClockScheduled Durable.sleep#1" line
node dist/entry.js run "write the release notes"             # resumes the same run; press Ctrl-C after the "StepStarted Durable.signal/reviewed/wait" line
node dist/entry.js approve "write the release notes" grace   # sends the review; the run publishes and ends

Each command prints the run's journal. The second run prints the entries that the first one recorded and continues after them: it does not start Outline or Research again, because their results are in the journal. No run ID is saved between the commands: the goal is the workflow's input, and equal input names one run.

Start workflows on a schedule

Experimental.Trigger.cron declares a schedule for a workflow, and Experimental.Trigger.layer runs the scheduler for as long as the program runs. The following program starts Report with the input "#ops" at 03:00 UTC every day. Each fire starts a new run, although the input is equal every day: the scheduler names a run by the trigger's id and the scheduled time, not by the input.

task Summarize {
  effect call(channel: string): string!never { return `summary for ${channel}` }
}
 
export workflow Report {
  effect call(channel: string) { return try Summarize(channel) }
}
 
export effect function main() {
  const nightly = try Experimental.Trigger.cron(Report, {
    id: "nightly-report",
    cron: "0 3 * * *",
    timezone: "UTC",
    input: ["#ops"],
    overlap: "skip",
    catchUp: "one"
  })
  const engine = Layer.provideMerge(Report.layer, Experimental.Durable.memory)
  provide Layer.provideMerge(Experimental.Trigger.layer([nightly]), Layer.provideMerge(Experimental.Trigger.memory, engine)) {
    try never
  }
}
 
await runPromise(main())

The last line starts main, and try never keeps the scheduler running until you stop the program. This sample is compiled but not run on this page, because it waits for the clock. The following table lists the options of Experimental.Trigger.cron.

OptionValueDefault
idA stable name. The trigger's stored state is keyed by it.Required
cronFive fields: minute, hour, day of month, month, day of weekRequired
timezoneThe IANA zone that the fields are read in"UTC"
inputThe workflow's arguments, as an arrayRequired
overlapWhat a fire does while the last run is still going: "skip" drops it, "buffer-one" keeps the newest and starts it when the run ends, "supersede" cancels the run and starts the new one"skip"
catchUpWhat the scheduler owes for fires that passed while no scheduler ran: "none", "one" (the newest) or "all" (the newest maxCatchUp)"none"
enabledfalse stops the trigger from starting runstrue

Experimental.Trigger.memory keeps trigger state in memory, and Experimental.Trigger.layerSql keeps it in a SQL database, so that schedulers on several hosts share one schedule. Experimental.Trigger.webhook starts a workflow, or delivers a signal, from a verified HTTP request. For its options, see VIP-61.

Hand work to a queue

Experimental.WorkQueue is a durable queue. A task offers an item with process and receives the worker's result. A worker layer runs the handler for each item, with a concurrency limit.

schema RenderJob { page: string }
 
export const Renders = Experimental.WorkQueue.make("Renders", { payload: RenderJob, success: Schema.String, key: (job) => job.page })
 
export const RendersWorker = Experimental.WorkQueue.worker(Renders, effect (job) => `<html>${job.page}</html>`, { concurrency: 4 })
 
task Render {
  effect call(page: string): string!never { return try Experimental.WorkQueue.process(Renders, { page }) }
}
 
export workflow Site {
  effect call(page: string) { return try Render(page) }
}
 
export effect function main() {
  const engine = Layer.provideMerge(Site.layer, Layer.merge(Experimental.Durable.memory, Experimental.WorkQueue.memory))
  provide Layer.provideMerge(RendersWorker, engine) {
    try Console.log(try Site("home"))
  }
}
 
await runPromise(main())
// Output: <html>home</html>

key is required: it identifies an item, so a replay of the same offer names the same item instead of adding another. Experimental.WorkQueue.memory keeps the queue in this process's memory. The workflow's layer needs the queue, because Render offers to it, so the sample merges the queue with the engine before it provides both to Site.layer.

The engine in this release

In this release, task and workflow run on Experimental.Durable, a journal in vibelang-runtime over Effect's WorkflowEngine service. VIP-55 and VIP-60 specify a different engine. When a release changes the engine, runs that this release recorded are not carried over. Finish or cancel stored runs before you upgrade.