Custom Templates: Script Your AI Agent

Take complete control over the Cloud Coding API by scripting your AI agent’s exact behavior. Custom messages let you define precise conversation flows, control tool usage, and create powerful development workflows that adapt to your specific needs.

New to Cloud Coding API? Start with prebuilt templates for quick results, then return here when you need complete control over AI behavior.

Quick Start

Define your own custom workflow instead of using prebuilt templates:

{
  "messages": [
    {
      "tools": "all",
      "content": "Add TypeScript support to this React project"
    }
  ],
  "repo_url": "https://github.com/username/my-project",
  "github_token": "ghp_...",
  "branch": "main",
  "haiku": true
}

Custom messages give you the same AI capabilities as prebuilt templates, but with complete control over the conversation flow and execution steps.

Why Use Custom Messages?

Prebuilt TemplatesCustom Messages
❌ Fixed workflows✅ Script any workflow
❌ Limited tool control✅ Choose tools per step
❌ Repository-wide scope✅ Directory-focused work
❌ Template variables only✅ Full conversation control
❌ Predefined steps✅ Custom workflow logic

Message Structure

Every message supports these fields:

{
  "content": "Your instruction for the AI agent",
  "tools": "all",                    // or ["Read", "Edit", "Bash"]
  "continueConversation": true,      // Continue previous context
  "workingDir": "./src/components"   // Focus on specific directory
}

Critical Limitation: You cannot change workingDir and use continueConversation: true in the same request. When changing directories, you must start a fresh conversation (omit continueConversation or set it to false).

Progressive Examples

Level 1: Single Task

Start with simple, focused tasks:

curl -X POST "https://api.cloudcoding.ai/invoke" \
  -H "Content-Type: application/json" \
  -H "x-api-key: your_api_key" \
  -d '{
    "messages": [
      {
        "tools": "all",
        "content": "Add comprehensive error handling to all API endpoints"
      }
    ],
    "repo_url": "https://github.com/username/api-project",
    "github_token": "ghp_...",
    "branch": "error-handling",
    "haiku": true
  }'

Level 2: Multi-Step Workflow

Chain related tasks together:

curl -X POST "https://api.cloudcoding.ai/invoke" \
  -H "Content-Type: application/json" \
  -H "x-api-key: your_api_key" \
  -d '{
    "messages": [
      {
        "tools": "all",
        "content": "Analyze the current test coverage and identify untested code"
      },
      {
        "tools": "all",
        "content": "Add comprehensive unit tests for all untested functions",
        "continueConversation": true
      },
      {
        "tools": ["Bash"],
        "content": "Run the test suite and ensure all tests pass",
        "continueConversation": true
      }
    ],
    "repo_url": "https://github.com/username/testing-project",
    "github_token": "ghp_...",
    "branch": "comprehensive-testing",
    "haiku": true
  }'

Level 3: Tool-Controlled Workflow

Precisely control which tools are used at each step:

curl -X POST "https://api.cloudcoding.ai/invoke" \
  -H "Content-Type: application/json" \
  -H "x-api-key: your_api_key" \
  -d '{
    "messages": [
      {
        "tools": ["Read", "LS", "Grep"],
        "content": "Explore the codebase structure and understand the authentication system"
      },
      {
        "tools": ["Edit", "Write"],
        "content": "Refactor the authentication to use modern security practices",
        "continueConversation": true
      },
      {
        "tools": ["Bash"],
        "content": "Test the updated authentication system",
        "continueConversation": true
      }
    ],
    "repo_url": "https://github.com/username/secure-app",
    "github_token": "ghp_...",
    "branch": "auth-security-update",
    "haiku": false
  }'

Level 4: Complex Task Planning

Break down complex tasks into manageable steps:

curl -X POST "https://api.cloudcoding.ai/invoke" \
  -H "Content-Type: application/json" \
  -H "x-api-key: your_api_key" \
  -d '{
    "messages": [
      {
        "tools": ["Task", "Read", "LS"],
        "content": "Analyze this project and create a detailed plan for setting up a CI/CD pipeline"
      },
      {
        "tools": "all",
        "content": "Implement the CI/CD pipeline based on the analysis and plan",
        "continueConversation": true
      }
    ],
    "repo_url": "https://github.com/username/deployment-project",
    "github_token": "ghp_...",
    "branch": "cicd-setup",
    "haiku": false
  }'

Level 5: Directory-Focused Development

Important: This example shows an incorrect pattern. You cannot change workingDir and use continueConversation: true. Each directory requires a separate API call.

Focus the agent on specific parts of your codebase using separate API calls:

# ❌ INCORRECT - Will not work as expected
curl -X POST "https://api.cloudcoding.ai/invoke" \
  -H "Content-Type: application/json" \
  -H "x-api-key: your_api_key" \
  -d '{
    "messages": [
      {
        "tools": "all",
        "content": "Convert React components to TypeScript",
        "workingDir": "./src/components"
      },
      {
        "tools": "all",
        "content": "Update hooks to TypeScript",
        "workingDir": "./src/hooks",
        "continueConversation": true  // ❌ This will fail!
      }
    ]
  }'

# ✅ CORRECT - Separate API calls for each directory
# Call 1: Components
curl -X POST "https://api.cloudcoding.ai/invoke" \
  -H "Content-Type: application/json" \
  -H "x-api-key: your_api_key" \
  -d '{
    "messages": [
      {
        "tools": "all",
        "content": "Convert all React components to TypeScript with proper prop types",
        "workingDir": "./src/components"
      }
    ],
    "repo_url": "https://github.com/username/typescript-migration",
    "github_token": "ghp_...",
    "branch": "typescript-conversion",
    "haiku": false
  }'

# Call 2: Hooks
curl -X POST "https://api.cloudcoding.ai/invoke" \
  -H "Content-Type: application/json" \
  -H "x-api-key: your_api_key" \
  -d '{
    "messages": [
      {
        "tools": "all",
        "content": "Update the custom hooks to use TypeScript interfaces",
        "workingDir": "./src/hooks"
      }
    ],
    "repo_url": "https://github.com/username/typescript-migration",
    "github_token": "ghp_...",
    "branch": "typescript-conversion",
    "haiku": false
  }'

# Call 3: Utils
curl -X POST "https://api.cloudcoding.ai/invoke" \
  -H "Content-Type: application/json" \
  -H "x-api-key: your_api_key" \
  -d '{
    "messages": [
      {
        "tools": "all",
        "content": "Add TypeScript types to the utility functions",
        "workingDir": "./src/utils"
      }
    ],
    "repo_url": "https://github.com/username/typescript-migration",
    "github_token": "ghp_...",
    "branch": "typescript-conversion",
    "haiku": false
  }'

Available Tools

Based on the actual system capabilities, you can specify these tools:

ToolPurposeUse When
"all"All available toolsMost scenarios (recommended)
"Task"Task management and planningProject planning and organization
"Bash"Execute shell commandsRunning tests, builds, deployments
"Glob"File pattern matchingFinding files with specific patterns
"Grep"Text search and matchingSearching for code patterns
"LS"Directory listingExploring project structure
"Read"Read file contentsUnderstanding existing code
"Edit"Edit existing filesModifying code
"MultiEdit"Edit multiple filesLarge refactoring tasks
"Write"Create new filesAdding new components/modules
"NotebookRead"Read Jupyter notebooksData science projects
"NotebookEdit"Edit Jupyter notebooksData science workflows
"WebFetch"Fetch web contentGetting external documentation
"TodoRead"Read todo listsProject management
"TodoWrite"Manage todo listsTask tracking
"WebSearch"Search the webFinding solutions and documentation

Real-World Workflow Patterns

Feature Development Workflow

Complete feature implementation from planning to deployment:

# Single API call approach - Full-stack feature implementation
curl -X POST "https://api.cloudcoding.ai/invoke" \
  -H "Content-Type: application/json" \
  -H "x-api-key: your_api_key" \
  -d '{
    "messages": [
      {
        "tools": ["Read", "LS", "Task"],
        "content": "Analyze the current codebase and create a detailed plan for implementing user profiles with avatars, preferences, and activity history."
      },
      {
        "tools": ["Write", "Edit"],
        "content": "Implement the backend API endpoints for user profiles according to the plan",
        "continueConversation": true
      },
      {
        "tools": ["Write", "Edit"],
        "content": "Create the frontend components for user profile management",
        "continueConversation": true
      },
      {
        "tools": ["Write", "Bash"],
        "content": "Add comprehensive tests and run the test suite",
        "continueConversation": true
      }
    ],
    "repo_url": "https://github.com/username/fullstack-app",
    "github_token": "ghp_...",
    "branch": "user-profiles-feature",
    "haiku": false
  }'

# Alternative: Directory-focused approach (separate API calls)
# Call 1: Backend implementation
curl -X POST "https://api.cloudcoding.ai/invoke" \
  -H "Content-Type: application/json" \
  -H "x-api-key: your_api_key" \
  -d '{
    "messages": [
      {
        "tools": ["Read", "LS"],
        "content": "Analyze the backend structure and implement user profile API endpoints with avatars, preferences, and activity history",
        "workingDir": "./backend"
      }
    ],
    "repo_url": "https://github.com/username/fullstack-app",
    "github_token": "ghp_...",
    "branch": "user-profiles-feature",
    "haiku": false
  }'

# Call 2: Frontend implementation
curl -X POST "https://api.cloudcoding.ai/invoke" \
  -H "Content-Type: application/json" \
  -H "x-api-key: your_api_key" \
  -d '{
    "messages": [
      {
        "tools": ["Write", "Edit"],
        "content": "Create React components for user profile management, integrating with the backend APIs",
        "workingDir": "./frontend/src/components"
      }
    ],
    "repo_url": "https://github.com/username/fullstack-app",
    "github_token": "ghp_...",
    "branch": "user-profiles-feature",
    "haiku": false
  }'

Security Audit Workflow

Comprehensive security review and fixes:

curl -X POST "https://api.cloudcoding.ai/invoke" \
  -H "Content-Type: application/json" \
  -H "x-api-key: your_api_key" \
  -d '{
    "messages": [
      {
        "tools": ["Read", "Grep", "WebSearch"],
        "content": "Conduct a thorough security audit of this application, checking for common vulnerabilities like SQL injection, XSS, CSRF, and insecure authentication"
      },
      {
        "tools": ["Edit", "Write"],
        "content": "Fix all identified security vulnerabilities and implement security best practices",
        "continueConversation": true
      },
      {
        "tools": ["Bash", "WebSearch"],
        "content": "Run security tests and validate that all vulnerabilities have been resolved",
        "continueConversation": true
      }
    ],
    "repo_url": "https://github.com/username/secure-app",
    "github_token": "ghp_...",
    "branch": "security-audit-fixes",
    "haiku": false
  }'

Code Migration Workflow

Large-scale TypeScript migration using directory-focused approach:

# Call 1: Analysis and utilities migration
curl -X POST "https://api.cloudcoding.ai/invoke" \
  -H "Content-Type: application/json" \
  -H "x-api-key: your_api_key" \
  -d '{
    "messages": [
      {
        "tools": ["Read", "LS", "Grep"],
        "content": "Analyze the JavaScript codebase and create a comprehensive TypeScript migration strategy. Start by converting utility functions and shared modules with proper type definitions.",
        "workingDir": "./src/utils"
      }
    ],
    "repo_url": "https://github.com/username/typescript-migration",
    "github_token": "ghp_...",
    "branch": "typescript-conversion",
    "haiku": false
  }'

# Call 2: Components migration
curl -X POST "https://api.cloudcoding.ai/invoke" \
  -H "Content-Type: application/json" \
  -H "x-api-key: your_api_key" \
  -d '{
    "messages": [
      {
        "tools": ["Edit", "Write"],
        "content": "Convert React components to TypeScript with proper prop interfaces and state types, using the utility types we defined",
        "workingDir": "./src/components"
      }
    ],
    "repo_url": "https://github.com/username/typescript-migration",
    "github_token": "ghp_...",
    "branch": "typescript-conversion",
    "haiku": false
  }'

# Call 3: Final validation
curl -X POST "https://api.cloudcoding.ai/invoke" \
  -H "Content-Type: application/json" \
  -H "x-api-key: your_api_key" \
  -d '{
    "messages": [
      {
        "tools": ["Bash", "Read"],
        "content": "Run TypeScript compiler across the entire project, fix any remaining type errors, and ensure the build passes"
      }
    ],
    "repo_url": "https://github.com/username/typescript-migration",
    "github_token": "ghp_...",
    "branch": "typescript-conversion",
    "haiku": false
  }'

API Refactoring Workflow

Single-directory focused refactoring:

curl -X POST "https://api.cloudcoding.ai/invoke" \
  -H "Content-Type: application/json" \
  -H "x-api-key: your_api_key" \
  -d '{
    "messages": [
      {
        "tools": ["Read", "LS", "Grep"],
        "content": "Analyze the API routes and identify opportunities for better error handling, validation, and performance"
      },
      {
        "tools": ["Edit", "Write"],
        "content": "Refactor API endpoints to use consistent error handling middleware and request validation",
        "continueConversation": true
      },
      {
        "tools": ["Write"],
        "content": "Add comprehensive API documentation and update existing endpoint documentation",
        "continueConversation": true
      },
      {
        "tools": ["Bash"],
        "content": "Run API tests and performance benchmarks to validate the improvements",
        "continueConversation": true
      }
    ],
    "repo_url": "https://github.com/username/api-refactor",
    "github_token": "ghp_...",
    "branch": "api-improvements",
    "workingDir": "./api",
    "haiku": false
  }'

Database Schema Migration

Focused database work:

curl -X POST "https://api.cloudcoding.ai/invoke" \
  -H "Content-Type: application/json" \
  -H "x-api-key: your_api_key" \
  -d '{
    "messages": [
      {
        "tools": ["Read", "LS"],
        "content": "Analyze the current database schema and create a migration plan for better normalization and performance"
      },
      {
        "tools": ["Write", "Edit"],
        "content": "Create database migration scripts for schema improvements",
        "continueConversation": true
      },
      {
        "tools": ["Edit"],
        "content": "Update ORM models and queries to work with the new schema",
        "continueConversation": true
      },
      {
        "tools": ["Bash"],
        "content": "Test the migration scripts and validate data integrity",
        "continueConversation": true
      }
    ],
    "repo_url": "https://github.com/username/db-migration",
    "github_token": "ghp_...",
    "branch": "schema-improvements",
    "workingDir": "./database",
    "haiku": false
  }'

Advanced Features

Conversation Continuity

Use continueConversation: true to maintain context across messages:

{
  "messages": [
    {
      "content": "Create a comprehensive user authentication system with JWT tokens"
    },
    {
      "content": "Now add password reset functionality to the authentication system we just created",
      "continueConversation": true
    },
    {
      "content": "Finally, implement two-factor authentication as an additional security layer",
      "continueConversation": true
    }
  ]
}

Directory Scoping

Use workingDir to focus the agent on specific parts of your repository:

Note: The example below shows an incorrect pattern - you cannot change workingDir and use continueConversation: true together.

// ❌ INCORRECT - This will not work
{
  "messages": [
    {
      "content": "Optimize all database queries in this directory",
      "workingDir": "./backend/database"
    },
    {
      "content": "Update the API routes to use the optimized queries",
      "workingDir": "./backend/routes",
      "continueConversation": true  // ❌ Will fail with directory change
    }
  ]
}

// ✅ CORRECT - Use separate API calls
// First call:
{
  "messages": [
    {
      "content": "Optimize all database queries in this directory",
      "workingDir": "./backend/database"
    }
  ]
}

// Second call:
{
  "messages": [
    {
      "content": "Update the API routes to use the optimized queries from the database directory",
      "workingDir": "./backend/routes"
    }
  ]
}

Working Directory Limitations

Critical Technical Constraint: The Cloud Coding API has an important limitation when using workingDir:

  • Cannot combine workingDir changes with continueConversation: true
  • Must use separate API calls for each different working directory
  • 🔧 Technical reason: The AI agent gets mounted to the specified directory and cannot maintain context across different mount points

This limitation is enforced at the system level and cannot be worked around.

Common Mistake

// ❌ This will NOT work - will fail or behave unexpectedly
{
  "messages": [
    {
      "workingDir": "./frontend",
      "content": "Update React components"
    },
    {
      "workingDir": "./backend",
      "content": "Now update the API",
      "continueConversation": true  // ❌ FAILS with directory change
    }
  ]
}

Correct Approach

# ✅ Two separate API calls
# Call 1: Frontend work
curl -X POST "https://api.cloudcoding.ai/invoke" \
  -d '{"messages": [{"workingDir": "./frontend", "content": "Update React components"}], ...}'

# Call 2: Backend work
curl -X POST "https://api.cloudcoding.ai/invoke" \
  -d '{"messages": [{"workingDir": "./backend", "content": "Update the API"}], ...}'

Best Practices

1. Start Simple, Build Complexity

{
  "messages": [
    {
      "content": "Add basic user authentication to this app"
    }
  ]
}

Then evolve to:

{
  "messages": [
    {
      "content": "Plan a comprehensive authentication system with JWT, refresh tokens, and social login"
    },
    {
      "content": "Implement the planned authentication system",
      "continueConversation": true
    },
    {
      "content": "Add comprehensive tests for all authentication flows",
      "continueConversation": true
    }
  ]
}

2. Use Descriptive Instructions

❌ Vague: "Fix the code" ✅ Specific: "Add error handling to all API endpoints, including proper HTTP status codes and user-friendly error messages"

3. Strategic Tool Selection

{
  "tools": ["Read", "LS"],
  "content": "Analyze the code architecture without making changes"
}

4. Leverage Working Directories

{
  "workingDir": "./src/components",
  "content": "Focus only on React components for this refactoring"
}

5. Task Planning

{
  "tools": ["Task", "Read", "LS"],
  "content": "Create a detailed plan before implementing this complex feature"
}

Python Integration

import requests
import json

def create_custom_workflow(api_key, messages, repo_url, github_token, branch="main", working_dir=None):
    """
    Execute a custom message workflow.
    """
    url = "https://api.cloudcoding.ai/invoke"
    headers = {
        "Content-Type": "application/json",
        "x-api-key": api_key
    }

    payload = {
        "messages": messages,
        "repo_url": repo_url,
        "github_token": github_token,
        "branch": branch,
        "haiku": True
    }

    # Add workingDir to the first message if specified
    if working_dir and messages:
        messages[0]["workingDir"] = working_dir

    response = requests.post(url, headers=headers, json=payload, stream=True)

    for line in response.iter_lines():
        if line.startswith(b'data: '):
            try:
                data = json.loads(line[6:])
                yield data
            except json.JSONDecodeError:
                continue

def multi_directory_workflow(api_key, workflow_steps, repo_url, github_token, branch="main"):
    """
    Execute a workflow across multiple directories using separate API calls.
    Each step is a dict with 'directory', 'messages', and optional 'description'.
    """
    results = []

    for i, step in enumerate(workflow_steps):
        print(f"Executing step {i+1}: {step.get('description', f'Work in {step[\"directory\"]}')}")

        # Each directory requires a separate API call
        messages = step["messages"]
        if step["directory"]:
            # Add workingDir to the first message
            if messages and isinstance(messages[0], dict):
                messages[0]["workingDir"] = step["directory"]

        step_results = list(create_custom_workflow(
            api_key, messages, repo_url, github_token, branch
        ))
        results.append({
            "step": i+1,
            "directory": step["directory"],
            "results": step_results
        })

    return results

# Example 1: Single directory workflow
single_dir_messages = [
    {
        "tools": "all",
        "content": "Add comprehensive error handling and logging to this application"
    },
    {
        "tools": ["Bash"],
        "content": "Run tests to ensure error handling works correctly",
        "continueConversation": True
    }
]

print("Single directory workflow:")
for event in create_custom_workflow("your_api_key", single_dir_messages,
                                   "https://github.com/user/repo", "ghp_token"):
    print(f"Event: {event}")

# Example 2: Multi-directory workflow (separate API calls)
workflow_steps = [
    {
        "directory": "./backend",
        "description": "Backend API improvements",
        "messages": [
            {
                "tools": ["Read", "Edit"],
                "content": "Improve API error handling and add request validation"
            }
        ]
    },
    {
        "directory": "./frontend",
        "description": "Frontend error handling",
        "messages": [
            {
                "tools": ["Edit", "Write"],
                "content": "Add error boundaries and improved error messaging to React components"
            }
        ]
    },
    {
        "directory": None,  # Repository root
        "description": "Integration testing",
        "messages": [
            {
                "tools": ["Bash", "Write"],
                "content": "Run end-to-end tests to validate error handling across the full stack"
            }
        ]
    }
]

print("\nMulti-directory workflow:")
results = multi_directory_workflow("your_api_key", workflow_steps,
                                  "https://github.com/user/repo", "ghp_token",
                                  branch="error-handling-improvements")

for result in results:
    print(f"Step {result['step']} ({'Root' if not result['directory'] else result['directory']}): {len(result['results'])} events")

Common Patterns Summary

PatternUse CaseImplementationExample
Single MessageSimple, focused tasksOne message, any directoryAdd dark mode toggle
Multi-StepRelated task sequence in same scopeMultiple messages with continueConversation: truePlan → Implement → Test
Tool-ControlledSpecific operations with controlled tool accessMessages with specific tool arraysRead-only analysis, then targeted editing
Task PlanningComplex feature developmentAnalysis → Implementation → Testing flowPlan → Implement → Test → Deploy
Single Directory FocusWork within one directoryworkingDir + multi-step messagesComponent library refactoring
Multi-DirectoryLarge codebase work across directoriesSeparate API calls (cannot use continueConversation)TypeScript migration per directory

Critical Pattern Limitation: Multi-directory workflows must use separate API calls. You cannot change workingDir and use continueConversation: true in the same request. This is a system-level constraint, not a documentation suggestion.

Next Steps

Ready to build your first custom workflow? Start with:

  1. Simple single message - Get comfortable with the basic structure
  2. Add conversation flow - Try continueConversation: true
  3. Control tools - Specify exact tools for each step
  4. Directory focusing - Use workingDir for targeted development
  5. Complex workflows - Combine all features for powerful automation

Pro Tip

Custom messages give you the power to script any development workflow. Start simple and gradually build more sophisticated automation as you learn the patterns.