workflow
Durable AI agent infrastructure — sets up Workflow DevKit with resilient workflows, streaming, and an extensible DurableAgent chat endpoint. Use this skill when the user says "add workflow", "setup workflow", "add durable agents", or "setup durable AI".
What this skill does
# Workflow DevKit
Durable AI agent infrastructure using [Workflow DevKit](https://useworkflow.dev). Workflows and steps survive crashes, redeploys, and infrastructure failures. Every LLM call and tool invocation is persisted, retried on failure, and observable via a local dashboard.
## Prerequisites
- Next.js app with `src/` directory and App Router
- Node.js 18+
- An AI provider API key (e.g. `OPENAI_API_KEY`)
## Installation
```bash
bun add workflow @workflow/ai ai
```
## Configuration
### Step 1: Update `next.config.ts`
Wrap your Next.js config with `withWorkflow()` to enable the `"use workflow"` and `"use step"` directives.
Find this:
```typescript
import type { NextConfig } from "next";
const nextConfig: NextConfig = {
```
Replace with:
```typescript
import { withWorkflow } from "workflow/next";
import type { NextConfig } from "next";
const nextConfig: NextConfig = {
```
Then find the bottom of the file where the config is exported. Find:
```typescript
export default nextConfig;
```
Replace with:
```typescript
export default withWorkflow(nextConfig);
```
### Step 2: Add TypeScript plugin (optional but recommended)
In `tsconfig.json`, add the workflow plugin for IntelliSense on directives.
Find:
```json
"compilerOptions": {
```
Add after the opening brace of `compilerOptions`:
```json
"plugins": [{ "name": "workflow" }],
```
### Step 3: Update middleware (if you have one)
If your project has a `middleware.ts`, update the matcher to exclude workflow internal routes.
Find the `matcher` config array and add `"/((?!.well-known/workflow).*)` to exclude workflow paths. If no middleware exists, skip this step.
## What Gets Created
```
src/
├── workflows/
│ └── chat/
│ ├── workflow.ts # DurableAgent chat workflow
│ └── tools.ts # Durable tool definitions (with comment slots)
├── app/
│ └── api/
│ └── ai/
│ └── chat/
│ ├── route.ts # POST — start workflow, stream response
│ └── [runId]/
│ └── stream/
│ └── route.ts # GET — reconnect to existing run
└── lib/
└── workflow-model.ts # Model configuration helper
```
## Setup Steps
### Step 4: Create `src/lib/workflow-model.ts`
DurableAgent accepts either a gateway model string (e.g. `"openai/gpt-4o-mini"`) or a factory function returning a provider model. We use the string approach which works with both the Vercel AI Gateway and direct provider keys.
```typescript
export function getWorkflowModel() {
return "openai/gpt-4o-mini";
}
```
### Step 5: Create `src/workflows/chat/tools.ts`
Durable tools are step functions that automatically retry on failure. Each tool gets full Node.js access inside `"use step"`.
```typescript
import { z } from "zod";
import { tool } from "ai";
// --- BASE TOOLS ---
export const getWeather = tool({
description: "Get the current weather for a location",
inputSchema: z.object({
location: z.string().describe("City name or coordinates"),
}),
execute: async ({ location }) => {
"use step";
// Replace with a real weather API call
return {
location,
temperature: 72,
condition: "sunny",
humidity: 45,
};
},
});
// [workflow-tools]: add more durable tools here
// --- TOOL REGISTRY ---
// Downstream skills add tools to this object.
export const allTools = {
getWeather,
// [workflow-tools]: register additional tools here
};
```
### Step 6: Create `src/workflows/chat/workflow.ts`
This is the core durable chat workflow. Every LLM call and tool invocation is persisted as a step.
```typescript
import { DurableAgent } from "@workflow/ai/agent";
import type { UIMessageChunk } from "ai";
import { getWritable } from "workflow";
import type { ModelMessage } from "ai";
import { getWorkflowModel } from "@/lib/workflow-model";
import { allTools } from "./tools";
export async function chatWorkflow(messages: ModelMessage[]) {
"use workflow";
const writable = getWritable<UIMessageChunk>();
// --- SYSTEM PROMPT (extensible) ---
const systemParts: string[] = [
"You are a helpful assistant. Be concise and clear in your responses.",
];
// [workflow-system]: append additional system prompt context here
const agent = new DurableAgent({
model: getWorkflowModel(),
system: systemParts.join("\n\n"),
tools: allTools,
});
await agent.stream({ messages, writable });
}
```
### Step 7: Create `src/app/api/ai/chat/route.ts`
The API route starts the workflow and returns a streaming response. It also exposes the `runId` so the client can reconnect if the connection drops.
```typescript
import { start } from "workflow/api";
import { type UIMessage, convertToModelMessages, createUIMessageStreamResponse } from "ai";
import { chatWorkflow } from "@/workflows/chat/workflow";
export async function POST(req: Request) {
const { messages }: { messages: UIMessage[] } = await req.json();
const modelMessages = await convertToModelMessages(messages);
const run = await start(chatWorkflow, [modelMessages]);
return createUIMessageStreamResponse({
stream: run.readable,
headers: {
"x-workflow-run-id": run.runId,
},
});
}
```
### Step 8: Create `src/app/api/ai/chat/[runId]/stream/route.ts`
This reconnection endpoint lets clients resume a stream after a network interruption.
```typescript
import { getRun } from "workflow/api";
export async function GET(
_req: Request,
{ params }: { params: Promise<{ runId: string }> }
) {
const { runId } = await params;
const run = await getRun(runId);
return new Response(run.getReadable(), {
headers: {
"Content-Type": "text/event-stream",
"Cache-Control": "no-cache",
Connection: "keep-alive",
"x-workflow-run-id": runId,
},
});
}
```
## Environment Variables
Add to `.env.local`. The model string format `"provider/model"` routes through the Vercel AI Gateway when deployed, or directly to the provider locally:
```
OPENAI_API_KEY=sk-...
```
To use a different provider, change the model string in `src/lib/workflow-model.ts`:
- `"openai/gpt-4o-mini"` — OpenAI (requires `OPENAI_API_KEY`)
- `"anthropic/claude-sonnet-4-5-20250929"` — Anthropic (requires `ANTHROPIC_API_KEY`)
- `"bedrock/claude-haiku-4-5-20251001-v1"` — AWS Bedrock
For Vercel AI Gateway in production, set:
```
GATEWAY_API_KEY=...
```
## Usage
### Start the dev server
```bash
bun run dev
```
The Local World activates automatically — workflow data is stored in `.workflow-data/` and steps process synchronously.
### Inspect workflows
```bash
npx workflow web
```
Opens the observability dashboard showing all runs, step traces, retries, and data flow.
```bash
npx workflow inspect runs
```
Lists all workflow runs from the CLI.
### Add `.workflow-data/` to `.gitignore`
```
.workflow-data/
```
### Test with curl
```bash
curl -X POST http://localhost:3000/api/ai/chat \
-H "Content-Type: application/json" \
-d '{"messages":[{"role":"user","content":"What is the weather in San Francisco?","parts":[{"type":"text","text":"What is the weather in San Francisco?"}],"id":"msg-1"}]}'
```
### Programmatic usage (from other API routes or server code)
```typescript
import { start, getRun } from "workflow/api";
import { chatWorkflow } from "@/workflows/chat/workflow";
import type { ModelMessage } from "ai";
// Fire and forget
const run = await start(chatWorkflow, [messages]);
console.log("Run started:", run.runId);
// Wait for completion
const result = await run.returnValue;
// Stream response
const response = new Response(run.readable);
// Check status later
const existingRun = await getRun(runId);
const status = await existingRun.status; // "running" | "completed" | "failed"
```
### Client-side integration (with @ai-sdk/react)
```typescript
"use client";
import { useChat, DefaultChatTransport } from "@ai-sdk/react";
const transport = new DefaultChatTransport({
api: "/api/ai/chat",Related in AI Agents
skill-development
IncludedComprehensive meta-skill for creating, managing, validating, auditing, and distributing Claude Code skills and slash commands (unified in v2.1.3+). Provides skill templates, creation workflows, validation patterns, audit checklists, naming conventions, YAML frontmatter guidance, progressive disclosure examples, and best practices lookup. Use when creating new skills, validating existing skills, auditing skill quality, understanding skill architecture, needing skill templates, learning about YAML frontmatter requirements, progressive disclosure patterns, tool restrictions (allowed-tools), skill composition, skill naming conventions, troubleshooting skill activation issues, creating custom slash commands, configuring command frontmatter, using command arguments ($ARGUMENTS, $1, $2), bash execution in commands, file references in commands, command namespacing, plugin commands, MCP slash commands, Skill tool configuration, or deciding between skills vs slash commands. Delegates to docs-management skill for official documentation.
reprompter
IncludedTransform messy prompts into well-structured, effective prompts — single or multi-agent. Use when: "reprompt", "reprompt this", "clean up this prompt", "structure my prompt", rough text needing XML tags and best practices, "reprompter teams", "repromptception", "run with quality", "smart run", "smart agents", multi-agent tasks, audits, parallel work, anything going to agent teams. Don't use when: simple Q&A, pure chat, immediate execution-only tasks. See "Don't Use When" section for details. Outputs: Structured XML/Markdown prompt, quality score (before/after), optional team brief + per-agent sub-prompts, agent team output files. Success criteria: Single mode quality score ≥ 7/10; Repromptception per-agent prompt quality score 8+/10; all required sections present, actionable and specific.
adaptive-compaction
IncludedAdaptive add-on policy and recovery layer that decides WHEN to compact, prune, snapshot, or fork -- replacing fixed-percent auto-compaction across Claude Code, Codex, and MCP-capable hosts. Trigger on auto-compact timing or damage: "when should I compact", "is it safe to compact now or start a fresh session", "auto-compact fires too early/mid-task", "switching to an unrelated task but the window still has space", "context rot", "answers get worse the longer the session runs", "the agent forgot the plan or my decisions after it summarized", "add a layer on top that manages context without changing the agent", raising autoCompactWindow to give the policy room, or installing/tuning a cross-tool compaction policy or PreCompact hook -- even when "compaction" is never said but the problem is context-window pressure or post-summarization memory loss. Do NOT use to summarize a conversation, build RAG, write a summarization prompt (decides WHEN not HOW), or answer max-context-length trivia.
agent-skill-creator
IncludedCreate cross-platform agent skills from workflow descriptions. Activates when users ask to create an agent, automate a repetitive workflow, create a custom skill, or need advanced agent creation. Triggers on phrases like create agent for, automate workflow, create skill for, every day I have to, daily I need to, turn process into agent, need to automate, create a cross-platform skill, validate this skill, export this skill, migrate this skill. Supports single skills, multi-agent suites, transcript processing, template-based creation, interactive configuration, cross-platform export, and spec validation.
llm-wiki
IncludedUse when building or maintaining a persistent personal knowledge base (second brain) in Obsidian where an LLM incrementally ingests sources, updates entity/concept pages, maintains cross-references, and keeps a synthesis current. Triggers include "second brain", "Obsidian wiki", "personal knowledge management", "ingest this paper/article/book", "build a research wiki", "compound knowledge", "Memex", or whenever the user wants knowledge to accumulate across sessions instead of being re-derived by RAG on every query.
skill-master
IncludedAgent Skills authoring, evaluation, and optimization. Create, edit, validate, benchmark, and improve skills following the agentskills.io specification. Use when designing SKILL.md files, structuring skill folders (references, scripts, assets), ingesting external documentation into skills, running trigger evals, benchmarking skill quality, optimizing descriptions, or performing blind A/B comparisons. Keywords: agentskills.io, SKILL.md, skill authoring, eval, benchmark, trigger optimization.