Skip to content

Orchestration patterns and PACKAGE.vibe

Experimental. Experimental.Patterns needs { "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 it.

Experimental.Patterns names the shapes that agentic programs repeat: ask several reviewers and let one decide, draft and revise until a review approves, or undo finished steps when a later step fails. A pattern is a function. It takes its stages as functions that return Effects (descriptions of work that run when you try them), and it returns one Effect. Use a pattern when a hand-written loop would restate one of these shapes. PACKAGE.vibe is the second subject of this page: a build declaration written as a Vibe module. The design for both is VIP-73.

effect function grade(reviewer: string, revision: string) {
  return { reviewer, lgtm: revision.length > 0 }
}
 
export effect function gate(revision: string) {
  return try Experimental.Patterns.Panel.run(revision, {
    panelists: {
      security: (revision: string) => grade("security", revision),
      style: (revision: string) => grade("style", revision)
    },
    moderator: effect ({ opinions }) => Object.keys(opinions).filter((name) => opinions[name].lgtm).join(" and ")
  })
}
// Run in an effect function: try Console.log(try gate("r1"))
// Output: security and style

Panel.run gives every panelist the same input, then gives the moderator { input, opinions }. opinions is keyed by panelist name, in the order you wrote the panelists, whatever order they finish in. The types of the result, the failures and the required services come from the stages you pass.

Patterns

The following table lists every pattern in Experimental.Patterns. Each name is a namespace, such as Experimental.Patterns.Panel.

CallWhat it does
Panel.run(input, { panelists, moderator, concurrency? })Asks every panelist the same input, then lets one moderator decide
ReviewLoop.run(input, { produce, review, revise, maxRounds, stall? })Produces, reviews and revises until a review approves or the rounds are spent
Debate.run(input, { rounds, proponent, opponent, judge })Runs a bounded, alternating exchange that a judge settles
Escalation.run(input, { rungs, accept?, fallback? })Tries each rung in order until one result is accepted
MapReduce.run({ shards }, { map, reduce, concurrency, onEmpty })Maps every shard, then reduces the results in shard order
Bounded.run(members, { concurrency, priority?, priorities? })Runs a record of Effects at a concurrency bound, highest priority first
Quarantine.run(members, { policy, concurrency? }), Quarantine.settle(result)Continues past a failed member and reports each as Succeeded or Quarantined
Saga.run(input, { steps, onFailure? })Runs steps in order and undoes the completed ones, newest first, when one fails
CheckSuite.run(input, { checks, strategy, concurrency, continueOnFail })Runs independent checks and reduces them to one verdict
MergeQueue.run(input, { members, failurePolicy, concurrency?, priority? })Lands members in one prioritized order
Runbook.run(input, { steps, approve, onDeny })Runs ordered steps, and asks for approval before a risky or critical step
Kanban.run(items, { columns, concurrency })Moves every item through ordered columns
Supervisor.run(input, { plan, worker, review, finalize, … })Lets one boss plan tasks, delegate them to workers and review the outcomes
Sidecar.run(input, { primary, shadow, score? })Runs a cheaper shadow beside the primary and scores the gap
DriftDetector.run(input, { baseline, capture, compare, alertIf?, alert? })Captures a snapshot, compares it with a baseline and alerts on drift
Intervene.run(input, { read, propose, apply, report, dryRun, approval? })Reads a target, proposes a change and applies it behind an optional approval
Trellis.validate(plan, envelope), Trellis.execute(plan, options)Checks and runs a delegation plan that a model wrote, inside a fixed envelope
DelegationChain.run(prompt, options)Runs a fixed chain: refine, plan, derisk, execute, review and settle
Optimizer.run(input, { generate, evaluate, maxIterations, targetScore? })Generates and evaluates candidates until a target score or the iteration bound
ScanFixVerify.run(input, { scan, fix, verify, maxRetries, maxIssues, concurrency })Fixes every issue a scan finds, and repeats until a scan is clean
Recursion.run(tree, { child, fuel, depth, fanout, parent? })Expands a tree of inputs inside a depth and fan-out envelope
Burndown.round(input, options), Burndown.run(input, { discover, dispatch, capacity?, maxRounds })Claims, works, lands and releases a backlog, round after round
Stall.policy(options), Stall.observe(policy, state, observation)The stall breaker that ReviewLoop and Supervisor use, for your own loops
PatternErrorThe failure that every pattern uses to refuse bad options: code, message, cause?

Orchestration patterns has a sample and the full rules for each pattern. Only the run forms exist. The make forms that declare a graph before anything runs are not in this release.

Review and revise in a loop

ReviewLoop.run returns a tagged result, so match tells an approved output from a spent loop.

export effect function releaseNotes() {
  const result = try Experimental.Patterns.ReviewLoop.run("notes", {
    maxRounds: 3,
    produce: effect (goal: string) => `${goal} v1`,
    review: effect (_output: string, round: number) => ({ approved: round === 2 }),
    revise: effect ({ round }) => `notes v${round + 1}`
  })
  return match (result) {
    when { _tag: "Approved", let output }: output;
    default: `not approved: ${result._tag}`;
  }
}
// Run in an effect function: try Console.log(try releaseNotes())
// Output: notes v2

A review approves with true, with "approved", or with an object whose own approved or accepted property is true. Any other review asks for a revision. maxRounds counts reviews, and a spent loop returns { _tag: "Exhausted", output, review }. With stall: { rounds, on? }, a loop whose output repeats rounds times in a row returns { _tag: "Stalled", … }.

Undo completed steps

Saga.run runs each step's action in order. When a step fails, the compensation of each completed step runs, newest first.

error SoldOut { item: string }
 
export effect function book() {
  const cancelled: string[] = []
  const result = try Experimental.Patterns.Saga.run("trip", {
    steps: [
      { id: "flight", action: effect (_state) => "F12", compensation: effect ({ value }: { value: string }) => { cancelled.push(value) } },
      { id: "hotel", action: effect (_state) => { throw new SoldOut({ item: "hotel" }) }, compensation: effect () => {} }
    ]
  })
  return `${result._tag}, cancelled ${cancelled.join(", ")}`
}
// Run in an effect function: try Console.log(try book())
// Output: Compensated, cancelled F12

The default onFailure: "compensate" returns { _tag: "Compensated", failure }. "compensate-and-fail" fails with the step's failure after the unwind, and "fail" undoes nothing. A run where every step finishes returns { _tag: "Completed", values }.

Make stages durable

A pattern adds no durability of its own. A stage is a durable step only when it calls a task of Experimental.Durable inside a workflow.

const asked: Array<string> = []
const Ask = Experimental.Durable.task("docs#Ask", { payload: { reviewer: Schema.String, revision: Schema.String }, success: Schema.Boolean })
const SpecGate = Experimental.Durable.workflow("docs#SpecGate", { payload: { revision: Schema.String }, success: Schema.Boolean })
 
const SpecGateLive = SpecGate.toLayer(effect ({ revision }) => {
  return Experimental.Patterns.Panel.run(revision, {
    panelists: {
      security: (revision: string) => Ask({ reviewer: "security", revision }),
      style: (revision: string) => Ask({ reviewer: "style", revision })
    },
    moderator: effect ({ opinions }) => Object.values(opinions).every((lgtm) => lgtm)
  }) catch () => false
}).pipe(
  Layer.provide(Ask.toLayer(effect ({ reviewer, revision }) => { asked.push(reviewer); return revision.length > 0 })),
  Layer.provideMerge(Experimental.Durable.memory)
)
 
export effect function twice() {
  provide SpecGateLive {
    const first = try SpecGate.execute({ revision: "r1" })
    const again = try SpecGate.execute({ revision: "r1" })
    return [first, again, asked.sort()]
  }
}
// Run in an effect function: try Console.log(try twice())
// Output: [ true, true, [ 'security', 'style' ] ]

Each panelist is one journaled step, so the second execute joins the finished run and asks nobody again. catch () => false handles the PatternError that Panel.run can fail with, because this workflow declares no failure type.

This sample uses the library forms Experimental.Durable.task and Experimental.Durable.workflow. Inside a workflow declaration, a pattern call reports EK5504, and a task called from a stage callback reports EK5502. Patterns inside workflow declarations are not in this release.

Handle bad options

A pattern does not throw. It fails with Experimental.Patterns.PatternError as a typed failure, so catch handles it.

export effect function refused() {
  const panel = Experimental.Patterns.Panel.run("r1", {
    panelists: { style: effect (revision: string) => revision.length },
    moderator: effect ({ opinions }) => `${opinions.style}`,
    concurrency: 0
  })
  return panel catch (error) => `${error.code}: ${error.message}`
}
// Run in an effect function: try Console.log(try refused())
// Output: invalid_decorator: Panel concurrency must be a positive safe integer, received 0

code is one of missing_slot, recursion_bound, envelope_conflict, invalid_decorator, invalid_input, exhausted, stalled, quarantined or compensation_failed. A pattern reads its options once, at the call. A later change to the options object does not reach a run that has not started.

PACKAGE.vibe

A PACKAGE.ts file declares a directory's build targets for the build tool that this repository uses, with constructors from @smthrs/targets. VIP-73 accepts the same declaration in a file named PACKAGE.vibe. The file is an ordinary Vibe module: it has no special file kind, scope or syntax, and it exports the same values.

// PACKAGE.vibe
import { Filegroup } from "@smthrs/targets/Filegroup"
import { glob } from "@smthrs/targets/Input"
import { Package as declare } from "@smthrs/targets/Package"
 
export const Package = declare({
  targets: {
    sources: Filegroup({ srcs: [glob("src/**/*.vibe")] })
  }
})

To write one, import the target constructors as a PACKAGE.ts does and export a Package value. A declaration builds values and runs nothing, so it has no top-level Effect. This module type-checks with the vibe compiler when @smthrs/targets is installed. It needs no experimental switch.

The following parts of VIP-73 are not in this release:

  • Discovery. The build tool in this checkout finds PACKAGE.ts files only. It does not find, load or run a PACKAGE.vibe file, and this repository contains none.
  • The conflict diagnostic. Nothing reports a directory that holds both PACKAGE.ts and PACKAGE.vibe.

Until a build tool loads PACKAGE.vibe, declare build targets in PACKAGE.ts.

Rules and diagnostics

The patterns add no diagnostics of their own. The following table lists the codes this page mentions.

Code or errorCondition
EK3013A file uses Experimental.Patterns without the builtins switch
EK5504A workflow declaration runs something other than a durable step with try, such as a pattern
EK5502A task is called outside a workflow's effect call, such as in a stage callback
PatternErrorA pattern refuses its options or cannot finish. code names the reason