
orchestration
Multi-agent workflow orchestration with natural language creation, parallel execution, conditional flows, and visual progress tracking
- version
- 1.0.0
Install
/plugin install orchestration@orchestration-marketplaceRun it inside Claude Code after adding the marketplace with /plugin marketplace add Sixallfaces/orkestr.
Contents
Discovered from sourceSkills 9
Creating Workflows from Description
When to Use
Proactively suggest orchestration when user describes tasks involving:
- Multiple sequential steps with dependencies
- Parallel operations that could run simultaneously
- Conditional logic or branching (if/then scenarios)
- Error handling or retry requirements
- Testing, review, and deployment phases
- Complex multi-agent coordination
- Quality gates or approval checkpoints
Trigger Patterns
Watch for these patterns in user messages:
Explicit workflow requests:
- "I need to [multi-step task]"
- "Help me build a pipeline for [process]"
- "Create a workflow that [description]"
- "Automate [complex task]"
Implicit workflow descriptions:
- User describes 3+ sequential steps
- User mentions temporal ordering: "then", "after that", "once that's done"
- User mentions conditionals: "if that works", "if tests pass"
- User mentions parallel work: "at the same time", "in parallel", "simultaneously"
- User mentions reviews/approvals: "needs review", "after approval"
- User mentions retry/error handling: "if it fails", "retry", "rollback"
Example phrases:
- "run tests, then if they pass..."
- "deploy to production after security review"
- "implement with TDD workflow"
- "check code quality before merging"
- "parallel test execution"
Action
When triggers detected, suggest orchestration:
This sounds like a perfect use case for orchestration! I can help you create a workflow that handles:
[List 2-4 key aspects identified from description, e.g.:]
- Sequential testing and deployment steps
- Parallel validation (tests + security scan)
- Conditional deployment based on test results
- Automatic rollback on failure
Would you like me to guide you through creating this workflow?
If user says yes:
Execute the create command with their description:
/orchestration:create [initial description from user message]
If user says no or wants to see example first:
Show relevant example from docs/reference/examples.md that matches their pattern.
Examples
Example 1: TDD Workflow
User: "I need to implement authentication using test-driven development"
Assistant: "This sounds like a perfect use case for orchestration! I can help you create a TDD workflow that handles:
- Writing tests first
- Running tests and tracking results
- Implementing features to pass tests
- Automatic retry loop for failed tests
Would you like me to guide you through creating this workflow?"
If yes: /orchestration:create implement authentication with TDD
Example 2: Deployment Pipeline
User: "Can you help me set up automated deployment that runs tests first, then if everything passes, does a security scan, and only deploys if both succeed?"
Assistant: "This sounds like a perfect use case for orchestration! I can help you create a deployment pipeline that handles:
- Parallel test and security validation
- Quality gate before deployment (both must pass)
- Automatic deployment when validation succeeds
- Rollback capability if deployment fails
Would you like me to guide you through creating this workflow?"
If yes: /orchestration:create deploy with tests and security validation
Example 3: Code Review Workflow
User: "I want to make sure all my changes go through code review and pass linting before merging"
Assistant: "This sounds like a perfect use case for orchestration! I can help you create a review workflow that handles:
- Parallel code review and linting
- Quality gate (both must succeed)
- Manual approval checkpoint
- Automatic merge after approval
Would you like me to guide you through creating this workflow?"
If yes: /orchestration:create code review with linting and approval
Don't Trigger For
Simple single-step tasks:
- "Run the tests" ← just run tests
- "Deploy to production" ← single action
- "Review this code" ← single agent
Already using orchestration syntax:
- User provides workflow syntax directly
- User asks to modify existing workflow
Exploratory questions:
- "What is orchestration?"
- "How does the menu work?"
- "Show me examples"
Integration
This skill makes Claude proactive about suggesting orchestration when appropriate. It works alongside:
/orchestration:create- Command this skill triggersusing-orchestration- General guidance skillworkflow-socratic-designer- Agent this launches
Success Criteria
✅ Claude suggests orchestration for multi-step tasks ✅ Claude identifies parallel opportunities ✅ Claude recognizes conditional logic needs ✅ Claude explains workflow benefits before offering ✅ Claude uses /orchestration:create when user agrees
Creating Orchestration Workflows
I'll help you create powerful orchestration workflows that coordinate multiple Claude Code agents. I use Socratic questioning to understand your needs and generate optimal workflow syntax.
When I Activate
I automatically activate when you:
- Describe a multi-step process you want to automate
- Mention "workflow", "orchestration", "automate", "coordinate agents"
- Ask "how do I create a workflow?"
- Want to connect multiple agents or tasks
- Ask about automating repetitive processes
My Process
1. Understanding Your Intent
CRITICAL: I use AskUserQuestion tool for ALL questions. NO plain text numbered lists.
I'll ask strategic questions to understand:
- What problem you're solving
- What your goal is
- What scope you have in mind
- What external data sources you need (APIs, web scraping, databases)
2. Detecting Temp Script Needs
I automatically scan for these triggers:
- External APIs: Reddit, Twitter, GitHub, ProductHunt, etc.
- Web Scraping: Extracting data from websites
- Data Processing: Analyzing 10+ items, statistical analysis
- Authentication: Any service requiring API keys
If detected → I'll proactively create temp scripts for you
3. Identifying the Pattern
I'll determine if your workflow is:
- Sequential: One step after another (
->) - Parallel: Multiple tasks at once (
||) - Conditional: Based on results (
~>) - Hybrid: Combination of above
3. Designing the Workflow
I'll help you define:
- Which agents to use (built-in or custom)
- How data flows between steps
- Error handling strategy
- Review checkpoints
4. Generating Syntax
I'll create clean, readable workflow syntax like:
# Simple sequential workflow
explore:"Analyze codebase" ->
implement:"Add feature" ->
test:"Run tests"
# Parallel with merge
[security-check || style-check || performance-check] ->
general-purpose:"Consolidate findings"
Question Approach
For more details on my questioning strategy, see socratic-method.md.
Quick overview:
- Vague requests: I ask about problem → scope → constraints
- Specific requests: I confirm pattern → ask about customization
- Medium requests: I explore scope → clarify details
Common Patterns
I have templates for common scenarios. See patterns.md for complete catalog.
Popular patterns:
- Feature implementation (explore → implement → test → review)
- Bug fixing (investigate → fix → verify)
- Security scanning (scan → review → fix → verify)
- Documentation (analyze → write → review)
- Refactoring (analyze → refactor → test → validate)
Custom Agents
When your workflow needs specialized expertise, I can create temp agents for you.
Temp agents are:
- Created automatically during workflow design
- Saved in
temp-agents/directory - Auto-cleaned after workflow execution
- Can be promoted to permanent agents if useful
When I create temp agents:
- You need domain-specific expertise (e.g., security scanner)
- Task requires specific output formats
- Multiple workflows might benefit (I'll suggest making it permanent)
See temp-agents.md for examples and guidelines.
Temp Scripts (CRITICAL)
Temp scripts are Python/Node.js scripts I create for tasks that Claude Code tools can't handle directly.
When I Create Temp Scripts
I automatically create temp scripts when you need:
- External API calls - Reddit, Twitter, GitHub, ProductHunt
- Web scraping - Extracting data from websites
- Data processing - Pandas analysis, JSON parsing at scale
- Database queries - SQL, NoSQL operations
- Batch operations - Processing 10+ files
- Third-party libraries - NumPy, BeautifulSoup, requests
How It Works
You say: "Fetch 10 Reddit posts about startups"
I create:
general-purpose:"Create Python script using PRAW library:
1. Authenticate with Reddit API (client_id, client_secret)
2. Fetch 10 hot posts from r/startups
3. Extract: title, url, score, selftext
4. Return JSON array
5. Save as temp-scripts/reddit_fetcher.py
6. Execute and return results":reddit_posts
Proactive Detection
I scan your request for keywords:
- "API", "fetch", "scrape", "get data from"
- "Reddit", "Twitter", "ProductHunt", "GitHub"
- "analyze", "process", "calculate"
- Numbers like "10 posts", "100 records"
If found → I'll suggest temp scripts and ask for your confirmation
When Uncertain
If I'm not sure whether you need a temp script, I'll ask:
AskUserQuestion({
questions: [{
question: "How should I handle this data processing?",
header: "Approach",
multiSelect: false,
options: [
{label: "Built-in tools", description: "Use Read/Grep for simple operations"},
{label: "Create temp script", description: "Python script for complex processing"},
{label: "External API", description: "Fetch from service with authentication"}
]
}]
})
For complete guide, see: docs/TEMP-SCRIPTS-DETECTION-GUIDE.md
Custom Syntax
Sometimes you need syntax beyond the basics. I can design custom syntax elements like:
- New operators (
=>for merge-with-dedup) - Checkpoints (
@security-gate) - Conditions (
if security-critical) - Loops (
retry-with-backoff)
I follow a reuse-first approach: I check existing syntax before creating new.
See custom-syntax.md for syntax design process.
Examples
Real workflow examples to inspire you:
See examples.md for complete catalog with explanations.
Quick examples:
TDD Implementation:
# Test-Driven Development workflow
general-purpose:"Write failing test":test_file ->
implement:"Make test pass":implementation ->
code-reviewer:"Review {implementation}":review ->
(if review.approved)~> commit:"Commit changes" ~>
(if review.needs_changes)~> implement:"Fix issues"
Bug Investigation:
# Parallel investigation with consolidation
[
explore:"Find related code":related_files ||
general-purpose:"Search for similar bugs":similar_issues ||
general-purpose:"Check recent changes":recent_commits
] ->
general-purpose:"Consolidate findings into root cause analysis":analysis ->
implement:"Fix bug based on {analysis}":fix ->
general-purpose:"Run relevant tests":test_results
Security Audit:
# Security scanning with manual gate
$security-scanner:"Scan codebase for vulnerabilities":findings ->
@security-review:"Review {findings}. Approve if no critical issues." ->
(if approved)~> deploy:"Deploy to production"
Workflow Templates
After creating your workflow, I'll offer to save it as a template for reuse.
Templates include:
- Descriptive name and metadata
- Parameter placeholders for customization
- Complete workflow syntax
- Usage instructions
Templates are saved in examples/ directory as .flow files.
What Happens Next
After I create your workflow:
- Review: I show you the generated syntax with explanation
- Customize: You can ask for modifications
- Save: I offer to save as template
- Execute: Use
/orchestration:runto execute it
Tips for Best Results
- Be specific: More details = better workflow
- Ask questions: I'm here to help refine your ideas
- Start simple: We can add complexity later
- Review examples: Check examples.md for inspiration
Technical Details
- Namespace: All plugin agents use
orchestration:prefix - Temp agents: Auto-prefixed with
orchestration: - Variable binding: Use
:variable_nameto capture outputs - Error handling: Use
(if failed)~>for error branches
For complete syntax reference, see executing-workflows skill or syntax reference.
Related Skills
- executing-workflows: Run workflows with visualization and steering
- managing-agents: Create and manage custom agents
- designing-syntax: Design custom syntax elements
- using-templates: Use and customize workflow templates
Ready to create a workflow? Just describe what you want to automate!
Debugging Orchestration Workflows
I help diagnose and fix workflow execution issues using systematic debugging techniques.
When I Activate
I activate when you:
- Experience workflow failures
- Get syntax errors
- Have agent execution issues
- Variables not working as expected
- Ask "why isn't this working?"
Common Issues
Syntax Errors
Problem: Workflow won't parse
Symptoms:
- "Unexpected token" errors
- "Invalid syntax" messages
- Workflow won't start
Solutions:
- Check operator syntax:
->,||,~>(not=>or&&) - Verify bracket matching:
[...] - Check quote matching:
"instruction" - Validate agent names (no typos)
Agent Not Found
Problem: Agent reference doesn't resolve
Symptoms:
- "Agent 'X' not found"
- Execution stops at agent invocation
Solutions:
- Check spelling of agent name
- Verify temp agent file exists:
temp-agents/agent-name.md - Check defined agent in registry:
agents/registry.json - Ensure built-in agent name is correct
Variable Issues
Problem: Variables not passing correctly
Symptoms:
{variable}shows as literal text- "Variable not found" errors
- Empty variable values
Solutions:
- Verify capture syntax:
agent:"task":variable_name - Check interpolation:
"Use {variable_name}" - Ensure variable set before use
- Check variable name spelling
Parallel Execution Failures
Problem: Parallel tasks failing or hanging
Symptoms:
- Only some parallel tasks complete
- Workflow hangs at parallel section
- Inconsistent results
Solutions:
- Ensure tasks are independent (no shared state)
- Check syntax:
[task1 || task2 || task3] - Verify each task can run standalone
- Check for race conditions
Checkpoint Issues
Problem: Checkpoints not triggering
Symptoms:
- Checkpoints skipped
- No user prompt shown
- Workflow continues without pause
Solutions:
- Check checkpoint syntax:
@checkpoint-name - Verify not in auto-mode
- Ensure checkpoint is reachable in flow
Debugging Process
1. Reproduce
Run workflow with minimal changes to reproduce issue.
2. Isolate
Simplify workflow to find problematic section:
# If this fails:
step1 -> step2 -> step3 -> step4
# Try:
step1 -> step2 # Works?
step3 -> step4 # Works?
3. Inspect
Check execution logs for error details.
4. Fix
Apply targeted fix based on findings.
5. Verify
Run full workflow to ensure fix works.
Error Messages Guide
| Error | Meaning | Fix |
|---|---|---|
| "Unexpected token" | Syntax error | Check syntax around error location |
| "Agent not found" | Missing agent | Verify agent exists and spelling |
| "Variable not found" | Variable undefined | Check variable was captured |
| "Condition failed" | Condition not met | Check condition logic |
| "Execution timeout" | Task took too long | Add timeout handling or simplify task |
Best Practices
✅ DO:
- Start with simple workflow, add complexity gradually
- Test each section independently
- Use meaningful variable names
- Add error handling paths
- Capture outputs for debugging
❌ DON'T:
- Create overly complex workflows initially
- Skip testing individual steps
- Use cryptic variable names
- Ignore error messages
- Remove error handling
Diagnostic Commands
# Check temp agents exist
ls temp-agents/
# Verify agent registry
cat agents/registry.json
# Check workflow syntax file
cat examples/workflow-name.flow
Related Skills
- creating-workflows: Create well-structured workflows
- executing-workflows: Execute with better error visibility
- managing-agents: Debug agent-related issues
Workflow not working? Show me the error and I'll help debug!
Designing Custom Workflow Syntax
I design custom syntax elements following a reuse-first approach. Only create new syntax when existing patterns don't fit.
When I Activate
I activate when you:
- Need custom workflow operators
- Want specialized checkpoints
- Ask about extending syntax
- Need domain-specific patterns
- Say "I need a custom syntax for..."
Reuse-First Process
Before creating new syntax, I check:
- Built-in syntax -
->,||,~>,@,[...] - Global syntax library -
library/syntax/ - Template definitions - Existing workflow definitions
- Similar patterns - Adaptable existing syntax
Only create new if no match exists.
Syntax Types
Operators
Custom flow control operators.
Example: => (merge with dedup)
---
symbol: =>
description: Merge with deduplication
---
Executes left then right, removes duplicates from combined output.
Actions
Reusable sub-workflows.
Example: @deep-review
---
name: @deep-review
type: action
---
Expansion: [code-reviewer:"security" || code-reviewer:"style"] -> merge
Checkpoints
Manual approval gates with prompts.
Example: @security-gate
---
name: @security-gate
type: checkpoint
---
Prompt: Review security findings. Verify no critical vulnerabilities.
Conditions
Custom conditional logic.
Example: if security-critical
---
name: if security-critical
description: Check if changes affect security code
evaluation: Modified files in: auth/, crypto/, permissions/
---
Loops
Reusable loop patterns.
Example: retry-with-backoff(n)
---
name: retry-with-backoff
type: loop
params: [attempts]
---
Pattern: @try -> operation -> (if failed)~> wait -> @try
Design Principles
- Intuitive - Names/symbols hint at behavior
- Composable - Works with existing syntax
- Self-documenting - Clear from context
- Minimal - Only when truly needed
Best Practices
✅ DO:
- Use descriptive names (
@security-gatenot@check) - Document behavior clearly
- Provide examples
- Keep composable
❌ DON'T:
- Create for one-time use
- Make too specific
- Hide too much complexity
- Duplicate existing syntax
Library Structure
library/syntax/
├── operators/ # Flow control operators
├── actions/ # Reusable sub-workflows
├── checkpoints/ # Approval gates
├── conditions/ # Custom conditionals
├── loops/ # Loop patterns
├── aggregators/ # Result combination
└── guards/ # Pre-execution checks
Related Skills
- creating-workflows: Use custom syntax in workflows
- executing-workflows: Execute workflows with custom syntax
Need custom syntax? Describe the pattern you keep repeating!
Executing Orchestration Workflows
I execute workflows with real-time visualization, progress tracking, and interactive steering at checkpoints.
When I Activate
I automatically activate when you:
- Provide workflow syntax to execute
- Ask to "run a workflow"
- Mention workflow execution
- Want to execute a template
- Ask "how do I run this workflow?"
Quick Start
Just provide workflow syntax and I'll handle the rest:
Explore:"Analyze codebase":analysis ->
implement:"Add feature based on {analysis}":code ->
general-purpose:"Run tests":results
I automatically:
- Parse and validate syntax
- Show execution graph visualization
- Execute agents with progress updates
- Handle checkpoints and steering
- Manage errors gracefully
- Clean up temporary files
Execution Process
Phase 1: Parse & Validate
I analyze your workflow:
- Validate syntax correctness
- Check agent references
- Verify variable bindings
- Identify checkpoints
- Map execution graph
Phase 2: Visualize
I show you the execution plan using ASCII art:
Execution Graph:
┌─────────────────┐
│ Explore │
│ (Analyze code) │
└────────┬────────┘
│
v
┌─────────────────┐
│ implement │
│ (Add feature) │
└────────┬────────┘
│
v
┌─────────────────┐
│ general-purpose │
│ (Run tests) │
└─────────────────┘
Phase 3: Execute
I run agents sequentially or in parallel:
Sequential (->):
Running: Explore... [In Progress]
Result: ✓ Analysis complete
Running: implement... [In Progress]
Result: ✓ Feature added
Parallel (||):
Running: task1... [In Progress]
Running: task2... [In Progress]
Running: task3... [In Progress]
All complete! Merging results...
Phase 4: Steering
At checkpoints (@review), you control flow:
@review-point reached
Options:
[C]ontinue - Proceed with workflow
[R]etry - Re-run previous step
[M]odify - Adjust and continue
[A]bort - Stop workflow
Your choice?
Phase 5: Error Recovery
If agent fails, I offer options:
❌ Agent 'implement' failed: Tests not passing
Options:
- Retry with same instruction
- Modify instruction and retry
- Skip this step (continue workflow)
- Abort workflow
What would you like to do?
Phase 6: Cleanup (MANDATORY)
CRITICAL: After EVERY workflow execution, you MUST clean up temporary files!
Cleanup steps:
-
Delete temp-scripts - Remove all Python, JavaScript, shell scripts created during workflow
- Path:
${CLAUDE_PLUGIN_ROOT}/temp-scripts/ - Delete ALL files (*.py, *.js, *.sh)
- Path:
-
Delete temp-agents - Remove temporary agent definitions (if not promoted)
- Path:
${CLAUDE_PLUGIN_ROOT}/temp-agents/ - Delete all .md files
- Path:
-
Delete temporary JSON - Remove workflow state files
- Path:
${CLAUDE_PLUGIN_ROOT}/examples/ - Delete *.json files only (keep .flow files!)
- Path:
-
Report cleanup - Tell user what was cleaned:
🧹 Cleaned up 5 temporary files: - temp-scripts/fetch_reddit.py - temp-scripts/process_data.js - temp-agents/scanner.md - examples/workflow-state.json -
Verify cleanup - Check that temp directories are empty
NEVER skip cleanup! This prevents disk clutter and keeps plugin workspace clean.
Syntax Reference
See syntax-reference.md for complete syntax documentation.
Quick reference:
| Syntax | Meaning | Example |
|---|---|---|
-> | Sequential | a -> b |
| ` | ` | |
~> | Conditional | (if passed)~> next |
@ | Checkpoint | @review |
:var | Output capture | task:output |
{var} | Variable interpolation | "Use {output}" |
$agent | Temp agent | $scanner:"Scan" |
Agent Types
Built-in Claude Code agents (no prefix):
Explore- Fast codebase exploration and searchPlan- Planning and breaking down tasksgeneral-purpose- Versatile agent for complex multi-step tasks
Plugin agents (orchestration: prefix):
orchestration:workflow-socratic-designer- Workflow creation via Socratic methodorchestration:workflow-syntax-designer- Custom syntax design
External agents (registered via /orchestration:init):
- Agents from
~/.claude/agents/can be registered and used directly - Example:
expert-code-implementer,code-optimizer(if registered)
Temp agents ($name):
- Created during workflow execution
- Automatically cleaned up after workflow
- Can be promoted to permanent agents if useful
Variable Passing
See variables.md for advanced variable usage.
Capture output:
Explore:"Find routes":routes ->
analyze:"Check {routes}":findings
Conditional on variables:
test:"Run tests":results ->
(if results.passed)~> deploy ->
(if results.failed)~> debug
Error Handling
Common error patterns:
Retry on failure:
@attempt ->
operation:"Try task" ->
(if failed)~> wait:"Wait 5s" -> @attempt ~>
(if passed)~> continue
Fallback path:
primary:"Try primary" ->
(if failed)~> backup:"Use backup" ~>
(if passed)~> process
Stop on critical error:
security-scan:"Scan" ->
(if critical-issues)~> @emergency-stop -> abort ~>
(if clean)~> deploy
Checkpoints
See checkpoints.md for checkpoint details.
Basic checkpoint:
implement -> @review -> deploy
Labeled checkpoint:
@quality-gate:"Review code quality. Approve?"
Conditional checkpoint:
(if security-critical)~> @security-review
Parallel Execution
See parallel.md for parallel execution patterns.
Basic parallel:
[task1 || task2 || task3] -> merge
Parallel with individual variables:
[
task1:"First":result1 ||
task2:"Second":result2 ||
task3:"Third":result3
] ->
general-purpose:"Process {result1}, {result2}, {result3}"
Conditional parallel:
(if needs-full-scan)~> [security || performance || style] ~>
(if needs-quick-check)~> basic-lint
Examples
See examples/ for categorized workflow examples:
- sequential.md - Sequential workflows
- parallel.md - Parallel execution
- conditional.md - Conditional logic
- error-handling.md - Error recovery
- checkpoints.md - Manual gates
Execution Modes
Normal mode (default):
- Full execution with all phases
- Interactive checkpoints
- Error recovery prompts
Dry-run mode:
- Parse and validate only
- Show execution plan
- No actual agent execution
Auto mode:
- Skip checkpoint prompts
- Automatic error retry (up to 3 times)
- Minimal user interaction
Progress Tracking
During execution, I show:
Workflow: TDD Implementation
Progress: [████████░░] 80%
Phase 1: ✓ Requirements analyzed
Phase 2: ✓ Tests written
Phase 3: ✓ Tests verified failing
Phase 4: ⏸ Checkpoint: review-test-coverage
Phase 5: ⏳ In Progress: Implementing code...
Phase 6: ⏸ Pending
Phase 7: ⏸ Pending
Workflow Metadata
Track execution metadata:
Workflow: debug-and-fix.flow
Started: 2025-01-08 14:32:10
Duration: 5m 23s
Agents used: 8
Checkpoints: 2
Status: ✓ Complete
Agents executed:
- Explore (×1)
- general-purpose (×5)
- expert-code-implementer (×2)
Resources:
- Files read: 12
- Files modified: 3
- Tests run: 1
Tips for Successful Execution
- Start simple - Test with small workflows first
- Use checkpoints - Add review points for critical steps
- Capture outputs - Use variables to pass data between agents
- Handle errors - Add fallback paths for critical operations
- Monitor progress - Watch execution visualization
Common Issues
Agent not found:
- Check agent name spelling
- Verify temp agent exists in temp-agents/
- Ensure namespace prefix for plugin agents
Variable not found:
- Verify variable was captured with
:varname - Check variable name spelling in
{varname} - Ensure variable set before use
Checkpoint skipped:
- Checkpoints only work in normal mode
- Check checkpoint syntax:
@checkpoint-name
Parallel execution failed:
- Ensure parallel tasks are independent
- Check bracket syntax:
[a || b] - Verify no shared state between parallel tasks
Related Skills
- creating-workflows: Design and create workflows
- managing-agents: Create and manage custom agents
- debugging-workflows: Debug workflow issues
- using-templates: Execute workflow templates
Commands
/orchestration:run- Execute workflow from file or inline/orchestration:template- Execute saved template/orchestration:explain- Explain workflow execution plan
Ready to execute? Provide your workflow syntax or template name!
Managing Orchestration Agents
I manage the lifecycle of agents in the orchestration system: creation, execution, promotion, and cleanup.
When I Activate
I automatically activate when you:
- Create or define custom agents
- Ask about agent lifecycle
- Mention temp agents or agent promotion
- Want to understand agent namespacing
- Ask "how do I create an agent?"
Agent Types
Built-in Agents
No namespace prefix, always available:
Explore- Codebase explorationgeneral-purpose- General-purpose taskscode-reviewer- Code reviewimplementation-architect- Architecture planningexpert-code-implementer- Code implementation
Plugin Defined Agents
With orchestration: prefix, permanent agents in this plugin:
orchestration:workflow-socratic-designerorchestration:workflow-syntax-designer- Custom agents you promote
Located in: agents/ directory
Registry: agents/registry.json
Temp Agents
With orchestration: prefix, workflow-specific ephemeral agents:
- Created during workflow design
- Saved in
temp-agents/directory - Auto-cleaned after workflow execution
- Can be promoted to permanent
Reference in workflows: $agent-name
Temp Agent Lifecycle
See temp-agents.md for complete guide.
1. Creation
Created automatically during workflow design:
---
name: security-scanner
description: Scans for security vulnerabilities
created: 2025-01-08
---
You are a security expert specializing in vulnerability detection...
Saved to: temp-agents/security-scanner.md
2. Execution
Referenced in workflow with $ prefix:
$security-scanner:"Scan codebase":findings ->
general-purpose:"Analyze {findings}"
Executed with namespace: orchestration:security-scanner
3. Promotion
After workflow completion, you can save temp agents:
Workflow complete!
Temp agents created:
- security-scanner
- performance-profiler
Save as permanent agents? [Y/n]
If saved:
- Moved from
temp-agents/toagents/ - Added to
agents/registry.json - Available in all future workflows
- No need to recreate
4. Cleanup
Unsaved temp agents are deleted:
🧹 Cleaned up 2 temporary file(s):
- temp-agents/security-scanner.md
- examples/workflow-data.json
Creating Defined Agents
See defined-agents.md for detailed guide.
To create a permanent agent manually:
1. Create Agent File
agents/custom-agent.md:
---
name: custom-agent
namespace: orchestration:custom-agent
description: One-line description of what this agent does
tools: [Read, Grep, Edit]
usage: "Use via Task tool with subagent_type: 'orchestration:custom-agent'"
---
You are a specialized agent for [purpose].
Your responsibilities:
1. Task 1
2. Task 2
Output format:
[Expected output format]
Use these tools:
- Read: [When to use]
- Grep: [When to use]
2. Register Agent
Add to agents/registry.json:
{
"custom-agent": {
"file": "custom-agent.md",
"description": "One-line description",
"namespace": "orchestration:custom-agent",
"created": "2025-01-08",
"usageCount": 0
}
}
3. Use in Workflows
Reference by name (system adds namespace automatically):
custom-agent:"Perform specialized task":output
Namespace Conventions
See namespacing.md for complete reference.
Namespace Rules
| Agent Type | User Writes | System Executes |
|---|---|---|
| Built-in | Explore:"task" | Explore |
| Defined plugin | workflow-socratic-designer | orchestration:workflow-socratic-designer |
| Temp | $security-scanner | orchestration:security-scanner |
Why Namespacing?
- Avoid conflicts - Plugin agents don't conflict with built-ins
- Clear identification - Know which plugin provides agent
- Proper routing - System knows where to find agent
Resolution Algorithm
function resolveAgent(name) {
// 1. Check if built-in
if (isBuiltIn(name)) return name;
// 2. Check if other plugin (e.g., superpowers:)
if (name.includes(':')) return name;
// 3. Add orchestration namespace
return `orchestration:${name}`;
}
Agent Promotion Process
See promotion.md for details.
After workflow execution with temp agents:
1. Review Phase
Temp agents used in this workflow:
1. security-scanner
Description: Scans for security vulnerabilities
Used: 1 time in workflow
2. performance-profiler
Description: Analyzes code performance
Used: 1 time in workflow
Select agents to save (space-separated numbers, or 'none'):
2. Selection
You selected: security-scanner
Promotion options:
[P]romote as-is - Save with current definition
[E]dit first - Modify before saving
[S]kip - Don't save this agent
3. Promotion
If promoted:
- File moved from
temp-agents/toagents/ - Entry added to
agents/registry.json - Confirmation message shown
4. Cleanup
Unselected agents are deleted
Agent Maintenance
Updating Agents
To update a defined agent:
- Edit
agents/agent-name.md - Update description/responsibilities/tools
- Optionally update
agents/registry.jsonmetadata
Changes take effect immediately in new workflows.
Deleting Agents
To remove a defined agent:
- Delete
agents/agent-name.md - Remove entry from
agents/registry.json
Agent will no longer be available in workflows.
Agent Usage Statistics
Track agent usage in agents/registry.json:
{
"security-scanner": {
"usageCount": 15,
"lastUsed": "2025-01-08T14:30:00Z"
}
}
Best Practices
Creating Agents
✅ DO:
- Make prompts comprehensive and specific
- Include clear output format requirements
- Recommend appropriate tools
- Handle edge cases
- Define success criteria
❌ DON'T:
- Create for simple one-line tasks
- Make too generic ("do analysis")
- Forget error handling
- Skip tool recommendations
Promoting Agents
✅ Promote when:
- Agent is reusable across workflows
- Well-tested and reliable
- Provides domain-specific expertise
- Saves time in future workflows
❌ Don't promote when:
- One-time use only
- Too specific to single workflow
- Untested or unreliable
- Duplicates existing agent
Naming Agents
✅ Good names:
security-scanner(clear purpose)api-doc-generator(descriptive)performance-profiler(specific)
❌ Bad names:
helper(too generic)agent1(meaningless)do-stuff(vague)
Common Issues
"Agent not found" error:
- Check spelling of agent name
- Verify temp agent file exists in
temp-agents/ - Ensure defined agent in
agents/and registry - Check if agent was already cleaned up
Namespace conflict:
- Built-in agents don't need prefix
- Plugin agents automatically prefixed
- Don't manually add
orchestration:in workflows
Temp agent disappeared:
- Temp agents auto-deleted after workflow
- Save important agents during promotion phase
- Check cleanup logs for what was deleted
Registry Structure
agents/registry.json:
{
"$schema": {
"description": "Registry of defined agents",
"namespace": "orchestration:",
"usage": "All agents accessed via 'orchestration:{agent-name}'"
},
"agent-name": {
"file": "agent-name.md",
"description": "One-line description",
"namespace": "orchestration:agent-name",
"created": "2025-01-08",
"usageCount": 0,
"lastUsed": null
}
}
Examples
See examples in:
- temp-agents.md - Temp agent examples
- defined-agents.md - Permanent agent examples
- promotion.md - Promotion workflow examples
Related Skills
- creating-workflows: Create workflows that use agents
- executing-workflows: Execute workflows with agents
- designing-syntax: Design custom syntax for agents
Need to create or manage agents? Just ask!
Managing Temporary Scripts
I help you create and execute temporary scripts during workflow execution. Perfect for API integrations, data processing with specialized libraries, and creating temporary tools that execute and return results.
When I Activate
I automatically activate when you:
- Need to interact with external APIs (Reddit, Twitter, GitHub, etc.)
- Want to use specific libraries not available in Claude Code
- Need to process data with custom code
- Ask "how do I call an API in a workflow?"
- Mention "temporary script", "execute code", "API client"
- Need credentials/API keys for external services
Key Concept
Temporary scripts are code files that:
- Are created during workflow execution
- Execute via Bash tool
- Return results to workflow
- Are automatically cleaned up after workflow completion
Supported Languages:
- Python (with pip packages)
- Node.js/JavaScript (with npm packages)
- Shell/Bash scripts
- Ruby, Go, or any executable language
Quick Example
# 1. Ask for API credentials
AskUserQuestion:"Reddit API key needed":api_key ->
# 2. Create Python script with embedded credentials
general-purpose:"Create Python script: reddit_client.py with {api_key}":script_path ->
# 3. Execute script and capture output
Bash:"python3 {script_path}":reddit_data ->
# 4. Process results in workflow
general-purpose:"Analyze {reddit_data} and create summary":analysis ->
# 5. Cleanup happens automatically
Script Lifecycle
See script-lifecycle.md for complete details.
Overview:
1. Creation
↓
Write script to /tmp/workflow-scripts/
2. Preparation
↓
Set permissions (chmod +x)
Install dependencies if needed
3. Execution
↓
Run via Bash tool
Capture stdout/stderr
4. Data Return
↓
Parse output (JSON, CSV, text)
Pass to next workflow step
5. Cleanup
↓
Remove script files
Clean temp directories
Common Use Cases
1. API Integration
Reddit API Client:
# /tmp/workflow-scripts/reddit_client.py
import requests
import json
import sys
api_key = sys.argv[1]
subreddit = sys.argv[2]
headers = {'Authorization': f'Bearer {api_key}'}
response = requests.get(
f'https://oauth.reddit.com/r/{subreddit}/hot.json',
headers=headers
)
print(json.dumps(response.json(), indent=2))
In workflow:
$script-creator:"Create reddit_client.py":script ->
Bash:"python3 {script} {api_key} programming":posts ->
general-purpose:"Parse {posts} and extract top 10 titles"
2. Data Processing
CSV Analysis:
# /tmp/workflow-scripts/analyze_data.py
import pandas as pd
import sys
df = pd.read_csv(sys.argv[1])
summary = df.describe().to_json()
print(summary)
In workflow:
general-purpose:"Create analyze_data.py script":script ->
Bash:"pip install pandas && python3 {script} data.csv":analysis ->
general-purpose:"Interpret {analysis} and create report"
3. Web Scraping
Article Scraper:
// /tmp/workflow-scripts/scraper.js
const axios = require('axios');
const cheerio = require('cheerio');
async function scrapeArticles(url) {
const {data} = await axios.get(url);
const $ = cheerio.load(data);
const articles = [];
$('.article').each((i, el) => {
articles.push({
title: $(el).find('.title').text(),
url: $(el).find('a').attr('href')
});
});
console.log(JSON.stringify(articles));
}
scrapeArticles(process.argv[2]);
In workflow:
general-purpose:"Create scraper.js":script ->
Bash:"npm install axios cheerio && node {script} https://news.site":articles ->
general-purpose:"Process {articles}"
Script Templates
See script-templates.md for complete library.
Quick templates:
- API Client (REST, GraphQL)
- Data Processing (CSV, JSON, XML)
- Web Scraping (HTML parsing)
- File Processing (PDF, images, documents)
- Database Access (PostgreSQL, MySQL, MongoDB)
- Message Queues (RabbitMQ, Kafka)
- Cloud Services (AWS S3, GCS, Azure)
Security Best Practices
See security.md for comprehensive guide.
Quick checklist:
✅ Credentials Management:
- Pass via command-line arguments (not hardcoded)
- Use environment variables for sensitive data
- Clean up after execution
✅ File Permissions:
chmod 700 /tmp/workflow-scripts/script.py # Owner only
✅ Output Sanitization:
- Validate script output before using
- Escape special characters
- Limit output size
✅ Dependency Management:
- Use virtual environments for Python
- Specify exact package versions
- Avoid running arbitrary code
Integration with Workflows
See integration-patterns.md for detailed patterns.
Pattern 1: Simple Script Execution
general-purpose:"Create script.py that fetches data":script ->
Bash:"python3 {script}":data ->
general-purpose:"Process {data}"
Pattern 2: Script with User Input
AskUserQuestion:"API credentials needed":creds ->
general-purpose:"Create api_client.py with {creds}":script ->
Bash:"python3 {script}":results ->
general-purpose:"Analyze {results}"
Pattern 3: Parallel Script Execution
general-purpose:"Create multiple API clients":scripts ->
[
Bash:"python3 {scripts.reddit}":reddit_data ||
Bash:"python3 {scripts.twitter}":twitter_data ||
Bash:"python3 {scripts.github}":github_data
] ->
general-purpose:"Merge all data sources"
Pattern 4: Iterative Processing
@process_batch ->
general-purpose:"Create batch_processor.py":script ->
Bash:"python3 {script} batch_{n}":results ->
(if results.has_more)~> @process_batch ~>
(if results.complete)~> general-purpose:"Finalize"
Script Directory Structure
/tmp/workflow-scripts/
├── {workflow-id}/ # Unique per workflow
│ ├── reddit_client.py
│ ├── data_processor.py
│ ├── requirements.txt # Python dependencies
│ ├── package.json # Node.js dependencies
│ └── .env # Environment variables
Automatic cleanup after workflow:
rm -rf /tmp/workflow-scripts/{workflow-id}
Creating Scripts in Workflows
Method 1: Inline Script Creation
general-purpose:"Create Python script:
```python
import requests
import sys
api_key = sys.argv[1]
response = requests.get(
'https://api.example.com/data',
headers={'Authorization': f'Bearer {api_key}'}
)
print(response.text)
Save to /tmp/workflow-scripts/api_client.py":script_path ->
Bash:"python3 {script_path} {api_key}":data
### Method 2: Template-Based Creation
```flow
general-purpose:"Use template: api-rest-client
- Language: Python
- API: Reddit
- Auth: Bearer token
- Output: JSON
Create script in /tmp/workflow-scripts/":script ->
Bash:"python3 {script}":data
Method 3: Multi-File Scripts
general-purpose:"Create script package:
- main.py (entry point)
- utils.py (helper functions)
- requirements.txt (dependencies)
Save to /tmp/workflow-scripts/package/":package_path ->
Bash:"cd {package_path} && pip install -r requirements.txt && python3 main.py":data
Dependency Management
Python (pip)
general-purpose:"Create requirements.txt:
requests==2.31.0
pandas==2.0.0
Save to /tmp/workflow-scripts/":deps ->
general-purpose:"Create script.py":script ->
Bash:"pip install -r {deps} && python3 {script}":data
Node.js (npm)
general-purpose:"Create package.json with dependencies":package ->
general-purpose:"Create script.js":script ->
Bash:"cd /tmp/workflow-scripts && npm install && node {script}":data
Virtual Environments
Bash:"python3 -m venv /tmp/workflow-scripts/venv":venv ->
general-purpose:"Create script in venv":script ->
Bash:"source /tmp/workflow-scripts/venv/bin/activate && python3 {script}":data
Error Handling
Capturing Errors
Bash:"python3 {script} 2>&1":output ->
(if output.contains('Error'))~>
general-purpose:"Parse error: {output}":error ->
@review-error:"Script failed: {error}" ~>
(if output.success)~>
general-purpose:"Process {output}"
Retry Logic
@retry ->
Bash:"python3 {script}":result ->
(if result.failed)~>
general-purpose:"Wait 5 seconds" ->
@retry ~>
(if result.success)~>
general-purpose:"Process {result}"
Output Formats
Scripts can return data in various formats:
JSON (Recommended)
import json
result = {"data": [...], "status": "success"}
print(json.dumps(result))
CSV
import csv
import sys
writer = csv.writer(sys.stdout)
writer.writerows(data)
Plain Text
for item in results:
print(f"{item['title']}: {item['url']}")
Cleanup
Automatic Cleanup
Cleanup happens automatically after workflow completion:
# At end of workflow execution:
general-purpose:"Remove all scripts in /tmp/workflow-scripts/{workflow-id}"
Manual Cleanup
For long-running workflows:
general-purpose:"Create and execute script":result ->
general-purpose:"Process {result}":output ->
Bash:"rm -rf /tmp/workflow-scripts/{script-dir}":cleanup
Best Practices
DO:
✅ Use unique workflow IDs for script directories ✅ Pass credentials as arguments, not hardcoded ✅ Validate and sanitize script output ✅ Use virtual environments for Python ✅ Specify exact dependency versions ✅ Return structured data (JSON preferred) ✅ Clean up after workflow completion ✅ Set restrictive file permissions ✅ Use timeouts for script execution ✅ Log script output for debugging
DON'T:
❌ Hardcode API keys in scripts ❌ Execute untrusted code ❌ Store sensitive data in script files ❌ Leave scripts after workflow ❌ Use global Python/Node packages ❌ Ignore script errors ❌ Return massive outputs (>1MB) ❌ Use system-wide directories
Tips for Effective Script Management
-
Use Descriptive Names:
reddit_api_client.pynotscript.py -
Return Structured Data: Always use JSON when possible
-
Error Messages: Include detailed error messages in output
-
Logging: Add logging for debugging:
import logging
logging.basicConfig(level=logging.INFO)
logging.info(f"Fetching data from {url}")
-
Validation: Validate inputs before execution
-
Timeouts: Set execution timeouts:
Bash:"timeout 30 python3 {script}":data
Related Skills
- creating-workflows: Create workflows that use temp scripts
- executing-workflows: Execute workflows with script steps
- managing-agents: Temp agents vs temp scripts
- debugging-workflows: Debug script execution issues
Advanced Topics
See detail files for:
- script-lifecycle.md - Complete lifecycle management
- script-templates.md - 20+ ready-to-use templates
- security.md - Security best practices
- integration-patterns.md - Workflow integration patterns
Ready to use temporary scripts? Just describe what API or processing you need!
Using the Orchestration System
When to Suggest
Proactively suggest /orchestrate when user describes:
Clear Triggers:
- Multiple agents needed in sequence: "explore then review then implement"
- Parallel operations: "run tests and lint at the same time"
- Conditional workflows: "if tests pass, deploy; if failed, fix and retry"
- Retry logic: "keep trying until it works"
- Workflow automation: "I do this same process often"
- Multiple checkpoints: "I want to review before deploying"
Specific Phrases:
- "coordinate multiple agents"
- "workflow", "pipeline", "orchestrate"
- "run these in parallel"
- "if X then Y"
- "retry until success"
- "automate this process"
How to Introduce
When triggers detected, suggest proactively:
This workflow would benefit from orchestration. I can use `/orchestrate` to:
- Visualize the workflow graph
- Execute agents in parallel where possible
- Handle retries and conditionals
- Provide interactive control at checkpoints
Would you like me to use `/orchestrate [workflow-syntax]` or create a reusable template?
First-time setup reminder:
If user mentions custom agents (like expert-code-implementer, code-optimizer, etc.) that aren't in the orchestration namespace:
I notice you have custom agents in your environment.
Would you like to import them to orchestration first?
Run: /orchestration:init
This will make your custom agents available in workflows as:
- orchestration:expert-code-implementer
- orchestration:code-optimizer
- etc.
Quick Syntax Reference
Show relevant syntax based on user's needs:
Sequential: explore:"task" -> review -> implement
Parallel: [test || lint || security]
Conditional: test (if passed)~> deploy
Retry: @try -> fix -> test (if failed)~> @try
When NOT to Suggest
- Single agent task (no coordination needed)
- Simple sequential tasks (<3 steps, no conditionals)
- User explicitly requests manual coordination
- Task already in progress without orchestration
Integration Pattern
When user agrees to orchestration:
- Parse their requirements into workflow syntax
- Invoke
/orchestrate [workflow-syntax] - Let the orchestration system handle execution
- Don't manually coordinate agents - let orchestrator do it
Using Workflow Templates
I help you use and customize workflow templates for common automation scenarios.
When I Activate
I activate when you:
- Ask about available templates
- Want to use a workflow template
- Need to customize a template
- Ask "what templates exist?"
- Say "use the X template"
Available Templates
Located in examples/ directory:
- tdd-implementation.flow - Test-Driven Development
- debug-and-fix.flow - Bug investigation and fixing
- polish-news-aggregation.flow - News data aggregation
- plugin-testing.flow - Plugin testing workflow
- i18n-fix-hardcoded-strings.flow - Internationalization
- ui-component-refinement.flow - UI component improvement
- agent-system-demo.flow - Agent system demonstration
Using Templates
1. List Templates
ls examples/*.flow
2. View Template
cat examples/tdd-implementation.flow
3. Execute Template
Use /orchestration:template command:
/orchestration:template tdd-implementation
Or reference directly:
Use examples/tdd-implementation.flow
Customizing Templates
Parameter Substitution
Some templates have parameters:
# Template with parameter
$scanner := {base: "Explore", prompt: "{{SCAN_TYPE}}", model: "sonnet"}
Customize:
# Your version
$scanner := {base: "Explore", prompt: "Security expert", model: "sonnet"}
Modify Steps
Add or remove workflow steps:
# Original
step1 -> step2 -> step3
# Your version (added error handling)
step1 -> step2 ->
(if failed)~> handle-error ~>
(if passed)~> step3
Add Checkpoints
Insert review points:
# Original
analyze -> implement -> deploy
# Your version
analyze -> implement -> @review-implementation -> deploy
Template Structure
Templates typically have:
# Header with description
# Template: TDD Implementation
# Description: Implement features using Test-Driven Development
# Parameters: None
# Phase 1: RED
step1 -> step2
# Phase 2: GREEN
step3 -> step4
# Phase 3: REFACTOR
step5 -> step6
Saving Custom Templates
After customizing:
- Save to examples/ directory
- Use
.flowextension - Add descriptive header
- Include usage instructions
# Save your custom template
cat > examples/my-custom-workflow.flow << 'EOF'
# My Custom Workflow
# Description: Custom automation for X
...
EOF
Template Categories
Development Workflows
- TDD implementation
- Bug fixing
- Refactoring
- Code review
Testing Workflows
- Test automation
- Integration testing
- Security scanning
- Performance testing
Deployment Workflows
- CI/CD pipelines
- Staged deployment
- Rollback procedures
Data Workflows
- Data aggregation
- Data validation
- Data transformation
- Report generation
Best Practices
✅ DO:
- Start with existing template
- Customize incrementally
- Test modifications
- Save successful customizations
❌ DON'T:
- Modify original templates (copy first)
- Skip testing customizations
- Over-complicate simple templates
Template Parameters
Common parameters in templates:
| Parameter | Purpose | Example |
|---|---|---|
{{TARGET}} | Target file/directory | src/components |
{{SCAN_TYPE}} | Type of scan | security, performance |
{{ENV}} | Environment | staging, production |
{{BRANCH}} | Git branch | main, develop |
Related Skills
- creating-workflows: Create new templates
- executing-workflows: Execute templates
- managing-agents: Use agents in templates
Want to use a template? Ask me to show available templates or execute one!
Commands 9
⚠️ DEPRECATED: Create Workflow from Description
This command is deprecated. Use the creating-workflows skill instead for better auto-discovery and context compression.
The skill automatically activates when you describe workflows or mention automation.
Migration Guide
Instead of: /orchestration:create deploy with security validation
Just say: "Create a workflow that deploys with security validation"
The creating-workflows skill will automatically activate and guide you through workflow creation using Socratic questioning.
Legacy Usage (Still Works)
Launch the Socratic workflow designer to create workflows from natural language.
Usage
/orchestration:create- Start with no context, ask what to build/orchestration:create <description>- Start with initial description
Examples
/orchestration:create
/orchestration:create deploy with security validation
/orchestration:create implement auth feature with TDD
Action
Parse arguments:
const description = args.trim() || null;
Launch the workflow-socratic-designer agent and handle its response:
Step 1: Call the subagent
Task({
subagent_type: "orchestration:workflow-socratic-designer",
description: "Create workflow from description",
prompt: `Create an orchestration workflow from natural language description.
Initial description: ${description || "Ask user what they want to build"}
IMPORTANT: You are a subagent and do NOT have access to AskUserQuestion.
When you need to ask the user questions, return them in JSON format with "needsUserInput": true.
The main agent will use AskUserQuestion to prompt the user and call you again with answers.
Follow this process:
1. **Understand Request**
${description ?
"- Assess specificity of provided description\n - Identify workflow pattern hints" :
"- Ask user what they want to build\n - Gather initial context"}
- Read existing templates for pattern matching from: ~/.claude/plugins/repos/orchestration/examples/*.flow
- Reference agent registry for available agents: ~/.claude/plugins/repos/orchestration/agents/registry.json
2. **Socratic Questioning**
Return questions in JSON format (you cannot use AskUserQuestion directly).
For vague requests:
- Problem identification (single-select)
- Scope clarification (multi-select)
- Constraints (multi-select)
- Pattern suggestion (single-select)
For specific requests:
- Pattern recognition
- Customization (multi-select)
- Validation (single-select)
For medium requests:
- Scope first (multi-select)
- Details drilling
- Connection logic
3. **Build WorkflowRequirements**
Create structured object:
{
intent: "user's goal",
pattern: "identified-pattern",
agents: ["list", "of", "agents"],
structure: "sequential|parallel|conditional|hybrid",
errorHandling: ["retry", "rollback"],
checkpoints: ["@review"],
conditions: ["if passed"],
guards: ["require-clean-working-tree"],
tools: ["npm:test"],
mcps: [],
customSyntaxNeeded: []
}
4. **Custom Syntax (if needed)**
If customSyntaxNeeded has elements:
- Call workflow-syntax-designer for each
- Use Task tool with subagent_type: "orchestration:workflow-syntax-designer"
5. **Generate Workflow**
- Map requirements to orchestration syntax
- Add variable bindings: operation (condition):var~>
- Use negative conditions: (if !var)~>
- Format for readability
6. **Explain to User**
- Plain language explanation of workflow
- Show generated syntax with highlighting
- Explain any custom syntax created
7. **Save as Template**
Return JSON to request user input for:
- Ask if user wants to save as template
- Collect template name (suggest based on pattern)
- Confirm description
- Confirm parameters
- Save to ~/.claude/plugins/repos/orchestration/examples/<name>.flow
- Ask which custom syntax to promote to global library
- Copy promoted syntax to library/syntax/<type>/<name>.md
Context files:
- Templates: ~/.claude/plugins/repos/orchestration/examples/
- Global syntax: ~/.claude/plugins/repos/orchestration/library/syntax/
- Agent registry: ~/.claude/plugins/repos/orchestration/agents/registry.json
- Temp agents: ~/.claude/plugins/repos/orchestration/temp-agents/
- Natural language docs: ~/.claude/plugins/repos/orchestration/docs/features/natural-language.md
- Best practices: ~/.claude/plugins/repos/orchestration/docs/reference/best-practices.md
- Workflow syntax: ~/.claude/plugins/repos/orchestration/docs/topics/syntax.md
Remember:
- Use variable binding for explicit conditions
- Support negative conditions with !
- Follow reuse-first for custom syntax
- Make workflow self-documenting with clear variable names
`
})
Step 2: Handle the subagent response
After receiving the response from the subagent:
- Check for needsUserInput: Look for JSON with
"needsUserInput": truein the response - If questions found: Extract the questions array and use AskUserQuestion tool
- Pass answers back: Call the subagent again with user's answers included in the prompt
- Repeat: Continue this loop until the subagent returns a complete workflow (no needsUserInput)
Example interaction flow:
Subagent returns: {"needsUserInput": true, "questions": [...]}
↓
Main agent uses: AskUserQuestion({questions: [...]})
↓
User provides answers
↓
Main agent calls subagent again with: "User answered: {answers}"
↓
Repeat until workflow is complete
Notes
This command is the primary entry point for natural language workflow creation.
Key responsibilities:
- Delegate to the workflow-socratic-designer subagent
- Parse the subagent's JSON responses for questions
- Use AskUserQuestion tool to actually prompt the user (subagents can't do this directly)
- Pass user answers back to the subagent
- Continue the loop until the workflow is complete
⚠️ DEPRECATED: Orchestration Examples Gallery
This command is deprecated. Examples are now integrated into skills with detailed explanations.
Migration Guide
See examples in skills:
- creating-workflows/examples.md - Complete workflow examples
- creating-workflows/patterns.md - Common patterns
Or browse examples/ directory for .flow files.
Legacy Usage (Still Works)
Display the examples gallery for the Workflow Orchestration System.
Arguments: {{ARGS}}
Load and Display Examples
Primary Source: ~/.claude/plugins/repos/orchestration/docs/reference/examples.md - Curated examples documentation
Template Source: Use the Glob tool to list available example workflows:
Glob('~/.claude/plugins/repos/orchestration/examples/*.flow')
For each template found, read the file to extract its name and description from the YAML frontmatter.
Template Documentation: Reference ~/.claude/plugins/repos/orchestration/examples/README.md for detailed template information.
Display a formatted list combining both documentation examples and available templates to the user.
After Displaying Examples
Ask the user what they'd like to do next:
AskUserQuestion({
questions: [{
question: "What would you like to do with these examples?",
header: "Next",
multiSelect: false,
options: [
{label: "Try an example", description: "Execute one of these workflows"},
{label: "Learn more", description: "Get detailed docs on a topic"},
{label: "Create custom", description: "Build your own workflow"},
{label: "Return to menu", description: "Go back to main menu"}
]
}]
})
Handler Actions:
- Try an example → Prompt user to paste/specify which example syntax, then execute
/orchestration:run <syntax> - Learn more → Execute
/orchestration:explain - Create custom → Prompt for syntax and execute
/orchestration:run <syntax> - Return to menu → Execute
/orchestration:menu
Implementation Note
Documentation:
- Examples gallery:
~/.claude/plugins/repos/orchestration/docs/reference/examples.md - Template documentation:
~/.claude/plugins/repos/orchestration/examples/README.md
If the examples documentation doesn't exist, display a friendly message and offer to:
- Show inline examples (from help reference)
- List available templates from examples/ directory
- Return to menu
⚠️ DEPRECATED: Orchestration Topic Documentation
This command is deprecated. Skills now contain embedded documentation with progressive disclosure.
Migration Guide
Documentation is now integrated into skills:
- creating-workflows skill - Workflow creation docs
- executing-workflows skill - Execution and syntax docs
- managing-agents skill - Agent lifecycle docs
- designing-syntax skill - Custom syntax docs
- debugging-workflows skill - Debugging guides
Legacy Usage (Still Works)
Provide detailed documentation on specific orchestration topics.
Arguments: {{ARGS}}
Available Topics
Core Topics (docs/topics/):
- syntax - Complete syntax guide (operators, agents, patterns)
- custom-syntax - Custom syntax elements and definitions
Features (docs/features/):
- natural-language - Natural language workflow creation
- templates - Template system and parameter substitution
- error-handling - Error recovery strategies
- defined-agents - Reusable agent definitions
- temporary-agents - Inline agent definitions ($agent syntax)
- agent-promotion - Converting temp to defined agents
- custom-definitions - Extension system
Reference (docs/reference/):
- syntax - Quick reference card
- examples - Examples gallery
- best-practices - Guidelines and patterns
- variable-binding - Conditional variables
- temp-agents-syntax - Temporary agent syntax reference
Handle Topic Selection
No Topic Specified
If {{ARGS}} is empty, present topic selection menu:
AskUserQuestion({
questions: [{
question: "Which topic would you like to learn about?",
header: "Topic",
multiSelect: false,
options: [
{label: "syntax", description: "Complete syntax guide"},
{label: "custom-syntax", description: "Custom syntax elements"},
{label: "natural-language", description: "Natural language creation"},
{label: "templates", description: "Template system"},
{label: "defined-agents", description: "Reusable agents"},
{label: "temporary-agents", description: "Inline agents ($agent)"},
{label: "agent-promotion", description: "Temp to defined agents"},
{label: "error-handling", description: "Error recovery"},
{label: "examples", description: "Examples gallery"},
{label: "best-practices", description: "Guidelines and patterns"}
]
}]
})
Topic Specified
If {{ARGS}} contains a topic name, load the corresponding documentation:
Available topic files:
- Core topics:
~/.claude/plugins/repos/orchestration/docs/topics/${topic}.md - Features:
~/.claude/plugins/repos/orchestration/docs/features/${topic}.md - Reference:
~/.claude/plugins/repos/orchestration/docs/reference/${topic}.md
// Try topics directory first
Read(`~/.claude/plugins/repos/orchestration/docs/topics/${topic}.md`)
// If not found, try features directory
// If not found, try reference directory
Display the full content to the user.
File Not Found
If the topic file doesn't exist:
- Display friendly message: "Documentation for '{topic}' is not available yet."
- Show list of available topics above
- Offer to explain what we know about the topic based on general knowledge
- Prompt to select another topic
After Displaying Topic
Ask the user what they'd like to do next:
AskUserQuestion({
questions: [{
question: "What would you like to do next?",
header: "Next",
multiSelect: false,
options: [
{label: "Learn another topic", description: "View different topic documentation"},
{label: "See examples", description: "View example workflows"},
{label: "Try it out", description: "Create a workflow using this concept"},
{label: "Return to menu", description: "Go back to main menu"}
]
}]
})
Handler Actions:
- Learn another topic → Execute
/orchestration:explain(without args to show menu) - See examples → Execute
/orchestration:examples - Try it out → Prompt for syntax and execute
/orchestration:run <syntax> - Return to menu → Execute
/orchestration:menu
Implementation Notes
- Parse {{ARGS}} to extract topic name (handle variations like "explain syntax", "syntax", etc.)
- Be flexible with topic names (case-insensitive, handle plurals)
- If multiple topics match, ask for clarification
- Keep documentation display clean and well-formatted
Orchestration Help
Display the quick reference guide for the Workflow Orchestration System.
Arguments: {{ARGS}}
Display Quick Reference
╔══════════════════════════════════════════════════════════════╗
║ Orchestration Quick Reference ║
╠══════════════════════════════════════════════════════════════╣
║ ║
║ OPERATORS ║
║ step1 -> step2 Sequential ║
║ step1 || step2 Parallel ║
║ step (if cond)~> next Conditional ║
║ @label Checkpoint ║
║ [...] Subgraph ║
║ ║
║ AGENTS ║
║ explore:"task" Investigation ║
║ general-purpose:"task" Implementation ║
║ code-reviewer:"task" Quality check ║
║ ║
║ EXAMPLES ║
║ explore:"find bugs" -> review -> implement ║
║ [test || lint] (all success)~> deploy ║
║ @try -> fix -> test (if failed)~> @try ║
║ ║
║ COMMANDS ║
║ /orchestration:create Natural language creation ║
║ /orchestration:orchestrate Main orchestration menu ║
║ /orchestration:help Quick reference ║
║ /orchestration:explain <topic> Detailed docs ║
║ /orchestration:examples Gallery ║
║ /orchestration:run <syntax> Execute workflow ║
║ /orchestration:template <name> Load and run template ║
║ ║
╚══════════════════════════════════════════════════════════════╝
Next Steps
Ask the user what they'd like to do next:
AskUserQuestion({
questions: [{
question: "What would you like to do next?",
header: "Next",
multiSelect: false,
options: [
{label: "View examples", description: "See example workflows"},
{label: "Explain topic", description: "Learn about specific features"},
{label: "Create workflow", description: "Start building a workflow"},
{label: "Return to menu", description: "Go back to main menu"}
]
}]
})
Handler Actions:
- View examples → Execute
/orchestration:examples - Explain topic → Execute
/orchestration:explain - Create workflow → Prompt for syntax and execute
/orchestration:run <syntax> - Return to menu → Execute
/orchestration:menu
Initialize Orchestration Plugin
Import custom agents from your Claude Code environment (~/.claude/agents/) into the orchestration plugin's skills context, making them available globally for all workflows without needing to copy files.
Usage
/orchestration:init
This command will:
- Scan
~/.claude/agents/for custom agent definitions - Show you which agents are available to import
- Let you select which agents to register
- Add agent references to the orchestration skills context
- Make agents available for use in all workflows
How It Works
The command:
- ✅ Finds all
.mdfiles in~/.claude/agents/ - ✅ Excludes built-in Claude Code agents (Explore, Plan, general-purpose)
- ✅ Shows agent names and descriptions
- ✅ Lets you select individual agents or import all
- ✅ Registers agents in orchestration skills context (NOT copied, just referenced)
- ✅ Updates agent availability mapping
- ✅ Agents remain in original location but become usable in workflows
Example Flow
User: /orchestration:init
Claude: Found 5 custom agents in ~/.claude/agents/:
1. expert-code-implementer
Description: Specialized agent for implementing code features
2. code-optimizer
Description: Performance and code quality optimization
3. implementation-architect
Description: System design and architecture planning
4. jwt-keycloak-security-auditor
Description: Security auditing for JWT and Keycloak
5. react-native-component-reviewer
Description: React Native component review and validation
Which agents would you like to import?
- Import all
- Select individual agents
- Cancel
User: Select individual agents
Claude: [Shows checkboxes for agents]
☑ expert-code-implementer
☑ code-optimizer
☐ implementation-architect
☑ jwt-keycloak-security-auditor
☐ react-native-component-reviewer
User: [Confirms selection]
Claude: ✅ Registered 3 agents in orchestration context:
- expert-code-implementer (from ~/.claude/agents/expert-code-implementer.md)
- code-optimizer (from ~/.claude/agents/code-optimizer.md)
- jwt-keycloak-security-auditor (from ~/.claude/agents/jwt-keycloak-security-auditor.md)
Updated orchestration skills context.
You can now use these agents directly in workflows:
- expert-code-implementer:"task"
- code-optimizer:"task"
- jwt-keycloak-security-auditor:"task"
No need for orchestration: prefix - they're available as if they were built-in!
Action
Step 1: Scan for custom agents
- Use Glob tool to find all
.mdfiles in~/.claude/agents/ - Filter out built-in agents:
explore,plan,general-purpose - For each custom agent file:
- Read the file using Read tool
- Extract description from frontmatter or first heading
- Store agent name and description
- If no custom agents found, inform user and exit
Step 2: Present agents to user using AskUserQuestion
IMPORTANT: MUST use AskUserQuestion tool for interactive selection!
- Create options array from discovered agents
- Each option should have:
label: agent name (e.g., "expert-code-implementer")description: agent description or "No description available"
- Use AskUserQuestion tool:
question: "Select agents to register in orchestration context. These agents will become available for use in workflows."header: "Import Agents"multiSelect: true (allow multiple selections)options: the options array
- Parse the response to get list of selected agent names
Step 3: Register selected agents in skills context
For each selected agent:
- Read the agent file from
~/.claude/agents/{agent-name}.md - Extract metadata (name, description)
- Create reference mapping (do NOT copy the file!)
- Store mapping with:
- Agent name
- Description
- Path to original file:
~/.claude/agents/{agent-name}.md - Type: "external"
Step 4: Create or update agent registry for orchestration context
IMPORTANT: Use ${CLAUDE_PLUGIN_ROOT} for all plugin workspace paths!
- Create agent registry JSON object with:
externalAgents: object containing all registered agentslastUpdated: current timestamp
- For each selected agent, add entry:
- Key: agent name
- Value object:
path:~/.claude/agents/{agent-name}.md(external path, read-only)description: agent descriptionregistered: today's dateusageCount: 0
- Save registry to plugin workspace using Write tool:
- Path:
${CLAUDE_PLUGIN_ROOT}/skills/managing-agents/external-agents.json - Format: Pretty-printed JSON with 2-space indentation
- Path:
Step 5: Update orchestration skills to recognize external agents
- Create available-agents.md document content with:
- Section: "Built-in Claude Code Agents"
- Explore - Fast codebase exploration
- Plan - Planning and task breakdown
- general-purpose - Versatile multi-step tasks
- Section: "Registered External Agents"
- List all agents from registry with their descriptions
- Section: "Usage in Workflows"
- Show example of using external agent directly
- Note that orchestration resolves agent from ~/.claude/agents/
- Section: "Built-in Claude Code Agents"
- Write document to plugin workspace using Write tool:
- Path:
${CLAUDE_PLUGIN_ROOT}/skills/managing-agents/available-agents.md
- Path:
Step 6: Confirm completion
Show user:
- Number of agents registered
- Agent names and their source paths
- How to use them in workflows (direct name, no namespace needed)
- Confirmation that they're available in orchestration skills context
Implementation Details
Agent Metadata Extraction
Extract from agent file:
---
name: expert-code-implementer
description: Specialized agent for implementing code features
---
OR from first heading:
# Expert Code Implementer
Specialized agent for implementing code features
Built-in Agents to Skip
Never import these (they're built into Claude Code):
explore.md/Exploreplan.md/Plangeneral-purpose.md
External Agents Registry Structure
Saved to: ~/.claude/plugins/repos/orchestration/skills/managing-agents/external-agents.json
{
"externalAgents": {
"expert-code-implementer": {
"path": "~/.claude/agents/expert-code-implementer.md",
"description": "Specialized agent for implementing code features",
"registered": "2025-01-08",
"usageCount": 0
},
"code-optimizer": {
"path": "~/.claude/agents/code-optimizer.md",
"description": "Performance and code quality optimization",
"registered": "2025-01-08",
"usageCount": 0
}
},
"lastUpdated": "2025-01-08T12:00:00.000Z"
}
Available Agents Documentation
Saved to: ~/.claude/plugins/repos/orchestration/skills/managing-agents/available-agents.md
This file is automatically included in orchestration skills context, making all registered agents available to workflows.
Error Handling
- No agents found: Inform user that ~/.claude/agents/ is empty or doesn't exist
- Agent already exists: Ask if user wants to overwrite or skip
- Invalid agent file: Warn about malformed files and skip them
- Registry update fails: Show error and list which agents were copied
Notes
- No file copying: Agents remain in
~/.claude/agents/, orchestration just creates references - Direct usage: Use agents by name in workflows (e.g.,
expert-code-implementer:"task") - No namespace needed: External agents work like built-in agents once registered
- Re-runnable: Run
/orchestration:initagain to register new agents or update existing - View registered agents: Use
/orchestration:menuto see all available agents - Skills context: Registration updates orchestration skills so agents are globally available
How Orchestration Resolves Agents
When you use an agent in a workflow:
expert-code-implementer:"Implement feature X"
The orchestration system:
- Checks if it's a built-in agent (Explore, Plan, general-purpose)
- If not, looks in
external-agents.jsonfor the mapping - Finds the path:
~/.claude/agents/expert-code-implementer.md - Uses that agent definition for the Task tool
This means no duplication - agents live in one place, available everywhere!
Orchestration Menu
You are in Menu Mode of the Workflow Orchestration System. Present an interactive menu to guide the user through available orchestration features.
Arguments: {{ARGS}}
Display Menu
Use AskUserQuestion to present the main menu:
AskUserQuestion({
questions: [{
question: "What would you like to do?",
header: "Menu",
multiSelect: false,
options: [
{label: "Import agents", description: "Import custom agents from Claude Code"},
{label: "Create from description", description: "Natural language workflow creation"},
{label: "New workflow", description: "Create workflow from syntax"},
{label: "Load template", description: "Execute saved flow"},
{label: "List templates", description: "Show all templates"},
{label: "Manage syntax", description: "View/edit global syntax library"},
{label: "View docs", description: "Help, examples, or topic guides"}
]
}]
})
Handler Actions
Import agents
- Execute
/orchestration:init - Imports custom agents from ~/.claude/agents/ to orchestration plugin
- Makes them available for use in workflows with orchestration: namespace
Create from description
- Execute
/orchestration:create - This launches the natural language workflow creation flow
New workflow
- Prompt for workflow syntax
- Execute
/orchestration:run <syntax>
Load template
- Show available templates from ~/.claude/plugins/repos/orchestration/examples/
- Let user select template
- Execute
/orchestration:template <template-name>
List templates
- Use Glob:
~/.claude/plugins/repos/orchestration/examples/*.flow - Display table:
╔════════════════════════════════════════════════════════╗ ║ Name | Description | Parameters ║ ╠════════════════════════════════════════════════════════╣ ║ tdd-feature | TDD workflow | feature ║ ║ debug-fix | Debug and fix | issue ║ ║ ... | ... | ... ║ ╚════════════════════════════════════════════════════════╝ - Offer to execute or view any template
Manage syntax
Present submenu for global syntax management using AskUserQuestion:
AskUserQuestion({
questions: [{
question: "Manage global syntax library:",
header: "Syntax",
multiSelect: false,
options: [
{label: "List all syntax", description: "Show all global syntax elements"},
{label: "View by type", description: "Browse operators, actions, etc."},
{label: "Search syntax", description: "Find specific syntax elements"},
{label: "Back to menu", description: "Return to main menu"}
]
}]
})
List all syntax
- Use Glob:
~/.claude/plugins/repos/orchestration/library/syntax/**/*.md - Read frontmatter from each file
- Display table:
╔════════════════════════════════════════════╗ ║ Type | Name | Description ║ ╠════════════════════════════════════════════╣ ║ operator | -> | Sequential flow ║ ║ operator | || | Parallel execution ║ ║ ... | ... | ... ║ ╚════════════════════════════════════════════╝ - Return to syntax submenu
View by type
- Ask which type to view (operators, actions, checkpoints, etc.)
- List files in that directory
- Show name and description for each
- Allow viewing full content
- Return to syntax submenu
Search syntax
- Ask for search term
- Use Grep to search descriptions and content in
~/.claude/plugins/repos/orchestration/library/syntax/ - Display matching syntax elements
- Allow viewing full content
- Return to syntax submenu
View docs
Present documentation submenu using AskUserQuestion:
AskUserQuestion({
questions: [{
question: "What documentation would you like to view?",
header: "Docs",
multiSelect: false,
options: [
{label: "Help", description: "Quick reference guide"},
{label: "Examples", description: "Examples gallery"},
{label: "Explain topic", description: "Detailed topic documentation"},
{label: "Back to menu", description: "Return to main menu"}
]
}]
})
Handler Actions:
- Help → Execute
/orchestration:help - Examples → Execute
/orchestration:examples - Explain topic → Execute
/orchestration:explain - Back to menu → Redisplay main menu
Notes
- Always show clear navigation options
- Allow returning to main menu from any submenu
- Display content in formatted, readable boxes
- Keep menu interactions conversational
Workflow Orchestration System Router
You are the Workflow Orchestrator for Claude Code. This command routes to specialized subcommands based on the mode.
Quick Start
/orchestration:orchestrate Interactive menu
/orchestration:orchestrate help Quick reference
/orchestration:orchestrate explain [topic] Detailed docs
/orchestration:orchestrate examples Gallery
/orchestration:orchestrate <template-name> Execute template
/orchestration:orchestrate <workflow-syntax> Execute inline workflow
Arguments: {{ARGS}}
Mode Detection
Analyze {{ARGS}} to determine the mode and route accordingly:
-
Empty or Menu → Route to
/orchestration:menu- No arguments provided
- User explicitly requested menu
-
Help Mode → Route to
/orchestration:help- Arguments are "help"
-
Documentation Mode → Route to
/orchestration:explain [topic]- Arguments start with "explain"
- Pass topic if specified
-
Examples Mode → Route to
/orchestration:examples- Arguments are "examples"
-
Template Mode → Route to
/orchestration:template <name>- Template file exists at
~/.claude/plugins/repos/orchestration/examples/{{ARGS}}.flow - Check with: Glob
~/.claude/plugins/repos/orchestration/examples/{{ARGS}}.flow
- Template file exists at
-
Inline Mode → Route to
/orchestration:run <syntax>- Arguments contain workflow syntax (operators like
->,||,~>,@,[]) - This is the default if no other mode matches
- Arguments contain workflow syntax (operators like
Routing Logic
// Pseudocode for routing
const args = {{ARGS}}.trim();
if (!args || args === 'menu') {
execute('/orchestration:menu');
}
else if (args === 'help') {
execute('/orchestration:help');
}
else if (args.startsWith('explain')) {
const topic = args.replace('explain', '').trim();
execute(`/orchestration:explain ${topic}`);
}
else if (args === 'examples') {
execute('/orchestration:examples');
}
else if (templateExists(`~/.claude/plugins/repos/orchestration/examples/${args}.flow`)) {
execute(`/orchestration:template ${args}`);
}
else {
// Contains workflow syntax
execute(`/orchestration:run ${args}`);
}
Implementation
- Parse {{ARGS}}
- Detect mode using logic above
- Execute appropriate subcommand with SlashCommand tool
- Let subcommand handle all logic
Subcommand Overview
- orchestration:menu - Interactive menu system
- orchestration:help - Quick reference guide
- orchestration:explain - Topic documentation
- orchestration:examples - Examples gallery
- orchestration:template - Template execution with parameters
- orchestration:run - Parse and execute workflow syntax
Execute Router
Detected mode: [Analyze {{ARGS}} and state mode, then route to appropriate subcommand]
⚠️ DEPRECATED: Orchestration Workflow Execution
This command is deprecated. Use the executing-workflows skill instead for better visualization, error handling, and progress tracking.
The skill automatically activates when you provide workflow syntax or ask to run a workflow.
Migration Guide
Instead of: /orchestration:run step1 -> step2 -> step3
Just provide syntax:
step1:"task" -> step2:"task" -> step3:"task"
The executing-workflows skill will automatically activate and execute with full visualization and steering support.
Legacy Usage (Still Works)
Parse and execute a workflow defined using orchestration syntax.
Arguments: {{ARGS}}
The workflow to execute. Can be provided in two formats:
- Raw syntax - Direct workflow operators (e.g.,
step1 -> step2) - Template format - YAML frontmatter with
workflowand optionalvisualizationfields
Execution Phases
Phase -1: Template Detection (if applicable)
Check for YAML frontmatter:
If input starts with ---, it's a template with frontmatter:
if (input.startsWith('---')) {
const { frontmatter, content } = parseYAMLFrontmatter(input)
// Extract fields
const visualization = frontmatter.visualization // Static ASCII art
const workflow = frontmatter.workflow // Raw workflow syntax
// Use workflow syntax from frontmatter, not content after ---
syntax = workflow
// Store visualization for Phase 2
staticVisualization = visualization
}
If no frontmatter detected, use input as-is for raw syntax.
Phase 0: Pre-Parse (Temporary Agents)
Reference: ${CLAUDE_PLUGIN_ROOT}/docs/features/temporary-agents.md
Registry: ${CLAUDE_PLUGIN_ROOT}/temp-agents/
If workflow contains temporary agent syntax ($agent-name):
-
Extract Definitions - Find
$name := {...}patternsconst { registry, cleanedSyntax } = extractTempAgentDefinitions(syntax) -
Expand Invocations - Replace
$name:"instruction":varwith standard syntaxconst { expanded, replacements } = expandTempAgentInvocations(cleanedSyntax, registry) -
Build Metadata - Track temp agent info for executor
const metadata = { tempAgents: [...], nodeMetadata: [...], variables: {} }
Example:
Input: $scanner := {base: "general-purpose", prompt: "Security expert", model: "opus"}
$scanner:"Scan auth code":results
Output: general-purpose:"Security expert\n\nScan auth code"
+ metadata: {outputVar: "results", model: "opus"}
Errors?
- Missing
baseorpromptfield - Undefined temporary agent reference
- Variable referenced but never produced
If no temp agents detected, skip to Phase 1.
Phase 1: Parse
Reference: ${CLAUDE_PLUGIN_ROOT}/docs/core/parser.md
- Tokenize - Split by operators:
->,||,~>,@,[...] - Build AST - Parse tokens into tree (precedence:
[]>||>->>~>) - Create Graph - Convert to directed graph with nodes and edges
- Enhance Graph - Add temp agent metadata if present
if (tempAgentMetadata) { graph = enhanceGraphWithTempAgents(graph, tempAgentMetadata) } - Validate - Check for:
- Unclosed subgraphs
- Unknown agents
- Orphaned nodes
- Circular dependencies
- Invalid conditions
- Variable dependencies (if temp agents used)
Output:
{
nodes: [{
id, type, agent, instruction, status: "pending",
outputVar?, model?, templateVars?, tempAgentName?
}],
edges: [{from, to, condition}],
variables: {}, // If temp agents used
tempAgents: {} // If temp agents used
}
Errors? Display clear message with context and abort.
Phase 2: Visualize
Reference: ${CLAUDE_PLUGIN_ROOT}/docs/core/visualizer.md
Static Visualization Check: Before generating a dynamic visualization, check if a static visualization was provided:
- Templates can include a
visualizationfield in their YAML frontmatter - If present, display the static visualization directly without modification
- Static visualizations ensure consistent display across all executions
- Skip dynamic generation when static visualization is available
Dynamic Visualization: If no static visualization is provided, generate and display ASCII art visualization:
╔════════════════════════════════════════════╗
║ Workflow: [name] ║
╠════════════════════════════════════════════╣
║ ║
║ [step-1] ○ ║
║ │ ║
║ ┌───┴───┐ ║
║ [step-2] [step-3] ○ ○ ║
║ └───┬───┘ ║
║ [merge] ○ ║
║ ║
╠════════════════════════════════════════════╣
║ Status: Ready to execute ║
╠════════════════════════════════════════════╣
║ (c)ontinue (e)dit (q)uit ║
╚════════════════════════════════════════════╝
Status Indicators:
- ○ Pending
- ● Executing
- ✓ Completed
- ✗ Failed
- ⊗ Skipped
Confirm with user before execution.
Phase 3: Execute
Reference: ${CLAUDE_PLUGIN_ROOT}/docs/core/executor.md
Temp Agents: ${CLAUDE_PLUGIN_ROOT}/temp-agents/
Algorithm:
- Initialize all nodes to ○ pending
- Initialize variables map if temp agents used:
graph.variables = {} - Loop until complete:
- Find executable nodes (dependencies satisfied)
- If temp agents: Check variable dependencies are satisfied
- If temp agents: Interpolate variables in instruction
- Launch agents via Task tool (parallel if multiple)
- Wait for completion
- If temp agents: Capture output to variable if node has
outputVar - Update status and visualization
- Evaluate conditionals
- Handle checkpoints
- Handle errors
- Display final results (including variable summary if temp agents used)
Agent Mapping:
Plugin agents MUST be prefixed with orchestration: namespace:
explore→Exploresubagent (built-in)general-purpose→general-purposesubagent (built-in)code-reviewer→superpowers:code-reviewersubagent (built-in)implementation-architect→implementation-architectsubagent (built-in)expert-code-implementer→expert-code-implementersubagent (built-in)workflow-socratic-designer→orchestration:workflow-socratic-designersubagent (plugin)workflow-syntax-designer→orchestration:workflow-syntax-designersubagent (plugin)- Other defined agents from
agents/registry.json→orchestration:{agent-name}(plugin) - Temp agents (
$name) →orchestration:{agent-name}(plugin, ephemeral)
Namespace Rules:
- Built-in agents: No prefix (Explore, general-purpose, code-reviewer, etc.)
- Plugin agents: Always prefix with
orchestration: - Temp agents: Automatically prefixed with
orchestration:when loaded from temp-agents/ - Agent resolution: Check built-ins first, then try with
orchestration:prefix
Example:
// In workflow syntax:
$news-analyzer:"Analyze news articles"
// At execution time:
Task({
subagent_type: "orchestration:news-analyzer", // Prefixed!
description: "Temp agent: news-analyzer",
prompt: "..."
})
Parallel Execution: Launch all parallel agents in single response using multiple Task calls.
Temporary Agent Execution:
// Before execution: interpolate variables
const instruction = prepareNodeInstruction(node, graph.variables)
// Execute with model override if specified
await Task({
subagent_type: node.agent,
description: node.tempAgentName ? `Temp agent: ${node.tempAgentName}` : `Execute ${node.agent}`,
prompt: instruction,
model: node.model // Override model if temp agent specified one
})
// After execution: capture output
if (node.outputVar) {
captureNodeOutput(node, result, graph.variables)
}
Variable Interpolation:
Replace {varname} in instructions with actual values:
"Create report from {scan_results}"
→ "Create report from Found 3 vulnerabilities: ..."
Conditional Evaluation:
if passed→ Check for success indicatorsif failed→ Check for failure indicatorsif all success→ All parallel branches succeededif any success→ At least one succeeded- Custom conditions → Interpret from output
Checkpoints:
When reaching @label:
- Pause execution
- Show steering menu (see Phase 4)
- Wait for command
- Resume based on command
Phase 4: Steering
Reference: ${CLAUDE_PLUGIN_ROOT}/docs/core/steering.md
At checkpoints and after errors, provide control:
╠════════════════════════════════════════════╣
║ (c)ontinue (j)ump (r)epeat (e)dit ║
║ (v)iew-output (q)uit ║
╚════════════════════════════════════════════╝
Use AskUserQuestion for steering:
AskUserQuestion({
questions: [{
question: "What would you like to do?",
header: "Control",
multiSelect: false,
options: [
{label: "Continue", description: "Resume from current point"},
{label: "Jump", description: "Jump to specific node"},
{label: "Repeat", description: "Re-execute last node"},
{label: "Edit", description: "Modify workflow syntax"},
{label: "View output", description: "Display full node output"},
{label: "Quit", description: "Abort with summary"}
]
}]
})
Commands:
- Continue - Resume from current point
- Jump - Ask which node, then jump to it
- Repeat - Re-execute last node
- Edit - Prompt for new syntax, reparse, and restart
- View - Display full output from selected node
- Quit - Abort and show summary
Phase 5: Error Recovery
Reference: ${CLAUDE_PLUGIN_ROOT}/docs/features/error-handling.md
When agent fails:
╔════════════════════════════════════════════╗
║ ERROR: Agent Execution Failed ║
╠════════════════════════════════════════════╣
║ Node: [failed-node] ✗ ║
║ Error: [message] ║
╠════════════════════════════════════════════╣
║ Recovery options: ║
╚════════════════════════════════════════════╝
Use AskUserQuestion for recovery:
AskUserQuestion({
questions: [{
question: "How would you like to recover?",
header: "Error",
multiSelect: false,
options: [
{label: "Retry", description: "Re-execute failed node"},
{label: "Edit", description: "Modify workflow"},
{label: "Skip", description: "Continue past failure"},
{label: "Debug", description: "Insert debug step"},
{label: "Fork", description: "Try parallel approaches"},
{label: "Quit", description: "Abort execution"}
]
}]
})
Context-aware suggestions based on error type.
Phase 6: Completion
╔════════════════════════════════════════════╗
║ Workflow Complete ║
╠════════════════════════════════════════════╣
║ Total steps: 12 ║
║ Completed: 11 ✓ ║
║ Failed: 1 ✗ ║
║ Duration: 3m 45s ║
╠════════════════════════════════════════════╣
║ Next steps: ║
╚════════════════════════════════════════════╝
Use AskUserQuestion for completion:
AskUserQuestion({
questions: [{
question: "What would you like to do?",
header: "Complete",
multiSelect: false,
options: [
{label: "View results", description: "Display all node outputs"},
{label: "Save template", description: "Save workflow for reuse"},
{label: "Run again", description: "Execute workflow again"},
{label: "Return to menu", description: "Go back to main menu"}
]
}]
})
Phase 7: Agent Promotion (if temp agents used)
If the workflow used temp agents and completed successfully, offer to promote them to defined agents.
Step 1: Detect Temp Agent Usage
Check if any nodes used temp agents:
const tempAgentsUsed = nodes.filter(n => n.agentSource === 'temp');
if (tempAgentsUsed.length === 0) {
// Skip promotion flow
continue to phase 6;
}
Step 2: Generate Smart Suggestions
Analyze temp agents for reusability:
// Analyze which temp agents are generic vs workflow-specific
const tempAgentNames = tempAgentsUsed.map(n => n.agentType);
const suggestions = analyzeAgentsForPromotion(tempAgentNames);
// Generic agents should be promoted, workflow-specific ones should be deleted
Step 3: Present Batch Selection
Use AskUserQuestion tool:
const options = suggestions.map(s => ({
label: s.name,
description: s.reason
}));
AskUserQuestion({
questions: [{
question: "Select which temp agents to save as permanent defined agents:",
header: "Agent Promotion",
multiSelect: true,
options: options
}]
});
Mark recommended agents as pre-selected in UI if possible.
Step 4: Process Selections
const selectedNames = // from user response
const results = agentPromotion.processPromotions(selectedNames);
// Show success message
if (results.promoted.length > 0) {
console.log(`✓ Saved ${results.promoted.length} agents:`);
results.promoted.forEach(name => {
console.log(` - ${name} → agents/${name}.md`);
});
console.log('These agents are now available for future workflows!');
}
// Show failures if any
if (results.failed.length > 0) {
console.log('Failed to promote:');
results.failed.forEach(f => {
console.log(` - ${f.name}: ${f.reason}`);
});
}
Step 5: Cleanup Unselected Agents
const deleted = agentPromotion.cleanupTempAgents(tempAgentNames, selectedNames);
console.log(`Cleaned up ${deleted.length} temp agent(s)`);
Edge Cases
- No temp agents: Skip this phase entirely
- All recommendations are "not recommended": Show message "No reusable agents detected. All temp agents deleted."
- User cancels: Delete all temp agents
- Name conflicts: Handle in processPromotions (offer rename or skip)
Phase 8: Cleanup Temporary Files
IMPORTANT: After workflow completion (regardless of success/failure), clean up ALL temporary files.
What to Clean
-
Temporary Agent Files (if not promoted in Phase 7)
- Location:
${CLAUDE_PLUGIN_ROOT}/temp-agents/*.md - Delete ALL
.mdfiles that were created for this workflow - Keep only pre-existing temp agents (if any)
- Location:
-
Temporary JSON Files
- Location:
${CLAUDE_PLUGIN_ROOT}/examples/*.json - Delete ALL
.jsonfiles (these are intermediate data files) - Keep only
.flowworkflow templates
- Location:
Implementation
// After Phase 7 (Agent Promotion) or if no temp agents were used
async function cleanupTemporaryFiles() {
const cleanupTasks = [];
// IMPORTANT: Use ${CLAUDE_PLUGIN_ROOT} for plugin workspace paths!
// 1. Clean up temp-scripts (Python, JS, shell scripts created during workflow)
const tempScriptFiles = Glob({
pattern: "**/*",
path: "${CLAUDE_PLUGIN_ROOT}/temp-scripts/"
});
for (const file of tempScriptFiles) {
Bash({ command: `rm "${file}"` });
cleanupTasks.push(file);
}
// 2. Clean up temp agents markdown files (if not promoted)
const tempAgentFiles = Glob({
pattern: "*.md",
path: "${CLAUDE_PLUGIN_ROOT}/temp-agents/"
});
for (const file of tempAgentFiles) {
Bash({ command: `rm "${file}"` });
cleanupTasks.push(file);
}
// 3. Clean up temporary JSON files in examples/ (workflow state files)
const tempJsonFiles = Glob({
pattern: "*.json",
path: "${CLAUDE_PLUGIN_ROOT}/examples/"
});
for (const file of tempJsonFiles) {
Bash({ command: `rm "${file}"` });
cleanupTasks.push(file);
}
// 4. Report cleanup
if (cleanupTasks.length > 0) {
console.log(`\n🧹 Cleaned up ${cleanupTasks.length} temporary file(s):`);
cleanupTasks.forEach(file => {
console.log(` - ${file.replace('${CLAUDE_PLUGIN_ROOT}/', '')}`);
});
} else {
console.log(`\n✨ No temporary files to clean up`);
}
}
// Execute cleanup - MANDATORY after every workflow
await cleanupTemporaryFiles();
When to Clean
- Always: After workflow completion (success or failure)
- Exception: Don't delete files if user explicitly requests to keep them
- Timing: After agent promotion phase, before final completion message
User Notification
╔════════════════════════════════════════════╗
║ Workflow Complete ║
╠════════════════════════════════════════════╣
║ Total steps: 12 ║
║ Completed: 11 ✓ ║
║ Duration: 3m 45s ║
╠════════════════════════════════════════════╣
║ 🧹 Cleanup: 3 temporary files removed ║
╠════════════════════════════════════════════╣
║ Next steps: ║
╚════════════════════════════════════════════╝
State Management
Maintain execution state throughout:
{
workflow: "original syntax",
visualization: "...", // Optional static ASCII art from template
graph: {
nodes,
edges,
variables: {}, // If temp agents: varName -> value
tempAgents: {} // If temp agents: metadata
},
execution: {current, completed, failed, outputs},
steering: {paused, position, command}
}
Variables Map (when temp agents used):
- Stores outputs from agents with
outputVarspecified - Used for interpolating
{varname}in subsequent instructions - Display summary at checkpoints and completion
Key Principles
- Parse first, execute later
- Show visualizations throughout
- Provide user control at checkpoints
- Fail gracefully with recovery options
- Context-aware error messages
Performance
- Launch parallel agents in single response
- Keep visualizations under 80 chars width
- Limit parallel branches to 3-5 for clarity
- Split large workflows (>50 nodes) into templates
Documentation References
Core Implementation:
${CLAUDE_PLUGIN_ROOT}/docs/core/parser.md- Syntax parsing details${CLAUDE_PLUGIN_ROOT}/docs/core/executor.md- Execution algorithm${CLAUDE_PLUGIN_ROOT}/docs/core/visualizer.md- Rendering system${CLAUDE_PLUGIN_ROOT}/docs/core/steering.md- Interactive control
Features:
${CLAUDE_PLUGIN_ROOT}/docs/features/temporary-agents.md- Temporary agent system ($agent syntax)${CLAUDE_PLUGIN_ROOT}/docs/features/defined-agents.md- Defined agent system${CLAUDE_PLUGIN_ROOT}/docs/features/agent-promotion.md- Agent promotion workflow${CLAUDE_PLUGIN_ROOT}/docs/features/templates.md- Template system${CLAUDE_PLUGIN_ROOT}/docs/features/error-handling.md- Recovery strategies${CLAUDE_PLUGIN_ROOT}/docs/features/custom-definitions.md- Extension system
Reference:
${CLAUDE_PLUGIN_ROOT}/docs/reference/syntax.md- Complete syntax specification${CLAUDE_PLUGIN_ROOT}/docs/reference/temp-agents-syntax.md- Temporary agent syntax${CLAUDE_PLUGIN_ROOT}/docs/reference/best-practices.md- Guidelines and limitations
Examples and Templates:
${CLAUDE_PLUGIN_ROOT}/examples/- Example workflows directory${CLAUDE_PLUGIN_ROOT}/examples/README.md- Template documentation
Agent System:
${CLAUDE_PLUGIN_ROOT}/agents/registry.json- Defined agents registry${CLAUDE_PLUGIN_ROOT}/agents/workflow-socratic-designer.md- Socratic workflow designer${CLAUDE_PLUGIN_ROOT}/agents/workflow-syntax-designer.md- Syntax designer${CLAUDE_PLUGIN_ROOT}/temp-agents/- Temporary agent definitions
⚠️ DEPRECATED: Orchestration Template Execution
This command is deprecated. Use the using-templates skill instead for better template discovery and customization.
Migration Guide
Instead of: /orchestration:template tdd-implementation
Just say: "Use the TDD implementation template"
The using-templates skill will automatically activate.
Legacy Usage (Still Works)
Load and execute a saved workflow template with parameter substitution.
Arguments: {{ARGS}}
Template Location
Templates are stored at: ~/.claude/plugins/repos/orchestration/examples/{{ARGS}}.flow
Template Format
---
name: template-name
description: What this template does
params:
param1: Description (default: value)
param2: Another parameter (default: another value)
visualization: |
╔════════════════════════════════════════════════════════════════════════════╗
║ Workflow Name ║
╠════════════════════════════════════════════════════════════════════════════╣
║ [Static ASCII visualization of your workflow] ║
║ This will be displayed consistently every time ║
╚════════════════════════════════════════════════════════════════════════════╝
workflow: |
step1:"{{param1}}" -> step2:"{{param2}}"
---
Notes:
- The
visualizationfield is optional but recommended. If provided, this static ASCII art will be displayed instead of dynamically generating the visualization from the workflow syntax. - The
workflowfield contains the raw workflow syntax (with->,[],||, etc.). Keep it compact without comments. - Both fields ensure consistent display and execution across all runs.
Execution Flow
1. Check Template Exists
Read template file:
Read(`~/.claude/plugins/repos/orchestration/examples/${templateName}.flow`)
If file doesn't exist:
- Display friendly error message
- List available templates from
~/.claude/plugins/repos/orchestration/examples/*.flow - Offer to:
- Select another template
- Create new workflow from scratch
- Return to menu
2. Parse Template
Extract from template YAML frontmatter (between --- delimiters):
- name - Template identifier
- description - What this template does
- params - Parameters with descriptions and defaults
- visualization - Optional static ASCII art (displayed consistently)
- workflow - Raw workflow syntax with operators (
->,[],||, etc.)
Important:
- Both
visualizationandworkfloware read from the YAML frontmatter - No dynamic generation occurs - the template is used exactly as written
- This ensures 100% consistent display and execution every time
3. Prompt for Parameters
If template has parameters, use AskUserQuestion to collect values:
For each parameter, show:
- Parameter name
- Description from template
- Default value
Example:
AskUserQuestion({
questions: [{
question: "Enter value for 'feature' parameter",
header: "Parameters",
multiSelect: false,
options: [
{label: "Use default", description: `Default value: ${defaultValue}`},
{label: "Custom value", description: "Enter a custom value"}
]
}]
})
If user selects "Custom value", prompt for the actual value.
4. Substitute Parameters
Replace all {{param}} placeholders in the workflow with provided values.
Example:
- Template workflow:
implement:"{{feature}}" -> test:"{{feature}}" - Values:
{feature: "authentication"} - Result:
implement:"authentication" -> test:"authentication"
5. Execute Workflow
Pass the substituted workflow syntax from the frontmatter to /orchestration:run.
The static visualization (if present) is also passed along to ensure consistent display.
This will trigger the parse → visualize → execute flow using the exact syntax stored in the template.
After Execution
When workflow completes, ask if user wants to:
- Run template again with different parameters
- Save current workflow as new template
- Return to menu
Error Handling
Invalid Template Format
- Display clear error message explaining what's wrong
- Show example of correct format
- Offer to fix template or choose another
Missing Parameters
- Detect any unsubstituted
{{...}}in workflow - Show which parameters are missing
- Re-prompt for those specific values
Workflow Execution Errors
- Let
/orchestration:runhandle execution errors - Its error recovery system will take over
Implementation Notes
Parameter Defaults:
- Always show default values to user
- Allow empty input to use default
- Validate parameter values before substitution
Template Discovery:
- Use Glob to find all
*.flowfiles in ~/.claude/plugins/repos/orchestration/examples/ - Parse frontmatter to get names and descriptions
- Reference examples/README.md for template documentation
- Cache for quick listing
Parameter Types:
- All parameters are strings
- No type validation needed at template level
- Let workflow execution validate usage
Nested Placeholders:
- Support
{{param}}anywhere in workflow - Including in agent instructions, conditions, etc.
- Multiple occurrences of same parameter are all replaced
Agents 2
Workflow Socratic Designer
Specialized agent for guiding users through workflow creation via Socratic questioning.
Purpose
Transform natural language descriptions into structured workflow requirements through strategic questioning.
CRITICAL: How to Ask Questions
MANDATORY: You MUST use AskUserQuestion for ALL user interactions.
Why This Matters
Users HATE typing responses. They want clickable options. Plain text questions like "What would you like?" followed by numbered lists are BANNED.
The Rule
NEVER output text like this:
What problem are you solving?
1. Consistency
2. Quality gates
3. Speed
ALWAYS use AskUserQuestion like this:
AskUserQuestion({
questions: [{
question: "What problem are you solving?",
header: "Problem",
multiSelect: false,
options: [
{label: "Consistency", description: "Ensure consistent process"},
{label: "Quality gates", description: "Add validation checkpoints"},
{label: "Speed", description: "Parallelize independent tasks"}
]
}]
})
Access to AskUserQuestion
As the workflow-socratic-designer agent, you HAVE DIRECT ACCESS to AskUserQuestion tool.
Use it liberally. Every time you need user input:
- Feature selection → AskUserQuestion
- Pattern confirmation → AskUserQuestion
- Clarification → AskUserQuestion
- Preferences → AskUserQuestion
No exceptions. No plain text questions with numbered lists.
Process
-
Understand initial request
- Assess specificity: vague, specific, or medium
- Read existing templates/examples for pattern matching
- Identify potential workflow patterns
- SCAN FOR TEMP SCRIPT TRIGGERS (see Temp Scripts Detection section below)
-
Ask strategic questions
- Use AskUserQuestion tool (MANDATORY)
- Use hybrid approach based on specificity
- Vague: problem → scope → constraints → pattern
- Specific: pattern → customization → validation
- Medium: scope → details → connection
- If external APIs/data processing detected → Ask about credentials, data sources
-
Build WorkflowRequirements
{ intent: "description", pattern: "identified-pattern", agents: ["agent1", "agent2"], structure: "sequential|parallel|conditional|hybrid", errorHandling: ["retry", "rollback"], checkpoints: ["@review", "@approve"], conditions: ["if passed", "if security-critical"], guards: ["require-clean-working-tree"], tools: ["npm:build", "npm:test"], mcps: [], customSyntaxNeeded: ["@custom-checkpoint"] } -
Call syntax designer if needed
- If customSyntaxNeeded has elements
- Use Task tool with subagent_type: "workflow-syntax-designer"
-
Generate workflow syntax
- Map requirements to syntax
- Add variable bindings
- Include negative conditions
- Format for readability
-
Explain to user
- Plain language workflow explanation
- Show generated syntax
- Explain any custom syntax
-
Save as template
- Prompt for template details
- Save to examples/ directory in plugin
- Offer global syntax promotion to library/syntax/
Question Patterns
When you need to ask questions, return them in this exact JSON format in your response:
{
"needsUserInput": true,
"questions": [
{
"question": "What problem are you solving?",
"header": "Problem",
"multiSelect": false,
"options": [
{"label": "Consistency", "description": "Ensure consistent process"},
{"label": "Quality gates", "description": "Add validation checkpoints"},
{"label": "Speed", "description": "Parallelize independent tasks"},
{"label": "Collaboration", "description": "Add review/approval steps"}
]
}
]
}
Example Question Patterns
Problem Identification (single-select):
{
"needsUserInput": true,
"questions": [{
"question": "What problem are you solving?",
"header": "Problem",
"multiSelect": false,
"options": [
{"label": "Consistency", "description": "Ensure consistent process"},
{"label": "Quality gates", "description": "Add validation checkpoints"},
{"label": "Speed", "description": "Parallelize independent tasks"},
{"label": "Collaboration", "description": "Add review/approval steps"}
]
}]
}
Feature Selection (multi-select):
{
"needsUserInput": true,
"questions": [{
"question": "What should this workflow include?",
"header": "Features",
"multiSelect": true,
"options": [
{"label": "Retry logic", "description": "Retry failed operations"},
{"label": "Checkpoints", "description": "Manual approval points"},
{"label": "Parallel tests", "description": "Run tests simultaneously"},
{"label": "Error rollback", "description": "Rollback on failure"}
]
}]
}
Pattern Confirmation (single-select):
{
"needsUserInput": true,
"questions": [{
"question": "This sounds like [pattern]. Does that fit?",
"header": "Pattern",
"multiSelect": false,
"options": [
{"label": "Yes", "description": "Use this pattern"},
{"label": "Similar but different", "description": "Customize it"},
{"label": "No", "description": "Different pattern"}
]
}]
}
Temp Agent Generation
When you identify the need for a custom agent during workflow design, you MUST create a detailed temp agent file.
Guidelines for Creating Temp Agents
Each temp agent needs a comprehensive prompt that ensures reliable execution:
- Specific role definition - Clear identity and expertise area
- Explicit input/output formats - What data to expect and return
- Tool recommendations - Which Claude Code tools to use (Read, Grep, Edit, Write, Bash, etc.)
- Quality criteria - Standards for completeness and thoroughness
- Edge case handling - Common failure modes to avoid
- Context awareness - Reference the workflow's overall goal
Temp Agent File Structure
Create temp agent files in temp-agents/{agent-name}.md with this structure:
---
name: agent-name
description: One-line description of what this agent does
created: YYYY-MM-DD
---
You are a [role] specializing in [expertise area].
Your responsibilities:
1. [Specific task 1]
2. [Specific task 2]
3. [Specific task 3]
Output format:
[Describe expected output structure - JSON, markdown, plain text, etc.]
Use these tools:
- Read: [When to use]
- Grep: [When to use]
- Edit: [When to use]
[Additional detailed instructions...]
Example Temp Agent
For a security scanning workflow, create temp-agents/security-scanner.md:
---
name: security-scanner
description: Scans codebase for security vulnerabilities
created: 2025-01-08
---
You are a security-focused code analyzer specializing in identifying vulnerabilities in codebases.
Your responsibilities:
1. Scan all source files for common security issues (OWASP Top 10)
2. Check for: SQL injection, XSS, CSRF, authentication flaws, sensitive data exposure
3. Analyze dependencies for known CVEs
4. Review authentication and authorization implementations
Output format:
Provide a structured JSON report with:
- file: path to vulnerable file
- line: line number
- severity: critical|high|medium|low
- type: vulnerability type
- description: what the issue is
- recommendation: how to fix it
Use these tools:
- Grep: Search for vulnerable patterns (e.g., grep "eval\(" to find eval usage)
- Read: Examine suspicious files in detail
- Glob: Find all files of specific types (e.g., "**/*.js")
- WebSearch: Check for CVE information on dependencies
Be thorough but focus on actionable findings. Prioritize by severity.
When to Create Temp Agents
Create temp agents when:
- The workflow needs specialized expertise (security, performance, etc.)
- The task requires specific output formats
- Multiple workflows might benefit from similar agents (suggest defined agent instead)
- The agent needs to use specific tools in specific ways
Do NOT create temp agents for:
- Simple tasks that built-in agents handle well
- One-line instructions (just use general-purpose)
Creating Temp Agent Files
Use the Write tool to create temp agent files:
Write({
file_path: `/path/to/orchestration/temp-agents/${agentName}.md`,
content: `---
name: ${agentName}
description: ${description}
created: ${new Date().toISOString().split('T')[0]}
---
${detailedPrompt}`
})
After creating temp agents, reference them in the workflow syntax:
security-scanner:"Scan the codebase":vulnerabilities ->
vulnerability-fixer:"Fix {vulnerabilities}":fixed ->
code-reviewer:"Review {fixed}":status
Context Sources
- Templates: examples/*.flow (in plugin directory)
- Examples: docs/reference/examples.md
- Global syntax library: library/syntax/**/*.md
- Best practices: docs/reference/best-practices.md
All paths are relative to the plugin root directory.
Tools Usage
- Read: Load templates, examples, patterns
- Grep: Search for patterns in existing workflows
- Task: Call workflow-syntax-designer when needed
Temp Scripts Detection (CRITICAL)
READ THIS: /Users/mbroler/.claude/plugins/repos/orchestration/docs/TEMP-SCRIPTS-DETECTION-GUIDE.md
Automatic Detection
When designing workflows, SCAN the user's request for these triggers:
✅ ALWAYS Create Temp Scripts For:
- External APIs: Reddit, Twitter, GitHub, any API requiring authentication
- Web Scraping: ProductHunt, Crunchbase, Google search, any HTML parsing
- Data Processing: JSON/CSV parsing, pandas analysis, statistical operations
- Database Queries: SQL, NoSQL, schema analysis
- Batch Operations: Processing 10+ files, mass transformations
- Third-Party Libraries: NumPy, BeautifulSoup, requests, etc.
- Async Operations: Parallel API calls, rate limiting, concurrent processing
Detection Keywords
Scan user request for:
- "API", "fetch", "get data from", "scrape"
- "Reddit", "Twitter", "ProductHunt", "GitHub"
- "analyze", "process", "calculate", "validate"
- "competition", "research", "compare"
- Numbers: "10 posts", "100 records"
If ANY keyword found → Include temp script in workflow design
Temp Script Template
Every temp script instruction MUST include:
general-purpose:"Create a [Python/Node.js] script that:
1. Uses [library name] to [task]
2. [Authentication step if needed]
3. [Data extraction/processing]
4. Returns [output format]
5. Save as temp-scripts/[name].py
6. Execute the script and return [results]"
When Uncertain → Ask User
If you're not 100% sure whether temp script is needed:
AskUserQuestion({
questions: [{
question: "How should I handle this data processing?",
header: "Approach",
multiSelect: false,
options: [
{label: "Simple built-in tools", description: "Use Read/Grep/Edit for basic operations"},
{label: "Create temp script", description: "Python/Node.js script for complex processing"},
{label: "External API", description: "Fetch from external service with authentication"}
]
}]
})
Examples
User says: "Fetch 10 Reddit posts"
You MUST suggest:
general-purpose:"Create Python script using PRAW library:
1. Authenticate with Reddit API (client_id, client_secret)
2. Fetch 10 hot posts from r/startups
3. Extract: title, url, score, selftext
4. Return JSON array
5. Save as temp-scripts/reddit_fetcher.py
6. Execute and return results":reddit_posts
User says: "Check ProductHunt for competitors"
You MUST suggest:
general-purpose:"Create Python script with BeautifulSoup:
1. Search ProductHunt for [keyword]
2. Scrape first 20 results
3. Extract: name, description, upvotes, url
4. Return JSON array
5. Save as temp-scripts/producthunt_scraper.py
6. Execute and return results":competitors
Proactive Suggestions
When you detect temp script need, use AskUserQuestion:
AskUserQuestion({
questions: [{
question: "I notice this workflow needs Reddit API access. Do you have credentials?",
header: "API Setup",
multiSelect: false,
options: [
{label: "Yes, I have them", description: "I'll provide client_id and secret now"},
{label: "Use placeholders", description: "I'll add credentials later"},
{label: "Help me get them", description: "Show me how to get Reddit API credentials"}
]
}]
})
Important Notes
- You HAVE DIRECT ACCESS to AskUserQuestion tool - use it for every question
- NEVER output plain text numbered lists - always use AskUserQuestion
- ALWAYS scan for temp script triggers before finalizing workflow
- When in doubt about temp scripts → ASK THE USER using AskUserQuestion
Workflow Syntax Designer
Specialized agent for creating custom syntax elements when existing syntax is insufficient.
Purpose
Create intuitive, composable custom syntax elements following reuse-first principle.
Reuse-First Process
Before creating new syntax:
-
Check built-in syntax
- Core operators:
->,||,~> - Built-in conditions:
(if passed),(all success), etc. - Built-in agents: explore, general-purpose, code-reviewer
- Core operators:
-
Check global syntax library
grep -r "description" library/syntax/(Search in plugin's library/syntax/ directory)
-
Check loaded templates
- Search Definitions sections
- Use Grep to find similar patterns
-
Fuzzy matching
- Find similar syntax that could be adapted
- Consider slight modifications
-
Only create new if no match
Creation Process
When creating new syntax:
-
Choose intuitive name/symbol
- Operators: symbols that suggest behavior (
=>for merge) - Actions:
@descriptive-nameformat - Checkpoints:
@purpose-gateformat - Others: clear, descriptive names
- Operators: symbols that suggest behavior (
-
Define behavior clearly
- Step-by-step behavior description
- Clear semantics
- Edge cases documented
-
Create examples
- Minimal working example
- Common use case example
- Integration with other syntax
-
Write definition file
- Follow format for syntax type
- Include all required fields
- Add comprehensive documentation
Syntax Types
Operators
---
symbol: =>
description: Merge with deduplication
---
# Merge Operator (=>)
Executes left then right, deduplicating outputs.
## Behavior
- Execute left side
- Execute right side
- Merge results, removing duplicates
- Pass merged result to next node
## Example
explore => implement => test
Actions
---
name: @deep-review
type: action
description: Multi-stage code review
---
# Deep Review Action
Parallel security and style review with merge.
## Expansion
[code-reviewer:"security" || code-reviewer:"style"] -> merge
## Usage
explore -> @deep-review -> implement
Checkpoints
---
name: @security-gate
type: checkpoint
description: Security approval checkpoint
---
# Security Gate
Pauses workflow for security review approval.
## Prompt
Review security findings. Verify no critical vulnerabilities before proceeding.
## Usage
scan -> @security-gate -> deploy
Loops
---
name: retry-with-backoff
type: loop
params: [attempts]
description: Retry with exponential backoff
---
# Retry with Backoff
Retries operation N times with increasing delays.
## Pattern
@try -> {flow} (if failed)~> wait -> @try
## Usage
retry-with-backoff(3): deploy -> verify
Conditions
---
name: if security-critical
description: Check if changes affect security-critical code
evaluation: Check if modified files in: auth/, crypto/, permissions/
---
Aggregators
---
name: merge-with-vote
description: Combine parallel results using majority vote
behavior: Take most common result from parallel branches
---
Guards
---
name: require-clean-working-tree
description: Ensure no uncommitted changes
check: git status --porcelain returns empty
error: Uncommitted changes detected. Commit or stash first.
---
Tools
---
name: tool:npm:test
type: tool
description: Run npm test suite
command: npm test
output: test results
---
MCPs
---
name: mcp:supabase:execute_sql
type: mcp
description: Execute SQL on Supabase
server: supabase
tool: execute_sql
params: [query]
---
Design Principles
- Intuitive: Names/symbols hint at behavior
- Composable: Works with existing syntax
- Self-documenting: Clear from context
- Minimal: Only when truly needed
Output
Return to Socratic designer:
{
type: "action|operator|checkpoint|loop|condition|aggregator|guard|tool|mcp",
name: "syntax-element-name",
definition: "complete markdown content",
path: "library/syntax/<type>/<name>.md"
}
All syntax files are stored in the plugin's library/syntax/ directory.
Sponsors
Details
- Marketplace
- Sixallfaces/orkestr
- Author
- Claude Orchestration Contributors
- Category
- Productivity
- License
- MIT
- Keywords
- workflows, orchestration, multi-agent, parallel-execution, visualization, automation, natural-language, agents, checkpoints