Workflows Cloudflare pour agents

VérifiéSûr

Pair un agent avec un workflow Cloudflare durable pour exécuter des tâches de longue durée avec reprise et retry.

Spar Skills Guide Bot
DeveloppementIntermédiaire
01/08/2026
Claude CodeCursorCodex
#cloudflare-workers#durable-execution#agent-framework#workflow-orchestration#typescript

Recommandé pour

Synthèse automatique

Ce skill fait créer un Cloudflare Workflow durable dans `agents/<route>/workflow.ts`, appairé à un agent ayjnt, avec binding, stub RPC typé et mixin `withWorkflow` générés par le framework.

Points forts

  • Convention de fichier simple (workflow.ts à côté de agent.ts) : le framework découvre le workflow au scan et émet le binding, sans chaîne de liaison magique.
  • Le mixin curryfié `withWorkflow<W>()(Base)` conserve le typage de bout en bout : les params sont vérifiés et `this.agent` reste typé.
  • Aucune migration nécessaire : l'état vit dans le Durable Object de l'agent, le workflow n'étant qu'un conteneur d'exécution éphémère.
  • Couvre les deux usages : `AgentWorkflow` pour un RPC typé vers l'agent et `WorkflowEntrypoint` pour du fire-and-forget.

Limites

  • Fortement couplé au framework ayjnt : la détection repose sur une regex source qui exige `extends AgentWorkflow` / `extends WorkflowEntrypoint` et interdit les imports aliasés.
  • Le skill s'arrête au cas des workflows colocalisés ; la section sur les workflows hors du dossier de l'agent est tronquée.
  • Peu de détails sur la gestion d'erreurs et les stratégies de retry au-delà de `step.do` et `step.sleep`.
Quand l'utiliser

À utiliser lorsqu'il faut ajouter à un agent ayjnt un traitement long, durable et reprenable, comme du traitement de commandes ou des retries avec backoff survivant aux redémarrages du worker.

Quand l'éviter

À éviter si le projet n'utilise pas le framework ayjnt ou si le travail est court et peut rester dans le handler de requête de l'agent.

Analyse de sécurité

Sûr
Score qualité82/100

This is purely technical documentation describing TypeScript code patterns for pairing agents with Cloudflare Workflows. It contains no executable shell commands, no destructive operations, no network exfiltration, no base64 payloads, and no attempts to disable safety controls. No tools are declared or invoked—the skill only presents illustrative code snippets that a developer would hand-write. Risk of listing is negligible.

Aucun point d'attention détecté

Comment cette analyse est faite

Exemples

Add a durable order workflow
Add a workflow to my orders agent: mark the order as running, call the payment API, then sleep 5 seconds before sending the confirmation.
Survive restarts with retries
Make my agent's order processing durable so it retries with backoff and survives worker restarts.
Trigger a workflow from the agent
Extend AgentWorkflow in agents/orders/workflow.ts and wire it up so onRequest can trigger it with a typed this.workflow(params) call.

name: ayjnt-workflows description: Pair an agent with a durable Cloudflare Workflow. Use when the user asks to "add a workflow", "run a long-running job", "extend AgentWorkflow", "make order processing durable", "retry with backoff", or "survive worker restarts". Creates agents/<route>/workflow.ts next to agent.ts; the framework wires the workflow binding, the typed RPC stub, and the GeneratedEnv field. Uses the withWorkflow<typeof MyWorkflow>()(Agent) mixin so the agent gets a typed this.workflow(params) shortcut with no magic binding strings. NO migrations — workflows are ephemeral execution containers; state lives in the paired Agent's DO.

Pair an agent with a workflow

workflow.ts next to agent.ts is the entire convention. The default-exported class extends AgentWorkflow (typed RPC back to the agent) or WorkflowEntrypoint (fire-and-forget). The framework discovers it at scan time and emits the binding.

File shape

// agents/<route>/workflow.ts
import { AgentWorkflow } from "agents/workflows";
import type { AgentWorkflowEvent } from "agents/workflows";
import type { WorkflowStep } from "cloudflare:workers";
import type MyAgent from "./agent.ts";

type Params = { /* user-defined params */ };

export default class MyWorkflow extends AgentWorkflow<MyAgent, Params> {
  async run(
    event: Readonly<AgentWorkflowEvent<Params>>,
    step: WorkflowStep,
  ): Promise<unknown> {
    const params = event.payload;

    await step.do("step-one", async () => {
      // durable work
      await this.agent.markStatus(params.id, "running");
    });

    const result = await step.do("step-two", async () => {
      // each step.do persists its return value
      return { something: "useful" };
    });

    await step.sleep("wait-a-bit", "5 seconds");

    return result;
  }
}

Rules

  • Default-export the class. ayjnt scans agents/**/workflow.ts files and reads the default export.
  • extends AgentWorkflow for typed RPC back to the agent. extends WorkflowEntrypoint when the workflow doesn't talk to an agent. ayjnt detects either.
  • Generic params: AgentWorkflow<AgentType, Params> — first arg is the paired Agent class (gives you this.agent with typed RPC); second is the workflow's payload type.
  • No aliased imports for the base class. The detection is source-level regex on extends AgentWorkflow / extends WorkflowEntrypoint.

Triggering from the agent

Use the withWorkflow mixin so you don't have to type the binding name. The framework knows the pairing from the file layout and injects the binding onto the agent's prototype at build time:

// agents/<route>/agent.ts
import { Agent } from "agents";
import { withWorkflow } from "ayjnt/workflow";
import type { GeneratedEnv } from "@ayjnt/env";
import type MyWorkflow from "./workflow.ts";

export default class MyAgent
  extends withWorkflow<typeof MyWorkflow>()(Agent)<GeneratedEnv, State>
{
  override async onRequest(req: Request): Promise<Response> {
    const params = await req.json();

    // No magic binding string — params type-checked against
    // MyWorkflow's Params generic. IntelliSense knows the shape.
    const workflowId = await this.workflow(params);

    return Response.json({ workflowId });
  }

  // The workflow calls this back via this.agent.markStatus(...)
  async markStatus(id: string, status: string): Promise<void> {
    this.setState({ /* … */ });
  }
}

Why curried

withWorkflow<W>()(Base) curries: the outer call binds the workflow type, the inner takes the base class. TypeScript can't partially infer one generic from a type arg and another from a value arg in a single call, so currying is the cleanest way to keep the syntax ergonomic while preserving Agent's <Env, State> parameterization downstream.

For non-co-located workflows

If a workflow lives outside the agent's folder (e.g. a fire-and-forget batch under a separate workflows/ tree), don't use the mixin. Call the SDK's runWorkflow directly with the binding name:

const workflowId = await this.runWorkflow("CLEANUP_JOB", params);

this.runWorkflow(binding, params) is provided by the SDK's Agent base class. The binding is type-checked against bindings ayjnt generated.

Name derivation

Class name drives everything:

  • OrdersProcessing → binding ORDERS_PROCESSING
  • OrdersProcessing → workflow name orders-processing (kebab)
  • OrdersProcessing → class_name: "OrdersProcessing"

Bindings must be unique across agents and workflows; the scanner errors at build time if two classes would collide.

What gets generated

// .ayjnt/dist/wrangler.jsonc
"workflows": [
  {
    "name": "orders-processing",
    "binding": "ORDERS_PROCESSING",
    "class_name": "OrdersProcessing"
  }
]
// .ayjnt/env.d.ts
export type GeneratedEnv = {
  ORDERS_AGENT: DurableObjectNamespace<OrdersAgent>;
  ORDERS_PROCESSING: Workflow;  // ← workflow binding, typed
};
// .ayjnt/dist/entry.ts
import OrdersProcessing from "../../agents/orders/workflow.ts";
export { OrdersProcessing };  // Cloudflare runtime registers the class

Workflows ≠ Durable Objects

  • No entries in migrations[]. Workflows are ephemeral execution containers. The framework will refuse to add a workflow class to the SQLite migrations.
  • State lives in the paired Agent's DO. Workflows don't have this.state. If you need state, RPC back into the agent and have it call setState.

step.do contract

Each step.do("name", fn) block is:

  • Idempotent across retries — if fn throws, the framework retries with exponential backoff. If the worker restarts, execution resumes from the last successful step using the persisted return value.
  • Keyed by name. Renaming a step in a deployed workflow makes the runtime think it's a new step and re-execute it. Treat step names like database column names — stable across deploys.

step.sleep("name", duration) also survives restarts.

Pair with a UI

The agent ⇄ workflow loop is naturally visible — each step.do flips the order's status, which broadcasts over WebSocket. Drop an app.tsx next to the agent and use the generated useAgent hook:

// agents/<route>/app.tsx
import { useAgent } from "@ayjnt/orders";

export default function OrdersUI() {
  const agent = useAgent();
  const orders = (agent.state as { orders?: Order[] })?.orders ?? [];
  // call agent.call("placeOrder", [{ sku, qty, customerId }]) on submit
  // render orders with their live status
}

Make the agent's trigger method @callable({ description: "..." }) so the UI can drive it via agent.call(method, args) without going through fetch.

Looking up a running workflow

// Inside the agent
const instance = await this.env.MY_WORKFLOW.get(workflowId);
const status = await instance.status();
// → { status: "running" | "complete" | "errored" | ..., output?: ... }

When NOT to use a workflow

  • The task is a single fetch + return → just do it in the agent.
  • The task is a stateless background side-effect → use{" "} this.ctx.waitUntil(fetch(...)).
  • The task needs millisecond-precision orchestration → workflows have per-step overhead; use the agent's scheduler instead.

Reach for workflows when you want durable, multi-step, retry-aware execution.

Reference

Du fichier au premier essai

Le téléchargement contient exactement le contenu affiché sur cette fiche. Cette copie peut différer de la dernière version du dépôt source.

Consulter la source et ses fichiers annexes

Ce téléchargement contient uniquement SKILL.md. Les scripts, références, modèles et dépendances éventuels ne sont pas inclus. Récupérez les fichiers nécessaires depuis la source en conservant leur arborescence avant de poursuivre.

1. Télécharger le fichier

Télécharger SKILL.md

Depuis la racine d’un projet de test, enregistrez le fichier sous .skill-downloads/cloudflare-workflows-for-agents-ms9wny4n/SKILL.md, ou utilisez la commande suivante. Ce dossier sert à examiner la skill avant son installation.

Commande pour macOS/Linux ou WSL : un shell POSIX et curl sont nécessaires. Sous Windows sans WSL, utilisez le bouton de téléchargement et créez le dossier manuellement.

mkdir -p '.skill-downloads/cloudflare-workflows-for-agents-ms9wny4n' && curl --fail --show-error --location 'https://skills-guides.com/api/skills/cloudflare-workflows-for-agents-ms9wny4n/download' --output '.skill-downloads/cloudflare-workflows-for-agents-ms9wny4n/SKILL.md.part' && mv '.skill-downloads/cloudflare-workflows-for-agents-ms9wny4n/SKILL.md.part' '.skill-downloads/cloudflare-workflows-for-agents-ms9wny4n/SKILL.md'

2. Vérifier les prérequis

Lisez SKILL.md avant de l’utiliser. Si le fichier cite des scripts ou services externes, examinez-les et préparez les accès nécessaires dans votre environnement de test.

Aucune section de prérequis reconnue dans ce fichier. Cela ne signifie pas qu’il est autonome : les bibliothèques, outils et accès peuvent être cités ailleurs dans le contenu ou dans le dépôt source.

Les plateformes de la fiche sont des indications du catalogue. Les chemins ci-dessous suivent la documentation des outils ; ils ne prouvent pas que cette skill y a été exécutée. Aucune version minimale de ces outils n’est attestée pour cette fiche.

3. Charger la skill

Après vérification, copiez le dossier complet dans le projet avec l’une des commandes ci-dessous, puis ouvrez une nouvelle session de l’outil. La commande s’arrête si un dossier du même nom existe déjà : comparez les fichiers avant de le remplacer.

Claude Code
test -f '.skill-downloads/cloudflare-workflows-for-agents-ms9wny4n/SKILL.md' && test -s '.skill-downloads/cloudflare-workflows-for-agents-ms9wny4n/SKILL.md' && mkdir -p '.claude/skills' && test ! -e '.claude/skills/ayjnt-workflows' && cp -R '.skill-downloads/cloudflare-workflows-for-agents-ms9wny4n' '.claude/skills/ayjnt-workflows'

Cursor
test -f '.skill-downloads/cloudflare-workflows-for-agents-ms9wny4n/SKILL.md' && test -s '.skill-downloads/cloudflare-workflows-for-agents-ms9wny4n/SKILL.md' && mkdir -p '.cursor/skills' && test ! -e '.cursor/skills/ayjnt-workflows' && cp -R '.skill-downloads/cloudflare-workflows-for-agents-ms9wny4n' '.cursor/skills/ayjnt-workflows'

Codex
test -f '.skill-downloads/cloudflare-workflows-for-agents-ms9wny4n/SKILL.md' && test -s '.skill-downloads/cloudflare-workflows-for-agents-ms9wny4n/SKILL.md' && mkdir -p '.agents/skills' && test ! -e '.agents/skills/ayjnt-workflows' && cp -R '.skill-downloads/cloudflare-workflows-for-agents-ms9wny4n' '.agents/skills/ayjnt-workflows'

OpenSkills

OpenSkills doit déjà être installé. La procédure locale install/read est contrôlée avec OpenSkills 1.5.0, qui exige Node.js ≥ 20.6.0. Aucun slug du catalogue n’est résolu automatiquement.

Installation officielle d’OpenSkills
openskills install './.skill-downloads/cloudflare-workflows-for-agents-ms9wny4n'

openskills read 'cloudflare-workflows-for-agents-ms9wny4n'

La lecture doit afficher le contenu du fichier installé et son dossier de base. Elle ne lance ni la skill ni ses dépendances.

Pour un agent qui lit AGENTS.md, synchronisez ensuite l’index. Cette commande modifie AGENTS.md : relisez le diff avant de l’utiliser.

openskills sync

Mode manuel ou autre outil : joignez SKILL.md à une conversation, ou ouvrez-le dans un agent capable de lire les fichiers. Ajoutez les ressources annexes nécessaires. Il n’existe pas de dossier universel reconnu par tous les outils.

4. Faire un premier essai

Utilisez une entrée courte et fictive : un endpoint d’API, un petit document ou un brief d’interface. Dans une nouvelle conversation, joignez le fichier ou donnez son chemin à l’agent, puis adaptez cette demande :

Lis .skill-downloads/cloudflare-workflows-for-agents-ms9wny4n/SKILL.md et applique ses instructions à cet exemple : [décrire une entrée de test]. Indique les fichiers, dépendances ou accès qui manquent. Produis le résultat demandé par la skill sans inventer de données ni exécuter de script non examiné.

Résultat attendu : une sortie correspondant aux instructions de la skill, ou une liste précise des prérequis manquants. Une simple confirmation de lecture ne valide pas le premier usage. Si une ressource externe est indisponible, ce parcours reste à tester.

Skills similaires