Details
## skills/output-build-workflow/SKILL.md
---
name: output-build-workflow
description: Implement an Output SDK workflow from a plan document. Use when the user asks to build, implement, or code a workflow from an existing plan, or after output-plan-workflow has produced a plan and the user is ready to build.
---
Your task is to implement an Output.ai workflow based on a provided plan document.
The workflow directory is provided as an argument (the workflow directory path). The workflow skeleton should already have been created there; if it has not, create it first.
Please read the plan file and implement the workflow according to its specifications.
Use the todo tool to track your progress through the implementation process.
# Implementation Rules
## Overview
Implement the workflow described in the plan document, following Output SDK patterns and best practices.
<pre_flight_check>
EXECUTE: Claude Skill: `output-meta-pre-flight`
</pre_flight_check>
<process_flow>
<step number="1" name="plan_analysis" subagent="workflow-context-fetcher">
### Step 1: Plan Analysis
Read and understand the plan document.
1. Read the plan file from the provided plan file path
2. Identify the workflow name, description, and purpose
3. Extract input and output schema definitions
4. List all required steps and their relationships
5. Note any LLM-based steps that require prompt templates
6. Understand error handling and retry requirements
</step>
<step number="2" name="workflow_implementation" subagent="workflow-quality">
### Step 2: Workflow Implementation
Update `workflow.ts` in the workflow directory with the workflow definition.
<implementation_checklist>
- Import required dependencies (workflow, z from '@outputai/core')
- Define inputSchema based on plan specifications
- Define outputSchema based on plan specifications
- Import step functions from steps.ts
- Implement workflow function with proper orchestration
- Handle conditional logic if specified in plan
- Add proper error handling
- When catching a specific step or evaluator error, use `hasErrorType(error, ErrorClass)` instead of `instanceof` (see `output-error-try-catch`)
</implementation_checklist>
<workflow_template>
```typescript
import { workflow, z } from '@outputai/core';
import { stepName } from './steps.js';
const inputSchema = z.object( {
// Define based on plan
} );
const outputSchema = z.object( {
// Define based on plan
} );
export default workflow( {
name: 'workflow-name-from-plan',
description: 'Description from plan',
inputSchema,
outputSchema,
fn: async input => {
// Implement orchestration logic from plan
const result = await stepName( input );
return { result };
}
} );
```
</workflow_template>
</step>
<step number="3" name="steps_implementation" subagent="workflow-quality">
### Step 3: Steps Implementation
Update `steps.ts` in the workflow directory with all step definitions from the plan.
<implementation_checklist>
- Import required dependencies (step, z from '@outputai/core')
- Implement each step with proper schema validation
- Add error handling and retry logic as specified
- Ensure step names match plan specifications
- Add descriptive comments for complex logic
</implementation_checklist>
<step_template>
```typescript
import { step, z } from '@outputai/core';
export const stepName = step( {
name: 'stepName',
description: 'Description from plan',
inputSchema: z.object( {
// Define based on plan
} ),
outputSchema: z.object( {
// Define based on plan
} ),
fn: async input => {
// Implement step logic from plan
return output;
}
} );
```
</step_template>
</step>
<step number="3.5" name="evaluators_implementation" subagent="workflow-quality">
### Step 3.5: Evaluators Implementation (if needed)
If the plan includes evaluator functions, implement them in `evaluators.ts` in the workflow directory.
<decision_tree>
IF plan_includes_evaluators:
CREATE evaluators.ts
IMPLEMENT evaluator functions per plan
ELSE:
SKIP to step 4
</decision_tree>
<implementation_checklist>
- Import required dependencies (evaluator, z, result types from '@outputai/core')
- Import `generateText` and `aiSdk` from `@outputai/llm` if using LLM-powered evaluators
- Implement each evaluator with proper schema validation
- Use appropriate result types (EvaluationBooleanResult, EvaluationNumberResult, EvaluationStringResult)
- Include confidence scores (0.0-1.0)
- Add reasoning for transparency
- All imports use .js extension
- Consider offline eval tests for dataset-driven verification (see `output-dev-eval-testing` skill)
</implementation_checklist>
<evaluator_template>
```typescript
import { evaluator, z, EvaluationBooleanResult } from '@outputai/core';
export const evaluateName = evaluator( {
name: 'evaluate_name',
description: 'Description from plan',
inputSchema: z.object( {
// Define based on plan
} ),
fn: async input => {
// Implement evaluation logic from plan
return new EvaluationBooleanResult( {
value: true,
confidence: 0.95,
reasoning: 'Explanation of evaluation'
} );
}
} );
```
</evaluator_template>
</step>
<step number="4" name="prompt_templates" subagent="workflow-prompt-writer">
### Step 4: Prompt Templates (if needed)
If the plan includes LLM-based steps, create prompt templates in the `prompts/` subdirectory of the workflow directory.
<decision_tree>
IF plan_includes_llm_steps:
CREATE prompt_templates
UPDATE steps.ts to use loadPrompt and generateText
ELSE:
SKIP to step 6
</decision_tree>
<llm_step_template>
```typescript
import { step, z } from '@outputai/core';
import { generateText } from '@outputai/llm';
export const llmStep = step( {
name: 'llmStep',
description: 'LLM-based step',
inputSchema: z.object( {
param: z.string()
} ),
outputSchema: z.string(),
fn: async ( { param } ) => {
const { result } = await generateText( {
prompt: 'prompt_name@v1',
variables: { param }
} );
return result;
}
} );
```
</llm_step_template>
<prompt_file_template>
```
---
provider: anthropic
# current as of 2026-05-04 — run output-dev-model-selection for the latest
model: claude-sonnet-4-6
temperature: 0.7
---
<assistant>
You are a helpful assistant.
</assistant>
<user>
</user>
```
</prompt_file_template>
</step>
<step number="5" name="readme_update">
### Step 5: README Update
Update `README.md` in the workflow directory with workflow-specific documentation.
<documentation_requirements>
- Update workflow name and description
- Document input schema with examples
- Document output schema with examples
- Explain each step's purpose
- Provide usage examples
- Document any prerequisites or setup requirements
- Include testing instructions
</documentation_requirements>
</step>
<step number="6" name="scenario_creation">
### Step 6: Scenario File Creation
Create at least one scenario file in the `scenarios/` subdirectory of the workflow directory for testing the workflow.
<scenario_requirements>
- Create `scenarios/` directory if it doesn't exist
- Create `test_input.json` with valid example input matching the inputSchema
- Input values should be realistic and demonstrate the workflow's purpose
- JSON must be valid and parseable
</scenario_requirements>
<scenario_template>
```json
{
// Populate with example values matching inputSchema
// Use realistic test data that demonstrates the workflow
}
```
</scenario_template>
<example>
For a workflow with inputSchema:
```typescript
z.object( {
topic: z.string(),
maxLength: z.number().optional()
} )
```
Create `scenarios/test_input.json`:
```json
{
"topic": "The history of artificial intelligence",
"maxLength": 500
}
```
</example>
</step>
<step number="7" name="validation" subagent="workflow-quality">
### Step 7: Implementation Validation
Verify the implementation is complete and correct.
<validation_checklist>
- All steps from plan are implemented
- Input/output schemas match plan specifications
- Workflow orchestration logic is correct
- Error handling is in place
- LLM prompts are created (if needed)
- Evaluators are implemented (if specified in plan)
- Evaluators use correct result types and confidence scores
- README is updated with accurate information
- Code follows Output SDK patterns
- TypeScript types are properly defined
- Scenario file exists with valid example input
- Offline eval tests created (if applicable)
</validation_checklist>
</step>
<step number="8" name="post_flight_check">
### Step 8: Post-Flight Check
Verify the implementation is ready for use.
<post_flight_check>
EXECUTE: Claude Skill: `output-meta-post-flight`
</post_flight_check>
</step>
</process_flow>
---- START ----
Use the workflow name, workflow directory, and plan file path provided as arguments, along with any additional instructions the user provided.
## skills/output-credentials-edit/SKILL.md
---
name: output-credentials-edit
description: View, edit, and set encrypted credentials in an Output.ai project. Use when adding secrets, updating API keys, verifying credential values, or retrieving a specific credential.
allowed-tools: [Read, Bash, Glob]
---
# Viewing and Editing Credentials
## When to Use This Skill
- Adding or updating API keys and secrets
- Verifying what credentials are currently stored
- Retrieving a specific credential value
- Checking credential structure before referencing in code
## Commands
### Edit (Opens `$EDITOR`)
```bash
# Edit global credentials
npx output credentials edit
# Edit environment-specific
npx output credentials edit -e production
npx output credentials edit -e development
# Edit per-workflow credentials
npx output credentials edit -w my_workflow
```
The file is decrypted to a temp file, opened in `$EDITOR`, then re-encrypted on save. The temp file is securely wiped (overwritten with null bytes) after closing.
Only `production` and `development` are valid environments: the worker picks the file from `NODE_ENV` and ignores any other name.
### Set (Single value, no editor)
```bash
# Set a single credential by dot-notation path
npx output credentials set anthropic.api_key sk-ant-...
npx output credentials set openai.api_key sk-... -e production
npx output credentials set stripe.secret_key sk_live_... -w payment_processing
```
Prefer `set` in non-interactive sessions, where `$EDITOR` can't be used. Intermediate keys are created as needed. When the new value would replace an object with a string (or the reverse), `set` asks for confirmation; pass `-y` to skip it.
### Show (Print to stdout)
```bash
# Show global credentials (plaintext — use carefully)
npx output credentials show
# Show environment-specific
npx output credentials show -e production
# Show per-workflow
npx output credentials show -w my_workflow
```
### Get (Single value)
```bash
# Get a single credential by dot-notation path
npx output credentials get anthropic.api_key
npx output credentials get aws.region
npx output credentials get stripe.secret_key -w payment_processing
```
Returns the raw string value (or JSON for nested objects).
## YAML Format
Credentials are stored as structured YAML with dot-notation access:
```yaml
anthropic:
api_key: sk-ant-...
openai:
api_key: sk-...
aws:
region: us-east-1
access_key_id: AKIA...
secret_access_key: ...
stripe:
secret_key: sk_live_...
webhook_secret: whsec_...
```
## Accessing Credentials in Code
```typescript
import { credentials } from '@outputai/core/credentials';
// Safe read — returns undefined if not found
const region = credentials.get('aws.region');
// Read with default
const region = credentials.get('aws.region', 'us-east-1');
// Strict read — throws MissingCredentialError if not found
const apiKey = credentials.require('anthropic.api_key');
```
## Credential Merging
Per-workflow credentials deep-merge over global credentials at runtime. Workflow values take precedence:
```yaml
# Global: anthropic.api_key = "sk-ant-global"
# Workflow: anthropic.api_key = "sk-ant-workflow"
# Runtime result: credentials.get('anthropic.api_key') → "sk-ant-workflow"
```
## Troubleshooting
| Error | Cause | Fix |
|-------|-------|-----|
| `MissingKeyError` | Key file not found and env var not set | Run `output credentials init` or set `OUTPUT_CREDENTIALS_KEY` |
| `MissingCredentialError` | Path not found in credentials | Add the value with `npx output credentials set` or `edit` |
| `InvalidCredentialsKeyError` | Key doesn't match the encrypted file, or the file is corrupted | Use the key the file was encrypted with, or re-init with `--force` (discards existing values) |
| `MalformedCredentialsKeyError` | Key isn't exactly 64 hex characters | Check the key for typos, whitespace, or truncation |
## Verification Checklist
- [ ] `npx output credentials show` prints expected values
- [ ] `npx output credentials get anthropic.api_key` returns the correct key
- [ ] No empty string values remain for required secrets
- [ ] Per-workflow credentials merge correctly with global
## Related Skills
- `output-credentials-init` — Create credentials files for the first time
- `output-credentials-env-vars` — Automatically wire credentials to env vars
- `output-dev-credentials` — Full credentials system reference
## skills/output-credentials-env-vars/SKILL.md
---
name: output-credentials-env-vars
description: "Wire encrypted credentials to environment variables using the credential: convention. Use when setting up LLM provider keys (ANTHROPIC_API_KEY, OPENAI_API_KEY) or any env var that should come from encrypted credentials."
allowed-tools: [Read, Edit, Bash, Glob]
---
# Credentials as Environment Variables
## When to Use This Skill
- Setting up `ANTHROPIC_API_KEY` or `OPENAI_API_KEY` from encrypted credentials
- Wiring any credential path to a `process.env` variable automatically
- Migrating from plaintext `.env` secrets to encrypted credentials
- Understanding why an env var is being resolved at worker startup
## The `credential:` Convention
Any env var whose value starts with `credential:` is resolved from encrypted credentials at worker startup. The format is:
```
ENV_VAR_NAME=credential:<dot.path>
```
### Example `.env`
```bash
# These are resolved automatically from the global credentials
ANTHROPIC_API_KEY=credential:anthropic.api_key
OPENAI_API_KEY=credential:openai.api_key
# Any credential path works
MY_SERVICE_TOKEN=credential:my_service.token
DATABASE_URL=credential:postgres.url
```
### Encrypted credentials (`config/credentials.yml.enc`)
```yaml
anthropic:
api_key: sk-ant-... # → resolves ANTHROPIC_API_KEY
openai:
api_key: sk-... # → resolves OPENAI_API_KEY
my_service:
token: tok_live_... # → resolves MY_SERVICE_TOKEN
postgres:
url: postgres://... # → resolves DATABASE_URL
```
## How It Works
When the worker starts, every env var set to `credential:<path>` is replaced with the decrypted value at that path. By the time a workflow runs, `ANTHROPIC_API_KEY` holds the real key and LLM SDKs read it as usual.
Values come from the global credentials for the current environment: `config/credentials/<NODE_ENV>.yml.enc` when it exists, otherwise `config/credentials.yml.enc`. Workflow-scoped credentials are never used for env vars, so keep these paths in the global file.
## Precedence Rules
Real env var values always take precedence. If `ANTHROPIC_API_KEY` is already set to a non-`credential:` value (e.g. from the shell or a CI secret), it is **never overwritten**:
```bash
# Real value - never replaced
ANTHROPIC_API_KEY=sk-ant-real-override
# Placeholder — gets replaced at startup
ANTHROPIC_API_KEY=credential:anthropic.api_key
```
This means you can override any credential ref at deploy time without changing files.
## Setting Up the Convention
### Step 1: Initialize credentials (if not done)
```bash
npx output credentials init
npx output credentials edit # Add anthropic.api_key, openai.api_key
```
### Step 2: Update `.env`
```bash
# Replace plaintext secrets with credential references
ANTHROPIC_API_KEY=credential:anthropic.api_key
OPENAI_API_KEY=credential:openai.api_key
```
### Step 3: Verify
Start the worker and look for the log line:
```
[info] Credentials: Resolved credential env vars { vars: [ "ANTHROPIC_API_KEY", "OPENAI_API_KEY" ] }
```
If the log line lists your env vars, credentials are wired correctly.
## Verification Checklist
- [ ] `config/credentials.yml.enc` contains the target credential paths
- [ ] `.env` uses `credential:<path>` values for the relevant env vars
- [ ] Worker startup log shows `Resolved credential env vars` listing the expected env vars
- [ ] First LLM workflow run succeeds (confirming `ANTHROPIC_API_KEY` is set correctly)
- [ ] Setting a real env var in the shell overrides the credential ref
## Related Skills
- `output-credentials-init` — Create the encrypted credentials file
- `output-credentials-edit` — Add/update credential values
- `output-dev-credentials` — Full credentials system reference
## skills/output-credentials-init/SKILL.md
---
name: output-credentials-init
description: Initialize encrypted credentials for an Output.ai project. Use when setting up credentials for the first time, adding environment-specific credentials, or adding per-workflow credentials.
allowed-tools: [Read, Bash, Glob]
---
# Initializing Credentials
## When to Use This Skill
- First time setting up credentials for a project
- Adding production/development environment-specific credentials
- Adding per-workflow credentials that override global ones
- Re-initializing credentials after losing a key file
## Overview
The `npx output credentials init` command generates two files:
- A **key file** (`.key`) — the decryption secret. **Never commit this.**
- An **encrypted YAML file** (`.yml.enc`) — the credentials store. Safe to commit.
## Commands
```bash
# Global credentials (most common)
npx output credentials init
# Environment-specific (only production and development are read by the worker, based on NODE_ENV)
npx output credentials init -e production
npx output credentials init -e development
# Per-workflow credentials (overrides globals for that workflow)
npx output credentials init -w my_workflow
# Force overwrite existing files
npx output credentials init --force
```
## What Gets Created
### Global (default)
```
config/
├── credentials.key ← Add to .gitignore
└── credentials.yml.enc ← Safe to commit
```
### Environment-specific
```
config/credentials/
├── production.key ← Add to .gitignore
└── production.yml.enc ← Safe to commit
```
### Per-workflow
```
src/workflows/{name}/
├── credentials.key ← Add to .gitignore
└── credentials.yml.enc ← Safe to commit
```
## Default Template
After init, the encrypted YAML contains this template:
```yaml
anthropic:
api_key: ""
openai:
api_key: ""
```
## After Init: Add Your Secrets
```bash
npx output credentials edit # Opens $EDITOR with decrypted YAML
```
Fill in the empty values, save, and close. The file is re-encrypted automatically.
## Gitignore Setup
```bash
echo "*.key" >> .gitignore
echo "config/credentials.key" >> .gitignore
```
Or add to your `.gitignore`:
```
# Credentials decryption keys — never commit
*.key
config/credentials.key
config/credentials/*.key
src/workflows/*/credentials.key
```
## CI/CD: Key Distribution
In CI/CD pipelines, pass the key as an environment variable instead of committing the file:
```bash
# Set in your CI/CD environment
OUTPUT_CREDENTIALS_KEY=<key-value>
# Environment-specific
OUTPUT_CREDENTIALS_KEY_PRODUCTION=<key-value>
# Per-workflow
OUTPUT_CREDENTIALS_KEY_MY_WORKFLOW=<key-value>
```
The key value is the contents of the `.key` file.
## Verification Checklist
- [ ] `config/credentials.key` created (or env-specific variant)
- [ ] `config/credentials.yml.enc` created
- [ ] `.key` files added to `.gitignore`
- [ ] `npx output credentials edit` run to fill in secret values
- [ ] `npx output credentials show` verifies decryption works
## Related Skills
- `output-credentials-edit` — Fill in and manage credential values
- `output-credentials-env-vars` — Wire credentials to environment variables
- `output-dev-credentials` — Full credentials system reference
## skills/output-debug-workflow/SKILL.md
---
name: output-debug-workflow
description: Debug Output SDK workflow issues. Use when user reports a workflow failing, erroring, hanging, producing wrong results, or asks to debug, troubleshoot, or investigate a workflow execution.
---
Your task is to systematically debug an Output SDK workflow issue in a local development environment.
The arguments the user provided describe the problem they're experiencing, and may include a specific workflow ID.
Use the todo tool to track your progress through the debugging process.
# Debugging Process
## Overview
Follow a systematic approach to identify and resolve workflow execution issues: verify infrastructure, gather evidence, analyze traces, and apply targeted fixes.
<pre_flight_check>
EXECUTE: Claude Skill: `output-meta-pre-flight`
</pre_flight_check>
<process_flow>
<step number="1" name="verify_services">
### Step 1: Verify Services Running
Before debugging, confirm that all required services are operational. The `output-services-check` skill provides comprehensive guidance.
<verification_commands>
```bash
# Check Docker containers are running
docker ps | grep output
# Verify Output services respond
curl -s http://localhost:3001/health || echo "API not responding"
# Check Temporal UI is accessible
curl -s http://localhost:8080 > /dev/null && echo "Temporal UI accessible" || echo "Temporal UI not accessible"
```
</verification_commands>
<decision_tree>
IF docker_not_running:
RUN: docker compose up -d
WAIT: for services to start (30-60 seconds)
IF output_dev_not_running:
RUN: npx output dev
WAIT: for services to initialize
IF all_services_running:
PROCEED: to step 2
</decision_tree>
**Expected State**:
- Docker containers for `output` are running
- API server responds at `http://localhost:3001`
- Temporal UI accessible at `http://localhost:8080`
</step>
<step number="2" name="list_workflow_runs">
### Step 2: List Workflow Runs
Identify the failing workflow execution by listing recent runs. The `output-workflow-runs-list` skill provides detailed filtering guidance.
<list_commands>
```bash
# List all recent workflow runs
npx output workflow runs list
# Filter by specific workflow type (if known)
npx output workflow runs list <workflowName>
# Get detailed JSON output for analysis
npx output workflow runs list --json
# Limit results to most recent
npx output workflow runs list --limit 10
```
</list_commands>
<identification_criteria>
Look for:
- Status: FAILED or TERMINATED
- Recent timestamp matching when the issue occurred
- Workflow type matching the problem description
</identification_criteria>
<decision_tree>
IF user_provided_workflow_id:
USE: provided workflow ID
PROCEED: to step 3
IF failed_runs_found:
SELECT: most recent failed run
NOTE: workflow ID from output
PROCEED: to step 3
IF no_runs_found:
CHECK: workflow exists with `npx output workflow list`
IF workflow_not_found:
REPORT: workflow doesn't exist
SUGGEST: verify workflow name and location
ELSE:
SUGGEST: run the workflow with `npx output workflow run <name>`
</decision_tree>
</step>
<step number="3" name="debug_workflow" subagent="workflow-debugger">
### Step 3: Debug Specific Workflow
Retrieve and analyze the execution trace for the identified workflow. The `output-workflow-trace` skill provides analysis techniques.
<debug_commands>
```bash
# Display execution trace (text format)
npx output workflow debug <workflowId>
# Display full untruncated trace (JSON format) - recommended for detailed analysis
npx output workflow debug <workflowId> --json
```
</debug_commands>
**Tip**: Use `--json` for complete trace data without truncation.
<analysis_checklist>
1. Identify which step failed
2. Examine the error message and stack trace
3. Check input data passed to the failing step
4. Check output data from preceding steps
5. Look for patterns matching common error types
</analysis_checklist>
<temporal_ui_guidance>
For visual workflow inspection, open the Temporal Web UI at **http://localhost:8080**:
- Find your workflow execution by ID
- View the event history timeline
- Inspect individual step inputs and outputs
</temporal_ui_guidance>
</step>
<step number="4" name="suggest_fixes" subagent="workflow-quality">
### Step 4: Suggest Fixes
Based on the trace analysis, identify the error pattern and suggest targeted fixes. Claude will invoke the relevant error skill based on symptoms.
<error_matching>
| Symptom | Skill |
|---------|-------|
| "incompatible schema" errors, type errors | `output-error-zod-import` |
| Replay failures, inconsistent results | `output-error-nondeterminism` |
| Retries not working, errors swallowed | `output-error-try-catch` |
| Type errors, undefined properties at step boundaries | `output-error-missing-schemas` |
| Workflow hangs, determinism errors | `output-error-direct-io` |
| Untraced requests, axios errors | `output-error-http-client` |
</error_matching>
<decision_tree>
IF error_matches_known_pattern:
INVOKE: relevant error skill for detailed fix
ELSE:
CONSULT: workflow-quality subagent for additional patterns
SUGGEST: Manual trace inspection in Temporal UI
</decision_tree>
<verification>
After applying fix:
```bash
# Re-run the workflow to verify
npx output workflow run <workflowName> --input '<json>'
# Or start asynchronously and check result
npx output workflow start <workflowName> --input '<json>'
npx output workflow status <workflowId>
npx output workflow result <workflowId>
# Or, if the fix only affects a specific step and earlier steps succeeded,
# re-run from after the last known-good step (skips re-executing earlier work)
npx output workflow reset <workflowId> --step <lastGoodStep> --reason "<fix description>"
```
For targeted rerun after fixing a downstream step, see the `output-workflow-reset` skill.
</verification>
</step>
</process_flow>
<post_flight_check>
EXECUTE: Claude Skill: `output-meta-post-flight`
</post_flight_check>
---- START ----
Use the problem description and any optional workflow ID the user provided.
## skills/output-dev-agent-class/SKILL.md
---
name: output-dev-agent-class
description: Use the Agent class for multi-step tool loops, conversation history, streaming progress, and reusable LLM agents. Use when building agents with skills, structured output, stateful conversations, or streaming callbacks.
allowed-tools: [Read, Write, Edit]
---
# Using the Agent Class
## Overview
The `Agent` class uses an internal AI SDK `ToolLoopAgent` through composition with Output prompt files and the skills system. It does not inherit from `ToolLoopAgent`. Use it when you need multi-step tool execution, conversation history, or a reusable agent instance. For single-shot LLM calls without tools, `generateText` is simpler.
## When to Use This Skill
- Building multi-step agents that call tools in a loop
- Using skills (lazy-loaded instructions) with an agent
- Creating agents with structured output via `aiSdk.Output.object()`
- Implementing stateful conversations with `messageStore`
- Streaming Agent progress with `onChunk`
- Deciding between `Agent` and `generateText`
## Import Pattern
```typescript
import { Agent, aiSdk } from '@outputai/llm';
import type { MessageStore } from '@outputai/llm';
import { z } from '@outputai/core';
```
`Agent` comes from `@outputai/llm`. Use `aiSdk.Output` for structured output. Import `z` from `@outputai/core` (never from `zod` directly). `MessageStore` is the type for a pluggable `getMessages` / `addMessages` store; implement it yourself.
## Construction
The prompt file is loaded and rendered at construction time. Variables and tools are fixed at construction. Skills and `maxSteps` come from the prompt file. The agent is ready to call `generate()`, `generateWithStreaming()`, or `stream()` immediately.
```typescript
const agent = new Agent( {
prompt: 'writing_assistant@v1',
variables: {
content_type: input.contentType,
focus: input.focus,
content: input.content
},
output: aiSdk.Output.object( { schema: reviewSchema } )
} );
```
### Constructor Options
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `prompt` | `string` | *(required)* | Prompt file name (e.g. `'writing_assistant@v1'`) |
| `promptDir` | `string` | - | Override the stack-resolved prompt directory |
| `variables` | `PromptVariables` | - | Template variables rendered at construction |
| `tools` | AI SDK tools | - | Caller tools; merged with prompt YAML tools (`load_skill` last) |
| `stopWhen` | function or function[] | - | Custom stop condition (overrides prompt `maxSteps` when tools exist) |
| `output` | `aiSdk.Output` | - | Structured output spec (e.g. `aiSdk.Output.object({ schema })`) |
| `messageStore` | `MessageStore` | - | Pluggable store for multi-turn history |
## generate()
Run the agent and return when complete:
```typescript
const result = await agent.generate();
console.log( result.text ); // Generated text
console.log( result.output ); // Structured output (when using aiSdk.Output.object)
console.log( result.usage ); // Token counts
```
The result has the same shape as `generateText`: `text`, `result` (alias for `text`), `output`, `usage`, `finishReason`, `toolCalls`, etc.
### Passing Additional Messages
Extend the conversation with extra messages:
```typescript
const result = await agent.generate( {
messages: [ { role: 'user', content: 'Focus on the introduction section.' } ]
} );
```
Messages are appended after the initial prompt messages (and any message-store history). You can also pass `abortSignal` and `toolChoice`.
## generateWithStreaming()
Use `generateWithStreaming()` when you need progress callbacks and a complete result:
```typescript
const result = await agent.generateWithStreaming( {
onChunk( { chunk } ) {
if ( chunk.type === 'text-delta' ) {
process.stdout.write( chunk.text );
}
}
} );
```
The method behaves like `generate()` while using streaming internally. It returns the complete response, rejects on stream errors, and automatically appends messages to the configured message store. It accepts the same `messages`, `abortSignal`, and `toolChoice` as `generate()`, plus `onChunk`. Prefer it over `stream()` in Temporal activity steps unless direct access to the stream result is required.
## stream()
Use `stream()` when direct control over `textStream` or `stream` is required. It accepts the same `messages`, `abortSignal`, and `toolChoice` as `generate()`, plus `onChunk`, `onEnd`, and `onError`:
```typescript
const stream = await agent.stream();
for await ( const chunk of stream.textStream ) {
process.stdout.write( chunk );
}
```
Like `streamText`, the stream result provides `textStream` and `stream` iterables, plus promise-based properties (`text`, `usage`, `finishReason`) that resolve on completion.
`stream()` appends messages to the message store in its wrapped `onEnd` when `finishReason` is not `'error'`. See `output-dev-llm-streaming` for streaming and error-handling guidance.
## Structured Output
Use `aiSdk.Output.object()` to get typed responses:
```typescript
const reviewSchema = z.object( {
issues: z.array( z.string() ).describe( 'List of issues found' ),
suggestions: z.array( z.string() ).describe( 'Actionable suggestions' ),
score: z.number().describe( 'Quality score 0-100' ),
summary: z.string().describe( 'Brief overall assessment' )
} );
const agent = new Agent( {
prompt: 'writing_assistant@v1',
variables: { content_type: 'documentation', focus: 'clarity', content: markdownContent },
output: aiSdk.Output.object( { schema: reviewSchema } )
} );
const { output } = await agent.generate();
// output: { issues: string[], suggestions: string[], score: number, summary: string }
```
Use `.describe()` on schema fields instead of `.min()/.max()` for number constraints. Anthropic does not support `minimum`/`maximum` JSON Schema constraints in tool definitions.
## Message Store
By default, Agent is stateless. Each `generate()` call starts fresh with only the initial prompt messages. Pass a `messageStore` to maintain history across calls:
```typescript
import { Agent } from '@outputai/llm';
import type { MessageStore } from '@outputai/llm';
const messages: Parameters<MessageStore['addMessages']>[0] = [];
const messageStore: MessageStore = {
getMessages: () => messages,
addMessages: incoming => {
messages.push( ...incoming );
}
};
const chatbot = new Agent( {
prompt: 'chatbot@v1',
messageStore
} );
const r1 = await chatbot.generate( {
messages: [ { role: 'user', content: 'Hello, tell me about Output.' } ]
} );
// r1.text: "Output is an AI framework for..."
const r2 = await chatbot.generate( {
messages: [ { role: 'user', content: 'How does it handle retries?' } ]
} );
// r2 sees the full history from r1
```
`MessageStore` is:
```typescript
interface MessageStore {
getMessages(): ModelMessage[] | Promise<ModelMessage[]>;
addMessages( messages: ModelMessage[] ): void | Promise<void>;
}
```
`ModelMessage` is an AI SDK type available through the `aiSdk` namespace or as an import from `ai`. There is no built-in store. Implement the interface in memory for a single process, or with your database for durable history.
## Using Agent in Workflow Steps
In workflow steps, construct a new Agent per invocation. Variables come from the step input:
```typescript
import { step, z } from '@outputai/core';
import { Agent, aiSdk } from '@outputai/llm';
const reviewSchema = z.object( {
summary: z.string().describe( 'Brief assessment' ),
issues: z.array( z.string() ).describe( 'Problems found' ),
suggestions: z.array( z.string() ).describe( 'Improvements' ),
score: z.number().describe( 'Quality score 0-100' )
} );
export const reviewContent = step( {
name: 'reviewContent',
description: 'Review technical content using Agent with structured output',
inputSchema: z.object( {
content: z.string().describe( 'The content to review' ),
content_type: z.string().describe( 'Type of content' ),
focus: z.string().describe( 'Review focus areas' )
} ),
outputSchema: reviewSchema,
fn: async input => {
const agent = new Agent( {
prompt: 'writing_assistant@v1',
variables: input,
output: aiSdk.Output.object( { schema: reviewSchema } )
} );
const { output } = await agent.generate();
return output;
}
} );
```
This is the standard pattern. Each step invocation is independent, and Agent construction is cheap.
## Using Agent with Skills
List skill paths in the prompt frontmatter. See `output-dev-skill-file` for the full skills guide.
## When to Use Agent vs generateText
| | `generateText` | `Agent` |
|---|---|---|
| **Best for** | Single-shot LLM calls | Multi-step tool loops |
| **Tools** | Supported | Supported |
| **Skills** | Supported | Supported |
| **Conversation history** | Manual | Built-in with `messageStore` |
| **Reusable instance** | No (function call) | Yes (construct once, call many) |
| **Structured output** | `aiSdk.Output.object()` | `aiSdk.Output.object()` |
Start with `generateText`. Move to `Agent` when you need conversation state or a reusable instance with a fixed configuration.
### generateText Example (for comparison)
```typescript
import { generateText } from '@outputai/llm';
const { result } = await generateText( {
prompt: 'generate_summary@v1',
variables: {
company_name: input.name,
website_content: input.websiteContent
}
} );
```
## Verification Checklist
- [ ] Import `Agent` from `@outputai/llm` (not from `ai` directly)
- [ ] Import `z` from `@outputai/core` (never from `zod`)
- [ ] Prompt file exists in `prompts/` folder
- [ ] Variables match `{{ variable }}` placeholders in the prompt
- [ ] Prompt frontmatter sets `maxSteps` when skills or tools need a ceiling other than 10
- [ ] `aiSdk.Output.object({ schema })` uses `.describe()` not `.min()/.max()` on numbers
- [ ] `messageStore` is only used when multi-turn history is needed
- [ ] Agent is constructed inside the step `fn` (not at module level) for workflow steps
- [ ] Prefer `generateWithStreaming()` when callbacks are sufficient
## Related Skills
- `output-dev-skill-file` - Creating skill files for agents
- `output-dev-llm-streaming` - Streaming progress and Temporal-safe error handling
- `output-dev-prompt-file` - Creating .prompt files used by agents
- `output-dev-step-function` - Using agents in step functions
- `output-dev-types-file` - Defining Zod schemas for structured output
- `output-dev-workflow-function` - Orchestrating agent-powered steps
## skills/output-dev-code-style/SKILL.md
---
name: output-dev-code-style
description: Code style conventions for Output SDK workflow projects. Use when writing or reviewing any TypeScript/JavaScript code. Discovers the project's own linting rules first; falls back to Output SDK conventions when no linter is configured.
allowed-tools: [Read, Bash, Glob, Grep]
---
# Code Style Conventions
## Overview
Generated code must match the style of the project it lives in. Many projects use their own linter or formatter (ESLint, Prettier, Biome, etc.) with rule sets that differ from Output's defaults. **Always discover and follow the project's rules first.** Only fall back to the Output SDK conventions below when the project has no linter or formatter configured.
## When to Use This Skill
- Writing any TypeScript or JavaScript code in a workflow project
- Reviewing generated code before delivery
- Fixing lint errors after generation
## Rules Discovery (do this first)
Before writing or reviewing code, determine the project's style rules:
1. **Check for a linter config.** Look for `eslint.config.js`, `.eslintrc.*`, `biome.json`, `deno.json`, or similar in the project root.
2. **Check for a formatter config.** Look for `.prettierrc*`, `.editorconfig`, or formatter settings in `package.json`.
3. **Check for lint/format scripts.** Look in `package.json` for `lint`, `lint:fix`, `format`, or similar scripts.
4. **Read existing source files.** If no config exists, infer conventions from the existing code (comma style, quote style, indentation, semicolons, spacing).
### If the project has a linter or formatter
- Follow its rules. Do not apply Output SDK conventions that conflict.
- Run the project's lint/format command after generating code.
- If a rule is ambiguous, match the patterns in existing source files.
### If the project has no linter or formatter
- Apply the Output SDK Default Conventions below.
- Match any conventions already present in existing source files -- consistency with the repo takes priority over the defaults below.
## Output SDK Default Conventions
These rules reflect the Output SDK's own ESLint config. Apply them only when the project has no linter configured and no conflicting conventions are evident in existing code.
### No Trailing Commas
Never use trailing commas in objects, arrays, function parameters, or type definitions.
```typescript
// CORRECT
const config = {
name: 'workflow',
timeout: 30000
};
const items = [ 'a', 'b', 'c' ];
export const myStep = step( {
name: 'myStep',
inputSchema: MyInputSchema,
outputSchema: MyOutputSchema,
fn: async input => {
return { result: input.value };
}
} );
```
```typescript
// WRONG - trailing commas
const config = {
name: 'workflow',
timeout: 30000, // <-- not allowed
}
const items = [ 'a', 'b', '