# Authentication Source: https://docs.pre.dev/api-reference/authentication Authenticate REST, SDK, and MCP clients with the right account or organization. Create or retrieve your pre.dev API key at [pre.dev/projects/key](https://pre.dev/projects/key). Keep the key in your application's secret configuration and send it from your server or local development environment. ```bash theme={null} curl --fail-with-body https://api.pre.dev/browser-agent-status \ -H "Authorization: Bearer $PREDEV_API_KEY" ``` ## Supported headers | Interface | Recommended | Also accepted | | --------- | ------------------------------------- | --------------------------------------------------------------- | | REST | `Authorization: Bearer ` | `x-api-key: ` | | MCP | Browser OAuth for interactive clients | `Authorization: Bearer `, `x-api-key`, or `predev-api-key` | The `predev-api-key` header is specific to MCP. Use Bearer authentication to share one convention across both interfaces. ## Account and organization context A personal key acts in the personal account. An organization key selects the organization's context for specifications and credit usage. Browser history is scoped to the authenticated caller. Use the same account or organization when submitting work and retrieving it. Authentication and feature access are separate checks. Architect REST endpoints and the product MCP server require a key accepted for an active solo subscription or an organization. Eligible accounts may then use a limited specification trial. Browser REST endpoints also admit valid free accounts; task submission applies its own trial, credit, and queue checks. A valid free account can therefore reach the Browser Agents REST API while an Architect or MCP call returns `401`. See [plans and credits](/coding-agent/plans-and-credits) and inspect the response message for the required action. ## SDK setup ```typescript Node.js theme={null} import { PredevAPI } from 'predev-api'; const client = new PredevAPI({ apiKey: process.env.PREDEV_API_KEY! }); ``` ```python Python theme={null} import os from predev_api import PredevAPI client = PredevAPI(api_key=os.environ["PREDEV_API_KEY"]) ``` ## MCP OAuth Add `https://api.pre.dev/mcp` to your client's remote HTTP servers, then use the client's authentication flow. The browser asks you to sign in and select the account or organization. [MCP setup](/architect-agent/mcp-setup) includes client configuration and troubleshooting. # Errors and retries Source: https://docs.pre.dev/api-reference/errors Handle HTTP failures, browser task outcomes, stream errors, and safe retries. Check the HTTP status before parsing a success response. Successful HTTP delivery and successful task execution are separate: a browser batch can return HTTP `200` with individual task failures, and a specification status request can return HTTP `200` with `status: "failed"`. ## HTTP errors | HTTP | Meaning | Next step | | ----- | ---------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------- | | `400` | Missing input, invalid ID, or an oversized browser batch | Correct the request | | `401` | Missing/invalid credentials, or the account cannot authenticate for this interface | Check the key and [account access](/api-reference/authentication) | | `402` | Insufficient credits or a browser subscription requirement | Read the message and any `actionUrl` | | `403` | Access denied or specification trial exhausted | Check account context and plan eligibility | | `404` | Resource missing or inaccessible | Check the returned ID and the caller | | `429` | Rate limit or browser in-flight limit reached | Back off; inspect your [queue](/browser-agents/api/queue-status) | | `500` | Server-side failure | Inspect whether work was accepted before resubmitting | | `503` | Streaming capacity or website verification unavailable | Inspect `code`; retry DNS verification later, or use async submission for streaming capacity | General API errors usually include `error` and may include `message`. Browser submission gates use a machine-readable `code`: ```json theme={null} { "error": "The submission would exceed your in-flight task limit.", "code": "QUEUE_FULL" } ``` | Browser code | HTTP | Handling | | ----------------------- | ----- | ------------------------------------------------------- | | `INVALID_TASK` | `400` | Correct the task object, instructions, or output schema | | `INVALID_URL` | `400` | Provide a full HTTP(S) website URL | | `MISSING_INSTRUCTION` | `400` | Add instructions or a non-empty output schema | | `URL_UNREACHABLE` | `400` | Fix the domain; no DNS address was found | | `URL_CHECK_UNAVAILABLE` | `503` | Retry later; no tasks were started or charged | | `BATCH_TOO_LARGE` | `400` | Split the batch | | `SUBSCRIPTION_REQUIRED` | `402` | Follow `actionUrl` to review plans | | `INSUFFICIENT_CREDITS` | `402` | Follow `actionUrl` to add credits | | `QUEUE_FULL` | `429` | Wait for tasks to finish or submit fewer tasks | | `RATE_LIMITED` | `429` | Retry with exponential backoff and jitter | Input validation errors may include a zero-based `taskIndex` and a `field`. Validation rejects the whole batch before charging or starting work. Invalid tasks and explicit permanent URL/DNS failures are not retried in another sandbox; transient execution failures can still be retried. These codes belong to Browser Agents. Do not assume an Architect `402` has a browser gate code. ## Streaming failures Once SSE response headers have been sent, a failure arrives as an `event: error` frame, even though the HTTP status is `200`. The browser SDKs raise an exception for these frames. A disconnected stream or EOF without `done` does not establish success; fetch the run by its saved ID. The existing-run stream's `done` payload contains only the batch status. Fetch the final result after it. The submission stream's `done` payload contains the full batch. See [streaming](/browser-agents/api/stream-task). ## Retry submissions For REST browser requests, send a stable **`Idempotency-Key`** header. If a run with the same caller/key already exists from the last 24 hours, the API returns that run as JSON instead of creating a new one—even if the retry requested streaming. Keep the payload the same and use a new key for intentional new work. The API does not compare payloads for you. Do not rely on this lookup as a lock for simultaneous duplicate requests. Serialize retries of the same logical submission. Specification generation has no documented idempotency key. If a request times out, check history before generating again. A retry can create another specification and consume more credits. ## SDK exceptions Both SDKs provide `AuthenticationError`, `RateLimitError`, and `PredevAPIError`. Browser gate codes also map to `SubscriptionRequiredError`, `InsufficientCreditsError`, `QueueFullError`, and `BatchTooLargeError`. Billing exceptions may include `actionUrl` in Node or `action_url` in Python. The Node base exception exposes `message`; Python exceptions can be read with `str(error)`. Neither SDK exposes a `statusCode` / `status_code` property on its base exception. Use direct HTTP when your application needs the original status, headers, and full response body. # API overview Source: https://docs.pre.dev/api-reference/overview The public REST API for specifications, browser automation, proposal review, and credit balances. All public REST endpoints use **`https://api.pre.dev`** as their base URL. Paths are mounted at the root: use `/browser-agent`, not `/api/v1/browser-agents`. Get a key at [pre.dev/projects/key](https://pre.dev/projects/key), then send `Authorization: Bearer $PREDEV_API_KEY`. Read [authentication](/api-reference/authentication) and [errors](/api-reference/errors) before building an integration. ## Specifications | Method | Path | Reference | | ------ | ----------------------- | ------------------------------------------------------------- | | POST | `/fast-spec` | [Generate a Fast Spec](/architect-agent/api/fast-spec) | | POST | `/deep-spec` | [Generate a Deep Spec](/architect-agent/api/deep-spec) | | GET | `/spec-status/{specId}` | [Status and full artifacts](/architect-agent/api/spec-status) | | GET | `/list-specs` | [List specifications](/architect-agent/api/list-specs) | | GET | `/find-specs` | [Search specifications](/architect-agent/api/find-specs) | | GET | `/credits-balance` | [Credit balance](/architect-agent/api/credits-balance) | ## Browser Agents | Method | Path | Reference | | ------ | ---------------------------- | -------------------------------------------------------------------- | | POST | `/browser-agent` | [Submit tasks](/browser-agents/api/run-task) | | GET | `/browser-agent/{id}` | [Status and results](/browser-agents/api/task-status) | | GET | `/browser-agent/{id}/stream` | [Watch an existing run with SSE](/browser-agents/api/stream-task) | | GET | `/browser-agent/{id}/ws` | [Get a live browser WebSocket URL](/browser-agents/api/live-browser) | | GET | `/list-browser-agents` | [List runs](/browser-agents/api/list-tasks) | | GET | `/browser-agent-status` | [Your queue and in-flight limit](/browser-agents/api/queue-status) | | GET | `/browser-agent-capacity` | [Service capacity](/browser-agents/api/capacity) | ## Proposals Upload a proposal, compare it with a generated specification, and retrieve the assessment. Start with the [proposal workflow](/architect-agent/proposals). | Method | Path | Reference | | ------ | ----------------------------------------- | ------------------------------------------------------------------------- | | POST | `/upload-proposal` | [Upload a proposal](/architect-agent/api/upload-proposal) | | GET | `/list-proposals` | [List proposals](/architect-agent/api/list-proposals) | | GET | `/get-proposal/{proposalId}` | [Retrieve a proposal](/architect-agent/api/get-proposal) | | POST | `/vet-proposal` | [Review a proposal against a spec](/architect-agent/api/vet-proposal) | | GET | `/list-vetted-proposals` | [List assessments for a spec](/architect-agent/api/list-vetted-proposals) | | GET | `/get-vetted-proposal/{vettedProposalId}` | [Retrieve an assessment](/architect-agent/api/get-vetted-proposal) | ## SDKs and MCP The [Node SDK](/architect-agent/sdks/node) and [Python SDK](/architect-agent/sdks/python) wrap specification and browser operations. Use direct HTTP for endpoints or headers without a wrapper, including proposal review, live browser URLs, existing-run SSE, and browser idempotency keys. The [MCP server](/architect-agent/mcp-setup) exposes seven primary tools and three deprecated browser aliases. MCP uses JSON-RPC over HTTP; its parameter names and result envelopes differ from REST. See the [tool reference](/mcp/tools). Download the complete [OpenAPI 3.1 schema](/api-reference/openapi.json) for code generation or agent ingestion. # Get credit balance Source: https://docs.pre.dev/architect-agent/api/credits-balance api-reference/openapi.json GET /credits-balance Read the credit balance selected by your authenticated account or organization. ```bash theme={null} curl --fail-with-body https://api.pre.dev/credits-balance \ -H "Authorization: Bearer $PREDEV_API_KEY" ``` Example response: ```json theme={null} { "success": true, "creditsRemaining": 42.5 } ``` Credit balances can be fractional. The key determines which account or organization balance is returned; there is no user or organization request parameter. Use this for budgeting before generation. A balance check does not reserve credits, and specification costs vary. For browser submissions, also check your [queue and in-flight limit](/browser-agents/api/queue-status). In Node, call `client.getCreditsBalance()`. In Python, `client.get_credits_balance()` returns a `CreditsBalanceResponse` object, so read `balance.creditsRemaining`. This is an exception to the Python SDK's dictionary-shaped specification and browser responses. # Generate a Deep Spec Source: https://docs.pre.dev/architect-agent/api/deep-spec api-reference/openapi.json POST /deep-spec Generate a detailed implementation specification with milestones, stories, and granular subtasks. Deep Spec adds implementation detail to the planning pass. It accepts the same JSON and multipart fields as [Fast Spec](/architect-agent/api/fast-spec). ## Example ```bash theme={null} curl --fail-with-body https://api.pre.dev/deep-spec \ -H "Authorization: Bearer $PREDEV_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "input": "Build an organization-scoped reporting platform with scheduled exports, audit logs, and role-based access.", "async": true }' ``` Save `specId` from the HTTP `200` response, then [poll its status](/architect-agent/api/spec-status). Async submission is useful for detailed specifications because generation can outlast client or proxy timeouts. [Inputs and outputs](/architect-agent/inputs-and-outputs) explains file uploads, existing context, JSON, Markdown, and graphs. Credit use is variable; inspect `creditsUsed` rather than assuming a fixed per-request price. Access and trial errors follow the same [authentication and error rules](/api-reference/errors) as Fast Spec. # Generate a Fast Spec Source: https://docs.pre.dev/architect-agent/api/fast-spec api-reference/openapi.json POST /fast-spec Generate a specification with architecture, milestones, user stories, and acceptance criteria. Fast Spec is a concise planning pass. [Compare Fast and Deep](/coding-agent/specifications/fast-vs-deep), or read [inputs and outputs](/architect-agent/inputs-and-outputs) for context, uploads, and artifact formats. ## Example ```bash theme={null} curl --fail-with-body https://api.pre.dev/fast-spec \ -H "Authorization: Bearer $PREDEV_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "input": "Add CSV exports to the reporting dashboard.", "currentContext": "Existing TypeScript app with a reports API and organization-scoped access.", "async": true }' ``` With `async: true`, HTTP `200` returns `{ "specId": "…", "status": "pending" }`. Poll [spec status](/architect-agent/api/spec-status) using the returned ID. With async omitted or false, the connection waits for the completed specification; long requests can exceed your client's timeout. ## Access and failures An accepted API key is required. Eligible accounts can use a limited specification trial; paid generation requires available credits. Trial exhaustion returns `403`, insufficient credits `402`, and invalid inputs `400`. See [authentication](/api-reference/authentication) and [errors](/api-reference/errors). Generation cost varies with the request. The completed result includes `creditsUsed` when available. A network timeout does not prove generation stopped; check history before creating another spec. # Search specifications Source: https://docs.pre.dev/architect-agent/api/find-specs api-reference/openapi.json GET /find-specs Search original specification inputs with a case-insensitive regular expression. Pass the required `query` parameter as a regular expression. Search applies to the **original input text**, not the generated specification body. ```bash theme={null} curl --fail-with-body --get https://api.pre.dev/find-specs \ -H "Authorization: Bearer $PREDEV_API_KEY" \ --data-urlencode 'query=export|report' \ --data-urlencode 'status=completed' \ --data-urlencode 'limit=20' ``` | Query | Matches | | ---------------- | --------------------------------------------- | | `payment` | Inputs containing payment, case-insensitively | | `^Build` | Inputs starting with Build | | `export\|report` | Inputs containing either word | Use `--data-urlencode` or your HTTP library's query encoder so regex characters reach the API intact. Escape regex metacharacters when you intend a literal search. The `specs`, `total`, and `hasMore` envelope uses the same summary format and pagination as [list specifications](/architect-agent/api/list-specs). Use [spec status](/architect-agent/api/spec-status) for full bodies. A missing or empty query returns `400`. An invalid regular expression returns `500`; correct the pattern instead of repeatedly retrying it. # Get a proposal Source: https://docs.pre.dev/architect-agent/api/get-proposal api-reference/openapi.json GET /get-proposal/{proposalId} Retrieve an uploaded proposal by its ID. Use the `proposalId` from upload or `_id` from listing: ```bash theme={null} curl --fail-with-body "https://api.pre.dev/get-proposal/$PROPOSAL_ID" \ -H "Authorization: Bearer $PREDEV_API_KEY" ``` The response is the proposal object itself, not a `{ proposal: … }` envelope. It can include `proposalName`, `proposalContent`, `proposalFile`, `createdAt`, and `updatedAt`. A malformed ID returns `400`; an unknown ID returns `404`. # Get a proposal assessment Source: https://docs.pre.dev/architect-agent/api/get-vetted-proposal api-reference/openapi.json GET /get-vetted-proposal/{vettedProposalId} Retrieve one stored proposal comparison and its recommendations. ```bash theme={null} curl --fail-with-body "https://api.pre.dev/get-vetted-proposal/$VETTED_PROPOSAL_ID" \ -H "Authorization: Bearer $PREDEV_API_KEY" ``` Use the assessment's `_id` returned by vetting or listing. The response is the assessment object itself. It includes the associated `specId` and `proposalId`, plus the [assessment fields](/architect-agent/proposals#assessment-fields). A malformed ID returns `400`, denied access `403`, and an unknown assessment `404`. # List proposals Source: https://docs.pre.dev/architect-agent/api/list-proposals api-reference/openapi.json GET /list-proposals List uploaded proposals with offset pagination. ```bash theme={null} curl --fail-with-body 'https://api.pre.dev/list-proposals?limit=20&skip=0' \ -H "Authorization: Bearer $PREDEV_API_KEY" ``` The response contains `proposals`, `total`, and `hasMore`. Proposals are sorted by creation time, newest first. `limit` defaults to `20` and is capped at `100`; use positive limits and a nonnegative `skip`. Listing is scoped to the authenticated user. Entries include `_id`, `proposalName`, `proposalContent`, timestamps, and optional file metadata. Use `_id` as `proposalId` in other proposal requests. # List specifications Source: https://docs.pre.dev/architect-agent/api/list-specs api-reference/openapi.json GET /list-specs Browse specification summaries with filters and offset pagination. Results are sorted newest first. Use `limit` (default `20`, maximum `100`), `skip` (default `0`), and optional `endpoint` or `status` filters. ```bash theme={null} curl --fail-with-body 'https://api.pre.dev/list-specs?limit=20&skip=0&status=completed' \ -H "Authorization: Bearer $PREDEV_API_KEY" ``` The response contains `specs`, `total`, and `hasMore`. Increase `skip` by your page size while `hasMore` is true. ## Summaries and full results Entries include `_id`, `created`, `input`, `endpoint`, `status`, available download links, and other summary metadata. They do **not** include full Markdown/JSON bodies, graph data, or live progress messages. Retrieve a specific entry with [spec status](/architect-agent/api/spec-status) before reading its artifacts. Supported endpoints are `fast_spec` and `deep_spec`; supported statuses are `pending`, `processing`, `completed`, and `failed`. Unknown filter values are ignored. Use [search](/architect-agent/api/find-specs) to match text in the original input. # List proposal assessments Source: https://docs.pre.dev/architect-agent/api/list-vetted-proposals api-reference/openapi.json GET /list-vetted-proposals List stored assessments for a specification you can access. ```bash theme={null} curl --fail-with-body --get https://api.pre.dev/list-vetted-proposals \ -H "Authorization: Bearer $PREDEV_API_KEY" \ --data-urlencode "specId=$SPEC_ID" \ --data-urlencode 'limit=20' \ --data-urlencode 'skip=0' ``` `specId` is required. The response contains `vettedProposals`, `total`, and `hasMore`. `limit` defaults to `20` and is capped at `100`; use a positive limit and nonnegative offset. An empty result is an empty array. Missing/invalid specification IDs return `400`, inaccessible specifications `403`, and unknown specifications `404`. Use an assessment's `_id` to [retrieve it directly](/architect-agent/api/get-vetted-proposal). # Get specification status Source: https://docs.pre.dev/architect-agent/api/spec-status api-reference/openapi.json GET /spec-status/{specId} Retrieve generation progress, a failure message, or the complete specification artifacts. Use the `specId` returned by an async request. IDs are 24-character hexadecimal strings; copy the returned value rather than constructing one. ```bash theme={null} curl --fail-with-body "https://api.pre.dev/spec-status/$SPEC_ID" \ -H "Authorization: Bearer $PREDEV_API_KEY" ``` ## Status lifecycle | Status | Meaning | Action | | ------------ | ----------------------------- | --------------------------------- | | `pending` | Accepted and waiting to start | Keep polling | | `processing` | Generation is underway | Display progress and keep polling | | `completed` | Generation finished | Read the specification artifacts | | `failed` | Generation failed | Read `errorMessage` | Poll at a bounded interval, for example five seconds, with an application deadline. The response identifies the request as **`_id`**, while the async submission names that value **`specId`**. `progress` is a percentage and `progressMessage` is display text. Completed requests report progress 100; a failed request can report progress 0. Progress is not a substitute for checking `status`. ## Result fields Full results can include both specification variants as JSON and Markdown, download URLs, graphs, technology explanations, archives, estimates, and credit usage. See [inputs and outputs](/architect-agent/inputs-and-outputs). Optional fields can be absent or null until their artifacts exist. A successful status lookup is HTTP `200` even when the generation status is `failed`. A malformed ID returns `400`; a missing or inaccessible request returns `404`. # Upload a proposal Source: https://docs.pre.dev/architect-agent/api/upload-proposal api-reference/openapi.json POST /upload-proposal Store proposal text or a document for later comparison with a specification. Provide `proposalName` and at least one of `text` or `file`. Text-only requests can use JSON; files use multipart form data. ```bash theme={null} curl --fail-with-body https://api.pre.dev/upload-proposal \ -H "Authorization: Bearer $PREDEV_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "proposalName": "Reporting dashboard implementation", "text": "We propose organization-scoped reports, CSV export, and audit logging delivered in three milestones." }' ``` The HTTP `200` response contains `success: true` and `proposalId`. Save that ID to [retrieve](/architect-agent/api/get-proposal) or [vet](/architect-agent/api/vet-proposal) the proposal. For file uploads, use the same [formats and 20 MiB limit](/architect-agent/inputs-and-outputs#upload-a-file) as specification uploads. Missing `proposalName`, or missing both file and text, returns `400`. # Vet a proposal Source: https://docs.pre.dev/architect-agent/api/vet-proposal api-reference/openapi.json POST /vet-proposal Compare a proposal with a completed specification and return the assessment. Provide `specId` and either an existing `proposalId`, or a new `proposalName` with `text` or `file`. An existing `proposalId` takes precedence over file/text fields. ```bash theme={null} curl --fail-with-body https://api.pre.dev/vet-proposal \ -H "Authorization: Bearer $PREDEV_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "specId": "507f1f77bcf86cd799439011", "proposalName": "Reporting dashboard implementation", "text": "We propose organization-scoped reports, CSV export, and audit logging delivered in three milestones." }' ``` Replace the example ID with an actual completed specification ID. The HTTP `200` response contains `success`, `vettedProposal`, and `proposal`. The assessment's `_id` is used to [retrieve it later](/architect-agent/api/get-vetted-proposal). ## Billing behavior This operation charges **100 credits before later proposal validation and analysis**. Check the specification, proposal ID, name, and content before calling it. There is no documented idempotency key, async mode, or automatic refund guarantee for validation/analysis failures. Check [existing assessments](/architect-agent/api/list-vetted-proposals) before retrying a request whose outcome is uncertain. Insufficient credits returns `402`. Input or ID validation can return `400`; a missing proposal can return `404`. Read the [proposal workflow](/architect-agent/proposals) for assessment fields. # Inputs and outputs Source: https://docs.pre.dev/architect-agent/inputs-and-outputs Provide context and files, then consume specifications, estimates, graphs, and documentation archives. Fast and Deep Spec share the same REST input fields and output formats. The [OpenAPI schema](/api-reference/openapi.json) defines their machine-readable shapes. ## Describe a project or a change | Field | JSON request | Meaning | | ---------------- | --------------------------------- | --------------------------------------------------------------------- | | `input` | Required, nonempty string | The project or feature to specify | | `currentContext` | Optional string | Existing stack, code structure, implemented behavior, and constraints | | `docURLs` | Optional array of strings | Documentation URLs to reference | | `async` | Optional boolean, default `false` | Return a `specId` for polling instead of waiting | `currentContext` is text, not a project lookup ID. Include the relevant context explicitly. The MCP equivalents are `executiveSummary` and `existingContext`; see the [field mapping](/for-agents#keep-names-distinct). ## Upload a file Use `multipart/form-data` with one `file`. Supply the file, `input` text, or both. Accepted formats are PDF, DOC, DOCX, TXT, JPEG, and PNG, up to **20 MiB** (20 × 1,024 × 1,024 bytes). ```bash theme={null} curl --fail-with-body https://api.pre.dev/fast-spec \ -H "Authorization: Bearer $PREDEV_API_KEY" \ -F 'file=@requirements.pdf;type=application/pdf' \ -F 'input=Turn these requirements into an implementation plan.' \ -F 'currentContext=Existing TypeScript app with PostgreSQL.' \ -F 'docURLs=["https://www.postgresql.org/docs/current/"]' \ -F 'async=true' ``` In multipart requests, encode `docURLs` as a **JSON string** and `async` as `true` or `false` text. Let your HTTP library set the multipart boundary. The file part must carry an accepted MIME type; renaming an unsupported file is not sufficient. The response may include `uploadedFileName` and `uploadedFileShortUrl`. File upload is a REST feature; MCP specification tools do not accept a `file` argument. ## Choose the output for your reader | Output | Contains | | ------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- | | `codingAgentSpecJson` | Title, executive summary, core functionality, stack, milestones, stories, acceptance criteria, and subtasks where generated | | `codingAgentSpecMarkdown` | The same implementation plan as Markdown | | `humanSpecJson` | Planning detail plus personas, roles, and hour estimates | | `humanSpecMarkdown` | Human-readable specification and estimates | | `codingAgentSpecUrl` / `humanSpecUrl` | Download links for the corresponding specification | | `totalHumanHours` | Estimated implementation effort; not a delivery commitment | Request [spec status](/architect-agent/api/spec-status) for full bodies. [List](/architect-agent/api/list-specs) and [search](/architect-agent/api/find-specs) return summaries and links, not full specification bodies or graphs. ## Graphs and visual artifacts `userFlowGraph` and `architectureGraph` each contain `nodes` and `edges`. Use node `id` values to resolve an edge's `source` and `target`. ```json theme={null} { "nodes": [ { "id": "web", "label": "Web app", "type": "container", "level": "C2" }, { "id": "api", "label": "API", "type": "container", "level": "C2" } ], "edges": [ { "source": "web", "target": "api", "description": "HTTPS requests" } ] } ``` In this example, the web app sends HTTPS requests to the API. The edge points from the node named by `source` to the node named by `target`: Node `level` can be a number, a string, or null: user-flow graphs can use numeric depth, while architecture graphs use levels such as `C1` and `C2`. `architectureInfographicUrl` is an optional rendered diagram. `enrichedTechStack` explains technology choices, uses, alternatives, and helpful links. ## Documentation archives When reference documentation can be retrieved, `zippedDocsUrls` contains entries with `platform`, `masterZipShortUrl`, and `masterMarkdownShortUrl`. Archive generation is best effort; archives may be absent or empty even when the specification succeeds. Use the source documentation for details that need current verification. ## Optional fields The returned fields depend on generation progress and available artifacts. Optional outputs may be absent or null; check them before rendering or downloading. Use `status` for lifecycle decisions, `progressMessage` for display, and `creditsUsed` for observed credit usage. # Connect the MCP server Source: https://docs.pre.dev/architect-agent/mcp-setup Use pre.dev's specification and browser tools from Claude Code, Cursor, or another remote MCP client. The pre.dev product MCP server is **`https://api.pre.dev/mcp`**. One connection exposes [seven primary tools](/mcp/tools) for specifications and browser automation. ## Connect your client Register the remote HTTP server: ```bash theme={null} claude mcp add --transport http predev https://api.pre.dev/mcp ``` In Claude Code, run `/mcp`, select predev, and follow the browser authentication flow. Sign in to pre.dev and select the account or organization to connect. See the [Claude Code MCP documentation](https://code.claude.com/docs/en/mcp) for client-specific settings. Add this to your Cursor MCP configuration, then use the server's authentication control: ```json theme={null} { "mcpServers": { "predev": { "url": "https://api.pre.dev/mcp" } } } ``` You can also [add pre.dev to Cursor](cursor://anysphere.cursor-deeplink/mcp/install?name=predev\&config=eyJ1cmwiOiJodHRwczovL2FwaS5wcmUuZGV2L21jcCJ9). The client opens a browser when authentication is needed. Add a remote server with **Streamable HTTP** transport and URL `https://api.pre.dev/mcp`. Use browser OAuth if your client supports it. For a programmatic client, send one of the [supported authentication headers](/api-reference/authentication), for example `Authorization: Bearer `. Obtain the key at [pre.dev/projects/key](https://pre.dev/projects/key). No pre.dev npm MCP server package is required. ## Try a tool Ask your assistant: ```text theme={null} Use pre.dev fast_spec to plan a team task manager with projects, assignees, due dates, and organization-scoped access. Retrieve the completed specification and show me its milestones. ``` Or try [browser automation](/browser-agents/mcp-tool): ```text theme={null} Use pre.dev browser_agent to read https://example.com and extract its main heading. Fetch the complete structured result afterward. ``` Tool execution uses your account's credits and access. Connecting a server does not change your plan. See [authentication eligibility](/api-reference/authentication) if a free account can use browser REST but cannot authenticate to MCP. ## Connection lifecycle The client authenticates, initializes the connection, discovers tools, and calls one. Progress notifications can arrive before the tool result. Use a standard MCP client library to handle JSON-RPC initialization and response streams. For Streamable HTTP, requests should accept both `application/json` and `text/event-stream`. ## Transport details | Endpoint | Purpose | | -------------------------------- | ----------------------------------------------------- | | `POST /mcp` | Current Streamable HTTP transport; stateless requests | | `GET /mcp/info` | Public metadata and tool inventory | | `GET /mcp` | Returns `405 Method Not Allowed`; this is expected | | `GET /mcp/sse` | Deprecated legacy SSE connection | | `POST /mcp/messages?sessionId=…` | Message endpoint for a legacy SSE session | The server advertises protocol versions `2024-11-05`, `2025-03-26`, `2025-06-18`, and `2025-11-25`. Let the client negotiate a supported version. An unsupported `MCP-Protocol-Version` header returns `400`. The current transport does not create a persistent MCP session ID or provide a server-initiated GET stream. Notifications arrive on the active POST response. Legacy clients must use the separate `/mcp/sse` endpoint. ## Troubleshooting | Symptom | What to check | | -------------------------------------------- | --------------------------------------------------------------------------------------- | | Opening `/mcp` in a browser returns `405` | Open [service metadata](https://api.pre.dev/mcp/info); configure the MCP client to POST | | Authentication fails | Reauthenticate in the client; check the selected account, key, and plan | | Tools are missing | Restart or refresh the client, then rediscover `tools/list` | | A spec tool returns before the spec is ready | Save its ID and poll `get_spec` | | A browser result contains only a summary | Call `browser_agent_get` for full data | | Progress is missing | Logging support varies by client; progress notifications require a `progressToken` | For exact arguments and return formats, use the [MCP tool reference](/mcp/tools). To attach a third-party server **to the pre.dev Coding Agent**, use [external MCP servers](/coding-agent/integrations/mcp-servers). # Architect API Source: https://docs.pre.dev/architect-agent/overview Generate software specifications with Markdown, structured JSON, architecture graphs, and implementation estimates. The Architect API turns a project description into an implementation plan. Choose **Fast Spec** for milestones and stories, or **Deep Spec** for a more detailed breakdown with subtasks. Both accept existing codebase context and reference documentation. Submit a request, poll its status, and read the completed artifacts. Connect fast\_spec and deep\_spec through the pre.dev MCP server. ## From request to artifacts Send your requirements, optional codebase context, and any reference files or documentation URLs. The completed result offers the same plan in formats suited to different readers. The coding-agent variant focuses on requirements and implementation structure. The human variant adds personas, roles, and effort estimates. Graphs, an architecture infographic, and documentation archives are returned when available; integrations should tolerate absent optional artifacts. ## Choose the depth | | Fast Spec | Deep Spec | | ----------------------- | ------------------------------------------- | --------------------------------- | | Structure | Milestones and user stories | Milestones, stories, and subtasks | | Starting point | Early planning and straightforward features | Detailed implementation planning | | Typical generation time | About 1 minute | About 3–5 minutes | | Typical credits | About 5–10 | About 10–50 | Times and credit usage are estimates, not fixed limits or quotes. Use the returned `creditsUsed` for actual consumption. See [plans and credits](/coding-agent/plans-and-credits) for access, and [Fast vs Deep](/coding-agent/specifications/fast-vs-deep) for planning guidance. ## Read next * [Inputs and outputs](/architect-agent/inputs-and-outputs) — files, context, documentation, and graph data. * [Status and results](/architect-agent/api/spec-status) — polling and failure handling. * [List](/architect-agent/api/list-specs) or [search](/architect-agent/api/find-specs) — retrieve existing work. * [Proposal review](/architect-agent/proposals) — compare a proposal with a completed specification. * [Python](/architect-agent/sdks/python) and [Node](/architect-agent/sdks/node) — official SDKs. # Review proposals against a spec Source: https://docs.pre.dev/architect-agent/proposals Upload a proposal, compare it with a completed specification, and retrieve the assessment. The proposal API compares a vendor or implementation proposal with a generated specification. It returns a recommendation, alignment and confidence scores, strengths, concerns, gaps, and suggested changes. ## Workflow 1. Generate a [Fast Spec](/architect-agent/api/fast-spec) or [Deep Spec](/architect-agent/api/deep-spec) and wait for completion. 2. [Upload a proposal](/architect-agent/api/upload-proposal) with `proposalName` and a file or text, or provide them directly to `/vet-proposal`. 3. [Vet the proposal](/architect-agent/api/vet-proposal) using the specification ID and proposal content or an existing `proposalId`. 4. Review the generated assessment; use [list assessments](/architect-agent/api/list-vetted-proposals) or [get assessment](/architect-agent/api/get-vetted-proposal) to retrieve it later. ## Cost and retries Vetting charges **100 credits per call** before subsequent proposal lookup, content validation, and analysis. Verify your IDs and required content before submitting. There is no documented idempotency key or async mode for this operation; do not automatically retry a timeout, because another call can charge again. Uploading and retrieving a proposal do not themselves run the paid comparison. These operations use direct REST; there are no proposal methods in the official SDKs or product MCP tools. ## Assessment fields | Field | Meaning | | ---------------------- | ----------------------------------- | | `shouldAccept` | Generated recommendation | | `acceptanceConfidence` | Confidence score, 0–100 | | `overallAlignment` | Alignment score, 0–100 | | `strengths` | Positive findings | | `weaknesses` | Concerns | | `criticalGaps` | Missing requirements | | `recommendations` | Suggested improvements | | `executiveSummary` | Short explanation of the assessment | Use the scores with their supporting explanations when reviewing a proposal. They are generated assessments, not a guarantee of delivery or suitability. # Architect quickstart Source: https://docs.pre.dev/architect-agent/quickstart Generate a specification asynchronously, poll to completion, and read its Markdown and JSON. By the end of this guide, you will have a saved specification ID and a completed implementation plan in Markdown and JSON. ## Before you start Get your key from [pre.dev/projects/key](https://pre.dev/projects/key) and make it available as `PREDEV_API_KEY`. The [authentication guide](/api-reference/authentication) explains account and organization access. ## 1. Submit a specification Use async mode so generation can continue without keeping your HTTP connection open: ```bash theme={null} curl --fail-with-body https://api.pre.dev/fast-spec \ -H "Authorization: Bearer $PREDEV_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "input": "Build a team task manager with projects, assignees, due dates, and organization-scoped access.", "async": true }' ``` The API returns HTTP `200` with an ID: ```json theme={null} { "specId": "507f1f77bcf86cd799439011", "status": "pending" } ``` To request a deeper implementation breakdown, use `/deep-spec` with the same body. For feature work, include `currentContext` describing the existing stack and architecture. See [inputs and outputs](/architect-agent/inputs-and-outputs). ## 2. Poll the saved ID Set `SPEC_ID` to the actual ID from your response: ```bash theme={null} curl --fail-with-body "https://api.pre.dev/spec-status/$SPEC_ID" \ -H "Authorization: Bearer $PREDEV_API_KEY" ``` Poll every few seconds with a deadline. Status moves through `pending` and `processing` to `completed` or `failed`. `progress` and `progressMessage` describe work in progress. ## 3. Read the result When `status` is `completed`, use: | Field | Purpose | | ------------------------------------------------- | -------------------------------------------- | | `codingAgentSpecMarkdown` / `codingAgentSpecJson` | Implementation context for agents | | `humanSpecMarkdown` / `humanSpecJson` | Human review, personas, roles, and estimates | | `userFlowGraph` / `architectureGraph` | Nodes and edges for visualization | | `predevUrl` | Open the project in the web workspace | | `creditsUsed` | Actual specification credit usage | If `status` is `failed`, read `errorMessage`. Do not treat an HTTP `200` status response as proof of successful generation. For a complete polling example, use the [Python SDK guide](/architect-agent/sdks/python) or [Node SDK guide](/architect-agent/sdks/node). # Node.js SDK Source: https://docs.pre.dev/architect-agent/sdks/node Generate and retrieve specifications with the published predev-api TypeScript client. ```bash theme={null} npm install predev-api ``` The package is ESM and supports Node.js 18+. ## Generate and wait for a specification ```typescript theme={null} import { PredevAPI } from 'predev-api'; const client = new PredevAPI({ apiKey: process.env.PREDEV_API_KEY! }); const job = await client.fastSpecAsync({ input: 'Build a team task manager with projects and assignees.', currentContext: 'Use TypeScript and preserve organization-scoped access.', }); console.log('Save this ID:', job.specId); const deadline = Date.now() + 600_000; async function waitForSpec() { while (Date.now() < deadline) { const spec = await client.getSpecStatus(job.specId); if (spec.status === 'completed') return spec; if (spec.status === 'failed') { throw new Error(spec.errorMessage ?? 'Specification failed'); } await new Promise(resolve => setTimeout(resolve, 5_000)); } throw new Error('Polling deadline reached; retrieve the saved spec ID later.'); } const spec = await waitForSpec(); console.log(spec.codingAgentSpecMarkdown); ``` ## Method reference | Method | Parameters | Return | | ------------------------ | ----------------------------------------------------- | --------------------------------- | | `fastSpec(options)` | `input`, optional `currentContext`, `docURLs`, `file` | `Promise` | | `deepSpec(options)` | Same | `Promise` | | `fastSpecAsync(options)` | Same | `Promise` | | `deepSpecAsync(options)` | Same | `Promise` | | `getSpecStatus(specId)` | Specification ID | `Promise` | | `listSpecs(params)` | Optional `limit`, `skip`, `endpoint`, `status` | `Promise` | | `findSpecs(params)` | Required `query`; same filters | `Promise` | | `getCreditsBalance()` | None | `Promise` | All methods use `https://api.pre.dev` by default. The constructor accepts `apiKey` and optional `baseUrl`; it has no timeout, retry, or custom-header option. Use direct HTTP when you need those controls. A polling deadline does not abort an in-flight SDK request. ## History and credits ```typescript theme={null} const page = await client.findSpecs({ query: 'report|export', status: 'completed' }); for (const summary of page.specs) { console.log(summary._id, summary.input); } const balance = await client.getCreditsBalance(); console.log(balance.creditsRemaining); ``` List and search return summaries. Retrieve a specific ID for full bodies and graphs. Optional artifacts can be absent or null; see [inputs and outputs](/architect-agent/inputs-and-outputs). ## File uploads Pass a **Blob with an accepted MIME type**. SDK 1.1.0 encodes its `{ data: Buffer, name }` alternative as `application/octet-stream`, which the API's file filter does not accept. ```typescript theme={null} import { readFile } from 'node:fs/promises'; const bytes = await readFile('requirements.pdf'); const upload = await client.fastSpecAsync({ input: 'Create an implementation plan from these requirements.', file: new Blob([new Uint8Array(bytes)], { type: 'application/pdf' }), docURLs: ['https://www.postgresql.org/docs/current/'], }); console.log(upload.specId); ``` The SDK serializes `docURLs` correctly for multipart requests. It generates a filename for Blob uploads; use direct multipart HTTP if preserving the original filename matters. See [accepted formats and limits](/architect-agent/inputs-and-outputs#upload-a-file). ## Errors ```typescript theme={null} import { AuthenticationError, RateLimitError, PredevAPIError } from 'predev-api'; try { await client.listSpecs({ limit: 20 }); } catch (error) { if (error instanceof AuthenticationError) { console.error('Check the API key and account access at pre.dev/projects/key.'); } else if (error instanceof RateLimitError) { console.error('Back off before retrying.'); } else if (error instanceof PredevAPIError) { console.error(error.message); } else { throw error; } } ``` The base exception has no `statusCode` property. Browser gate errors have additional typed subclasses; see [errors and retries](/api-reference/errors). An Architect `402` without a machine-readable browser gate code raises `PredevAPIError`. Continue with the [Browser Agents Node guide](/browser-agents/sdks/node), [npm package](https://www.npmjs.com/package/predev-api), or [SDK source](https://github.com/predotdev/predev-api). # SDKs Source: https://docs.pre.dev/architect-agent/sdks/overview Install the official Node.js and Python SDKs for specifications and browser tasks. Both SDKs use the package name **`predev-api`** and support specification generation and Browser Agents. | | Node.js / TypeScript | Python | | --------------------- | --------------------------------------------- | ----------------------------------------------- | | Install | `npm install predev-api` | `pip install predev-api` | | Import | `import { PredevAPI } from 'predev-api'` | `from predev_api import PredevAPI` | | Runtime | Node.js 18+ | Python 3.8+ | | HTTP behavior | Promises; async generator for browser streams | Blocking requests; iterator for browser streams | | Specification results | JavaScript objects | Dictionaries | | Credit balance | JavaScript object | `CreditsBalanceResponse` object | | Browser results | JavaScript objects | Dictionaries | Both clients accept an API key and optional base URL. Neither exposes a client-wide timeout or retry configuration option. Python sets timeouts inside its methods; use server-side async submission for long work and direct HTTP when you need transport controls. Specifications, bounded polling, uploads, and errors. Specification results, async jobs, and file uploads. See [Browser Agents SDKs](/browser-agents/sdks/overview) for task execution and streaming. Use direct REST for proposal review, live browser URLs, existing-run SSE, capacity statistics, and idempotency headers. # Python SDK Source: https://docs.pre.dev/architect-agent/sdks/python Generate and retrieve specifications with the published predev-api Python package. ```bash theme={null} pip install predev-api ``` Python 3.8+ is supported. ## Generate and wait for a specification ```python theme={null} import os import time from predev_api import PredevAPI client = PredevAPI(api_key=os.environ["PREDEV_API_KEY"]) job = client.fast_spec_async( input_text="Build a team task manager with projects and assignees.", current_context="Use TypeScript and preserve organization-scoped access.", ) print("Save this ID:", job["specId"]) deadline = time.monotonic() + 600 while time.monotonic() < deadline: spec = client.get_spec_status(job["specId"]) if spec["status"] == "completed": print(spec.get("codingAgentSpecMarkdown", "No Markdown returned")) break if spec["status"] == "failed": raise RuntimeError(spec.get("errorMessage", "Specification failed")) time.sleep(5) else: raise TimeoutError("Polling deadline reached; retrieve the saved spec ID later.") ``` Specification, status, search, list, and browser methods return **dictionaries** at runtime, despite dataclass return annotations in the package. Use `job["specId"]` and `spec["status"]`, not `job.specId` or `spec.status`. `get_credits_balance()` is the exception: it constructs a `CreditsBalanceResponse` object. ## Method reference | Method | Parameters | Runtime return | | -------------------------- | ------------------------------------------------------------ | ------------------------------------------- | | `fast_spec(...)` | `input_text`, optional `current_context`, `doc_urls`, `file` | Completed specification dictionary | | `deep_spec(...)` | Same | Completed specification dictionary | | `fast_spec_async(...)` | Same | Dictionary with `specId`, `status` | | `deep_spec_async(...)` | Same | Dictionary with `specId`, `status` | | `get_spec_status(spec_id)` | Specification ID | Specification dictionary | | `list_specs(...)` | Optional `limit`, `skip`, `endpoint`, `status` | Dictionary with `specs`, `total`, `hasMore` | | `find_specs(query, ...)` | Required regex `query`; same filters | Dictionary with `specs`, `total`, `hasMore` | | `get_credits_balance()` | None | `CreditsBalanceResponse` object | `*_async` submits server-side work and returns its ID; these are ordinary blocking Python functions, not coroutines. Do not `await` them. Calls to generate specs use a 300-second HTTP timeout; status/list/search calls use 60 seconds. A polling deadline is separate from an individual HTTP timeout. ## History and credits ```python theme={null} page = client.find_specs(query="report|export", status="completed", limit=20) for summary in page["specs"]: print(summary["_id"], summary.get("input")) balance = client.get_credits_balance() print(balance.creditsRemaining) ``` List and search return summaries. Fetch the ID with `get_spec_status` for full Markdown, JSON, and graphs. See [inputs and outputs](/architect-agent/inputs-and-outputs). ## File uploads The SDK accepts a file path or binary file object via `file`. In 1.1.0, it does not set an explicit file-part MIME type or JSON-encode multipart `doc_urls`. Use direct HTTP when uploading reference documents, especially when supplying documentation URLs: ```python theme={null} import json import requests with open("requirements.pdf", "rb") as document: response = requests.post( "https://api.pre.dev/fast-spec", headers={"Authorization": "Bearer " + os.environ["PREDEV_API_KEY"]}, data={ "input": "Create an implementation plan from these requirements.", "docURLs": json.dumps(["https://www.postgresql.org/docs/current/"]), "async": "true", }, files={"file": ("requirements.pdf", document, "application/pdf")}, timeout=60, ) response.raise_for_status() job = response.json() print(job["specId"]) ``` See [accepted formats and limits](/architect-agent/inputs-and-outputs#upload-a-file). ## Errors ```python theme={null} from predev_api import AuthenticationError, RateLimitError, PredevAPIError try: page = client.list_specs(limit=20) except AuthenticationError: print("Check the API key and account access at pre.dev/projects/key.") except RateLimitError: print("Back off before retrying.") except PredevAPIError as error: print(str(error)) ``` The base exception has no `status_code` attribute. Browser gate errors have additional typed subclasses; see [errors and retries](/api-reference/errors). An Architect `402` without a machine-readable browser gate code raises `PredevAPIError`. Continue with the [Browser Agents Python guide](/browser-agents/sdks/python), [PyPI package](https://pypi.org/project/predev-api/), or [SDK source](https://github.com/predotdev/predev-api). # Get service capacity Source: https://docs.pre.dev/browser-agents/api/capacity api-reference/openapi.json GET /browser-agent-capacity Read advisory service queue statistics; use account queue status to size your own submissions. ```bash theme={null} curl --fail-with-body https://api.pre.dev/browser-agent-capacity \ -H "Authorization: Bearer $PREDEV_API_KEY" ``` This endpoint returns service-level queue and execution statistics. Fields include `totalActive`, `maxSandboxes`, `pending`, `claimed`, `running`, `failed`, `utilization` (percentage), and `oldestQueuedAgeMs`. The response is an advisory operational snapshot, not an admission guarantee or a forecast. Additional diagnostic fields may be returned. **Use [`GET /browser-agent-status`](/browser-agents/api/queue-status) and its `cap` field for your account's current limit**; the service snapshot's `perUserCap` is a legacy field. There is no dedicated method in the current SDKs or product MCP tools; call the endpoint with direct HTTP when needed. # List browser runs Source: https://docs.pre.dev/browser-agents/api/list-tasks api-reference/openapi.json GET /list-browser-agents Browse your browser task history with filters and offset pagination. ```bash theme={null} curl --fail-with-body 'https://api.pre.dev/list-browser-agents?limit=20&skip=0' \ -H "Authorization: Bearer $PREDEV_API_KEY" ``` The response contains `batches`, `total`, and `hasMore`. Entries are sorted newest first. Increase `skip` by your page size while `hasMore` is true. `limit` defaults to 20 and is clamped to 1–100. Use a nonnegative `skip`. The `status` filter accepts `processing` or `completed`; omit it to include all stored statuses, including failed runs. ## Summary rows Rows include the run `id`, task count `total`, finished-task `completed` count, `status`, `totalCreditsUsed`, and available names and timestamps. Their `results` arrays can contain null slots. The first slot may be a partial task stub to identify the run before results arrive. Fetch [run status](/browser-agents/api/task-status) for full task details and timelines. List summaries and detailed run snapshots have different behavior for the `completed` count; use `status` to decide whether a run is terminal. Node: `client.listBrowserAgents({ limit: 20, skip: 0 })`. Python: `client.list_browser_agents(limit=20, skip=0)` returns a dictionary. # Watch the live browser Source: https://docs.pre.dev/browser-agents/api/live-browser api-reference/openapi.json GET /browser-agent/{id}/ws Get an authenticated WebSocket URL for available browser frames in a run you own. Request the live-view URL using your API key and an existing run ID: ```bash theme={null} curl --fail-with-body "https://api.pre.dev/browser-agent/$BATCH_ID/ws" \ -H "Authorization: Bearer $PREDEV_API_KEY" ``` The response is `{ "url": "wss://…" }`. Connect to that URL exactly as returned; it includes the authorization needed for the live view. Treat it as a credential-bearing URL and keep it out of public logs. ## Frames Where live capture is available, JSON messages with `type: "frame"` contain: | Field | Meaning | | ----------- | ------------------------------------------- | | `taskIndex` | Zero-based index within the run | | `b64` | Base64-encoded JPEG image | | `w`, `h` | Capture metadata dimensions, when available | | `ts` | Unix timestamp in milliseconds | Filter for `type: "frame"` before reading those fields. For a preview image, use `data:image/jpeg;base64,` followed by `b64` as the image source. Frames are a live visual feed, not a durable recording, task-control channel, or completion signal. Some execution paths do not produce live frames. Use [SSE or polling](/browser-agents/api/stream-task) for authoritative task state and `includeEvents=true` for available screenshot history. `404` can mean the run is inaccessible or live streaming is unavailable. A returned URL does not guarantee that a frame will arrive. Current SDKs and MCP tools do not have a wrapper for this endpoint. # Get your queue status Source: https://docs.pre.dev/browser-agents/api/queue-status api-reference/openapi.json GET /browser-agent-status Inspect pending and running tasks and the in-flight ceiling for your account. ```bash theme={null} curl --fail-with-body https://api.pre.dev/browser-agent-status \ -H "Authorization: Bearer $PREDEV_API_KEY" ``` | Field | Meaning | | --------- | ---------------------------------------------------------- | | `pending` | Tasks waiting to start | | `claimed` | Tasks assigned for execution | | `running` | Tasks running | | `total` | Pending + claimed + running tasks counted by this snapshot | | `cap` | Your account's current in-flight ceiling | | `userId` | Authenticated caller identifier | ## Size a submission A request's task count must fit your available in-flight capacity as well as the service's batch-size limit. Lowering `concurrency` does not reduce how many submitted tasks count against the cap. For example, a snapshot with `cap: 25` and `total: 20` suggests room for five tasks. Submit a small batch, then wait for capacity to free before sending the next one. Treat the snapshot as advisory: it is not a reservation, and the submission gate can still return `QUEUE_FULL`. The cap depends on the plan and service configuration. Read `cap` rather than hard-coding a number or assuming the 1,000-task request ceiling is your account limit. Node: `client.browserAgentStatus()`. Python: `client.browser_agent_status()` returns a dictionary. [Service capacity](/browser-agents/api/capacity) is a separate endpoint and does not replace your account's cap. # Run browser tasks Source: https://docs.pre.dev/browser-agents/api/run-task api-reference/openapi.json POST /browser-agent Submit a task array and receive JSON, an async run ID, or a live SSE stream. Always pass a `tasks` array, including for a single task. Each request creates one run, called a batch in response types. [Authentication](/api-reference/authentication) uses `Authorization: Bearer $PREDEV_API_KEY` or `x-api-key`. ## Task controls Every task needs a full HTTP(S) `url` and either a nonblank `instruction` or a non-empty `output` JSON Schema object. String-valued `input` is optional and does not replace instructions. Choose `mode: "extract"` for schema-oriented reads or `mode: "agent"` for goal-driven navigation; `auto` lets the service choose. `maxSteps` and `maxDurationSeconds` set per-task budgets. For compatibility with MCP, use `1`–`50` steps and `5`–`600` seconds. REST also accepts the older `maxIterations` and `timeoutMs` names; those take precedence if both forms are sent. Do not send both forms in new code. Defaults vary with the task and execution path, so set an explicit budget when your workflow depends on one. ```json theme={null} { "tasks": [{ "url": "https://example.com", "instruction": "Extract the main page heading.", "output": { "type": "object", "properties": { "heading": { "type": "string" } }, "required": ["heading"] }, "mode": "extract", "maxSteps": 10, "maxDurationSeconds": 120 }], "concurrency": 5, "async": true } ``` When `output` is omitted, schema inference may be attempted. Supply your own schema for a predictable contract; a successful task does not always have `data`. ## Input validation The service validates the entire batch before charging credits, creating a run, or queueing browser work. Malformed URLs, missing instructions without an output schema, and domains with no DNS address return an actionable error with a `code`, a zero-based `taskIndex`, and a `field` when applicable. DNS verification has a five-second request budget. Temporary DNS failures return `503` with `URL_CHECK_UNAVAILABLE`; retry the submission later. No tasks are started when verification fails. This check verifies the hostname, not page availability: authenticated pages and bot-protected sites remain eligible for browser execution. The dashboard applies the same task and URL format checks before enabling Run. CSV instructions are checked after row-variable interpolation. Output-schema-only extraction remains supported through the API and MCP. ## Synchronous With neither `async` nor `stream` enabled, the connection waits for a `BatchResult`. Use this for short tasks. The [quickstart](/browser-agents/quickstart) contains complete curl and SDK examples. ## Async With `async: true`, HTTP `200` returns an initial result such as: ```json theme={null} { "id": "507f1f77bcf86cd799439011", "total": 1, "completed": 0, "results": [], "totalCreditsUsed": 0, "status": "processing" } ``` Save **`id`**, then [poll the run](/browser-agents/api/task-status) or [attach an SSE stream](/browser-agents/api/stream-task). `totalCreditsUsed: 0` on this initial response does not mean no credit floor was charged at submission. ## Streaming With `stream: true`, the response is `text/event-stream`. If both `stream` and `async` are true, **streaming takes precedence**; the server does not reject that combination. Send only your intended mode for clarity. ```bash theme={null} curl --fail-with-body -N https://api.pre.dev/browser-agent \ -H "Authorization: Bearer $PREDEV_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "tasks": [{"url":"https://example.com","instruction":"Read the main heading."}], "stream": true }' ``` | SSE event | `data` payload | | ------------- | -------------------------------------------------- | | `task_event` | `{ taskIndex, type, timestamp, iteration?, data }` | | `task_result` | `{ taskIndex, ...taskResult }` | | `done` | Full `BatchResult` | | `error` | `{ error, code?, actionUrl?, taskIndex?, field? }` | Lines beginning with `:` are keepalive comments. The task index is zero-based. Individual task `done` events inside `task_event` do not finish the batch; wait for the outer SSE `done` event and inspect all task statuses. A submission stream does not provide the initial `snapshot` event or reliably expose a run ID before completion. Use async submission followed by an [existing-run stream](/browser-agents/api/stream-task) when you need a saved ID for recovery. Disconnecting does not cancel the work. ## Billing and limits * The default request ceiling is **1,000 tasks**. Your account's in-flight cap can be much smaller and counts every submitted task, including queued work. * `concurrency` defaults to **5** and is clamped to **1–20**. It controls parallelism within the run; it does not let you exceed your account limit. * Submission checks the credit floor of **0.1 credits per task**. Successful tasks settle at at least that floor, with usage increasing for more complex work. Failed tasks settle at zero and their prepaid floor is refunded. * Browser billing uses **\$0.10 per credit**. Treat the returned `creditsUsed` and `totalCreditsUsed` as the recorded task charges, not a forecast or a reserved amount. * Free accounts have a limited browser trial budget in addition to the account credit balance. An exhausted trial returns `SUBSCRIPTION_REQUIRED`. Use [queue status](/browser-agents/api/queue-status) to size batches and [errors](/api-reference/errors) to handle `QUEUE_FULL`, `RATE_LIMITED`, and billing responses. Capacity snapshots are advisory; another submission can consume capacity before yours arrives. ## Idempotency Send an `Idempotency-Key` header, or `idempotencyKey` in the JSON body, to recover an existing run from the last **24 hours**. The header takes precedence. Use a unique key per logical submission and keep the payload stable across retries. A matching existing run returns HTTP `200` as **JSON**, including when `stream: true` was requested. Check the response content type. The current SDK methods and MCP tool do not expose this option; use direct REST when needed. See [retry semantics](/api-reference/errors#retry-submissions). ## Response schemas The generated schema below describes the run and task fields. [Get run status](/browser-agents/api/task-status) explains pending entries, task outcomes, retry counts, and timelines. The `completed` count alone is not a reliable completion signal; use batch `status`. # Stream an existing run Source: https://docs.pre.dev/browser-agents/api/stream-task api-reference/openapi.json GET /browser-agent/{id}/stream Attach to an existing browser run with an initial snapshot, live SSE updates, and terminal status. Submit with `async: true`, save the run ID, then attach to this endpoint. This lets your application recover results even if the stream disconnects. ```bash theme={null} curl --fail-with-body -N "https://api.pre.dev/browser-agent/$BATCH_ID/stream" \ -H "Authorization: Bearer $PREDEV_API_KEY" ``` ## Event contract | Event | Payload | When | | ------------- | --------------------------------------------------- | ---------------------------------- | | `snapshot` | Full run result with available timelines | On connection | | `batch_meta` | `{ name, taskNames }` | Display names become available | | `task_event` | `{ taskIndex, type, timestamp, iteration?, data }` | A task emits an event | | `task_result` | `{ taskIndex, ...taskResult }` | A task finishes | | `done` | `{ status: "completed" }` or `{ status: "failed" }` | The batch reaches a terminal state | | `error` | `{ error }` | The stream cannot continue | The existing-run stream's **`done` contains status only**. Fetch [the run](/browser-agents/api/task-status) after `done` for final data and credit usage. This differs from the [submission stream](/browser-agents/api/run-task#streaming), whose `done` contains the full batch. ## Reconnect and recover An already-terminal run emits `snapshot`, then `done`, then closes. Keepalive lines start with `:` and are not JSON events. Closing the stream does not cancel the run. The stream has no event-ID replay contract. After a disconnect, fetch a fresh result or reconnect for a new snapshot; do not assume that every transient event will be replayed. Treat EOF without `done` as an interrupted stream and check status. The API also accepts `apiKey` as a query parameter for EventSource clients. Prefer header authentication with a streaming HTTP client to keep API keys out of URLs. ## Errors Before streaming begins, invalid IDs return `400`, authentication failures `401`, inaccessible runs `404`, and stream capacity limits `503`. For `503`, poll [run status](/browser-agents/api/task-status). Once headers are sent, handle SSE `error` frames as failures even with HTTP `200`. The SDKs stream **submission** responses; use direct HTTP for this existing-run endpoint. # Get run status and results Source: https://docs.pre.dev/browser-agents/api/task-status api-reference/openapi.json GET /browser-agent/{id} Retrieve a browser run, individual task outcomes, retry counts, and optional execution timelines. Use the `id` returned by [task submission](/browser-agents/api/run-task). A run is also called a batch in the API and SDK types. ```bash theme={null} curl --fail-with-body "https://api.pre.dev/browser-agent/$BATCH_ID" \ -H "Authorization: Bearer $PREDEV_API_KEY" ``` ## Batch and task states Batch `status` is `processing`, `completed`, or `failed`. Stop polling on either terminal state. A completed batch may contain unsuccessful tasks. | Task status | Meaning | | ---------------- | --------------------------------------------------- | | `PENDING` | Waiting to run | | `RUNNING` | Execution has started | | `SUCCESS` | The task succeeded | | `BLOCKED` | The site blocked the task | | `CAPTCHA_FAILED` | A challenge could not be completed | | `TIMEOUT` | The execution budget expired | | `LOOP` | Repeated actions prevented progress | | `NO_TARGET` | The requested target or usable result was not found | | `ERROR` | Another execution failure; read `error` | ## In-progress results `results` is aligned to task order. An entry can be a terminal result, a `PENDING`/`RUNNING` stub, or null when task details are unavailable. Pending entries need not include `data`, `durationMs`, or `creditsUsed`. The detail response counts result slots in `completed`, including synthesized entries. **Use `status`, not `completed === total` or array length, to decide whether the run is finished.** Additional fields can include: | Field | Meaning | | ------------------------------------------- | --------------------------------------------------------------------------------- | | `name` / `taskNames` | Generated display names, when available | | `results[i].attempts` | Execution attempts; greater than one indicates a retry | | `results[i].queuePosition` | Advisory position for pending work; zero for running work, or null if unavailable | | `results[i].instruction`, `input`, `output` | Original task inputs when available | | `totalCreditsUsed` | Sum of reported task credit usage | Inspect task `status` before using `data`. Treat display names, queue position, and timestamps as optional. ## Event timeline Set `includeEvents=true` when you need execution evidence: ```bash theme={null} curl --fail-with-body "https://api.pre.dev/browser-agent/$BATCH_ID?includeEvents=true" \ -H "Authorization: Bearer $PREDEV_API_KEY" ``` `results[i].events` contains available task events. `liveEvents[i]` can contain events for unfinished tasks; completed slots can be empty arrays. These fields can remain present after batch completion. An event uses `{ type, timestamp, iteration?, data }`, where `timestamp` is Unix time in milliseconds. Types include `navigation`, `plan`, `action`, `screenshot`, `validation`, `done`, `error`, and lifecycle events. Accept unfamiliar event types and inspect their payloads instead of assuming a closed list. Screenshot payloads can contain inline image data rather than a URL. Events vary by execution path and are not guaranteed for every step. Timelines can be large, so omit them from routine status checks. The [existing-run stream](/browser-agents/api/stream-task) provides a snapshot followed by live updates. A malformed ID returns `400`. An unknown or inaccessible run returns `404`. # Browser tasks with MCP Source: https://docs.pre.dev/browser-agents/mcp-tool Run browser tasks from your assistant, then retrieve structured results and execution evidence. Connect the [pre.dev MCP server](/architect-agent/mcp-setup) once. It provides `browser_agent`, `browser_agent_get`, and `browser_agent_list` alongside the specification tools. ## Extract structured data Call `browser_agent` with these arguments: ```json theme={null} { "tasks": [{ "url": "https://example.com", "instruction": "Extract the main page heading.", "output": { "type": "object", "properties": { "heading": { "type": "string" } }, "required": ["heading"] }, "mode": "extract", "maxSteps": 10, "maxDurationSeconds": 120 }] } ``` The tool returns a text summary and run ID. Call `browser_agent_get` with that ID to get the complete `structuredContent`, including `results[i].data`. ## Run a longer workflow For a multi-step workflow, use `mode: "agent"`, give a concrete completion condition, and submit asynchronously: ```json theme={null} { "tasks": [{ "url": "https://news.ycombinator.com/newest", "instruction": "Open the next page using More, then collect the first five story titles and links.", "successCondition": "The next page has been opened and five stories from that page have been collected.", "output": { "type": "object", "properties": { "stories": { "type": "array", "items": { "type": "object", "properties": { "title": { "type": "string" }, "url": { "type": "string" } }, "required": ["title", "url"] }, "minItems": 5, "maxItems": 5 } }, "required": ["stories"] }, "mode": "agent", "maxSteps": 20, "maxDurationSeconds": 180 }], "async": true } ``` Save the ID from the returned text, then call `browser_agent_get` every few seconds. Stop when batch `status` becomes `completed` or `failed`, and inspect each task's uppercase status. A completed batch does not mean every task succeeded. ## Inspect evidence ```json theme={null} { "id": "507f1f77bcf86cd799439011", "includeEvents": true } ``` This returns task timelines and any available screenshots. During synchronous execution, clients with logging support can also receive `notifications/message`. These are MCP notification envelopes, not REST SSE frames; heavy event data may be shortened. ## History and limits Use `browser_agent_list` with `limit`, `skip`, and optionally `status: "processing"` or `"completed"`. Its structured response has `total` and `batches`; use `browser_agent_get` for each run's full data. The same credit, batch-size, and account in-flight gates apply as in REST. `concurrency` allows `1`–`20` tasks within a run, default `5`. Retrieve [queue status](/browser-agents/api/queue-status) through REST when you need the current account limit. The MCP tool does not expose REST's idempotency header or a cancellation operation. Closing the client does not establish that browser work stopped. See the [complete tool reference](/mcp/tools) for every field and the older `browser_task` aliases. # Migrate a browser workflow Source: https://docs.pre.dev/browser-agents/migrate-from-browser-use Translate a locally managed browser workflow into pre.dev tasks and results. To move a browser-use workflow to pre.dev, express the browser objective as a task, submit it to the hosted service, and handle the returned task outcome. The request and lifecycle differ from a locally managed agent, so plan the migration around behavior and result contracts. ## Map the concepts | Existing workflow | pre.dev equivalent | | ------------------------------------------- | --------------------------------------------------------------- | | Launch a browser and choose a starting page | Set the task's `url` | | Describe the agent's goal | Set `instruction` and optional `successCondition` | | Parse output into a model | Supply an `output` JSON Schema | | Run several independent jobs | Put tasks in one array and request `concurrency` | | Limit steps or wall time | Set `maxSteps` and `maxDurationSeconds` per task | | Track a long-running job | Submit `async: true`, persist the ID, and poll or attach to SSE | | Inspect the browser | Request available events, screenshots, or the live browser URL | ## Submit a first task ```bash theme={null} curl --fail-with-body https://api.pre.dev/browser-agent \ -H "Authorization: Bearer $PREDEV_API_KEY" \ -H 'Content-Type: application/json' \ -d '{ "tasks": [{ "url": "https://example.com", "instruction": "Read the page title", "mode": "extract", "maxSteps": 5, "maxDurationSeconds": 30, "output": { "type": "object", "properties": {"title": {"type": "string"}}, "required": ["title"] } }], "async": true }' ``` Set `PREDEV_API_KEY` in your environment first. Save the returned `id`, then [retrieve the run](/browser-agents/api/task-status). Wait for terminal batch status and inspect every task's `status`; a completed batch can contain failed tasks. ## Check assumptions before migrating The public request schema does not provide a persistent browser-profile or cookie-jar management API. Plan authentication inside the supported task workflow rather than assuming your local browser session transfers to the service. Use an explicit output schema where your application depends on a stable result shape. Pending results can be null or partial. Report blocked, timed-out, and failed tasks as such instead of treating missing data as successful extraction. For retry behavior, use the [REST idempotency option](/browser-agents/api/run-task). SDK 1.1.0 does not expose every newer request control in its typed interfaces; the [SDK guide](/browser-agents/sdks/overview) identifies when direct REST is needed. ## Validate the migration Run a representative authorized task and compare the required behavior and data with your existing workflow. Then add bounded polling, error handling, and concurrency appropriate to your account. Published benchmarks describe their own datasets and dates; measure your workload before relying on a cost or speed estimate. # Browser Agents Source: https://docs.pre.dev/browser-agents/overview Run browser workflows and extract structured data through REST, SDKs, or MCP. Give Browser Agents a starting URL and a task. It navigates pages, interacts with forms and controls, and returns task outcomes with data and an optional execution timeline. Extract a page heading with curl, Python, or TypeScript. Give your assistant browser automation and structured results. ## Choose how the task runs | Mode | Use it for | Supply | | --------- | ------------------------------------------------------ | ---------------------------------------------------------------------- | | `extract` | Read page content into a known shape | An `output` JSON Schema, optionally an instruction | | `agent` | Navigate, search, fill forms, or perform several steps | A clear instruction and success condition; optionally an output schema | | `auto` | Let the service choose the execution path | A URL and your goal or schema | Provide an explicit `output` when downstream code expects a particular structure. If it is omitted, the service may infer an output schema; do not assume a specific data shape or that every task returns text. ## Request lifecycle One request creates one **run**, also called a **batch** in response types. A run contains one or more tasks. Use its `id` to retrieve progress and results; each task has its own status and credit usage. The [status guide](/browser-agents/api/task-status#batch-and-task-states) includes an interactive example of queued, running, completed, and failed work. ## Choose how to receive results | Interface | Behavior | | ----------------------------------------------------------- | -------------------------------------------------- | | [Synchronous request](/browser-agents/api/run-task) | Wait for the run and return JSON | | [Async request](/browser-agents/api/run-task#async) | Return the run ID, then poll or attach a stream | | [Submission stream](/browser-agents/api/run-task#streaming) | Live SSE events and a full final result | | [Existing-run stream](/browser-agents/api/stream-task) | Initial snapshot, live events, and terminal status | | [Live browser](/browser-agents/api/live-browser) | View available browser frames over WebSocket | Task counts, account in-flight limits, and per-run concurrency are different controls. Check [queue status](/browser-agents/api/queue-status) when submitting larger workloads. ## Credits Successful tasks have a **0.1-credit minimum**; more complex tasks can cost more. Failed tasks settle at zero credits. Submission reserves or charges the task floor before execution, so you need available credits to start. Read [billing and limits](/browser-agents/api/run-task#billing-and-limits) for details. ## Benchmark Explore the [interactive benchmark report](https://pre.dev/browser-agents-benchmark.html) for task results, costs, timings, and execution traces. The [reproduction repository](https://github.com/predotdev/browser-agents-benchmark) includes task definitions and scoring rules. Browser tasks do not expose persistent login profiles, reusable cookie sessions, or a recurring-schedule API. Schedule submissions in your own application and provide the inputs each task needs. # Browser Agents quickstart Source: https://docs.pre.dev/browser-agents/quickstart Extract a page heading, inspect the result, and choose a response mode. Extract the main heading from a page and read it as structured data. This example uses `https://example.com` and an output schema with one required field: `heading`. ## Before you start Get a key from [pre.dev/projects/key](https://pre.dev/projects/key) and store it as `PREDEV_API_KEY`. You need available credits to submit a task; see [authentication and account access](/api-reference/authentication). ## Run the task Choose curl, Node.js, or Python. The default request waits for the result. ```bash curl theme={null} curl --fail-with-body 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 main page heading.", "output": { "type": "object", "properties": { "heading": { "type": "string" } }, "required": ["heading"] } }] }' ``` ```typescript Node.js theme={null} // npm install predev-api import { PredevAPI } from 'predev-api'; const client = new PredevAPI({ apiKey: process.env.PREDEV_API_KEY! }); const run = await client.browserAgent([{ url: 'https://example.com', instruction: 'Extract the main page heading.', output: { type: 'object', properties: { heading: { type: 'string' } }, required: ['heading'], }, }]); const task = run.results[0]; if (!task || task.status !== 'SUCCESS') { throw new Error(task?.error ?? 'The task did not succeed'); } console.log(task.data); ``` ```python Python theme={null} # pip install predev-api import os from predev_api import PredevAPI client = PredevAPI(api_key=os.environ["PREDEV_API_KEY"]) run = client.browser_agent([{ "url": "https://example.com", "instruction": "Extract the main page heading.", "output": { "type": "object", "properties": {"heading": {"type": "string"}}, "required": ["heading"], }, }]) task = run["results"][0] if not task or task["status"] != "SUCCESS": raise RuntimeError((task or {}).get("error", "The task did not succeed")) print(task["data"]) ``` ## Read the response A successful task has `status: "SUCCESS"` and, for this example, data shaped like `{ "heading": "Example Domain" }`. The run also has an `id`, lowercase batch `status`, `results`, and `totalCreditsUsed`. An illustrative response excerpt: ```json theme={null} { "id": "507f1f77bcf86cd799439011", "status": "completed", "results": [ { "status": "SUCCESS", "data": { "heading": "Example Domain" } } ] } ``` A batch marked `completed` can contain failed tasks. Check `results[0].status` before reading `results[0].data`; the SDK examples above include this check. Explore the [run and task states](/browser-agents/api/task-status#batch-and-task-states) for failure cases. ## Use async for longer work Add `"async": true` to the REST request body, `{ async: true }` to Node options, or `run_async=True` to the Python call. Set `BATCH_ID` to the actual `id` returned by your request, then poll: ```bash theme={null} curl --fail-with-body "https://api.pre.dev/browser-agent/$BATCH_ID" \ -H "Authorization: Bearer $PREDEV_API_KEY" ``` Stop when batch `status` becomes `completed` or `failed`. You can also [watch an existing run with SSE](/browser-agents/api/stream-task) or submit with `stream: true` for a [submission stream](/browser-agents/api/run-task#streaming). ## Use MCP Follow [MCP setup](/architect-agent/mcp-setup), then ask your assistant: ```text theme={null} Use pre.dev browser_agent to extract the main heading from https://example.com into an object with a heading string. Retrieve the full result using browser_agent_get. ``` ## Make it your own Replace the URL and instruction, then describe the data your application needs in `output`. For a workflow with several actions, make the desired end state explicit. Continue with [task modes and limits](/browser-agents/api/run-task), [streaming results](/browser-agents/api/stream-task), or [safe retries](/api-reference/errors#retry-submissions). # Node.js browser SDK Source: https://docs.pre.dev/browser-agents/sdks/node Submit browser tasks, poll results, and consume a live submission stream with TypeScript. ```bash theme={null} npm install predev-api ``` This guide targets published **1.1.0**. See [SDK setup](/architect-agent/sdks/node) for configuration and general errors. ## Submit and poll ```typescript theme={null} import { PredevAPI } from 'predev-api'; const client = new PredevAPI({ apiKey: process.env.PREDEV_API_KEY! }); const tasks = [{ url: 'https://example.com', instruction: 'Extract the main page heading.', output: { type: 'object', properties: { heading: { type: 'string' } }, required: ['heading'], }, }]; const job = await client.browserAgent(tasks, { async: true }); console.log('Save this ID:', job.id); const deadline = Date.now() + 600_000; async function waitForRun() { while (Date.now() < deadline) { const run = await client.getBrowserAgent(job.id); if (run.status === 'completed' || run.status === 'failed') return run; await new Promise(resolve => setTimeout(resolve, 5_000)); } throw new Error('Polling deadline reached; retrieve the saved run later.'); } const run = await waitForRun(); for (const task of run.results) { if (task?.status === 'SUCCESS') console.log(task.data); else console.error(task?.error ?? 'No successful result'); } ``` Use batch `status` to detect completion and inspect every task result. The current TypeScript declarations lag some REST fields, including running stubs and nullable result slots; guard missing values at runtime. ## Method options | Method | Options | | ------------------------------ | -------------------------------- | | `browserAgent(tasks, options)` | `concurrency`, `stream`, `async` | | `getBrowserAgent(id, options)` | `includeEvents` | | `listBrowserAgents(params)` | `limit`, `skip`, `status` | | `browserAgentStatus()` | None | There is no client-wide timeout, retry, or arbitrary-header configuration. Published task types do not declare `mode`, `maxSteps`, or `maxDurationSeconds`; use [direct REST](/browser-agents/api/run-task) when your integration needs those controls without extending the package's types. ## Stream a new submission Reuse `client` and `tasks` from the example above: ```typescript theme={null} let sawDone = false; for await (const message of client.browserAgent(tasks, { stream: true })) { if (message.event === 'task_event') { console.log(message.data.taskIndex, message.data.type); } else if (message.event === 'done') { sawDone = true; console.log(message.data.status, message.data.totalCreditsUsed); } } if (!sawDone) throw new Error('The stream ended before a final result arrived.'); ``` `stream: true` returns an async generator; synchronous and async-submission modes return a Promise. The stream example creates a **new run**. Streamed `error` frames raise exceptions. To attach to an existing run, use [direct HTTP SSE](/browser-agents/api/stream-task). ## History and evidence ```typescript theme={null} const queue = await client.browserAgentStatus(); console.log(queue.total, queue.cap); const page = await client.listBrowserAgents({ limit: 20, status: 'completed' }); for (const summary of page.batches) console.log(summary.id, summary.totalCreditsUsed); const evidence = await client.getBrowserAgent(job.id, { includeEvents: true }); ``` Timelines can be large; omit `includeEvents` for routine polling. See [status and results](/browser-agents/api/task-status) for event shapes and per-task fields. ## Billing and queue errors ```typescript theme={null} import { InsufficientCreditsError, QueueFullError, PredevAPIError } from 'predev-api'; try { await client.browserAgent(tasks, { async: true }); } catch (error) { if (error instanceof InsufficientCreditsError) { console.error(error.message, error.actionUrl); } else if (error instanceof QueueFullError) { console.error('Wait for tasks to finish before submitting more work.'); } else if (error instanceof PredevAPIError) { console.error(error.message); } else { throw error; } } ``` Use [direct REST](/browser-agents/api/run-task#idempotency) for an idempotency key; the SDK does not forward arbitrary options as headers or request fields. # Browser Agents SDKs Source: https://docs.pre.dev/browser-agents/sdks/overview Run, retrieve, list, and stream browser work with the official predev-api packages. Browser Agents uses the same **`predev-api`** packages as the Architect API. | Operation | Node | Python | | ----------------------- | ------------------------------------ | --------------------------------------------- | | Run tasks | `browserAgent(tasks, options)` | `browser_agent(tasks, ...)` | | Submit asynchronously | `{ async: true }` | `run_async=True` | | Stream a new submission | `{ stream: true }` → async generator | `stream=True` → iterator | | Retrieve a run | `getBrowserAgent(id, options)` | `get_browser_agent(id, include_events=False)` | | List runs | `listBrowserAgents(params)` | `list_browser_agents(...)` | | Read account queue | `browserAgentStatus()` | `browser_agent_status()` | Node returns objects and Python returns dictionaries. Both expose typed browser gate exceptions. The Python SDK is blocking even when submitting a server-side async job. Promises, async generators, and current TypeScript field coverage. Dictionary results, bounded polling, and streaming iterators. Use direct REST for `Idempotency-Key`, [existing-run SSE](/browser-agents/api/stream-task), [live browser URLs](/browser-agents/api/live-browser), or [service capacity](/browser-agents/api/capacity). Current SDK method signatures do not expose these operations or arbitrary headers. # Python browser SDK Source: https://docs.pre.dev/browser-agents/sdks/python Submit browser tasks, poll dictionary results, and consume a live submission stream. ```bash theme={null} pip install predev-api ``` This guide targets published **1.1.0**. See [SDK setup](/architect-agent/sdks/python) for configuration and general errors. ## Submit and poll ```python theme={null} import os import time from predev_api import PredevAPI client = PredevAPI(api_key=os.environ["PREDEV_API_KEY"]) tasks = [{ "url": "https://example.com", "instruction": "Extract the main page heading.", "output": { "type": "object", "properties": {"heading": {"type": "string"}}, "required": ["heading"], }, "mode": "extract", "maxSteps": 10, "maxDurationSeconds": 120, }] job = client.browser_agent(tasks, run_async=True) print("Save this ID:", job["id"]) deadline = time.monotonic() + 600 while time.monotonic() < deadline: run = client.get_browser_agent(job["id"]) if run["status"] in ("completed", "failed"): for task in run["results"]: if task and task.get("status") == "SUCCESS": print(task.get("data")) else: print("Task failed:", (task or {}).get("error", "No result")) break time.sleep(5) else: raise TimeoutError("Polling deadline reached; retrieve the saved run later.") ``` The SDK passes task dictionaries through to REST, including the current per-task controls. `run_async=True` submits asynchronous **server** work; the Python method itself blocks until the submission response arrives. ## Method options | Method | Options | | ---------------------------- | ------------------------------------------------ | | `browser_agent(tasks, ...)` | `concurrency`, `stream=False`, `run_async=False` | | `get_browser_agent(id, ...)` | `include_events=False` | | `list_browser_agents(...)` | `limit`, `skip`, `status` | | `browser_agent_status()` | None | Browser submission requests use a 300-second HTTP timeout, retrieval/list requests 60 seconds, and queue status 30 seconds. Use async submission for longer tasks. There is no exposed client-wide timeout or retry option. ## Stream a new submission Reuse `client` and `tasks` from the example above: ```python theme={null} saw_done = False for message in client.browser_agent(tasks, stream=True): if message["event"] == "task_event": print(message["data"]["taskIndex"], message["data"]["type"]) elif message["event"] == "done": saw_done = True run = message["data"] print(run["status"], run["totalCreditsUsed"]) if not saw_done: raise RuntimeError("The stream ended before a final result arrived.") ``` This call creates a **new run**. Streamed `error` frames raise SDK exceptions. A clean iterator exit without `done` still requires recovery; the SDK does not make EOF a terminal success. To attach to a saved async ID, use [existing-run SSE over direct HTTP](/browser-agents/api/stream-task). ## History and evidence ```python theme={null} queue = client.browser_agent_status() print(queue["total"], queue["cap"]) page = client.list_browser_agents(limit=20, status="completed") for summary in page["batches"]: print(summary["id"], summary["totalCreditsUsed"]) run = client.get_browser_agent(job["id"], include_events=True) ``` `include_events=True` adds available timelines and screenshots. Routine polling should omit it. [Status and results](/browser-agents/api/task-status) explains pending stubs, null slots, uppercase task statuses, and lowercase batch statuses. ## Billing and queue errors ```python theme={null} from predev_api import InsufficientCreditsError, QueueFullError, PredevAPIError try: job = client.browser_agent(tasks, run_async=True) except InsufficientCreditsError as error: print(str(error), error.action_url) except QueueFullError: print("Wait for tasks to finish before submitting more work.") except PredevAPIError as error: print(str(error)) ``` Use [direct REST](/browser-agents/api/run-task#idempotency) when a retry needs an idempotency key; the SDK has no idempotency or arbitrary-header option. # 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-09-07 ### Reject unusable browser tasks before starting work * The dashboard now keeps Run disabled until each task has a valid website URL and instructions or an output schema, with inline guidance and consistent URL normalization for drafts and CSV rows. * The backend checks task input and DNS before charging or queueing, so empty tasks and nonexistent domains do not consume sandbox time. Output-schema-only extraction remains supported. * Permanent task and URL failures no longer get another sandbox attempt. Failed runner outcomes display as failed in the run details. ## 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#billing-and-queue-errors). #### 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#billing-and-queue-errors). # CLI commands Source: https://docs.pre.dev/cli/commands Supported terminal commands, launch flags, and integration controls. Type `/` to open the command palette. Use the arrow keys to select, Enter to run, and Escape to dismiss. Commands with arguments keep the composer open for the rest of the request. ## Work and models | Command | Action | | ------------------- | ----------------------------------------------------------- | | `/auto` | Let the agent answer, build, or plan as needed | | `/plan` | Work on the plan; returns to Auto when the plan is produced | | `/sprint ` | Launch a dedicated sprint in another session | | `/fork ` | Start a task in an isolated session | | `/effort` | Choose auto, low, medium, or high sprint effort | | `/model` | Open model selection for all phases or individual phases | A message prefixed with `>>` also forks a task. Separate sessions use separate Git worktrees. Review their changes and integration result, particularly when tasks modify related files. ```text theme={null} /fork add tests for the invoice date formatter ``` ## Project and conversation | Command | Action | | ---------- | ------------------------------------------------------------- | | `/reverse` | Analyze an existing codebase and produce architecture context | | `/kanban` | Open the Kanban view | | `/roadmap` | Open the roadmap view | | `/arch` | Open the architecture view | | `/clear` | Clear the visible chat feed; preserve stored history | | `/help` | Show commands and keybindings | | `/login` | Sign in or switch accounts through the browser | Escape returns from project views to chat. Views require the corresponding project data. ## Integrations and billing | Command | Action | | --------------- | ------------------------------------------------------------ | | `/integrations` | View personal workspace connections, MCP servers, and skills | | `/skills` | View, toggle, or remove personal skill entries | | `/mcp` | View, toggle, or remove personal MCP entries | | `/balance` | Show remaining credits | | `/topup` | Open credit purchasing in the browser | | `/upgrade` | Open plan selection in the browser | In the Skills and MCP panels, use Enter to toggle, `d` to remove, and `o` to open the web app to add or configure entries. Connecting OAuth accounts also happens in the web app. These CLI panels show personal entries. Use [Project setup](/coding-agent/integrations/overview) on the web for project-scoped entries, team connections, and provider account selection. `/pro` is retired. `/init` and `/share` may appear in the shared command metadata, but the current CLI does not implement their handlers. Use the web Share menu for collaboration. ## Launch flags | Invocation | Effect | | --------------------------------- | ----------------------------------------- | | `predev ""` | Start with an opening prompt | | `predev --new` or `predev -n` | Create a fresh project for this directory | | `predev --version` or `predev -v` | Print the installed version and exit | | `predev --help` or `predev -h` | Print launch help and exit | # Work on an existing repo Source: https://docs.pre.dev/cli/existing-repos Map a local codebase and make changes you can review with Git. ```bash theme={null} cd my-existing-app predev ``` The current directory is the workspace. The CLI associates it with a pre.dev project and resumes that association on later launches. `--new` creates a fresh association. Accept the existing-codebase analysis prompt when offered, or run `/reverse`. Inspect the result with `/arch`. Rerun analysis after major structural changes when the stored architecture needs refreshing. ```text theme={null} Fix invoice date formatting for non-US locales. Preserve the existing timezone handling and add a regression test. ``` Use `/plan` if you want to develop the approach first. For separate workstreams, use `/sprint` or `/fork` with a clear task description. ```bash theme={null} git status git diff ``` Read the reported tests, review changes in the active checkout or session worktree, and resolve any conflicts before committing or merging. Request the commit, PR, or review behavior you want explicitly in the task. Project planning artifacts are also available in the web workspace. Local and hosted code still follow your repository's synchronization workflow. For a hosted checkout, use [GitHub import](/coding-agent/projects/importing-repos). # pre.dev CLI Source: https://docs.pre.dev/cli/overview Use the coding agent in a local project directory. The `predev` CLI reads and edits files in your working directory. It connects that directory to a pre.dev project for conversation history and planning artifacts. ## Install and launch The installer supports macOS and Linux on ARM64 and x64. It requires `curl` and Python 3. ```bash theme={null} curl -fsSL https://pre.dev/install | bash ``` It installs under `~/.predev`, adds `predev` to your shell path, and launches the CLI in an interactive terminal. For installation without launching: ```bash theme={null} curl -fsSL https://pre.dev/install | PREDEV_NO_AUTORUN=1 bash ``` Then run it from your repository: ```bash theme={null} cd my-project predev ``` If your shell has not picked up the PATH change, open a new terminal or run `~/.predev/bin/predev`. ## First run Sign in through the browser when prompted, then return to the terminal. The CLI stores its credential in `~/.predev/auth.json`; `/login` signs in again or switches accounts. The CLI resolves a project for the directory and resumes it on subsequent launches. Use `predev --new` to create a fresh project association. An existing codebase can be mapped with `/reverse` before you request changes. ```bash theme={null} predev "add an empty state to the reports page" predev --version predev --help ``` ## Work in the terminal Auto mode is the default. Use `/plan` for planning, `/sprint ` for a dedicated sprint, and `/fork ` for a separate session. `/kanban`, `/roadmap`, and `/arch` open project views in the terminal. Review file changes with `git status` and `git diff`. Shared project records do not automatically synchronize all local files with a hosted checkout; use the normal Git workflow for the repository. The launcher checks for updates in the background and verifies downloaded releases. A background update can take effect on a later launch; `predev --version` reports the installed version in use. Commands, launch flags, and integration controls. Map the architecture and review local changes. # Verification Source: https://docs.pre.dev/coding-agent/building/acceptance-criteria Define acceptance criteria and inspect the checks, browser flows, and evidence behind a change. Acceptance criteria describe observable behavior that should hold when the work is complete. Include them in the task or specification so implementation and review use the same definition of success. ```text theme={null} A team member can export only the invoices they can access. The CSV preserves currency and timezone information. An empty result shows a useful message. A failed request leaves the export button usable for retry. ``` ## Verification workflow High-effort sprints include a separate acceptance phase. Direct chat and lower-effort work use different execution paths, so inspect the checks that actually ran for the task. ## Evidence to inspect | Check | Useful evidence | | -------------- | ----------------------------------------------------------- | | Types and lint | Actual commands, exit results, and relevant failures | | Tests | Which behavior and regression cases were exercised | | Browser flows | The user action and its observed result in the same flow | | Screenshots | Captured state, viewport, and the feature being reviewed | | Design review | Specific layout, accessibility, or component-state findings | Browser tools can navigate, interact, assert outcomes, and capture screenshots. A screenshot establishes visible state; a passing interaction assertion establishes more about behavior. Both can be useful in review. ## Make the checks reproducible Provide the project's setup commands, test accounts or role requirements, and any services needed to run the application. Ask the agent to identify skipped checks and blockers such as missing configuration or an unavailable preview. For permissions-sensitive features, verify both allowed and denied cases. For UI changes, include the relevant screen sizes and interaction states. Review test data and external side effects as part of the task scope. ## Before shipping Read the diff and the final verification report. A completed run or an opened PR alone is not evidence that every possible behavior was tested. Repository CI and your review process still determine whether the change is ready to merge. Continue with [pull requests](/coding-agent/building/pull-requests) and [preview](/coding-agent/building/preview-and-hosting). # Auto, Plan, and effort Source: https://docs.pre.dev/coding-agent/building/build-modes Choose the agent's intent, sprint scope, and depth of work. Three controls answer different questions: **Auto or Plan** sets the intent of your conversation, **sprints** define a unit of work, and **effort** controls how deeply a sprint approaches it. [Model selection](/coding-agent/building/pro-mode) chooses the models used for that work. ## Auto and Plan | Mode | Behavior | Command | | ---- | ------------------------------------------------------------------------ | ------- | | Auto | The agent can answer, ask for context, implement directly, or plan first | `/auto` | | Plan | Messages shape requirements, user flows, roadmap, and architecture | `/plan` | Auto is the default. Plan mode returns to Auto when the plan is produced. Selecting Plan does not itself start a build: send the requirements you want to develop, review the artifacts, then request implementation. ## Choose a unit of work For a small change, describe it in chat. Use a dedicated sprint for a defined feature: ```text theme={null} /sprint add CSV export to the reports page with a progress indicator ``` `/fork ` starts another task in a separate session. In projects with a roadmap, **Build Next Task** works on the next unit of planned work and **Build on Autopilot** continues through the roadmap. Availability depends on the project's plan and active work. Follow the session that owns the run. Parallel work, queuing, and admission limits depend on the client and account; submitting another message is not a guarantee that it starts immediately. ## Sprint effort Set effort with `/effort` before launching the sprint. | Setting | Approach | | -------- | ---------------------------------------------------- | | `auto` | Choose an approach for the task | | `low` | A direct implementation loop for focused changes | | `medium` | A direct loop organized around a task list | | `high` | A separate research, coding, and acceptance workflow | Higher effort can involve more model work and credits. Effort controls the workflow; it does not promise a particular duration or result. A direct chat change does not necessarily run the full high-effort pipeline. ## Review the outcome State the checks you need in the request: for example, type checking, a specific test suite, or a browser journey. Read the actual [verification evidence](/coding-agent/building/acceptance-criteria) and inspect the diff before shipping. # Collaboration Source: https://docs.pre.dev/coding-agent/building/collaboration Invite collaborators and manage preview access separately from project editing. Open **Share** in the web workspace to invite collaborators, manage their roles, and configure access to the deployed preview. `/share` opens these controls in the web client. ## Invite and manage collaborators Enter an email and send the invitation. The current Share flow invites new collaborators as **Viewers**. The owner can then use **Make Admin** or **Make Viewer** to change their role. | Role | Project access | | ------ | ---------------------------------------------------------- | | Owner | Manage the project and collaborator roles | | Admin | Edit the project and manage permitted Viewer collaborators | | Viewer | View the project with read-only permissions | Only the owner can assign Admin access. Admins cannot manage the owner or other admins. The interface exposes the actions available to your role. ## Preview privacy The **Public preview access** toggle controls access to the deployed application. Making the preview public lets people open its shared URL; it does not make them project editors. For private previews, open the app through the authorized workspace flow. A raw copied preview URL may lack the access grant needed to identify you. Application-level login and permissions are separate from this preview access setting. A custom domain requires a public preview and an existing deployment. See [custom domains](/coding-agent/building/custom-domains). ## Work in parallel Use [separate sessions](/coding-agent/building/sessions-and-parallel-agents) for distinct workstreams. Presence indicators show which session collaborators are viewing. Review each session before using Merge; that action can automatically merge a clean PR. Team projects use organization-scoped connections and configuration. Review [integration scope](/coding-agent/integrations/overview) before changing a setting shared with other projects. # Custom domains Source: https://docs.pre.dev/coding-agent/building/custom-domains Connect a hostname to a deployed, public pre.dev app. A custom domain requires an existing deployment and **Public preview access** enabled in **Share**. The current interface supports one custom domain per project. In the project's Share controls, open **Custom Domain** and enter a hostname such as `app.example.com`. Copy the exact DNS target shown after adding it. At your DNS provider, add the record shown in the interface. For a subdomain, this is normally a CNAME: | Type | Host | Target | | ----- | ----------------------------------------------------- | --------------------------------- | | CNAME | `app` or `app.example.com`, as your provider requires | The exact target shown by pre.dev | Use a hostname as the target, without an `https://` prefix or a path. For an apex domain, follow your provider's supported alias or flattening configuration and the records shown by pre.dev. Return to pre.dev and click **Verify Connection**. Once verification and hostname setup succeed, the domain becomes active. Allow time for DNS and certificate provisioning before checking HTTPS. Open the domain and exercise key flows. Review allowed origins, login callback URLs, cookies, and any provider configuration that depends on the hostname. The agent can help update application settings after domain activation. ## Troubleshooting | Symptom | What to check | | ------------------------------------- | ----------------------------------------------------------------------------------------------- | | Cannot add a domain | The project has a deployment, preview is public, and no domain is already configured | | DNS verification fails | The hostname resolves to the exact target shown; the DNS change may still be propagating | | Verify is unavailable | Wait for the current operation indicated by the interface | | HTTPS is not ready | Check hostname status and certificate provisioning; do not repeatedly remove a valid DNS record | | App loads but login or API calls fail | Check callback URLs, allowed origins, cookies, and runtime configuration | Use the domain's remove control to detach it. Remove the corresponding DNS record at your provider when it is no longer needed. The original deployment URL remains the fallback hosting address. # Preview and hosting Source: https://docs.pre.dev/coding-agent/building/preview-and-hosting Inspect a running app, share its preview, and review deployment state. Open **Preview** to inspect the running application when the project has a deployment. The workspace checks its status and can attempt to restore an idle environment. If setup or startup fails, use the reported status and agent debugging controls to resolve it. A code change can exist before the application starts successfully. Check the build output, environment variables, start command, and preview behavior before sharing the result. ## Sessions and access Select the session whose work you want to inspect. Hosted session previews use the session's deployment where available. Confirm the selected session and URL before comparing changes. Use **Share → Public preview access** to make the app accessible through its shareable URL. Private preview access uses the authorized workspace flow. Public preview access and permission to edit the project are [separate settings](/coding-agent/building/collaboration). ## Mobile projects Supported Expo or React Native projects have a mobile preview with a phone frame and a device link or QR code. Follow the device instructions shown by the preview. Tokenized links can expire; refresh the link through the interface when needed. If the mobile server is unavailable, **Debug with Agent** sends the relevant context into the project conversation. The project must have a working compatible mobile setup before the device preview can load. ## History and export The Code and history views let you inspect available commits, branches, and file changes. Uncommitted work is not a saved Git version. Review the selected commit and the confirmation before using **Revert**, because it changes the working code. Use the available export controls to download code or planning artifacts. Review setup instructions and required configuration when running an export elsewhere. **Refresh from GitHub** synchronizes a linked hosted checkout after external changes when offered. ## Hosting and domains Hosted apps can be served through their assigned `.pre.dev` URLs with HTTPS and supported WebSocket routing. Runtime availability still depends on a healthy application and its configured services. To serve a deployed public app on your own hostname, follow [custom domain setup](/coding-agent/building/custom-domains). Review your production requirements and provider configuration as part of the project's deployment workflow. # Model selection Source: https://docs.pre.dev/coding-agent/building/pro-mode Choose a model for all phases or set different models for each phase. Use `/model` to open the model picker. The live catalog shows the choices available to your account; model availability and defaults can change. | Phase | Work it controls | | ---------- | -------------------------------------------------- | | Chat | Conversation and direct agent work | | Research | Investigation in workflows with a research phase | | Coding | Implementation in workflows with a coding phase | | Acceptance | Verification in workflows with an acceptance phase | Choose one model for all phases or set a phase separately. In clients that support model command arguments, `/model all ` applies one model throughout and `/model reset` restores automatic choices. Use the picker to select a valid model identifier. Model settings persist with the project. A phase selection only matters when that phase runs; [effort](/coding-agent/building/build-modes) determines the sprint workflow. `/pro` has been retired. Use `/model` for model selection. The **Pro subscription** is a billing plan and is separate from these controls. For availability and credit allowances, see [plans and credits](/coding-agent/plans-and-credits). # Roadmap and progress Source: https://docs.pre.dev/coding-agent/building/progress-tracking Inspect planned work, active sessions, and completion evidence. The roadmap organizes available planning artifacts into milestones, stories, and subtasks. Use `/kanban` or `/roadmap`, or open **Plan → Roadmap**. A project needs roadmap data for this view; a direct build may not have generated it. ## Kanban | Column | Meaning | | ----------- | ----------------------------------------------- | | Backlog | Planned work that is not prioritized | | Next Tasks | Upcoming work, including stories you prioritize | | In Progress | Work marked active | | Done | Work marked complete | Where editing is enabled for your role and project, drag cards, reorder upcoming work, and open stories to edit their details. Some transitions are restricted during active builds. Status changes and incoming updates are reflected in the board. A manually changed status records a planning decision. Use the run's messages, diff, and [verification evidence](/coding-agent/building/acceptance-criteria) to establish what was implemented and tested. ## Timeline and artifacts Switch to **Timeline** for the Gantt view of milestones, stories, estimates, and progress. Screenshots attached to milestones can be opened in the gallery when captures are available. Planning estimates describe expected effort. They are not deadlines or a promise that a live agent run will take the displayed number of hours. ## Sync to a project management tool Use the roadmap's sync controls with a connected Linear or Jira account. Review the selected provider workspace and the sync result. When the roadmap changes, the interface can offer **Sync new changes**. This workflow pushes the pre.dev roadmap to the external tool. Do not assume arbitrary edits in the external tool automatically update the pre.dev plan. GitHub code synchronization is a separate [repository workflow](/coding-agent/projects/github-integration). ## Follow active work The session feed shows current actions, questions, errors, and results. Notifications can link back to a question, missing configuration, or completed work. Return to the session to inspect its latest status before starting duplicate work. # Pull requests and merges Source: https://docs.pre.dev/coding-agent/building/pull-requests Review session changes and choose how they enter your repository. Connect the project to GitHub to use hosted branch and pull-request workflows. A session's work can be reviewed as a diff and integrated through the session controls or a requested PR workflow. ## Request a reviewable change State the target branch and review behavior in the task: ```text theme={null} Implement CSV export on a feature branch. Run the relevant checks and open a pull request against main. Leave the PR open for review. Include the behavior change, verification, and any known limitations. ``` Review the code, check results, and preview evidence. Request corrections in the relevant session so the agent works against the right branch and context. ## Session Merge The web session **Merge** action can create a GitHub PR and automatically merge it when the change is clean. It is an integration action, so inspect the session before confirming it. If conflicts occur, use the offered resolution workflow or resolve them in GitHub, then verify the result. The PR URL and session status show the outcome. Repository permissions and branch rules can prevent a merge. ## Keep the checkout current When changes land outside pre.dev, use the available **Refresh from GitHub** action to synchronize the hosted code. Check the selected branch and any local changes before refreshing or starting another build. Direct agent work, sprint workflows, and session merges do not all use identical commit behavior. Specify restrictions that matter to the task and enforce branch protection in the repository where appropriate. See [GitHub connections](/coding-agent/projects/github-integration), [parallel sessions](/coding-agent/building/sessions-and-parallel-agents), and [verification](/coding-agent/building/acceptance-criteria). # Sessions and parallel agents Source: https://docs.pre.dev/coding-agent/building/sessions-and-parallel-agents Separate workstreams, inspect each result, and merge when ready. A session groups a conversation and its branch of work. Use sessions for independent features, experiments, or collaborators working at the same time. ## Start separate work Use `/fork ` for another task, `/sprint ` for a dedicated sprint, or the session controls in the web workspace. Additional web sessions require a GitHub connection and available session capacity. Each session has its own chat context and branch. Hosted sessions can have their own running environment and preview. CLI sessions use separate Git worktrees. Select the session before inspecting its code, messages, or preview. ## Work with collaborators Presence indicators show who is viewing a session. Give parallel tasks clear boundaries and review overlapping files before merging. Separate branches reduce interference during implementation; they can still conflict when integrated. ## Merge, promote, or archive | Action | Effect | | --------------- | ----------------------------------------------------------------------------------------------- | | Merge | Integrate the session through the GitHub merge workflow; a clean PR can be merged automatically | | Promote to Main | Change which session serves as the project's main session | | Archive | Remove a session from the active list while retaining its record | | Revive | Restore an archived session when its backing branch is still available | Promoting a session and merging its code are different operations. Read the confirmation and resulting status for the selected action. A deleted GitHub branch can prevent revival. If needed, start a new session from the current Main. See [pull requests and merges](/coding-agent/building/pull-requests). # Service API keys Source: https://docs.pre.dev/coding-agent/integrations/api-keys Store reusable third-party credentials and propagate updates to projects. Use **API Keys** in [workspace Integrations](https://pre.dev/projects/integrations) for credentials your applications use, such as payment, email, storage, or database keys. A **pre.dev API key** authenticates calls to pre.dev itself and is managed at [pre.dev/projects/key](https://pre.dev/projects/key). See [API authentication](/api-reference/authentication) for that workflow. ## Add a service credential 1. Open **Integrations → API Keys**. 2. Choose a provider or add a custom entry. 3. Enter the credential values and save. 4. Open the target project's **Env Vars** to review the values it needs. Keys are stored encrypted. Use the configuration controls for secret values; do not rely on a guarantee that arbitrary agent output can never expose a value. ## Import several keys Use **Import Keys** to paste configuration or upload a supported `.env`, `.txt`, or `.json` file. The importer can also extract values from an image. Review detected names and values before saving, especially for multiple environments or accounts. ## Apply and rotate Reusable credentials can supply project environment configuration. Existing projects may need propagation after a change. When the interface reports projects with outdated values, review the affected projects and apply the update to the intended ones. For a value specific to one application, use [Project setup → Env Vars](/coding-agent/integrations/env-vars). Verify the running application's behavior after updating a credential; some integrations also require an application restart or provider-side configuration. # Environment variables Source: https://docs.pre.dev/coding-agent/integrations/env-vars Detect missing configuration, import values, and update a project's runtime. Open **Project setup → Env Vars** using `/integrations`, or click **Environment** from Code. The editor combines detected requirements with custom configuration for the project. ## Configure the project 1. Review variables detected from the code and the provider instructions shown for them. 2. Fill missing values or add custom variables. 3. Review imported or inherited values and remove entries the app no longer needs. 4. Save and check the application's runtime status. Sensitive values are masked with a reveal control. Custom names are normalized to uppercase. Saved values persist across detection scans. Saving persists the configuration and applies it to the running project where available. A service that reads variables only at startup may require a restart; inspect the runtime result rather than assuming a save alone verified the integration. ## Bulk import Paste `.env` text or drop a supported `.env`, `.txt`, `.json`, or image file. The importer matches values to detected variables and can add custom entries. Review the result before saving, including environment-specific values and names that appear more than once. ## Shared values [Workspace service keys](/coding-agent/integrations/api-keys) provide reusable credentials. Team configuration can also supply shared environment values. Propagation controls show affected projects so you can apply updates individually or together. The project's Env Vars view is where you review its concrete configuration. Workspace key changes do not prove that every existing project's runtime has already picked them up. ## Missing configuration The build can report missing variables and send a notification linking back to Project setup. Supply the values, resume the relevant task if needed, and verify the feature that depends on them. The [pre.dev API key page](https://pre.dev/projects/key) is for authenticating to pre.dev; application service credentials belong in Integrations or the project's environment. # External MCP servers Source: https://docs.pre.dev/coding-agent/integrations/mcp-servers Give the Coding Agent access to additional tools and data sources. Connect an external MCP server when the agent needs tools from another service or your own system. To use **pre.dev's tools in another assistant**, follow [product MCP setup](/architect-agent/mcp-setup) instead. ## Add a server 1. Open **Project setup → MCP** or **MCP Servers** in [workspace Integrations](https://pre.dev/projects/integrations). 2. Paste a remote URL, a supported command, or the server configuration. 3. Include the authentication headers or environment values required by that server. 4. Use **Test** to check the handshake and advertised tools. 5. Save and enable the entry. Remote configuration example; replace the URL and credential with your server's values: ```json theme={null} { "url": "https://mcp.example.com/mcp", "headers": { "Authorization": "Bearer YOUR_SERVER_TOKEN" } } ``` Standard-input/output configurations use `command`, `args`, and `env`. The command runs in the agent's execution environment; a path on your own laptop is not automatically available there. Compatibility depends on transport, authentication, and runtime requirements. Test the actual configuration before relying on its tools. ## Scope and controls Personal projects inherit personal MCP entries and can override a matching name. Organization entries are shared across the organization. See [integration scope](/coding-agent/integrations/overview). In the CLI, `/mcp` lists personal entries and supports toggling or removal. Press `o` to add or configure entries on the web. On the web, use `/integrations` to open Project setup. Enable the servers needed for the task, and describe the operation you want the agent to perform. A successful connection test confirms tool discovery; individual calls can still fail because of provider permissions or service errors. # Provider connections Source: https://docs.pre.dev/coding-agent/integrations/oauth Connect accounts and select the right workspace default or project account. Provider connections authorize the agent to use services through your account. Start from **Project setup → Connections** or [workspace Integrations](https://pre.dev/projects/integrations). ## Connect an account 1. Choose the personal or team workspace that should own the connection. 2. Select the provider and complete its authorization flow. 3. Review the connected account label and any requested permissions. 4. In the project, choose that account or inherit the workspace default. Multiple accounts for one provider can coexist. For example, a workspace can hold two GitHub or Slack accounts, and each project can select the one it needs. A project pin takes precedence over the workspace default. ## Available providers The connection catalog includes code hosts, project management, communication, documents, design, CRM, deployment, and monitoring. Examples include GitHub, GitLab, Bitbucket, Linear, Jira, Slack, Notion, Google Workspace, Microsoft 365, Figma, HubSpot, Vercel, Supabase, and Sentry. The catalog and granted provider permissions determine available operations. Connecting a service does not start a sync or authorize every possible action automatically; request the work you want the agent to perform. ## Maintain a connection Use the connection menu to manage the default, label, or account connection. A **needs re-auth** indicator means you should reauthorize it in the web app. If the agent cannot find a repository or workspace, check both the selected account and its provider-side access. Before disconnecting an account, check which projects pin it or inherit it as their default. Choose a replacement when those projects still need the provider. In the CLI, `/integrations` displays personal connected accounts and their status; press `o` to manage them in the browser. # Integrations Source: https://docs.pre.dev/coding-agent/integrations/overview Connect provider accounts, agent tools, instructions, and application configuration. Open `/integrations` in a web project for **Project setup**. Use [workspace Integrations](https://pre.dev/projects/integrations) to manage reusable personal connections and configuration. | Setting | Purpose | Guide | | ------------------ | ---------------------------------------------------------------------- | -------------------------------------------------------------- | | Connections | Authorize a provider account and choose which account the project uses | [Provider connections](/coding-agent/integrations/oauth) | | Skills | Reusable instructions for the coding agent | [Agent skills](/coding-agent/integrations/skills) | | MCP | Tools exposed by an external MCP server | [External MCP servers](/coding-agent/integrations/mcp-servers) | | Env Vars | Secrets and configuration used by your application | [Environment variables](/coding-agent/integrations/env-vars) | | Workspace API keys | Reusable third-party credentials for projects | [Service API keys](/coding-agent/integrations/api-keys) | ## Connection selection A personal project uses its personal workspace's connections. A team project uses its team's connections. Each workspace can connect multiple accounts for the same provider. In **Connections**, leave a provider on **workspace default** or pin an account for this project. Connecting an account from Project setup selects it for that project. ## Skill and MCP scope Personal projects inherit personal entries and can add project-specific entries. A project entry with the same name takes precedence over its personal default. Organization entries remain shared within the organization, including when managed from a team project. The CLI's `/skills`, `/mcp`, and `/integrations` panels manage or display personal entries. Use the web for team configuration and project overrides. ## Connect pre.dev to another agent To give an external assistant pre.dev's specification and browser tools, use the [product MCP server](/architect-agent/mcp-setup). That is a separate direction of integration from adding an external MCP server to the Coding Agent. # Agent skills Source: https://docs.pre.dev/coding-agent/integrations/skills Save reusable instructions at personal, project, or organization scope. Skills provide reusable instructions to the Coding Agent, such as a testing convention, style guide, or repository workflow. ```text theme={null} Use the repository's existing component library. For behavior changes, run the relevant test suite and report its result. Record any verification that could not be completed. ``` ## Add a skill Open **Project setup → Skills** for a project, or **Agent Skills** in [workspace Integrations](https://pre.dev/projects/integrations). Add a name and instructions, save, and enable the entry. | Where you configure it | Scope | | ---------------------------- | ---------------------------------------------------------------------- | | Personal workspace | Reusable personal default | | Personal project | Project-specific entry; a matching name overrides the personal default | | Organization or team project | Organization-wide entry | Choose a distinct name when the instruction should supplement an inherited entry. Reuse its name when you intend a personal project to override it. ## Edit or disable Use the entry controls to edit, toggle, or remove a skill. Apply changes before starting the work that should use them; do not assume a running task has reloaded its instructions. In the CLI, `/skills` lists personal entries. Enter toggles an entry, `d` removes it, and `o` opens the web app for creation and configuration. Use the web to manage project-specific or organization entries. Skills guide behavior. Review the actual output and checks for the task, especially when a requirement must be enforced by a test or repository policy. # Coding Agent Source: https://docs.pre.dev/coding-agent/overview Build and maintain software in the web workspace or your local terminal. Describe a change, give the agent the project context it needs, and review the code and evidence it produces. pre.dev supports new apps, existing repositories, planning, implementation, and browser verification. The default **Auto** mode lets the agent answer a question, make a direct change, or plan a larger task. Switch to **Plan** when you want to shape requirements and architecture before implementation. ## Make the first request useful Give the agent an outcome it can implement and you can verify: ```text theme={null} Add assignee and status filters to the issue board. Keep the existing card layout. Filters should work together, and an empty result should offer a way to clear them. ``` For existing code, include what happens today and what should change. For a new app, start with one working flow before expanding the scope. ## Choose your workspace | Surface | Best starting point | | -------------------- | ------------------------------------------------------------------------------ | | Web | Create a project, import GitHub code, review plans, and use hosted previews | | CLI | Work directly in a local checkout and review changes with your usual Git tools | | Architect API or MCP | Generate specifications for another development workflow | The web and CLI share project records, planning artifacts, and account settings where supported. Local files and hosted checkouts still need their normal Git synchronization. A short web workflow from prompt to review. Install the CLI and start in a local repository. Choose how the agent approaches the work. Find code, plans, previews, and project setup. # Plans and credits Source: https://docs.pre.dev/coding-agent/plans-and-credits Understand plan allowances, measured usage, and account limits. Credits pay for coding, planning, and browser tasks. Use `/balance` in the workspace or CLI to check your remaining credits. ## Plans Paid plans include a monthly credit allowance. Team credits are pooled across members. Prices below are for monthly billing; see [pricing](https://pre.dev/pricing) for annual billing and Enterprise options. | Plan | Monthly price | Included credits | Main additions | | ---------- | ------------- | -------------------- | ------------------------------------------- | | Free | \$0 | 20 | Coding in web and CLI, browser agents | | Plus | \$10 | 100 monthly | Fast Spec and the default model offering | | Premium | \$49 | 500 monthly | Full model catalog | | Pro | \$199 | 2,500 monthly | Deep Spec | | Team | \$499 | 5,000 pooled monthly | Unlimited team seats, Architect MCP and API | | Enterprise | Custom | Per agreement | Dedicated support and negotiated capacity | Free includes 20 credits to get started. Manage your subscription and view your account's price and allowance in billing. ## What consumes credits | Work | How to interpret the charge | | ------------------- | ------------------------------------------------------------------------------------------------ | | Coding and planning | Measured model work; model choice and effort affect usage | | Fast and Deep specs | Variable usage; see the [Architect comparison](/architect-agent/overview) for estimates | | Browser tasks | Successful tasks have a 0.1-credit floor; failed task outcomes have zero settled charge | | Proposal assessment | 100 credits per vetting request; [validate inputs before submitting](/architect-agent/proposals) | Browser submission reserves a minimum amount before execution. Final settlement accounts for task outcomes. A submission may be rejected because of an account limit even when the overall balance is positive. Browser trial limits and inflight caps are separate from your total credit allowance. ## Check usage and recover Use `/balance` for the account balance and project cost analytics for a breakdown of work. In the CLI, `/topup` and `/upgrade` open billing. A run paused for insufficient credits may resume after billing recovers; inspect its current status before launching duplicate work. For integrations, [GET /credits-balance](/architect-agent/api/credits-balance) returns the effective balance. [GET /browser-agent-status](/browser-agents/api/queue-status) reports the current browser inflight cap. ## API and MCP access Browser REST is available to eligible free accounts. Architect REST and the product MCP server require subscription or organization authentication, with additional trial checks for specification generation. See [authentication](/api-reference/authentication) for account requirements and [errors and retries](/api-reference/errors) for access errors. # Create a project Source: https://docs.pre.dev/coding-agent/projects/creating-a-project Start from a prompt or bring an existing repository. Start at [pre.dev](https://pre.dev). Describe a new application, or choose **Import** to work with an existing GitHub repository. To work on local files, [launch the CLI](/cli/overview) in your repository. ## Write a useful starting prompt Include the intended users, the first outcome you want to deliver, technical constraints, and how you will judge success. ```text theme={null} Build a booking app for a small photography studio. Customers should choose a session type and an available time. Staff should see upcoming bookings and be able to cancel them. Use the existing payment provider; start with test payments. First milestone: a customer can complete one booking without a duplicate slot. ``` Attach relevant reference material and supply existing-system context when you have it. Connect credentials through [Project setup](/coding-agent/integrations/overview). ## Choose the next step **Auto** can start implementation directly or decide that more planning is useful. Choose **Plan** or send `/plan` to focus on requirements, flows, and architecture. Review the generated artifacts before asking the agent to build against them. Fast and Deep specs are [different planning depths](/coding-agent/specifications/fast-vs-deep). Model choice is a separate setting in `/model`; the old `/pro` command has been retired. ## Continue the project Open it again from [Projects](https://pre.dev/projects). Ask for the next change, inspect the current code and preview, or start a dedicated sprint. Available planning views depend on which artifacts the project has produced. # GitHub integration Source: https://docs.pre.dev/coding-agent/projects/github-integration Connect the right GitHub account, import code, and review branch changes. Use GitHub to import a repository, keep hosted project code in a repository, and review changes through branches and pull requests. ## Select the account Connect GitHub in **Project setup → Connections** or workspace Integrations. Complete GitHub's authorization flow with access to the repositories you need. A workspace can connect multiple GitHub accounts. In the project, select a specific account or inherit the workspace default. Team projects use team workspace connections. If a repository is missing, check the selected account, organization authorization, and repository permissions. ## Work with a repository [Import a repo](/coding-agent/projects/importing-repos) to start from existing code. For a new project, use the available GitHub connection and repository setup controls to link its code. Additional hosted sessions require a connected GitHub project. Session branches keep parallel work separate until integration. Review the target branch and [merge behavior](/coding-agent/building/pull-requests) before combining changes. ## Keep work synchronized The Code and history views show repository information when available. After pushing changes outside pre.dev, use **Refresh from GitHub** when offered and confirm the active branch is current. The CLI edits your local checkout; use its normal Git workflow to exchange code with GitHub. Sharing a pre.dev project record does not replace that synchronization. If you rotate or disconnect an account, update affected project pins and confirm repository operations still work with the replacement connection. # Import a repository Source: https://docs.pre.dev/coding-agent/projects/importing-repos Understand an existing GitHub codebase and build on its conventions. Import connects a GitHub repository to a hosted pre.dev project. For code already on your machine, you can also [use the CLI directly](/cli/existing-repos). Select **Import**, then choose an accessible repository or supply its URL. Connect the GitHub account that can access private repositories. Organization access depends on the permissions granted in GitHub. Let pre.dev analyze the code, dependencies, and structure. Use `/reverse` to refresh the architecture after significant changes. The output depends on the code and configuration available to the agent. Review the installation and start commands, and fill required environment variables in **Project setup → Env Vars**. An imported repository may need project-specific services or setup before its preview runs. Describe the desired behavior and the conventions to preserve. ```text theme={null} Add a wishlist to the existing shop. Reuse the current auth, database access layer, and component library. Include an empty state and verify that one user cannot read another user's list. ``` Inspect the diff and reported checks, test the preview if available, and use the project's Git workflow to merge and deploy. For multiple connected GitHub accounts, check the account selected in **Project setup → Connections**. A project can pin one account or inherit its workspace default. See [GitHub integration](/coding-agent/projects/github-integration). # Quickstart Source: https://docs.pre.dev/coding-agent/quickstart Create a project, make a change, and review the result. Build a small issue board, add a useful filter, and inspect the result. You can follow the same workflow in a new project or an existing repository. ## Before you start You need a [pre.dev account](https://pre.dev) and available [credits](/coding-agent/plans-and-credits). To work on existing code, have access to the GitHub repository you want to import. ## Build your first change Sign in at [pre.dev](https://pre.dev) and describe what you want to build, or [import a GitHub repository](/coding-agent/projects/importing-repos). ```text theme={null} Build an issue tracker for a small design team. Include projects, assignees, due dates, and a status board. Start with a working board using sample data. ``` **Auto** is the default: the agent chooses an appropriate next step. Use `/plan` to work on the requirements and architecture first. Plan mode returns to Auto when the plan is produced. For an existing app, include the expected behavior, the current problem, and any files or constraints you already know. Open `/integrations` for **Project setup**. Choose the relevant connection account, enable skills or MCP servers, and fill required **Env Vars**. Use [environment settings](/coding-agent/integrations/env-vars) for secrets and configuration. Ask the agent to implement the first useful piece. For a dedicated sprint, use: ```text theme={null} /sprint add filtering by assignee and status, with an empty state ``` A useful result lets you combine both filters, shows only matching issues, and explains when no issues match. Include these criteria in your request so you can check them in the preview. Follow the active session and its progress. Additional web sessions may require a connected GitHub repository. Inspect the code changes, reported checks, and available preview. Test your acceptance criteria, then request any corrections. Use your project's GitHub and deployment workflow to ship the reviewed result. The session **Merge** action can create a pull request and merge it automatically when clean. Use a review-first request if you want a PR left open. ## Check the result Select an assignee and a status, then clear each filter. Try a combination with no matching issues. Compare that behavior with the code changes and the agent's verification report. | If you need to… | Continue with | | -------------------------------------------- | ----------------------------------------------------------------- | | Find code, plans, or the active session | [The workspace](/coding-agent/workspace) | | Understand which checks ran | [Verification](/coding-agent/building/acceptance-criteria) | | Open a preview or troubleshoot a missing one | [Preview and hosting](/coding-agent/building/preview-and-hosting) | | Review and merge the code | [Pull requests](/coding-agent/building/pull-requests) | # Fast vs Deep specs Source: https://docs.pre.dev/coding-agent/specifications/fast-vs-deep Choose planning depth based on the decisions you need to make. Fast Spec gives a quicker project-level plan. Deep Spec develops a more detailed breakdown for complex work. Both can produce requirements, architecture, and specifications for humans and coding agents. | Choose | When it helps | | --------- | -------------------------------------------------------------------------- | | Fast Spec | Explore scope, validate an idea, or establish a first architecture | | Deep Spec | Coordinate a larger project or examine implementation details and subtasks | Deep output typically includes more granular stories and subtasks. Inspect the generated artifacts for the actual level of detail; do not rely on a fixed number of milestones or tasks. Generation time and credits vary with scope. The [Architect overview](/architect-agent/overview) keeps current estimates in one place. [Plans and credits](/coding-agent/plans-and-credits) explains commercial availability. ## Refine the plan Start with Fast when you need to assess direction, then request deeper planning for areas that need more detail. In the REST API, an existing spec's text goes in `currentContext`; in MCP it goes in `existingContext`. Neither field is a spec ID or an automatic upgrade operation. In the Coding Agent, **Plan** mode focuses the conversation on planning. **Auto** decides how to approach the next request. These conversation modes are separate from spec depth and [model choice](/coding-agent/building/pro-mode). See [understanding specs](/coding-agent/specifications/understanding-specs) and [API inputs and outputs](/architect-agent/inputs-and-outputs). # Understanding specs Source: https://docs.pre.dev/coding-agent/specifications/understanding-specs Read requirements, architecture, milestones, and the artifacts available to agents. A spec connects the project's goals to a proposed implementation. It supplies context for planning, coding, and review; it should be checked against the actual requirements and current codebase. A useful reading order is **goal → architecture → milestone → story → acceptance criteria**. Deep specifications can add implementation subtasks to a story. ## Read the artifacts | Artifact | What to review | | --------------------------- | ------------------------------------------------ | | Executive summary | Intended users, scope, and constraints | | Core functionality | The behaviors the project should support | | Architecture and tech stack | Components, dependencies, and technology choices | | Milestones and stories | Delivery order and concrete units of work | | Acceptance criteria | Observable outcomes used in verification | | Subtasks | Implementation detail, especially in Deep specs | Human-oriented output can include roles, personas, and effort estimates. Coding-agent output emphasizes implementation and omits human staffing detail. The API exposes Markdown, structured JSON, and available graphs; see [inputs and outputs](/architect-agent/inputs-and-outputs) for exact fields. ## Refine before building Ask the agent to resolve missing requirements, adjust constraints, or refine acceptance criteria. Use the available plan and story editing controls for the project. Confirm the updated artifact before launching work that depends on it. Changing a plan does not retroactively update shipped code. Request the corresponding implementation change, and check that an active task is using the intended requirements. ## Example acceptance criteria ```text theme={null} Story: Export invoices - The exported rows match the current filters. - The file includes the currency for every monetary amount. - Users cannot export invoices outside their account. - An empty result displays an explanation instead of an empty download. ``` Track planned work in the [roadmap](/coding-agent/building/progress-tracking) and inspect implementation evidence in [verification](/coding-agent/building/acceptance-criteria). # The workspace Source: https://docs.pre.dev/coding-agent/workspace Navigate agent chat, planning artifacts, code, preview, and project settings. The project workspace brings the agent conversation, code, and project artifacts into one place. Use the session tabs to switch workstreams and the view menu to inspect the current project. ## Views | View | Shortcut | What it shows | | ------------------- | ------------ | ------------------------------------------- | | Agent | Cmd/Ctrl + 1 | Chat, tool activity, and the current run | | Plan → Roadmap | Cmd/Ctrl + 2 | Available milestones, stories, and timeline | | Plan → Architecture | Cmd/Ctrl + 3 | Available system and user-flow graphs | | Plan → Spec | Cmd/Ctrl + 4 | Available specification documents | | Code | Cmd/Ctrl + 5 | Source files and Git information | Planning views appear when their artifacts exist. A direct build can have working code before it has a roadmap or architecture graph. Open the preview from the workspace's preview controls when a development server is available. ## Chat controls Type `/` to see commands supported by the current client. | Command | Action | | ------------------------------ | -------------------------------------------------------- | | `/auto` | Let the agent choose whether to answer, build, or plan | | `/plan` | Shape the plan before implementation | | `/model` | Choose models for chat, research, coding, and acceptance | | `/effort` | Set sprint effort to auto, low, medium, or high | | `/balance` | View remaining credits | | `/sprint ` | Start a dedicated sprint | | `/fork ` | Start another session for a task | | `/integrations` | Open Project setup | | `/reverse` | Analyze an existing codebase | | `/kanban`, `/roadmap`, `/arch` | Open project planning views | | `/share` | Open sharing controls | The [CLI command reference](/cli/commands) lists terminal-specific commands and keys. The web and CLI palettes have different capabilities. ## Project setup Open `/integrations`, use the prompt bar's **+** menu, or use **Environment** from Code. The **Project setup** dialog has four tabs: * **Connections**: choose a workspace account for each provider. * **Skills**: configure the agent's reusable instructions. * **MCP**: connect additional tools and data sources. * **Env Vars**: configure the application's environment. [Integrations](/coding-agent/integrations/overview) explains workspace defaults and project overrides. ## Sessions and sharing A session has its own conversation and branch of work. The active session determines what you are inspecting. Presence indicators help collaborators see which session others are viewing. Use **Share** to manage collaborators and preview access. Public preview access does not grant permission to edit the project. See [sessions](/coding-agent/building/sessions-and-parallel-agents) and [collaboration](/coding-agent/building/collaboration). # Guide for agents Source: https://docs.pre.dev/for-agents Select the right pre.dev interface, use exact field names, and handle long-running work reliably. Use this page when implementing a pre.dev integration or choosing a pre.dev tool for a user's task. ## Read the contract | Resource | Use it for | | ----------------------------------------------------------- | ------------------------------------------------------------------------------- | | [Documentation index](https://docs.pre.dev/llms.txt) | Discover pages without loading the whole site | | [All documentation](https://docs.pre.dev/llms-full.txt) | Full-text ingestion when you need the entire reference | | [This page as Markdown](https://docs.pre.dev/for-agents.md) | Read a single page; append `.md` to other page URLs too | | [OpenAPI schema](/api-reference/openapi.json) | REST methods, paths, request bodies, and response schemas | | [MCP tools](/mcp/tools) | Tool parameters and return formats; discover the live schemas with `tools/list` | | [MCP service metadata](https://api.pre.dev/mcp/info) | Transport and protocol information without authentication | The documentation site's **Ask AI / MCP** features search documentation. To execute product tools, connect to **`https://api.pre.dev/mcp`** using the [product MCP setup](/architect-agent/mcp-setup). ## Select an interface | Task | REST | MCP | | --------------------------------- | ----------------------------------------------------- | -------------------- | | Generate a concise specification | `POST /fast-spec` | `fast_spec` | | Generate a detailed specification | `POST /deep-spec` | `deep_spec` | | Retrieve a specification | `GET /spec-status/{specId}` | `get_spec` | | Browse specification history | `GET /list-specs` | `list_specs` | | Search specification input | `GET /find-specs` | Use REST | | Run browser tasks | `POST /browser-agent` | `browser_agent` | | Retrieve a browser run | `GET /browser-agent/{id}` | `browser_agent_get` | | Browse browser history | `GET /list-browser-agents` | `browser_agent_list` | | Review a proposal | [Proposal REST endpoints](/architect-agent/proposals) | Use REST | | Check available credits | `GET /credits-balance` | Use REST | Both official SDKs are named **`predev-api`**. Python imports use `from predev_api import PredevAPI`; Node imports use `import { PredevAPI } from 'predev-api'`. The Python SDK uses blocking HTTP calls, including its server-side async submission methods. ## Keep names distinct | Meaning | REST | MCP | Python SDK | | ---------------------------------- | -------------------------------------------- | ------------------------------------------- | ------------------ | | What to specify | `input` | `executiveSummary` (at least 10 characters) | `input_text` | | Existing codebase context | `currentContext` | `existingContext` | `current_context` | | Reference documentation | `docURLs` | `docURLs` | `doc_urls` | | Specification polling ID | `specId` from submission; `_id` on retrieval | `specId` | `result["specId"]` | | Browser run ID | `id` | `id` | `result["id"]` | | Submit browser work asynchronously | `async: true` | `async: true` | `run_async=True` | Pass existing context as **text describing the codebase**. It is not an ID that automatically loads another project. ## Handle work that takes time 1. For REST specifications, submit with `async: true`, save `specId`, and poll the status endpoint at a bounded interval, such as every five seconds. 2. Stop polling specifications on `completed` or `failed`. On success, consume `codingAgentSpecMarkdown` or `codingAgentSpecJson`; use the human variants for review and estimates. 3. For browser work, always send a `tasks` array. Save the returned `id`, then poll or [stream the existing run](/browser-agents/api/stream-task). 4. Browser **batch** status is lowercase (`processing`, `completed`, `failed`). Individual **task** statuses are uppercase. A completed batch can contain failed tasks; inspect each task's `status` and `error`. 5. Use batch `status` to detect completion. Results may contain `PENDING`/`RUNNING` entries or `null` slots. Do not infer completion from array length or the `completed` count alone. 6. Request `includeEvents=true` when you need evidence or debugging. Timelines can contain large screenshots; omit them for routine polling. ## Submit deliberately * Browser tasks can interact with external sites. State the action and success condition clearly, and use the task's `output` JSON Schema when your code depends on a specific data shape. * Check [queue capacity](/browser-agents/api/queue-status) before submitting a large batch. The default 1,000-task request ceiling and your account's in-flight limit are different limits. * REST browser submissions accept `Idempotency-Key` for retries within 24 hours. Use one key per logical submission. This is a lookup, not an atomic guarantee for simultaneous first submissions. This option is not exposed by the current MCP tool or SDK method signatures. * A timeout or disconnected stream does not prove the task stopped. Retrieve the existing run before submitting work again. Stream EOF is not a success signal. * Handle HTTP errors and stream `error` frames. [Errors and retries](/api-reference/errors) explains billing, queue, and rate-limit responses. * Some MCP tools return text without `structuredContent`, and some specification failures return text without `isError`. Read the tool result and confirm specification status with `get_spec`. ## Current integration boundaries The public REST API has no general coding-session, deployment, cancellation, webhook-registration, or recurring-schedule endpoint. Build with the [Coding Agent](/coding-agent/overview) or [CLI](/cli/overview), and schedule API calls in your own application when needed. Browser tasks do not expose a reusable login-session or cookie-profile API. # MCP tool reference Source: https://docs.pre.dev/mcp/tools The seven primary pre.dev tools, exact input names, result formats, and deprecated aliases. Connect once at **`https://api.pre.dev/mcp`** to use specification generation and browser automation. [Setup instructions](/architect-agent/mcp-setup) cover authentication and client configuration. Call **`tools/list`** after initialization for the live input schemas. `GET /mcp/info` is a human-readable service inventory; it is not the protocol's tool-discovery method. ## Tool inventory | Tool | Purpose | Result | | -------------------- | --------------------------------------- | -------------------------------------------------- | | `fast_spec` | Generate a concise specification | Text with artifact links or a `get_spec` handoff | | `deep_spec` | Generate a detailed specification | Text with artifact links or a `get_spec` handoff | | `get_spec` | Retrieve a specification and its status | Text and, on success, `structuredContent` | | `list_specs` | Paginated specification history | Text and, for a nonempty page, `structuredContent` | | `browser_agent` | Run browser tasks | Text summary or an async run ID | | `browser_agent_get` | Retrieve browser task results | JSON text and `structuredContent` | | `browser_agent_list` | Paginated browser history | Text and `structuredContent` | Generation and browser execution consume credits. Retrieval and listing do not launch new work. The server marks browser execution as potentially destructive because a task can click, submit forms, or change data on external sites. ## fast\_spec and deep\_spec Both tools accept the same parameters: | Parameter | Required | Type | Meaning | | ------------------ | -------- | ----------------------------- | ----------------------------------------------------------- | | `executiveSummary` | Yes | String, minimum 10 characters | What to specify | | `existingContext` | No | String | Existing code, stack, constraints, and architecture as text | | `docURLs` | No | Array of URL strings | Reference documentation | ```json theme={null} { "executiveSummary": "Add CSV exports to the reporting dashboard.", "existingContext": "An existing TypeScript app with a reports API and organization-scoped access.", "docURLs": ["https://www.rfc-editor.org/rfc/rfc4180"] } ``` These MCP tools do **not** take REST's `input`, `currentContext`, `file`, or `async` fields. They may return before generation finishes. If the result provides a specification ID, call `get_spec` until its status is `completed` or `failed`. Generation results are text, not the REST `SpecResponse` JSON envelope. A progress notification reaching 100 does not replace a terminal status check. ## get\_spec ```json theme={null} { "specId": "507f1f77bcf86cd799439011" } ``` `specId` is required. Use the ID returned by generation or listing. A successful `structuredContent` contains `specId` and `status`; it may also include `endpoint`, `created`, `executionTimeMs`, `progress`, `specUrl`, `predevUrl`, `output`, and `errorMessage`. `output` is specification Markdown, preferring the coding-agent variant. Status is `pending`, `processing`, `completed`, `failed`, or `unknown`. Optional values may be absent while generation is running. ## list\_specs | Parameter | Type | Default | Values | | ---------- | ------ | ------- | ---------------------------------------------- | | `limit` | Number | `20` | `1`–`100` | | `skip` | Number | `0` | Zero or greater | | `endpoint` | String | All | `fast_spec`, `deep_spec` | | `status` | String | All | `pending`, `processing`, `completed`, `failed` | For nonempty pages, `structuredContent` contains `specs`, `total`, `hasMore`, `skip`, and `limit`. Each entry uses **`specId`**, not REST's `_id`. Use `get_spec` for the full body. An empty page returns a text-only result. There is no `find_specs` MCP tool; use [REST search](/architect-agent/api/find-specs). ## browser\_agent | Parameter | Required | Type | Meaning | | ------------- | -------- | ---------------- | ---------------------------------------------------- | | `tasks` | Yes | Nonempty array | One object per browser task | | `concurrency` | No | Number, `1`–`20` | Parallel task allowance within this run; default `5` | | `async` | No | Boolean | Return the run ID without waiting for results | Each task supports: | Field | Type | Meaning | | -------------------- | -------------------------- | --------------------------------------------------------------- | | `url` | String, required | Starting URL | | `instruction` | String | Goal to accomplish | | `input` | Object of string values | Form fields or other task inputs | | `output` | JSON Schema | Expected output shape | | `successCondition` | String | Natural-language completion condition | | `mode` | `auto`, `extract`, `agent` | Automatic routing, schema extraction, or goal-driven navigation | | `maxSteps` | Integer, `1`–`50` | Planning-iteration budget | | `maxDurationSeconds` | Integer, `5`–`600` | Per-task execution budget in seconds | Limits apply to each task. Set explicit budgets for long flows; defaults can vary by task and execution mode. Your account's [in-flight limit](/browser-agents/api/queue-status) also applies to the whole submission. Synchronous execution returns a **text summary**, which truncates task data. Retrieve `browser_agent_get` for full structured results. Async execution returns the ID in text so you can poll it. The MCP tool has no `stream` or `idempotencyKey` input. It emits live notifications during synchronous execution when the client supports them. See [browser MCP examples](/browser-agents/mcp-tool). ## browser\_agent\_get ```json theme={null} { "id": "507f1f77bcf86cd799439011", "includeEvents": false } ``` `id` is required; `includeEvents` is optional and defaults to false. `structuredContent` contains the [browser run](/browser-agents/api/task-status), including individual task outcomes and extracted data. Set `includeEvents` to true to retrieve timelines and screenshots. ## browser\_agent\_list | Parameter | Type | Default | Values | | --------- | ------ | ------- | ------------------------- | | `limit` | Number | `20` | `1`–`100` | | `skip` | Number | `0` | Use a nonnegative offset | | `status` | String | All | `processing`, `completed` | The structured result contains `total` and `batches`. Each batch has `id`, `status`, `total`, `completed`, and `totalCreditsUsed`. Unlike REST listing, this tool does **not** return `hasMore`; compare your offset and page length with `total`. ## Notifications and errors The server sends `notifications/message` with `params: { level, logger, data }`. Browser messages contain a task index and event details; large screenshot and DOM values can be elided. Specification messages report phases such as `start`, `generating`, and `packaging`. To receive `notifications/progress`, include a `progressToken` in the `tools/call` request's `_meta`: ```json theme={null} { "jsonrpc": "2.0", "id": 2, "method": "tools/call", "params": { "name": "browser_agent", "arguments": { "tasks": [{ "url": "https://example.com", "instruction": "Read the page heading." }] }, "_meta": { "progressToken": "heading-run" } } } ``` Browser failures return `isError: true` when the tool call itself fails. Specification tools can return an error in text without `isError`; inspect the content and retrieve the specification status where an ID is available. Disconnecting or cancelling notification delivery does not cancel the underlying browser run. ## Deprecated aliases | Older name | Current name | | ------------------- | -------------------- | | `browser_task` | `browser_agent` | | `browser_task_get` | `browser_agent_get` | | `browser_task_list` | `browser_agent_list` | The aliases remain registered for compatibility. Use the current names in new integrations. Credits, proposal review, queue status, and live browser URL retrieval are available through REST rather than dedicated MCP tools. # pre.dev documentation Source: https://docs.pre.dev/overview Build software, generate specifications, and run browser tasks. Use the [Coding Agent](/coding-agent/quickstart) to implement a change, the [Architect API](/architect-agent/quickstart) to plan one, or [Browser Agents](/browser-agents/quickstart) to work with a website. ## Choose your interface | Work from | Use | Start with | | -------------------- | --------------------------------------------------- | ---------------------------------------------------- | | A browser | The web workspace for code, plans, and previews | [Build your first project](/coding-agent/quickstart) | | A local repository | The CLI and your existing Git workflow | [Install the CLI](/cli/overview) | | Your application | REST or an SDK for specifications and browser tasks | [API overview](/api-reference/overview) | | Another AI assistant | The product MCP server | [Connect MCP](/architect-agent/mcp-setup) | The public API exposes planning and browser operations. For code implementation, start in the web workspace or CLI. ## Build an integration Choose your account, authenticate a request, and check access. Recognize terminal states, recover from failures, and retry safely. Giving these docs to a coding assistant? Start with the [guide for agents](/for-agents) and the [OpenAPI schema](/api-reference/openapi.json). For account access and usage, see [plans and credits](/coding-agent/plans-and-credits).