Fabric

CI fabric on Hex Gleam

Fabric runs bounded LLM agents and durable control graphs in Gleam on Erlang/OTP. Typed tools and application policy govern effects; recorded outcomes support approval and recovery. Applications provide models, domain operations, authorization and resource supervision.

Use Fabric when an agent or workflow needs typed boundaries, approval, or recovery across process loss. Fabric targets Erlang and requires Gleam 1.18 or later.

Capabilities

Typical uses

Fabric does not provide retrieval or vector storage, agent token streaming, remote agent protocols, distributed Erlang, or general workflow compensation. Saga, Relay, and Hellhound integrations are application recipes; see the module documentation and consumer examples.

Install

Add Fabric from Hex:

gleam add fabric

Commit gleam.toml and manifest.toml to retain the resolved versions. The optional PostgreSQL adapter installs from a Git subdirectory.

Start with an agent

This short-lived summarizer uses an in-memory store. Pass a model made with fabric/llm.model(client, config, model_id) and the application's started HTTP Gun client, or provide a custom fabric/model.Model.

import fabric
import fabric/agent
import fabric/model
import fabric/policy
import fabric/run
import fabric/store
import fabric/store/backend
import gleam/erlang/process
import gleam/option.{None}
import gleam/result
import gleam/time/duration

pub type Error {
  InvalidAgent(List(agent.ConfigError))
  StoreFailed(backend.StoreError)
  RunFailed(fabric.Error)
}

pub fn summarize(
  model: model.Model,
  text: String,
) -> Result(run.Status(String), Error) {
  use summarizer <- result.try(
    agent.new("summarizer", model, [], policy.always_allow())
    |> agent.with_system_prompt("Summarize the supplied text in one paragraph.")
    |> agent.with_max_turns(2)
    |> agent.with_model_timeout(run.After(duration.seconds(20)))
    |> agent.build
    |> result.map_error(InvalidAgent),
  )
  let runs = store.in_memory(process.new_name("summaries"))
  use Nil <- result.try(store.start(runs) |> result.map_error(StoreFailed))
  let outcome =
    fabric.start(
      runs,
      summarizer,
      id: run.new_id(),
      context: Nil,
      prompt: text,
      correlation: None,
    )
    |> result.try(fabric.await(_, within: duration.seconds(45)))
    |> result.map_error(RunFailed)
  use Nil <- result.try(store.stop(runs) |> result.map_error(StoreFailed))
  outcome
}

The in-memory records disappear when the store stops. Services needing recovery supervise a persistent store and keep each run id. A completed answer does not prove every action succeeded; inspect fabric.snapshot before treating it as business success.

Core model

The application builds a checked Agent or Graph definition and starts runs in a Store. The store retains run state and supervises runners; a handle only addresses a run, not its worker. Typed Tool and graph Operation boundaries classify external results, while application Policy and approval verifiers decide who may proceed.

flowchart LR
  app[Application] -->|defines and starts| control[Agent or graph]
  app -->|owns| supervisor[OTP supervisor]
  supervisor --> store[Store]
  control -->|committed transitions| store
  store -->|supervises| runners[Runners]
  store --> backend[Memory, directory, or custom backend]
  runners --> model[Model or provider]
  runners --> effects[Tools and graph operations]

Ownership and recovery

Handing a call over to another system

When a person or another system decides a call, possibly days later, the policy hands it over with policy.HandOver(reason). The run ends at once as run.HandedOver, with the call's action, tool and arguments as recorded: the tool never runs, the model takes no further turn, and no approval is left to answer or expire. Other calls of the same model reply that had not started are withdrawn. The application files the call keyed by its action's text form (run.action_ref_to_string, read back with run.parse_action_ref). When the decision is recorded, fabric.handover_history returns the conversation with the decision as the call's result, and input.continuation starts a follow-on run from it with no new user message, so the model continues from the decision as it would have in the original run. Add a prompt with input.new only when the application has something new to tell the model.

The follow-on run has the same agent and the same policy. A policy that always hands the call over hands it over again if the follow-on model repeats the call, so the policy recognises the follow-on, here from its context, and denies the repeat.

/// Which run the policy decides for: the one that proposes, or the
/// follow-on that tells the customer what was decided.
pub type Stage {
  Deciding
  Telling
}

/// Refunds are decided by finance, never by the agent's run. The follow-on
/// run has the same agent and policy: there a repeated refund call is
/// denied, or it would be handed over again.
fn refund_policy(stage: Stage, action: policy.Action) {
  case action.name, stage {
    "refund_fee", Deciding ->
      Ok(policy.HandOver("refunds are decided by finance"))
    "refund_fee", Telling -> Ok(policy.Deny("the refund is already decided"))
    _, _ -> Ok(policy.Allow)
  }
}

/// Runs the agent until it rests. A handover gives the application the
/// call to file, keyed by its action's text form.
fn file_refund(
  runs: store.Store,
  desk: agent.Agent(Stage, String),
  id: run.RunId,
) -> Result(#(String, String), String) {
  let assert Ok(handle) =
    fabric.start(
      runs,
      desk,
      id:,
      context: Deciding,
      prompt: "Refund Ana's fee.",
      correlation: None,
    )
  case fabric.await(handle, within: duration.seconds(5)) {
    Ok(run.Finished(run.HandedOver(action:, arguments_json:, ..))) ->
      Ok(#(run.action_ref_to_string(action), arguments_json))
    other -> Error(string.inspect(other))
  }
}

/// Once the decision is recorded: a follow-on run continues the handed-over
/// conversation from the decision, given as the call's result.
fn tell(
  runs: store.Store,
  desk: agent.Agent(Stage, String),
  handed: run.RunId,
  decided: String,
) -> Result(fabric.Run(Stage, String), String) {
  use first <- result.try(
    fabric.open(runs, desk, Deciding, handed)
    |> result.map_error(string.inspect),
  )
  use snapshot <- result.try(
    fabric.snapshot(first) |> result.map_error(string.inspect),
  )
  use history <- result.try(
    fabric.handover_history(snapshot, result: decided)
    |> result.map_error(string.inspect),
  )
  use follow <- result.try(
    input.continuation(history) |> result.map_error(string.inspect),
  )
  fabric.start_with_input(
    runs,
    desk,
    id: run.new_id(),
    context: Telling,
    input: follow,
    correlation: None,
  )
  |> result.map_error(string.inspect)
}

Only a run that ended HandedOver has a handover history. A run parked on an approval under the earlier approach and then ended with fabric.cancel cannot be continued this way in 0.3.0: an application moving from parking to handing over tells those in-flight cases from its own record or starts a fresh run.

A graph run takes no handover; it waits for the other system as a signal. See usage/handover and ADR 0021.

Examples

The usage examples cover bounds, failure classification, waiting, budgets, reconciliation, and recovery. The graph consumer, decision consumer, jobs consumer, and writing consumer show larger applications. The PostgreSQL adapter documents database-backed leases and operations.

Generation settings are fixed on a model instance and supplied again when rebuilding a runtime. Fabric retains its own messages, tools, answer decoding, and correlation. This checked excerpt assumes imports from fabric/agent, fabric/llm, fabric/policy, llm_wire/generation, and json/blueprint/codec; client and config come from your provider setup.

let settings =
  generation.default()
  |> generation.with_max_tokens(128)
  |> generation.with_temperature(0.2)
let assert Ok(agent) =
  agent.new(
    "configured",
    llm.configured_model(client, config, "fixture", settings),
    [],
    policy.always_allow(),
  )
  |> agent.with_answer(codec.int())
  |> agent.build

The design defines supported contracts, limits, and unbuilt capabilities. BENCHMARKS.md records historical live-provider measurements and their limits; Fabric has no runtime benchmark harness. See AGENTS.md for development and validation commands.