[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7AK4EXVP70S6258TQ411K7A":3,"skill-same:01M7AK4EXVP70S6258TQ411K7A":60},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":15,"categories":16,"keywords":17,"publishedAt":18,"linkOnly":19,"markdownContent":20,"markdownBody":21,"frontMatter":22,"refName":24,"commitSha":25,"skillDirectory":5,"forksCount":26,"repositoryHtmlUrl":27,"repositoryHomepageUrl":6,"ownerHtmlUrl":28,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":29,"install":30,"resources":43},"01M7AK4EXVP70S6258TQ411K7A","cloudflare-workflows",null,"Complete knowledge domain for Cloudflare Workflows - durable execution framework\nfor building multi-step applications on Workers that automatically retry, persist\nstate, and run for hours or days.\n\nUse when: creating long-running workflows, implementing retry logic, building\nevent-driven processes, scheduling multi-step tasks, coordinating between APIs,\nor encountering \"NonRetryableError\", \"I\u002FO context\", \"workflow execution failed\",\n\"serialization error\", or \"WorkflowEvent not found\" errors.\n\nKeywords: cloudflare workflows, workflows workers, durable execution, workflow step,\nWorkflowEntrypoint, step.do, step.sleep, workflow retries, NonRetryableError,\nworkflow state, wrangler workflows, workflow events, long-running tasks, step.sleepUntil,\nstep.waitForEvent, workflow bindings","davidanthonyn\u002Fagent-skills","davidanthonyn","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F55152980?v=4","01M7AJ4MY8S5C2RJCGX6626J0G","01M7AJ4MZB7EC7CAP27ANCSE7N",1,"MIT","https:\u002F\u002Fgithub.com\u002Fdavidanthonyn\u002Fagent-skills\u002Fblob\u002Fmain\u002Fcloudflare-workflows\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: cloudflare-workflows\ndescription: |\n  Complete knowledge domain for Cloudflare Workflows - durable execution framework\n  for building multi-step applications on Workers that automatically retry, persist\n  state, and run for hours or days.\n\n  Use when: creating long-running workflows, implementing retry logic, building\n  event-driven processes, scheduling multi-step tasks, coordinating between APIs,\n  or encountering \"NonRetryableError\", \"I\u002FO context\", \"workflow execution failed\",\n  \"serialization error\", or \"WorkflowEvent not found\" errors.\n\n  Keywords: cloudflare workflows, workflows workers, durable execution, workflow step,\n  WorkflowEntrypoint, step.do, step.sleep, workflow retries, NonRetryableError,\n  workflow state, wrangler workflows, workflow events, long-running tasks, step.sleepUntil,\n  step.waitForEvent, workflow bindings\nlicense: MIT\n---\n\n# Cloudflare Workflows\n\n**Status**: Production Ready ✅\n**Last Updated**: 2025-10-22\n**Dependencies**: cloudflare-worker-base (for Worker setup)\n**Latest Versions**: wrangler@4.44.0, @cloudflare\u002Fworkers-types@4.20251014.0\n\n---\n\n## Quick Start (10 Minutes)\n\n### 1. Create a Workflow\n\nUse the Cloudflare Workflows starter template:\n\n```bash\nnpm create cloudflare@latest my-workflow -- --template cloudflare\u002Fworkflows-starter --git --deploy false\ncd my-workflow\n```\n\n**What you get:**\n- WorkflowEntrypoint class template\n- Worker to trigger workflows\n- Complete wrangler.jsonc configuration\n\n### 2. Understand the Basic Structure\n\n**src\u002Findex.ts:**\n\n```typescript\nimport { WorkflowEntrypoint, WorkflowStep, WorkflowEvent } from 'cloudflare:workers';\n\ntype Env = {\n  MY_WORKFLOW: Workflow;\n};\n\ntype Params = {\n  userId: string;\n  email: string;\n};\n\nexport class MyWorkflow extends WorkflowEntrypoint\u003CEnv, Params> {\n  async run(event: WorkflowEvent\u003CParams>, step: WorkflowStep) {\n    \u002F\u002F Access params from event.payload\n    const { userId, email } = event.payload;\n\n    \u002F\u002F Step 1: Do some work\n    const result = await step.do('process user', async () => {\n      return { processed: true, userId };\n    });\n\n    \u002F\u002F Step 2: Wait before next action\n    await step.sleep('wait 1 hour', '1 hour');\n\n    \u002F\u002F Step 3: Continue workflow\n    await step.do('send email', async () => {\n      \u002F\u002F Send email logic\n      return { sent: true, email };\n    });\n\n    \u002F\u002F Optional: return final state\n    return { completed: true, userId };\n  }\n}\n\n\u002F\u002F Worker to trigger workflow\nexport default {\n  async fetch(req: Request, env: Env): Promise\u003CResponse> {\n    \u002F\u002F Create new workflow instance\n    const instance = await env.MY_WORKFLOW.create({\n      params: { userId: '123', email: 'user@example.com' }\n    });\n\n    return Response.json({\n      id: instance.id,\n      status: await instance.status()\n    });\n  }\n};\n```\n\n### 3. Configure Wrangler\n\n**wrangler.jsonc:**\n\n```jsonc\n{\n  \"name\": \"my-workflow\",\n  \"main\": \"src\u002Findex.ts\",\n  \"compatibility_date\": \"2025-10-22\",\n  \"workflows\": [\n    {\n      \"name\": \"my-workflow\",\n      \"binding\": \"MY_WORKFLOW\",\n      \"class_name\": \"MyWorkflow\"\n    }\n  ]\n}\n```\n\n### 4. Deploy and Test\n\n```bash\n# Deploy workflow\nnpm run deploy\n\n# Trigger workflow (visit in browser or curl)\ncurl https:\u002F\u002Fmy-workflow.\u003Csubdomain>.workers.dev\u002F\n\n# View workflow instances\nnpx wrangler workflows instances list my-workflow\n\n# Check instance status\nnpx wrangler workflows instances describe my-workflow \u003Cinstance-id>\n```\n\n---\n\n## WorkflowEntrypoint Class\n\n### Extend WorkflowEntrypoint\n\nEvery Workflow must extend `WorkflowEntrypoint` and implement a `run()` method:\n\n```typescript\nexport class MyWorkflow extends WorkflowEntrypoint\u003CEnv, Params> {\n  async run(event: WorkflowEvent\u003CParams>, step: WorkflowStep) {\n    \u002F\u002F Workflow steps here\n  }\n}\n```\n\n**Type Parameters:**\n- `Env` - Environment bindings (KV, D1, R2, etc.)\n- `Params` - Type of workflow parameters passed via `event.payload`\n\n### run() Method\n\n```typescript\nasync run(\n  event: WorkflowEvent\u003CParams>,\n  step: WorkflowStep\n): Promise\u003CT | void>\n```\n\n**Parameters:**\n- `event` - Contains workflow metadata and payload\n- `step` - Provides step methods (do, sleep, sleepUntil, waitForEvent)\n\n**Returns:**\n- Optional return value (must be serializable)\n- Return value available via instance.status()\n\n**Example:**\n\n```typescript\nexport class OrderWorkflow extends WorkflowEntrypoint\u003CEnv, OrderParams> {\n  async run(event: WorkflowEvent\u003COrderParams>, step: WorkflowStep) {\n    const { orderId, customerId } = event.payload;\n\n    \u002F\u002F Access bindings via this.env\n    const order = await this.env.DB.prepare(\n      'SELECT * FROM orders WHERE id = ?'\n    ).bind(orderId).first();\n\n    const result = await step.do('process payment', async () => {\n      \u002F\u002F Payment processing\n      return { paid: true, amount: order.total };\n    });\n\n    \u002F\u002F Return final state\n    return {\n      orderId,\n      status: 'completed',\n      paidAmount: result.amount\n    };\n  }\n}\n```\n\n---\n\n## Step Methods\n\n### step.do() - Execute Work\n\n```typescript\nstep.do\u003CT>(\n  name: string,\n  config?: WorkflowStepConfig,\n  callback: () => Promise\u003CT>\n): Promise\u003CT>\n```\n\n**OR** (config is optional):\n\n```typescript\nstep.do\u003CT>(\n  name: string,\n  callback: () => Promise\u003CT>\n): Promise\u003CT>\n```\n\n**Parameters:**\n- `name` - Step name (for observability)\n- `config` (optional) - Retry configuration\n- `callback` - Async function that does the work\n\n**Returns:**\n- The value returned from callback (must be serializable)\n\n**Example:**\n\n```typescript\n\u002F\u002F Simple step\nconst files = await step.do('fetch files', async () => {\n  const response = await fetch('https:\u002F\u002Fapi.example.com\u002Ffiles');\n  return await response.json();\n});\n\n\u002F\u002F Step with retry config\nconst result = await step.do(\n  'call payment API',\n  {\n    retries: {\n      limit: 10,\n      delay: '10 seconds',\n      backoff: 'exponential'\n    },\n    timeout: '5 minutes'\n  },\n  async () => {\n    const response = await fetch('https:\u002F\u002Fpayment-api.example.com\u002Fcharge', {\n      method: 'POST',\n      body: JSON.stringify({ amount: 100 })\n    });\n    return await response.json();\n  }\n);\n```\n\n**CRITICAL - Serialization:**\n- Return value must be JSON serializable\n- ✅ Allowed: string, number, boolean, Array, Object, null\n- ❌ Forbidden: Function, Symbol, circular references, undefined\n- Step will throw error if return value isn't serializable\n\n---\n\n### step.sleep() - Relative Sleep\n\n```typescript\nstep.sleep(name: string, duration: WorkflowDuration): Promise\u003Cvoid>\n```\n\n**Parameters:**\n- `name` - Step name\n- `duration` - Number (milliseconds) or human-readable string\n\n**Accepted units:**\n- `\"second\"` \u002F `\"seconds\"`\n- `\"minute\"` \u002F `\"minutes\"`\n- `\"hour\"` \u002F `\"hours\"`\n- `\"day\"` \u002F `\"days\"`\n- `\"week\"` \u002F `\"weeks\"`\n- `\"month\"` \u002F `\"months\"`\n- `\"year\"` \u002F `\"years\"`\n\n**Examples:**\n\n```typescript\n\u002F\u002F Sleep for 5 minutes\nawait step.sleep('wait 5 minutes', '5 minutes');\n\n\u002F\u002F Sleep for 1 hour\nawait step.sleep('hourly delay', '1 hour');\n\n\u002F\u002F Sleep for 2 days\nawait step.sleep('wait 2 days', '2 days');\n\n\u002F\u002F Sleep using milliseconds\nawait step.sleep('wait 30 seconds', 30000);\n\n\u002F\u002F Common pattern: schedule daily task\nawait step.do('send daily report', async () => {\n  \u002F\u002F Send report\n});\nawait step.sleep('wait until tomorrow', '1 day');\n\u002F\u002F Workflow continues next day\n```\n\n**Priority:**\n- Workflows resuming from sleep take priority over new instances\n- Ensures older workflows complete before new ones start\n\n---\n\n### step.sleepUntil() - Sleep to Specific Date\n\n```typescript\nstep.sleepUntil(\n  name: string,\n  timestamp: Date | number\n): Promise\u003Cvoid>\n```\n\n**Parameters:**\n- `name` - Step name\n- `timestamp` - Date object or UNIX timestamp (milliseconds)\n\n**Examples:**\n\n```typescript\n\u002F\u002F Sleep until specific date\nconst launchDate = new Date('2025-12-25T00:00:00Z');\nawait step.sleepUntil('wait for launch', launchDate);\n\n\u002F\u002F Sleep until UNIX timestamp\nconst timestamp = Date.parse('24 Oct 2024 13:00:00 UTC');\nawait step.sleepUntil('wait until time', timestamp);\n\n\u002F\u002F Sleep until next Monday 9am UTC\nconst nextMonday = new Date();\nnextMonday.setDate(nextMonday.getDate() + ((1 + 7 - nextMonday.getDay()) % 7 || 7));\nnextMonday.setUTCHours(9, 0, 0, 0);\nawait step.sleepUntil('wait until Monday 9am', nextMonday);\n\n\u002F\u002F Schedule work at specific time\nawait step.do('prepare campaign', async () => {\n  \u002F\u002F Prepare marketing campaign\n});\n\nconst campaignLaunch = new Date('2025-11-01T12:00:00Z');\nawait step.sleepUntil('wait for campaign launch', campaignLaunch);\n\nawait step.do('launch campaign', async () => {\n  \u002F\u002F Launch campaign\n});\n```\n\n---\n\n### step.waitForEvent() - Wait for External Event\n\n```typescript\nstep.waitForEvent\u003CT>(\n  name: string,\n  options: { type: string; timeout?: string | number }\n): Promise\u003CT>\n```\n\n**Parameters:**\n- `name` - Step name\n- `options.type` - Event type to match\n- `options.timeout` (optional) - Max wait time (default: 24 hours)\n\n**Returns:**\n- The event payload sent via `instance.sendEvent()`\n\n**Example:**\n\n```typescript\nexport class PaymentWorkflow extends WorkflowEntrypoint\u003CEnv, Params> {\n  async run(event: WorkflowEvent\u003CParams>, step: WorkflowStep) {\n    \u002F\u002F Create payment intent\n    await step.do('create payment intent', async () => {\n      \u002F\u002F Call Stripe API\n    });\n\n    \u002F\u002F Wait for webhook from Stripe (max 1 hour)\n    const webhookData = await step.waitForEvent\u003CStripeWebhook>(\n      'wait for payment confirmation',\n      { type: 'stripe-webhook', timeout: '1 hour' }\n    );\n\n    \u002F\u002F Continue based on webhook\n    if (webhookData.status === 'succeeded') {\n      await step.do('fulfill order', async () => {\n        \u002F\u002F Fulfill order\n      });\n    } else {\n      await step.do('handle failed payment', async () => {\n        \u002F\u002F Handle failure\n      });\n    }\n  }\n}\n\n\u002F\u002F Worker receives webhook and sends event to workflow\nexport default {\n  async fetch(req: Request, env: Env): Promise\u003CResponse> {\n    if (req.url.includes('\u002Fwebhook\u002Fstripe')) {\n      const webhookData = await req.json();\n\n      \u002F\u002F Get workflow instance by ID (stored when created)\n      const instance = await env.PAYMENT_WORKFLOW.get(instanceId);\n\n      \u002F\u002F Send event to waiting workflow\n      await instance.sendEvent({\n        type: 'stripe-webhook',\n        payload: webhookData\n      });\n\n      return new Response('OK');\n    }\n  }\n};\n```\n\n**Timeout behavior:**\n- If timeout expires, throws error and workflow can retry or fail\n- Wrap in try-catch if timeout should not fail workflow\n\n```typescript\ntry {\n  const event = await step.waitForEvent('wait for user input', {\n    type: 'user-submitted',\n    timeout: '10 minutes'\n  });\n} catch (error) {\n  \u002F\u002F Timeout occurred - handle gracefully\n  await step.do('send reminder', async () => {\n    \u002F\u002F Send reminder to user\n  });\n}\n```\n\n---\n\n## WorkflowStepConfig\n\nConfigure retry behavior for individual steps:\n\n```typescript\ninterface WorkflowStepConfig {\n  retries?: {\n    limit: number;          \u002F\u002F Max retry attempts (Infinity allowed)\n    delay: string | number; \u002F\u002F Delay between retries\n    backoff?: 'constant' | 'linear' | 'exponential';\n  };\n  timeout?: string | number; \u002F\u002F Max time per attempt\n}\n```\n\n### Default Configuration\n\nIf no config provided, Workflows uses:\n\n```typescript\n{\n  retries: {\n    limit: 5,\n    delay: 10000,      \u002F\u002F 10 seconds\n    backoff: 'exponential'\n  },\n  timeout: '10 minutes'\n}\n```\n\n### Retry Examples\n\n**Constant Backoff (same delay each time):**\n\n```typescript\nawait step.do(\n  'send email',\n  {\n    retries: {\n      limit: 3,\n      delay: '30 seconds',\n      backoff: 'constant'  \u002F\u002F Always wait 30 seconds\n    }\n  },\n  async () => {\n    \u002F\u002F Send email\n  }\n);\n```\n\n**Linear Backoff (increasing delay):**\n\n```typescript\nawait step.do(\n  'poll API',\n  {\n    retries: {\n      limit: 5,\n      delay: '1 minute',\n      backoff: 'linear'  \u002F\u002F 1m, 2m, 3m, 4m, 5m\n    }\n  },\n  async () => {\n    \u002F\u002F Poll API\n  }\n);\n```\n\n**Exponential Backoff (recommended for most cases):**\n\n```typescript\nawait step.do(\n  'call rate-limited API',\n  {\n    retries: {\n      limit: 10,\n      delay: '10 seconds',\n      backoff: 'exponential'  \u002F\u002F 10s, 20s, 40s, 80s, 160s, ...\n    },\n    timeout: '5 minutes'\n  },\n  async () => {\n    \u002F\u002F API call\n  }\n);\n```\n\n**Unlimited Retries:**\n\n```typescript\nawait step.do(\n  'critical operation',\n  {\n    retries: {\n      limit: Infinity,  \u002F\u002F Retry forever\n      delay: '1 minute',\n      backoff: 'exponential'\n    }\n  },\n  async () => {\n    \u002F\u002F Operation that must succeed eventually\n  }\n);\n```\n\n**No Retries:**\n\n```typescript\nawait step.do(\n  'non-idempotent operation',\n  {\n    retries: {\n      limit: 0  \u002F\u002F Fail immediately on error\n    }\n  },\n  async () => {\n    \u002F\u002F One-time operation\n  }\n);\n```\n\n---\n\n## Error Handling\n\n### NonRetryableError\n\nForce workflow to fail immediately without retrying:\n\n```typescript\nimport { WorkflowEntrypoint, WorkflowStep, WorkflowEvent } from 'cloudflare:workers';\nimport { NonRetryableError } from 'cloudflare:workflows';\n\nexport class MyWorkflow extends WorkflowEntrypoint\u003CEnv, Params> {\n  async run(event: WorkflowEvent\u003CParams>, step: WorkflowStep) {\n    await step.do('validate input', async () => {\n      if (!event.payload.userId) {\n        throw new NonRetryableError('userId is required');\n      }\n\n      \u002F\u002F Validate user exists\n      const user = await this.env.DB.prepare(\n        'SELECT * FROM users WHERE id = ?'\n      ).bind(event.payload.userId).first();\n\n      if (!user) {\n        \u002F\u002F Terminal error - retrying won't help\n        throw new NonRetryableError('User not found');\n      }\n\n      return user;\n    });\n  }\n}\n```\n\n**When to use NonRetryableError:**\n- ✅ Authentication\u002Fauthorization failures\n- ✅ Invalid input that won't change\n- ✅ Resource doesn't exist (404)\n- ✅ Validation errors\n- ❌ Network failures (should retry)\n- ❌ Rate limits (should retry with backoff)\n- ❌ Temporary service outages (should retry)\n\n---\n\n### Catch Errors to Continue Workflow\n\nPrevent entire workflow from failing by catching step errors:\n\n```typescript\nexport class MyWorkflow extends WorkflowEntrypoint\u003CEnv, Params> {\n  async run(event: WorkflowEvent\u003CParams>, step: WorkflowStep) {\n    \u002F\u002F Critical step - workflow fails if this fails\n    await step.do('process payment', async () => {\n      \u002F\u002F Payment processing\n    });\n\n    \u002F\u002F Optional step - workflow continues even if it fails\n    try {\n      await step.do('send confirmation email', async () => {\n        \u002F\u002F Email sending\n      });\n    } catch (error) {\n      console.log(`Email failed: ${error.message}`);\n\n      \u002F\u002F Do cleanup or alternative action\n      await step.do('log email failure', async () => {\n        await this.env.DB.prepare(\n          'INSERT INTO failed_emails (user_id, error) VALUES (?, ?)'\n        ).bind(event.payload.userId, error.message).run();\n      });\n    }\n\n    \u002F\u002F Workflow continues\n    await step.do('update order status', async () => {\n      \u002F\u002F Update status\n    });\n  }\n}\n```\n\n**Pattern: Graceful degradation:**\n\n```typescript\n\u002F\u002F Try primary service, fall back to secondary\nlet result;\n\ntry {\n  result = await step.do('call primary API', async () => {\n    return await callPrimaryAPI();\n  });\n} catch (error) {\n  console.log('Primary API failed, trying backup');\n\n  result = await step.do('call backup API', async () => {\n    return await callBackupAPI();\n  });\n}\n```\n\n---\n\n## Triggering Workflows\n\n### From Workers\n\n**Configure binding in wrangler.jsonc:**\n\n```jsonc\n{\n  \"name\": \"trigger-worker\",\n  \"main\": \"src\u002Findex.ts\",\n  \"compatibility_date\": \"2025-10-22\",\n  \"workflows\": [\n    {\n      \"name\": \"my-workflow\",\n      \"binding\": \"MY_WORKFLOW\",\n      \"class_name\": \"MyWorkflow\",\n      \"script_name\": \"workflow-worker\"  \u002F\u002F If workflow is in different Worker\n    }\n  ]\n}\n```\n\n**Trigger from Worker:**\n\n```typescript\ntype Env = {\n  MY_WORKFLOW: Workflow;\n};\n\nexport default {\n  async fetch(req: Request, env: Env): Promise\u003CResponse> {\n    \u002F\u002F Create new workflow instance\n    const instance = await env.MY_WORKFLOW.create({\n      params: {\n        userId: '123',\n        email: 'user@example.com'\n      }\n    });\n\n    \u002F\u002F Return instance ID\n    return Response.json({\n      id: instance.id,\n      status: await instance.status()\n    });\n  }\n};\n```\n\n### Get Instance Status\n\n```typescript\n\u002F\u002F Get instance by ID\nconst instance = await env.MY_WORKFLOW.get(instanceId);\n\n\u002F\u002F Get status\nconst status = await instance.status();\n\nconsole.log(status);\n\u002F\u002F {\n\u002F\u002F   status: 'running' | 'complete' | 'errored' | 'queued' | 'unknown',\n\u002F\u002F   error: string | null,\n\u002F\u002F   output: any  \u002F\u002F Return value from run() if complete\n\u002F\u002F }\n```\n\n### Send Events to Running Instance\n\n```typescript\n\u002F\u002F Get instance\nconst instance = await env.MY_WORKFLOW.get(instanceId);\n\n\u002F\u002F Send event (will be received by step.waitForEvent)\nawait instance.sendEvent({\n  type: 'user-action',\n  payload: { action: 'approved' }\n});\n```\n\n### Pause and Resume\n\n```typescript\n\u002F\u002F Pause instance\nawait instance.pause();\n\n\u002F\u002F Resume instance\nawait instance.resume();\n\n\u002F\u002F Terminate instance\nawait instance.terminate();\n```\n\n---\n\n## Workflow Patterns\n\n### Pattern 1: Long-Running Process\n\n```typescript\nexport class VideoProcessingWorkflow extends WorkflowEntrypoint\u003CEnv, VideoParams> {\n  async run(event: WorkflowEvent\u003CVideoParams>, step: WorkflowStep) {\n    const { videoId } = event.payload;\n\n    \u002F\u002F Step 1: Upload to processing service\n    const uploadResult = await step.do('upload video', async () => {\n      const video = await this.env.MY_BUCKET.get(`videos\u002F${videoId}`);\n      const response = await fetch('https:\u002F\u002Fprocessor.example.com\u002Fupload', {\n        method: 'POST',\n        body: video?.body\n      });\n      return await response.json();\n    });\n\n    \u002F\u002F Step 2: Wait for processing (could take hours)\n    await step.sleep('wait for initial processing', '10 minutes');\n\n    \u002F\u002F Step 3: Poll for completion\n    let processed = false;\n    let attempts = 0;\n\n    while (!processed && attempts \u003C 20) {\n      const status = await step.do(`check status attempt ${attempts}`, async () => {\n        const response = await fetch(\n          `https:\u002F\u002Fprocessor.example.com\u002Fstatus\u002F${uploadResult.jobId}`\n        );\n        return await response.json();\n      });\n\n      if (status.complete) {\n        processed = true;\n      } else {\n        attempts++;\n        await step.sleep(`wait before retry ${attempts}`, '5 minutes');\n      }\n    }\n\n    \u002F\u002F Step 4: Download processed video\n    await step.do('download processed video', async () => {\n      const response = await fetch(uploadResult.downloadUrl);\n      const processed = await response.blob();\n      await this.env.MY_BUCKET.put(`processed\u002F${videoId}`, processed);\n    });\n\n    return { videoId, status: 'complete' };\n  }\n}\n```\n\n---\n\n### Pattern 2: Event-Driven Approval Flow\n\n```typescript\nexport class ApprovalWorkflow extends WorkflowEntrypoint\u003CEnv, ApprovalParams> {\n  async run(event: WorkflowEvent\u003CApprovalParams>, step: WorkflowStep) {\n    const { requestId, requesterId } = event.payload;\n\n    \u002F\u002F Step 1: Create approval request\n    await step.do('create approval request', async () => {\n      await this.env.DB.prepare(\n        'INSERT INTO approvals (id, requester_id, status) VALUES (?, ?, ?)'\n      ).bind(requestId, requesterId, 'pending').run();\n    });\n\n    \u002F\u002F Step 2: Send notification to approvers\n    await step.do('notify approvers', async () => {\n      await sendNotification(requestId);\n    });\n\n    \u002F\u002F Step 3: Wait for approval (max 7 days)\n    let approvalEvent;\n\n    try {\n      approvalEvent = await step.waitForEvent\u003CApprovalEvent>(\n        'wait for approval decision',\n        { type: 'approval-decision', timeout: '7 days' }\n      );\n    } catch (error) {\n      \u002F\u002F Timeout - auto-reject\n      await step.do('auto-reject due to timeout', async () => {\n        await this.env.DB.prepare(\n          'UPDATE approvals SET status = ? WHERE id = ?'\n        ).bind('rejected', requestId).run();\n      });\n\n      return { requestId, status: 'rejected', reason: 'timeout' };\n    }\n\n    \u002F\u002F Step 4: Process decision\n    await step.do('process approval decision', async () => {\n      await this.env.DB.prepare(\n        'UPDATE approvals SET status = ?, approver_id = ? WHERE id = ?'\n      ).bind(approvalEvent.approved ? 'approved' : 'rejected', approvalEvent.approverId, requestId).run();\n    });\n\n    \u002F\u002F Step 5: Execute approved action (if approved)\n    if (approvalEvent.approved) {\n      await step.do('execute approved action', async () => {\n        \u002F\u002F Execute the action\n      });\n    }\n\n    return { requestId, status: approvalEvent.approved ? 'approved' : 'rejected' };\n  }\n}\n```\n\n---\n\n### Pattern 3: Scheduled Workflow\n\n```typescript\nexport class DailyReportWorkflow extends WorkflowEntrypoint\u003CEnv, ReportParams> {\n  async run(event: WorkflowEvent\u003CReportParams>, step: WorkflowStep) {\n    \u002F\u002F Calculate next 9am UTC\n    const now = new Date();\n    const tomorrow9am = new Date();\n    tomorrow9am.setUTCDate(tomorrow9am.getUTCDate() + 1);\n    tomorrow9am.setUTCHours(9, 0, 0, 0);\n\n    \u002F\u002F Sleep until tomorrow 9am\n    await step.sleepUntil('wait until 9am tomorrow', tomorrow9am);\n\n    \u002F\u002F Generate report\n    const report = await step.do('generate daily report', async () => {\n      const results = await this.env.DB.prepare(\n        'SELECT * FROM metrics WHERE date = ?'\n      ).bind(now.toISOString().split('T')[0]).all();\n\n      return {\n        date: now.toISOString().split('T')[0],\n        metrics: results.results\n      };\n    });\n\n    \u002F\u002F Send report\n    await step.do('send report', async () => {\n      await sendEmail({\n        to: event.payload.recipients,\n        subject: `Daily Report - ${report.date}`,\n        body: formatReport(report.metrics)\n      });\n    });\n\n    return { sent: true, date: report.date };\n  }\n}\n```\n\n---\n\n### Pattern 4: Workflow Chaining\n\n```typescript\nexport class OrderWorkflow extends WorkflowEntrypoint\u003CEnv, OrderParams> {\n  async run(event: WorkflowEvent\u003COrderParams>, step: WorkflowStep) {\n    const { orderId } = event.payload;\n\n    \u002F\u002F Step 1: Process payment\n    const paymentResult = await step.do('process payment', async () => {\n      return await processPayment(orderId);\n    });\n\n    \u002F\u002F Step 2: Trigger fulfillment workflow\n    const fulfillmentInstance = await step.do('start fulfillment', async () => {\n      return await this.env.FULFILLMENT_WORKFLOW.create({\n        params: {\n          orderId,\n          paymentId: paymentResult.id\n        }\n      });\n    });\n\n    \u002F\u002F Step 3: Wait for fulfillment to complete\n    await step.sleep('wait for fulfillment', '5 minutes');\n\n    \u002F\u002F Step 4: Check fulfillment status\n    const fulfillmentStatus = await step.do('check fulfillment', async () => {\n      const instance = await this.env.FULFILLMENT_WORKFLOW.get(fulfillmentInstance.id);\n      return await instance.status();\n    });\n\n    if (fulfillmentStatus.status === 'complete') {\n      \u002F\u002F Step 5: Send confirmation\n      await step.do('send order confirmation', async () => {\n        await sendConfirmation(orderId);\n      });\n    }\n\n    return { orderId, status: 'complete' };\n  }\n}\n```\n\n---\n\n## Wrangler Commands\n\n### List Workflow Instances\n\n```bash\n# List all instances of a workflow\nnpx wrangler workflows instances list my-workflow\n\n# Filter by status\nnpx wrangler workflows instances list my-workflow --status running\nnpx wrangler workflows instances list my-workflow --status complete\nnpx wrangler workflows instances list my-workflow --status errored\n```\n\n### Describe Instance\n\n```bash\n# Get detailed info about specific instance\nnpx wrangler workflows instances describe my-workflow \u003Cinstance-id>\n\n# Output shows:\n# - Current status (running\u002Fcomplete\u002Ferrored)\n# - Each step with start\u002Fend times\n# - Step outputs\n# - Retry history\n# - Any errors\n# - Sleep state (if sleeping)\n```\n\n### Trigger Workflow (Development)\n\n```bash\n# Deploy workflow\nnpx wrangler deploy\n\n# Trigger via HTTP (if Worker is set up to trigger)\ncurl https:\u002F\u002Fmy-workflow.\u003Csubdomain>.workers.dev\u002F\n```\n\n---\n\n## State Persistence\n\n### What Can Be Persisted\n\nWorkflows automatically persist state returned from `step.do()`:\n\n**✅ Serializable Types:**\n- Primitives: `string`, `number`, `boolean`, `null`\n- Arrays: `[1, 2, 3]`, `['a', 'b', 'c']`\n- Objects: `{ key: 'value' }`, `{ nested: { data: true } }`\n- Nested structures: `{ users: [{ id: 1, name: 'Alice' }] }`\n\n**❌ Non-Serializable Types:**\n- Functions: `() => {}`\n- Symbols: `Symbol('key')`\n- Circular references: `const obj = {}; obj.self = obj;`\n- undefined (use null instead)\n- Class instances (serialize to plain objects)\n\n**Example - Correct Serialization:**\n\n```typescript\n\u002F\u002F ✅ Good - all values serializable\nconst result = await step.do('fetch data', async () => {\n  return {\n    users: [\n      { id: 1, name: 'Alice', active: true },\n      { id: 2, name: 'Bob', active: false }\n    ],\n    timestamp: Date.now(),\n    metadata: null\n  };\n});\n\n\u002F\u002F ❌ Bad - contains function\nconst bad = await step.do('bad example', async () => {\n  return {\n    data: [1, 2, 3],\n    transform: (x) => x * 2  \u002F\u002F ❌ Function not serializable\n  };\n});\n\u002F\u002F This will throw an error!\n```\n\n### Access State Across Steps\n\n```typescript\nexport class MyWorkflow extends WorkflowEntrypoint\u003CEnv, Params> {\n  async run(event: WorkflowEvent\u003CParams>, step: WorkflowStep) {\n    \u002F\u002F Step 1: Get data\n    const userData = await step.do('fetch user', async () => {\n      return { id: 123, email: 'user@example.com' };\n    });\n\n    \u002F\u002F Step 2: Use data from step 1\n    const orderData = await step.do('create order', async () => {\n      return {\n        userId: userData.id,      \u002F\u002F ✅ Access previous step's data\n        userEmail: userData.email,\n        orderId: 'ORD-456'\n      };\n    });\n\n    \u002F\u002F Step 3: Use data from step 1 and 2\n    await step.do('send confirmation', async () => {\n      await sendEmail({\n        to: userData.email,       \u002F\u002F ✅ Still accessible\n        subject: `Order ${orderData.orderId} confirmed`\n      });\n    });\n  }\n}\n```\n\n---\n\n## Observability\n\n### Built-in Metrics\n\nWorkflows automatically track:\n- **Instance status**: queued, running, complete, errored, paused\n- **Step execution**: start\u002Fend times, duration, success\u002Ffailure\n- **Retry history**: attempts, errors, delays\n- **Sleep state**: when workflow will wake up\n- **Output**: return values from steps and run()\n\n### View Metrics in Dashboard\n\nAccess via Cloudflare dashboard:\n1. Workers & Pages\n2. Select your workflow\n3. View instances and metrics\n\n**Metrics include:**\n- Total instances created\n- Success\u002Ferror rates\n- Average execution time\n- Step-level performance\n\n### Programmatic Access\n\n```typescript\n\u002F\u002F Get instance status\nconst instance = await env.MY_WORKFLOW.get(instanceId);\nconst status = await instance.status();\n\nconsole.log(status);\n\u002F\u002F {\n\u002F\u002F   status: 'complete',\n\u002F\u002F   error: null,\n\u002F\u002F   output: { userId: '123', status: 'processed' }\n\u002F\u002F }\n```\n\n---\n\n## Limits\n\n| Feature | Limit |\n|---------|-------|\n| **Max workflow duration** | 30 days |\n| **Max steps per workflow** | 10,000 |\n| **Max sleep\u002FsleepUntil duration** | 30 days |\n| **Max step timeout** | 15 minutes |\n| **Max concurrent instances** | Unlimited (autoscales) |\n| **Max payload size** | 128 KB |\n| **Max step output size** | 128 KB |\n| **Max waitForEvent timeout** | 30 days |\n| **Max retry limit** | Infinity (configurable) |\n\n**Notes:**\n- `step.sleep()` and `step.sleepUntil()` do NOT count toward 10,000 step limit\n- Workflows can run for up to 30 days total\n- Each step execution limited to 15 minutes max\n- Retries count as separate attempts, not separate steps\n\n---\n\n## Pricing\n\n**Requires Workers Paid plan** ($5\u002Fmonth)\n\n**Workflow Executions:**\n- First 10,000,000 step executions\u002Fmonth: **FREE**\n- After that: **$0.30 per million step executions**\n\n**What counts as a step execution:**\n- Each `step.do()` call\n- Each retry of a step\n- `step.sleep()`, `step.sleepUntil()`, `step.waitForEvent()` do NOT count\n\n**Cost examples:**\n- Workflow with 5 steps, no retries: **5 step executions**\n- Workflow with 3 steps, 1 step retries 2 times: **5 step executions** (3 + 2)\n- 10M simple workflows\u002Fmonth (5 steps each): ((50M - 10M) \u002F 1M) × $0.30 = **$12\u002Fmonth**\n\n---\n\n## Always Do ✅\n\n1. **Use descriptive step names** - \"fetch user data\", not \"step 1\"\n2. **Return serializable values only** - primitives, arrays, plain objects\n3. **Use NonRetryableError for terminal errors** - auth failures, invalid input\n4. **Configure retry limits** - avoid infinite retries unless necessary\n5. **Catch errors for optional steps** - use try-catch if step can fail gracefully\n6. **Use exponential backoff for retries** - default backoff for most cases\n7. **Validate inputs early** - fail fast with NonRetryableError if invalid\n8. **Store workflow instance IDs** - save to DB\u002FKV to query status later\n9. **Use waitForEvent for human-in-loop** - approvals, external confirmations\n10. **Monitor workflow metrics** - track success rates and errors\n\n---\n\n## Never Do ❌\n\n1. **Never return functions from steps** - will throw serialization error\n2. **Never create circular references** - will fail to serialize\n3. **Never assume steps execute immediately** - they may retry or sleep\n4. **Never use blocking operations** - use step.do() for async work\n5. **Never exceed 128 KB payload\u002Foutput** - will fail\n6. **Never retry non-idempotent operations infinitely** - use retry limits\n7. **Never ignore serialization errors** - fix the data structure\n8. **Never use workflows for real-time operations** - use Durable Objects instead\n9. **Never skip error handling for critical steps** - wrap in try-catch or use NonRetryableError\n10. **Never assume step order is guaranteed across retries** - each step is independent\n\n---\n\n## Troubleshooting\n\n### Issue: \"Cannot perform I\u002FO on behalf of a different request\"\n\n**Cause:** Trying to use I\u002FO objects created in one request context from another request handler\n\n**Solution:** Always perform I\u002FO within `step.do()` callbacks\n\n```typescript\n\u002F\u002F ❌ Bad - I\u002FO outside step\nconst response = await fetch('https:\u002F\u002Fapi.example.com\u002Fdata');\nconst data = await response.json();\n\nawait step.do('use data', async () => {\n  \u002F\u002F Using data from outside step's I\u002FO context\n  return data;  \u002F\u002F This will fail!\n});\n\n\u002F\u002F ✅ Good - I\u002FO inside step\nconst data = await step.do('fetch data', async () => {\n  const response = await fetch('https:\u002F\u002Fapi.example.com\u002Fdata');\n  return await response.json();  \u002F\u002F ✅ Correct\n});\n```\n\n---\n\n### Issue: NonRetryableError behaves differently in dev vs production\n\n**Known Issue:** Throwing NonRetryableError with empty message in dev mode causes retries, but works correctly in production\n\n**Workaround:** Always provide a message to NonRetryableError\n\n```typescript\n\u002F\u002F ❌ May retry in dev\nthrow new NonRetryableError();\n\n\u002F\u002F ✅ Works consistently\nthrow new NonRetryableError('User not found');\n```\n\n**Source:** [workers-sdk#10113](https:\u002F\u002Fgithub.com\u002Fcloudflare\u002Fworkers-sdk\u002Fissues\u002F10113)\n\n---\n\n### Issue: \"The requested module 'cloudflare:workers' does not provide an export named 'WorkflowEvent'\"\n\n**Cause:** Incorrect import or outdated @cloudflare\u002Fworkers-types\n\n**Solution:**\n\n```bash\n# Update types\nnpm install -D @cloudflare\u002Fworkers-types@latest\n\n# Ensure correct import\nimport { WorkflowEntrypoint, WorkflowStep, WorkflowEvent } from 'cloudflare:workers';\nimport { NonRetryableError } from 'cloudflare:workflows';\n```\n\n---\n\n### Issue: Step returns undefined instead of expected value\n\n**Cause:** Step callback doesn't return a value\n\n**Solution:** Always return from step callbacks\n\n```typescript\n\u002F\u002F ❌ Bad - no return\nconst result = await step.do('get data', async () => {\n  const data = await fetchData();\n  \u002F\u002F Missing return!\n});\nconsole.log(result);  \u002F\u002F undefined\n\n\u002F\u002F ✅ Good - explicit return\nconst result = await step.do('get data', async () => {\n  const data = await fetchData();\n  return data;  \u002F\u002F ✅\n});\n```\n\n---\n\n### Issue: Workflow instance stuck in \"running\" state\n\n**Possible causes:**\n1. Step is sleeping for long duration\n2. Step is waiting for event that never arrives\n3. Step is retrying with long backoff\n\n**Solution:**\n\n```bash\n# Check instance details\nnpx wrangler workflows instances describe my-workflow \u003Cinstance-id>\n\n# Look for:\n# - Sleep state (will show wake time)\n# - Waiting for event (will show event type and timeout)\n# - Retry history (will show attempts and delays)\n```\n\n---\n\n## Production Checklist\n\nBefore deploying workflows to production:\n\n- [ ] All steps have descriptive names\n- [ ] Retry limits configured for all steps\n- [ ] NonRetryableError used for terminal errors\n- [ ] Critical steps have error handling\n- [ ] Optional steps wrapped in try-catch\n- [ ] No non-serializable values returned\n- [ ] Payload sizes under 128 KB\n- [ ] Workflow duration under 30 days\n- [ ] Instance IDs stored for status queries\n- [ ] Monitoring and alerting configured\n- [ ] waitForEvent timeouts configured\n- [ ] Tested in development environment\n- [ ] Tested retry behavior\n- [ ] Tested error scenarios\n\n---\n\n## Related Documentation\n\n- [Cloudflare Workflows Docs](https:\u002F\u002Fdevelopers.cloudflare.com\u002Fworkflows\u002F)\n- [Get Started Guide](https:\u002F\u002Fdevelopers.cloudflare.com\u002Fworkflows\u002Fget-started\u002Fguide\u002F)\n- [Workers API](https:\u002F\u002Fdevelopers.cloudflare.com\u002Fworkflows\u002Fbuild\u002Fworkers-api\u002F)\n- [Sleeping and Retrying](https:\u002F\u002Fdevelopers.cloudflare.com\u002Fworkflows\u002Fbuild\u002Fsleeping-and-retrying\u002F)\n- [Events and Parameters](https:\u002F\u002Fdevelopers.cloudflare.com\u002Fworkflows\u002Fbuild\u002Fevents-and-parameters\u002F)\n- [Limits](https:\u002F\u002Fdevelopers.cloudflare.com\u002Fworkflows\u002Freference\u002Flimits\u002F)\n- [Pricing](https:\u002F\u002Fdevelopers.cloudflare.com\u002Fworkflows\u002Fplatform\u002Fpricing\u002F)\n- [Changelog](https:\u002F\u002Fdevelopers.cloudflare.com\u002Fworkflows\u002Freference\u002Fchangelog\u002F)\n\n---\n\n**Last Updated**: 2025-10-22\n**Version**: 1.0.0\n**Maintainer**: Jeremy Dawes | jeremy@jezweb.net\n","# Cloudflare Workflows\n\n**Status**: Production Ready ✅\n**Last Updated**: 2025-10-22\n**Dependencies**: cloudflare-worker-base (for Worker setup)\n**Latest Versions**: wrangler@4.44.0, @cloudflare\u002Fworkers-types@4.20251014.0\n\n---\n\n## Quick Start (10 Minutes)\n\n### 1. Create a Workflow\n\nUse the Cloudflare Workflows starter template:\n\n```bash\nnpm create cloudflare@latest my-workflow -- --template cloudflare\u002Fworkflows-starter --git --deploy false\ncd my-workflow\n```\n\n**What you get:**\n- WorkflowEntrypoint class template\n- Worker to trigger workflows\n- Complete wrangler.jsonc configuration\n\n### 2. Understand the Basic Structure\n\n**src\u002Findex.ts:**\n\n```typescript\nimport { WorkflowEntrypoint, WorkflowStep, WorkflowEvent } from 'cloudflare:workers';\n\ntype Env = {\n  MY_WORKFLOW: Workflow;\n};\n\ntype Params = {\n  userId: string;\n  email: string;\n};\n\nexport class MyWorkflow extends WorkflowEntrypoint\u003CEnv, Params> {\n  async run(event: WorkflowEvent\u003CParams>, step: WorkflowStep) {\n    \u002F\u002F Access params from event.payload\n    const { userId, email } = event.payload;\n\n    \u002F\u002F Step 1: Do some work\n    const result = await step.do('process user', async () => {\n      return { processed: true, userId };\n    });\n\n    \u002F\u002F Step 2: Wait before next action\n    await step.sleep('wait 1 hour', '1 hour');\n\n    \u002F\u002F Step 3: Continue workflow\n    await step.do('send email', async () => {\n      \u002F\u002F Send email logic\n      return { sent: true, email };\n    });\n\n    \u002F\u002F Optional: return final state\n    return { completed: true, userId };\n  }\n}\n\n\u002F\u002F Worker to trigger workflow\nexport default {\n  async fetch(req: Request, env: Env): Promise\u003CResponse> {\n    \u002F\u002F Create new workflow instance\n    const instance = await env.MY_WORKFLOW.create({\n      params: { userId: '123', email: 'user@example.com' }\n    });\n\n    return Response.json({\n      id: instance.id,\n      status: await instance.status()\n    });\n  }\n};\n```\n\n### 3. Configure Wrangler\n\n**wrangler.jsonc:**\n\n```jsonc\n{\n  \"name\": \"my-workflow\",\n  \"main\": \"src\u002Findex.ts\",\n  \"compatibility_date\": \"2025-10-22\",\n  \"workflows\": [\n    {\n      \"name\": \"my-workflow\",\n      \"binding\": \"MY_WORKFLOW\",\n      \"class_name\": \"MyWorkflow\"\n    }\n  ]\n}\n```\n\n### 4. Deploy and Test\n\n```bash\n# Deploy workflow\nnpm run deploy\n\n# Trigger workflow (visit in browser or curl)\ncurl https:\u002F\u002Fmy-workflow.\u003Csubdomain>.workers.dev\u002F\n\n# View workflow instances\nnpx wrangler workflows instances list my-workflow\n\n# Check instance status\nnpx wrangler workflows instances describe my-workflow \u003Cinstance-id>\n```\n\n---\n\n## WorkflowEntrypoint Class\n\n### Extend WorkflowEntrypoint\n\nEvery Workflow must extend `WorkflowEntrypoint` and implement a `run()` method:\n\n```typescript\nexport class MyWorkflow extends WorkflowEntrypoint\u003CEnv, Params> {\n  async run(event: WorkflowEvent\u003CParams>, step: WorkflowStep) {\n    \u002F\u002F Workflow steps here\n  }\n}\n```\n\n**Type Parameters:**\n- `Env` - Environment bindings (KV, D1, R2, etc.)\n- `Params` - Type of workflow parameters passed via `event.payload`\n\n### run() Method\n\n```typescript\nasync run(\n  event: WorkflowEvent\u003CParams>,\n  step: WorkflowStep\n): Promise\u003CT | void>\n```\n\n**Parameters:**\n- `event` - Contains workflow metadata and payload\n- `step` - Provides step methods (do, sleep, sleepUntil, waitForEvent)\n\n**Returns:**\n- Optional return value (must be serializable)\n- Return value available via instance.status()\n\n**Example:**\n\n```typescript\nexport class OrderWorkflow extends WorkflowEntrypoint\u003CEnv, OrderParams> {\n  async run(event: WorkflowEvent\u003COrderParams>, step: WorkflowStep) {\n    const { orderId, customerId } = event.payload;\n\n    \u002F\u002F Access bindings via this.env\n    const order = await this.env.DB.prepare(\n      'SELECT * FROM orders WHERE id = ?'\n    ).bind(orderId).first();\n\n    const result = await step.do('process payment', async () => {\n      \u002F\u002F Payment processing\n      return { paid: true, amount: order.total };\n    });\n\n    \u002F\u002F Return final state\n    return {\n      orderId,\n      status: 'completed',\n      paidAmount: result.amount\n    };\n  }\n}\n```\n\n---\n\n## Step Methods\n\n### step.do() - Execute Work\n\n```typescript\nstep.do\u003CT>(\n  name: string,\n  config?: WorkflowStepConfig,\n  callback: () => Promise\u003CT>\n): Promise\u003CT>\n```\n\n**OR** (config is optional):\n\n```typescript\nstep.do\u003CT>(\n  name: string,\n  callback: () => Promise\u003CT>\n): Promise\u003CT>\n```\n\n**Parameters:**\n- `name` - Step name (for observability)\n- `config` (optional) - Retry configuration\n- `callback` - Async function that does the work\n\n**Returns:**\n- The value returned from callback (must be serializable)\n\n**Example:**\n\n```typescript\n\u002F\u002F Simple step\nconst files = await step.do('fetch files', async () => {\n  const response = await fetch('https:\u002F\u002Fapi.example.com\u002Ffiles');\n  return await response.json();\n});\n\n\u002F\u002F Step with retry config\nconst result = await step.do(\n  'call payment API',\n  {\n    retries: {\n      limit: 10,\n      delay: '10 seconds',\n      backoff: 'exponential'\n    },\n    timeout: '5 minutes'\n  },\n  async () => {\n    const response = await fetch('https:\u002F\u002Fpayment-api.example.com\u002Fcharge', {\n      method: 'POST',\n      body: JSON.stringify({ amount: 100 })\n    });\n    return await response.json();\n  }\n);\n```\n\n**CRITICAL - Serialization:**\n- Return value must be JSON serializable\n- ✅ Allowed: string, number, boolean, Array, Object, null\n- ❌ Forbidden: Function, Symbol, circular references, undefined\n- Step will throw error if return value isn't serializable\n\n---\n\n### step.sleep() - Relative Sleep\n\n```typescript\nstep.sleep(name: string, duration: WorkflowDuration): Promise\u003Cvoid>\n```\n\n**Parameters:**\n- `name` - Step name\n- `duration` - Number (milliseconds) or human-readable string\n\n**Accepted units:**\n- `\"second\"` \u002F `\"seconds\"`\n- `\"minute\"` \u002F `\"minutes\"`\n- `\"hour\"` \u002F `\"hours\"`\n- `\"day\"` \u002F `\"days\"`\n- `\"week\"` \u002F `\"weeks\"`\n- `\"month\"` \u002F `\"months\"`\n- `\"year\"` \u002F `\"years\"`\n\n**Examples:**\n\n```typescript\n\u002F\u002F Sleep for 5 minutes\nawait step.sleep('wait 5 minutes', '5 minutes');\n\n\u002F\u002F Sleep for 1 hour\nawait step.sleep('hourly delay', '1 hour');\n\n\u002F\u002F Sleep for 2 days\nawait step.sleep('wait 2 days', '2 days');\n\n\u002F\u002F Sleep using milliseconds\nawait step.sleep('wait 30 seconds', 30000);\n\n\u002F\u002F Common pattern: schedule daily task\nawait step.do('send daily report', async () => {\n  \u002F\u002F Send report\n});\nawait step.sleep('wait until tomorrow', '1 day');\n\u002F\u002F Workflow continues next day\n```\n\n**Priority:**\n- Workflows resuming from sleep take priority over new instances\n- Ensures older workflows complete before new ones start\n\n---\n\n### step.sleepUntil() - Sleep to Specific Date\n\n```typescript\nstep.sleepUntil(\n  name: string,\n  timestamp: Date | number\n): Promise\u003Cvoid>\n```\n\n**Parameters:**\n- `name` - Step name\n- `timestamp` - Date object or UNIX timestamp (milliseconds)\n\n**Examples:**\n\n```typescript\n\u002F\u002F Sleep until specific date\nconst launchDate = new Date('2025-12-25T00:00:00Z');\nawait step.sleepUntil('wait for launch', launchDate);\n\n\u002F\u002F Sleep until UNIX timestamp\nconst timestamp = Date.parse('24 Oct 2024 13:00:00 UTC');\nawait step.sleepUntil('wait until time', timestamp);\n\n\u002F\u002F Sleep until next Monday 9am UTC\nconst nextMonday = new Date();\nnextMonday.setDate(nextMonday.getDate() + ((1 + 7 - nextMonday.getDay()) % 7 || 7));\nnextMonday.setUTCHours(9, 0, 0, 0);\nawait step.sleepUntil('wait until Monday 9am', nextMonday);\n\n\u002F\u002F Schedule work at specific time\nawait step.do('prepare campaign', async () => {\n  \u002F\u002F Prepare marketing campaign\n});\n\nconst campaignLaunch = new Date('2025-11-01T12:00:00Z');\nawait step.sleepUntil('wait for campaign launch', campaignLaunch);\n\nawait step.do('launch campaign', async () => {\n  \u002F\u002F Launch campaign\n});\n```\n\n---\n\n### step.waitForEvent() - Wait for External Event\n\n```typescript\nstep.waitForEvent\u003CT>(\n  name: string,\n  options: { type: string; timeout?: string | number }\n): Promise\u003CT>\n```\n\n**Parameters:**\n- `name` - Step name\n- `options.type` - Event type to match\n- `options.timeout` (optional) - Max wait time (default: 24 hours)\n\n**Returns:**\n- The event payload sent via `instance.sendEvent()`\n\n**Example:**\n\n```typescript\nexport class PaymentWorkflow extends WorkflowEntrypoint\u003CEnv, Params> {\n  async run(event: WorkflowEvent\u003CParams>, step: WorkflowStep) {\n    \u002F\u002F Create payment intent\n    await step.do('create payment intent', async () => {\n      \u002F\u002F Call Stripe API\n    });\n\n    \u002F\u002F Wait for webhook from Stripe (max 1 hour)\n    const webhookData = await step.waitForEvent\u003CStripeWebhook>(\n      'wait for payment confirmation',\n      { type: 'stripe-webhook', timeout: '1 hour' }\n    );\n\n    \u002F\u002F Continue based on webhook\n    if (webhookData.status === 'succeeded') {\n      await step.do('fulfill order', async () => {\n        \u002F\u002F Fulfill order\n      });\n    } else {\n      await step.do('handle failed payment', async () => {\n        \u002F\u002F Handle failure\n      });\n    }\n  }\n}\n\n\u002F\u002F Worker receives webhook and sends event to workflow\nexport default {\n  async fetch(req: Request, env: Env): Promise\u003CResponse> {\n    if (req.url.includes('\u002Fwebhook\u002Fstripe')) {\n      const webhookData = await req.json();\n\n      \u002F\u002F Get workflow instance by ID (stored when created)\n      const instance = await env.PAYMENT_WORKFLOW.get(instanceId);\n\n      \u002F\u002F Send event to waiting workflow\n      await instance.sendEvent({\n        type: 'stripe-webhook',\n        payload: webhookData\n      });\n\n      return new Response('OK');\n    }\n  }\n};\n```\n\n**Timeout behavior:**\n- If timeout expires, throws error and workflow can retry or fail\n- Wrap in try-catch if timeout should not fail workflow\n\n```typescript\ntry {\n  const event = await step.waitForEvent('wait for user input', {\n    type: 'user-submitted',\n    timeout: '10 minutes'\n  });\n} catch (error) {\n  \u002F\u002F Timeout occurred - handle gracefully\n  await step.do('send reminder', async () => {\n    \u002F\u002F Send reminder to user\n  });\n}\n```\n\n---\n\n## WorkflowStepConfig\n\nConfigure retry behavior for individual steps:\n\n```typescript\ninterface WorkflowStepConfig {\n  retries?: {\n    limit: number;          \u002F\u002F Max retry attempts (Infinity allowed)\n    delay: string | number; \u002F\u002F Delay between retries\n    backoff?: 'constant' | 'linear' | 'exponential';\n  };\n  timeout?: string | number; \u002F\u002F Max time per attempt\n}\n```\n\n### Default Configuration\n\nIf no config provided, Workflows uses:\n\n```typescript\n{\n  retries: {\n    limit: 5,\n    delay: 10000,      \u002F\u002F 10 seconds\n    backoff: 'exponential'\n  },\n  timeout: '10 minutes'\n}\n```\n\n### Retry Examples\n\n**Constant Backoff (same delay each time):**\n\n```typescript\nawait step.do(\n  'send email',\n  {\n    retries: {\n      limit: 3,\n      delay: '30 seconds',\n      backoff: 'constant'  \u002F\u002F Always wait 30 seconds\n    }\n  },\n  async () => {\n    \u002F\u002F Send email\n  }\n);\n```\n\n**Linear Backoff (increasing delay):**\n\n```typescript\nawait step.do(\n  'poll API',\n  {\n    retries: {\n      limit: 5,\n      delay: '1 minute',\n      backoff: 'linear'  \u002F\u002F 1m, 2m, 3m, 4m, 5m\n    }\n  },\n  async () => {\n    \u002F\u002F Poll API\n  }\n);\n```\n\n**Exponential Backoff (recommended for most cases):**\n\n```typescript\nawait step.do(\n  'call rate-limited API',\n  {\n    retries: {\n      limit: 10,\n      delay: '10 seconds',\n      backoff: 'exponential'  \u002F\u002F 10s, 20s, 40s, 80s, 160s, ...\n    },\n    timeout: '5 minutes'\n  },\n  async () => {\n    \u002F\u002F API call\n  }\n);\n```\n\n**Unlimited Retries:**\n\n```typescript\nawait step.do(\n  'critical operation',\n  {\n    retries: {\n      limit: Infinity,  \u002F\u002F Retry forever\n      delay: '1 minute',\n      backoff: 'exponential'\n    }\n  },\n  async () => {\n    \u002F\u002F Operation that must succeed eventually\n  }\n);\n```\n\n**No Retries:**\n\n```typescript\nawait step.do(\n  'non-idempotent operation',\n  {\n    retries: {\n      limit: 0  \u002F\u002F Fail immediately on error\n    }\n  },\n  async () => {\n    \u002F\u002F One-time operation\n  }\n);\n```\n\n---\n\n## Error Handling\n\n### NonRetryableError\n\nForce workflow to fail immediately without retrying:\n\n```typescript\nimport { WorkflowEntrypoint, WorkflowStep, WorkflowEvent } from 'cloudflare:workers';\nimport { NonRetryableError } from 'cloudflare:workflows';\n\nexport class MyWorkflow extends WorkflowEntrypoint\u003CEnv, Params> {\n  async run(event: WorkflowEvent\u003CParams>, step: WorkflowStep) {\n    await step.do('validate input', async () => {\n      if (!event.payload.userId) {\n        throw new NonRetryableError('userId is required');\n      }\n\n      \u002F\u002F Validate user exists\n      const user = await this.env.DB.prepare(\n        'SELECT * FROM users WHERE id = ?'\n      ).bind(event.payload.userId).first();\n\n      if (!user) {\n        \u002F\u002F Terminal error - retrying won't help\n        throw new NonRetryableError('User not found');\n      }\n\n      return user;\n    });\n  }\n}\n```\n\n**When to use NonRetryableError:**\n- ✅ Authentication\u002Fauthorization failures\n- ✅ Invalid input that won't change\n- ✅ Resource doesn't exist (404)\n- ✅ Validation errors\n- ❌ Network failures (should retry)\n- ❌ Rate limits (should retry with backoff)\n- ❌ Temporary service outages (should retry)\n\n---\n\n### Catch Errors to Continue Workflow\n\nPrevent entire workflow from failing by catching step errors:\n\n```typescript\nexport class MyWorkflow extends WorkflowEntrypoint\u003CEnv, Params> {\n  async run(event: WorkflowEvent\u003CParams>, step: WorkflowStep) {\n    \u002F\u002F Critical step - workflow fails if this fails\n    await step.do('process payment', async () => {\n      \u002F\u002F Payment processing\n    });\n\n    \u002F\u002F Optional step - workflow continues even if it fails\n    try {\n      await step.do('send confirmation email', async () => {\n        \u002F\u002F Email sending\n      });\n    } catch (error) {\n      console.log(`Email failed: ${error.message}`);\n\n      \u002F\u002F Do cleanup or alternative action\n      await step.do('log email failure', async () => {\n        await this.env.DB.prepare(\n          'INSERT INTO failed_emails (user_id, error) VALUES (?, ?)'\n        ).bind(event.payload.userId, error.message).run();\n      });\n    }\n\n    \u002F\u002F Workflow continues\n    await step.do('update order status', async () => {\n      \u002F\u002F Update status\n    });\n  }\n}\n```\n\n**Pattern: Graceful degradation:**\n\n```typescript\n\u002F\u002F Try primary service, fall back to secondary\nlet result;\n\ntry {\n  result = await step.do('call primary API', async () => {\n    return await callPrimaryAPI();\n  });\n} catch (error) {\n  console.log('Primary API failed, trying backup');\n\n  result = await step.do('call backup API', async () => {\n    return await callBackupAPI();\n  });\n}\n```\n\n---\n\n## Triggering Workflows\n\n### From Workers\n\n**Configure binding in wrangler.jsonc:**\n\n```jsonc\n{\n  \"name\": \"trigger-worker\",\n  \"main\": \"src\u002Findex.ts\",\n  \"compatibility_date\": \"2025-10-22\",\n  \"workflows\": [\n    {\n      \"name\": \"my-workflow\",\n      \"binding\": \"MY_WORKFLOW\",\n      \"class_name\": \"MyWorkflow\",\n      \"script_name\": \"workflow-worker\"  \u002F\u002F If workflow is in different Worker\n    }\n  ]\n}\n```\n\n**Trigger from Worker:**\n\n```typescript\ntype Env = {\n  MY_WORKFLOW: Workflow;\n};\n\nexport default {\n  async fetch(req: Request, env: Env): Promise\u003CResponse> {\n    \u002F\u002F Create new workflow instance\n    const instance = await env.MY_WORKFLOW.create({\n      params: {\n        userId: '123',\n        email: 'user@example.com'\n      }\n    });\n\n    \u002F\u002F Return instance ID\n    return Response.json({\n      id: instance.id,\n      status: await instance.status()\n    });\n  }\n};\n```\n\n### Get Instance Status\n\n```typescript\n\u002F\u002F Get instance by ID\nconst instance = await env.MY_WORKFLOW.get(instanceId);\n\n\u002F\u002F Get status\nconst status = await instance.status();\n\nconsole.log(status);\n\u002F\u002F {\n\u002F\u002F   status: 'running' | 'complete' | 'errored' | 'queued' | 'unknown',\n\u002F\u002F   error: string | null,\n\u002F\u002F   output: any  \u002F\u002F Return value from run() if complete\n\u002F\u002F }\n```\n\n### Send Events to Running Instance\n\n```typescript\n\u002F\u002F Get instance\nconst instance = await env.MY_WORKFLOW.get(instanceId);\n\n\u002F\u002F Send event (will be received by step.waitForEvent)\nawait instance.sendEvent({\n  type: 'user-action',\n  payload: { action: 'approved' }\n});\n```\n\n### Pause and Resume\n\n```typescript\n\u002F\u002F Pause instance\nawait instance.pause();\n\n\u002F\u002F Resume instance\nawait instance.resume();\n\n\u002F\u002F Terminate instance\nawait instance.terminate();\n```\n\n---\n\n## Workflow Patterns\n\n### Pattern 1: Long-Running Process\n\n```typescript\nexport class VideoProcessingWorkflow extends WorkflowEntrypoint\u003CEnv, VideoParams> {\n  async run(event: WorkflowEvent\u003CVideoParams>, step: WorkflowStep) {\n    const { videoId } = event.payload;\n\n    \u002F\u002F Step 1: Upload to processing service\n    const uploadResult = await step.do('upload video', async () => {\n      const video = await this.env.MY_BUCKET.get(`videos\u002F${videoId}`);\n      const response = await fetch('https:\u002F\u002Fprocessor.example.com\u002Fupload', {\n        method: 'POST',\n        body: video?.body\n      });\n      return await response.json();\n    });\n\n    \u002F\u002F Step 2: Wait for processing (could take hours)\n    await step.sleep('wait for initial processing', '10 minutes');\n\n    \u002F\u002F Step 3: Poll for completion\n    let processed = false;\n    let attempts = 0;\n\n    while (!processed && attempts \u003C 20) {\n      const status = await step.do(`check status attempt ${attempts}`, async () => {\n        const response = await fetch(\n          `https:\u002F\u002Fprocessor.example.com\u002Fstatus\u002F${uploadResult.jobId}`\n        );\n        return await response.json();\n      });\n\n      if (status.complete) {\n        processed = true;\n      } else {\n        attempts++;\n        await step.sleep(`wait before retry ${attempts}`, '5 minutes');\n      }\n    }\n\n    \u002F\u002F Step 4: Download processed video\n    await step.do('download processed video', async () => {\n      const response = await fetch(uploadResult.downloadUrl);\n      const processed = await response.blob();\n      await this.env.MY_BUCKET.put(`processed\u002F${videoId}`, processed);\n    });\n\n    return { videoId, status: 'complete' };\n  }\n}\n```\n\n---\n\n### Pattern 2: Event-Driven Approval Flow\n\n```typescript\nexport class ApprovalWorkflow extends WorkflowEntrypoint\u003CEnv, ApprovalParams> {\n  async run(event: WorkflowEvent\u003CApprovalParams>, step: WorkflowStep) {\n    const { requestId, requesterId } = event.payload;\n\n    \u002F\u002F Step 1: Create approval request\n    await step.do('create approval request', async () => {\n      await this.env.DB.prepare(\n        'INSERT INTO approvals (id, requester_id, status) VALUES (?, ?, ?)'\n      ).bind(requestId, requesterId, 'pending').run();\n    });\n\n    \u002F\u002F Step 2: Send notification to approvers\n    await step.do('notify approvers', async () => {\n      await sendNotification(requestId);\n    });\n\n    \u002F\u002F Step 3: Wait for approval (max 7 days)\n    let approvalEvent;\n\n    try {\n      approvalEvent = await step.waitForEvent\u003CApprovalEvent>(\n        'wait for approval decision',\n        { type: 'approval-decision', timeout: '7 days' }\n      );\n    } catch (error) {\n      \u002F\u002F Timeout - auto-reject\n      await step.do('auto-reject due to timeout', async () => {\n        await this.env.DB.prepare(\n          'UPDATE approvals SET status = ? WHERE id = ?'\n        ).bind('rejected', requestId).run();\n      });\n\n      return { requestId, status: 'rejected', reason: 'timeout' };\n    }\n\n    \u002F\u002F Step 4: Process decision\n    await step.do('process approval decision', async () => {\n      await this.env.DB.prepare(\n        'UPDATE approvals SET status = ?, approver_id = ? WHERE id = ?'\n      ).bind(approvalEvent.approved ? 'approved' : 'rejected', approvalEvent.approverId, requestId).run();\n    });\n\n    \u002F\u002F Step 5: Execute approved action (if approved)\n    if (approvalEvent.approved) {\n      await step.do('execute approved action', async () => {\n        \u002F\u002F Execute the action\n      });\n    }\n\n    return { requestId, status: approvalEvent.approved ? 'approved' : 'rejected' };\n  }\n}\n```\n\n---\n\n### Pattern 3: Scheduled Workflow\n\n```typescript\nexport class DailyReportWorkflow extends WorkflowEntrypoint\u003CEnv, ReportParams> {\n  async run(event: WorkflowEvent\u003CReportParams>, step: WorkflowStep) {\n    \u002F\u002F Calculate next 9am UTC\n    const now = new Date();\n    const tomorrow9am = new Date();\n    tomorrow9am.setUTCDate(tomorrow9am.getUTCDate() + 1);\n    tomorrow9am.setUTCHours(9, 0, 0, 0);\n\n    \u002F\u002F Sleep until tomorrow 9am\n    await step.sleepUntil('wait until 9am tomorrow', tomorrow9am);\n\n    \u002F\u002F Generate report\n    const report = await step.do('generate daily report', async () => {\n      const results = await this.env.DB.prepare(\n        'SELECT * FROM metrics WHERE date = ?'\n      ).bind(now.toISOString().split('T')[0]).all();\n\n      return {\n        date: now.toISOString().split('T')[0],\n        metrics: results.results\n      };\n    });\n\n    \u002F\u002F Send report\n    await step.do('send report', async () => {\n      await sendEmail({\n        to: event.payload.recipients,\n        subject: `Daily Report - ${report.date}`,\n        body: formatReport(report.metrics)\n      });\n    });\n\n    return { sent: true, date: report.date };\n  }\n}\n```\n\n---\n\n### Pattern 4: Workflow Chaining\n\n```typescript\nexport class OrderWorkflow extends WorkflowEntrypoint\u003CEnv, OrderParams> {\n  async run(event: WorkflowEvent\u003COrderParams>, step: WorkflowStep) {\n    const { orderId } = event.payload;\n\n    \u002F\u002F Step 1: Process payment\n    const paymentResult = await step.do('process payment', async () => {\n      return await processPayment(orderId);\n    });\n\n    \u002F\u002F Step 2: Trigger fulfillment workflow\n    const fulfillmentInstance = await step.do('start fulfillment', async () => {\n      return await this.env.FULFILLMENT_WORKFLOW.create({\n        params: {\n          orderId,\n          paymentId: paymentResult.id\n        }\n      });\n    });\n\n    \u002F\u002F Step 3: Wait for fulfillment to complete\n    await step.sleep('wait for fulfillment', '5 minutes');\n\n    \u002F\u002F Step 4: Check fulfillment status\n    const fulfillmentStatus = await step.do('check fulfillment', async () => {\n      const instance = await this.env.FULFILLMENT_WORKFLOW.get(fulfillmentInstance.id);\n      return await instance.status();\n    });\n\n    if (fulfillmentStatus.status === 'complete') {\n      \u002F\u002F Step 5: Send confirmation\n      await step.do('send order confirmation', async () => {\n        await sendConfirmation(orderId);\n      });\n    }\n\n    return { orderId, status: 'complete' };\n  }\n}\n```\n\n---\n\n## Wrangler Commands\n\n### List Workflow Instances\n\n```bash\n# List all instances of a workflow\nnpx wrangler workflows instances list my-workflow\n\n# Filter by status\nnpx wrangler workflows instances list my-workflow --status running\nnpx wrangler workflows instances list my-workflow --status complete\nnpx wrangler workflows instances list my-workflow --status errored\n```\n\n### Describe Instance\n\n```bash\n# Get detailed info about specific instance\nnpx wrangler workflows instances describe my-workflow \u003Cinstance-id>\n\n# Output shows:\n# - Current status (running\u002Fcomplete\u002Ferrored)\n# - Each step with start\u002Fend times\n# - Step outputs\n# - Retry history\n# - Any errors\n# - Sleep state (if sleeping)\n```\n\n### Trigger Workflow (Development)\n\n```bash\n# Deploy workflow\nnpx wrangler deploy\n\n# Trigger via HTTP (if Worker is set up to trigger)\ncurl https:\u002F\u002Fmy-workflow.\u003Csubdomain>.workers.dev\u002F\n```\n\n---\n\n## State Persistence\n\n### What Can Be Persisted\n\nWorkflows automatically persist state returned from `step.do()`:\n\n**✅ Serializable Types:**\n- Primitives: `string`, `number`, `boolean`, `null`\n- Arrays: `[1, 2, 3]`, `['a', 'b', 'c']`\n- Objects: `{ key: 'value' }`, `{ nested: { data: true } }`\n- Nested structures: `{ users: [{ id: 1, name: 'Alice' }] }`\n\n**❌ Non-Serializable Types:**\n- Functions: `() => {}`\n- Symbols: `Symbol('key')`\n- Circular references: `const obj = {}; obj.self = obj;`\n- undefined (use null instead)\n- Class instances (serialize to plain objects)\n\n**Example - Correct Serialization:**\n\n```typescript\n\u002F\u002F ✅ Good - all values serializable\nconst result = await step.do('fetch data', async () => {\n  return {\n    users: [\n      { id: 1, name: 'Alice', active: true },\n      { id: 2, name: 'Bob', active: false }\n    ],\n    timestamp: Date.now(),\n    metadata: null\n  };\n});\n\n\u002F\u002F ❌ Bad - contains function\nconst bad = await step.do('bad example', async () => {\n  return {\n    data: [1, 2, 3],\n    transform: (x) => x * 2  \u002F\u002F ❌ Function not serializable\n  };\n});\n\u002F\u002F This will throw an error!\n```\n\n### Access State Across Steps\n\n```typescript\nexport class MyWorkflow extends WorkflowEntrypoint\u003CEnv, Params> {\n  async run(event: WorkflowEvent\u003CParams>, step: WorkflowStep) {\n    \u002F\u002F Step 1: Get data\n    const userData = await step.do('fetch user', async () => {\n      return { id: 123, email: 'user@example.com' };\n    });\n\n    \u002F\u002F Step 2: Use data from step 1\n    const orderData = await step.do('create order', async () => {\n      return {\n        userId: userData.id,      \u002F\u002F ✅ Access previous step's data\n        userEmail: userData.email,\n        orderId: 'ORD-456'\n      };\n    });\n\n    \u002F\u002F Step 3: Use data from step 1 and 2\n    await step.do('send confirmation', async () => {\n      await sendEmail({\n        to: userData.email,       \u002F\u002F ✅ Still accessible\n        subject: `Order ${orderData.orderId} confirmed`\n      });\n    });\n  }\n}\n```\n\n---\n\n## Observability\n\n### Built-in Metrics\n\nWorkflows automatically track:\n- **Instance status**: queued, running, complete, errored, paused\n- **Step execution**: start\u002Fend times, duration, success\u002Ffailure\n- **Retry history**: attempts, errors, delays\n- **Sleep state**: when workflow will wake up\n- **Output**: return values from steps and run()\n\n### View Metrics in Dashboard\n\nAccess via Cloudflare dashboard:\n1. Workers & Pages\n2. Select your workflow\n3. View instances and metrics\n\n**Metrics include:**\n- Total instances created\n- Success\u002Ferror rates\n- Average execution time\n- Step-level performance\n\n### Programmatic Access\n\n```typescript\n\u002F\u002F Get instance status\nconst instance = await env.MY_WORKFLOW.get(instanceId);\nconst status = await instance.status();\n\nconsole.log(status);\n\u002F\u002F {\n\u002F\u002F   status: 'complete',\n\u002F\u002F   error: null,\n\u002F\u002F   output: { userId: '123', status: 'processed' }\n\u002F\u002F }\n```\n\n---\n\n## Limits\n\n| Feature | Limit |\n|---------|-------|\n| **Max workflow duration** | 30 days |\n| **Max steps per workflow** | 10,000 |\n| **Max sleep\u002FsleepUntil duration** | 30 days |\n| **Max step timeout** | 15 minutes |\n| **Max concurrent instances** | Unlimited (autoscales) |\n| **Max payload size** | 128 KB |\n| **Max step output size** | 128 KB |\n| **Max waitForEvent timeout** | 30 days |\n| **Max retry limit** | Infinity (configurable) |\n\n**Notes:**\n- `step.sleep()` and `step.sleepUntil()` do NOT count toward 10,000 step limit\n- Workflows can run for up to 30 days total\n- Each step execution limited to 15 minutes max\n- Retries count as separate attempts, not separate steps\n\n---\n\n## Pricing\n\n**Requires Workers Paid plan** ($5\u002Fmonth)\n\n**Workflow Executions:**\n- First 10,000,000 step executions\u002Fmonth: **FREE**\n- After that: **$0.30 per million step executions**\n\n**What counts as a step execution:**\n- Each `step.do()` call\n- Each retry of a step\n- `step.sleep()`, `step.sleepUntil()`, `step.waitForEvent()` do NOT count\n\n**Cost examples:**\n- Workflow with 5 steps, no retries: **5 step executions**\n- Workflow with 3 steps, 1 step retries 2 times: **5 step executions** (3 + 2)\n- 10M simple workflows\u002Fmonth (5 steps each): ((50M - 10M) \u002F 1M) × $0.30 = **$12\u002Fmonth**\n\n---\n\n## Always Do ✅\n\n1. **Use descriptive step names** - \"fetch user data\", not \"step 1\"\n2. **Return serializable values only** - primitives, arrays, plain objects\n3. **Use NonRetryableError for terminal errors** - auth failures, invalid input\n4. **Configure retry limits** - avoid infinite retries unless necessary\n5. **Catch errors for optional steps** - use try-catch if step can fail gracefully\n6. **Use exponential backoff for retries** - default backoff for most cases\n7. **Validate inputs early** - fail fast with NonRetryableError if invalid\n8. **Store workflow instance IDs** - save to DB\u002FKV to query status later\n9. **Use waitForEvent for human-in-loop** - approvals, external confirmations\n10. **Monitor workflow metrics** - track success rates and errors\n\n---\n\n## Never Do ❌\n\n1. **Never return functions from steps** - will throw serialization error\n2. **Never create circular references** - will fail to serialize\n3. **Never assume steps execute immediately** - they may retry or sleep\n4. **Never use blocking operations** - use step.do() for async work\n5. **Never exceed 128 KB payload\u002Foutput** - will fail\n6. **Never retry non-idempotent operations infinitely** - use retry limits\n7. **Never ignore serialization errors** - fix the data structure\n8. **Never use workflows for real-time operations** - use Durable Objects instead\n9. **Never skip error handling for critical steps** - wrap in try-catch or use NonRetryableError\n10. **Never assume step order is guaranteed across retries** - each step is independent\n\n---\n\n## Troubleshooting\n\n### Issue: \"Cannot perform I\u002FO on behalf of a different request\"\n\n**Cause:** Trying to use I\u002FO objects created in one request context from another request handler\n\n**Solution:** Always perform I\u002FO within `step.do()` callbacks\n\n```typescript\n\u002F\u002F ❌ Bad - I\u002FO outside step\nconst response = await fetch('https:\u002F\u002Fapi.example.com\u002Fdata');\nconst data = await response.json();\n\nawait step.do('use data', async () => {\n  \u002F\u002F Using data from outside step's I\u002FO context\n  return data;  \u002F\u002F This will fail!\n});\n\n\u002F\u002F ✅ Good - I\u002FO inside step\nconst data = await step.do('fetch data', async () => {\n  const response = await fetch('https:\u002F\u002Fapi.example.com\u002Fdata');\n  return await response.json();  \u002F\u002F ✅ Correct\n});\n```\n\n---\n\n### Issue: NonRetryableError behaves differently in dev vs production\n\n**Known Issue:** Throwing NonRetryableError with empty message in dev mode causes retries, but works correctly in production\n\n**Workaround:** Always provide a message to NonRetryableError\n\n```typescript\n\u002F\u002F ❌ May retry in dev\nthrow new NonRetryableError();\n\n\u002F\u002F ✅ Works consistently\nthrow new NonRetryableError('User not found');\n```\n\n**Source:** [workers-sdk#10113](https:\u002F\u002Fgithub.com\u002Fcloudflare\u002Fworkers-sdk\u002Fissues\u002F10113)\n\n---\n\n### Issue: \"The requested module 'cloudflare:workers' does not provide an export named 'WorkflowEvent'\"\n\n**Cause:** Incorrect import or outdated @cloudflare\u002Fworkers-types\n\n**Solution:**\n\n```bash\n# Update types\nnpm install -D @cloudflare\u002Fworkers-types@latest\n\n# Ensure correct import\nimport { WorkflowEntrypoint, WorkflowStep, WorkflowEvent } from 'cloudflare:workers';\nimport { NonRetryableError } from 'cloudflare:workflows';\n```\n\n---\n\n### Issue: Step returns undefined instead of expected value\n\n**Cause:** Step callback doesn't return a value\n\n**Solution:** Always return from step callbacks\n\n```typescript\n\u002F\u002F ❌ Bad - no return\nconst result = await step.do('get data', async () => {\n  const data = await fetchData();\n  \u002F\u002F Missing return!\n});\nconsole.log(result);  \u002F\u002F undefined\n\n\u002F\u002F ✅ Good - explicit return\nconst result = await step.do('get data', async () => {\n  const data = await fetchData();\n  return data;  \u002F\u002F ✅\n});\n```\n\n---\n\n### Issue: Workflow instance stuck in \"running\" state\n\n**Possible causes:**\n1. Step is sleeping for long duration\n2. Step is waiting for event that never arrives\n3. Step is retrying with long backoff\n\n**Solution:**\n\n```bash\n# Check instance details\nnpx wrangler workflows instances describe my-workflow \u003Cinstance-id>\n\n# Look for:\n# - Sleep state (will show wake time)\n# - Waiting for event (will show event type and timeout)\n# - Retry history (will show attempts and delays)\n```\n\n---\n\n## Production Checklist\n\nBefore deploying workflows to production:\n\n- [ ] All steps have descriptive names\n- [ ] Retry limits configured for all steps\n- [ ] NonRetryableError used for terminal errors\n- [ ] Critical steps have error handling\n- [ ] Optional steps wrapped in try-catch\n- [ ] No non-serializable values returned\n- [ ] Payload sizes under 128 KB\n- [ ] Workflow duration under 30 days\n- [ ] Instance IDs stored for status queries\n- [ ] Monitoring and alerting configured\n- [ ] waitForEvent timeouts configured\n- [ ] Tested in development environment\n- [ ] Tested retry behavior\n- [ ] Tested error scenarios\n\n---\n\n## Related Documentation\n\n- [Cloudflare Workflows Docs](https:\u002F\u002Fdevelopers.cloudflare.com\u002Fworkflows\u002F)\n- [Get Started Guide](https:\u002F\u002Fdevelopers.cloudflare.com\u002Fworkflows\u002Fget-started\u002Fguide\u002F)\n- [Workers API](https:\u002F\u002Fdevelopers.cloudflare.com\u002Fworkflows\u002Fbuild\u002Fworkers-api\u002F)\n- [Sleeping and Retrying](https:\u002F\u002Fdevelopers.cloudflare.com\u002Fworkflows\u002Fbuild\u002Fsleeping-and-retrying\u002F)\n- [Events and Parameters](https:\u002F\u002Fdevelopers.cloudflare.com\u002Fworkflows\u002Fbuild\u002Fevents-and-parameters\u002F)\n- [Limits](https:\u002F\u002Fdevelopers.cloudflare.com\u002Fworkflows\u002Freference\u002Flimits\u002F)\n- [Pricing](https:\u002F\u002Fdevelopers.cloudflare.com\u002Fworkflows\u002Fplatform\u002Fpricing\u002F)\n- [Changelog](https:\u002F\u002Fdevelopers.cloudflare.com\u002Fworkflows\u002Freference\u002Fchangelog\u002F)\n\n---\n\n**Last Updated**: 2025-10-22\n**Version**: 1.0.0\n**Maintainer**: Jeremy Dawes | jeremy@jezweb.net\n",{"name":5,"license":14,"description":23},"Complete knowledge domain for Cloudflare Workflows - durable execution framework\nfor building multi-step applications on Workers that automatically retry, persist\nstate, and run for hours or days.\n\nUse when: creating long-running workflows, implementing retry logic, building\nevent-driven processes, scheduling multi-step tasks, coordinating between APIs,\nor encountering \"NonRetryableError\", \"I\u002FO context\", \"workflow execution failed\",\n\"serialization error\", or \"WorkflowEvent not found\" errors.\n\nKeywords: cloudflare workflows, workflows workers, durable execution, workflow step,\nWorkflowEntrypoint, step.do, step.sleep, workflow retries, NonRetryableError,\nworkflow state, wrangler workflows, workflow events, long-running tasks, step.sleepUntil,\nstep.waitForEvent, workflow bindings\n","main","6b73b29e4866f997b1eb47fe8d9631396265fc24",0,"https:\u002F\u002Fgithub.com\u002Fdavidanthonyn\u002Fagent-skills","https:\u002F\u002Fgithub.com\u002Fdavidanthonyn","2026-09-09 16:06:07",{"source":8,"skillName":5,"commands":31,"prompt":41,"zipAvailable":42},[32,35,38],{"tool":33,"command":34},"npx","npx skills add davidanthonyn\u002Fagent-skills --skill cloudflare-workflows",{"tool":36,"command":37},"bunx","bunx skills add davidanthonyn\u002Fagent-skills --skill cloudflare-workflows",{"tool":39,"command":40},"pnpm","pnpm dlx skills add davidanthonyn\u002Fagent-skills --skill cloudflare-workflows","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fdavidanthonyn\u002Fagent-skills\u002Fblob\u002Fmain\u002Fcloudflare-workflows\u002FSKILL.md",true,[44,50,54],{"path":45,"resourceType":46,"resourceTypeDesc":47,"sizeBytes":48,"sourceHtmlUrl":49},"README.md","REFERENCE","参考文档",7255,"https:\u002F\u002Fgithub.com\u002Fdavidanthonyn\u002Fagent-skills\u002Fblob\u002Fmain\u002Fcloudflare-workflows\u002FREADME.md",{"path":51,"resourceType":46,"resourceTypeDesc":47,"sizeBytes":52,"sourceHtmlUrl":53},"SKILL.json",36072,"https:\u002F\u002Fgithub.com\u002Fdavidanthonyn\u002Fagent-skills\u002Fblob\u002Fmain\u002Fcloudflare-workflows\u002FSKILL.json",{"path":55,"resourceType":56,"resourceTypeDesc":57,"sizeBytes":58,"sourceHtmlUrl":59},"SKILL.md.backup","OTHER","其他",33489,"https:\u002F\u002Fgithub.com\u002Fdavidanthonyn\u002Fagent-skills\u002Fblob\u002Fmain\u002Fcloudflare-workflows\u002FSKILL.md.backup",[61,68,76,83,90,99],{"skillNo":62,"name":63,"nameZh":6,"description":64,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":65,"categories":66,"keywords":67,"publishedAt":18},"01M7AQNJDXVNVMN08N5BHBGZBF","zustand-state-management","Production-tested setup for Zustand state management in React applications with TypeScript.\nThis skill provides comprehensive patterns for building scalable, type-safe global state.\n\nUse when: setting up global state in React, migrating from Redux or Context API, implementing\nstate persistence with localStorage, configuring TypeScript with Zustand, using slices pattern\nfor modular stores, adding devtools middleware for debugging, handling Next.js SSR hydration,\nor encountering hydration errors, TypeScript inference issues, or persist middleware problems.\n\nPrevents 5 documented issues: Next.js hydration mismatches, TypeScript double parentheses\nsyntax errors, persist middleware export errors, infinite render loops, and slices pattern\ntype inference failures.\n\nKeywords: zustand, state management, React state, TypeScript state, persist middleware,\ndevtools, slices pattern, global state, React hooks, create store, useBoundStore,\nStateCreator, hydration error, text content mismatch, infinite render, localStorage,\nsessionStorage, immer middleware, shallow equality, selector pattern, zustand v5","https:\u002F\u002Fgithub.com\u002Fdavidanthonyn\u002Fagent-skills\u002Fblob\u002Fmain\u002Fzustand-state-management\u002FSKILL.md",[],[],{"skillNo":69,"name":70,"nameZh":6,"description":71,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":72,"sourceHtmlUrl":73,"categories":74,"keywords":75,"publishedAt":18},"01M7AQN2DW9DTPM8BYNZSHQANC","zetic-mlange","Help users integrate the ZETIC Melange (MLange) on-device AI SDK into Android (Kotlin\u002FJava) and iOS (Swift) mobile apps. Use this skill whenever the user mentions Zetic, MLange, Melange, ZeticMLangeModel, ZeticMLangeLLMModel, ZeticMLangeHFModel, on-device NPU inference for mobile, or deploying ML models to Android\u002FiOS with NPU acceleration. Also trigger when users ask about running LLMs on-device with GGUF quantization, mobile NPU model deployment, or converting PyTorch\u002FONNX models for mobile inference. Covers general model inference, LLM inference (streaming token generation), and HuggingFace model loading.","https:\u002F\u002Fgithub.com\u002Fdavidanthonyn\u002Fagent-skills\u002Fblob\u002Fmain\u002Fzetic-mlange\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fdavidanthonyn\u002Fagent-skills\u002Fblob\u002Fmain\u002Fzetic-mlange\u002FSKILL.md",[],[],{"skillNo":77,"name":78,"nameZh":6,"description":79,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":80,"categories":81,"keywords":82,"publishedAt":18},"01M7AQMEK370FBPC75N2W8WA4W","youtube-downloader","Download videos, audio, playlists, and channels from YouTube and 1000+ websites using yt-dlp. Supports quality selection, format conversion, subtitle download, playlist filtering, metadata extraction, thumbnail download, and batch operations. Use when downloading YouTube videos in any quality (4K, 8K, HDR), extracting audio as MP3\u002FM4A\u002FFLAC, downloading entire playlists\u002Fchannels, getting subtitles in multiple languages, converting to specific formats, downloading live streams, archiving content, or batch processing multiple URLs. Optimized for reliability with automatic retries, rate limiting, and error handling.","https:\u002F\u002Fgithub.com\u002Fdavidanthonyn\u002Fagent-skills\u002Fblob\u002Fmain\u002Fyoutube-downloader\u002FSKILL.md",[],[],{"skillNo":84,"name":85,"nameZh":6,"description":86,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":87,"categories":88,"keywords":89,"publishedAt":18},"01M7AQHKQ4VQB04NH6BG4SV9Q7","wordpress-plugin-core","This skill provides comprehensive knowledge for WordPress plugin development, covering core patterns, security best practices, database interactions, hooks\u002Ffilters, Settings API, custom post types, REST API, and AJAX. This skill should be used when creating WordPress plugins, troubleshooting security issues, implementing custom post types\u002Ftaxonomies, building admin interfaces, or working with the WordPress database.\n\nUse when: Creating new WordPress plugins, implementing nonces\u002Fsanitization\u002Fescaping, working with $wpdb and prepared statements, building Settings API pages, registering custom post types or taxonomies, implementing REST API endpoints, handling AJAX requests, debugging plugin activation\u002Fdeactivation issues, preventing SQL injection\u002FXSS\u002FCSRF vulnerabilities.\n\nKeywords: wordpress plugin development, wordpress security, wordpress hooks, wordpress filters, wordpress database, wpdb prepare, sanitize_text_field, esc_html, wp_nonce, custom post type, register_post_type, settings api, rest api, admin-ajax, wordpress sql injection, wordpress xss, wordpress csrf, plugin header, activation hook, deactivation hook, wordpress coding standards, wordpress plugin architecture","https:\u002F\u002Fgithub.com\u002Fdavidanthonyn\u002Fagent-skills\u002Fblob\u002Fmain\u002Fwordpress-plugin-core\u002FSKILL.md",[],[],{"skillNo":91,"name":92,"nameZh":6,"description":93,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":94,"licenseFileUrl":95,"sourceHtmlUrl":96,"categories":97,"keywords":98,"publishedAt":18},"01M7AQH4JW8F2MJFS1C43TZ2TY","webapp-testing","Test local web applications with Playwright. Use when asked to verify frontend functionality, debug UI behavior, capture browser screenshots, or inspect browser logs.","Apache-2.0","https:\u002F\u002Fgithub.com\u002Fdavidanthonyn\u002Fagent-skills\u002Fblob\u002Fmain\u002Fwebapp-testing\u002FLICENSE.txt","https:\u002F\u002Fgithub.com\u002Fdavidanthonyn\u002Fagent-skills\u002Fblob\u002Fmain\u002Fwebapp-testing\u002FSKILL.md",[],[],{"skillNo":100,"name":101,"nameZh":6,"description":102,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":103,"categories":104,"keywords":105,"publishedAt":18},"01M7AQH0PWD6Z1NN66V15DT25M","web-performance-audit","Audit web performance using Chrome DevTools MCP. Use when asked to audit, profile, debug, or optimize page load performance, Lighthouse scores, or site speed.","https:\u002F\u002Fgithub.com\u002Fdavidanthonyn\u002Fagent-skills\u002Fblob\u002Fmain\u002Fweb-performance-audit\u002FSKILL.md",[],[]]