# Get Credits Balance Source: https://docs.pre.dev/architect-agent/api/credits-balance GET /credits-balance Check the remaining credits balance for your API key. Get the remaining credits balance for the authenticated API key holder. ## Overview * **Use Cases:** Monitor credit usage, check balance before making requests * **Processing Time:** Instant * **Response:** JSON object with creditsRemaining count ## Endpoint ``` GET https://api.pre.dev/credits-balance ``` ## Headers ``` Authorization: Bearer YOUR_API_KEY ``` ## Parameters No request body required. Authentication is via the `Authorization` header. ## Example Request ```bash theme={null} curl https://api.pre.dev/credits-balance \ -H "Authorization: Bearer YOUR_API_KEY" ``` ## Response ### Success Response ```json theme={null} { "success": true, "creditsRemaining": 450 } ``` | Field | Type | Description | | ------------------ | ------- | -------------------------------------------- | | `success` | boolean | Whether the request succeeded | | `creditsRemaining` | number | Number of credits remaining for this API key | ### Error Response - Missing Context ```json theme={null} { "error": "Missing context", "message": "Unable to determine user or organization from API key" } ``` ### Error Response - Server Error ```json theme={null} { "error": "Failed to retrieve credits balance", "message": "Internal server error details" } ``` ## Credit Costs | Endpoint | Cost | When Charged | | --------- | --------------- | ------------------------------- | | Fast Spec | \~5-10 credits | Per-inference during generation | | Deep Spec | \~10-50 credits | Per-inference during generation | ## Code Examples ### cURL ```bash theme={null} curl https://api.pre.dev/credits-balance \ -H "Authorization: Bearer YOUR_API_KEY" ``` ### Python ```python theme={null} import requests def get_credits_balance(api_key: str) -> dict: """Get the current credits balance for the API key.""" url = "https://api.pre.dev/credits-balance" headers = {"Authorization": f"Bearer {api_key}"} try: response = requests.get(url, headers=headers, timeout=60) response.raise_for_status() data = response.json() return { "success": data["success"], "creditsRemaining": data["creditsRemaining"] } except requests.RequestException as e: raise Exception(f"Request failed: {str(e)}") from e # Usage api_key = "YOUR_API_KEY" balance = get_credits_balance(api_key) print(f"Credits remaining: {balance['creditsRemaining']}") ``` ### JavaScript/Node.js ```javascript theme={null} async function getCreditsBalance(apiKey) { const url = 'https://api.pre.dev/credits-balance'; try { const response = await fetch(url, { method: 'GET', headers: { 'Authorization': `Bearer ${apiKey}` } }); if (!response.ok) { const error = await response.json(); throw new Error(error.message || 'Failed to get credits balance'); } return await response.json(); } catch (error) { throw new Error(`Request failed: ${error.message}`); } } // Usage try { const balance = await getCreditsBalance('YOUR_API_KEY'); console.log(`Credits remaining: ${balance.creditsRemaining}`); } catch (error) { console.error('Error:', error.message); } ``` ### TypeScript ```typescript theme={null} interface CreditsBalanceResponse { success: boolean; creditsRemaining: number; } async function getCreditsBalance(apiKey: string): Promise { const url = 'https://api.pre.dev/credits-balance'; try { const response = await fetch(url, { method: 'GET', headers: { 'Authorization': `Bearer ${apiKey}` } }); if (!response.ok) { const error = await response.json(); throw new Error(error.message || 'Failed to get credits balance'); } return await response.json(); } catch (error) { if (error instanceof Error) { throw new Error(`Request failed: ${error.message}`); } throw error; } } // Usage try { const balance = await getCreditsBalance('YOUR_API_KEY'); console.log(`Credits remaining: ${balance.creditsRemaining}`); if (balance.creditsRemaining < 20) { console.warn('⚠️ Low credits! Consider purchasing more.'); } } catch (error) { console.error('Error:', error); } ``` ## Use Cases ### Before Making Expensive Requests Check your balance before initiating a spec request: ```typescript theme={null} const balance = await getCreditsBalance(apiKey); if (balance.creditsRemaining > 0) { // Safe to make spec request const spec = await generateDeepSpec({ input: "Build an enterprise platform" }); } else { console.log(`Insufficient credits. Have ${balance.creditsRemaining}`); } ``` ### Monitor Credit Usage Track credit consumption over time: ```typescript theme={null} async function checkAndNotify(apiKey: string) { const balance = await getCreditsBalance(apiKey); if (balance.creditsRemaining < 50) { // Send low balance notification await sendAlert(`Only ${balance.creditsRemaining} credits remaining`); } } ``` ## Dashboard Access ### Solo Users View your credits balance via the dashboard: * **URL:** [https://pre.dev/projects/key](https://pre.dev/projects/key) * Shows your remaining credits * Option to purchase additional credits ### Enterprise Users Access credits and billing information: * **URL:** [https://pre.dev/enterprise/dashboard?page=api](https://pre.dev/enterprise/dashboard?page=api) * View organization-wide credit usage * Manage team API keys and quotas ## Error Handling ### Authentication Failures ```bash theme={null} # Invalid API key curl https://api.pre.dev/credits-balance \ -H "Authorization: Bearer invalid_key" ``` Response: ```json theme={null} { "error": "Unauthorized", "message": "Invalid API key" } ``` ### Network Issues Implement retry logic with exponential backoff: ```typescript theme={null} async function getCreditsBalanceWithRetry( apiKey: string, maxRetries: number = 3 ): Promise { for (let attempt = 0; attempt < maxRetries; attempt++) { try { return await getCreditsBalance(apiKey); } catch (error) { if (attempt === maxRetries - 1) throw error; const delay = Math.pow(2, attempt) * 1000; // Exponential backoff await new Promise(resolve => setTimeout(resolve, delay)); } } throw new Error('Max retries exceeded'); } ``` ## Best Practices ### Regular Monitoring * Check balance before making expensive spec requests * Implement alerts when credits fall below a threshold * Monitor credit usage patterns to plan purchases ### Integration Patterns * Cache balance checks (don't call on every request) * Update cache every 5-10 minutes * Use for decision logic in your application ### Error Handling * Always handle network failures gracefully * Implement retry logic for transient errors * Provide meaningful error messages to users ## HTTP Status Codes | Code | Meaning | Action | | ---- | ------------ | ---------------------------------- | | 200 | Success | Process the response | | 400 | Bad Request | Check request parameters | | 401 | Unauthorized | Verify API key is valid and active | | 500 | Server Error | Contact support | View all available API endpoints. # Generate Deep Spec Source: https://docs.pre.dev/architect-agent/api/deep-spec POST /deep-spec Complete documentation for the Deep Spec endpoint. Generate exhaustive, enterprise-grade project specifications. Generate an ultra-detailed, comprehensive project specification. ## Overview * **Cost:** Variable (typically \~10-50 credits based on complexity) * **Use Cases:** Complex systems, enterprise applications, critical projects * **Processing Time:** \~3-5 minutes (sync) or instant return (async) * **Output:** Exhaustive analysis, detailed architecture, comprehensive planning ## Availability Deep Spec consumes more credits than Fast Spec and is available on paid plans. See [pre.dev/pricing](https://pre.dev/pricing) for which plans include it. ## Endpoint ``` POST https://api.pre.dev/deep-spec ``` ## Headers **For JSON requests:** ``` Content-Type: application/json Authorization: Bearer YOUR_API_KEY ``` **For file upload requests:** ``` Content-Type: multipart/form-data Authorization: Bearer YOUR_API_KEY ``` ## Request Body ### Parameters **For JSON requests:** | Parameter | Type | Required | Description | | ---------------- | --------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `input` | string | ✅ | Description of what you want to build | | `currentContext` | string | ❌ | **CRITICAL:** Existing project/codebase context. When provided, generates feature addition spec. When omitted, generates full new project spec with setup, deployment, docs, maintenance | | `docURLs` | string\[] | ❌ | **Optional:** Array of documentation URLs that Architect will reference when generating specifications. Useful for API documentation, design systems, or existing project docs | | `async` | boolean | ❌ | `false` (default) - wait for completion, or `true` - return immediately with `specId` for status polling | **For file upload requests (multipart/form-data):** | Parameter | Type | Required | Description | | --------- | --------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `file` | File | ❌ | **Optional:** File to be parsed as input (e.g., existing code, documentation, requirements). Can be used alone or combined with `input` text | | `input` | string | ❌ | **Optional:** Additional text description when using file upload. Can be empty string if using only file | | `docURLs` | string\[] | ❌ | **Optional:** Array of documentation URLs that Architect will reference when generating specifications. Useful for API documentation, design systems, or existing project docs | | `async` | boolean | ❌ | `false` (default) - wait for completion, or `true` - return immediately with `specId` for status polling | ### Deep Spec vs Fast Spec | Feature | Fast Spec | Deep Spec | | --------------- | -------------------- | ------------------------------- | | Cost | \~5-10 credits | \~10-50 credits | | Processing Time | \~1 min | \~3-5 min | | Structure | Milestones → Stories | Milestones → Stories → Subtasks | | Detail Level | Comprehensive | Ultra-detailed | | Best For | MVPs, prototypes | Enterprise, complex systems | ## Example Requests ### New Enterprise Project ```json theme={null} { "input": "Build an enterprise healthcare management platform with patient records, appointment scheduling, billing, insurance processing, and HIPAA compliance for a multi-location hospital system.", } ``` ### Complex Feature Addition ```json theme={null} { "input": "Add AI-powered diagnostics, predictive analytics, and automated treatment recommendations to existing healthcare platform", "currentContext": "Existing platform has patient management, scheduling, basic reporting, built with React/Node.js/PostgreSQL, serves 50+ medical practices", } ``` ### Async Processing ```json theme={null} { "input": "Build a comprehensive fintech platform with banking, investments, crypto trading, regulatory compliance, and real-time market data", "async": true } ``` ### Example: With Documentation URLs ```json theme={null} { "input": "Build an enterprise healthcare platform with HIPAA compliance and telemedicine capabilities", "docURLs": [ "https://docs.pre.dev", "https://docs.hl7.org" ], "async": true } ``` ### Example: With File Upload ```javascript theme={null} // Prepare file upload for enterprise requirements document const formData = new FormData(); formData.append('file', enterpriseRequirementsFile); // PDF with detailed enterprise requirements formData.append('input', 'Generate comprehensive deep spec for the uploaded enterprise platform requirements'); formData.append('docURLs', JSON.stringify([ "https://docs.pre.dev", "https://docs.hl7.org", "https://enterprise-docs.company.com" ])); formData.append('async', 'true'); const response = await fetch('https://api.pre.dev/deep-spec', { method: 'POST', headers: { 'Authorization': 'Bearer YOUR_API_KEY' // Note: Don't set Content-Type for FormData - browser sets it automatically }, body: formData }); const result = await response.json(); console.log('Spec ID:', result.specId); ``` ### Example: File Upload with Existing Context ```javascript theme={null} // Upload existing architecture docs and add context const formData = new FormData(); formData.append('file', currentArchitectureFile); // Current system architecture formData.append('input', 'Add microservices architecture and improve scalability for our existing healthcare platform'); formData.append('currentContext', 'Existing platform handles 100k+ patients, built with React/Node.js/PostgreSQL, has basic HIPAA compliance'); formData.append('async', 'true'); ``` ## Response ### Success Response (Sync Mode) ```json theme={null} { "endpoint": "deep_spec", "input": "Build an enterprise healthcare management platform...", "status": "completed", "success": true, "humanSpecUrl": "https://api.pre.dev/s/a6hFJRV6", "codingAgentSpecUrl": "https://api.pre.dev/s/a6hFJRV7", "codingAgentSpecJson": { "executiveSummary": "An enterprise healthcare platform...", "coreFunctionalities": [ { "name": "Patient Records", "description": "Secure patient data management", "priority": "High" } ], "techStack": [ { "name": "React", "category": "Frontend" }, { "name": "Node.js", "category": "Backend" } ], "techStackGrouped": { "Frontend": ["React"], "Backend": ["Node.js"] }, "milestones": [ { "milestoneNumber": 1, "description": "Patient Management", "stories": [ { "title": "Patient intake", "complexity": "M", "subTasks": [{ "description": "Design intake workflow", "complexity": "S" }] } ] } ] }, "codingAgentSpecMarkdown": "# Enterprise Healthcare Platform\\n\\n## Executive Summary\\n...", "humanSpecJson": { "executiveSummary": "An enterprise healthcare platform...", "personas": [{ "title": "Clinician", "description": "Provides care and updates records" }], "roles": [{ "name": "Backend Engineer", "shortHand": "BE" }], "techStack": [{ "name": "PostgreSQL", "category": "Database" }], "techStackGrouped": { "Database": ["PostgreSQL"] }, "totalHours": 320, "milestones": [ { "milestoneNumber": 1, "description": "Patient Management", "hours": 110, "stories": [ { "title": "Patient intake", "hours": 16, "subTasks": [{ "description": "Implement intake API", "hours": 6, "complexity": "M" }] } ] } ] }, "humanSpecMarkdown": "# Enterprise Healthcare Platform\\n\\n## Executive Summary\\n...", "architectureInfographicUrl": "https://res.cloudinary.com/dfvg7gm6w/image/upload/v1765403270/infographics/arch_infographic_cfac141b_1765403269989_0.jpg", "executionTime": 185000, "predevUrl": "https://pre.dev/projects/abc123", "creditsUsed": 28, "zippedDocsUrls": [ { "platform": "docs.hl7.org", "masterZipShortUrl": "https://api.pre.dev/s/xyz789" }, { "platform": "stripe.com", "masterZipShortUrl": "https://api.pre.dev/s/abc456" } ] } ``` | Field | Type | Description | | ---------------------------- | ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `endpoint` | string | Endpoint used: `"deep_spec"` | | `input` | string | Original input text provided | | `status` | string | Completion status: `"completed"` when successful | | `success` | boolean | Whether the request succeeded | | `humanSpecUrl` | string | URL where the human-readable spec is hosted (downloadable markdown) | | `humanSpecMarkdown` | string | Full markdown SOW with all details | | `humanSpecJson` | object | Full structured SOW JSON (hours, personas, roles) | | `totalHumanHours` | number | Estimated total hours for a human to implement the spec | | `architectureInfographicUrl` | string | URL to a visual architecture infographic/diagram for the specification | | `codingAgentSpecUrl` | string | URL where the coding agent spec format is hosted (downloadable markdown) | | `codingAgentSpecMarkdown` | string | Simplified markdown SOW for AI tools | | `codingAgentSpecJson` | object | Simplified structured SOW JSON for AI tools | | `executionTime` | number | Processing time in milliseconds | | `predevUrl` | string | pre.dev project URL where you can view and edit the spec | | `creditsUsed` | number | Total credits consumed by this spec generation. Available in real-time during processing and persisted on completion. Typical values: Fast spec \~5-10, Deep spec \~10-50 | | `zippedDocsUrls` | array | Array of scraped documentation archives. Each object contains `platform` (hostname from the doc URL), `masterZipShortUrl` (download link to the ZIP archive), and optional `masterMarkdownShortUrl` (consolidated markdown). Empty array if no `docURLs` provided or scraping fails | ### Success Response (Async Mode) **Immediate response when `async: true`:** ```json theme={null} { "specId": "507f1f77bcf86cd799439011", "status": "pending" } ``` | Field | Type | Description | | -------- | ------ | -------------------------------------------------------------- | | `specId` | string | Unique ID to poll for status (use with `/spec-status/:specId`) | | `status` | string | Initial status: `"pending"` | ## Output Structure: Milestones → Stories → Subtasks Deep Spec follows a **three-level hierarchy** for comprehensive implementation planning: ```markdown theme={null} ### - [ ] **Milestone 2**: User authentication and profile management - [ ] **User Registration** - (M): As a: new user, I want to: register an account with email and password, So that: I can access the platform - **Acceptance Criteria:** - [ ] User can register with valid email and password - [ ] Email verification sent upon registration - [ ] Duplicate emails handled gracefully - [ ] Password strength requirements enforced - [ ] DB: Create/verify table_users migration - (M) - [ ] Infra: Configure Clerk (external_clerk) & auth settings - (M) - [ ] FE: Implement /RegisterPage UI comp_registerPage_mainForm - (M) - [ ] FE: Add client-side validation & reCAPTCHA on register form - (M) - [ ] API: Implement registerWithEmail mutation in router_route_registerPage - (M) - [ ] Backend: Create user record in table_users and auth_methods - (M) - [ ] Integration: Connect API to Clerk for email confirmation/session - (M) - [ ] QA: Write unit and integration tests for registration flow - (M) - [ ] Docs: Document registration API and front-end behavior - (M) - [ ] **Password Reset** - (M): As a: registered user, I want to: reset my password securely, So that: I can regain access - **Acceptance Criteria:** - [ ] User can request password reset link via valid email - [ ] Reset link expires after a defined period - [ ] New password must meet strength requirements - [ ] System invalidates existing sessions after password change - [ ] DB: Create password_resets table migration - (M) - [ ] API: Implement requestPasswordReset mutation (validate, create token) - (M) - [ ] API: Implement verifyResetToken and finalizeReset mutation - (M) - [ ] Frontend: Add Password Reset Request page (/auth/password-reset) - (M) - [ ] Frontend: Add Password Reset Form page (/auth/reset?token=) - (M) - [ ] Auth Integration: Wire Clerk for account lookup and session invalidation - (M) - [ ] Infra: Email service integration and template for reset link - (M) - [ ] Security: Add reCAPTCHA and rate limiting to request endpoint - (M) - [ ] Testing: End-to-end tests for reset flow - (M) - [ ] Docs: Document API, pages, and operational runbook - (M) ``` **Key Characteristics:** * High-level milestones group related features * Detailed user stories with comprehensive acceptance criteria * **Granular implementation subtasks** (DB, API, Frontend, Testing, Docs) * Subtasks categorized by layer (DB, Infra, FE, API, Backend, QA, Docs) * Task-level complexity estimates for precise planning ## Direct SOW Formats Deep Spec returns the full Scope of Work inline, and also provides URL endpoints: * **codingAgentSpecJson** / **codingAgentSpecMarkdown**: concise outputs for AI coding assistants (no hours/personas/roles) * **humanSpecJson** / **humanSpecMarkdown**: full outputs with hours, personas, and roles for stakeholder review Use cases: * Feed Cursor/Copilot: `codingAgentSpecJson` or `codingAgentSpecMarkdown` * Display in PM tools or dashboards: `humanSpecJson` * Export/PDF for clients: `humanSpecMarkdown` * Quick effort check: `totalHumanHours` or `humanSpecJson.totalHours` ### Type definitions (shared by Fast and Deep Spec) **Coding Agent JSON (concise, no hours/personas/roles):** ```typescript theme={null} interface CodingAgentSpecJson { title?: string; executiveSummary: string; coreFunctionalities: SpecCoreFunctionality[]; techStack: SpecTechStackItem[]; techStackGrouped: Record; milestones: CodingAgentMilestone[]; } interface CodingAgentMilestone { milestoneNumber: number; description: string; stories: CodingAgentStory[]; } interface CodingAgentStory { id?: string; title: string; description?: string; acceptanceCriteria?: string[]; complexity?: string; subTasks: CodingAgentSubTask[]; } interface CodingAgentSubTask { id?: string; description: string; complexity: string; // "S" | "M" | "L" | "XL" } ``` **Human JSON (full detail with hours/personas/roles):** ```typescript theme={null} interface HumanSpecJson { title?: string; executiveSummary: string; coreFunctionalities: SpecCoreFunctionality[]; personas: SpecPersona[]; techStack: SpecTechStackItem[]; techStackGrouped: Record; milestones: HumanSpecMilestone[]; totalHours: number; roles: SpecRole[]; } interface HumanSpecMilestone { milestoneNumber: number; description: string; hours: number; stories: HumanSpecStory[]; } interface HumanSpecStory { id?: string; title: string; description?: string; acceptanceCriteria?: string[]; hours: number; complexity?: string; subTasks: HumanSpecSubTask[]; } interface HumanSpecSubTask { id?: string; description: string; hours: number; complexity: string; roles?: SpecRole[]; } interface SpecPersona { title: string; description: string; primaryGoals?: string[]; painPoints?: string[]; keyTasks?: string[]; } interface SpecRole { name: string; shortHand: string; } interface SpecCoreFunctionality { name: string; description: string; priority?: string; // "High" | "Medium" | "Low" } interface SpecTechStackItem { name: string; category: string; } ``` ## What Makes Deep Spec Different Deep Spec goes beyond Fast Spec in four ways: richer feature analysis (user journeys, edge cases, cross-feature dependencies), deeper architecture planning (schemas, security, scalability), broader risk assessment (technical, security, compliance), and a fuller implementation roadmap (critical path, resourcing, handoffs). If you're choosing between the two, see [Fast vs Deep Specs](/coding-agent/specifications/fast-vs-deep) — the short version: reach for Deep Spec on complex, multi-team, or compliance-heavy systems. ## Code Examples ### cURL - Enterprise Healthcare Platform ```bash theme={null} curl -X POST https://api.pre.dev/deep-spec \ -H "Content-Type: application/json" \ -H "Authorization: Bearer YOUR_API_KEY" \ -d '{ "input": "Build an enterprise healthcare management platform with patient records, appointment scheduling, billing, insurance processing, telemedicine capabilities, and HIPAA compliance for a multi-location hospital system with 500+ providers.", }' ``` ### Python - Financial Services Platform ```python theme={null} import requests response = requests.post( 'https://api.pre.dev/deep-spec', headers={ 'Content-Type': 'application/json', 'Authorization': 'Bearer YOUR_API_KEY' }, json={ 'input': 'Build a fintech platform with banking services, investment management, cryptocurrency trading, regulatory compliance (SEC, FINRA), and real-time market data integration for retail and institutional investors.', 'async': True # Deep specs benefit from async processing } ) result = response.json() print(f"Spec ID: {result['specId']}") ``` ### JavaScript - Complex SaaS Application ```javascript theme={null} const response = await fetch('https://api.pre.dev/deep-spec', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer YOUR_API_KEY' }, body: JSON.stringify({ input: 'Build a comprehensive SaaS project management platform with advanced workflow automation, AI-powered insights, enterprise integrations, multi-tenant architecture, and real-time collaboration for teams of 1000+ users.', async: true }) }); const result = await response.json(); console.log(`Spec ID: ${result.specId}`); ``` ## Deep Spec Output Structure ### 1. Executive Summary & Business Case * Detailed problem statement and solution approach * Success metrics and KPIs * Stakeholder analysis * High-level timeline and milestones ### 2. Comprehensive Feature Catalog * Detailed feature specifications with user stories * Complex workflow documentation * Integration requirements mapping * Third-party service dependencies ### 3. Enterprise Architecture Design * System architecture diagrams * Database design specifications * API design and integration patterns * Security architecture blueprint ### 4. Implementation Strategy * Detailed development phases with dependencies * Critical path identification * Risk mitigation strategies * Quality assurance approach ### 5. Operational Considerations * Deployment strategy and environment planning * Monitoring and alerting requirements * Backup and disaster recovery planning * Support and maintenance guidelines ## Documentation Scraping & Archives ### Overview When you provide `docURLs` in your request, Architect automatically scrapes the documentation in parallel with spec generation and packages it into downloadable ZIP archives. This feature helps AI agents and developers have context about external APIs, design systems, or frameworks referenced in the spec. ### How It Works 1. **Parallel Processing:** Documentation scraping runs simultaneously with spec generation (not sequentially), so it doesn't slow down your request 2. **Graceful Degradation:** If documentation scraping fails, spec generation still completes successfully 3. **Organized Archives:** Each platform gets its own ZIP with hierarchical folder structure based on the documentation site ### Response Field: `zippedDocsUrls` ```typescript theme={null} interface ZippedDocsUrl { platform: string; // Hostname extracted from doc URL (e.g., "stripe.com", "docs.github.com") masterZipShortUrl: string; // Short URL to download the ZIP archive masterMarkdownShortUrl?: string; // Optional: consolidated markdown file } ``` ### Example Request with Documentation URLs ```json theme={null} { "input": "Build a payment processing system with Stripe integration", "docURLs": [ "https://stripe.com/docs/api", "https://stripe.com/docs/payments", "https://docs.github.com/en/rest" ] } ``` ### Example Response with Documentation Archives ```json theme={null} { "endpoint": "fast_spec", "codingAgentSpecUrl": "https://api.pre.dev/s/a6hFJRV6", "zippedDocsUrls": [ { "platform": "stripe.com", "masterZipShortUrl": "https://api.pre.dev/s/xyz789" }, { "platform": "docs.github.com", "masterZipShortUrl": "https://api.pre.dev/s/abc456" } ] } ``` ### ZIP Archive Structure Each ZIP archive contains: * Individual markdown files (one per scraped page) * Hierarchical folder structure mirroring the documentation site * Organized by documentation site structure ### Supported Domain Formats The system handles various domain formats: * `.com`, `.io`, `.org`, `.net` * `.cloud`, `.dev`, `.ai` * Country-specific TLDs (`.co.uk`, `.com.au`, etc.) * Newer TLDs (`.tech`, `.app`, etc.) ### Best Practices for Documentation URLs **Do:** * ✅ Provide specific documentation pages relevant to your spec * ✅ Include API documentation for integrations you're building * ✅ Reference design system docs for UI consistency * ✅ Use official documentation sources **Don't:** * ❌ Include general marketing pages * ❌ Link to blog posts instead of official documentation * ❌ Reference deprecated or outdated documentation * ❌ Link to non-documentation content ### Viewing Documentation Archives **Enterprise users** can view and download documentation archives from the API Usage Logs browser: 1. Navigate to [https://pre.dev/enterprise/dashboard?page=api](https://pre.dev/enterprise/dashboard?page=api) 2. Click on any API call to open the details modal 3. View the "Documentation Archives" section 4. Click download links to get the ZIP files ### Error Handling If documentation scraping fails: * `zippedDocsUrls` will be an empty array `[]` * Spec generation continues normally * No error is thrown (graceful degradation) If `docURLs` is not provided or is an empty array: * `zippedDocsUrls` will be an empty array `[]` * Spec generation proceeds normally ## Best Practices for Deep Spec ### Input Quality for Complex Projects * **Detailed business requirements** - Include specific compliance needs * **Technical constraints** - Existing systems, performance requirements * **Scale expectations** - User numbers, data volume, transaction rates * **Integration landscape** - Existing tools, APIs, third-party services * **Documentation URLs** - Provide comprehensive documentation for all external dependencies ### Planning for Enterprise Projects * **Allocate sufficient time** - Deep specs can take \~3-5 minutes * **Use async mode** for the best experience with complex inputs * **Review thoroughly** - Deep specs contain extensive detail requiring careful review * **Share with stakeholders** - Use as a comprehensive project brief * **Distribute documentation archives** - Ensure development team has complete context ### Cost Credits are charged per-inference based on actual token usage: \~10-50 credits for Deep Spec vs \~5-10 for Fast Spec. See [Plans & Credits](/coding-agent/plans-and-credits). Monitor async specification processing progress. # Generate Fast Spec Source: https://docs.pre.dev/architect-agent/api/fast-spec POST /fast-spec Complete documentation for the Fast Spec endpoint. Generate comprehensive project specifications in ~1 minute. Generate a quick, comprehensive project specification. ## Overview * **Cost:** Variable (typically \~5-10 credits based on complexity) * **Use Cases:** MVPs, prototypes, rapid iteration * **Processing Time:** \~1 minute (sync) or instant return (async) * **Output:** Complete feature breakdown, architecture, milestones ## Endpoint ``` POST https://api.pre.dev/fast-spec ``` ## Headers **For JSON requests:** ``` Content-Type: application/json Authorization: Bearer YOUR_API_KEY ``` **For file upload requests:** ``` Content-Type: multipart/form-data Authorization: Bearer YOUR_API_KEY ``` ## Request Body ### Parameters **For JSON requests:** | Parameter | Type | Required | Description | | ---------------- | --------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `input` | string | ✅ | Description of what you want to build | | `currentContext` | string | ❌ | **CRITICAL:** Existing project/codebase context. When provided, generates feature addition spec. When omitted, generates full new project spec with setup, deployment, docs, maintenance | | `docURLs` | string\[] | ❌ | **Optional:** Array of documentation URLs that Architect will reference when generating specifications. Useful for API documentation, design systems, or existing project docs | | `async` | boolean | ❌ | `false` (default) - wait for completion, or `true` - return immediately with `specId` for status polling | **For file upload requests (multipart/form-data):** | Parameter | Type | Required | Description | | --------- | --------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `file` | File | ❌ | **Optional:** File to be parsed as input (e.g., existing code, documentation, requirements). Can be used alone or combined with `input` text | | `input` | string | ❌ | **Optional:** Additional text description when using file upload. Can be empty string if using only file | | `docURLs` | string\[] | ❌ | **Optional:** Array of documentation URLs that Architect will reference when generating specifications. Useful for API documentation, design systems, or existing project docs | | `async` | boolean | ❌ | `false` (default) - wait for completion, or `true` - return immediately with `specId` for status polling | ### Understanding `currentContext` **Omit `currentContext` (New Project):** ```json theme={null} { "input": "Build a task management SaaS" } ``` **Generates:** Complete new project including: * Initial setup and scaffolding * Deployment configuration * Documentation structure * Support and maintenance guidelines * Infrastructure setup * CI/CD pipelines * Monitoring and logging **Provide `currentContext` (Feature Addition):** ```json theme={null} { "input": "Add real-time notifications and activity feed", "currentContext": "Existing Next.js task management app with Supabase, has auth, task CRUD, team features" } ``` **Generates:** Incremental feature spec including: * New features only (respects existing architecture) * Integration points with current codebase * Migration considerations * No redundant setup/deployment (already exists) ### Example: New Project ```json theme={null} { "input": "Build a SaaS project management tool with team collaboration, real-time updates, task tracking, and time logging. Include user authentication and role-based permissions.", } ``` ### Example: Feature Addition ```json theme={null} { "input": "Add a calendar view and Gantt chart visualization to the existing project management tool", "currentContext": "We have a task management system with list and board views, user auth, and basic team features", } ``` ### Example: Async Request ```json theme={null} { "input": "Build a comprehensive e-commerce platform with inventory management", "async": true } ``` ### Example: With Documentation URLs ```json theme={null} { "input": "Build a customer support ticketing system with priority levels and file attachments", "docURLs": [ "https://docs.pre.dev", "https://docs.stripe.com" ] } ``` ### Example: With File Upload ```javascript theme={null} // Prepare file upload const formData = new FormData(); formData.append('file', fileInput.files[0]); // fileInput is your HTML file input formData.append('input', ''); formData.append('docURLs', JSON.stringify(["https://docs.pre.dev"])); const response = await fetch('https://api.pre.dev/fast-spec', { method: 'POST', headers: { 'Authorization': 'Bearer YOUR_API_KEY' }, body: formData }); ``` ### Example: File Upload with Additional Context ```javascript theme={null} // Upload a requirements document and add context const formData = new FormData(); formData.append('file', requirementsFile); // PDF or text file with requirements formData.append('input', 'Please focus on the authentication and user management features from the uploaded requirements document'); formData.append('docURLs', JSON.stringify(["https://docs.pre.dev/auth"])); ``` ## Response ### Success Response (Sync Mode) ```json theme={null} { "endpoint": "fast_spec", "input": "Build a SaaS project management tool with team collaboration...", "status": "completed", "success": true, "humanSpecUrl": "https://api.pre.dev/s/a6hFJRV6", "codingAgentSpecUrl": "https://api.pre.dev/s/a6hFJRV7", "codingAgentSpecJson": { "executiveSummary": "A modern task management platform...", "coreFunctionalities": [ { "name": "Task CRUD", "description": "Create, read, update, delete tasks", "priority": "High" } ], "techStack": [ { "name": "React", "category": "Frontend" }, { "name": "Node.js", "category": "Backend" } ], "techStackGrouped": { "Frontend": ["React", "TailwindCSS"], "Backend": ["Node.js", "Express"] }, "milestones": [ { "milestoneNumber": 1, "description": "Core Task Management", "stories": [ { "id": "US-001", "title": "User can create a task", "acceptanceCriteria": ["Task form validates input", "Task saved to database"], "complexity": "M", "subTasks": [{ "id": "ST-001", "description": "Design task form UI", "complexity": "S" }] } ] } ] }, "codingAgentSpecMarkdown": "# Task Management App\\n\\n## Executive Summary\\n...", "humanSpecJson": { "executiveSummary": "A modern task management platform...", "personas": [{ "title": "Team Lead", "description": "Manages work allocation" }], "techStack": [{ "name": "PostgreSQL", "category": "Database" }], "techStackGrouped": { "Database": ["PostgreSQL"] }, "roles": [{ "name": "Full Stack Developer", "shortHand": "FSD" }], "totalHours": 120, "milestones": [ { "milestoneNumber": 1, "description": "Core Task Management", "hours": 40, "stories": [ { "id": "US-001", "title": "User can create a task", "hours": 8, "subTasks": [{ "description": "Implement task creation API", "hours": 3, "complexity": "M" }] } ] } ] }, "humanSpecMarkdown": "# Task Management App\\n\\n## Executive Summary\\n...", "architectureInfographicUrl": "https://res.cloudinary.com/dfvg7gm6w/image/upload/v1765403270/infographics/arch_infographic_cfac141b_1765403269989_0.jpg", "executionTime": 38500, "predevUrl": "https://pre.dev/projects/abc123", "creditsUsed": 7, "zippedDocsUrls": [ { "platform": "stripe.com", "masterZipShortUrl": "https://api.pre.dev/s/xyz789" }, { "platform": "docs.github.com", "masterZipShortUrl": "https://api.pre.dev/s/abc456" } ] } ``` | Field | Type | Description | | ---------------------------- | ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `endpoint` | string | Endpoint used: `"fast_spec"` or `"deep_spec"` | | `input` | string | Original input text provided | | `status` | string | Completion status: `"completed"` when successful | | `success` | boolean | Whether the request succeeded | | `humanSpecUrl` | string | URL where the human-readable spec is hosted (downloadable markdown) | | `humanSpecMarkdown` | string | Full markdown SOW content (human review) | | `humanSpecJson` | object | Full structured SOW JSON with hours, personas, roles | | `totalHumanHours` | number | Estimated total hours for a human to implement the spec | | `architectureInfographicUrl` | string | URL to a visual architecture infographic/diagram for the specification | | `codingAgentSpecUrl` | string | URL where the coding agent spec format is hosted (downloadable markdown) | | `codingAgentSpecMarkdown` | string | Simplified markdown SOW for AI coding tools | | `codingAgentSpecJson` | object | Simplified structured SOW JSON for AI coding tools | | `executionTime` | number | Processing time in milliseconds | | `predevUrl` | string | pre.dev project URL where you can view and edit the spec | | `creditsUsed` | number | Total credits consumed by this spec generation. Available in real-time during processing and persisted on completion. Typical values: Fast spec \~5-10, Deep spec \~10-50 | | `zippedDocsUrls` | array | Array of scraped documentation archives. Each object contains `platform` (hostname from the doc URL), `masterZipShortUrl` (download link to the ZIP archive), and optional `masterMarkdownShortUrl` (consolidated markdown). Empty array if no `docURLs` provided or scraping fails | ### Success Response (Async Mode) **Immediate response when `async: true`:** ```json theme={null} { "specId": "507f1f77bcf86cd799439011", "status": "pending" } ``` | Field | Type | Description | | -------- | ------ | -------------------------------------------------------------- | | `specId` | string | Unique ID to poll for status (use with `/spec-status/:specId`) | | `status` | string | Initial status: `"pending"` | **Poll `/spec-status/:specId` to check progress.** ### Async Status Flow 1. **Pending** → Initial queue state 2. **Processing** → Actively generating spec 3. **Completed** → Success, output available 4. **Failed** → Error occurred **Typical processing times:** * Fast Spec: \~1 minute * Deep Spec: \~3-5 minutes Poll every 10-15 seconds for best UX. ## Output Structure: Milestones → Stories Fast Spec follows a **two-level hierarchy** optimized for rapid development: ```markdown theme={null} ### - [ ] **Milestone 1**: User authentication and profile management - [ ] **User Registration** - (M): As a: new user, I want to: register an account with email and password, So that: I can access the platform - **Acceptance Criteria:** - [ ] User can register with valid email and password - [ ] Email verification sent upon registration - [ ] Duplicate emails handled gracefully - [ ] Password strength requirements enforced - [ ] **User Login** - (S): As a: registered user, I want to: log in securely, So that: I can access my account - **Acceptance Criteria:** - [ ] User can log in with correct credentials - [ ] Invalid credentials rejected with clear message - [ ] Session persists across browser tabs - [ ] Password reset option available - [ ] **User Profile** - (M): As a: registered user, I want to: manage my profile, So that: I can update my information - **Acceptance Criteria:** - [ ] User can view and edit profile details - [ ] Shipping addresses can be saved - [ ] Password can be changed with re-authentication - [ ] Account can be deactivated ``` **Key Characteristics:** * High-level milestones group related features * User stories with acceptance criteria * Complexity estimates (XS, S, M, L, XL) * ❌ No granular implementation subtasks ## Direct SOW Formats Fast Spec returns the Scope of Work directly in both JSON and Markdown, and also provides URL endpoints. The JSON is typed and split for coding agents vs. human reviewers. **Recommended usage** * Feed AI tools: `codingAgentSpecJson` or `codingAgentSpecMarkdown` * Human-readable UI/PDF: `humanSpecMarkdown` * Planning dashboards: `humanSpecJson.totalHours`, `humanSpecJson.roles` * Download links: `codingAgentSpecUrl` and `humanSpecUrl` ### Type definitions (shared by Fast and Deep Spec) **Coding Agent JSON (concise, no hours/personas/roles):** ```typescript theme={null} interface CodingAgentSpecJson { title?: string; executiveSummary: string; coreFunctionalities: SpecCoreFunctionality[]; techStack: SpecTechStackItem[]; techStackGrouped: Record; milestones: CodingAgentMilestone[]; } interface CodingAgentMilestone { milestoneNumber: number; description: string; stories: CodingAgentStory[]; } interface CodingAgentStory { id?: string; title: string; description?: string; acceptanceCriteria?: string[]; complexity?: string; subTasks: CodingAgentSubTask[]; } interface CodingAgentSubTask { id?: string; description: string; complexity: string; // "S" | "M" | "L" | "XL" } ``` **Human JSON (full detail with hours/personas/roles):** ```typescript theme={null} interface HumanSpecJson { title?: string; executiveSummary: string; coreFunctionalities: SpecCoreFunctionality[]; personas: SpecPersona[]; techStack: SpecTechStackItem[]; techStackGrouped: Record; milestones: HumanSpecMilestone[]; totalHours: number; roles: SpecRole[]; } interface HumanSpecMilestone { milestoneNumber: number; description: string; hours: number; stories: HumanSpecStory[]; } interface HumanSpecStory { id?: string; title: string; description?: string; acceptanceCriteria?: string[]; hours: number; complexity?: string; subTasks: HumanSpecSubTask[]; } interface HumanSpecSubTask { id?: string; description: string; hours: number; complexity: string; roles?: SpecRole[]; } interface SpecPersona { title: string; description: string; primaryGoals?: string[]; painPoints?: string[]; keyTasks?: string[]; } interface SpecRole { name: string; shortHand: string; } interface SpecCoreFunctionality { name: string; description: string; priority?: string; // "High" | "Medium" | "Low" } interface SpecTechStackItem { name: string; category: string; } ``` ## Code Examples ### cURL - Complete Flow **Synchronous Request:** ```bash theme={null} curl -X POST https://api.pre.dev/fast-spec \ -H "Content-Type: application/json" \ -H "Authorization: Bearer YOUR_API_KEY" \ -d '{ "input": "Build a real-time collaborative whiteboard with drawing tools, shapes, text, and team presence indicators" }' ``` **Asynchronous Request with Polling:** ```bash theme={null} # Step 1: Start async processing RESPONSE=$(curl -X POST https://api.pre.dev/fast-spec \ -H "Content-Type: application/json" \ -H "Authorization: Bearer YOUR_API_KEY" \ -d '{ "input": "Build a CRM with contact management, deal pipeline, and email integration", "async": true }') SPEC_ID=$(echo $RESPONSE | jq -r '.specId') # Step 2: Poll for status while true; do STATUS=$(curl https://api.pre.dev/spec-status/$SPEC_ID \ -H "Authorization: Bearer YOUR_API_KEY") STATE=$(echo $STATUS | jq -r '.status') if [ "$STATE" = "completed" ]; then echo "Spec ready!" echo $STATUS | jq -r '.codingAgentSpecUrl' break elif [ "$STATE" = "failed" ]; then echo "Processing failed" echo $STATUS | jq -r '.errorMessage' break fi echo "Status: $STATE - $(echo $STATUS | jq -r '.progress')" sleep 10 done ``` ### Python - Complete Implementation ```python theme={null} import requests import time from typing import Dict, Any class ArchitectAPI: def __init__(self, api_key: str): self.api_key = api_key self.base_url = "https://api.pre.dev" def generate_spec( self, input_text: str, current_context: str = None, async_mode: bool = False ) -> Dict[str, Any]: """Generate a fast spec.""" headers = { "Content-Type": "application/json", "Authorization": f"Bearer {self.api_key}" } payload = { "input": input_text, "async": async_mode } if current_context: payload["currentContext"] = current_context response = requests.post( f"{self.base_url}/fast-spec", headers=headers, json=payload ) response.raise_for_status() return response.json() def check_status(self, spec_id: str) -> Dict[str, Any]: """Check async processing status.""" headers = {"Authorization": f"Bearer {self.api_key}"} response = requests.get( f"{self.base_url}/spec-status/{spec_id}", headers=headers ) response.raise_for_status() return response.json() def wait_for_completion(self, spec_id: str, poll_interval: int = 10) -> Dict[str, Any]: """Wait for async processing to complete.""" while True: status = self.check_status(spec_id) if status["status"] == "completed": return status elif status["status"] == "failed": raise Exception(f"Processing failed: {status.get('errorMessage')}") print(f"Status: {status['status']} - {status.get('progress', 'Processing...')}") time.sleep(poll_interval) # Usage api = ArchitectAPI(api_key="YOUR_API_KEY") # Synchronous (wait for result) result = api.generate_spec( input_text="Build a fitness tracking app with workout logging, progress charts, and social features", ) print(f"Spec URL: {result['codingAgentSpecUrl']}") # Asynchronous (poll for result) response = api.generate_spec( input_text="Add AI meal planning and nutrition tracking to existing fitness app", current_context="Existing app has workout logging, user profiles, and basic social features built with React Native and Firebase", async_mode=True ) result = api.wait_for_completion(response["specId"]) print(f"Spec ready: {result['codingAgentSpecUrl']}") ``` ### JavaScript/Node.js - Complete Implementation ```javascript theme={null} const fetch = require('node-fetch'); class ArchitectAPI { constructor(apiKey) { this.apiKey = apiKey; this.baseUrl = 'https://api.pre.dev'; } async generateSpec({ input, currentContext = null, async = false }) { const headers = { 'Content-Type': 'application/json', 'Authorization': `Bearer ${this.apiKey}` }; const payload = { input, async }; if (currentContext) { payload.currentContext = currentContext; } const response = await fetch(`${this.baseUrl}/fast-spec`, { method: 'POST', headers, body: JSON.stringify(payload) }); if (!response.ok) { const error = await response.json(); throw new Error(error.message || 'API request failed'); } return response.json(); } async checkStatus(specId) { const headers = { 'Authorization': `Bearer ${this.apiKey}` }; const response = await fetch( `${this.baseUrl}/spec-status/${specId}`, { headers } ); if (!response.ok) { throw new Error('Failed to check status'); } return response.json(); } async waitForCompletion(specId, pollInterval = 10000) { while (true) { const status = await this.checkStatus(specId); if (status.status === 'completed') { return status; } else if (status.status === 'failed') { throw new Error(`Processing failed: ${status.errorMessage}`); } console.log(`Status: ${status.status} - ${status.progress || 'Processing...'}`); await new Promise(resolve => setTimeout(resolve, pollInterval)); } } } // Usage Examples // Synchronous (async () => { const api = new ArchitectAPI('YOUR_API_KEY'); try { const result = await api.generateSpec({ input: 'Build an e-learning platform with video courses, quizzes, certificates, and student progress tracking' }); console.log('Spec URL:', result.codingAgentSpecUrl); } catch (error) { console.error('Error:', error.message); } })(); // With Documentation URLs (async () => { const api = new ArchitectAPI('YOUR_API_KEY'); try { const result = await api.generateSpec({ input: 'Build a customer support ticketing system with priority levels and file attachments', docURLs: [ 'https://docs.pre.dev', 'https://docs.stripe.com' ] }); console.log('Spec URL:', result.codingAgentSpecUrl); } catch (error) { console.error('Error:', error.message); } })(); // With File Upload (async () => { const api = new ArchitectAPI('YOUR_API_KEY'); try { // For file uploads, use multipart/form-data const formData = new FormData(); formData.append('file', fileInput.files[0]); formData.append('input', 'Analyze the uploaded requirements document'); formData.append('docURLs', JSON.stringify(['https://docs.pre.dev'])); const response = await fetch(`${api.baseUrl}/fast-spec`, { method: 'POST', headers: { 'Authorization': `Bearer ${api.apiKey}` // Note: Don't set Content-Type for FormData - browser sets it automatically }, body: formData }); const result = await response.json(); console.log('Spec URL:', result.codingAgentSpecUrl); } catch (error) { console.error('Error:', error.message); } })(); // Asynchronous with polling (async () => { const api = new ArchitectAPI('YOUR_API_KEY'); try { // Start processing const response = await api.generateSpec({ input: 'Add gamification with points, badges, and leaderboards', currentContext: 'Existing e-learning platform with courses and progress tracking', async: true }); console.log('Spec ID:', response.specId); // Wait for completion const result = await api.waitForCompletion(response.specId); console.log('Spec ready:', result.codingAgentSpecUrl); } catch (error) { console.error('Error:', error.message); } })(); ``` ### TypeScript - Type-Safe Implementation ```typescript theme={null} interface SpecRequest { input: string; currentContext?: string; docURLs?: string[]; async?: boolean; } interface FileUploadRequest { file?: File; input?: string; docURLs?: string[]; async?: boolean; } interface SpecResponse { status: 'pending' | 'processing' | 'completed' | 'failed'; codingAgentSpecUrl?: string; codingAgentSpecMarkdown?: string; humanSpecUrl?: string; humanSpecMarkdown?: string; } interface AsyncResponse { specId: string; status: 'pending' | 'processing' | 'completed' | 'failed'; } interface ZippedDocsUrl { platform: string; masterZipShortUrl: string; masterMarkdownShortUrl?: string; } interface StatusResponse { _id?: string; created?: string; endpoint: 'fast_spec' | 'deep_spec'; input: string; status: 'pending' | 'processing' | 'completed' | 'failed'; success: boolean; uploadedFileShortUrl?: string; uploadedFileName?: string; humanSpecUrl?: string; totalHumanHours?: number; architectureInfographicUrl?: string; codingAgentSpecUrl?: string; executionTime?: number; predevUrl?: string; zippedDocsUrls?: ZippedDocsUrl[]; errorMessage?: string; creditsUsed?: number; // Total credits consumed (available during processing and on completion) progress?: number; // Overall progress percentage (0-100) progressMessage?: string; // Detailed progress message (e.g., "Generating User Stories...") } class ArchitectAPI { private apiKey: string; private baseUrl: string = 'https://api.pre.dev'; constructor(apiKey: string) { this.apiKey = apiKey; } async generateSpec(request: SpecRequest): Promise { const response = await fetch(`${this.baseUrl}/fast-spec`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${this.apiKey}` }, body: JSON.stringify(request) }); if (!response.ok) { const error = await response.json(); throw new Error(error.message || 'API request failed'); } return response.json(); } async checkStatus(specId: string): Promise { const response = await fetch(`${this.baseUrl}/spec-status/${specId}`, { headers: { 'Authorization': `Bearer ${this.apiKey}` } }); if (!response.ok) { throw new Error('Failed to check status'); } return response.json(); } async waitForCompletion(specId: string, pollInterval: number = 10000): Promise { while (true) { const status = await this.checkStatus(specId); if (status.status === 'completed') { return status; } else if (status.status === 'failed') { throw new Error(`Processing failed: ${status.errorMessage}`); } console.log(`${status.status}: ${status.progress || 'Processing...'}`); await new Promise(resolve => setTimeout(resolve, pollInterval)); } } } ``` ## What You Get The generated specification includes: * **Executive summary** * **Feature breakdown** by category * **Technical architecture** recommendations * **Implementation milestones** with effort estimates * **User stories** and acceptance criteria * **Task checklist** with progress tracking (status legend: `[ ]` → `[→]` → `[✓]` → `[⊘]`) * **Risk analysis** and considerations * **Markdown formatted** for direct agent use ## Using Task Tracking As your agent implements features, actively manage progress: 1. **Mark tasks in progress:** Change `[ ]` to `[→]` when starting 2. **Mark complete:** Change `[→]` to `[✓]` when done 3. **Mark skipped:** Change `[ ]` to `[⊘]` if skipping (with reason) Don't let your agent skip tasks without questioning why — it keeps implementation comprehensive and on-track. ## Documentation Scraping & Archives ### Overview When you provide `docURLs` in your request, Architect automatically scrapes the documentation in parallel with spec generation and packages it into downloadable ZIP archives. This feature helps AI agents and developers have context about external APIs, design systems, or frameworks referenced in the spec. ### How It Works 1. **Parallel Processing:** Documentation scraping runs simultaneously with spec generation (not sequentially), so it doesn't slow down your request 2. **Graceful Degradation:** If documentation scraping fails, spec generation still completes successfully 3. **Organized Archives:** Each platform gets its own ZIP with hierarchical folder structure based on the documentation site ### Response Field: `zippedDocsUrls` ```typescript theme={null} interface ZippedDocsUrl { platform: string; // Hostname extracted from doc URL (e.g., "stripe.com", "docs.github.com") masterZipShortUrl: string; // Short URL to download the ZIP archive masterMarkdownShortUrl?: string; // Optional: consolidated markdown file } ``` ### Example Request with Documentation URLs ```json theme={null} { "input": "Build a payment processing system with Stripe integration", "docURLs": [ "https://stripe.com/docs/api", "https://stripe.com/docs/payments", "https://docs.github.com/en/rest" ] } ``` ### Example Response with Documentation Archives ```json theme={null} { "endpoint": "fast_spec", "codingAgentSpecUrl": "https://api.pre.dev/s/a6hFJRV6", "zippedDocsUrls": [ { "platform": "stripe.com", "masterZipShortUrl": "https://api.pre.dev/s/xyz789" }, { "platform": "docs.github.com", "masterZipShortUrl": "https://api.pre.dev/s/abc456" } ] } ``` ### ZIP Archive Structure Each ZIP archive contains: * Individual markdown files (one per scraped page) * Hierarchical folder structure mirroring the documentation site * Organized by documentation site structure ### Supported Domain Formats The system handles various domain formats: * `.com`, `.io`, `.org`, `.net` * `.cloud`, `.dev`, `.ai` * Country-specific TLDs (`.co.uk`, `.com.au`, etc.) * Newer TLDs (`.tech`, `.app`, etc.) ### Best Practices for Documentation URLs **Do:** * ✅ Provide specific documentation pages relevant to your spec * ✅ Include API documentation for integrations you're building * ✅ Reference design system docs for UI consistency * ✅ Use official documentation sources **Don't:** * ❌ Include general marketing pages * ❌ Link to blog posts instead of official documentation * ❌ Reference deprecated or outdated documentation * ❌ Link to non-documentation content ### Viewing Documentation Archives **Enterprise users** can view and download documentation archives from the API Usage Logs browser: 1. Navigate to [https://pre.dev/enterprise/dashboard?page=api](https://pre.dev/enterprise/dashboard?page=api) 2. Click on any API call to open the details modal 3. View the "Documentation Archives" section 4. Click download links to get the ZIP files ### Error Handling If documentation scraping fails: * `zippedDocsUrls` will be an empty array `[]` * Spec generation continues normally * No error is thrown (graceful degradation) If `docURLs` is not provided or is an empty array: * `zippedDocsUrls` will be an empty array `[]` * Spec generation proceeds normally ## Best Practices ### Writing Effective Input * Be specific about core features * Include business context and constraints * Mention technical preferences if any ### Managing Your Agent * Actively interrupt to ensure tasks are checked off * Question every skipped task * Verify acceptance criteria before marking complete * Triple check that tests are written Generate ultra-detailed specifications for complex projects. # Find Specs Source: https://docs.pre.dev/architect-agent/api/find-specs GET /find-specs Search specs using regex patterns. Perfect for finding specs by keywords, patterns, or complex search criteria. Search for specifications using powerful regex patterns with optional status and endpoint filtering. ## Overview * **Cost:** Free (no credits required) * **Use Cases:** Keyword search, pattern matching, finding related specs * **Response Time:** Instant * **Search:** Case-insensitive regex matching against spec input text * **Returns:** Paginated array of matching specs ## Endpoint ``` GET https://api.pre.dev/find-specs ``` ## Headers ``` Authorization: Bearer YOUR_API_KEY ``` ## Query Parameters | Parameter | Type | Required | Default | Description | | ---------- | ------- | -------- | ------- | ------------------------------------------------------------------- | | `query` | string | ✅ | - | **REQUIRED** - Regex pattern to search (case-insensitive) | | `limit` | integer | ❌ | 20 | Results per page (1-100) | | `skip` | integer | ❌ | 0 | Number of records to skip for pagination | | `endpoint` | string | ❌ | - | Filter by endpoint: `fast_spec` or `deep_spec` | | `status` | string | ❌ | - | Filter by status: `pending`, `processing`, `completed`, or `failed` | ### Parameter Details **query** (REQUIRED) * Regex pattern matched against spec `input` field * Case-insensitive by default * Supports full regex syntax * Must be URL-encoded in request **limit** * Minimum: 1 * Maximum: 100 * Default: 20 **skip** * Minimum: 0 * Used for pagination **endpoint** * `fast_spec` - Only search Fast Spec generations * `deep_spec` - Only search Deep Spec generations **status** * `pending` - Only queued specs * `processing` - Only specs currently generating * `completed` - Only successfully finished specs * `failed` - Only failed generations ## Regex Pattern Examples | Pattern | What It Matches | Example Use Case | | ------------------ | ------------------------------ | ---------------------------------- | | `payment` | Contains "payment" (any case) | Find all payment-related specs | | `^Build` | Starts with "Build" | Find all "Build X" specs | | `platform$` | Ends with "platform" | Find platform projects | | `(API\|REST)` | Contains "API" OR "REST" | Find API-related specs | | `auth.*system` | "auth" followed by "system" | Find authentication systems | | `\d{3,}` | Contains 3+ consecutive digits | Find specs with quantities/budgets | | `saas\|sass` | Contains "saas" OR "sass" | Catch common misspellings | | `e-?commerce` | "ecommerce" or "e-commerce" | Match hyphen variations | | `task.*management` | "task" then "management" | Find task/project mgmt tools | | `real.?time` | "realtime" or "real time" | Match spacing variations | ## Response ### Success Response Same structure as `/list-specs`: ```json theme={null} { "specs": [ { "_id": "507f1f77bcf86cd799439011", "created": "2024-01-15T14:30:00.000Z", "endpoint": "fast_spec", "input": "Build a payment processing system with Stripe integration", "status": "completed", "success": true, "humanSpecUrl": "https://api.pre.dev/s/a6hFJRV6", "totalHumanHours": 120, "codingAgentSpecUrl": "https://api.pre.dev/s/a6hFJRV7", "executionTime": 38500 } ], "total": 8, "hasMore": false } ``` ### Response Fields Identical to the [list-specs endpoint](/architect-agent/api/list-specs#response-fields). See that documentation for complete field descriptions. ## Code Examples ### cURL Examples **Simple keyword search:** ```bash theme={null} curl -H "Authorization: Bearer YOUR_API_KEY" \ "https://api.pre.dev/find-specs?query=payment" ``` **Search with URL encoding:** ```bash theme={null} # Search for specs starting with "Build" curl -H "Authorization: Bearer YOUR_API_KEY" \ "https://api.pre.dev/find-specs?query=%5EBuild" ``` **Search completed specs only:** ```bash theme={null} curl -H "Authorization: Bearer YOUR_API_KEY" \ "https://api.pre.dev/find-specs?query=dashboard&status=completed" ``` **Search with OR condition:** ```bash theme={null} # Find specs containing "API" OR "REST" curl -H "Authorization: Bearer YOUR_API_KEY" \ "https://api.pre.dev/find-specs?query=(API%7CREST)" ``` **Complex pattern with pagination:** ```bash theme={null} # Find e-commerce specs (handles hyphen variations) curl -H "Authorization: Bearer YOUR_API_KEY" \ "https://api.pre.dev/find-specs?query=e-?commerce&limit=50&skip=0" ``` ### JavaScript/Node.js ```javascript theme={null} async function findSpecs(query, options = {}) { const { limit = 20, skip = 0, endpoint = null, status = null } = options; const params = new URLSearchParams({ query, limit: limit.toString(), skip: skip.toString() }); if (endpoint) params.append('endpoint', endpoint); if (status) params.append('status', status); const response = await fetch( `https://api.pre.dev/find-specs?${params}`, { headers: { 'Authorization': 'Bearer YOUR_API_KEY' } } ); if (!response.ok) { throw new Error(`API error: ${response.status}`); } return response.json(); } // Usage examples // Simple keyword search const paymentSpecs = await findSpecs('payment'); console.log(`Found ${paymentSpecs.total} payment specs`); // Search for specs starting with "Build" const buildSpecs = await findSpecs('^Build'); // Search with filters const dashboards = await findSpecs('dashboard', { status: 'completed', limit: 50 }); // Complex regex: find API or REST specs const apiSpecs = await findSpecs('(API|REST)'); // Search with pagination async function searchAllMatches(query) { let allMatches = []; let skip = 0; const limit = 50; while (true) { const response = await findSpecs(query, { skip, limit }); allMatches.push(...response.specs); if (!response.hasMore) break; skip += limit; } return allMatches; } // Search for e-commerce (with hyphen variation) const ecommerce = await findSpecs('e-?commerce'); // Find authentication systems const authSystems = await findSpecs('auth.*system'); ``` ### TypeScript ```typescript theme={null} interface FindSpecsOptions { limit?: number; skip?: number; endpoint?: 'fast_spec' | 'deep_spec'; status?: 'pending' | 'processing' | 'completed' | 'failed'; } interface SearchResult { specs: SpecObject[]; total: number; hasMore: boolean; query: string; } class SpecSearchClient { constructor(private apiKey: string) {} async findSpecs( query: string, options: FindSpecsOptions = {} ): Promise { const { limit = 20, skip = 0, endpoint, status } = options; const params = new URLSearchParams({ query, limit: limit.toString(), skip: skip.toString() }); if (endpoint) params.append('endpoint', endpoint); if (status) params.append('status', status); const response = await fetch( `https://api.pre.dev/find-specs?${params}`, { headers: { 'Authorization': `Bearer ${this.apiKey}` } } ); if (!response.ok) { throw new Error(`API error: ${response.status}`); } const data = await response.json(); return { ...data, query }; } async *searchPaginated( query: string, options: FindSpecsOptions = {} ): AsyncGenerator { let skip = 0; const limit = options.limit || 50; while (true) { const response = await this.findSpecs(query, { ...options, skip, limit }); if (response.specs.length === 0) break; yield response.specs; if (!response.hasMore) break; skip += limit; } } async searchWithHighlight( query: string, options: FindSpecsOptions = {} ): Promise> { const result = await this.findSpecs(query, options); // Add highlighting to matched text const regex = new RegExp(`(${query})`, 'gi'); return result.specs.map(spec => ({ ...spec, highlight: spec.input.replace(regex, '$1') })); } } // Usage const searchClient = new SpecSearchClient('YOUR_API_KEY'); // Simple search const results = await searchClient.findSpecs('payment', { status: 'completed' }); console.log(`Found ${results.total} completed payment specs`); // Paginated search for await (const batch of searchClient.searchPaginated('dashboard')) { console.log(`Processing ${batch.length} dashboard specs...`); batch.forEach(spec => console.log(` - ${spec.input}`)); } // Search with highlighting const highlighted = await searchClient.searchWithHighlight('payment'); highlighted.forEach(spec => { console.log(spec.highlight); // HTML with tags }); // Complex searches const apiOrRest = await searchClient.findSpecs('(API|REST)'); const startsWithBuild = await searchClient.findSpecs('^Build'); const hasRealtime = await searchClient.findSpecs('real.?time'); ``` ### Python ```python theme={null} import requests from typing import Optional, List, Dict, Any, Generator import urllib.parse class SpecSearchClient: def __init__(self, api_key: str): self.api_key = api_key self.base_url = 'https://api.pre.dev' def find_specs( self, query: str, limit: int = 20, skip: int = 0, endpoint: Optional[str] = None, status: Optional[str] = None ) -> Dict[str, Any]: """ Search specs using regex pattern. Args: query: Regex pattern to search (case-insensitive) limit: Number of results per page (1-100) skip: Number of records to skip endpoint: Filter by 'fast_spec' or 'deep_spec' status: Filter by 'pending', 'processing', 'completed', or 'failed' Returns: Dictionary with 'specs' array, 'total' count, and 'hasMore' flag """ params = { 'query': query, 'limit': limit, 'skip': skip } if endpoint: params['endpoint'] = endpoint if status: params['status'] = status response = requests.get( f'{self.base_url}/find-specs', params=params, headers={'Authorization': f'Bearer {self.api_key}'} ) response.raise_for_status() return response.json() def search_all( self, query: str, endpoint: Optional[str] = None, status: Optional[str] = None, batch_size: int = 50 ) -> List[Dict[str, Any]]: """Fetch all specs matching the search query.""" all_results = [] skip = 0 while True: response = self.find_specs( query=query, limit=batch_size, skip=skip, endpoint=endpoint, status=status ) all_results.extend(response['specs']) if not response['hasMore']: break skip += batch_size return all_results def search_paginated( self, query: str, endpoint: Optional[str] = None, status: Optional[str] = None, batch_size: int = 50 ) -> Generator[List[Dict[str, Any]], None, None]: """Generator that yields batches of search results.""" skip = 0 while True: response = self.find_specs( query=query, limit=batch_size, skip=skip, endpoint=endpoint, status=status ) if not response['specs']: break yield response['specs'] if not response['hasMore']: break skip += batch_size # Usage examples client = SpecSearchClient('YOUR_API_KEY') # Simple keyword search payment_specs = client.find_specs('payment') print(f"Found {payment_specs['total']} payment specs") # Search with filters dashboards = client.find_specs( 'dashboard', status='completed', limit=50 ) # Complex regex patterns api_specs = client.find_specs('(API|REST)') # OR condition build_specs = client.find_specs('^Build') # Starts with auth_systems = client.find_specs('auth.*system') # Pattern with wildcard # Search for e-commerce (handles hyphen variations) ecommerce = client.find_specs('e-?commerce') # Get all matches all_payment_specs = client.search_all('payment', status='completed') print(f"Total payment specs: {len(all_payment_specs)}") # Process in batches for batch in client.search_paginated('dashboard', batch_size=25): print(f"Processing {len(batch)} dashboard specs") for spec in batch: print(f" - {spec['input'][:60]}...") # Common search patterns def search_patterns(): """Examples of useful search patterns.""" # Find all SaaS projects saas_specs = client.find_specs('saas', status='completed') # Find real-time features (handles spacing) realtime = client.find_specs('real.?time') # Find specs with numbers (budgets, quantities) with_numbers = client.find_specs(r'\d{3,}') # Find authentication/authorization auth = client.find_specs('auth(entication|orization)?') # Find e-commerce variations ecommerce = client.find_specs('e-?commerce') return { 'saas': saas_specs['total'], 'realtime': realtime['total'], 'with_numbers': with_numbers['total'], 'auth': auth['total'], 'ecommerce': ecommerce['total'] } ``` ## Common Use Cases ### 1. Search Bar Implementation ```javascript theme={null} async function handleSearch(searchTerm, filters = {}) { try { // Escape special regex characters for literal search const escapedTerm = searchTerm.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); const results = await findSpecs(escapedTerm, { status: filters.status, endpoint: filters.endpoint, limit: 20 }); return { results: results.specs, total: results.total, hasMore: results.hasMore }; } catch (error) { console.error('Search failed:', error); return { results: [], total: 0, hasMore: false }; } } ``` ### 2. Find Related Specs ```python theme={null} def find_related_specs(base_spec_input: str, client: SpecSearchClient): """Find specs related to a given spec.""" # Extract key terms (simplified example) keywords = base_spec_input.lower().split()[:3] pattern = '|'.join(keywords) related = client.find_specs(pattern, limit=10) return related['specs'] ``` ### 3. Category-Based Search ```typescript theme={null} const CATEGORY_PATTERNS: Record = { ecommerce: 'e-?commerce|shop|store|cart', authentication: 'auth(entication|orization)?|login|signup', realtime: 'real.?time|websocket|live|streaming', payment: 'payment|billing|stripe|checkout', dashboard: 'dashboard|analytics|metrics|reporting', api: '(API|REST|GraphQL)', social: 'social|chat|messaging|comment', ai: '(AI|ML|machine.?learning|artificial.?intelligence)' }; async function searchByCategory(category: string) { const pattern = CATEGORY_PATTERNS[category]; if (!pattern) { throw new Error(`Unknown category: ${category}`); } return await searchClient.findSpecs(pattern, { status: 'completed', limit: 50 }); } ``` ### 4. Advanced Search with Multiple Criteria ```javascript theme={null} async function advancedSearch({ mustInclude = [], // All of these terms shouldInclude = [], // Any of these terms mustExclude = [], // None of these terms status = null, endpoint = null }) { // Build regex pattern let pattern = ''; if (mustInclude.length > 0) { // Positive lookahead for each required term pattern = mustInclude.map(term => `(?=.*${term})`).join(''); pattern += '.*'; } if (shouldInclude.length > 0) { pattern += `(${shouldInclude.join('|')})`; } // Note: mustExclude requires client-side filtering as regex negative lookahead // can be complex. Better to filter results after fetching. const results = await findSpecs(pattern || '.*', { status, endpoint }); // Client-side filtering for exclusions if (mustExclude.length > 0) { const excludeRegex = new RegExp(mustExclude.join('|'), 'i'); results.specs = results.specs.filter( spec => !excludeRegex.test(spec.input) ); results.total = results.specs.length; } return results; } // Usage const results = await advancedSearch({ mustInclude: ['task', 'management'], shouldInclude: ['team', 'collaboration'], mustExclude: ['deprecated'], status: 'completed' }); ``` ## Regex Tips & Tricks ### Common Patterns ```javascript theme={null} // Case variations 'saas|SaaS|SAAS' // Match any capitalization // Word boundaries '\\bapi\\b' // Match "api" as whole word only // Optional characters 'e-?commerce' // Match "ecommerce" or "e-commerce" 'real.?time' // Match "realtime" or "real time" // Character classes '[Pp]ayment' // Match "Payment" or "payment" 'task[- ]management' // Match "task management" or "task-management" // Quantifiers '\\d{3,}' // 3 or more digits 'feature.*flag' // "feature" then "flag" with anything between // Alternation '(dashboard|admin|panel)' // Match any of these // Start/End anchors '^Build' // Must start with "Build" 'platform$' // Must end with "platform" ``` ### URL Encoding When using cURL or constructing URLs directly, encode special characters: | Character | Encoded | Example Pattern | Encoded URL | | --------- | ------------ | ----------------- | ------------------------ | | `^` | `%5E` | `^Build` | `query=%5EBuild` | | `$` | `%24` | `platform$` | `query=platform%24` | | `\|` | `%7C` | `API\|REST` | `query=API%7CREST` | | `(` | `%28` | `(API\|REST)` | `query=%28API%7CREST%29` | | `)` | `%29` | `(API\|REST)` | `query=%28API%7CREST%29` | | Space | `%20` or `+` | `task management` | `query=task+management` | Most HTTP clients handle this automatically. ## Best Practices ### Search Patterns * Start with simple keywords, add complexity if needed * Use case-insensitive patterns (already default) * Handle common variations (hyphens, spaces, plural forms) * Test patterns before using in production ### Performance * Use specific patterns to reduce result sets * Combine with `status` and `endpoint` filters * Implement pagination for large result sets * Cache frequent searches ### User Experience * Show loading states during search * Display result counts * Highlight matched terms in results * Provide search suggestions or examples * Handle empty results gracefully ### Error Handling * Validate regex patterns client-side when possible * Catch and display API errors clearly * Provide fallback for invalid regex * Show helpful messages for no results ## Limitations * Search only matches against the `input` field * Maximum 100 results per request (use pagination for more) * Regex is case-insensitive by default * Very complex regex patterns may impact performance List all specs with pagination and filtering. # List Specs Source: https://docs.pre.dev/architect-agent/api/list-specs GET /list-specs List all specs with pagination and filtering. Perfect for displaying user spec history, recent specs, or filtered views. List all specifications with support for pagination and filtering by status or endpoint type. ## Overview * **Cost:** Free (no credits required) * **Use Cases:** Display spec history, build dashboards, monitor spec status * **Response Time:** Instant * **Returns:** Paginated array of specs with metadata ## Endpoint ``` GET https://api.pre.dev/list-specs ``` ## Headers ``` Authorization: Bearer YOUR_API_KEY ``` ## Query Parameters | Parameter | Type | Required | Default | Description | | ---------- | ------- | -------- | ------- | ------------------------------------------------------------------- | | `limit` | integer | ❌ | 20 | Results per page (1-100) | | `skip` | integer | ❌ | 0 | Number of records to skip for pagination | | `endpoint` | string | ❌ | - | Filter by endpoint: `fast_spec` or `deep_spec` | | `status` | string | ❌ | - | Filter by status: `pending`, `processing`, `completed`, or `failed` | ### Parameter Details **limit** * Minimum: 1 * Maximum: 100 * Default: 20 * Controls how many specs are returned per request **skip** * Minimum: 0 * Used for pagination (e.g., skip=20 for page 2 with limit=20) **endpoint** * `fast_spec` - Only show Fast Spec generations * `deep_spec` - Only show Deep Spec generations **status** * `pending` - Queued but not started * `processing` - Currently generating * `completed` - Successfully finished * `failed` - Generation failed ## Response ### Success Response ```json theme={null} { "specs": [ { "_id": "507f1f77bcf86cd799439011", "created": "2024-01-15T14:30:00.000Z", "endpoint": "fast_spec", "input": "Build a SaaS project management tool with team collaboration", "status": "completed", "success": true, "humanSpecUrl": "https://api.pre.dev/s/a6hFJRV6", "totalHumanHours": 120, "codingAgentSpecUrl": "https://api.pre.dev/s/a6hFJRV7", "executionTime": 38500, "predevUrl": "https://pre.dev/projects/abc123", }, { "_id": "507f1f77bcf86cd799439012", "created": "2024-01-15T12:15:00.000Z", "endpoint": "deep_spec", "input": "Build an enterprise healthcare platform with HIPAA compliance", "status": "processing", "success": false, "progress": 45, "progressMessage": "Generating architecture recommendations..." } ], "total": 42, "hasMore": true } ``` ### Response Fields | Field | Type | Description | | --------- | ------- | --------------------------------------------- | | `specs` | array | Array of spec objects (see Spec Object below) | | `total` | integer | Total number of specs matching the filters | | `hasMore` | boolean | Whether more pages are available | ### Spec Object Fields | Field | Type | Always Present | Description | | ---------------------- | ------- | -------------- | ------------------------------------------------------------------------ | | `_id` | string | ✅ | Unique spec identifier | | `created` | string | ✅ | ISO 8601 timestamp of creation | | `endpoint` | string | ✅ | `"fast_spec"` or `"deep_spec"` | | `input` | string | ✅ | Original input text | | `status` | string | ✅ | Current status | | `success` | boolean | ✅ | Whether generation succeeded | | `uploadedFileShortUrl` | string | ❌ | URL if file was uploaded | | `uploadedFileName` | string | ❌ | Name of uploaded file | | `humanSpecUrl` | string | ❌ | Human-readable spec URL (when completed) | | `totalHumanHours` | number | ❌ | Estimated total hours for a human to implement the spec (when completed) | | `codingAgentSpecUrl` | string | ❌ | Coding agent spec URL (when completed) | | `executionTime` | number | ❌ | Processing time in ms (when completed) | | `predevUrl` | string | ❌ | pre.dev project URL (when completed) | | `errorMessage` | string | ❌ | Error details (when failed) | | `progress` | number | ❌ | Completion percentage 0-100 (when processing) | | `progressMessage` | string | ❌ | Status message (when processing) | ## Code Examples ### cURL Examples **Get first 20 specs:** ```bash theme={null} curl -H "Authorization: Bearer YOUR_API_KEY" \ "https://api.pre.dev/list-specs" ``` **Get completed specs only:** ```bash theme={null} curl -H "Authorization: Bearer YOUR_API_KEY" \ "https://api.pre.dev/list-specs?status=completed" ``` **Paginate through results:** ```bash theme={null} # Page 1 (specs 0-19) curl -H "Authorization: Bearer YOUR_API_KEY" \ "https://api.pre.dev/list-specs?limit=20&skip=0" # Page 2 (specs 20-39) curl -H "Authorization: Bearer YOUR_API_KEY" \ "https://api.pre.dev/list-specs?limit=20&skip=20" # Page 3 (specs 40-59) curl -H "Authorization: Bearer YOUR_API_KEY" \ "https://api.pre.dev/list-specs?limit=20&skip=40" ``` **Get all deep specs:** ```bash theme={null} curl -H "Authorization: Bearer YOUR_API_KEY" \ "https://api.pre.dev/list-specs?endpoint=deep_spec" ``` **Get failed specs for debugging:** ```bash theme={null} curl -H "Authorization: Bearer YOUR_API_KEY" \ "https://api.pre.dev/list-specs?status=failed&limit=100" ``` **Combine filters:** ```bash theme={null} curl -H "Authorization: Bearer YOUR_API_KEY" \ "https://api.pre.dev/list-specs?endpoint=fast_spec&status=completed&limit=50" ``` ### JavaScript/Node.js ```javascript theme={null} async function listSpecs(options = {}) { const { limit = 20, skip = 0, endpoint = null, status = null } = options; const params = new URLSearchParams({ limit: limit.toString(), skip: skip.toString() }); if (endpoint) params.append('endpoint', endpoint); if (status) params.append('status', status); const response = await fetch( `https://api.pre.dev/list-specs?${params}`, { headers: { 'Authorization': 'Bearer YOUR_API_KEY' } } ); if (!response.ok) { throw new Error(`API error: ${response.status}`); } return response.json(); } // Usage examples // Get recent specs const recent = await listSpecs({ limit: 5 }); console.log(`Showing ${recent.specs.length} of ${recent.total} specs`); // Get completed specs only const completed = await listSpecs({ status: 'completed' }); // Paginate through all specs async function getAllSpecs() { let allSpecs = []; let skip = 0; const limit = 50; while (true) { const response = await listSpecs({ skip, limit }); allSpecs.push(...response.specs); if (!response.hasMore) break; skip += limit; } return allSpecs; } // Build pagination UI async function loadPage(pageNumber, pageSize = 20) { const skip = pageNumber * pageSize; const data = await listSpecs({ skip, limit: pageSize }); return { specs: data.specs, currentPage: pageNumber, totalPages: Math.ceil(data.total / pageSize), hasNext: data.hasMore }; } ``` ### TypeScript ```typescript theme={null} interface ListSpecsOptions { limit?: number; skip?: number; endpoint?: 'fast_spec' | 'deep_spec'; status?: 'pending' | 'processing' | 'completed' | 'failed'; } interface SpecObject { _id: string; created: string; endpoint: 'fast_spec' | 'deep_spec'; input: string; status: 'pending' | 'processing' | 'completed' | 'failed'; success: boolean; uploadedFileShortUrl?: string; uploadedFileName?: string; humanSpecUrl?: string; codingAgentSpecUrl?: string; executionTime?: number; predevUrl?: string; errorMessage?: string; progress?: number; progressMessage?: string; } interface ListSpecsResponse { specs: SpecObject[]; total: number; hasMore: boolean; } class SpecClient { constructor(private apiKey: string) {} async listSpecs(options: ListSpecsOptions = {}): Promise { const { limit = 20, skip = 0, endpoint, status } = options; const params = new URLSearchParams({ limit: limit.toString(), skip: skip.toString() }); if (endpoint) params.append('endpoint', endpoint); if (status) params.append('status', status); const response = await fetch( `https://api.pre.dev/list-specs?${params}`, { headers: { 'Authorization': `Bearer ${this.apiKey}` } } ); if (!response.ok) { throw new Error(`API error: ${response.status}`); } return response.json(); } async *paginateSpecs( options: ListSpecsOptions = {} ): AsyncGenerator { let skip = 0; const limit = options.limit || 20; while (true) { const response = await this.listSpecs({ ...options, skip, limit }); yield response.specs; if (!response.hasMore) break; skip += limit; } } } // Usage const client = new SpecClient('YOUR_API_KEY'); // Simple list const response = await client.listSpecs({ status: 'completed' }); console.log(`Found ${response.total} completed specs`); // Pagination generator for await (const specsPage of client.paginateSpecs({ limit: 50 })) { console.log(`Processing ${specsPage.length} specs...`); specsPage.forEach(spec => { console.log(`- ${spec.input.substring(0, 50)}...`); }); } ``` ### Python ```python theme={null} import requests from typing import Optional, List, Dict, Any, Generator class SpecClient: def __init__(self, api_key: str): self.api_key = api_key self.base_url = 'https://api.pre.dev' def list_specs( self, limit: int = 20, skip: int = 0, endpoint: Optional[str] = None, status: Optional[str] = None ) -> Dict[str, Any]: """ List specs with optional filtering and pagination. Args: limit: Number of results per page (1-100) skip: Number of records to skip endpoint: Filter by 'fast_spec' or 'deep_spec' status: Filter by 'pending', 'processing', 'completed', or 'failed' Returns: Dictionary with 'specs' array, 'total' count, and 'hasMore' flag """ params = {'limit': limit, 'skip': skip} if endpoint: params['endpoint'] = endpoint if status: params['status'] = status response = requests.get( f'{self.base_url}/list-specs', params=params, headers={'Authorization': f'Bearer {self.api_key}'} ) response.raise_for_status() return response.json() def get_all_specs( self, endpoint: Optional[str] = None, status: Optional[str] = None, batch_size: int = 50 ) -> List[Dict[str, Any]]: """Fetch all specs matching the filters.""" all_specs = [] skip = 0 while True: response = self.list_specs( limit=batch_size, skip=skip, endpoint=endpoint, status=status ) all_specs.extend(response['specs']) if not response['hasMore']: break skip += batch_size return all_specs def paginate_specs( self, endpoint: Optional[str] = None, status: Optional[str] = None, batch_size: int = 50 ) -> Generator[List[Dict[str, Any]], None, None]: """Generator that yields batches of specs.""" skip = 0 while True: response = self.list_specs( limit=batch_size, skip=skip, endpoint=endpoint, status=status ) if not response['specs']: break yield response['specs'] if not response['hasMore']: break skip += batch_size # Usage examples client = SpecClient('YOUR_API_KEY') # Get recent specs recent = client.list_specs(limit=5) print(f"Showing {len(recent['specs'])} of {recent['total']} specs") # Get all completed specs completed_specs = client.get_all_specs(status='completed') print(f"Found {len(completed_specs)} completed specs") # Process specs in batches for batch in client.paginate_specs(status='completed', batch_size=25): print(f"Processing batch of {len(batch)} specs") for spec in batch: print(f" - {spec['input'][:50]}...") # Filter by endpoint and status fast_completed = client.list_specs( endpoint='fast_spec', status='completed', limit=100 ) # Build pagination for UI def get_page(page_number: int, page_size: int = 20): skip = page_number * page_size response = client.list_specs(skip=skip, limit=page_size) return { 'specs': response['specs'], 'current_page': page_number, 'total_pages': (response['total'] + page_size - 1) // page_size, 'has_next': response['hasMore'] } # Display page 3 page_data = get_page(2, page_size=20) print(f"Page {page_data['current_page'] + 1} of {page_data['total_pages']}") ``` ## Common Use Cases ### 1. Display Recent Specs Dashboard ```javascript theme={null} async function getRecentSpecsForDashboard() { const response = await fetch( 'https://api.pre.dev/list-specs?limit=10', { headers: { 'Authorization': 'Bearer YOUR_API_KEY' } } ); const data = await response.json(); return data.specs.map(spec => ({ id: spec._id, title: spec.input.substring(0, 80) + '...', type: spec.endpoint === 'fast_spec' ? 'Fast' : 'Deep', status: spec.status, createdAt: new Date(spec.created), url: spec.humanSpecUrl })); } ``` ### 2. Monitor Failed Specs ```python theme={null} def check_failed_specs(client): """Check for failed specs in the last 24 hours.""" failed = client.list_specs(status='failed', limit=100) recent_failures = [] for spec in failed['specs']: created = datetime.fromisoformat(spec['created'].replace('Z', '+00:00')) if datetime.now(timezone.utc) - created < timedelta(hours=24): recent_failures.append({ 'id': spec['_id'], 'input': spec['input'], 'error': spec.get('errorMessage', 'Unknown error'), 'created': created }) return recent_failures ``` ### 3. Export Completed Specs ```javascript theme={null} async function exportCompletedSpecs() { const allCompleted = []; let skip = 0; const limit = 50; while (true) { const response = await fetch( `https://api.pre.dev/list-specs?status=completed&skip=${skip}&limit=${limit}`, { headers: { 'Authorization': 'Bearer YOUR_API_KEY' } } ); const data = await response.json(); allCompleted.push(...data.specs); if (!data.hasMore) break; skip += limit; } return allCompleted; } ``` ### 4. Build Pagination Component ```typescript theme={null} interface PaginationState { currentPage: number; pageSize: number; totalItems: number; items: SpecObject[]; } async function loadPage( pageNumber: number, pageSize: number, filters?: ListSpecsOptions ): Promise { const client = new SpecClient('YOUR_API_KEY'); const response = await client.listSpecs({ ...filters, skip: pageNumber * pageSize, limit: pageSize }); return { currentPage: pageNumber, pageSize, totalItems: response.total, items: response.specs }; } ``` ## Best Practices ### Pagination * Use reasonable page sizes (20-50 specs) * Cache results when appropriate * Show loading states while fetching ### Filtering * Combine filters to reduce result sets * Use `status=completed` for user-facing spec lists * Use `status=failed` for debugging/monitoring ### Performance * Don't fetch all specs at once if you have many * Use pagination for large datasets * Consider implementing infinite scroll with `skip` parameter ### Error Handling * Always check response status codes * Handle empty result sets gracefully * Show appropriate messages when no specs match filters Search specs using regex patterns for advanced filtering. # Spec Status Source: https://docs.pre.dev/architect-agent/api/spec-status GET /spec-status/{specId} Monitor the progress of asynchronous specification processing requests. Check the status of an asynchronous specification processing request. ## Overview When you make an async request (`"async": true`), use this endpoint to poll for completion status. ## Endpoint ``` GET https://api.pre.dev/spec-status/:specId ``` ## Parameters | Parameter | Location | Required | Description | | --------- | -------- | -------- | ------------------------------------------- | | `specId` | Path | ✅ | Spec ID returned from async spec processing | ## Example Request ```bash theme={null} curl https://api.pre.dev/spec-status/507f1f77bcf86cd799439011 \ -H "Authorization: Bearer YOUR_API_KEY" ``` The `specId` in the URL is the value returned as `specId` from the async spec generation request. ## Response ### Pending ```json theme={null} { "_id": "507f1f77bcf86cd799439011", "created": "2025-10-03T10:00:00Z", "endpoint": "fast_spec", "input": "Build a SaaS project management tool...", "status": "pending", "success": false, "progress": 0, "progressMessage": "Initializing..." } ``` ### Processing ```json theme={null} { "_id": "507f1f77bcf86cd799439011", "created": "2025-10-03T10:00:00Z", "endpoint": "fast_spec", "input": "Build a SaaS project management tool...", "status": "processing", "success": false, "progress": 45, "progressMessage": "Generating User Stories...", "creditsUsed": 3 } ``` ### Completed ```json theme={null} { "_id": "507f1f77bcf86cd799439011", "created": "2025-10-03T10:00:00Z", "endpoint": "fast_spec", "input": "Build a SaaS project management tool...", "status": "completed", "success": true, "humanSpecUrl": "https://api.pre.dev/s/a6hFJRV6", "totalHumanHours": 120, "architectureInfographicUrl": "https://res.cloudinary.com/dfvg7gm6w/image/upload/v1765403270/infographics/arch_infographic_cfac141b_1765403269989_0.jpg", "codingAgentSpecUrl": "https://api.pre.dev/s/a6hFJRV7", "codingAgentSpecJson": { "title": "Task Management App", "executiveSummary": "A modern task management application...", "coreFunctionalities": [{ "name": "Task CRUD", "description": "Create, read, update, delete tasks", "priority": "High" }], "techStack": [{ "name": "React", "category": "Frontend" }], "techStackGrouped": { "Frontend": ["React", "TailwindCSS"] }, "milestones": [{ "milestoneNumber": 1, "description": "Core Task Management", "stories": [] }] }, "codingAgentSpecMarkdown": "# Task Management App\n\n## Executive Summary\n...", "humanSpecJson": { "title": "Task Management App", "executiveSummary": "A modern task management application...", "coreFunctionalities": [{ "name": "Task CRUD", "description": "Create, read, update, delete tasks", "priority": "High" }], "personas": [{ "title": "Project Manager", "description": "Manages team tasks" }], "techStack": [{ "name": "React", "category": "Frontend" }], "techStackGrouped": { "Frontend": ["React", "TailwindCSS"] }, "milestones": [{ "milestoneNumber": 1, "description": "Core Task Management", "hours": 40, "stories": [] }], "totalHours": 120, "roles": [{ "name": "Full Stack Developer", "shortHand": "FSD" }] }, "humanSpecMarkdown": "# Task Management App\n\n## Executive Summary\n...", "executionTime": 38500, "predevUrl": "https://pre.dev/projects/abc123", "creditsUsed": 7, "progress": 100, "progressMessage": "Completed successfully", "userFlowGraph": { "nodes": [ { "id": "authentication", "label": "Authentication", "type": "flow", "level": 1 }, { "id": "dashboard", "label": "Dashboard", "type": "flow", "level": 2 }, { "id": "task_management", "label": "Task Management", "type": "flow", "level": 3 } ], "edges": [ { "source": "authentication", "target": "dashboard" }, { "source": "dashboard", "target": "task_management" } ] }, "architectureGraph": { "nodes": [ { "id": "web_main_app", "label": "React Web Application", "type": "frontend" }, { "id": "api_main_service", "label": "Node.js API Service", "type": "api-services" }, { "id": "db_primary", "label": "PostgreSQL Database", "type": "databases" } ], "edges": [ { "source": "web_main_app", "target": "api_main_service", "edgeType": "uses" }, { "source": "api_main_service", "target": "db_primary", "edgeType": "reads_writes" } ] }, "enrichedTechStack": [ { "name": "React", "useFor": "Frontend", "reason": "Component-based architecture ideal for building interactive task management UIs with real-time updates", "description": "A JavaScript library for building user interfaces with a virtual DOM for efficient rendering", "link": "https://react.dev", "alternatives": [{ "name": "Vue.js", "link": "https://vuejs.org", "description": "Progressive JavaScript framework" }] } ] } ``` ### Failed ```json theme={null} { "_id": "507f1f77bcf86cd799439011", "created": "2025-10-03T10:00:00Z", "endpoint": "fast_spec", "input": "Build a SaaS project management tool...", "status": "failed", "success": false, "errorMessage": "Invalid input format", "executionTime": 5000, "progress": 0, "progressMessage": "Failed to generate specification" } ``` ## Response Fields | Field | Type | Description | | ---------------------------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `_id` | string | MongoDB ObjectId of the spec request | | `created` | string | ISO timestamp when the request was created | | `endpoint` | string | Which endpoint was used: `"fast_spec"` or `"deep_spec"` | | `input` | string | Original input text provided | | `status` | string | Current status: `"pending"`, `"processing"`, `"completed"`, or `"failed"` | | `success` | boolean | Whether the request succeeded | | `uploadedFileShortUrl` | string | Short URL for uploaded file (if file was uploaded) | | `uploadedFileName` | string | Name of uploaded file (if file was uploaded) | | `humanSpecUrl` | string | URL where the human-readable spec is hosted - downloadable markdown (only when completed) | | `totalHumanHours` | number | Estimated total hours for a human to implement the spec (only when completed) | | `architectureInfographicUrl` | string | URL to a visual architecture infographic/diagram for the specification (only when completed) | | `codingAgentSpecUrl` | string | URL where the coding agent spec format is hosted - downloadable markdown (only when completed) | | `codingAgentSpecJson` | object | Structured JSON spec optimized for AI coding assistants (only when completed) | | `codingAgentSpecMarkdown` | string | Markdown spec optimized for AI coding assistants (only when completed) | | `humanSpecJson` | object | Full structured JSON spec with hours, personas, and roles (only when completed) | | `humanSpecMarkdown` | string | Full markdown spec with all details for human review (only when completed) | | `executionTime` | number | Processing time in milliseconds (only when completed or failed) | | `predevUrl` | string | pre.dev project URL where you can view and edit the spec (only when completed) | | `errorMessage` | string | Error description (only when failed) | | `creditsUsed` | number | Total credits consumed by this spec generation. Available in real-time during processing and persisted on completion. Typical values: Fast spec \~5-10, Deep spec \~10-50 | | `progress` | number | Overall progress percentage (0-100) | | `progressMessage` | string | Detailed progress message (e.g., "Generating User Stories...") | | `userFlowGraph` | object | User flow graph with `nodes` (id, label, type, description, level) and `edges` (source, target, edgeType). Nodes include a numeric `level` (1, 2, 3...) indicating graph depth for layered rendering (only when completed) | | `architectureGraph` | object | System architecture graph with `nodes` (id, label, type, description) and `edges` (source, target, edgeType). Node `type` is one of: `"frontend"`, `"api-services"`, `"databases"`, `"external-services"` (only when completed) | | `enrichedTechStack` | array | Enriched tech stack items with `name`, `useFor`, `reason`, `description`, `link`, `helpfulLinks`, and `alternatives` for each technology (only when completed) | ## Fetching the spec URLs `humanSpecUrl` and `codingAgentSpecUrl` are public short links (`https://api.pre.dev/s/...`). They need no auth header and return the document directly (markdown, or a zip for bundles): ```bash theme={null} curl https://api.pre.dev/s/a6hFJRV6 -o spec.md ``` The same content is also inlined in the response as `humanSpecMarkdown` / `codingAgentSpecMarkdown`, so you rarely need to fetch the URLs at all. ## Polling Best Practices ### Polling Interval * **Recommended:** Poll every 10-15 seconds * **Minimum:** Don't poll more frequently than every 5 seconds * **Maximum:** No need to poll more than every 30 seconds ### Example Polling Script ```bash theme={null} #!/bin/bash SPEC_ID="507f1f77bcf86cd799439011" API_KEY="YOUR_API_KEY" while true; do RESPONSE=$(curl -s https://api.pre.dev/spec-status/$SPEC_ID \ -H "Authorization: Bearer $API_KEY") STATUS=$(echo $RESPONSE | jq -r '.status') case $STATUS in "completed") echo "✅ Spec processing completed!" echo $RESPONSE | jq -r '.codingAgentSpecUrl' break ;; "failed") echo "❌ Spec processing failed:" echo $RESPONSE | jq -r '.errorMessage' break ;; "pending"|"processing") echo "$(date): $STATUS - $(echo $RESPONSE | jq -r '.progress')% - $(echo $RESPONSE | jq -r '.progressMessage')" sleep 10 ;; *) echo "Unknown status: $STATUS" break ;; esac done ``` ### Python Polling Example ```python theme={null} import requests import time from typing import Dict, Any def poll_spec_status(api_key: str, spec_id: str, poll_interval: int = 10) -> Dict[str, Any]: """Poll for spec processing completion.""" while True: response = requests.get( f'https://api.pre.dev/spec-status/{spec_id}', headers={'Authorization': f'Bearer {api_key}'} ) response.raise_for_status() data = response.json() status = data['status'] if status == 'completed': print("✅ Spec processing completed!") return data elif status == 'failed': print(f"❌ Spec processing failed: {data.get('errorMessage')}") raise Exception(f"Processing failed: {data.get('errorMessage')}") else: print(f"⏳ {status}: {data.get('progress', 0)}% - {data.get('progressMessage', 'Processing...')}") time.sleep(poll_interval) # Usage result = poll_spec_status("YOUR_API_KEY", "507f1f77bcf86cd799439011") print(f"Spec URL: {result['codingAgentSpecUrl']}") ``` ### JavaScript Polling Example ```javascript theme={null} async function pollSpecStatus(apiKey, specId, pollInterval = 10000) { while (true) { const response = await fetch( `https://api.pre.dev/spec-status/${specId}`, { headers: { 'Authorization': `Bearer ${apiKey}` } } ); if (!response.ok) { throw new Error('Failed to check status'); } const data = await response.json(); const status = data.status; if (status === 'completed') { console.log('✅ Spec processing completed!'); return data; } else if (status === 'failed') { console.error(`❌ Spec processing failed: ${data.errorMessage}`); throw new Error(`Processing failed: ${data.errorMessage}`); } else { console.log(`⏳ ${status}: ${data.progress || 0}% - ${data.progressMessage || 'Processing...'}`); await new Promise(resolve => setTimeout(resolve, pollInterval)); } } } // Usage try { const result = await pollSpecStatus('YOUR_API_KEY', '507f1f77bcf86cd799439011'); console.log(`Spec URL: ${result.codingAgentSpecUrl}`); } catch (error) { console.error('Error:', error.message); } ``` ## Expected Processing Times | Spec Type | Typical Time | Maximum Expected | | --------- | ------------- | ---------------- | | Fast Spec | \~1 minute | 2 minutes | | Deep Spec | \~3-5 minutes | 5 minutes | **Note:** Times can vary based on input complexity and system load. ## Error Handling ### Common Issues **Spec ID Not Found:** ```json theme={null} { "error": "Request not found", "message": "No request found with ID: 507f1f77bcf86cd799439011" } ``` *Cause:* Invalid spec ID or request expired **Unauthorized:** ```json theme={null} { "error": "Unauthorized", "message": "Invalid API key" } ``` *Cause:* Invalid or missing API key ## Best Practices ### User Experience * Show a loading indicator while polling * Display progress messages to users * Set a reasonable timeout (e.g., 30 minutes) * Provide a way to cancel or retry ### Rate Limiting * Respect the polling interval recommendations * Implement exponential backoff for retries * Handle rate limit responses gracefully ### Monitoring * Log polling attempts for debugging * Track completion times for performance monitoring * Alert on unusual failure rates View all available API endpoints. # MCP Setup (Architect API) Source: https://docs.pre.dev/architect-agent/mcp-setup Install the pre.dev MCP server into Cursor, Claude Code, VS Code, or Windsurf so your agent can call fast_spec and deep_spec. The pre.dev MCP server gives any AI coding agent production-ready planning: full specs, architecture, and sequenced roadmaps, generated before a line of code is written. ## Quick Start Make sure you're signed in. The MCP install will open a browser tab to ask which account (solo or enterprise organization) to authorize. Run this in your terminal: ```bash theme={null} claude mcp add --transport http predev https://api.pre.dev/mcp ``` A browser window opens — sign into pre.dev (if not already), pick which account or organization to authorize, and click **Approve**. Claude Code completes the handshake automatically. For troubleshooting, see the [Claude Code MCP documentation](https://docs.claude.com/en/docs/claude-code/mcp). Run this in your terminal: ```bash theme={null} code --add-mcp "{\"name\":\"predev\",\"url\":\"https://api.pre.dev/mcp\"}" ``` Restart VS Code. On first tool use, VS Code opens a browser tab to authorize — pick which account or organization to connect. For troubleshooting, see the [VS Code MCP documentation](https://code.visualstudio.com/docs/copilot/customization/mcp-servers). [ Add to Cursor](cursor://anysphere.cursor-deeplink/mcp/install?name=predev\&config=eyJ1cmwiOiJodHRwczovL2FwaS5wcmUuZGV2L21jcCJ9) Click the button to install. On first tool use Cursor opens a browser tab to authorize — pick which pre.dev account or organization to connect. Open your AI coding agent and try this command: ``` Use pre.dev to generate a spec for a task management app ``` If successful, you'll receive a comprehensive project specification! ## Why your agent needs it Coding agents drift on complex, multi-file projects when they plan as they go. The pre.dev MCP server front-loads the plan, so your agent builds against real architecture instead of improvising: * **Complete system designs** — database schemas, API contracts, component hierarchies * **Sequenced roadmaps** — milestones and stories your agent can execute in order * **Technology decisions** — auth, state management, and API choices made up front * **Shared context** — the same spec works across every tool that speaks MCP ## Available Tools **Cost:** \~5-10 credits (variable) | **Speed:** \~1 minute Quick project specifications perfect for rapid prototyping and MVP planning. ``` Use pre.dev fast_spec to generate a spec for: A social media app with real-time messaging, photo sharing, and user profiles ``` **Cost:** \~10-50 credits (variable) | **Speed:** \~3-5 minutes Comprehensive, detailed specifications ideal for enterprise projects and complex systems. ``` Use pre.dev deep_spec to generate a detailed spec for: An enterprise CRM with AI-powered lead scoring, automated workflows, and advanced analytics ``` ## Advanced Features Build on existing work by referencing previous specs or projects: ``` Use pre.dev deep_spec to add payment processing to this existing project: [existing_context_id] ``` The MCP will automatically: * Fetch your existing context * Validate permissions * Generate new specs that build on your previous work Automatically scrape and archive external documentation alongside spec generation. Simply reference documentation URLs in your request: ``` Use pre.dev deep_spec to generate a spec for a payment system with Stripe integration. Reference https://stripe.com/docs/api ``` **What you get:** * ✅ **Accurate Specs:** AI uses the documentation to generate precise integration specifications * ✅ **Documentation Archives:** Downloadable ZIP files containing all scraped documentation * ✅ **Organized by Platform:** Each documentation source gets its own well-structured archive * ✅ **Parallel Processing:** Documentation scraping runs simultaneously with spec generation (no slowdown) * ✅ **Graceful Fallback:** Spec generation completes even if documentation scraping fails **Enterprise users** can view and download documentation archives from the API Usage Logs in their dashboard. **Example with multiple docs:** ``` Use pre.dev deep_spec to generate a healthcare platform spec with HL7 FHIR integration and HIPAA compliance. Reference https://docs.hl7.org and https://www.hhs.gov/hipaa ``` You'll receive separate archives for HL7 and HIPAA documentation alongside your spec. ## Cost Management **Check Your Usage:** Visit [pre.dev/projects/key](https://pre.dev/projects/key) to view remaining credits, usage history, and upgrade options. **Out of Credits?** If you run out of credits, you'll see this message: ``` ❌ Insufficient Credits Available You have insufficient credits to generate a spec. ``` Visit [pre.dev/projects/key](https://pre.dev/projects/key) to upgrade your plan or purchase additional credits. ## Common Use Cases Perfect for MVPs and quick validation: ``` Use pre.dev fast_spec to generate a spec for: MVP of a food delivery app with restaurant listings, order tracking, and payment integration ``` Detailed specs for complex systems: ``` Use pre.dev deep_spec to generate a detailed spec for: Enterprise data analytics platform with real-time dashboards, multi-tenant architecture, and role-based access ``` Extend existing projects: ``` Use pre.dev deep_spec to add user authentication and authorization to this existing e-commerce project ``` Generate comprehensive documentation: ``` Use pre.dev deep_spec to generate technical documentation for: Microservices architecture with Docker, Kubernetes, and service mesh ``` ## Troubleshooting * Re-run `claude mcp add` (or the Cursor one-click) to redo the browser authorization * Make sure you're signed into the right pre.dev account in your browser before the consent page loads * If you're an enterprise admin, pick the correct organization on the consent page — each org has its own credit pool * Check that your subscription is active at [pre.dev/projects/key](https://pre.dev/projects/key) * Restart your editor after adding the MCP config * Verify the URL: `https://api.pre.dev/mcp` * Check JSON syntax in configuration # Architect API Source: https://docs.pre.dev/architect-agent/overview The planning brain for your coding agent. API + MCP. The **Architect API** is pre.dev's core planning engine, exposed as a standalone API and MCP server. Drop it into Cursor, Claude Code, Lovable, Bolt, or your own tooling — and any coding agent suddenly plans complex builds like a senior architect. **If the Coding Agent is "pre.dev builds your app," the Architect API is "your coding agent plans like pre.dev."** ## Lifecycle Send one natural-language prompt describing what you want built. Optionally attach context IDs from previous specs, docs URLs, or uploaded files. The Architect returns a structured spec: tech stack, system design, milestones, user stories, acceptance criteria, and (with Deep Spec) granular subtasks. Feed the spec to your coding agent. It now has the architectural context to build multi-file systems correctly on the first try. One `curl`, one API key — or install the MCP server into your editor. ## Two ways to call it `POST https://api.pre.dev/fast-spec` or `/deep-spec` with a Bearer token. Sync or async. Perfect for CI/CD, custom tooling, or SDK-based workflows. `https://api.pre.dev/mcp` — one-click install into Cursor, Claude Code, VS Code, or Windsurf. Your agent calls `fast_spec` / `deep_spec` as tools. ## When to use which | Use Case | Recommended | | ------------------------------------------------------ | -------------------------------------------------- | | Generate specs inside Cursor / Claude Code / Windsurf | **MCP Server** | | One-off spec for a feature you'll build manually | **MCP Server** | | Integrate spec generation into CI/CD | **REST API** | | Build custom tooling on top of pre.dev | **REST API + SDKs** | | Already using pre.dev's web app to build full projects | **[Coding Agent](/coding-agent/overview)** instead | ## Endpoints at a glance * **`POST /fast-spec`** — High-level plan in \~1 min (\~5–10 credits) * **`POST /deep-spec`** — Granular subtasks in \~3–5 min (\~10–50 credits) * **`GET /spec-status/:id`** — Poll async generation progress * **`GET /list-specs`** — List your generated specs * **`GET /find-specs`** — Search specs by content * **`GET /credits-balance`** — Check remaining credits See the full [API Reference](/architect-agent/api/fast-spec) or grab an [SDK](/architect-agent/sdks/overview). ## Quick example ```bash theme={null} curl -X POST https://api.pre.dev/fast-spec \ -H "Content-Type: application/json" \ -H "Authorization: Bearer YOUR_API_KEY" \ -d '{"input": "Build a task management app with team collaboration"}' ``` ## Explore | | | | ----------------------------------------------------------------------- | ------------------------------------------- | | [Quickstart](/architect-agent/quickstart) | Your first spec in under 5 minutes | | [MCP Setup](/architect-agent/mcp-setup) | Install into Cursor / Claude Code / VS Code | | [Understanding Specs](/coding-agent/specifications/understanding-specs) | What's inside a pre.dev spec | | [Fast vs Deep Spec](/coding-agent/specifications/fast-vs-deep) | Which endpoint to pick | | [API Reference](/architect-agent/api/fast-spec) | Full endpoint docs | | [SDKs](/architect-agent/sdks/overview) | TypeScript and Python | ## Why your coding agent needs it AI coding agents are powerful, but they struggle with complex, multi-file projects without proper architecture. Built-in planning modes give basic task decomposition but lack deep architectural context, miss implementation details, and don't reason about schemas, API contracts, or system boundaries. The Architect API equips your agent with: * ✅ **Enterprise-grade architecture** — complete system designs with schemas, contracts, and component hierarchies * ✅ **Implementation roadmaps** — sequenced build plans that guide your agent through complex projects * ✅ **Technology decisions** — pre-made architectural choices for auth, state, APIs, and more * ✅ **Full context** — your agent knows exactly what to build, how, and why # Quickstart Source: https://docs.pre.dev/architect-agent/quickstart Call your first Architect API spec in under 5 minutes. Pick the path that matches how you work: a one-line `curl`, an MCP install into your editor, or an SDK call. ## 1. Get your API key One click to copy your API key and see remaining credits. ## 2. Call the Architect ```bash theme={null} curl -X POST https://api.pre.dev/fast-spec \ -H "Content-Type: application/json" \ -H "Authorization: Bearer YOUR_API_KEY" \ -d '{"input": "Build a task management app with team collaboration"}' ``` You'll get back a structured spec with milestones, user stories, and architecture — in about a minute. [ Add to Cursor](cursor://anysphere.cursor-deeplink/mcp/install?name=predev\&config=eyJ1cmwiOiJodHRwczovL2FwaS5wcmUuZGV2L21jcCJ9) Click the button, restart Cursor. On first use a browser tab opens — sign in to pre.dev and pick which account or organization to authorize. Then ask: ``` Use pre.dev to generate a spec for a task management app with team collaboration ``` Full setup for Cursor / Claude Code / VS Code / Windsurf: [MCP Setup](/architect-agent/mcp-setup). ```bash theme={null} claude mcp add --transport http predev https://api.pre.dev/mcp ``` Your browser will open to authorize — pick which account or organization to connect. Then ask Claude: ``` Use pre.dev fast_spec to plan a task management app ``` ```bash theme={null} npm install predev-api ``` ```ts theme={null} import { PredevAPI } from 'predev-api'; const client = new PredevAPI({ apiKey: process.env.PREDEV_API_KEY }); const spec = await client.fastSpec({ input: 'Build a task management app with team collaboration', }); console.log(spec); ``` See [Node SDK](/architect-agent/sdks/node) for full docs. ```bash theme={null} pip install predev-api ``` ```python theme={null} import os from predev_api import PredevAPI client = PredevAPI(api_key=os.environ["PREDEV_API_KEY"]) spec = client.fast_spec(input_text="Build a task management app with team collaboration") print(spec) ``` See [Python SDK](/architect-agent/sdks/python) for full docs. ## 3. Hand the spec to your coding agent Whatever you got back is structured markdown (or JSON) your coding agent can consume directly. Paste it into Cursor's chat, drop it into Claude Code, or feed it to Lovable / Bolt. Your agent now has the architectural context to build the whole thing on the first pass. For a richer breakdown, use [`/deep-spec`](/architect-agent/api/deep-spec) instead — it adds granular subtasks and per-task acceptance criteria (\~3–5 minutes). *** ## What's next? Pick the right depth for your project. What's actually in a pre.dev spec. All endpoints, parameters, and response schemas. Install into every major AI editor. # Node SDK Source: https://docs.pre.dev/architect-agent/sdks/node TypeScript/Node.js client for the pre.dev Architect API - Generate comprehensive software specifications A TypeScript/Node.js client library for the pre.dev Architect API. Generate comprehensive software specifications using AI-powered analysis. ## Features * **Fast Spec**: Generate comprehensive specifications quickly - perfect for MVPs and prototypes * **Deep Spec**: Generate ultra-detailed specifications for complex systems with enterprise-grade depth * **Async Spec**: Non-blocking async methods for long-running requests * **Status Tracking**: Check the status of async specification generation requests * **Credits Management**: Check your remaining credits balance * **Full TypeScript Support**: Complete type definitions for better IDE support * **Error Handling**: Custom exceptions for different error scenarios * **Modern ES Modules**: Uses ES6+ import/export syntax ## Installation Install the pre.dev Node SDK using npm: ```bash theme={null} npm install predev-api ``` ## Quick Start ```typescript theme={null} import { PredevAPI } from 'predev-api'; // Initialize the predev client with your API key const predev = new PredevAPI({ apiKey: 'your_api_key_here' }); // Generate a fast specification const result = await predev.fastSpec({ input: 'Build a SaaS project management tool with team collaboration' }); console.log(result); ``` ## Authentication The Pre.dev API uses API key authentication. Get your API key from the [pre.dev dashboard](https://pre.dev/projects/key): ```typescript theme={null} const predev = new PredevAPI({ apiKey: 'your_api_key' }); ``` ## API Methods ### Synchronous Methods #### fastSpec() Generate a fast specification (\~1 minute, \~5-10 credits). ```typescript theme={null} const result = await predev.fastSpec({ input: 'Build a SaaS project management tool with real-time collaboration' }); ``` **Parameters:** * `options.input` **(required)**: `string` - Description of what you want to build * `options.currentContext` **(optional)**: `string` - Existing project context * `options.docURLs` **(optional)**: `string[]` - Documentation URLs to reference **Returns:** `Promise` object with complete specification data #### deepSpec() Generate a deep specification (\~3-5 minutes, \~10-50 credits). ```typescript theme={null} const result = await predev.deepSpec({ input: 'Build a healthcare platform with HIPAA compliance' }); ``` **Parameters:** Same as `fastSpec()` **Returns:** `Promise` object with comprehensive specification data ### Asynchronous Methods #### fastSpecAsync() Generate a fast specification asynchronously (returns immediately). ```typescript theme={null} const result = await predev.fastSpecAsync({ input: 'Build a comprehensive e-commerce platform' }); // Returns: { specId: "spec_123", status: "pending" } ``` **Parameters:** Same as `fastSpec()` **Returns:** `Promise` object with `specId` for polling #### deepSpecAsync() Generate a deep specification asynchronously (returns immediately). ```typescript theme={null} const result = await predev.deepSpecAsync({ input: 'Build a fintech platform with regulatory compliance' }); // Returns: { specId: "spec_456", status: "pending" } ``` **Parameters:** Same as `fastSpec()` **Returns:** `Promise` object with `specId` for polling ### Status Checking #### getSpecStatus() Check the status of an async specification generation request. ```typescript theme={null} const status = await predev.getSpecStatus('spec_123'); // Returns full SpecResponse with status: "pending" | "processing" | "completed" | "failed" ``` **Parameters:** * `specId` **(required)**: `string` - The specification ID from async methods **Returns:** `Promise` object with current status and data (when completed) ### Credits Management #### getCreditsBalance() Get the remaining credits balance for your API key. ```typescript theme={null} const balance = await predev.getCreditsBalance(); // Returns: { success: true, creditsRemaining: 450 } ``` **Parameters:** None **Returns:** `Promise` object with credits remaining **Example:** ```typescript theme={null} const balance = await predev.getCreditsBalance(); if (balance.creditsRemaining < 50) { console.log(`Low credits: ${balance.creditsRemaining} remaining`); } else { console.log(`Credits available: ${balance.creditsRemaining}`); } ``` ### Listing and Searching Specs #### listSpecs() List all specs with optional filtering and pagination. ```typescript theme={null} // Get first 20 specs const result = await predev.listSpecs(); // Get completed specs only const completed = await predev.listSpecs({ status: 'completed' }); // Paginate: get specs 20-40 const page2 = await predev.listSpecs({ skip: 20, limit: 20 }); // Filter by endpoint type const fastSpecs = await predev.listSpecs({ endpoint: 'fast_spec' }); ``` **Parameters:** * `params.limit` **(optional)**: `number` - Results per page (1-100, default: 20) * `params.skip` **(optional)**: `number` - Offset for pagination (default: 0) * `params.endpoint` **(optional)**: `"fast_spec" | "deep_spec"` - Filter by endpoint type * `params.status` **(optional)**: `"pending" | "processing" | "completed" | "failed"` - Filter by status **Returns:** `Promise` object with specs array and pagination metadata #### findSpecs() Search for specs using regex patterns. ```typescript theme={null} // Search for "payment" specs const paymentSpecs = await predev.findSpecs({ query: 'payment' }); // Search for specs starting with "Build" const buildSpecs = await predev.findSpecs({ query: '^Build' }); // Search: only completed specs mentioning "auth" const authSpecs = await predev.findSpecs({ query: 'auth', status: 'completed' }); // Complex regex: find SaaS or SASS projects const saasSpecs = await predev.findSpecs({ query: 'saas|sass' }); ``` **Parameters:** * `params.query` **(required)**: `string` - Regex pattern (case-insensitive) * `params.limit` **(optional)**: `number` - Results per page (1-100, default: 20) * `params.skip` **(optional)**: `number` - Offset for pagination (default: 0) * `params.endpoint` **(optional)**: `"fast_spec" | "deep_spec"` - Filter by endpoint type * `params.status` **(optional)**: `"pending" | "processing" | "completed" | "failed"` - Filter by status **Returns:** `Promise` object with matching specs and pagination metadata **Regex Pattern Examples:** \| Pattern | Matches | ||---------|---------| \| `payment` | "payment", "Payment", "make payment" | \| `^Build` | Specs starting with "Build" | \| `platform$` | Specs ending with "platform" | \| `(API\|REST)` | Either "API" or "REST" | \| `auth.*system` | "auth" then anything then "system" | \| `\\d{3,}` | 3+ digits (budgets, quantities) | \| `saas\|sass` | SaaS or SASS | ## File Upload Support All `fastSpec`, `deepSpec`, `fastSpecAsync`, and `deepSpecAsync` methods support optional file uploads. This allows you to provide architecture documents, requirements files, design mockups, RFPs (Request for Proposals), or other context files to improve specification generation. ### Browser/Web Environment ```typescript theme={null} // Using File input from HTML form const fileInput = document.querySelector('input[type="file"]'); const file = fileInput.files[0]; const result = await predev.fastSpec({ input: 'Generate specs based on this design document', file: file // Pass the File object directly }); ``` ### Node.js Environment ```typescript theme={null} import fs from 'fs'; // Method 1: Using file path (simplest) const result = await predev.fastSpec({ input: 'Build based on these requirements', file: { data: fs.readFileSync('requirements.pdf'), name: 'requirements.pdf' } }); // Method 2: Using file object const fileContent = fs.readFileSync('architecture.doc'); const result = await predev.deepSpec({ input: 'Create comprehensive specs', file: { data: fileContent, name: 'architecture.doc' } }); ``` ### Supported File Types * PDF documents (`*.pdf`) * Word documents (`*.doc`, `*.docx`) * Text files (`*.txt`) * Images (`*.jpg`, `*.png`, `*.jpeg`) ### Response with File Upload When you upload a file, the response includes: ```typescript theme={null} { uploadedFileName?: string; // Name of the uploaded file uploadedFileShortUrl?: string; // URL to access the file codingAgentSpecUrl?: string; // Spec optimized for AI systems humanSpecUrl?: string; // Spec optimized for humans // ... other fields } ``` ## Response Types ### AsyncResponse ```typescript theme={null} { specId: string; // Unique ID for polling (e.g., "spec_abc123") status: "pending" | "processing" | "completed" | "failed"; } ``` ### SpecResponse ```typescript theme={null} interface SpecResponse { // Basic info _id?: string; // Internal ID created?: string; // ISO timestamp endpoint: "fast_spec" | "deep_spec"; input: string; // Original input text status: "pending" | "processing" | "completed" | "failed"; success: boolean; uploadedFileShortUrl?: string; // URL to input file uploadedFileName?: string; // Name of input file // Output data (when completed) humanSpecUrl?: string; // URL to human-readable spec humanSpecMarkdown?: string; // Full markdown SOW for humans/clients humanSpecJson?: HumanSpecJson; // Full structured SOW JSON (hours/personas/roles) totalHumanHours?: number; // Estimated hours for human implementation codingAgentSpecUrl?: string; // URL to coding agent spec format codingAgentSpecMarkdown?: string; // Direct markdown SOW for AI tools codingAgentSpecJson?: CodingAgentSpecJson; // Direct structured SOW JSON for AI tools executionTime?: number; // Processing time in milliseconds // Integration URLs (when completed) predevUrl?: string; // Link to pre.dev project architectureInfographicUrl?: string; // Rendered architecture infographic zippedDocsUrls?: ZippedDocsUrl[]; // Downloadable doc bundles // Structured graphs (when completed) userFlowGraph?: SpecGraph; // User flow nodes + edges architectureGraph?: SpecGraph; // System architecture nodes + edges enrichedTechStack?: SpecEnrichedTechStackItem[]; // Tech choices with useFor/reason // Billing creditsUsed?: number; // Credits consumed (live during processing) // Error handling errorMessage?: string; // Error details if failed progress?: number; // Overall progress percentage (0-100) progressMessage?: string; // Detailed progress message (e.g., "Generating User Stories...") } interface CodingAgentSpecJson { title?: string; executiveSummary: string; coreFunctionalities: SpecCoreFunctionality[]; techStack: SpecTechStackItem[]; techStackGrouped: Record; milestones: CodingAgentMilestone[]; } interface CodingAgentMilestone { milestoneNumber: number; description: string; stories: CodingAgentStory[]; } interface CodingAgentStory { id?: string; title: string; description?: string; acceptanceCriteria?: string[]; complexity?: string; subTasks: CodingAgentSubTask[]; } interface CodingAgentSubTask { id?: string; description: string; complexity: string; // "S" | "M" | "L" | "XL" } interface HumanSpecJson { title?: string; executiveSummary: string; coreFunctionalities: SpecCoreFunctionality[]; personas: SpecPersona[]; techStack: SpecTechStackItem[]; techStackGrouped: Record; milestones: HumanSpecMilestone[]; totalHours: number; roles: SpecRole[]; } interface HumanSpecMilestone { milestoneNumber: number; description: string; hours: number; stories: HumanSpecStory[]; } interface HumanSpecStory { id?: string; title: string; description?: string; acceptanceCriteria?: string[]; hours: number; complexity?: string; subTasks: HumanSpecSubTask[]; } interface HumanSpecSubTask { id?: string; description: string; hours: number; complexity: string; roles?: SpecRole[]; } interface SpecPersona { title: string; description: string; primaryGoals?: string[]; painPoints?: string[]; keyTasks?: string[]; } interface SpecRole { name: string; shortHand: string; } interface SpecCoreFunctionality { name: string; description: string; priority?: string; // "High" | "Medium" | "Low" } interface SpecTechStackItem { name: string; category: string; } ``` ### ListSpecsResponse ```typescript theme={null} { specs: SpecResponse[]; // Array of spec objects total: number; // Total count of matching specs hasMore: boolean; // Whether more results are available } ``` ### CreditsBalanceResponse ```typescript theme={null} { success: boolean; creditsRemaining: number; } ``` ## Examples ### Generate Fast Spec ```typescript theme={null} import { PredevAPI } from 'predev-api'; const predev = new PredevAPI({ apiKey: 'your_api_key' }); const result = await predev.fastSpec({ input: 'Build a SaaS project management tool with team collaboration', }); console.log(`Specification URL: ${result.humanSpecUrl}`); ``` ### Generate Deep Spec with Context ```typescript theme={null} import { PredevAPI } from 'predev-api'; const predev = new PredevAPI({ apiKey: 'your_api_key' }); const result = await predev.deepSpec({ input: 'Add advanced analytics dashboard', currentContext: 'Existing e-commerce platform with user auth and product catalog', }); console.log(result.codingAgentSpecUrl); ``` ### With Documentation URLs ```typescript theme={null} import { PredevAPI } from 'predev-api'; const predev = new PredevAPI({ apiKey: 'your_api_key' }); const result = await predev.fastSpec({ input: 'Build a customer support ticketing system', docURLs: ['https://docs.pre.dev', 'https://docs.stripe.com'], }); ``` ### Async Workflow with Polling ```typescript theme={null} import { PredevAPI } from 'predev-api'; const predev = new PredevAPI({ apiKey: 'your_api_key' }); async function generateSpec() { // Start async generation const asyncResult = await predev.fastSpecAsync({ input: 'Build a social media platform', }); console.log(`Spec ID: ${asyncResult.specId}`); // Poll for completion let status; while (true) { status = await predev.getSpecStatus(asyncResult.specId); console.log(`Status: ${status.status}`); if (status.status === 'completed' || status.status === 'failed') { break; } await new Promise(resolve => setTimeout(resolve, 5000)); } if (status.status === 'completed') { console.log(`Specification URL: ${status.codingAgentSpecUrl}`); } } generateSpec(); ``` ### List and Filter Specs ```typescript theme={null} import { PredevAPI } from 'predev-api'; const predev = new PredevAPI({ apiKey: 'your_api_key' }); // Get all completed specs const completed = await predev.listSpecs({ status: 'completed', limit: 50 }); console.log(`Total completed specs: ${completed.total}`); completed.specs.forEach(spec => { console.log(`- ${spec.input} (${spec.endpoint})`); }); ``` ### Search Specs with Regex ```typescript theme={null} import { PredevAPI } from 'predev-api'; const predev = new PredevAPI({ apiKey: 'your_api_key' }); // Find all payment-related specs const paymentSpecs = await predev.findSpecs({ query: 'payment|checkout|billing', status: 'completed', limit: 20 }); console.log(`Found ${paymentSpecs.total} payment-related specs`); ``` ### Check Credits Balance ```typescript theme={null} import { PredevAPI } from 'predev-api'; const predev = new PredevAPI({ apiKey: 'your_api_key' }); // Get current credit balance const balance = await predev.getCreditsBalance(); console.log(`Credits remaining: ${balance.creditsRemaining}`); // Check before making expensive request if (balance.creditsRemaining >= 50) { const result = await predev.deepSpec({ input: 'Build an enterprise platform' }); console.log(`Spec ready: ${result.codingAgentSpecUrl}`); } else { console.log(`Insufficient credits. Need 50, have ${balance.creditsRemaining}`); } ``` ## Error Handling All SDK errors inherit from `PredevAPIError`. Typed subclasses map to HTTP status codes: | Exception | HTTP | When | | --------------------------- | ----- | ----------------------------------------------------------------------------------- | | `AuthenticationError` | 401 | Missing or invalid API key | | `SubscriptionRequiredError` | 402 | Endpoint needs an active subscription | | `InsufficientCreditsError` | 402 | Not enough credits — top up at [pre.dev/projects/key](https://pre.dev/projects/key) | | `BatchTooLargeError` | 400 | Request exceeds size limits | | `QueueFullError` | 429 | Per-user in-flight queue is full — retry later | | `RateLimitError` | 429 | Too many requests — back off and retry | | `PredevAPIError` | other | Any other API error (has `.statusCode`) | ```typescript theme={null} import { PredevAPI, AuthenticationError, InsufficientCreditsError, RateLimitError, PredevAPIError, } from 'predev-api'; const predev = new PredevAPI({ apiKey: process.env.PREDEV_API_KEY! }); try { const spec = await predev.fastSpec({ input: 'Build a task management app' }); } catch (err) { if (err instanceof AuthenticationError) { console.error('Check your API key at pre.dev/projects/key'); } else if (err instanceof InsufficientCreditsError) { console.error('Out of credits:', err.message); } else if (err instanceof RateLimitError) { console.error('Rate limited - retry with backoff'); } else if (err instanceof PredevAPIError) { console.error(`API error (${err.statusCode}):`, err.message); } else { throw err; } } ``` ## Documentation For more information about the Pre.dev Architect API, visit: * [API Documentation](https://docs.pre.dev/) * [pre.dev Website](https://pre.dev/) * [npm Package](https://www.npmjs.com/package/predev-api) ## Support For issues, questions, or contributions: * [GitHub Repository](https://github.com/predotdev/predev-api) * [Discord Community](https://discord.com/invite/ejVTRJ6WXS) # Architect API SDKs Source: https://docs.pre.dev/architect-agent/sdks/overview pre.dev SDKs are wrappers around the pre.dev Architect API to help you easily generate comprehensive software specifications ## Official SDKs Explore the Python SDK for pre.dev Architect API - perfect for Python developers Explore the Node.js SDK for pre.dev Architect API - TypeScript-first with full type support ## Features All pre.dev SDKs provide: * **Fast Spec Generation**: Comprehensive specifications in \~1 minute (\~5-10 credits) * **Deep Spec Generation**: Ultra-detailed specs in \~3-5 minutes (\~10-50 credits) * **Status Tracking**: Check the status of async specification generation requests * **Type Safety**: Full type definitions for better IDE support * **Error Handling**: Custom exceptions for different error scenarios # Python SDK Source: https://docs.pre.dev/architect-agent/sdks/python Python client for the pre.dev Architect API - Generate comprehensive software specifications A Python client library for the pre.dev Architect API. Generate comprehensive software specifications using AI-powered analysis. ## Features * **Fast Spec**: Generate comprehensive specifications quickly - perfect for MVPs and prototypes * **Deep Spec**: Generate ultra-detailed specifications for complex systems with enterprise-grade depth * **Async Spec**: Non-blocking async methods for long-running requests * **Status Tracking**: Check the status of async specification generation requests * **List & Search**: Discover, filter, and search through your specification history * **Credits Management**: Check your remaining credits balance * **Type Hints**: Full type annotations for better IDE support * **Error Handling**: Custom exceptions for different error scenarios ## Installation Install the pre.dev Python SDK using pip: ```bash theme={null} pip install predev-api ``` ## Quick Start ```python theme={null} from predev_api import PredevAPI # Initialize the predev client with your API key predev = PredevAPI(api_key="your_api_key_here") # Generate a fast specification result = predev.fast_spec( input_text="Build a task management app with team collaboration" ) print(result) ``` ## Authentication The pre.dev API uses API key authentication. Get your API key from the [pre.dev dashboard](https://pre.dev/projects/key): ```python theme={null} predev = PredevAPI(api_key="your_api_key") ``` ## API Methods ### Synchronous Methods #### Fast Spec Generation Generate a fast specification (\~1 minute, \~5-10 credits). ```python theme={null} result = predev.fast_spec( input_text="Build a SaaS project management tool with real-time collaboration", current_context=None, # Optional: existing project context doc_urls=None # Optional: documentation URLs to reference ) ``` **Parameters:** * `input_text` **(required)**: `str` - Description of what you want to build * `current_context` **(optional)**: `str` - Existing project context * `doc_urls` **(optional)**: `List[str]` - Documentation URLs to reference **Returns:** `SpecResponse` object with complete specification data **Example:** ```python theme={null} result = predev.fast_spec( input_text="Build a SaaS project management tool with real-time collaboration" ) ``` #### Deep Spec Generation Generate a deep specification (\~3-5 minutes, \~10-50 credits). ```python theme={null} result = predev.deep_spec( input_text="Build a healthcare platform with HIPAA compliance", current_context=None, # Optional: existing project context doc_urls=None # Optional: documentation URLs ) ``` **Parameters:** Same as `fast_spec` **Returns:** `SpecResponse` object with comprehensive specification data **Example:** ```python theme={null} result = predev.deep_spec( input_text="Build a healthcare platform with HIPAA compliance" ) ``` ### Asynchronous Methods #### Fast Spec Async Generate a fast specification asynchronously (returns immediately). ```python theme={null} result = predev.fast_spec_async( input_text="Build a comprehensive e-commerce platform" ) # Returns: AsyncResponse(specId="spec_123", status="pending") ``` **Parameters:** Same as `fast_spec` **Returns:** `AsyncResponse` object with `specId` for polling #### Deep Spec Async Generate a deep specification asynchronously (returns immediately). ```python theme={null} result = predev.deep_spec_async( input_text="Build a fintech platform with regulatory compliance" ) # Returns: AsyncResponse(specId="spec_456", status="pending") ``` **Parameters:** Same as `fast_spec` **Returns:** `AsyncResponse` object with `specId` for polling ### Status Checking #### Get Spec Status Check the status of an async specification generation request. ```python theme={null} status = predev.get_spec_status("spec_123") # Returns SpecResponse with status: "pending" | "processing" | "completed" | "failed" ``` **Parameters:** * `spec_id` **(required)**: `str` - The specification ID from async methods **Returns:** `SpecResponse` object with current status and data (when completed) **Example:** ```python theme={null} status = predev.get_spec_status("spec_123") # Returns SpecResponse with status: "pending" | "processing" | "completed" | "failed" ``` ### Credits Management #### Get Credits Balance Get the remaining credits balance for your API key. ```python theme={null} balance = predev.get_credits_balance() # Returns: CreditsBalanceResponse(success=True, creditsRemaining=450) ``` **Parameters:** None **Returns:** `CreditsBalanceResponse` object with credits remaining **Example:** ```python theme={null} balance = predev.get_credits_balance() if balance.creditsRemaining < 50: print(f"Low credits: {balance.creditsRemaining} remaining") else: print(f"Credits available: {balance.creditsRemaining}") ``` ### Listing and Searching Specs #### List Specifications List all specs with optional filtering and pagination. ```python theme={null} # Get first 20 specs result = predev.list_specs() # Get completed specs only completed = predev.list_specs(status='completed') # Paginate: get specs 20-40 page2 = predev.list_specs(skip=20, limit=20) # Filter by endpoint type fast_specs = predev.list_specs(endpoint='fast_spec') ``` **Parameters:** * `limit` **(optional)**: `int` - Results per page (1-100, default: 20) * `skip` **(optional)**: `int` - Offset for pagination (default: 0) * `endpoint` **(optional)**: `"fast_spec" | "deep_spec"` - Filter by endpoint type * `status` **(optional)**: `"pending" | "processing" | "completed" | "failed"` - Filter by status **Returns:** `ListSpecsResponse` object with specs array and pagination metadata #### Search Specifications Search for specs using regex patterns (case-insensitive). ```python theme={null} # Search for "payment" specs payment_specs = predev.find_specs(query='payment') # Search for specs starting with "Build" build_specs = predev.find_specs(query='^Build') # Search: only completed specs mentioning "auth" auth_specs = predev.find_specs( query='auth', status='completed' ) # Complex regex: find SaaS or SASS projects saas_specs = predev.find_specs(query='saas|sass') ``` **Parameters:** * `query` **(required)**: `str` - Regex pattern (case-insensitive) * `limit` **(optional)**: `int` - Results per page (1-100, default: 20) * `skip` **(optional)**: `int` - Offset for pagination (default: 0) * `endpoint` **(optional)**: `"fast_spec" | "deep_spec"` - Filter by endpoint type * `status` **(optional)**: `"pending" | "processing" | "completed" | "failed"` - Filter by status **Returns:** `ListSpecsResponse` object with matching specs and pagination metadata **Regex Pattern Examples:** | Pattern | Matches | | -------------- | ------------------------------------ | | `payment` | "payment", "Payment", "make payment" | | `^Build` | Specs starting with "Build" | | `platform$` | Specs ending with "platform" | | `(API\|REST)` | Either "API" or "REST" | | `auth.*system` | "auth" then anything then "system" | | `\\d{3,}` | 3+ digits (budgets, quantities) | | `saas\|sass` | SaaS or SASS | ## File Upload Support All `fast_spec`, `deep_spec`, `fast_spec_async`, and `deep_spec_async` methods support optional file uploads. This allows you to provide architecture documents, requirements files, design mockups, RFPs (Request for Proposals), or other context files to improve specification generation. ### Using File Path (Simplest) ```python theme={null} from predev_api import PredevAPI predev = PredevAPI(api_key="your_api_key") # Just pass the file path as a string result = predev.fast_spec( input_text="Generate specs based on these requirements", file="path/to/requirements.pdf" ) ``` ### Using File-like Objects ```python theme={null} # Open and upload a file with open("architecture.doc", "rb") as f: result = predev.deep_spec( input_text="Create comprehensive specs", file=f ) # Or pass a file-like object from io import BytesIO file_content = BytesIO(b"Design specifications...") result = predev.fast_spec( input_text="Generate specs", file=file_content ) ``` ### Supported File Types * PDF documents (`*.pdf`) * Word documents (`*.doc`, `*.docx`) * Text files (`*.txt`) * Images (`*.jpg`, `*.png`, `*.jpeg`) ### Response with File Upload When you upload a file, the response includes: ```python theme={null} result = predev.fast_spec( input_text="Based on the design document", file="design.pdf" ) print(result.uploadedFileName) # "design.pdf" print(result.uploadedFileShortUrl) # "https://api.pre.dev/f/xyz123" print(result.codingAgentSpecUrl) # Spec for AI systems print(result.humanSpecUrl) # Spec for humans ``` ## Response Types ### AsyncResponse ```python theme={null} @dataclass class AsyncResponse: specId: str # Unique ID for polling (e.g., "spec_abc123") status: Literal['pending', 'processing', 'completed', 'failed'] ``` ### SpecResponse ```python theme={null} @dataclass class SpecResponse: # Basic info _id: Optional[str] = None # Internal ID created: Optional[str] = None # ISO timestamp endpoint: Optional[Literal['fast_spec', 'deep_spec']] = None input: Optional[str] = None # Original input text status: Optional[Literal['pending', 'processing', 'completed', 'failed']] = None success: Optional[bool] = None # Output data (when completed) uploadedFileShortUrl: Optional[str] = None # URL to input file uploadedFileName: Optional[str] = None # Name of input file humanSpecUrl: Optional[str] = None # URL to human-readable spec humanSpecMarkdown: Optional[str] = None # Full markdown SOW for humans/clients humanSpecJson: Optional['HumanSpecJson'] = None # Full structured SOW JSON totalHumanHours: Optional[float] = None # Estimated hours for human implementation codingAgentSpecUrl: Optional[str] = None # URL to coding agent spec format codingAgentSpecMarkdown: Optional[str] = None # Simplified markdown SOW for AI tools codingAgentSpecJson: Optional['CodingAgentSpecJson'] = None # Structured SOW JSON for AI tools executionTime: Optional[int] = None # Processing time in milliseconds # Integration URLs (when completed) predevUrl: Optional[str] = None # Link to pre.dev project architectureInfographicUrl: Optional[str] = None # Rendered architecture infographic zippedDocsUrls: Optional[List[ZippedDocsUrl]] = None # Downloadable doc bundles userFlowGraph: Optional[SpecGraph] = None # User flow nodes + edges architectureGraph: Optional[SpecGraph] = None # System architecture nodes + edges enrichedTechStack: Optional[List[SpecEnrichedTechStackItem]] = None # Tech choices with useFor/reason creditsUsed: Optional[float] = None # Credits consumed (live during processing) # Error handling errorMessage: Optional[str] = None # Error details if failed progress: Optional[int] = None # Overall progress percentage (0-100) progressMessage: Optional[str] = None # Detailed progress message (e.g., "Generating User Stories...") @dataclass class CodingAgentSpecJson: title: Optional[str] = None executiveSummary: Optional[str] = None coreFunctionalities: Optional[List['SpecCoreFunctionality']] = None techStack: Optional[List['SpecTechStackItem']] = None techStackGrouped: Optional[dict] = None milestones: Optional[List['CodingAgentMilestone']] = None @dataclass class CodingAgentMilestone: milestoneNumber: int = 0 description: str = '' stories: List['CodingAgentStory'] = None @dataclass class CodingAgentStory: id: Optional[str] = None title: str = '' description: Optional[str] = None acceptanceCriteria: Optional[List[str]] = None complexity: Optional[str] = None subTasks: List['CodingAgentSubTask'] = None @dataclass class CodingAgentSubTask: id: Optional[str] = None description: str = '' complexity: str = '' @dataclass class HumanSpecJson: title: Optional[str] = None executiveSummary: Optional[str] = None coreFunctionalities: Optional[List['SpecCoreFunctionality']] = None personas: Optional[List['SpecPersona']] = None techStack: Optional[List['SpecTechStackItem']] = None techStackGrouped: Optional[dict] = None milestones: Optional[List['HumanSpecMilestone']] = None totalHours: Optional[float] = None roles: Optional[List['SpecRole']] = None @dataclass class HumanSpecMilestone: milestoneNumber: int = 0 description: str = '' hours: float = 0.0 stories: List['HumanSpecStory'] = None @dataclass class HumanSpecStory: id: Optional[str] = None title: str = '' description: Optional[str] = None acceptanceCriteria: Optional[List[str]] = None hours: float = 0.0 complexity: Optional[str] = None subTasks: List['HumanSpecSubTask'] = None @dataclass class HumanSpecSubTask: id: Optional[str] = None description: str = '' hours: float = 0.0 complexity: str = '' roles: Optional[List['SpecRole']] = None @dataclass class SpecPersona: title: str = '' description: str = '' primaryGoals: Optional[List[str]] = None painPoints: Optional[List[str]] = None keyTasks: Optional[List[str]] = None @dataclass class SpecRole: name: str = '' shortHand: str = '' @dataclass class SpecCoreFunctionality: name: str = '' description: str = '' priority: Optional[str] = None # "High" | "Medium" | "Low" @dataclass class SpecTechStackItem: name: str = '' category: str = '' ``` ### ListSpecsResponse ```python theme={null} @dataclass class ListSpecsResponse: specs: List[SpecResponse] # Array of spec objects total: int # Total count of matching specs hasMore: bool # Whether more results are available ``` ### CreditsBalanceResponse ```python theme={null} @dataclass class CreditsBalanceResponse: success: bool creditsRemaining: int ``` ## Examples ### Generate Fast Spec ```python theme={null} from predev_api import PredevAPI predev = PredevAPI(api_key="your_api_key") spec = predev.fast_spec( input_text="Build a task management app with team collaboration" ) print(spec.codingAgentSpecMarkdown) ``` ### Search Specs with Regex ```python theme={null} from predev_api import PredevAPI predev = PredevAPI(api_key="your_api_key") # Find all payment-related specs payment_specs = predev.find_specs(query='payment') print(f"Found {payment_specs.total} payment specs") # Find specs starting with "Build" build_specs = predev.find_specs(query='^Build') # Find completed authentication specs auth_specs = predev.find_specs( query='auth', status='completed', endpoint='deep_spec' ) # Complex search: SaaS or SASS projects saas_specs = predev.find_specs(query='saas|sass') for spec in saas_specs.specs: print(f"Found: {spec.input}") ``` ### Check Credits Balance ```python theme={null} from predev_api import PredevAPI predev = PredevAPI(api_key="your_api_key") # Get current credit balance balance = predev.get_credits_balance() print(f"Credits remaining: {balance.creditsRemaining}") # Check before making expensive request if balance.creditsRemaining >= 50: result = predev.deep_spec( input_text="Build an enterprise platform" ) else: print(f"Insufficient credits. Need 50, have {balance.creditsRemaining}") ``` ## Error Handling All SDK errors inherit from `PredevAPIError`. Typed subclasses map to HTTP status codes so you can handle billing and rate-limit cases explicitly: | Exception | HTTP | When | | --------------------------- | ----- | ----------------------------------------------------------------------------------- | | `AuthenticationError` | 401 | Missing or invalid API key | | `SubscriptionRequiredError` | 402 | Endpoint needs an active subscription | | `InsufficientCreditsError` | 402 | Not enough credits — top up at [pre.dev/projects/key](https://pre.dev/projects/key) | | `BatchTooLargeError` | 400 | Request exceeds size limits | | `QueueFullError` | 429 | Per-user in-flight queue is full — retry later | | `RateLimitError` | 429 | Too many requests — back off and retry | | `PredevAPIError` | other | Any other API error (has `.status_code`) | ```python theme={null} from predev_api import ( PredevAPI, AuthenticationError, InsufficientCreditsError, RateLimitError, PredevAPIError, ) predev = PredevAPI(api_key="your_api_key") try: spec = predev.fast_spec(input_text="Build a task management app") except AuthenticationError: print("Check your API key at pre.dev/projects/key") except InsufficientCreditsError as e: print(f"Out of credits: {e}") except RateLimitError: print("Rate limited - retry with backoff") except PredevAPIError as e: print(f"API error ({e.status_code}): {e}") ``` Typed exceptions require `predev-api` >= 1.1.0. # List Tasks Source: https://docs.pre.dev/browser-agents/api/list-tasks GET /list-browser-agents Paginate over every browser-agent task submission your API key has created. Filter by status, control page size with limit/skip. Paginate over every run this API key has created, newest first. Useful for building a history UI, reconciling your own records, or spot-checking processing runs. ## Overview * **Method:** `GET` * **Path:** `/list-browser-agents` * **Auth:** same `Authorization: Bearer YOUR_API_KEY` as [Run a Task](/browser-agents/api/run-task) * **Sort order:** newest first (`createdAt` descending). * **Scope:** only runs owned by this API key are returned. ## Query Parameters | Name | Type | Default | Description | | -------- | ----------------------------- | ------- | ----------------------------------------------------------------------- | | `limit` | `integer` | `20` | Page size. `1` ≤ `limit` ≤ `100`. Values outside the range are clamped. | | `skip` | `integer` | `0` | Number of runs to skip (offset-based pagination). | | `status` | `"processing" \| "completed"` | — | Filter by run state. Omit to return all states. | ## Response ```typescript theme={null} interface ListRunsResponse { batches: BatchResult[]; // historical field name — each entry is a run summary total: number; // total matching runs (ignores limit/skip) hasMore: boolean; // true when skip + limit < total } ``` Each entry in `batches` is a summary row: | Field | Type | Description | | ------------------ | ----------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `id` | `string` | Run id. Pass to [`GET /browser-agent/:id`](/browser-agents/api/task-status) for full results. | | `total` | `integer` | Number of tasks in the run. | | `completed` | `integer` | How many tasks have finished. | | `results` | `TaskResult[]` | Array sized to `total`. Index `0` is pre-populated with a stub `{ url, instruction }` for the first task so you can render a list row even before it completes; other indices are `null` until the run finishes. | | `totalCreditsUsed` | `number` | Running credits total across completed tasks. | | `status` | `"processing" \| "completed" \| "failed"` | Current state. | | `createdAt` | ISO-8601 | Run creation time. | | `completedAt` | ISO-8601 | Only set once `status !== "processing"`. | The envelope field is historically named `batches`, not `runs`, to stay backward-compatible with older clients. Each entry is the same run-summary shape described above. ## Example ```bash theme={null} curl "https://api.pre.dev/list-browser-agents?limit=10&status=completed" \ -H "Authorization: Bearer $PREDEV_API_KEY" ``` ```json theme={null} { "batches": [ { "id": "65f8a9d2c1e4b5a6f7e8d9c0", "total": 3, "completed": 3, "results": [ { "url": "https://example.com", "instruction": "Extract the heading.", "status": "SUCCESS", "data": { "heading": "Example Domain" }, "creditsUsed": 0.11, "durationMs": 4820 }, { "...": "..." }, { "...": "..." } ], "totalCreditsUsed": 0.41, "status": "completed", "createdAt": "2026-04-16T18:22:10.224Z", "completedAt": "2026-04-16T18:23:07.918Z" } ], "total": 87, "hasMore": true } ``` ## Status Codes | Code | Meaning | | ----- | ------------------------------------ | | `200` | OK. Body is the list envelope above. | | `401` | Missing or invalid bearer token. | ## Pagination Patterns ### Python — iterate every run ```python theme={null} import requests API_KEY = "YOUR_API_KEY" BASE = "https://api.pre.dev/list-browser-agents" HDR = {"Authorization": f"Bearer {API_KEY}"} def iter_runs(status: str | None = None, page_size: int = 100): skip = 0 while True: params = {"limit": page_size, "skip": skip} if status: params["status"] = status r = requests.get(BASE, headers=HDR, params=params) r.raise_for_status() page = r.json() for run in page["batches"]: yield run if not page.get("hasMore"): return skip += page_size # Tally credits used across every completed run. total_credits = sum(run["totalCreditsUsed"] for run in iter_runs(status="completed")) print(f"Lifetime spend: {total_credits} credits") ``` ### Node.js — fetch a single page ```javascript theme={null} const API_KEY = process.env.PREDEV_API_KEY; const BASE = "https://api.pre.dev/list-browser-agents"; async function listRuns({ limit = 20, skip = 0, status } = {}) { const params = new URLSearchParams({ limit: String(limit), skip: String(skip) }); if (status) params.set("status", status); const res = await fetch(`${BASE}?${params}`, { headers: { Authorization: `Bearer ${API_KEY}` }, }); if (!res.ok) throw new Error(`${res.status} ${await res.text()}`); return res.json(); } const { batches, total, hasMore } = await listRuns({ limit: 25, status: "processing" }); console.log(`${batches.length}/${total} in-flight runs`); ``` ### TypeScript — pull all pages ```typescript theme={null} async function fetchAllRuns(opts: { status?: "processing" | "completed" } = {}) { const all: any[] = []; let skip = 0; const limit = 100; while (true) { const page = await listRuns({ limit, skip, ...opts }); all.push(...page.batches); if (!page.hasMore) break; skip += limit; } return all; } ``` List responses echo only the *first* task's URL/instruction into `results[0]` as a stub. To inspect every task in a run, fetch it by id with [`GET /browser-agent/:id`](/browser-agents/api/task-status). # Queue Status & Capacity Source: https://docs.pre.dev/browser-agents/api/queue-status GET /browser-agent-status and GET /browser-agent-capacity — watch your in-flight work and the global pool. Two lightweight read endpoints for operating at volume. ## GET /browser-agent-status Your own live queue: how many tasks you have running and queued, and your plan's in-flight cap. Free to call, cheap on our side — poll it as often as you like. ```bash theme={null} curl https://api.pre.dev/browser-agent-status \ -H "Authorization: Bearer $PREDEV_API_KEY" ``` ```json theme={null} { "userId": "...", "running": 12, "claimed": 3, "pending": 40, "total": 55, "cap": 100 } ``` | Field | Description | | --------- | ----------------------------------------------------------------------------- | | `running` | Tasks executing right now | | `claimed` | Tasks picked up, about to run | | `pending` | Tasks waiting in your queue | | `total` | running + claimed + pending | | `cap` | Your plan's max in-flight tasks — submits beyond this return `429 QUEUE_FULL` | Use it to throttle your own submit loop: stay under `cap` and you'll never see `QUEUE_FULL`. Also available in the SDKs as `browserAgentStatus()` (TypeScript) and `browser_agent_status()` (Python). ## GET /browser-agent-capacity Global pool state — useful for deciding whether now is a good time to submit a large set of tasks. Any valid API key can read it. ```bash theme={null} curl https://api.pre.dev/browser-agent-capacity \ -H "Authorization: Bearer $PREDEV_API_KEY" ``` Returns current queue and sandbox-pool statistics. POST /browser-agent — sync, async, or streaming. GET /list-browser-agents — history with pagination. # Run a Task Source: https://docs.pre.dev/browser-agents/api/run-task POST /browser-agent Run one or more browser-automation tasks. Supports sync, async, and SSE streaming modes. Up to 1000 tasks per request. Run one or more browser-agent tasks in parallel. One request, one clean response — or a live SSE stream, or an async handle to poll. The `tasks` field is always an array, even for a single task — so one endpoint covers both "run one task" and "run 1000 tasks in parallel". No separate batch vs. single-task API. ## Overview * **Method:** `POST` * **Path:** `/browser-agent` * **Cost:** billed per successful task. Failed tasks are free. * **Max tasks per request:** `1000` * **Max in-flight tasks per user:** varies by plan (5 on the free tier, up to 150 on Enterprise). Check yours with [`GET /browser-agent-status`](/browser-agents/api/queue-status) **`concurrency` vs your in-flight cap:** `concurrency` controls parallel workers *within one request*. Your in-flight cap counts *every* submitted task (pending, claimed, and running) across your account — so a 200-task submission counts as 200 against the cap immediately, even at `concurrency: 5`. If a submission would exceed your remaining cap, it's rejected with `429 QUEUE_FULL`; chunk large workloads to your cap using [`GET /browser-agent-status`](/browser-agents/api/queue-status). * **Per-task default timeout:** `240000` ms ## Headers | Header | Required | Description | | --------------- | -------- | --------------------- | | `Authorization` | ✅ | `Bearer YOUR_API_KEY` | | `Content-Type` | ✅ | `application/json` | ## Request Body | Field | Type | Required | Description | | ------------- | --------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | | `tasks` | `Task[]` | ✅ | Array of tasks. `1` ≤ length ≤ `1000`. | | `concurrency` | `integer` | ❌ | Parallel workers within this run. `1`–`20`. Default `5`. | | `async` | `boolean` | ❌ | If `true`, returns `{ id, status: "processing" }` immediately. Poll [`GET /browser-agent/:id`](/browser-agents/api/task-status). Default `false`. | | `stream` | `boolean` | ❌ | If `true`, returns an SSE stream with per-step events + final results. Default `false`. Mutually exclusive with `async`. | ### `Task` object | Field | Type | Required | Description | | ------------------ | ------------------------ | -------- | ------------------------------------------------------------------------------------------------ | | `url` | `string` (URI) | ✅ | Starting page URL the agent navigates to. | | `instruction` | `string` | ❌ | Natural-language goal. What should the agent accomplish on this page? | | `input` | `Record` | ❌ | String values the agent should use during the run — form values, credentials, search queries. | | `output` | JSON Schema | ❌ | Schema describing the shape of data to extract. If omitted, the agent returns unstructured text. | | `successCondition` | `string` | ❌ | Natural-language assertion. Task is marked `SUCCESS` only if this holds at the end. | | `timeoutMs` | `integer` | ❌ | Per-task max runtime in milliseconds. Default `240000`. | ## Response Modes ### Sync (default) Default behavior. The request holds the HTTP connection until every task in the run completes, then returns the full `BatchResult`. Best for: small runs (≤ 50 tasks), interactive scripts, jobs where you want one clean response. ```bash theme={null} curl -X POST https://api.pre.dev/browser-agent \ -H "Authorization: Bearer $PREDEV_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "tasks": [ { "url": "https://example.com", "instruction": "Extract the page heading." } ] }' ``` **Response (200):** ```json theme={null} { "id": "65f8a9d2c1e4b5a6f7e8d9c0", "total": 1, "completed": 1, "results": [ { "url": "https://example.com", "instruction": "Extract the page heading.", "status": "SUCCESS", "data": { "heading": "Example Domain" }, "creditsUsed": 0.11, "durationMs": 4820 } ], "totalCreditsUsed": 0.11, "status": "completed", "createdAt": "2026-04-16T18:22:10.224Z", "completedAt": "2026-04-16T18:22:15.044Z" } ``` ### Async (`async: true`) Returns immediately with a `batchId`. Poll [`GET /browser-agent/:id`](/browser-agents/api/task-status) for progress. Best for: large runs, long-running tasks, fire-and-forget jobs. ```bash theme={null} curl -X POST https://api.pre.dev/browser-agent \ -H "Authorization: Bearer $PREDEV_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "tasks": [{ "url": "https://example.com", "instruction": "Extract the heading." }], "async": true }' ``` **Response (200):** ```json theme={null} { "id": "65f8a9d2c1e4b5a6f7e8d9c0", "total": 1, "completed": 0, "results": [], "totalCreditsUsed": 0, "status": "processing" } ``` ### Stream (`stream: true`) Returns `text/event-stream` with per-step events. Each frame has a `taskIndex` tying it back to a task in the run. Best for: live UI progress, debugging, watching what the agent is doing in real time. **SSE frames:** | Event | When | Payload | | ------------- | ------------------------------------------------------------------------ | ------------------------------ | | `task_event` | Agent performs a step (navigation, plan, action, screenshot, validation) | `{ taskIndex, type, data }` | | `task_result` | A single task finishes | `{ taskIndex, ...TaskResult }` | | `done` | Entire run finishes | Full `BatchResult` | | `error` | Fatal error aborted the run | `{ error }` | Keepalive `:keepalive` comments are sent every 10s to stop intermediaries from closing the connection. ```bash theme={null} curl -N -X POST https://api.pre.dev/browser-agent \ -H "Authorization: Bearer $PREDEV_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "tasks": [{ "url": "https://example.com", "instruction": "Extract the heading." }], "stream": true }' ``` **Example frames:** ``` :ok event: task_event data: {"taskIndex":0,"type":"navigation","data":{"url":"https://example.com"}} event: task_event data: {"taskIndex":0,"type":"screenshot","data":{"url":"https://..."}} event: task_result data: {"taskIndex":0,"status":"SUCCESS","data":{"heading":"Example Domain"},"durationMs":4820} event: done data: {"id":"65f8...","total":1,"completed":1,"results":[...],"status":"completed"} ``` If the server is at SSE capacity, new stream requests get `503`. Fall back to `async: true` + polling. ## Response Schemas ### `BatchResult` | Field | Type | Description | | ------------------ | ----------------------------------------- | ------------------------------------------------------------------------------------------------------------ | | `id` | `string` | Run id (Mongo ObjectId). Use with [`GET /browser-agent/:id`](/browser-agents/api/task-status). | | `total` | `integer` | Number of tasks in the run. | | `completed` | `integer` | Number of tasks finished (any status). | | `results` | `TaskResult[]` | Per-task results, aligned by `taskIndex`. | | `totalCreditsUsed` | `number` | Sum of credits billed across the run. 1 credit = \$0.10, floor 0.1 per billed task. | | `status` | `"processing" \| "completed" \| "failed"` | Run state. | | `createdAt` | ISO-8601 | Run creation time. | | `completedAt` | ISO-8601 | Run completion time. Omitted while processing. | | `liveEvents` | `RunnerEvent[][]` | Only when fetching with `includeEvents=true` — in-flight event streams for tasks that haven't yet completed. | | `error` | `string` | Set only when `status === "failed"`. | ### `TaskResult` | Field | Type | Description | | ------------- | ------------------------ | ---------------------------------------------------------------------------------------------------------------------------------- | | `url` | `string` | Starting URL (echoed from the request). | | `instruction` | `string` | Task instruction (echoed). | | `input` | `Record` | Task input (echoed). | | `status` | `TaskStatus` | See [task statuses](#task-statuses). | | `data` | `any` | Extracted data, validated against the task's `output` schema. `null` if no `output` was specified or the task failed. | | `creditsUsed` | `number` | Credits billed for this task. Floor 0.1 (= \$0.01) for `SUCCESS`; scales up with task complexity. Zero for non-`SUCCESS` statuses. | | `durationMs` | `integer` | Wall-clock runtime. | | `error` | `string` | Failure reason, when `status` is not `SUCCESS`. | | `events` | `RunnerEvent[]` | Full step timeline. Only returned when fetching with `includeEvents=true`. | ### Task statuses | Status | Meaning | Billed? | | ---------------- | ---------------------------------------------------------------- | ------- | | `SUCCESS` | Task completed; `output` schema (if any) validated. | ✅ | | `PENDING` | Task queued, not yet started (async/polling response only). | — | | `ERROR` | Task errored during execution. | ❌ | | `TIMEOUT` | Task hit `timeoutMs`. | ❌ | | `BLOCKED` | Target site blocked the agent (bot protection, geo-block, etc.). | ❌ | | `CAPTCHA_FAILED` | CAPTCHA challenge couldn't be solved. | ❌ | | `LOOP` | Agent got stuck in a redirect or action loop. | ❌ | | `NO_TARGET` | Required element wasn't found on the page. | ❌ | ## Status Codes | Code | Meaning | | ----- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `200` | Sync result, async stub, or start of SSE stream. | | `400` | Missing `tasks`, task without `url`, `tasks.length > 1000`, or `code: BATCH_TOO_LARGE`. | | `401` | Missing or invalid bearer token. | | `402` | Subscription required (`code: SUBSCRIPTION_REQUIRED`) or insufficient credits (`code: INSUFFICIENT_CREDITS`). Body includes `actionUrl` — see [Error response shape](#error-response-shape). | | `429` | Rate-limited (`code: RATE_LIMITED`) or queue full (`code: QUEUE_FULL`). Retry after a back-off. | | `503` | SSE capacity exceeded on this pod. Retry with `async: true` and poll. | ### Error response shape Non-2xx responses return a structured JSON body (and the matching SSE `error` event when streaming): ```json theme={null} { "error": "Need ~0.5 credits, have 0.00. Buy more to continue.", "code": "INSUFFICIENT_CREDITS", "actionUrl": "https://pre.dev/projects/key?upgrade=credits" } ``` `code` lets clients dispatch typed handlers without parsing strings. `actionUrl`, when present, deep-links the user back to pre.dev with the right modal pre-opened — paste it into `window.open` and they'll land on the credit-purchase or subscription flow ready to go. | `code` | When | `actionUrl` | | ----------------------- | ----------------------------------------------------- | ---------------- | | `SUBSCRIPTION_REQUIRED` | Trial limit reached on this API key. | Subscribe modal. | | `INSUFFICIENT_CREDITS` | Subscribed but credit balance too low for this batch. | Credits modal. | | `RATE_LIMITED` | Per-minute request cap hit. | — | | `QUEUE_FULL` | Per-user in-flight task cap hit. | — | | `BATCH_TOO_LARGE` | `tasks.length` exceeds the per-request maximum. | — | The Node and Python SDKs map every `code` value to a typed exception class with the `actionUrl` populated — see the [Node SDK](/browser-agents/sdks/node#error-handling) and [Python SDK](/browser-agents/sdks/python#error-handling) error-handling sections. ## Code Examples ### Multiple tasks with concurrency ```bash theme={null} curl -X POST https://api.pre.dev/browser-agent \ -H "Authorization: Bearer $PREDEV_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "tasks": [ { "url": "https://news.ycombinator.com", "instruction": "Extract the top 5 story titles." }, { "url": "https://www.reddit.com/r/programming", "instruction": "Extract the top 5 post titles." } ], "concurrency": 2 }' ``` ### Structured extraction with `output` schema ```bash theme={null} curl -X POST https://api.pre.dev/browser-agent \ -H "Authorization: Bearer $PREDEV_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "tasks": [ { "url": "https://news.ycombinator.com", "instruction": "Extract the top 5 stories.", "output": { "type": "object", "properties": { "stories": { "type": "array", "items": { "type": "object", "properties": { "title": { "type": "string" }, "points": { "type": "number" } }, "required": ["title", "points"] } } }, "required": ["stories"] } } ] }' ``` ### Python — sync + async + streaming ```python theme={null} import json import time import requests API_KEY = "YOUR_API_KEY" BASE = "https://api.pre.dev/browser-agent" HDR = {"Authorization": f"Bearer {API_KEY}", "Content-Type": "application/json"} def run_sync(tasks, concurrency=5): r = requests.post(BASE, headers=HDR, json={"tasks": tasks, "concurrency": concurrency}) r.raise_for_status() return r.json() def run_async(tasks, concurrency=5, poll_every=5): r = requests.post(BASE, headers=HDR, json={"tasks": tasks, "concurrency": concurrency, "async": True}) r.raise_for_status() batch_id = r.json()["id"] while True: poll = requests.get(f"{BASE}/{batch_id}", headers=HDR).json() if poll["status"] in ("completed", "failed"): return poll print(f"{poll['completed']}/{poll['total']} done") time.sleep(poll_every) def run_stream(tasks): with requests.post(BASE, headers=HDR, json={"tasks": tasks, "stream": True}, stream=True) as r: r.raise_for_status() event = None for line in r.iter_lines(decode_unicode=True): if line is None or line.startswith(":"): continue if line.startswith("event: "): event = line[len("event: "):].strip() elif line.startswith("data: "): data = json.loads(line[len("data: "):]) yield event, data # sync result = run_sync([{"url": "https://example.com", "instruction": "Extract the heading."}]) print(result["results"][0]["data"]) # stream for event, data in run_stream([{"url": "https://example.com", "instruction": "Extract the heading."}]): if event == "task_event": print(f"[task {data['taskIndex']}] {data.get('type')}") elif event == "task_result": print(f"[task {data['taskIndex']}] {data['status']} → {data.get('data')}") elif event == "done": print("batch done:", data["id"]) break ``` ### Node.js — sync + streaming ```javascript theme={null} const API_KEY = process.env.PREDEV_API_KEY; const BASE = "https://api.pre.dev/browser-agent"; const HDR = { "Authorization": `Bearer ${API_KEY}`, "Content-Type": "application/json", }; async function runSync(tasks, concurrency = 5) { const res = await fetch(BASE, { method: "POST", headers: HDR, body: JSON.stringify({ tasks, concurrency }), }); if (!res.ok) throw new Error(`${res.status} ${await res.text()}`); return res.json(); } async function* runStream(tasks) { const res = await fetch(BASE, { method: "POST", headers: HDR, body: JSON.stringify({ tasks, stream: true }), }); if (!res.ok) throw new Error(`${res.status} ${await res.text()}`); const reader = res.body.getReader(); const decoder = new TextDecoder(); let buffer = ""; let event = null; while (true) { const { value, done } = await reader.read(); if (done) break; buffer += decoder.decode(value, { stream: true }); let idx; while ((idx = buffer.indexOf("\n")) !== -1) { const line = buffer.slice(0, idx).trim(); buffer = buffer.slice(idx + 1); if (!line || line.startsWith(":")) continue; if (line.startsWith("event: ")) event = line.slice(7).trim(); else if (line.startsWith("data: ")) yield { event, data: JSON.parse(line.slice(6)) }; } } } // sync const result = await runSync([ { url: "https://example.com", instruction: "Extract the heading." }, ]); console.log(result.results[0].data); // stream for await (const { event, data } of runStream([ { url: "https://example.com", instruction: "Extract the heading." }, ])) { if (event === "task_event") console.log(`[task ${data.taskIndex}]`, data.type); if (event === "task_result") console.log(`[task ${data.taskIndex}]`, data.status, data.data); if (event === "done") break; } ``` ### TypeScript — fully typed client ```typescript theme={null} type TaskStatus = | "SUCCESS" | "PENDING" | "ERROR" | "TIMEOUT" | "BLOCKED" | "CAPTCHA_FAILED" | "LOOP" | "NO_TARGET"; interface Task { url: string; instruction?: string; input?: Record; output?: Record; successCondition?: string; timeoutMs?: number; } interface TaskResult { url: string; instruction?: string; input?: Record; status: TaskStatus; data?: unknown; creditsUsed: number; durationMs: number; error?: string; } interface BatchResult { id: string; total: number; completed: number; results: TaskResult[]; totalCreditsUsed: number; status: "processing" | "completed" | "failed"; createdAt?: string; completedAt?: string; error?: string; } interface BatchRequest { tasks: Task[]; concurrency?: number; async?: boolean; stream?: boolean; } export class BrowserAgents { constructor(private apiKey: string, private base = "https://api.pre.dev/browser-agent") {} private headers() { return { "Authorization": `Bearer ${this.apiKey}`, "Content-Type": "application/json", }; } async run(req: BatchRequest): Promise { const res = await fetch(this.base, { method: "POST", headers: this.headers(), body: JSON.stringify(req) }); if (!res.ok) throw new Error(`${res.status} ${await res.text()}`); return res.json(); } } ``` ## Error Handling All non-2xx responses follow the [structured shape above](#error-response-shape). The two billing codes carry an `actionUrl` that auto-opens the right modal on pre.dev — surface it in your UI and the user is one click from resolving the gate. ### `402 SUBSCRIPTION_REQUIRED` This API key's user is on the trial plan and has used their lifetime free task. Send them to `actionUrl` (subscribe modal) or have them upgrade at [pre.dev/projects/key](https://pre.dev/projects/key). ### `402 INSUFFICIENT_CREDITS` Subscription is fine, but the credit balance is below the per-task estimate (0.1 credits/task by default; failed tasks aren't billed but you need the headroom to start). Send them to `actionUrl` (credits modal) — or top up at [pre.dev/projects/key](https://pre.dev/projects/key). ### `429 RATE_LIMITED` / `QUEUE_FULL` Per-minute request cap hit, or you're at your plan's in-flight task cap. Wait for tasks to drain, lower `concurrency`, or check [`GET /browser-agent-status`](/browser-agents/api/queue-status). ### `503 SSE capacity exceeded` The serving pod is already at its SSE connection cap. Retry the request with `"async": true` and poll — the underlying work isn't affected. ### `400` / invalid task shape Every task needs a `url`. If you get `400`, check you're not sending `tasks: { ... }` (a single object) — it must always be an array, even for one task. Fetch results for an async or historical task submission, with the full per-step event timeline. # Stream a Running Task Source: https://docs.pre.dev/browser-agents/api/stream-task GET /browser-agent/{id}/stream — Server-Sent Events for a task run that's already in progress. Attach a live Server-Sent Events stream to an in-progress run. You get an immediate snapshot, then per-step events as they happen. The stream closes itself when the run completes or fails. Use this when you submitted with `async: true` and want live progress without polling. If you want streaming from the moment of submission, pass `stream: true` on [`POST /browser-agent`](/browser-agents/api/run-task) instead. ## Endpoint ``` GET https://api.pre.dev/browser-agent/{id}/stream ``` ## Auth Standard header auth works, and because `EventSource` in browsers can't set custom headers, an `apiKey` query param is also accepted: ```bash theme={null} # Header auth curl -N https://api.pre.dev/browser-agent/$BATCH_ID/stream \ -H "Authorization: Bearer $PREDEV_API_KEY" # Query-param auth (for EventSource) curl -N "https://api.pre.dev/browser-agent/$BATCH_ID/stream?apiKey=$PREDEV_API_KEY" ``` ## Events | Event | Payload | When | | ------------- | --------------------------------------------------- | --------------------------------------------------- | | `snapshot` | Full result so far (with events) | Immediately on connect | | `task_event` | One execution step (navigation, action, extraction) | Live, per step | | `task_result` | A task's final result | As each task finishes | | `done` | Final state | The run completed or failed, then the stream closes | ## Errors | Status | Meaning | | ------ | ---------------------------------------------------------------------------------------------------------- | | `404` | Run not found (or not yours) | | `400` | Invalid id | | `503` | Server at SSE capacity — fall back to polling [`GET /browser-agent/{id}`](/browser-agents/api/task-status) | ## Example ```ts theme={null} const res = await fetch( `https://api.pre.dev/browser-agent/${batchId}/stream`, { headers: { Authorization: `Bearer ${process.env.PREDEV_API_KEY}` } } ); const reader = res.body!.getReader(); const decoder = new TextDecoder(); while (true) { const { done, value } = await reader.read(); if (done) break; process.stdout.write(decoder.decode(value)); } ``` GET /browser-agent/:id — simple polling with optional event timeline. # Task Status Source: https://docs.pre.dev/browser-agents/api/task-status GET /browser-agent/{id} Fetch the status and results of a browser-agent task submission by id. Works for in-progress and completed submissions. Opt into the full per-step event timeline with includeEvents=true. Fetch one run by id. Use this to poll an async submission, review a historical run, or pull the full per-step event timeline for debugging. ## Overview * **Method:** `GET` * **Path:** `/browser-agent/{id}` * **Auth:** same `Authorization: Bearer YOUR_API_KEY` as [Run a Task](/browser-agents/api/run-task) * **Scope:** you can only fetch runs created with your own API key. ## Path Parameters | Name | Type | Required | Description | | ---- | -------- | -------- | ---------------------------------------------------------------------------------------------------- | | `id` | `string` | ✅ | Run id returned by [`POST /browser-agent`](/browser-agents/api/run-task) (a 24-char Mongo ObjectId). | ## Query Parameters | Name | Type | Default | Description | | --------------- | --------- | ------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `includeEvents` | `boolean` | `false` | When `true`, includes the full per-step event timeline on each `TaskResult` (see [`events`](#event-timeline)) and adds a top-level `liveEvents` field for tasks that are still running. Payloads can be large — screenshots inflate them fast. | ## Response Returns the same `BatchResult` shape produced by `POST /browser-agent`. See [Run a Task → Response Schemas](/browser-agents/api/run-task#response-schemas) for the field-by-field breakdown. ### In-progress runs While `status === "processing"`: * `results[i]` holds a completed task when task `i` has finished, otherwise a **synthesized pending stub** with `{ url, instruction, input, status: "PENDING" }` so your UI can always render the task row. * `completed` counts how many tasks have a real result (not stubs). * When `includeEvents=true`, `liveEvents[i]` holds the in-flight event stream for each still-running task. Completed tasks get `liveEvents[i] = []`. ### Completed runs When `status === "completed"` (or `"failed"`): * Every `results[i]` is a real `TaskResult`. * `liveEvents` is omitted (all timelines live on `results[i].events` when `includeEvents=true`). * `completedAt` is populated. ## Example — polling an async run ```bash theme={null} curl https://api.pre.dev/browser-agent/65f8a9d2c1e4b5a6f7e8d9c0 \ -H "Authorization: Bearer $PREDEV_API_KEY" ``` ```json theme={null} { "id": "65f8a9d2c1e4b5a6f7e8d9c0", "total": 3, "completed": 2, "results": [ { "url": "https://example.com", "instruction": "Extract the heading.", "status": "SUCCESS", "data": { "heading": "Example Domain" }, "creditsUsed": 0.11, "durationMs": 4820 }, { "url": "https://news.ycombinator.com", "instruction": "Extract the top 5 story titles.", "status": "SUCCESS", "data": { "stories": ["...", "..."] }, "creditsUsed": 0.18, "durationMs": 8132 }, { "url": "https://www.reddit.com/r/programming", "instruction": "Extract the top 5 post titles.", "status": "PENDING" } ], "totalCreditsUsed": 0.29, "status": "processing", "createdAt": "2026-04-16T18:22:10.224Z" } ``` ## Example — full timeline for one task ```bash theme={null} curl "https://api.pre.dev/browser-agent/65f8a9d2c1e4b5a6f7e8d9c0?includeEvents=true" \ -H "Authorization: Bearer $PREDEV_API_KEY" ``` Each `TaskResult` now carries an `events` array, and while any task is still running `liveEvents` is populated too. ```json theme={null} { "id": "65f8a9d2c1e4b5a6f7e8d9c0", "total": 1, "completed": 1, "status": "completed", "results": [ { "url": "https://example.com", "status": "SUCCESS", "data": { "heading": "Example Domain" }, "creditsUsed": 0.11, "durationMs": 4820, "events": [ { "type": "navigation", "data": { "url": "https://example.com" } }, { "type": "plan", "data": { "reasoning": "The heading is the

..." } }, { "type": "screenshot", "data": { "url": "https://cdn.pre.dev/screenshots/..." } }, { "type": "action", "data": { "action": "extract", "selector": "h1" } }, { "type": "validation", "data": { "passed": true } }, { "type": "done", "data": { "status": "SUCCESS" } } ] } ] } ``` ### Event timeline The `events` array records every step the agent took. Each event is `{ type, data, ts? }`. Event types you'll see: | Type | When | Notable `data` fields | | ------------ | ----------------------------------------- | -------------------------------------------------------- | | `navigation` | Agent loaded a URL | `url` | | `plan` | Agent reasoned about next steps | `reasoning`, `steps` | | `action` | Agent performed an interaction | `action` (`click`/`type`/`scroll`/`extract`), `selector` | | `screenshot` | Frame captured | `url` (CDN link) | | `validation` | Output schema / success condition checked | `passed`, `errors` | | `done` | Task finished | `status` | | `error` | Task errored | `message` | Internal fields (sandbox provider, LLM model, token counts) are stripped from events before they're returned. You only see what your task did, not how we ran it. ## Status Codes | Code | Meaning | | ----- | -------------------------------------------- | | `200` | Run found. Body is the `BatchResult`. | | `400` | Malformed run id. | | `401` | Missing or invalid bearer token. | | `404` | Run not found, or not owned by this API key. | ## Polling Patterns ### Python — poll until done ```python theme={null} import time import requests API_KEY = "YOUR_API_KEY" BASE = "https://api.pre.dev/browser-agent" HDR = {"Authorization": f"Bearer {API_KEY}"} def wait_for_run(run_id: str, *, include_events: bool = False, poll_every: float = 5.0, timeout_s: float = 1800): deadline = time.time() + timeout_s while True: params = {"includeEvents": "true"} if include_events else None r = requests.get(f"{BASE}/{run_id}", headers=HDR, params=params) r.raise_for_status() run = r.json() if run["status"] in ("completed", "failed"): return run print(f"{run['completed']}/{run['total']} done") if time.time() > deadline: raise TimeoutError(f"run {run_id} still processing after {timeout_s}s") time.sleep(poll_every) run = wait_for_run("65f8a9d2c1e4b5a6f7e8d9c0") for r in run["results"]: print(r["status"], r.get("data")) ``` ### Node.js — poll with exponential backoff ```javascript theme={null} const API_KEY = process.env.PREDEV_API_KEY; const BASE = "https://api.pre.dev/browser-agent"; async function waitForRun(id, { includeEvents = false, maxMs = 30 * 60_000 } = {}) { const deadline = Date.now() + maxMs; let delay = 1000; while (Date.now() < deadline) { const url = `${BASE}/${id}${includeEvents ? "?includeEvents=true" : ""}`; const res = await fetch(url, { headers: { Authorization: `Bearer ${API_KEY}` } }); if (!res.ok) throw new Error(`${res.status} ${await res.text()}`); const run = await res.json(); if (run.status === "completed" || run.status === "failed") return run; await new Promise((r) => setTimeout(r, delay)); delay = Math.min(delay * 1.5, 15_000); } throw new Error(`timed out waiting for run ${id}`); } const run = await waitForRun("65f8a9d2c1e4b5a6f7e8d9c0"); console.log(run.results.map((r) => r.data)); ``` For interactive UIs use `stream: true` on the initial [Run a Task](/browser-agents/api/run-task) request to skip polling entirely. Use `GET /browser-agent/:id?includeEvents=true` only to reconstruct timelines for historical runs. Paginate over every task submission your API key has created, filter by status. # MCP Setup (Browser Agents) Source: https://docs.pre.dev/browser-agents/mcp-tool Install the pre.dev MCP server — your coding agent gets browser automation as a native tool. **One pre.dev MCP server, all the tools.** Install it once and your agent gets `browser_agent` (browser automation) plus `fast_spec` / `deep_spec` (the [Architect API](/architect-agent/overview)) in one shot. ## Quick Start Setup uses browser OAuth — your first MCP call opens pre.dev to sign in and authorize. No API key needed for editor use. Run this in your terminal: ```bash theme={null} claude mcp add --transport http predev https://api.pre.dev/mcp ``` Your browser opens to authorize — sign into pre.dev (if not already) and pick which account or organization to connect. See the [Claude Code MCP docs](https://docs.claude.com/en/docs/claude-code/mcp) for MCP basics. [ Add to Cursor](cursor://anysphere.cursor-deeplink/mcp/install?name=predev\&config=eyJ1cmwiOiJodHRwczovL2FwaS5wcmUuZGV2L21jcCJ9) Click the button above — Cursor installs the pre.dev server. On first tool use, a browser tab opens to authorize. Ask your agent: ``` Use pre.dev browser_agent to extract the top 10 stories from news.ycombinator.com with title, url, and points. ``` Your agent calls the `browser_agent` tool and returns structured JSON. ## Example prompts ``` Use pre.dev browser_agent to extract the top 10 products from https://www.producthunt.com with name, tagline, and upvote count. Return a JSON array. ``` ``` Use pre.dev browser_agent: go to https://news.ycombinator.com/newest, click "More" twice to load 90 stories, then extract all titles and points. ``` ``` Use pre.dev browser_agent to process these 50 company URLs. For each: extract the company name, tagline, and link to their pricing page. Run with concurrency 10. ``` ``` Use pre.dev browser_agent to log into https://app.example.com with the credentials in `input` (email + password), then extract the list of projects from the dashboard. ``` ## Live event streaming Every step of a task emits an MCP `notifications/message` frame. The `taskIndex` field ties each event to a specific task in the batch. Your agent sees: * `navigation` — the agent loaded a URL * `plan` — the agent decided what to do next * `action` — a click, type, or scroll executed * `screenshot` — a screenshot was captured * `done` — the task completed Event shapes are identical to the REST SSE stream — see [Run a Task → SSE frames](/browser-agents/api/run-task#stream-stream-true). ## Auth In editors, auth is browser OAuth — you sign in once and pick the account or org to connect. For programmatic MCP clients, an API key from [pre.dev/projects/key](https://pre.dev/projects/key) also works as a `predev-api-key` header. ## Troubleshooting * Restart your client after adding the MCP config * Verify the URL is exactly `https://api.pre.dev/mcp` * Check JSON syntax in your config file * Confirm your API key is valid at [pre.dev/projects/key](https://pre.dev/projects/key) * Make sure the `Authorization` header starts with `Bearer ` (with the space) * Solo accounts: use your personal key. Enterprise: use the org key from your org settings * Check your subscription is active `browser_task`, `browser_task_list`, `browser_task_get` still work as aliases — old integrations continue working without changes. # Migrate from Browser Use Source: https://docs.pre.dev/browser-agents/migrate-from-browser-use Swap Browser Use Cloud for pre.dev Browser Agents — same task shape, 100/100 vs 93/100 pass rate, ~2.8× cheaper AND ~4× faster. If you're running Browser Use Cloud today, switching to pre.dev Browser Agents is an SDK swap + an env-var rename. Same task shape (URL + instruction + schema), same structured JSON out. On our public [benchmark](/browser-agents/overview#benchmark) (June 2026 run), pre.dev passes **100/100** vs Browser Use Cloud's **93/100** — and is **\~2.8× cheaper and \~4× faster** ($0.0143 vs $0.0405 per task, 7.9s vs 32.0s avg). ## 1. Swap env vars + install the SDK ```bash theme={null} npm uninstall browser-use-sdk npm install predev-api # Replace in .env, .env.example, CI, docker-compose, etc. # BROWSER_USE_API_KEY=... → PREDEV_API_KEY=... ``` ```bash theme={null} pip uninstall browser-use-sdk pip install predev-api # Replace in .env, .env.example, CI, docker-compose, etc. # BROWSER_USE_API_KEY=... → PREDEV_API_KEY=... ``` Grab your pre.dev key at [pre.dev/projects/key](https://pre.dev/projects/key). *** ## 2. Run one task **Before — Browser Use** ```ts theme={null} import { BrowserUse } from 'browser-use-sdk/v3'; const client = new BrowserUse({ apiKey: process.env.BROWSER_USE_API_KEY! }); const response = await client.run( 'Extract the H1 from https://example.com. Return JSON { heading: string }.', { model: 'bu-mini' }, ); const data = JSON.parse(response.output); ``` **After — pre.dev** ```ts theme={null} import { PredevAPI } from 'predev-api'; const client = new PredevAPI({ apiKey: process.env.PREDEV_API_KEY! }); const result = await client.browserAgent([ { url: 'https://example.com', instruction: 'Extract the H1.', output: { type: 'object', properties: { heading: { type: 'string' } }, required: ['heading'], }, }, ]); const data = result.results[0].data; // { heading: 'Example Domain' } ``` **Before — Browser Use** ```python theme={null} import os, json from browser_use_sdk import BrowserUse client = BrowserUse(api_key=os.environ["BROWSER_USE_API_KEY"]) response = client.run( "Extract the H1 from https://example.com. Return JSON { heading: string }.", model="bu-mini", ) data = json.loads(response.output) ``` **After — pre.dev** ```python theme={null} import os from predev_api import PredevAPI client = PredevAPI(api_key=os.environ["PREDEV_API_KEY"]) result = client.browser_agent([ { "url": "https://example.com", "instruction": "Extract the H1.", "output": { "type": "object", "properties": {"heading": {"type": "string"}}, "required": ["heading"], }, } ]) data = result["results"][0]["data"] # {'heading': 'Example Domain'} ``` Key differences: * **URL is a first-class field**, not embedded in the instruction. The agent navigates there before running. * **Output schema is JSON Schema**, not a serialized Pydantic/Zod model. The runner validates the response and retries on schema-failure. * **Tasks is always an array** — one method covers 1 task or 1,000. *** ## 3. Run many tasks in parallel Browser Use makes you fire N concurrent `run()` calls yourself. pre.dev takes an array and fans out server-side — one request, one response. **Before — Browser Use (manual fan-out)** ```ts theme={null} const urls = ['https://news.ycombinator.com', 'https://lobste.rs', 'https://reddit.com/r/programming']; const responses = await Promise.all( urls.map((url) => client.run(`Extract the top 5 story titles from ${url}. Return JSON { titles: string[] }.`, { model: 'bu-mini' }), ), ); const data = responses.map((r) => JSON.parse(r.output)); ``` **After — pre.dev (one call, server-side concurrency)** ```ts theme={null} const result = await client.browserAgent( urls.map((url) => ({ url, instruction: 'Extract the top 5 story titles.', output: { type: 'object', properties: { titles: { type: 'array', items: { type: 'string' } } }, required: ['titles'], }, })), { concurrency: 3 }, ); const data = result.results.map((r) => r.data); ``` **Before — Browser Use (manual fan-out)** ```python theme={null} import asyncio, json urls = ['https://news.ycombinator.com', 'https://lobste.rs', 'https://reddit.com/r/programming'] async def one(url): r = await client.run(f"Extract the top 5 story titles from {url}. Return JSON {{titles: string[]}}.", model="bu-mini") return json.loads(r.output) data = await asyncio.gather(*(one(u) for u in urls)) ``` **After — pre.dev (one call, server-side concurrency)** ```python theme={null} result = client.browser_agent( [ { "url": url, "instruction": "Extract the top 5 story titles.", "output": { "type": "object", "properties": {"titles": {"type": "array", "items": {"type": "string"}}}, "required": ["titles"], }, } for url in urls ], concurrency=3, ) data = [r["data"] for r in result["results"]] ``` Up to 1,000 tasks per request. See [Run a Task](/browser-agents/api/run-task) for the full schema. *** ## 4. Async + poll pattern If you were polling Browser Use by session id, pre.dev has a direct equivalent: pass `async: true` on submit, then call `getBrowserAgent(id)`. **Before — Browser Use** ```ts theme={null} const handle = client.run(task, { model: 'bu-mini' }); const sessionId = handle.sessionId; while (true) { const status = await client.sessions.get(sessionId); if (status.state === 'finished') break; await new Promise((r) => setTimeout(r, 2000)); } ``` **After — pre.dev** ```ts theme={null} const { id } = await client.browserAgent( [{ url, instruction, output }], { async: true }, ); while (true) { const batch = await client.getBrowserAgent(id); if (batch.status === 'completed' || batch.status === 'failed') break; await new Promise((r) => setTimeout(r, 2000)); } ``` **Before — Browser Use** ```python theme={null} import time handle = client.run(task, model="bu-mini") session_id = handle.session_id while True: status = client.sessions.get(session_id) if status.state == "finished": break time.sleep(2) ``` **After — pre.dev** ```python theme={null} import time batch = client.browser_agent( [{"url": url, "instruction": instruction, "output": output}], run_async=True, ) while True: state = client.get_browser_agent(batch["id"]) if state["status"] in ("completed", "failed"): break time.sleep(2) ``` See [Task Status](/browser-agents/api/task-status) for the full polling contract (pass `includeEvents=True` for the per-step timeline). *** ## One-shot Claude Code prompt Drop this into [Claude Code](https://claude.com/claude-code) at the root of your repo. Works for any stack — Node, Bun, Deno, Python, monorepos. ```markdown theme={null} Migrate this codebase from Browser Use Cloud to pre.dev Browser Agents. ## Why pre.dev Browser Agents is a drop-in replacement for Browser Use Cloud's task API: same URL + instruction + JSON-schema contract, structured JSON output, ~2.8× cheaper AND ~4× faster at 100/100 pass on the public benchmark (vs Browser Use's 93/100). Docs: https://docs.pre.dev/browser-agents/migrate-from-browser-use ## Do this 1. **Find call sites.** Search the entire repo (not just `src/`) for: - Imports: `browser-use-sdk`, `from browser_use`, `BrowserUse`, `browser_use_sdk`. - Env refs: `BROWSER_USE_API_KEY` in code, `.env`, `.env.example`, `.env.*`, CI configs (`.github/workflows/*`, `render.yaml`, `vercel.json`, `docker-compose*.yml`, `Dockerfile*`, `fly.toml`), README, internal docs. - Any `cloud.browser-use.com` or `api.browser-use.com` URLs. 2. **Swap the SDK.** - Node/TS/Bun: replace `browser-use-sdk` dependency with `predev-api` in `package.json`, `bun.lockb`, `yarn.lock`, or `pnpm-lock.yaml` (let the user run the install). - Python: replace `browser-use-sdk` with `predev-api` in `requirements.txt`, `pyproject.toml`, `poetry.lock`, or `Pipfile` (let the user run the install). 3. **Rewrite calls** per these rules. Full mapping at https://docs.pre.dev/browser-agents/migrate-from-browser-use — read it once before editing. | Browser Use | pre.dev | |---|---| | `import { BrowserUse } from 'browser-use-sdk/v3'` | `import { PredevAPI } from 'predev-api'` | | `new BrowserUse({ apiKey })` | `new PredevAPI({ apiKey })` | | `client.run(taskStr, { model })` | `client.browserAgent([{ url, instruction, output }])` | | `response.output` (JSON string) | `result.results[0].data` (already parsed) | | Python `from browser_use_sdk import BrowserUse` | `from predev_api import PredevAPI` | | Python `BrowserUse(api_key=...)` | `PredevAPI(api_key=...)` | | Python `client.run(task, model=...)` | `client.browser_agent([{...}])` | | Python `json.loads(response.output)` | `result["results"][0]["data"]` | | Embedded URL in task string | first-class `url` field | | Zod/Pydantic schema | JSON Schema in `output` field | | Parallel via `Promise.all(client.run(...))` | single call with `client.browserAgent([...])` + `{ concurrency }` | | `handle.sessionId` + session polling | `client.browserAgent([...], { async: true })` + `client.getBrowserAgent(id)` | | Python async equivalent | `client.browser_agent([...], run_async=True)` + `client.get_browser_agent(id)` | 4. **Env vars.** Rename `BROWSER_USE_API_KEY` → `PREDEV_API_KEY` everywhere (code, env files, CI, docker). Base URL is `https://api.pre.dev` if it's referenced explicitly. 5. **Unsupported features — leave TODOs, don't delete.** For any of: - `client.sessions.*` (persistent sessions) - `client.agent_profiles.*` / `AgentProfile` - `client.schedules.*` - raw Playwright handoff Leave a comment above the call: `// TODO: pre.dev equivalent not yet available — see https://docs.pre.dev/browser-agents/migrate-from-browser-use` and keep the original code path so tests don't explode. We'll hand-migrate these. 6. **Verify.** After edits, run the project's typecheck and test commands (infer them from `package.json` scripts, `pyproject.toml`, or a `Makefile`). Fix anything that breaks. Do not skip this step. 7. **Report.** At the end, print: - Files changed (grouped: imports, env, call sites). - Count of migrated calls. - Count of TODO-comments left for unsupported features. - Any test/typecheck failures you couldn't fix, with exact file:line and why. ## Constraints - **Don't delete** any original code until the replacement is verified working. If unsure of a mapping, leave the old call with a TODO and surface it in the final report. - **Don't guess** the pre.dev SDK name — it's `predev-api` on both npm and pip. If that's not what the project's package manager resolves, stop and ask. - **Respect the user's existing code style** — don't reformat files you didn't otherwise change. ``` *** ## Next * [Quickstart](/browser-agents/quickstart) — run your first task end-to-end. * [Run a Task API reference](/browser-agents/api/run-task) — the full `POST /browser-agent` contract. * [Benchmark](/browser-agents/overview#benchmark) — how the numbers were measured. # Browser Agents Source: https://docs.pre.dev/browser-agents/overview Browser automation for humans and AI. Navigate, interact, and extract data from any website. **Browser Agents for humans + AI.** Give the agent a URL and an instruction — it drives a real browser, follows the flow, and returns structured JSON validated against your schema. No Playwright plumbing, no selector maintenance. Copy-paste examples in curl, TypeScript, Python, and MCP. Your first task in under a minute. Grab a key from [pre.dev/projects/key](https://pre.dev/projects/key) and set it as `PREDEV_API_KEY`. ## What Browser Agents can do * Scrape pricing, listings, and contacts into JSON * Enrich CSVs with fresh web data * Read authed dashboards (Linear, Notion, Stripe) * Log in, navigate, fill forms * Submit bulk forms from a CSV * Step through multi-page flows end-to-end * Run critical flows on a schedule * Verify checkout across plans * Flag pricing, UI, or copy drift * Drop-in MCP for Claude Code & Cursor * URL + instruction → typed JSON * Replaces flaky Playwright code ## Benchmark pre.dev Browser Agents passes **100 / 100** tasks in our public suite vs Browser Use Cloud's **93 / 100** — and it's **\~2.8× cheaper AND \~4× faster**. | Provider | Pass rate | \$ / task | Total \$ | Avg time / task | | -------------------------- | ------------: | -----------: | ---------: | --------------: | | **pre.dev Browser Agents** | **100 / 100** | **\$0.0143** | **\$1.43** | **7.9 s** | | Browser Use Cloud | 93 / 100 | \$0.0405 | \$4.05 | 32.0 s | Same 100 tasks. Same JSON output schemas. Same uniform pass predicate. Numbers from the June 2026 benchmark run — the [interactive report](https://pre.dev/browser-agents-benchmark.html) always has the latest. * **[Interactive report](https://pre.dev/browser-agents-benchmark.html)** — radar chart, leaderboard, per-task drilldown with traces and screenshots. * **[Raw data + reproduction](https://github.com/predotdev/browser-agents-benchmark)** — clone, set two API keys, `bun run bench`. ## Two ways to call it `POST https://api.pre.dev/browser-agent` with a tasks array. Sync, async, or live SSE streams. Up to 1,000 tasks per request. One-click install into Cursor, Claude Code, VS Code, or Windsurf. Your agent gets `browser_agent` as a tool — no orchestration code. ## Next * [Quickstart](/browser-agents/quickstart) — runnable curl / TS / Python / MCP * [REST API reference](/browser-agents/api/run-task) * [MCP tool setup](/browser-agents/mcp-tool) # Quickstart Source: https://docs.pre.dev/browser-agents/quickstart Four copy-paste examples: curl, TypeScript, Python, MCP. Sign in once at [pre.dev/projects/key](https://pre.dev/projects/key) and copy your key. Set it as `PREDEV_API_KEY` before running any of the examples below. Every example below: * uses your `PREDEV_API_KEY` env var * hits the live API at `https://api.pre.dev` * extracts the H1 from `example.com` as the simplest possible task ## 1. curl ```bash theme={null} export PREDEV_API_KEY=... # from pre.dev/projects/key curl -X POST https://api.pre.dev/browser-agent \ -H "Authorization: Bearer $PREDEV_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "tasks": [{ "url": "https://example.com", "instruction": "Extract the heading.", "output": { "type": "object", "properties": { "heading": { "type": "string" } }, "required": ["heading"] } }] }' ``` ## 2. TypeScript ```ts theme={null} import { PredevAPI } from 'predev-api'; const client = new PredevAPI({ apiKey: process.env.PREDEV_API_KEY! }); const result = await client.browserAgent([ { url: 'https://example.com', instruction: 'Extract the heading.', output: { type: 'object', properties: { heading: { type: 'string' } }, required: ['heading'], }, }, ]); console.log(result.results[0].data); // { heading: 'Example Domain' } ``` ## 3. Python ```python theme={null} import os from predev_api import PredevAPI client = PredevAPI(api_key=os.environ["PREDEV_API_KEY"]) result = client.browser_agent([ { "url": "https://example.com", "instruction": "Extract the heading.", "output": { "type": "object", "properties": {"heading": {"type": "string"}}, "required": ["heading"], }, } ]) print(result["results"][0]["data"]) # {'heading': 'Example Domain'} ``` ## 4. MCP (Claude Code, Cursor) Add pre.dev as an MCP server. For Claude Code: ```bash theme={null} claude mcp add --transport http predev https://api.pre.dev/mcp ``` For Cursor and other editors, add the HTTP server to your MCP config: ```json theme={null} { "mcpServers": { "predev": { "url": "https://api.pre.dev/mcp" } } } ``` On first use a browser tab opens — sign in to pre.dev to authorize. Then your agent gets a `browser_agent` tool it can call directly. Example prompt to the agent: > Use the `browser_agent` tool to extract the product title and price > from [https://www.apple.com/iphone-17-pro/](https://www.apple.com/iphone-17-pro/) and return > the JSON. Full MCP reference: [MCP Tool](/browser-agents/mcp-tool) ## What happens under the hood 1. Your POST lands and your tasks are queued. 2. Each task is dispatched to an isolated, sandboxed browser. 3. An AI planner drives the browser through navigation, actions, and extraction. 4. The result streams back as structured JSON, validated against your `output` schema. 5. Billed per successful task. Failed tasks are free. ## Streaming + async modes The quickstart uses sync mode (one HTTP request, one JSON response). For long-running task sets, flip to async: ```bash theme={null} # Async: returns immediately with batchId, poll for progress curl -X POST https://api.pre.dev/browser-agent \ -H "Authorization: Bearer $PREDEV_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "async": true, "tasks": [...] }' # → { "id": "69df...", "status": "processing" } # Poll for the run curl https://api.pre.dev/browser-agent/$BATCH_ID \ -H "Authorization: Bearer $PREDEV_API_KEY" ``` Or Server-Sent Events for live per-step updates: ```bash theme={null} curl -N -X POST https://api.pre.dev/browser-agent \ -H "Authorization: Bearer $PREDEV_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "stream": true, "tasks": [...] }' # → event: task_event ... \n event: task_result ... \n event: done ``` Full wire format: [Run a Task](/browser-agents/api/run-task) # Node SDK Source: https://docs.pre.dev/browser-agents/sdks/node TypeScript / Node.js client for pre.dev Browser Agents — run tasks sync, async, or streamed. The official TypeScript client for pre.dev. `predev-api` ships both the Architect and Browser Agents surfaces — one package, one key, full type support. ## Installation ```bash theme={null} npm install predev-api ``` ## Quick Start ```typescript theme={null} import { PredevAPI } from 'predev-api'; const predev = new PredevAPI({ apiKey: process.env.PREDEV_API_KEY! }); const result = await predev.browserAgent([ { url: 'https://example.com', instruction: 'Extract the page heading.', output: { type: 'object', properties: { heading: { type: 'string' } }, required: ['heading'], }, }, ]); console.log(result.results[0].data); // → { heading: "Example Domain" } ``` ## Authentication Grab a key from the Browser Agents dashboard. ```typescript theme={null} const predev = new PredevAPI({ apiKey: 'YOUR_API_KEY' }); ``` ## API Methods ### `browserAgent()` Submit one or more browser tasks. Overloaded based on `stream`: ```typescript theme={null} // Sync / async → Promise predev.browserAgent(tasks, { concurrency?: number; async?: boolean }): Promise; // Streaming → AsyncGenerator predev.browserAgent(tasks, { concurrency?: number; stream: true }): AsyncGenerator; ``` **Parameters:** * `tasks` **(required)**: `BrowserTask[]` — see [Task shape](#task-shape) * `options.concurrency` **(optional)**: `number` — parallel workers (1–20, default 5) * `options.async` **(optional)**: `boolean` — return immediately with a batch id; poll with `getBrowserAgent()` * `options.stream` **(optional)**: `true` — return an async generator of SSE frames instead ### Task shape ```typescript theme={null} interface BrowserTask { url: string; // required instruction?: string; // natural-language goal input?: Record; // string inputs the agent uses during the run output?: Record; // JSON Schema for the data to extract } ``` ### `getBrowserAgent()` Fetch the status and results of a task submission by id. Works for in-progress and completed submissions. ```typescript theme={null} const result = await predev.getBrowserAgent(id, { includeEvents?: boolean }); ``` **Parameters:** * `id` **(required)**: `string` — id returned from `browserAgent(tasks, { async: true })` or from streaming * `options.includeEvents` **(optional)**: `boolean` — include the full per-step event timeline (navigation, plan, screenshot, action, validation). Payloads can be large. ### `listBrowserAgents()` List your past and in-progress runs, newest first. ```ts theme={null} const { batches, total, hasMore } = await client.listBrowserAgents({ limit: 20, // optional skip: 0, // optional status: 'completed' // optional: 'processing' | 'completed' }); ``` ### `browserAgentStatus()` Your live queue snapshot — running / queued counts and your plan's in-flight cap. Poll it to throttle a large submit loop. ```ts theme={null} const q = await client.browserAgentStatus(); // { userId, running, claimed, pending, total, cap } if (q.total < q.cap - 10) { await client.browserAgent(nextChunk, { async: true }); } ``` ## Response Types ```typescript theme={null} interface BrowserAgentTaskResult { url: string; status: | 'SUCCESS' | 'PENDING' | 'ERROR' | 'TIMEOUT' | 'BLOCKED' | 'CAPTCHA_FAILED' | 'LOOP' | 'NO_TARGET'; data?: unknown; creditsUsed: number; durationMs: number; error?: string; } interface BrowserAgentResponse { id: string; total: number; completed: number; results: BrowserAgentTaskResult[]; totalCreditsUsed: number; status: 'processing' | 'completed' | 'failed'; createdAt?: string; completedAt?: string; } ``` ## Streaming Events ```typescript theme={null} type BrowserAgentEventType = | 'navigation' // agent loaded a URL | 'screenshot' // frame captured | 'plan' // agent reasoned about next steps | 'action' // click / type / scroll / extract | 'validation' // output schema or success condition checked | 'done' // task finished | 'error'; // task errored interface BrowserAgentStreamEvent { taskIndex: number; type: BrowserAgentEventType; timestamp: number; iteration?: number; data: any; } type BrowserAgentSSEMessage = | { event: 'task_event'; data: BrowserAgentStreamEvent } | { event: 'task_result'; data: BrowserAgentTaskResult & { taskIndex: number } } | { event: 'done'; data: BrowserAgentResponse } | { event: 'error'; data: { error: string } }; ``` ## Examples ### Sync — wait for every task ```typescript theme={null} const result = await predev.browserAgent( [ { url: 'https://news.ycombinator.com', instruction: 'Extract the top 5 story titles.' }, { url: 'https://www.reddit.com/r/programming', instruction: 'Extract the top 5 post titles.' }, ], { concurrency: 2 }, ); for (const r of result.results) { console.log(r.status, r.data); } ``` ### Async — poll for completion ```typescript theme={null} const { id } = await predev.browserAgent(tasks, { async: true }); while (true) { const status = await predev.getBrowserAgent(id); if (status.status === 'completed' || status.status === 'failed') { console.log(status.results); break; } console.log(`${status.completed}/${status.total} done`); await new Promise(r => setTimeout(r, 5000)); } ``` ### Streaming — live per-step events ```typescript theme={null} for await (const msg of predev.browserAgent(tasks, { stream: true })) { if (msg.event === 'task_event') { console.log(`[task ${msg.data.taskIndex}]`, msg.data.type); } else if (msg.event === 'task_result') { console.log(`[task ${msg.data.taskIndex}]`, msg.data.status, msg.data.data); } else if (msg.event === 'done') { console.log('batch done:', msg.data.id, msg.data.totalCreditsUsed, 'credits'); } else if (msg.event === 'error') { console.error('error:', msg.data.error); } } ``` ### Full timeline for a past submission ```typescript theme={null} const result = await predev.getBrowserAgent(id, { includeEvents: true }); for (const task of result.results) { console.log(task.status, task.url); for (const event of (task as any).events ?? []) { console.log(' -', event.type); } } ``` ## Error Handling The SDK throws typed exceptions for the most common gating cases. The two billing-gate exceptions carry an `actionUrl` — a deep link back to pre.dev that auto-opens the right modal (subscribe / buy credits) when the user lands there. Same exceptions fire on REST and SSE error paths. ```typescript theme={null} import { PredevAPIError, AuthenticationError, RateLimitError, SubscriptionRequiredError, InsufficientCreditsError, QueueFullError, BatchTooLargeError, } from 'predev-api'; try { const result = await predev.browserAgent(tasks); } catch (err) { if (err instanceof InsufficientCreditsError) { // Subscription is fine, balance is too low — send the user to the credits modal. if (err.actionUrl) window.open(err.actionUrl, '_blank'); } else if (err instanceof SubscriptionRequiredError) { // Trial limit hit — send the user to the subscribe modal. if (err.actionUrl) window.open(err.actionUrl, '_blank'); } else if (err instanceof AuthenticationError) { // 401 — invalid or missing API key } else if (err instanceof RateLimitError) { // 429 RATE_LIMITED — back off and retry } else if (err instanceof QueueFullError) { // 429 QUEUE_FULL — wait for in-flight tasks to drain } else if (err instanceof BatchTooLargeError) { // 400 — split into smaller batches } else if (err instanceof PredevAPIError) { console.error(err.message); } } ``` | Exception | HTTP | `code` | | --------------------------- | ----- | ----------------------- | | `SubscriptionRequiredError` | 402 | `SUBSCRIPTION_REQUIRED` | | `InsufficientCreditsError` | 402 | `INSUFFICIENT_CREDITS` | | `RateLimitError` | 429 | `RATE_LIMITED` | | `QueueFullError` | 429 | `QUEUE_FULL` | | `BatchTooLargeError` | 400 | `BATCH_TOO_LARGE` | | `AuthenticationError` | 401 | — | | `PredevAPIError` | other | — | Mid-stream errors on the SSE stream throw the same typed exceptions — a `for await` loop wrapped in `try/catch` is enough. # Browser Agents SDKs Source: https://docs.pre.dev/browser-agents/sdks/overview Official Python and Node SDKs for pre.dev Browser Agents — fully-typed clients with sync, async, and SSE streaming built in. The same `predev-api` package that wraps the Architect endpoints also ships the Browser Agents client. One install, one key, both surfaces. ## Official SDKs `pip install predev-api` — synchronous, async, and streaming task runs with a single method. `npm install predev-api` — fully-typed TypeScript client with async generators for SSE streams. ## Features Both SDKs expose the full Browser Agents surface: * **Run tasks** — submit one or thousands of tasks in a single call, with `concurrency` control * **Sync mode** — waits for every task to complete and returns the full result * **Async mode** — submit and return immediately with a batch id you can poll * **Streaming mode** — live SSE stream of `task_event`, `task_result`, `done`, and `error` frames * **Status polling** — fetch a task submission by id, optionally with the full per-step event timeline (screenshots, plans, actions, validations) * **Typed results** — structured `data` validated against your JSON Schema `output` * **Error handling** — typed exceptions for auth, rate limits, and API errors Grab a key, set it as `PREDEV_API_KEY`, then follow either SDK page. # Python SDK Source: https://docs.pre.dev/browser-agents/sdks/python Python client for pre.dev Browser Agents — run tasks sync, async, or streamed. The official Python client for pre.dev. `predev-api` ships both the Architect and Browser Agents surfaces — one package, one key. ## Installation ```bash theme={null} pip install predev-api ``` ## Quick Start ```python theme={null} from predev_api import PredevAPI predev = PredevAPI(api_key="YOUR_API_KEY") result = predev.browser_agent([ { "url": "https://example.com", "instruction": "Extract the page heading.", "output": { "type": "object", "properties": { "heading": { "type": "string" } }, "required": ["heading"] } } ]) print(result["results"][0]["data"]) # → { "heading": "Example Domain" } ``` ## Authentication Grab a key from the Browser Agents dashboard. ```python theme={null} predev = PredevAPI(api_key="YOUR_API_KEY") ``` ## API Methods ### `browser_agent()` Submit one or more browser tasks and get the results back. ```python theme={null} result = predev.browser_agent( tasks, concurrency=None, # parallel workers, 1–20, default 5 stream=False, # set True to get an SSE iterator run_async=False, # set True to return immediately with a batch id ) ``` **Parameters:** * `tasks` **(required)**: `List[Dict]` — see [Task shape](#task-shape) below * `concurrency` **(optional)**: `int` — parallel workers within this batch (1–20, default 5) * `stream` **(optional)**: `bool` — when `True`, returns an iterator yielding SSE events instead of a final result * `run_async` **(optional)**: `bool` — when `True`, returns immediately with `{ id, status: "processing" }`; poll with `get_browser_agent(id)` **Returns:** * Default: `Dict` with `id`, `total`, `completed`, `results`, `totalCreditsUsed`, `status` * With `stream=True`: `Iterator[Dict]` yielding `{ "event": ..., "data": ... }` frames * With `run_async=True`: `Dict` with `id` and `status: "processing"` — poll `get_browser_agent(id)` ### Task shape ```python theme={null} { "url": "https://...", # required "instruction": "Extract the price.", # natural-language goal "input": { "query": "laptops" }, # string inputs the agent uses during the run "output": { # JSON Schema describing the data to extract "type": "object", "properties": { "price": { "type": "number" } }, "required": ["price"] } } ``` ### `get_browser_agent()` Fetch the status and results of a task submission by id. Works for in-progress and completed submissions. ```python theme={null} result = predev.get_browser_agent(batch_id, include_events=False) ``` **Parameters:** * `batch_id` **(required)**: `str` — id returned from `browser_agent(..., run_async=True)` or from streaming * `include_events` **(optional)**: `bool` — when `True`, includes the full per-step event timeline (navigation, plan, screenshot, action, validation) for each task. Payloads can be large. **Returns:** `Dict` with the same shape as `browser_agent()` sync response, plus `events[]` on each task (or `liveEvents[]` for tasks still in flight) when `include_events=True`. ### `list_browser_agents()` List your past and in-progress runs, newest first. ```python theme={null} result = client.list_browser_agents(limit=20, skip=0, status="completed") # {"batches": [...], "total": 132, "hasMore": True} ``` ### `browser_agent_status()` Your live queue snapshot — running / queued counts and your plan's in-flight cap. Poll it to throttle a large submit loop. ```python theme={null} q = client.browser_agent_status() # {"userId": ..., "running": 12, "claimed": 3, "pending": 40, "total": 55, "cap": 100} if q["total"] < q["cap"] - 10: client.browser_agent(next_chunk, run_async=True) ``` ## Response Shape ```python theme={null} { "id": "65f8a9d2c1e4b5a6f7e8d9c0", "total": 2, "completed": 2, "results": [ { "url": "https://example.com", "instruction": "Extract the page heading.", "status": "SUCCESS", # SUCCESS | ERROR | TIMEOUT | BLOCKED | CAPTCHA_FAILED | LOOP | NO_TARGET | PENDING "data": { "heading": "Example Domain" }, "creditsUsed": 0.11, "durationMs": 4820 }, { "url": "https://news.ycombinator.com", "status": "SUCCESS", "data": { "stories": ["..."] }, "creditsUsed": 0.18, "durationMs": 8132 } ], "totalCreditsUsed": 0.29, "status": "completed", # processing | completed | failed "createdAt": "2026-04-16T18:22:10.224Z", "completedAt": "2026-04-16T18:22:27.510Z" } ``` ## Examples ### Sync — wait for every task ```python theme={null} result = predev.browser_agent([ { "url": "https://news.ycombinator.com", "instruction": "Extract the top 5 story titles." }, { "url": "https://www.reddit.com/r/programming", "instruction": "Extract the top 5 post titles." }, ], concurrency=2) for r in result["results"]: print(r["status"], r.get("data")) ``` ### Async — poll for completion ```python theme={null} import time batch = predev.browser_agent(tasks, run_async=True) batch_id = batch["id"] while True: status = predev.get_browser_agent(batch_id) if status["status"] in ("completed", "failed"): break print(f"{status['completed']}/{status['total']} done") time.sleep(5) for r in status["results"]: print(r["status"], r.get("data")) ``` ### Streaming — live per-step events ```python theme={null} for msg in predev.browser_agent(tasks, stream=True): if msg["event"] == "task_event": e = msg["data"] print(f"[task {e['taskIndex']}] {e['type']}") elif msg["event"] == "task_result": r = msg["data"] print(f"[task {r['taskIndex']}] {r['status']} → {r.get('data')}") elif msg["event"] == "done": print("batch done:", msg["data"]["id"], msg["data"]["totalCreditsUsed"], "credits") elif msg["event"] == "error": print("error:", msg["data"]["error"]) ``` ### Full timeline for a past submission ```python theme={null} result = predev.get_browser_agent(batch_id, include_events=True) for task in result["results"]: print(task["status"], task["url"]) for event in task.get("events", []): print(" -", event["type"]) ``` ## Error Handling The SDK raises typed exceptions for the most common gating cases. The two billing-gate exceptions carry an `action_url` — a deep link back to pre.dev that auto-opens the right modal (subscribe / buy credits) when the user lands there. Same exceptions fire on REST and SSE error paths. ```python theme={null} import webbrowser from predev_api import ( PredevAPIError, AuthenticationError, RateLimitError, SubscriptionRequiredError, InsufficientCreditsError, QueueFullError, BatchTooLargeError, ) try: result = predev.browser_agent(tasks) except InsufficientCreditsError as e: # Subscription is fine, balance is too low — send the user to the credits modal. if e.action_url: webbrowser.open(e.action_url) except SubscriptionRequiredError as e: # Trial limit hit — send the user to the subscribe modal. if e.action_url: webbrowser.open(e.action_url) except AuthenticationError: # 401 — invalid or missing API key ... except RateLimitError: # 429 RATE_LIMITED — back off and retry ... except QueueFullError: # 429 QUEUE_FULL — wait for in-flight tasks to drain ... except BatchTooLargeError: # 400 — split into smaller batches ... except PredevAPIError as e: print(e) ``` | Exception | HTTP | `code` | | --------------------------- | ----- | ----------------------- | | `SubscriptionRequiredError` | 402 | `SUBSCRIPTION_REQUIRED` | | `InsufficientCreditsError` | 402 | `INSUFFICIENT_CREDITS` | | `RateLimitError` | 429 | `RATE_LIMITED` | | `QueueFullError` | 429 | `QUEUE_FULL` | | `BatchTooLargeError` | 400 | `BATCH_TOO_LARGE` | | `AuthenticationError` | 401 | — | | `PredevAPIError` | other | — | Mid-stream errors on the SSE stream raise the same typed exceptions — a `for msg in client.browser_agent(..., stream=True):` loop wrapped in `try/except` is enough. # Changelog Source: https://docs.pre.dev/changelog What's new in the pre.dev API and SDKs. User-facing changes to the pre.dev API, SDKs, and dashboard. Subscribe via the [GitHub releases page](https://github.com/predotdev/predev-api/releases) to get notified on every SDK bump. ## 2026-07-15 ### Act from your inbox, and a much snappier app * **Answer the agent's questions straight from email.** If the agent asks a clarifying question while you're away, the email now has one-click answer buttons — tap your choice and the build picks up immediately. Links are signed and safe from email scanners. * **Credits run out mid-build? You get the full picture.** The build pauses safely and you receive an email with current progress, screenshots, and the live preview link. Top up and resume where it left off. A "we'll email you when it's ready" cue now appears during sprints so you can close the tab with confidence. * **A broad speed pass.** The dashboard, opening a project, and chat are all significantly faster, and the hottest screens paint instantly from cache. * **Renaming a project keeps old links working**, and builds now survive server restarts and idle timers instead of stalling. ## 2026-07-13 ### Watch the agent think, and dial the effort * **Live thinking ticker.** While the agent reasons, its thinking streams in real time; finished reasoning collapses into a "Thoughts" block you can expand later. * **Effort levels.** Choose how deep each sprint goes with `/effort` — **low** (fast direct pass), **medium** (task-list loop), or **high** (full research → code → verify pipeline), with **auto** routing each sprint for you by default. See [Build Modes & Effort](/coding-agent/building/build-modes). * **Fewer unnecessary questions.** The agent now asks clarifying questions only when it genuinely needs an answer — and pings you when a direct sprint finishes. * **Cleaner parallel-agent view** with per-branch objective, progress, and conclusion. ## 2026-07-09 ### The terminal-style workspace, on the web * **Terminal chat everywhere.** The web workspace now matches the CLI: a terminal-style chat with a `/` command palette (`/sprint`, `/effort`, `/model`, `/balance`, `/fork`, and more) and live view tabs for Plan, Code, and Preview. See [The Workspace](/coding-agent/workspace). * **The pre.dev CLI** brings the same agent, slash commands, and views to your terminal. * **Before/after screenshot evidence** on every browser verification step — see exactly what the agent checked and what changed. * **Builds pick themselves back up.** Interrupted sprints resume automatically instead of waiting for you to notice. ## 2026-07-08 ### Generate media inside your build * **Images, video, audio, and music in chat.** Ask the agent for a logo, a hero video, a voiceover, or a soundtrack mid-build — generated media lands directly in your project. * **More reliable builds against your acceptance criteria**, with a hardened verification loop. * Faster, cheaper generated images, and GitHub sync no longer breaks from build cache. ## 2026-06-25 ### Parallel agents you can actually inspect * **The parallel-agent panel shows real work**: per-agent live streaming, full tool detail, and real file diffs as multiple agents fan out across a sprint. * **Upgraded coding agent model** across all build paths, plus fixes for the agent getting stuck repeating itself. * Faster app load and a cleaner agent step view with per-step timestamps. ## 2026-06-14 ### Usage-based billing for Browser Agents * **Pay per task, not per seat.** Browser agent tasks bill against your credit balance — 1 credit = \$0.10, with a 0.1-credit floor per task. **Failed tasks are free.** * **Tier-aware rate limits** raise throughput for paid plans. * Typed billing errors with `actionUrl` deep-links (see the 2026-04-30 entry) now cover the full task lifecycle. ## 2026-06-09 ### Sessions: fork, merge, and build in parallel * **Run multiple build sessions at once.** Fork a session to try something risky, work several in parallel, and merge back what works — merges no longer drop fork edits, even when git is in a bad state. * **OAuth connectors, MCP servers, and agent skills** arrive in the coding agent: connect your services once and every build inherits them. See [Integrations](/coding-agent/integrations/overview). * Secrets and build artifacts now stay strictly out of your GitHub repos. ## 2026-05-26 ### Real-time collaboration and mobile preview * **Multi-session collaboration**: live sync, presence avatars, and per-session status across everyone working on a project. Session forks landed earlier in the month and are now hardened. * **Mobile preview** with a phone-framed viewport and an Expo QR code for native projects. * **Much faster returns to a project**: speculative pre-resume from the dashboard and an instant hot path when nothing changed. ## 2026-05-08 ### Browser agents join the chat * **`browser_agent` in the workspace**: the planning agent can now drive a real browser mid-conversation, with an inline timeline card showing every step. * **Faster and tougher browser automation**: an express path for simple extractions, a form-fill specialist, and stronger stealth for protected sites. * Queue messages while architecture generation is running — they're picked up the moment it finishes. ## 2026-04-30 ### `pre.dev/projects/key` — one-click API key copy New page at [https://pre.dev/projects/key](https://pre.dev/projects/key). Sign in once and copy your key — masked-key reveal + copy button inside the dashboard sidebar. Useful when sharing example apps and SDK quickstarts: link any "Get an API key" CTA straight here. Unauthenticated visitors are bounced to sign-in and auto-returned to `/projects/key` after. ### Browser Agents — typed billing errors with `actionUrl` Non-2xx responses for [`POST /browser-agent`](/browser-agents/api/run-task) now carry a structured body: ```json theme={null} { "error": "Need ~0.5 credits, have 0.00. Buy more to continue.", "code": "INSUFFICIENT_CREDITS", "actionUrl": "https://pre.dev/projects/browser-agents?upgrade=credits" } ``` `code` is one of `SUBSCRIPTION_REQUIRED`, `INSUFFICIENT_CREDITS`, `RATE_LIMITED`, `QUEUE_FULL`, `BATCH_TOO_LARGE`. `actionUrl` (when present) deep-links the user back to pre.dev with the right billing modal pre-opened — `window.open(actionUrl)` is enough to send the user to the credit-purchase or subscription flow without any extra UI. The same body is emitted on the SSE `error` event when streaming. #### Node SDK — `predev-api@1.1.0` ```ts theme={null} import { InsufficientCreditsError, SubscriptionRequiredError } from 'predev-api'; try { await client.browserAgent(tasks); } catch (e) { if (e instanceof InsufficientCreditsError) window.open(e.actionUrl); else if (e instanceof SubscriptionRequiredError) window.open(e.actionUrl); } ``` New typed exceptions: `SubscriptionRequiredError`, `InsufficientCreditsError`, `QueueFullError`, `BatchTooLargeError`. All non-breaking — existing `instanceof PredevAPIError` checks still match. See the [Node SDK error-handling docs](/browser-agents/sdks/node#error-handling). #### Python SDK — `predev-api==1.1.0` ```python theme={null} from predev_api import InsufficientCreditsError, SubscriptionRequiredError import webbrowser try: client.browser_agent(tasks) except InsufficientCreditsError as e: if e.action_url: webbrowser.open(e.action_url) except SubscriptionRequiredError as e: if e.action_url: webbrowser.open(e.action_url) ``` New exceptions mirror the Node SDK with `action_url` field. See the [Python SDK error-handling docs](/browser-agents/sdks/python#error-handling). # CLI Commands Source: https://docs.pre.dev/cli/commands Every slash command in the pre.dev CLI, grouped by what it does. Type `/` in the chat input to open the command palette. Keep typing to filter, use ↑/↓ to move, Enter to run, Esc to dismiss. Commands that take arguments (like `/sprint` and `/fork`) keep the composer open so you can type the rest. ## Building | Command | Description | | ------------------- | ------------------------------------------------------------------------- | | `/sprint ` | Launch a custom sprint in a new session — builds the feature you describe | | `/effort` | Set the sprint effort level (auto / low / medium / high) | | `/model` | Choose models per phase (chat / research / coding / acceptance) | | `/pro` | Toggle pro mode — pin every phase to Claude Opus | ### /sprint example ``` /sprint add CSV export to the reports page with a progress toast ``` The sprint opens as a new tab in the fleet bar and builds in an isolated session while you keep chatting in main. Your `/effort` and `/model` settings apply and persist per project. ## Sessions | Command | Description | | ---------------- | --------------------------------------------- | | `/fork ` | Spin a prompt off into a new isolated session | ### /fork example ``` /fork write integration tests for the billing webhooks ``` The fork runs in parallel in its own tab — you stay in your current session. Prefixing any message with `>>` does the same thing: ``` >> upgrade eslint and fix any new violations ``` Forked sessions work in isolated git worktrees, so parallel sessions never trample each other's changes. Open sessions persist: quit the CLI and relaunch, and your tabs come back. ## Project | Command | Description | | ---------- | ---------------------------------------------------- | | `/reverse` | Map the existing codebase — runs reverse engineering | | `/arch` | Open the Architecture graph view | | `/kanban` | Open the Kanban board | | `/roadmap` | Open the Roadmap / Gantt view | `/kanban`, `/roadmap`, and `/arch` render right in the terminal — press Esc to return to chat. They show the same project data as the web workspace. `/reverse` runs in the background (typically a few minutes) and you can keep chatting while it maps your codebase into the architecture graph. See [Work on an Existing Repo](/cli/existing-repos) for the full flow. ## Setup | Command | Description | | ---------- | ------------------------------------------------------------------------------------------------------------------------- | | `/login` | Log in to pre.dev (or switch accounts) via your browser | | `/skills` | Manage agent skills — toggle, add, remove | | `/mcp` | Manage MCP servers — toggle, add, remove | | `/balance` | Show your remaining credit balance | | `/topup` | Buy more credits — opens billing in your browser; a run stopped by the credit wall resumes automatically after you top up | | `/upgrade` | Upgrade your plan — opens the plan picker in your browser | Skills and MCP servers are account-level — anything you configure in the CLI applies across your projects, in the CLI and on the web. OAuth integrations are managed from the web workspace. See [Integrations](/coding-agent/integrations/overview). ## Launch flags Flags you can pass to `predev` itself: | Flag | Description | | ------------------------ | --------------------------------------------------------------------- | | `predev ""` | Start with an opening prompt instead of an empty chat | | `predev --new` (or `-n`) | Create a fresh project for this directory, even if one already exists | # Work on an Existing Repo Source: https://docs.pre.dev/cli/existing-repos Point the pre.dev CLI at a codebase you already have and start shipping features on it. The CLI is the fastest way to bring pre.dev into a codebase that already exists. There's no import step and nothing to upload — `cd` into the repo, run `predev`, and the agent works on your files where they live. ```bash theme={null} cd my-existing-app predev ``` The first launch in a folder creates a pre.dev project linked to that directory. When the CLI sees an existing codebase — a GitHub remote or a directory full of source files — it offers to reverse-engineer it before you start: ``` Existing repo detected — GitHub: acme/my-existing-app. Want pre.dev to reverse-engineer it first? ``` Pick **Yes** to kick off the mapping right away, or **Not now** and run `/reverse` whenever you're ready. ``` /reverse ``` Maps the existing code into your project's architecture graph. It runs in the background — typically a few minutes — and you can keep chatting while it works. When it's done, `/arch` shows the resulting architecture graph right in the terminal, and the agent plans future work against it instead of rediscovering your codebase every session. ``` /sprint add SSO login with Okta alongside the existing email auth ``` Each sprint opens as a new tab and builds in an isolated session. With the architecture mapped, sprints slot new work into the structure you already have — reusing your patterns, stack, and conventions rather than inventing new ones. For smaller changes, just chat: ``` the date formatting on the invoices page is wrong for non-US locales — fix it ``` The agent edits files directly in your working tree, so your normal workflow is the review process: ```bash theme={null} git status git diff ``` Stage, commit, and push on your own terms. Parallel sessions (`/fork`, `/sprint`) work in isolated git worktrees so they never collide with your checkout or with each other; their work lands back in your main workspace when they finish. Everything stays in sync with the web workspace. The reverse-engineered architecture, Kanban board, and roadmap for this repo are all there when you open the same project at pre.dev. ## Tips * **One directory, one project.** Relaunching `predev` in the same folder resumes the same project — history, sessions, and settings included. Use `predev --new` if you want a clean slate for the same directory. * **Re-run `/reverse` after big changes.** If the codebase shifts significantly (a large merge, a refactor done outside pre.dev), reverse-engineer again so the architecture graph matches reality. ## Next steps Every slash command, grouped by what it does. Install, first run, and when to use the CLI vs the web. # pre.dev CLI Source: https://docs.pre.dev/cli/overview The pre.dev agent in your terminal, working directly on your local repo. The `predev` CLI brings the full pre.dev agent to your terminal. Run it in any project directory and you get the same agent chat and slash commands as the web workspace — except the agent reads and edits the files in that folder directly. ```bash theme={null} curl -fsSL https://pre.dev/install | bash ``` Works on macOS and Linux (Apple Silicon, ARM64, and x64). The installer puts everything under `~/.predev`, adds `predev` to your PATH, and keeps itself up to date — you never run the installer again. ## First run ```bash theme={null} cd my-project curl -fsSL https://pre.dev/install | bash ``` The installer launches `predev` for you as soon as it finishes — one command and you're in the agent. It also adds `predev` to your PATH for next time (set `PREDEV_NO_AUTORUN=1` to skip the auto-launch, e.g. in provisioning scripts). ```bash theme={null} cd my-project predev ``` The current directory becomes the agent's workspace. You can also pass an opening prompt directly: `predev "add dark mode to the settings page"`. On first launch the CLI opens your browser to pre.dev. Sign in (or pick your account), approve, and return to the terminal — the CLI picks up your session automatically. Your credential is stored locally in `~/.predev/auth.json`; you won't need to log in again on that machine. Run `/login` anytime to switch accounts. The CLI links each directory to a pre.dev project. The first launch in a folder creates one; every launch after that resumes it — chat history, sessions, and settings included. Pass `--new` to start a fresh project for the same folder. If the folder already contains code, the CLI detects it and offers to reverse-engineer the codebase into your project's architecture before you start. See [Work on an Existing Repo](/cli/existing-repos). ## What you can do Everything runs through the chat input. Type `/` to open the command palette — see the full [command reference](/cli/commands). Ask questions, request changes, debug — the agent reads and edits the files in your working directory. `/sprint ` builds a feature end to end in a parallel session while you keep working. `/fork ` spins a task off into an isolated session — run several at once from the fleet bar. `/reverse` maps an existing codebase into your project's architecture graph. `/kanban`, `/roadmap`, and `/arch` render the Kanban board, roadmap, and architecture graph right in your terminal. `/balance` shows remaining credits; `/model`, `/effort`, and `/pro` control which models do the work. If you run out mid-task, the CLI opens your billing page — top up and it resumes the interrupted work automatically. ## CLI or web? Both clients share the same projects, sessions, and data — you can start in one and continue in the other. | Use the CLI when... | Use the web when... | | ----------------------------------------------------------- | ------------------------------------------------------------ | | You're working on a repo that already lives on your machine | You're starting a brand-new project from an idea | | You want the agent editing local files you review with git | You want a hosted preview you can click through as it builds | | You live in the terminal and want everything in one place | You're collaborating with teammates in a shared workspace | | You're adopting pre.dev into an existing codebase | You're managing specs, milestones, and builds visually | The CLI and web stay in sync. A sprint started in the terminal shows up in the web workspace, and if a run is live from the web, the CLI reflects it instead of starting a competing run. ## Staying up to date The install one-liner is a one-time bootstrap. After that, the `predev` launcher checks for new releases in the background and installs them automatically — every launch runs the newest installed version. New versions land in `~/.predev/versions/` and downloads are checksum-verified. ## Next steps Every slash command, grouped by what it does. Point pre.dev at a codebase you already have. How pre.dev's agents plan, build, and verify. MCP servers, skills, and OAuth services — all manageable from the CLI. # Verification Source: https://docs.pre.dev/coding-agent/building/acceptance-criteria How pre.dev proves every task ships working code — static checks, real browser flows, screenshots, and design review. pre.dev's key differentiator: agents **cannot mark a task as complete** until it passes verification. Not "the code compiles" — the agent drives your app in a real browser, exercises the feature end to end, and captures screenshot evidence before a PR opens. ## What drives verification Verification isn't generic smoke testing. Each user story in your spec carries **acceptance criteria** — concrete, testable statements of what "done" means. Those criteria are what the agent verifies against, so the checks map directly to what you asked for. During verification the agent's editing tools are disabled. It can observe and report, but it cannot quietly patch code to make a check pass — fixes happen in a separate coding pass, then verification runs again. ## The verification gate Every completed task passes through the full pipeline before a pull request is opened: The build agent implements the task based on the specification. Type checking, linting, and tests must pass — if any fail, the agent fixes and retries. The agent drives the running app in a real browser, exercising each acceptance criterion as a multi-step flow. UI files are scanned for accessibility, dark-mode, layout, and placeholder issues. All checks passed — a pull request is created with verified, working code. ## Static checks The baseline gate, adapted to your stack: For typed projects, full compilation must pass — no type errors, no missing imports, strict mode when configured. Python projects get mypy/pyright, Rust gets cargo check, and so on. Code must pass your project's configured linter (ESLint, Prettier, ruff, clippy, …) — consistent formatting, no unused variables, style guide compliance. New tests must pass and existing tests must not break. Verification rules are detected from your project configuration (tsconfig, eslint config, pytest.ini, etc.) — you don't configure anything manually. ## Browser flows For anything with a UI, static checks aren't enough. The agent drives your app in a real browser using scripted multi-step flows — the same way a user would: * **Navigate** to a page, then move between pages through the app's own links and buttons * **Fill** forms and **type** into inputs * **Click** buttons and links (resolved by visible text or selector) * **Wait** for elements to appear after an action triggers a load * **Evaluate** JavaScript to assert the outcome — row counts, toast text, updated state A flow that interacts with the app **must assert its outcome in the same flow**. Filling a form in one step and checking a count in a separate, unrelated flow proves nothing causally — the platform enforces that cause and effect are demonstrated together. ```text theme={null} Example flow — add a book and prove it appears: 1. navigate /dashboard 2. fill #title → "The Great Gatsby" 3. fill #author → "F. Scott Fitzgerald" 4. click Submit 5. wait .book-card 6. evaluate document.querySelectorAll('.book-card').length ``` If a step fails, the flow stops and reports exactly which step broke and why — the agent adjusts and re-runs the remaining steps. ### Screenshot evidence Before/after screenshots are captured automatically around every flow. They appear as cards on the flow's message in chat, so you can watch verification happen, and they're collected in your project's screenshot feed — the most recent one even becomes the thumbnail on your Preview button. ## Design review Alongside functional checks, an automated design review scans the UI files written in the session and returns issues with **file, line number, severity, and a suggested fix**: * **Accessibility** — missing alt text, unlabeled inputs, icon-only buttons without labels, removed focus outlines, click handlers without keyboard support, undersized touch targets, heading-hierarchy skips * **Typography** — missing font fallbacks, text too small to read on mobile * **Layout** — content-clipping overflow, fixed widths that break on mobile, z-index conflicts, inconsistent spacing scales * **Color & dark mode** — hardcoded colors without dark-mode variants, low-contrast text * **Component states** — buttons missing hover, disabled, or cursor styles * **Leftover placeholders** — lorem ipsum, TODO comments in rendered markup, example.com URLs, and hardcoded credentials Errors must be fixed before the task completes; the review re-runs to confirm. ## Verifying auth and roles Apps with authentication get verified as real signed-in users. The agent provisions temporary test accounts on demand — and for role-based access control, it can create a **separate test user per role** (admin, member, employer, job-seeker, whatever your app defines) and sign in as each one to confirm that role-gated routes show the right thing to the right user. Repeated verification of the same role reuses the same test user, so state you set up as "admin" persists across checks. ## Verification before the PR A pull request only opens after the acceptance pass finishes — the PR body lists the completed stories, and the evidence behind them (browser-flow steps, before/after screenshots, static-check results) lives in the chat feed and the project's screenshot gallery. You review the PR knowing every story it lists was exercised, not just generated. ## Why this matters Without a verification gate, AI-generated code often has: * Type errors that surface only at build time * Features that compile but don't actually work when clicked * UI that looks broken in dark mode or on mobile * Role checks that were never exercised * Placeholder text that ships to production pre.dev eliminates these by making verification a **gate** — not an afterthought. The agent iterates until everything passes; you only see the final, verified result. ## What's next? Verified work ships as a PR — review and merge on your terms. See the verified build live at your project's URL. # Build Modes & Effort Source: https://docs.pre.dev/coding-agent/building/build-modes Control what agents build next, how deep each sprint goes, and which models do the work. Building on pre.dev has two independent axes, plus a model picker: 1. **Sprint mode** — *what* to build next: the next roadmap task, the whole roadmap on autopilot, or a custom task you describe. 2. **Effort level** — *how deep* each sprint goes: a fast direct pass, a task-list loop, or the full research → code → verify pipeline. 3. **Model picker** — *which model* runs each phase of the work. ## Sprint mode: what to build Agents build **one roadmap task at a time**, then wait for your review before proceeding. The next incomplete task from your roadmap is assigned to the coding agent The agent implements the task in a secure sandbox Acceptance criteria are verified (types, lint, tests, browser) Review the result, give feedback, then continue to the next task **Best for:** learning how pre.dev works, sensitive codebases, and teaching the agent your preferences by reviewing early tasks. Agents work through the **entire roadmap autonomously**, building task after task until everything is done, credits run out, or you stop it. * Tasks follow the milestone order in your roadmap * Each task goes through acceptance verification before the next starts * Steer a running autopilot anytime by sending feedback in chat * The roadmap view shows real-time progress **Best for:** projects where you trust the spec and want maximum speed, overnight builds, and well-defined projects with clear requirements. Describe **any task** — a feature, a fix, a refactor — and the agent runs it through a full sprint, independent of the roadmap. Launch one by asking in chat ("build me a dark mode toggle") or with the slash command: ``` /sprint add CSV export to the reports page ``` If a sprint is already running, the new one is queued and starts automatically when the current one finishes. **Best for:** work that isn't on the roadmap yet — urgent fixes, experiments, or features you thought of mid-build. Just **talk to the agent**. Ask questions about the spec or the codebase, request explanations, or have it make small edits directly — no sprint needed. **Best for:** one-line fixes, debugging, asking the agent to explain code, and quick adjustments that don't warrant a full sprint. ### Choosing a sprint mode | Scenario | Recommended | | --------------------------------- | -------------------------------------------------- | | First time using pre.dev | Build Next Task | | Small MVP you want fast | Build on Autopilot | | Complex production app | Build Next Task (at least for the first milestone) | | Feature that isn't on the roadmap | Custom sprint | | Overnight build | Build on Autopilot | | Quick question or one-line fix | Chat | You can switch modes at any time: validate the first few tasks one at a time, flip to Autopilot once the agent has your patterns down, and drop into chat whenever you need a quick change. ## Effort level: how deep each sprint goes Set the effort level with `/effort`: | Level | Name | How it works | | -------- | --------- | --------------------------------------------------------------------------------- | | `auto` | Auto | Routes each sprint automatically based on the task (recommended) | | `low` | **Vibe** | Fast direct loop, minimal ceremony — great for quick iterations | | `medium` | **Todo** | Direct loop with a task list — the agent plans its steps, then works through them | | `high` | **Build** | The full research → code → verify pipeline | **When each is right:** * **Vibe (low)** — UI tweaks, copy changes, small features where speed matters more than process. * **Todo (medium)** — multi-step features that benefit from a visible task list but don't need a research phase. * **Build (high)** — complex features, integrations, and anything where you want the agent to research the codebase first and verify acceptance criteria at the end. * **Auto** — let pre.dev pick per sprint. Good default if you don't want to think about it. Effort applies per sprint: the setting at launch time governs how deep that sprint goes. Higher effort uses more [credits](/coding-agent/plans-and-credits) — the research and verification phases are extra model work. ## Model picker: which models do the work Every sprint moves through phases, and you can pin a different model to each with `/model`: | Phase | What it covers | | -------------- | ----------------------------------------------------- | | **Chat** | Interactive chat turns — the main ad-hoc loop | | **Research** | Exploring the codebase and requirements before coding | | **Coding** | Writing the implementation | | **Acceptance** | Verifying the result against acceptance criteria | Available models: | Model | Notes | | ------------------------ | ------------------------------------- | | **GLM 5.2** | The default — fast and cost-effective | | **Kimi K2.6** / **K2.7** | Strong open-weight alternatives | | **MiniMax M3** | Open-weight alternative | | **Claude Sonnet 4.6** | High quality, balanced cost | | **Claude Opus 4.8** | The Pro model — maximum quality | | **GPT 5.5** | OpenAI's flagship | Typing `/model` walks you through it: pick a phase, then pick a model. Set a phase back to **Default** to return it to GLM 5.2. ### Pro Mode `/pro` is the one-toggle shortcut: it pins **every phase** to the Pro model (Claude Opus 4.8) for maximum quality. Pro Mode uses more credits per sprint, so a common pattern is to iterate in standard mode and flip on Pro for final production passes. See [Pro Mode & Model Selection](/coding-agent/building/pro-mode) for details, and [pricing](https://pre.dev/pricing) for plan differences. ## What's next? How every task is verified before it counts as done. Watch build progress in real time from the roadmap. # Collaboration Source: https://docs.pre.dev/coding-agent/building/collaboration Invite team members and control project access. pre.dev projects support role-based collaboration, letting you invite team members with different permission levels and control who can view or modify your work. ## Inviting Collaborators 1. Open your project dashboard 2. Go to the **Share** menu 3. Enter the collaborator's email address 4. Click invite New collaborators join as **Viewers**. Once they've joined, the project owner can promote them with **Make Admin**. The collaborator receives an email invitation with a link to access the project. ## Roles pre.dev uses three permission levels: | Role | Permissions | | ---------- | ------------------------------------------------------------------------------------------------------------- | | **Owner** | Full control — edit project, manage all collaborators, invite admins, change privacy settings, delete project | | **Admin** | Edit project, invite and manage Viewer collaborators | | **Viewer** | Read-only access to project specs, builds, and code | ### Permission Rules * Only the **Owner** can invite or assign the Admin role * **Admins** can invite Viewers and remove Viewers * **Admins** cannot manage other Admins or the Owner * **Viewers** cannot invite or manage anyone The project creator is always the Owner. Ownership cannot be transferred or reassigned through the collaborator management interface. ## Managing Collaborators From the Share menu, you can: * **Change roles** — Use **Make Admin** / **Make Viewer** next to a collaborator to change their permission level (subject to the permission rules above) * **Remove collaborators** — Click the remove button to revoke access immediately ## Working in Parallel Collaboration isn't just access control — collaborators can build at the same time. Each person can work in their own **session**: an isolated branch of the project with its own agent, chat thread, and sandbox. When a session's work is ready, merge it back into Main. Presence avatars on the session tabs show who's viewing what, so you always know where your teammates are. See [Sessions & Parallel Agents](/coding-agent/building/sessions-and-parallel-agents) for the full workflow. ## Project Privacy Projects can be set to **public** or **private**: * **Public** — Anyone with the link can view the deployed app preview * **Private** — Only the owner and invited collaborators can access the project To change privacy settings: 1. Open the project dashboard 2. Toggle the privacy setting in the Share menu Making a project private automatically rescinds any enterprise organization invitations associated with that project. ## Enterprise Collaboration Enterprise organization members can be invited to projects as a group: * An Owner or Admin invites the enterprise organization to a project * All members of that organization gain access * Enterprise invitations are tracked separately from individual collaborator invitations * If the project is made private, enterprise invitations are automatically revoked Enterprise collaboration is available on Enterprise tier plans. See your organization settings for details. # Custom Domains Source: https://docs.pre.dev/coding-agent/building/custom-domains Point your own domain to your pre.dev deployed app. Custom domains let you serve your pre.dev deployed application from your own domain (e.g., `app.yourcompany.com`) instead of the default `.pre.dev` URL. ## Prerequisites Before adding a custom domain, your project must meet two requirements: 1. **Deployed** — Your app must have a live deployment with a `.pre.dev` URL 2. **Public** — Your app preview must be set to public (toggle this in the Share menu) ## Step 1 — Add Your Domain 1. Open your project dashboard 2. Navigate to the **Custom Domain** section 3. Enter your domain (e.g., `app.example.com`) 4. Click **Add** You'll receive a **CNAME target** — this is your project's deployment URL that you need to point your domain to. ## Step 2 — Configure DNS Add a CNAME record at your DNS provider pointing to the deployment URL: | Record Type | Host/Name | Value/Target | | ----------- | ----------------- | ---------------------- | | `CNAME` | `app.example.com` | `your-project.pre.dev` | The exact steps vary by DNS provider (Cloudflare, Namecheap, GoDaddy, Route 53, etc.). Look for "Add DNS Record" or "Manage DNS" in your provider's dashboard. ### Common DNS Provider Examples **Cloudflare:** 1. Go to your domain's DNS settings 2. Click **Add record** 3. Type: `CNAME`, Name: your subdomain, Target: your CNAME target 4. Set proxy status to **DNS only** (gray cloud) for initial setup **Namecheap:** 1. Go to Domain List → Manage → Advanced DNS 2. Click **Add New Record** 3. Type: `CNAME`, Host: your subdomain, Value: your CNAME target **GoDaddy:** 1. Go to My Products → DNS → Manage 2. Click **Add** under Records 3. Type: `CNAME`, Name: your subdomain, Value: your CNAME target ## Step 3 — Verify 1. Return to the Custom Domain section in your project dashboard 2. Click **Verify Connection** 3. pre.dev checks that your CNAME record is pointing correctly 4. Once verified, an SSL certificate is automatically provisioned After verification, your app is accessible at both your custom domain and the original `.pre.dev` URL. Both HTTP and WebSocket traffic are supported. When your domain is verified, pre.dev automatically notifies the build agent to update CORS settings if needed, so both URLs work simultaneously without issues. ## How It Works * pre.dev routes your custom domain to your deployed app * SSL certificates are automatically provisioned and managed * Traffic is routed to the same deployment as your `.pre.dev` URL * The app's `PREDEV_DEPLOYMENT_URL` environment variable is updated to reflect your custom domain ## Limitations * **One custom domain per project** — To add a different domain, remove the existing one first * **Subdomains work best** — `app.example.com` maps cleanly with a CNAME; bare domains like `example.com` need a DNS provider that supports CNAME flattening / ALIAS records at the apex * **No `pre.dev` subdomains** — You cannot add `*.pre.dev` as a custom domain ## Removing a Domain 1. Click the **trash icon** next to your domain in the Custom Domain section 2. Confirm removal 3. The routing rule and SSL certificate are cleaned up automatically 4. Your app reverts to being accessible only at the `.pre.dev` URL After removing a custom domain, you should also remove the CNAME record from your DNS provider to avoid pointing to a stale target. ## Troubleshooting ### DNS not resolving DNS changes can take **up to 48 hours** to propagate, though most providers update within minutes. If verification fails: * Wait a few minutes and click **Verify Connection** again * Use a DNS lookup tool (like `dig` or [dnschecker.org](https://dnschecker.org)) to check if your CNAME record is live * Confirm you're using a CNAME record, not an A record ### CNAME points to wrong target The error "CNAME points to X, expected Y" means your DNS record exists but points to the wrong destination. Update the CNAME value to match the target shown in the pre.dev dashboard. ### Verification button disabled The Verify Connection button is disabled while another agent operation is running. Wait for the current operation to finish, then retry. ### SSL certificate not provisioning SSL certificates are provisioned automatically after DNS verification. This typically takes 1-2 minutes. If your site shows a certificate warning after 10+ minutes, try removing and re-adding the domain. # Preview & Hosting Source: https://docs.pre.dev/coding-agent/building/preview-and-hosting Every project runs live at its own pre.dev URL while you build — preview it, test it on your phone, roll back versions, and take the code anywhere. Every pre.dev project gets a **live deployment at its own `.pre.dev` subdomain** from the moment the agent starts building. There's no separate deploy step to see your app — the running application is always a click away, and it updates as the agent works. The Preview panel: your app running live inside the workspace ## Live preview Click the **Preview** button in your workspace to open the running app. Once the agent has captured screenshots of your app, the button itself shows the latest one as a thumbnail — a live snapshot of where your build stands. When you open the preview, pre.dev checks that the deployment is healthy first. If the environment has gone idle, it's brought back automatically — you'll see a brief "Checking deployment..." state, then your app. The preview URL is a real, shareable URL. Set the preview to public in the Share menu and anyone with the link can try your app — no pre.dev account needed. If you're working in multiple sessions on the same project, each fork gets its **own preview URL** (`{project}-{session}.pre.dev`), so parallel experiments never overwrite each other's running app. ## Mobile preview For Expo / React Native projects, the Preview button opens a **mobile preview** instead: Your app renders inside a phone-sized frame right in the browser, so you see it at real device proportions while you iterate. A QR code sits alongside the frame. Install Expo Go, scan the code with your camera, and the app opens on your actual phone — or copy the URL directly. The QR link is tokenized and time-limited; it refreshes automatically while the preview is open, and you can regenerate it with one click if it expires. If the mobile bundler stops responding, the preview shows a **Debug with Agent** button — one click sends the agent everything it needs to diagnose and restart the dev server. ### Using the mobile preview Click **Preview** — for mobile projects the button shows a phone icon and opens the phone-framed view. Grab the free Expo Go app on iOS or Android. Point your camera at the QR code in the sidebar. The app opens on your device and hot-reloads as the agent makes changes. ## Version history Every change the agent makes lands as a **git commit**, and the Version History panel gives you the full timeline: * Commits per branch, with author, relative time, and the commit message * Expandable file-level detail — which files changed, with additions and deletions * Branch tabs, and a repository selector for multi-repo projects Click any commit and hit **Revert** to restore your codebase to that exact point. The revert checks out the commit and syncs every file, with live progress — no git commands, no terminal. Reverting moves your working code back to the selected commit. Anything after that point is still safe in git history, so you can roll forward again the same way. ## Hosting The `.pre.dev` URL isn't just a preview — it's real hosting: * **HTTPS by default** on every project URL * **HTTP and WebSocket traffic** both supported, so realtime features work out of the box * Apps that serve on a non-standard port are routed automatically — the agent wires the preview URL to whichever port your main app actually runs on ## Custom domains When your app is ready for the world, point your own domain at it — `app.yourcompany.com` instead of the `.pre.dev` URL. Add the domain in your project dashboard, create one CNAME record, and SSL is provisioned automatically. See [Custom Domains](/coding-agent/building/custom-domains) for the full setup. ## Take it anywhere The Code view: browse the live codebase, check the env, download everything Your project is never locked in. From the project action menu: **Export Code** downloads your full codebase as a zip — every file, ready to run locally or host anywhere. **Export Graph** downloads your project's architecture graph for use outside pre.dev. **Open in IDE** hands your spec to Cursor, Lovable, v0, or Bolt.new with a prompt that tells the tool to implement it step by step. Link GitHub for automatic commits and pull requests. See Pull Requests. ## GitHub is the source of truth Once linked, your GitHub repository holds the canonical code: the agent commits its work there, PRs are opened there, and Version History reads from the same commits. If you push changes to the repo yourself, pre.dev detects that the branch has moved ahead and offers a one-click **Refresh from GitHub** to pull your commits in before the next build or export. Learn more in [Pull Requests](/coding-agent/building/pull-requests). # Pro Mode & Model Selection Source: https://docs.pre.dev/coding-agent/building/pro-mode Pin every phase to the strongest model, or pick models per phase. Pro Mode is the quality dial turned all the way up: toggling `/pro` pins **every phase** of the agent's work — chat, research, coding, and acceptance — to the Pro model, **Claude Opus 4.8**. ## What it changes Every sprint runs in phases, and each phase normally uses the default model (GLM 5.2) unless you've overridden it. Pro Mode overrides all of them at once: | | Standard | Pro Mode | | ---------- | -------------------------- | --------------- | | Chat | GLM 5.2 (or your override) | Claude Opus 4.8 | | Research | GLM 5.2 (or your override) | Claude Opus 4.8 | | Coding | GLM 5.2 (or your override) | Claude Opus 4.8 | | Acceptance | GLM 5.2 (or your override) | Claude Opus 4.8 | Toggle it off with `/pro` again and your previous per-phase settings apply. ## Credits Pro Mode uses **more credits** per sprint — the Pro model costs more per token than the default. Check your remaining balance anytime with `/balance`, and see [pricing](https://pre.dev/pricing) for plan differences. A common workflow: iterate in standard mode while shaping a feature, then flip on Pro Mode for the final production pass. You can toggle between sprints without losing any project state. ## Per-phase control with /model If all-Opus is more than you need, `/model` gives you the same power with precision — pin a strong model to just the phase that matters: ``` /model coding sonnet-4.6 /model acceptance opus-4.8 ``` The full catalog: | Model | Notes | | ------------------------ | ------------------------------- | | **GLM 5.2** | The default | | **Kimi K2.6** / **K2.7** | Strong open-weight alternatives | | **MiniMax M3** | Open-weight alternative | | **Claude Sonnet 4.6** | High quality, balanced cost | | **Claude Opus 4.8** | The Pro model | | **GPT 5.5** | OpenAI's flagship | Set a phase back to **Default** to return it to GLM 5.2. For the full picture — sprint modes, effort levels, and how the model picker fits in — see [Build Modes & Effort](/coding-agent/building/build-modes). # Roadmap & Tracking Source: https://docs.pre.dev/coding-agent/building/progress-tracking Follow your build on a Kanban board or Gantt timeline, sync it to Linear or Jira, and get email updates with screenshots. pre.dev turns your spec into a living roadmap. As agents build, statuses update in real time — on a Kanban board, on a Gantt timeline, in your project management tool of choice, and in your inbox. Type `/kanban` or `/roadmap` in the chat to jump straight to the roadmap view. ## Roadmap Structure The roadmap tracks three levels of detail: * **Milestones** — Top-level phases of delivery * **Stories** — Feature-level requirements within each milestone * **Subtasks** — Granular implementation steps within a story Completion rolls up automatically: when every subtask in a story is done, the story is done; when every story in a milestone is done, the milestone is done. The roadmap comes from your project's spec. If you haven't generated one yet, the roadmap view prompts you to generate it first. ## Kanban Board The Kanban board: drag stories between Backlog, Next Tasks, In Progress, and Done The default roadmap view is a Kanban board with four columns: | Column | What's in it | | --------------- | ------------------------------------------------------------------------------------------------ | | **Backlog** | Stories waiting their turn | | **Next Tasks** | What the agent will pick up next — the upcoming stories auto-fill here, and you can pin your own | | **In Progress** | What an agent is building right now | | **Done** | Completed stories | The board is fully interactive: * **Drag and drop** — Move a card between columns to change its status. Drag a story into **Next Tasks** to prioritize it, or back to **Backlog** to defer it. Reorder cards within a column to set sequence. * **Add stories** — Create a new card with just a title; pre.dev writes the description and acceptance criteria for you automatically. * **Edit stories** — Click a card to edit its details. Cards show which milestone they belong to, the user-flow step they implement, and the architecture components they depend on. * **Live updates** — Statuses stream in as agents work, without losing your place or your local ordering. While an agent is actively building, you can't manually drop cards into **In Progress** — that column reflects what the agent is really working on. ## Gantt Timeline The timeline: milestones on a Gantt chart with live progress Toggle from **Kanban** to **Timeline** to see the same roadmap as a Gantt chart: * **Hierarchy** — Milestones (M1, M2, …) with their stories and subtasks nested beneath * **Status colors** — Gray (not started), amber (in progress), green (done) * **Progress bars** — Milestone and story progress is computed live from subtask completion * **Effort estimates** — Estimated hours per milestone * **Zoom levels** — Daily, monthly, or quarterly granularity, with a today marker ## Real-Time Updates When agents are building, the roadmap updates live: * Stories move to **In Progress** when an agent picks them up * Stories move to **Done** as work completes, and progress rolls up to the story and milestone bars immediately * New stories the agent scopes out appear on the board as they're created * Kanban and Timeline stay in sync — they're two views of the same roadmap, so a drag on the board shows up on the timeline too ## Milestone Screenshots As agents complete work, they capture screenshots of the running app. Each milestone on the timeline shows a strip of these screenshots — visual proof of what was actually built, not just a checked box. Click any thumbnail to open a full-screen gallery with keyboard navigation and capture timestamps, so you can flip through the build history of a milestone at a glance. ## Task Statuses | Status | Meaning | | ----------- | --------------------------------- | | Not Started | Not yet picked up | | In Progress | Currently being built by an agent | | Done | Finished | You can change a story's status yourself at any time — drag it on the Kanban board or edit it directly. ## Roadmap Sync: Linear & Jira Push your roadmap into the tool your team already uses. From the roadmap's sync menu: 1. Connect your **Linear** or **Jira** account (a standard OAuth sign-in — see [OAuth Connectors](/coding-agent/integrations/oauth)) 2. Click sync — pre.dev creates a project in your workspace and creates issues from your milestones and stories 3. When it finishes, you get a direct link to the created project Sync is versioned against your roadmap. When the roadmap changes — new stories, edits, re-scoping — a **Sync new changes** prompt appears, and re-syncing updates the issues in Linear or Jira to match the current roadmap. Sync is one-way: pre.dev is the source of truth, and each sync brings the external project in line with your roadmap. Progress streams into the sync panel while it runs, so you can watch issues land. Connecting **GitHub** does something different: it creates a repository and pushes each session's work to its own `predev/` branch, with pull requests into `main`. See [Pull Requests](/coding-agent/building/pull-requests) for how code review works. ## Email Notifications You don't have to watch the dashboard. pre.dev emails you at the moments that matter: ### Ready to build When the architecture phase completes, you get an email with an architecture overview and a link to start the build. ### Question waiting If the agent is blocked on a clarifying question and you've stepped away, the email **is** the question — shown in full, with one-click answer buttons. Clicking an answer submits it and drops you straight into the building project. Each question emails you at most once, and you can always skip: pre.dev makes sensible choices you can change later. ### Progress milestones At 25%, 50%, 75%, and 100% completion you get a progress email — sent once per threshold — with: * A progress bar showing how far along the build is * Screenshots from the most recent build session * A link straight back to your project ### Waiting on you If the agent finishes its current work and the project is sitting idle waiting for your input, you get a reminder with recent screenshots and a **Continue Building** link back to where you left off. ## Using Progress for Decision-Making The roadmap helps you decide: * **When to switch modes** — If early PRs look good, switch to Autopilot * **Where to focus review** — Prioritize reviewing complex milestone PRs * **What to adjust** — If a milestone is taking too long, simplify the spec * **When to ship** — Once key milestones are complete, you might ship early and iterate ## What's next? Bring teammates into the project. Run multiple workstreams at once. # Pull Requests Source: https://docs.pre.dev/coding-agent/building/pull-requests How pre.dev agents deliver code through reviewable PRs. Every task completed by a build agent produces a pull request. The AI never pushes directly to main — you always have the opportunity to review, request changes, or reject code before it's merged. ## PR Workflow ``` Task assigned → Agent builds in sandbox → Verification passes → Feature branch created → PR opened ``` ### What Each PR Contains ```diff theme={null} # predev/dtc-913 → main · 631a912 · PR #1 # feat(Setup): Write concise design aesthetic/rules # workspace/package.json (+251) + "private": true, "name": "mobile", "sideEffects": false, "scripts": { + "build": "react-router build", "clean": "node scripts/clean.js", + "dev": "react-router dev", "test": "vitest run", ``` * **Feature branch** — Named after the task (e.g., `predev/setup-user-auth`) * **Implementation code** — All files created or modified for the task * **Tests** — Unit tests covering the new functionality * **Diff summary** — Clear view of what changed and why * **Verification status** — All acceptance criteria results ## Branch Strategy pre.dev follows a clean branch strategy: | Branch | Purpose | | ---------- | ----------------------------------------------- | | `main` | Your production branch — agents never push here | | `predev/*` | Feature branches for each completed task | Each task gets its own feature branch. You can merge them individually or batch them. ## Reviewing PRs When reviewing agent-generated PRs: 1. **Check the diff** — Verify the implementation matches what you expected 2. **Review acceptance results** — All automated checks should show PASSED 3. **Test locally** (optional) — Pull the branch and run it yourself 4. **Merge or request changes** — If something's off, the agent can iterate ## Merge Strategies You control how PRs are merged: * **Merge immediately** — For tasks you're confident about * **Batch merge** — Let several PRs accumulate, review them together, merge in order * **Cherry-pick** — Merge only specific PRs while skipping or reworking others ## Code Quality Because every PR passes [acceptance verification](/coding-agent/building/acceptance-criteria) before it's opened, you're reviewing **verified, working code** — not hoping it compiles. * Types compile cleanly * Linting rules pass * Tests pass * UI renders correctly (for frontend tasks) ## PR History Your project's PR history serves as a detailed log of how the codebase was built: * Each PR maps to a specific task in the spec * PRs are opened in milestone order * The commit history tells the story of the project's construction This makes it easy to understand why any piece of code exists — trace it back to the task and user story in the spec. ## What's next? Your merged work, live at your project's pre.dev URL. Watch milestones complete as PRs land. # Sessions & Parallel Agents Source: https://docs.pre.dev/coding-agent/building/sessions-and-parallel-agents Work several streams at once — isolated sessions you merge back, and sub-agents that fan out within a sprint. pre.dev gives you two ways to parallelize work: **sessions** (isolated branches of your project, each with its own agent and chat) and **parallel agents** (sub-agents that fan out within a single sprint). ## Sessions Every session is an **isolated branch of your project**. It gets its own dedicated git branch, its own chat thread, and its own sandbox — so an experiment in one session can't break another. The tab bar above the chat shows your sessions. **Main** is always first; every other session is a fork. ### Create a session * Click **+ New session** in the tab bar (forks from your current session), or * Use the slash command to fork and hand the new session a task in one step: ``` /fork rebuild the settings page with tabs ``` `/sprint ` also launches its custom sprint in a new session, keeping your current session free. Sessions require the project to be connected to GitHub — each one lives on its own branch. There's a cap on active sessions per project; archive an unused one if you hit it. ### Work in parallel, merge back Run different tasks in different sessions simultaneously — a feature in one, a refactor in another — then bring the work together: Open a session's menu (▾) and choose **Merge into Main**. pre.dev opens a pull request and auto-merges it when it's clean. If the merge conflicts, you'll see the PR link plus a **Let agent resolve** button. The agent in Main picks up the conflict markers, resolves them, commits, and pushes — or you can resolve on GitHub yourself. If a fork *became* the real project, choose **Make this the Main** instead of merging. The session becomes Main — including taking over the project's live preview URL. ### Archive and revive Done with a session? **Archive** it from the menu — it leaves the tab bar but its git branch is preserved, so you can **Revive** it later from the Archived dropdown and pick up exactly where it left off. ### Working with teammates Sessions are multiplayer. Presence avatars on each tab show who else is viewing that session right now, and session changes (create, rename, archive, promote) sync live to everyone in the project. Double-click a fork's tab to rename it (Main keeps its name). ## Parallel agents Within a single sprint, the agent can **fan independent tasks out to multiple sub-agents in one wave** — for example, building three unrelated components at the same time instead of one after another. When this happens, a live panel appears in the chat feed: Each sub-agent gets a tab showing its objective, live status, and tool count. Switch tabs to watch any of them work. Every tool call inside a branch is a click-to-expand card — search results, command output, and file diffs, same as the main feed. A strip at the top of each branch lists every file that agent wrote or edited. When a branch finishes, its summary and findings appear in a conclusion box — including a pass/fail verdict for verification branches. Sub-agents work within the session's workspace, so their results land together in the same branch — no merge step needed. Verification branches run read-only; building branches write code. ## When to use which | Situation | Use | | ---------------------------------------------------------------- | ------------------------------------------------------ | | Two features you want to build side by side, reviewed separately | **Sessions** | | A risky experiment you might throw away | **Session** (archive it if it doesn't pan out) | | A teammate working on something else in the same project | **Sessions** (one each, presence shows who's where) | | One feature with several independent pieces | **Parallel agents** — the agent fans out automatically | | Deciding a fork is now the real product | **Promote to Main** | These compose: each session's agent can fan out its own parallel sub-agents. Sessions are the coarse-grained split you control; parallel agents are the fine-grained split the agent manages within a sprint. ## What's next? Control what each session builds and how deep sprints go. Invite teammates and control project access. # API Keys Source: https://docs.pre.dev/coding-agent/integrations/api-keys API keys and secrets for authenticating with third-party services. API Keys are the credentials your projects need to talk to third-party services — Stripe, OpenAI, Supabase, Resend, anything. Store them once; every project inherits them. ## Categories pre.dev groups supported services into categories so you can see what you've configured at a glance: * **AI Text** — OpenAI, Anthropic, Mistral, Groq, … * **AI Image / Video / Audio** — DALL·E, Stability, Runway, ElevenLabs, … * **AI Search & Scraping** — Exa, Tavily, Perplexity, Brave Search, You.com, Firecrawl, Serper, Browserbase * **Payments** — Stripe, PayPal * **Email** — Resend, SendGrid, Mailgun * **Auth** — Clerk, Auth0, Supabase Auth * **Database** — Supabase, PlanetScale, Neon * **Storage** — S3, Cloudflare R2, Uploadthing * **Analytics** — PostHog, Mixpanel, Amplitude You can also add keys for any service not on this list. ## Adding a key 1. Open **[Integrations → API Keys](https://pre.dev/projects/integrations)** 2. Pick a provider (or add a custom one) 3. Paste your key 4. Save The key is encrypted before it's stored. It never appears in plaintext after saving — not in the UI, not in agent output, not in PR diffs. ## Bulk import from `.env` Click **Import Keys** on the API Keys tab and paste a `.env` — or drop a `.env`/`.txt`/`.json` file, even a screenshot. pre.dev parses the keys, detects which provider each belongs to, and stages them for review before saving. ## How agents use them On every build, the agent: 1. Scans your configured API keys 2. Picks the ones relevant to the current task 3. Writes them into the project's `.env` (secrets), not the code 4. References them via `process.env.STRIPE_SECRET_KEY` etc. in the generated code Result: the code you get back runs against your real accounts from the first build. ## Propagating changes If you rotate a key, update it in Integrations — a **"N projects behind"** banner appears when existing projects are out of date. Click it to propagate the new values, per project or all at once. # Environment Variables Source: https://docs.pre.dev/coding-agent/integrations/env-vars Configure your app's secrets and settings — pre.dev detects what's needed, you fill in the values, the running app picks them up. Environment variables are how your project gets its secrets and configuration — database URLs, payment keys, auth credentials. pre.dev detects which variables your app actually needs, tells you when any are missing, and applies your values to the running app. ## The environment editor Click the **Environment** button in your workspace to open the editor. If required variables are missing, the button shows a red badge with the count. The editor lists every variable your project needs — detected automatically by scanning your code — with the service each one belongs to and instructions for where to find its value. Detection runs with live progress, so you can watch variables appear as the scan finds them. From here you can: * **Fill in values** for detected variables (sensitive values are masked, with a toggle to reveal) * **Add custom variables** your app needs beyond what was detected * **Remove** variables you don't want set (and restore them if you change your mind) Hit **Save** and your values are persisted and written to the running app, so the change takes effect without you touching a terminal. A few things the editor handles for you: * Custom variable names are normalized to `UPPER_CASE` automatically * Saved values persist across re-scans — updating the detected list never wipes what you've entered * Known providers are recognized by name, so a custom `RESEND_API_KEY` still gets the right service attribution and instructions ## Bulk import You don't have to enter values one at a time: Switch to **Paste text** and paste your `.env` contents (or raw API keys) — or drop a `.env`, `.txt`, or `.json` file. Even a screenshot of your keys works. pre.dev parses the input and matches each value to the variable it belongs to. Variables that aren't in the detected list are added as custom variables. Matched values fill in live so you can verify before saving. ## Missing variable detection While building, the agent works out which environment variables the project genuinely requires. If required values are missing, pre.dev emails you a precise list — each variable's **name**, the **service it belongs to**, and **what it's for**: ```text theme={null} Missing Variables STRIPE_SECRET_KEY Stripe — Payment processing CLERK_SECRET_KEY Clerk — Authentication ``` The email links straight back to your project with the environment editor already open, and each variable comes with step-by-step instructions for where to find its value. Nothing blocks silently: without the required values some features won't work, so the email tells you exactly what's needed instead of leaving you to discover it at runtime. ## Organization-wide propagation Teams on an enterprise organization can define **shared environment variables at the org level** in the knowledge base. When shared variables change — or new projects are missing them — the propagation panel shows every project that's out of date and exactly which variables each one is missing. Push updates per project, or hit **Update All** to bring every project up to date in one click. ## Environment variables vs. API keys The two work together: * **[API Keys](/coding-agent/integrations/api-keys)** are stored once at the account level ([pre.dev/projects/key](https://pre.dev/projects/key)) — the agent picks the relevant ones on each build and writes them into the project's `.env` automatically. * **Environment variables** are per-project: the editor shows you what the project needs, including values that came from your stored keys, plus anything project-specific. Store credentials you reuse across projects (Stripe, OpenAI, Resend, …) as API keys so every new project inherits them. Use the environment editor for one-off, project-specific values. Plan availability for team and organization features is listed on the [pricing page](https://pre.dev/pricing). # External MCP Servers Source: https://docs.pre.dev/coding-agent/integrations/mcp-servers Connect external tool servers to extend what pre.dev can do. MCP Servers let you plug any Model Context Protocol server into your Coding Agent. Whatever tools that server exposes, the agent can call — as if they were built into pre.dev. If you've already built an MCP server for Claude, Cursor, or VS Code, it works here with zero changes. ## When to use one * **Internal tooling** — your team has an MCP server that queries your staging database, triggers deploys, or exposes a private API * **Third-party MCP servers** — GitHub, Linear, Sentry, Grafana, Notion — any MCP-speaking service * **Custom automations** — any script you've wrapped as an MCP server (cron control, DNS changes, feature flag flips) ## Connecting a server 1. Open **[Integrations → MCP Servers](https://pre.dev/projects/integrations)** 2. Click **Add MCP Server** 3. Paste the server's JSON config — a remote server (`url` + `headers`) or a stdio server (`command`, `args`, `env`) 4. Click **Test** — pre.dev handshakes with the server and lists its tools 5. Save — the agent can now call those tools on any project ## What the agent sees Once a server is connected, its tools show up in the agent's available toolset automatically. If your server exposes a `queryStaging` tool, the agent can reason about when to call it ("this task needs the latest customer count from staging → call `queryStaging`") and execute the call during a build. ## Toggling servers MCP servers can be toggled on and off from the Integrations page (and with `/mcp` in the workspace or CLI). Turn off servers whose tools would add noise; leave on the ones that earn their place. ## Security * Connection configs stay server-side and are never embedded in project code * Your server's auth is respected — pre.dev forwards the headers you configured on every call # OAuth Connectors Source: https://docs.pre.dev/coding-agent/integrations/oauth Sign in once to let pre.dev read and write to external services on your behalf. OAuth Connectors let pre.dev act on your behalf in external services — reading data, creating resources, or keeping state in sync — without you pasting API keys. You click "Connect," sign in once, and the agent inherits that authorization for every project. ## How it works 1. Open **[Integrations → OAuth Connectors](https://pre.dev/projects/integrations)** 2. Pick a service and click **Connect** 3. Sign in through the service's standard OAuth flow — the service shows you a consent screen listing exactly what access pre.dev is requesting, and nothing is granted until you approve 4. Done — any project the agent builds can now use that connector ## Available connectors **Project management** * **Linear** — create and update issues; sync your roadmap into a Linear project * **Jira** (Atlassian) — create and update tickets; sync your roadmap into a Jira project * **Asana** — tasks and projects * **Monday.com** — boards and items **Communication** * **Slack** — send messages, post updates to channels * **Discord** — interact with your servers **Docs, files & knowledge** * **Notion** — read briefs and docs, write pages and databases * **Google Workspace** — Sheets, Drive, Docs, Calendar, Gmail * **Microsoft** — Microsoft Graph (Outlook, OneDrive, Teams data) * **Dropbox** — read and write files **Design** * **Figma** — read design files and components **Data & CRM** * **Airtable** — read and write bases * **HubSpot** — contacts, deals, CRM records * **Salesforce** — objects and records in your org **Source control** * **GitHub** — repositories for your project's code (see [Pull Requests](/coding-agent/building/pull-requests)) * **GitLab** — API access to your GitLab resources * **Bitbucket** — repository access ## What agents do with them When a build task mentions a connected service, the agent uses the connector directly: * **"Create a Linear issue for every failing test"** → agent uses your Linear connector * **"Send a Slack message when a PR merges"** → agent uses your Slack connector * **"Read my Notion project brief before starting"** → agent reads via your Notion connector * **"Pull the pricing table from my Google Sheet"** → agent reads via your Google connector * **"Log new signups as HubSpot contacts"** → agent writes via your HubSpot connector If the agent needs a service you haven't connected yet, it tells you and points you to the Integrations page. The agent never sees your password. It holds a scoped token that you can revoke from the Integrations page at any time. ## Security * Tokens stay server-side — the agent calls each service through pre.dev's integration layer, so tokens are never embedded in your project's code or exposed to the browser * Scopes are shown on the consent screen before you authorize — pre.dev requests the minimum required * Expiring tokens are refreshed automatically; if a refresh fails, the agent asks you to reconnect rather than failing silently * You can disconnect any connector from the Integrations page and all active tokens are revoked # Integrations Source: https://docs.pre.dev/coding-agent/integrations/overview Everything you connect once that every project inherits. Agents are only as capable as the services they can reach. Integrations are the services, credentials, servers, and custom instructions you connect once — every project you build on pre.dev picks them up automatically. Open your Integrations at **[pre.dev/projects/integrations](https://pre.dev/projects/integrations)**. Changes propagate to every project. Integrations: OAuth connectors, agent skills, MCP servers, and API keys in one place ## The four types Sign in once to let pre.dev read and write to external services on your behalf. Custom instructions injected into the agent prompt for every project. Connect external tool servers to extend what pre.dev can do. API keys and secrets for authenticating with third-party services. ## How agents use your integrations When a build agent picks up a task, it scans your integrations and makes decisions: * Needs to send email? It finds your **Resend** or **SendGrid** API key and wires it up in the `.env`. * Needs to read your Linear issues? It uses the **Linear OAuth** connector you signed in with. * Needs to follow a style guide? It picks up your **Agent Skill** that says "always use Tailwind, never write inline styles." * Needs a custom tool outside our built-ins? It calls your **MCP Server** as if it were a native tool. No placeholder credentials. No stub implementations. Agents build with the real thing. ## Security * API keys are **encrypted at rest** and only decrypted inside sandboxed build agents * OAuth tokens are scoped to the services you explicitly connect and revocable at any time * No key or secret ever appears in generated code or PR diffs — they're injected via the project's `.env` * Integrations are scoped to your account (or organization, for enterprise) and never shared between users # Agent Skills Source: https://docs.pre.dev/coding-agent/integrations/skills Custom instructions injected into the agent prompt for every project. Agent Skills are your own instructions that get injected into the agent's prompt on every build. Think of them as the rules you'd give a senior engineer joining your team — code style, preferred libraries, architectural patterns, things to avoid. ## Examples * "Always use Tailwind. Never write inline styles." * "Use Zod for all schema validation. Never use Joi or Yup." * "Prefer server components in Next.js unless a client hook is explicitly required." * "All database queries go through Prisma. No raw SQL." * "Tests must use Vitest, not Jest." ## Creating a skill 1. Open **[Integrations → Agent Skills](https://pre.dev/projects/integrations)** 2. Click **Add Skill** 3. Give it a name and write the instructions (they're injected into the agent's prompt) 4. Toggle it on From that moment on, every project the Coding Agent works on respects the rule. ## When to use a skill vs. a project-level instruction * **Skill** = applies to *every* project you build, forever. "I always use Tailwind." * **Project-level instruction** = applies to one project only. "This project needs to be WCAG AA compliant." Skills are your persistent preferences. Project instructions are per-build context. ## Toggling and editing Skills have an on/off toggle on the Integrations page. Turn a skill off for one experimental build, turn it back on afterwards. Edits to a skill take effect on the next task the agent picks up. # Coding Agent Source: https://docs.pre.dev/coding-agent/overview Describe an app. pre.dev plans it, builds it autonomously for hours, and ships real pull requests to your GitHub. The **Coding Agent** is pre.dev's flagship. Point it at a prompt, a template, or an existing GitHub repo — it plans the architecture first, then builds against that plan autonomously, verifying each task, opening real PRs, and deploying a live preview. You stay in the loop as a reviewer, not a typist. Sign up, describe an app, hit **Build on Autopilot**. Minutes to a deployed product. ## How it works One prompt → a full structured spec: stack, milestones, user stories, acceptance criteria. Fast Spec in \~1 minute, Deep Spec in \~3–5. Agents work the roadmap in isolated sandboxes — for hours if the roadmap calls for it. Each task verifies itself (types, lint, tests, browser) before it ships. Real PRs land on feature branches in your GitHub. A live preview runs the whole time; hosting and custom domains are built in. ## Built for long-horizon work Most coding agents are great for twenty minutes. pre.dev is built for the build that takes all day: Dial how deep each sprint goes with `/effort` — **low** for a fast direct pass, **medium** for a task-list loop, **high** for the full research → code → verify pipeline. Or leave it on **auto** (the default). Pin a different model to each phase of the work — chat, research, coding, acceptance — with `/model`, or flip on Pro Mode for the strongest model everywhere. Every session is an isolated branch of your project. Fork to try something risky, work several in parallel, merge back what works. Context persists across all of them. Big sprints fan out to multiple agents at once. Watch each branch's objective, progress, live diffs, and conclusion in real time. ## What you get Stripe, Supabase, Clerk, OpenAI, Linear, Slack — any service you've connected. Real keys, real endpoints, real data. No `YOUR_API_KEY` placeholders. Every PR passes types, lint, tests, and browser verification — with before/after screenshots as evidence — before it's opened. Live timeline of the agent's work — its streaming thoughts, which file it's editing, which test just passed, which PR just opened. Pick a **sprint mode** — Autopilot for the whole roadmap, Next Task to review each PR, custom sprints for anything else, or plain chat — and an **effort level** for how deep each sprint goes. Work from the **web workspace** — a terminal-style chat with live Plan, Code, and Preview views — or from the **[pre.dev CLI](/cli/overview)** with the same slash commands and controls. See [The Workspace](/coding-agent/workspace). ## Extend what the agent can do Agents are only as capable as the services they can reach. Connect your stack once — every project inherits it. Sign in once (GitHub, Linear, Slack, Notion, etc.) so the agent can read and write on your behalf. Store provider keys (Stripe, OpenAI, Twilio) once and inject them into every build. Attach any MCP server to expand the tool set the agent can call at build time. Custom instructions injected into every prompt — your conventions, your constraints, your voice. ## Who it's for Ship without writing code. Stay focused on product direction while the agent handles implementation. Compress weeks of boilerplate into hours. Spend your time on the parts that actually need you. Queue work as specs and review PRs — the agent handles the rote 70%, you focus on the 30% that matters. Standardize delivery across client projects. Consistent stacks, consistent quality, faster turnaround. # Plans & Credits Source: https://docs.pre.dev/coding-agent/plans-and-credits What each plan includes, what credits pay for, and what happens when you run out mid-build. Everything on pre.dev — spec generation, build sprints, browser agent tasks — draws from one credit balance. Every plan refills that balance monthly. [pre.dev/pricing](https://pre.dev/pricing) is the source of truth for current prices, credit amounts, and plan features. The numbers below reflect the pricing page at the time of writing. ## Plans | Plan | Price | Monthly credits | Adds | | -------------- | -------- | --------------- | ------------------------------------------------------------------------------------------------------------------------------------------- | | **Free** | \$0 | 100 | Everything you need to plan and build: architecture planning, autonomous coding and verification, deployment and preview, GitHub automation | | **Plus** | \$25/mo | 200 | More credits | | **Premium** | \$49/mo | 500 | [Pro Mode](/coding-agent/building/pro-mode) | | **Pro** | \$199/mo | 2,500 | Deep Spec | | **Enterprise** | Custom | Unlimited | Architect API + MCP, dedicated solutions engineer | A few feature notes, per the [pricing page](https://pre.dev/pricing): * **[Pro Mode](/coding-agent/building/pro-mode)** — pin the strongest model to every phase of a build — is included from the **Premium** plan. * **[Deep Spec](/coding-agent/specifications/fast-vs-deep)** — the granular, subtask-level specification — is included from the **Pro** plan. Fast Spec is available on every plan. * Core building blocks — architecture planning, autonomous coding and verification agents, automatic deployment and preview, GitHub automation, and data-source connections — are on **every plan, including Free**. ## What credits pay for **Fast Spec:** \~5–10 credits, \~1 minute. **Deep Spec:** \~10–50 credits, \~3–5 minutes. Cost scales with project complexity. Sprints consume credits as the agent researches, codes, and verifies. Higher [effort levels](/coding-agent/building/build-modes#effort-level-how-deep-each-sprint-goes) do more model work and cost more. **1 credit = \$0.10**, billed per task with a **0.1-credit floor**. Failed tasks are free. Failed browser agent tasks aren't billed, but you need at least the 0.1-credit floor available for a task to start. ## Check your balance Three ways, depending on where you are: Type `/balance` in the chat composer for your remaining credits. [pre.dev/projects/key](https://pre.dev/projects/key) shows your balance alongside your API key. `GET /credits-balance` returns your remaining credits programmatically. ## Per-project cost analytics The workspace tracks what each project has spent, so you can see where credits actually go — which sprints, which phases, which features. Use it to decide where auto effort is fine and where a cheaper [low-effort pass](/coding-agent/building/build-modes) would do. ## What happens when credits run out mid-build Running out of credits during a sprint doesn't lose your work: The agent stops at a clean point. Nothing is discarded — the code, the plan, and the sprint's progress are all preserved. It includes the build's current progress, screenshots of the app so far, and a link to the live preview — so you can judge how far it got without opening the workspace. Add credits or upgrade at [pre.dev/pricing](https://pre.dev/pricing), then resume the build. It picks up where it paused. ## FAQ See [pre.dev/pricing](https://pre.dev/pricing) for the current policy on credit refills and rollover. Fast Spec (\~5–10 credits) is the default and right for most projects. Deep Spec (\~10–50 credits) adds granular subtasks and is worth it for complex, production-bound builds. See [Fast vs Deep](/coding-agent/specifications/fast-vs-deep). At 1 credit = \$0.10 with a 0.1-credit floor per task, a credit covers up to \~10 simple tasks — and failed tasks cost nothing. The Enterprise plan has unlimited credits, the Architect API + MCP, and a dedicated solutions engineer — [contact us via pricing](https://pre.dev/pricing). # Creating a Project Source: https://docs.pre.dev/coding-agent/projects/creating-a-project Three ways to start a project on pre.dev. Start from a prompt — with Import, Deep Spec, and Pro toggles inline There are two ways to start: describe what you want to build, or import an existing repo. Type what you want to build into the prompt box and hit **Start building**. pre.dev's planning engine analyzes your requirements, picks the stack and architecture, and generates the spec — you review it before any code is written. Two toggles shape the run: * **Deep Spec** — a more comprehensive plan with granular subtasks (see [Fast vs Deep](/coding-agent/specifications/fast-vs-deep)) * **Pro** — the strongest models on every phase (see [Pro Mode](/coding-agent/building/pro-mode)) **Example input:** ``` A collaborative whiteboard app with real-time drawing, sticky notes, video chat, and export to PDF. The app should support teams of up to 50 people. ``` Connect an existing GitHub repository and continue building on it. pre.dev reverse-engineers the existing codebase — understanding the tech stack, patterns, and architecture — then generates specs for new features that integrate seamlessly. **When to use:** * You have an existing project you want to extend * You're adding features to a codebase you didn't build * You want AI agents to work within your established patterns See [Importing Repos](/coding-agent/projects/importing-repos) for detailed instructions. ## Writing a Good Project Description The quality of your specification depends on how well you describe your project. Here are tips: **Include:** * What the app does (core functionality) * Who uses it (target users) * Key features you want * Any technical constraints (specific APIs, compliance needs, platform targets) * Scale expectations (number of users, data volume) **Example — vague (less optimal):** ``` Build me a chat app ``` **Example — detailed (much better):** ``` Build a team messaging app similar to Slack with: - Real-time channels and direct messages - File sharing with drag-and-drop upload (up to 50MB) - Message search across all channels - Threaded replies - @mentions with notifications - Integration with GitHub for commit notifications Target: small teams of 5-20 people. Stack preference: React frontend, Node.js backend, PostgreSQL. ``` ## After Creation Once your project is created and the specification is generated: Add, remove, or modify milestones and stories Connect keys for external services agents will need Choose a build mode and let agents work # GitHub Integration Source: https://docs.pre.dev/coding-agent/projects/github-integration How pre.dev reads your repos, opens pull requests against them, and keeps your git history clean. pre.dev's Coding Agent is built around GitHub end-to-end. Connect once and every project can import existing repos, ship real PRs, and leave a clean branch-per-task history behind. ## Connect your account Go to **[Integrations → OAuth Connectors](https://pre.dev/projects/integrations)** and click **Connect GitHub**. You authorize through GitHub's standard OAuth flow — pre.dev only ever holds a scoped token, never your password, and you can revoke it at any time. ## Import an existing repo Once GitHub is connected you can start a project from any repo you have access to — public or private. See what pre.dev detects from your codebase (stack, patterns, schema, API contracts) and how imported projects behave afterwards. ## Pull requests, not pushes Every task a build agent completes ends in a **pull request**. The agent never pushes to `main`. Branches are named after the task (e.g. `predev/setup-user-auth`). One task in the spec = one branch = one PR. Types compile, lint passes, tests pass, browser checks pass — or the PR is never opened in the first place. Merge immediately, batch, or cherry-pick. Review the diff, verify acceptance results, merge on your terms. Every PR maps back to a specific story in the spec, so your git log is a readable record of how the app was built. The full lifecycle: branch naming, diff contents, merge strategies, PR history. ## Security * Tokens stay server-side and are only used for the scopes you approved * pre.dev requests the `repo` scope (GitHub has no narrower read/write split) to import repos and open PRs, `workflow` so pushes that touch CI files don't fail, and basic profile scopes (`read:user`, `user:email`) * Disconnect anytime from the [Integrations](https://pre.dev/projects/integrations) page — all active tokens are revoked # Importing Repos Source: https://docs.pre.dev/coding-agent/projects/importing-repos Reverse-engineer existing codebases and continue building with pre.dev. pre.dev can import existing GitHub repositories, understand their architecture, and generate new specs that integrate with your established codebase. ```text theme={null} # Import Repository > Search repositories... stripe-sync private Updated today nexus-api private Updated 2d ago quantum-ui public Updated today forge-cli private Updated 1w ago pulse-analytics private Updated 3d ago terraform-aws public Updated today ``` ## How It Works 1. **Connect your repo** — Provide the GitHub repository URL or select from your connected repos 2. **Analysis** — pre.dev scans the codebase to understand: * Tech stack and framework * Project structure and patterns * Existing features and components * Database schema (if detectable) * API routes and contracts 3. **Spec generation** — Describe what you want to add, and pre.dev generates specs that fit within the existing architecture 4. **Build** — Agents implement new features following the patterns established in your codebase ## What Gets Analyzed | Aspect | What pre.dev Detects | | ----------------- | ---------------------------------------------------------------- | | **Framework** | React, Vue, Angular, Next.js, Express, Django, Rails, etc. | | **Language** | TypeScript, JavaScript, Python, Go, Rust, and more | | **Structure** | Folder organization, module patterns, component hierarchy | | **Patterns** | State management approach, API layer design, auth implementation | | **Dependencies** | Package ecosystem, third-party integrations | | **Configuration** | Build tools, linting rules, test setup | ## Use Cases ### Adding Features to Existing Apps ``` Import my e-commerce repo and add: - A wishlist feature with sharing via link - Product recommendations based on browsing history - A loyalty points system ``` pre.dev generates specs that use your existing database schema, component library, and API patterns. ### Refactoring ``` Import my monolith and generate a plan to: - Extract the payment processing into a microservice - Add proper error handling across all API endpoints - Migrate from REST to GraphQL for the frontend queries ``` ### Onboarding to Unfamiliar Codebases Import a repo you didn't write and let pre.dev explain its architecture, then generate specs for changes you need to make. ## Requirements * The repository must be accessible (public or connected via GitHub OAuth) * Supported languages and frameworks are detected automatically * Large monorepos may take longer to analyze ## After Import Once imported, your project works exactly like any other pre.dev project: * View and edit the generated spec * Use any [build mode](/coding-agent/building/build-modes) * Agents write code that follows your existing patterns * PRs are opened against your repo # Quickstart Source: https://docs.pre.dev/coding-agent/quickstart Go from idea to shipped software in minutes with the Coding Agent. This guide walks you through creating your first project on pre.dev and shipping it with autonomous agents. ## 1. Create your account Describe what you want to ship Create a free account at pre.dev to get started. ## 2. Start a new project From the homepage, you have three ways to start: | Mode | Description | | ----------------------- | --------------------------------------------------------------- | | **Full-Stack Template** | Start from a curated template with a pre-configured stack | | **Adaptive** | Describe your idea and let pre.dev choose the best architecture | | **Import** | Connect an existing GitHub repo and continue building on it | Type your project idea into the input box. Be as descriptive as you want — the more context you give, the better the spec. **Example:** ``` I would like to build a virtual museum tour platform with AR exhibits, user-generated galleries, and a ticketing system for live events. ``` ## 3. Choose your spec level Before generating, choose between: * **Fast Spec** (shown as **Plan** in the picker) — A fast, high-level spec with milestones and user stories (\~1 minute) * **Deep Spec** — A comprehensive breakdown with granular subtasks and acceptance criteria (\~3-5 minutes) See [Fast vs Deep Specs](/coding-agent/specifications/fast-vs-deep) for guidance on which to choose. ## 4. Review your specification pre.dev generates a structured specification containing: * **Technical architecture** and recommended stack * **Milestones** — phased delivery plan * **User stories** — feature requirements with acceptance criteria * **Subtasks** — granular implementation steps (Deep Spec only) * **Complexity estimates** per task You can edit the spec, add/remove stories, or adjust the architecture before building. ## 5. Start building Once you're happy with the spec, choose how pre.dev builds: | Mode | How It Works | | ---------------------- | --------------------------------------------------------------- | | **Build Next Task** | Agents build one task at a time, you review each PR | | **Build on Autopilot** | Agents work through the entire roadmap autonomously | | **Chat** | Interactive mode — ask the agent questions or guide it manually | Click **Build on Autopilot** to let agents ship the entire project, or **Build Next Task** for more control. ## 6. Review pull requests Each completed task produces: * A **feature branch** with the implementation * A **pull request** for you to review * **Passing acceptance criteria** (type checks, linting, browser verification) The AI never pushes to main. You review and merge on your terms. ## 7. Ship Once you're satisfied with the code, merge the PRs and deploy. Your project is live. *** ## What's next? Learn when to use Autopilot vs. manual build modes. Connect API keys, OAuth services, MCP servers, and skills. Use pre.dev's planner as an API inside your own coding agent. Scrape, automate, and extract from any web page. # Fast vs Deep Specs Source: https://docs.pre.dev/coding-agent/specifications/fast-vs-deep Choose the right specification level for your project. pre.dev offers two specification levels. The right choice depends on your project's complexity, timeline, and how much guidance you want build agents to have. ## Fast Spec (Plan) **Structure:** Milestones → User Stories A high-level spec that gives agents the big picture without granular subtask breakdowns. Agents figure out implementation details autonomously. **Best for:** * MVPs and prototypes * Personal/side projects * Rapid iteration workflows * Solo developers * Projects where speed matters more than detailed planning **What you get:** * High-level milestones with complexity estimates * User stories for each feature * Basic acceptance criteria * Technical architecture overview **Cost:** \~5-10 credits | **Speed:** \~1 minute ## Deep Spec **Structure:** Milestones → User Stories → Granular Subtasks A comprehensive spec with implementation-level detail. Every task is broken down into specific, actionable subtasks with their own acceptance criteria. **Best for:** * Production applications * Complex architectures * Team coordination * Mission-critical systems * When you want maximum control over what agents build **What you get:** * Detailed milestones with phased delivery * User stories with comprehensive acceptance criteria * Granular implementation subtasks * Task-level complexity estimates * Detailed technical architecture with schema designs **Cost:** \~10-50 credits | **Speed:** \~3-5 minutes ## Comparison | Feature | Fast Spec | Deep Spec | | ---------------------- | ---------- | ------------- | | Milestones | Yes | Yes | | User Stories | Yes | Yes | | Acceptance Criteria | Basic | Comprehensive | | Granular Subtasks | No | Yes | | Architecture Depth | Good | Comprehensive | | Effort Estimates | High-level | Per-subtask | | Documentation Scraping | Yes | Yes | ## Decision Framework **Use Fast Spec if:** * You're validating an idea quickly * The project is straightforward (CRUD apps, simple tools) * You trust agents to make implementation decisions * You want to iterate on the spec after seeing initial output **Use Deep Spec if:** * You're building something you'll ship to real users * The project has complex business logic * You want precise control over each implementation step * You're working in a regulated domain (healthcare, finance) * Multiple people need to understand the build plan ## Combining Both A common pattern is to start with a **Fast Spec** to validate the overall direction, then generate a **Deep Spec** once you're confident in the approach. The Deep Spec can reference the Fast Spec as context. You can also generate a Fast Spec and selectively request deep breakdowns for only the complex milestones — keeping simple features at the story level while getting granular subtasks for the tricky parts. ## What's next? What's actually inside a pre.dev spec. Turn the spec into working code. What specs cost and what each plan includes. Generate the same specs programmatically. # Understanding Specs Source: https://docs.pre.dev/coding-agent/specifications/understanding-specs What pre.dev specifications contain and how agents use them. A specification is the structured blueprint that guides pre.dev's build agents. It's generated by pre.dev's planning engine based on your project description, and it contains everything agents need to implement your project correctly. The Spec view: your full specification, editable and exportable ## Spec Structure Every specification follows a hierarchical structure: ``` Project ├── Technical Architecture │ ├── Tech Stack │ ├── System Design │ └── Infrastructure ├── Milestone 1: Core Foundation │ ├── User Story 1.1 │ │ ├── Acceptance Criteria │ │ ├── Subtask 1.1.1 │ │ ├── Subtask 1.1.2 │ │ └── Subtask 1.1.3 │ └── User Story 1.2 │ ├── Acceptance Criteria │ └── Subtasks... ├── Milestone 2: Feature Layer │ └── ... └── Milestone 3: Polish & Deploy └── ... ``` ## Components ### Technical Architecture The top-level section defines the system design: * **Tech stack** — Languages, frameworks, databases, hosting * **System design** — Component hierarchy, data flows, API contracts * **Database schema** — Tables/collections, relationships, indexes * **Infrastructure** — Deployment targets, CI/CD, environment config ### Milestones Milestones are phases of delivery. They're sequenced so that foundational work comes first: * Each milestone has a **complexity estimate** * Milestones are typically built in order (dependencies respected) * Example: "Core Foundation" → "User Features" → "Admin & Analytics" → "Polish & Deploy" ### User Stories Each milestone contains user stories — feature-level requirements: * Written in standard format: "As a \[user], I want \[feature], so that \[benefit]" * Include **acceptance criteria** — specific conditions that must be true for the story to be complete * Acceptance criteria become the verification checks during building ### Subtasks (Deep Spec only) Subtasks are the granular implementation steps within each story: * Specific enough for an agent to implement directly * Include task-level complexity estimates * Have their own status tracking ## Task Status Tracking Every subtask has a status indicator: ```markdown theme={null} - [ ] To Do — Not yet started - [→] In Progress — Currently being built - [✓] Complete — Finished and verified - [⊘] Skipped — Intentionally skipped (with reason) ``` These statuses update in real-time as agents work through the spec. ## Editing Specs Specifications are **living documents**. Before or during building, you can: Add new features you want included, or remove features you've decided against. The spec updates immediately. Change what "done" means for any story. Agents building that task will use the updated criteria. Adjust delivery priority. Move critical features earlier or defer nice-to-haves. Switch frameworks, databases, or tools. Subsequent tasks will use the new stack. Edits are reflected immediately — agents building subsequent tasks will always use the latest version of the spec. ## How Agents Use Specs When a build agent picks up a task, it receives: 1. The **full specification** for architectural context 2. The **specific subtask** it's responsible for 3. The **acceptance criteria** it must satisfy 4. The **current codebase** state 5. Any **Integrations** entries (API keys, docs) This focused context means agents don't hallucinate features or make uninformed architectural decisions — they implement exactly what the spec defines. ## Example Spec Fragment ```markdown theme={null} ## Milestone 2: User Authentication (Complexity: Medium) ### Story 2.1: User Registration As a new user, I want to create an account with email and password, so that I can access personalized features. **Acceptance Criteria:** - User can register with email, password, and display name - Email validation prevents invalid formats - Password must be 8+ characters with one uppercase and one number - Duplicate emails show clear error message - Successful registration sends verification email #### Subtasks: - [ ] Create registration API endpoint with input validation - [ ] Build registration form component with client-side validation - [ ] Implement email verification flow with token generation - [ ] Add duplicate email detection with user-friendly error - [ ] Write unit tests for registration logic ``` ## What's next? Pick the right depth for your project. Start building against the spec. The interactive architecture graph, generated with your spec # The Workspace Source: https://docs.pre.dev/coding-agent/workspace A terminal-style chat plus live views of your plan, code, and running app. Every pre.dev project opens into the workspace: a terminal-style chat where you talk to the agent, surrounded by live views of everything it produces — the plan, the architecture, the spec, the code, and the running app. The workspace: terminal chat with the agent, session tabs, and live build progress ## The Agent chat The Agent view is where the work happens. Type what you want in plain language — a feature, a bug report, a question about the codebase — and the agent takes it from there. Every action the agent takes — searching, editing files, running commands — appears as a card in the feed. Click any card to expand the full detail: search results, file diffs, command output. While the agent reasons, a live ticker streams its thinking. Finished reasoning collapses into a "Thoughts" disclosure you can expand later. Type `/` in an empty composer to open the command palette. Filter by typing, navigate with arrow keys, execute with Enter. ## View tabs The view switcher (top of the workspace) moves between live views of your project. Each has a keyboard shortcut: Switch views from the header, or with ⌘1–⌘5 | View | Shortcut | What you see | | ----------------------- | -------- | ------------------------------------------------------ | | **Agent** | `⌘1` | The chat — talk to the agent, watch it work | | **Plan → Roadmap** | `⌘2` | Milestones and timeline, with real-time build progress | | **Plan → Architecture** | `⌘3` | Interactive system architecture graph | | **Plan → Spec** | `⌘4` | The full project specification documents | | **Code** | `⌘5` | The live codebase with git status and history | The Plan tabs and Code update in real time as the agent builds — you can watch files appear in the Code view while a sprint runs. The running app itself lives behind the **Preview** button. Two buttons sit alongside the views: * **Env vars** — manage your project's environment variables and API keys. See [Environment Variables](/coding-agent/integrations/env-vars). * **Preview** — open the running app. See [Preview & Hosting](/coding-agent/building/preview-and-hosting). ## Slash commands Type `/` in the chat composer to open the palette: The slash palette: build controls without leaving the composer | Command | What it does | | ------------------- | --------------------------------------------------------------- | | `/pro` | Toggle Pro Mode — pin every phase to the Pro model | | `/model` | Choose models per phase (chat / research / coding / acceptance) | | `/balance` | Show your remaining credit balance | | `/effort` | Set the sprint effort level (auto / low / medium / high) | | `/sprint ` | Launch a custom sprint in a new session | | `/fork ` | Spin a prompt off into a new isolated session | | `/reverse` | Map an existing codebase with reverse engineering | | `/kanban` | Jump to the Kanban board | | `/roadmap` | Jump to the Roadmap / Gantt | | `/arch` | Jump to the Architecture graph | A few more (`/skills`, `/mcp`, `/integrations`, `/share`, `/clear`, `/help`) appear in the palette marked "soon" — skills, MCP servers, and integrations are managed from the Integrations page until they go live in the composer. Two commands are two-level: `/effort ` lists the levels inline, and `/model ` walks you through phase, then model — all without leaving the composer. The same workspace concepts — the agent chat, slash commands, effort and model settings — work identically in the pre.dev CLI. See the [CLI overview](/cli/overview). ## Sessions The tab bar above the chat holds your sessions — isolated branches of the project you can work on in parallel and merge back. See [Sessions & Parallel Agents](/coding-agent/building/sessions-and-parallel-agents). ## What's next? Choose what to build next and how deep each sprint goes. Fork isolated sessions and fan work out to parallel agents. Monitor build progress from the roadmap view. Connect API keys, OAuth services, MCP servers, and skills. # What is pre.dev? Source: https://docs.pre.dev/overview The coding agent built for long-horizon tasks: it plans before it codes, remembers across sessions, and runs autonomously for hours. pre.dev is the coding agent for work that outlasts a single prompt. Before it writes any code, it plans — a full architecture, spec, and roadmap — then builds against that plan autonomously for hours, verifying each task before moving to the next and shipping real pull requests to your GitHub. Sessions persist, fork, and merge, so tomorrow's work builds on today's instead of starting over. ## Why plan first * **Long-horizon work needs a map.** An agent that improvises for hours drifts. pre.dev's spec — stack, milestones, user stories, acceptance criteria — is the contract every sprint builds and verifies against. * **Memory across sessions.** The plan, the codebase, and everything the agent has learned about your project persist. Fork a session to try something, merge back what works. * **Autonomy you can steer.** Run the whole roadmap on autopilot, review one task at a time, or dial effort per sprint — from a fast direct pass to the full research → code → verify pipeline. ## What's on this site * **[Coding Agent](/coding-agent/overview)** Flagship The full loop — plan, build, verify, ship. Use it from the web workspace or the CLI. * **[Browser Agents](/browser-agents/overview)** — fast, cheap, sandboxed browser automation for humans and AI. One REST call or MCP tool: scrape authed dashboards, fill forms, run multi-step flows, extract structured JSON. * **[Architect API](/architect-agent/overview)** — the planning brain as a standalone REST API and MCP server. Drop `fast_spec` / `deep_spec` into Cursor, Claude Code, or your own tooling. * **[CLI](/cli/overview)** — the same agent, workspace, and slash commands in your terminal. ## Find your way around **Ship entire applications from a prompt.** Real PRs, verified acceptance criteria, live preview and hosting, autonomous multi-hour builds. Sign up, describe an app, hit **Build on Autopilot**. Minutes to a deployed product. The web workspace's chat, slash commands, effort and model controls — in your terminal, on your machine. **Browser automation that behaves like an API.** Sync, async, or SSE-streamed. Structured data out, not raw HTML. One `POST /fast-spec` or `/deep-spec` returns a full structured plan — tech stack, milestones, user stories, granular subtasks. REST + MCP. What credits pay for, what each plan includes, and what happens when you run out mid-build.