From 3973f484415bd0751b1035ae8c29464a0791721d Mon Sep 17 00:00:00 2001 From: Smoke Person Date: Sat, 5 Dec 2026 01:22:18 -0500 Subject: [PATCH] docs: SDKs group (overview, TypeScript SDK, Python SDK) with "Build with the agent", and the Agent API REST reference - SDKs nav group moves next to API in Reference. The Node page is now the TypeScript SDK; both language pages follow Install / Set up the client / Build with the agent / Specifications / Browser agents / Credits / Errors, with a full create -> stream -> build next -> status walkthrough. Overview has TypeScript/Python CodeGroups and a language table. Page slugs are unchanged (parity baseline and existing links). - New Agent API group: overview + one page per operation (create, send, events SSE, build, status, stop), and the six operations, their schemas and examples in api-reference/openapi.json. - Example checkers mock the /agent/projects routes and assert the walkthrough hits each one; source coverage reads routes/agent_api.ts. - llms.txt lists the new pages (trimmed elsewhere to stay under 16 KB). The guides target predev-api 1.2.0, which is not published yet. The CI pins stay at 1.1.0 until then; check:node and check:python pass locally against the 1.2.0 build. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01PwA31qPkrcHj7kogbsmWS4 --- agent-api/build.mdx | 24 + agent-api/create-project.mdx | 25 + agent-api/events.mdx | 32 + agent-api/overview.mdx | 71 ++ agent-api/send-message.mdx | 25 + agent-api/status.mdx | 20 + agent-api/stop.mdx | 16 + api-reference/openapi.json | 1253 ++++++++++++++++++++++++++++- api-reference/overview.mdx | 17 +- architect-agent/overview.mdx | 2 +- architect-agent/quickstart.mdx | 2 +- architect-agent/sdks/node.mdx | 128 ++- architect-agent/sdks/overview.mdx | 83 +- architect-agent/sdks/python.mdx | 132 ++- docs.json | 28 +- llms.txt | 29 +- scripts/check-docs.mjs | 2 +- scripts/check-node-examples.mjs | 32 +- scripts/check-python-examples.py | 49 ++ snippets/sdk-install.mdx | 2 +- 20 files changed, 1869 insertions(+), 103 deletions(-) create mode 100644 agent-api/build.mdx create mode 100644 agent-api/create-project.mdx create mode 100644 agent-api/events.mdx create mode 100644 agent-api/overview.mdx create mode 100644 agent-api/send-message.mdx create mode 100644 agent-api/status.mdx create mode 100644 agent-api/stop.mdx diff --git a/agent-api/build.mdx b/agent-api/build.mdx new file mode 100644 index 0000000..6a0ea50 --- /dev/null +++ b/agent-api/build.mdx @@ -0,0 +1,24 @@ +--- +title: "Build the plan" +openapi: "/api-reference/openapi.json POST /agent/projects/{id}/build" +description: "Build the next task in a project's plan, a custom task, or every remaining task." +--- + +```bash +curl --fail-with-body -X POST "https://api.pre.dev/agent/projects/$PROJECT_ID/build" \ + -H "Authorization: Bearer $PREDEV_API_KEY" \ + -H "Content-Type: application/json" \ + -d '{"maxCredits": 50}' +``` + +| Body | Run | +| --- | --- | +| `{}` | Build the next task in the plan | +| `{ "task": "Add CSV export" }` | Build a custom task instead | +| `{ "all": true }` | Build every remaining task | + +The call returns `202` once the build has started. Follow it on [the event stream](/agent-api/events). Check progress with [status](/agent-api/status). + +`maxCredits` stops the run once it has spent that many credits on the project. The server checks spending every 15 seconds, so a run can go slightly over the cap before it stops. Limits per account: 20 build-next and 10 build-all calls per minute. + +TypeScript: `client.agent.buildNext(projectId)` / `buildAll(projectId)`. Python: `client.agent.build_next(project_id)` / `build_all(project_id)`. diff --git a/agent-api/create-project.mdx b/agent-api/create-project.mdx new file mode 100644 index 0000000..8f83cdf --- /dev/null +++ b/agent-api/create-project.mdx @@ -0,0 +1,25 @@ +--- +title: "Create a project" +openapi: "/api-reference/openapi.json POST /agent/projects" +description: "Start a project from a prompt; the coding agent begins on it right away." +--- + +```bash +curl --fail-with-body https://api.pre.dev/agent/projects \ + -H "Authorization: Bearer $PREDEV_API_KEY" \ + -H "Content-Type: application/json" \ + -d '{"prompt": "A habit tracker with daily streaks", "mode": "plan"}' +``` + +The call returns `201` with `projectId` and the Main `sessionId` as soon as the project exists. Planning and building continue in the background: follow them with [the event stream](/agent-api/events) or poll [status](/agent-api/status). + +| Field | Meaning | +| --- | --- | +| `prompt` | What to build. Up to 100,000 characters. | +| `mode` | `build` (default) builds right away. `plan` writes the plan first; build it with [build](/agent-api/build). | +| `model` | A model key. Omit it to use the default. | +| `idempotencyKey` | Send the same key on a retry and you get the same project back, not a second one. | + +Starting a project needs a paid plan (`402 SUBSCRIPTION_REQUIRED` otherwise). Limit: 10 projects per minute per account. + +TypeScript: `client.agent.createProject({ prompt })`. Python: `client.agent.create_project(prompt)`. diff --git a/agent-api/events.mdx b/agent-api/events.mdx new file mode 100644 index 0000000..80b1292 --- /dev/null +++ b/agent-api/events.mdx @@ -0,0 +1,32 @@ +--- +title: "Stream agent events" +openapi: "/api-reference/openapi.json GET /agent/projects/{id}/events" +description: "Server-Sent Events for a project's chat: text as it is written, tool calls, status, and a done event per run." +--- + +```bash +curl --fail-with-body -N "https://api.pre.dev/agent/projects/$PROJECT_ID/events" \ + -H "Authorization: Bearer $PREDEV_API_KEY" +``` + +## Event contract + +| Event | Payload | When | +| --- | --- | --- | +| `cursor` | `{ cursor }`, also sent as the SSE `id` | On connect, and after each finished message or run | +| `status` | `{ state: "running" \| "idle", agentStatus, runTitle }` | On connect, and whenever the agent's status changes | +| `message.delta` | `{ messageId, delta }` | The agent writes text | +| `message` | `{ messageId, role, content, completed, replayed? }` | A message is finished, or replayed from a cursor | +| `tool` | `{ messageId, tool, toolId, text, completed }` | The agent uses a tool | +| `done` | `{ state: "idle" }` | A run that was running has ended | +| `error` | `{ error, code }` | The stream cannot start or continue | + +Lines starting with `:` are heartbeats, sent every 15 seconds. They are not events. The stream stays open across runs, so close it when you are finished. + +## Resume after a disconnect + +Keep the last `cursor` you received. Reconnect with `?cursor=` or a `Last-Event-ID` header. The stream first sends every message that changed since that cursor, as `message` events with `replayed: true`, then live events. If you connect without a cursor, you get live events only. + +The SDKs do this for you: `client.agent.stream(projectId)` reconnects from the last cursor and, by default, ends after `done`. Use `sessionId` to follow a session other than Main. + +Limit: 30 new streams per minute per account. `503 BUSY` means the server is full; retry after a few seconds. diff --git a/agent-api/overview.mdx b/agent-api/overview.mdx new file mode 100644 index 0000000..d6a44ac --- /dev/null +++ b/agent-api/overview.mdx @@ -0,0 +1,71 @@ +--- +title: "Agent API" +description: "Drive the pre.dev coding agent over REST: create a project, send messages, stream events, build the plan, check status, and stop." +--- + +The Agent API runs the same coding agent as the web workspace, from your own code. Projects you create with it appear in your pre.dev dashboard. You can open any of them there and keep working. + +## The flow + +1. [Create a project](/agent-api/create-project) from a prompt. Save `projectId`. +2. [Stream events](/agent-api/events) to watch the agent plan and write code. +3. [Build](/agent-api/build) the next task, or all of them. +4. [Send messages](/agent-api/send-message) to steer it. [Check status](/agent-api/status) for progress and credits. [Stop](/agent-api/stop) it at any time. + +```bash +# 1. Create +PROJECT_ID=$(curl --fail-with-body -s https://api.pre.dev/agent/projects \ + -H "Authorization: Bearer $PREDEV_API_KEY" \ + -H "Content-Type: application/json" \ + -d '{"prompt": "A habit tracker with daily streaks", "mode": "plan"}' | jq -r .projectId) + +# 2. Watch (Ctrl-C when you see event: done) +curl -N "https://api.pre.dev/agent/projects/$PROJECT_ID/events" \ + -H "Authorization: Bearer $PREDEV_API_KEY" + +# 3. Build the next task +curl --fail-with-body -X POST "https://api.pre.dev/agent/projects/$PROJECT_ID/build" \ + -H "Authorization: Bearer $PREDEV_API_KEY" \ + -H "Content-Type: application/json" -d '{}' + +# 4. Progress +curl --fail-with-body "https://api.pre.dev/agent/projects/$PROJECT_ID/status" \ + -H "Authorization: Bearer $PREDEV_API_KEY" +``` + +The [TypeScript](/architect-agent/sdks/node#build-with-the-agent) and [Python](/architect-agent/sdks/python#build-with-the-agent) SDKs wrap every endpoint under `client.agent`. Their `stream()` reconnects and resumes for you. + +## Endpoints + +| Method | Path | Reference | +| --- | --- | --- | +| POST | `/agent/projects` | [Create a project](/agent-api/create-project) | +| POST | `/agent/projects/{id}/messages` | [Send a message](/agent-api/send-message) | +| GET | `/agent/projects/{id}/events` | [Stream agent events](/agent-api/events) | +| POST | `/agent/projects/{id}/build` | [Build the plan](/agent-api/build) | +| GET | `/agent/projects/{id}/status` | [Get project status](/agent-api/status) | +| POST | `/agent/projects/{id}/stop` | [Stop the agent](/agent-api/stop) | + +## Access, billing, and limits + +- **Key.** Use the same API key as every other endpoint (see [authentication](/api-reference/authentication)). It needs an active plan. +- **Projects.** A key can reach projects its account owns or is a member of. Sending, building, and stopping need edit access. Status and events need view access. +- **Credits.** Agent runs are billed like runs in the workspace: to the project's owner, or to the team for a team project. `maxCredits` on [build](/agent-api/build) caps one run. +- **Rate limits** per account per minute: 10 new projects, 30 messages, 20 build-next and 10 build-all calls, 30 new event streams, 120 status reads, 30 stops. A `429` carries `Retry-After`. + +## Errors + +Error bodies are `{ "error": "", "code": "" }`. + +| Status | Code | When | +| --- | --- | --- | +| `400` | `BAD_USER_INPUT` | A field is missing or invalid | +| `401` | | Missing or invalid key | +| `402` | `SUBSCRIPTION_REQUIRED`, `INSUFFICIENT_CREDITS` | No plan, or no credits on the paying account | +| `403` | `FORBIDDEN` | The key's account cannot act on this project | +| `404` | `NOT_FOUND` | No such project, or the session is not in it | +| `409` | `NO_SESSION`, `RUNNER_CHANGED` | The project has no chat session yet, or the session is moving between a computer and the cloud. Retry. | +| `429` | `RATE_LIMITED` | Over a per-minute limit | +| `503` | `AGENT_UNAVAILABLE`, `BUSY` | The agent could not start, or the server has too many streams. Retry. | + +See [errors and retries](/api-reference/errors) for retry rules. diff --git a/agent-api/send-message.mdx b/agent-api/send-message.mdx new file mode 100644 index 0000000..35a7e49 --- /dev/null +++ b/agent-api/send-message.mdx @@ -0,0 +1,25 @@ +--- +title: "Send a message" +openapi: "/api-reference/openapi.json POST /agent/projects/{id}/messages" +description: "Send the agent a message in a project's chat and start its turn." +--- + +```bash +curl --fail-with-body "https://api.pre.dev/agent/projects/$PROJECT_ID/messages" \ + -H "Authorization: Bearer $PREDEV_API_KEY" \ + -H "Content-Type: application/json" \ + -d '{"message": "Add reminders by email"}' +``` + +The call returns `202` once the agent has accepted the turn. If a turn is already running, the message waits behind it. The reply arrives on [the event stream](/agent-api/events). + +| Field | Meaning | +| --- | --- | +| `message` | What to say to the agent. | +| `sessionId` | A chat session in the project. Omit it to use the Main session. | +| `mode` | `auto` lets the agent act. `plan` limits it to planning. The setting stays for the project until you change it. | +| `model` | Switches the project to this model key before the turn. | + +Runs are billed to the project's owner (or team). If that account has no credits, the call returns `402 INSUFFICIENT_CREDITS`. Limit: 30 messages per minute per account. + +TypeScript: `client.agent.send(projectId, { message })`. Python: `client.agent.send(project_id, message)`. diff --git a/agent-api/status.mdx b/agent-api/status.mdx new file mode 100644 index 0000000..e8fc4e8 --- /dev/null +++ b/agent-api/status.mdx @@ -0,0 +1,20 @@ +--- +title: "Get project status" +openapi: "/api-reference/openapi.json GET /agent/projects/{id}/status" +description: "Plan progress, whether the agent is running, and credits used." +--- + +```bash +curl --fail-with-body "https://api.pre.dev/agent/projects/$PROJECT_ID/status" \ + -H "Authorization: Bearer $PREDEV_API_KEY" +``` + +| Field | Meaning | +| --- | --- | +| `state` | `running` while the agent works; otherwise `idle` | +| `agentStatus` | What the agent is doing now, in a few words | +| `progress` | `percent`, `done`, `total`, `left`; `ready` counts built work whose feature checks pass | +| `features` | Each planned feature with its status and story counts | +| `creditsUsed` | Credits spent on this project so far | + +Polling is fine for dashboards (limit: 120 calls per minute per account). To watch a run as it happens, use [the event stream](/agent-api/events). diff --git a/agent-api/stop.mdx b/agent-api/stop.mdx new file mode 100644 index 0000000..7c850b1 --- /dev/null +++ b/agent-api/stop.mdx @@ -0,0 +1,16 @@ +--- +title: "Stop the agent" +openapi: "/api-reference/openapi.json POST /agent/projects/{id}/stop" +description: "Stop the agent's running turn or build." +--- + +```bash +curl --fail-with-body -X POST "https://api.pre.dev/agent/projects/$PROJECT_ID/stop" \ + -H "Authorization: Bearer $PREDEV_API_KEY" \ + -H "Content-Type: application/json" \ + -d '{}' +``` + +Send `sessionId` to stop one session. Without it, every run on the project stops. `stopped: false` means nothing was running. Work the agent already saved stays. + +TypeScript: `client.agent.stop(projectId)`. Python: `client.agent.stop(project_id)`. diff --git a/api-reference/openapi.json b/api-reference/openapi.json index 5ec45f7..0de587d 100644 --- a/api-reference/openapi.json +++ b/api-reference/openapi.json @@ -2,7 +2,7 @@ "openapi": "3.1.0", "info": { "title": "pre.dev API", - "description": "Public REST API for software specifications, browser automation, and credit balance. Base URL: https://api.pre.dev. MCP is documented separately at https://docs.pre.dev/mcp/tools.", + "description": "Public REST API for the coding agent, software specifications, browser automation, and credit balance. Base URL: https://api.pre.dev. MCP is documented separately at https://docs.pre.dev/mcp/tools.", "version": "1.1.0", "contact": { "name": "pre.dev Support", @@ -2149,6 +2149,957 @@ } ] } + }, + "/agent/projects": { + "post": { + "operationId": "agentCreateProject", + "tags": [ + "Agent" + ], + "summary": "Create a project from a prompt", + "description": "Creates a project and starts the coding agent on it. Returns at once; follow the work with GET /agent/projects/{id}/events.", + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AgentCreateProjectRequest" + }, + "example": { + "prompt": "A habit tracker with daily streaks", + "mode": "plan" + } + } + } + }, + "responses": { + "201": { + "description": "Project created (or the one an earlier call with the same idempotencyKey created).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AgentProject" + }, + "example": { + "projectId": "64b7f3e1c2a9d5e6f8a01234", + "sessionId": "64b7f3e1c2a9d5e6f8a05678" + } + } + } + }, + "400": { + "description": "Invalid request body.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + }, + "example": { + "code": "BAD_USER_INPUT", + "error": "prompt is required" + } + } + } + }, + "401": { + "description": "Missing, invalid, or ineligible authentication.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + }, + "examples": { + "missing_key": { + "summary": "No key sent", + "value": { + "error": "Missing API key", + "message": "Please provide an API key via Authorization: Bearer header or x-api-key header" + } + }, + "invalid_key": { + "summary": "Unknown key", + "value": { + "error": "Authentication failed", + "message": "Invalid API key" + } + } + } + } + } + }, + "402": { + "description": "A paid plan is needed to start a project.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + }, + "example": { + "error": "Subscribe to start a project.", + "code": "SUBSCRIPTION_REQUIRED" + } + } + } + }, + "429": { + "description": "More than 10 createProject per minute for this account. Retry-After says when to retry.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + }, + "example": { + "error": "Rate limit exceeded: 10 createProject requests per minute", + "code": "RATE_LIMITED" + } + } + }, + "headers": { + "Retry-After": { + "schema": { + "type": "integer" + }, + "description": "Seconds until the window resets." + } + } + } + }, + "security": [ + { + "apiKeyAuth": [] + }, + { + "xApiKey": [] + } + ], + "x-codeSamples": [ + { + "lang": "cURL", + "source": "curl --fail-with-body -X POST \"https://api.pre.dev/agent/projects\" \\\n -H \"Authorization: Bearer $PREDEV_API_KEY\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\"prompt\":\"A habit tracker with daily streaks\",\"mode\":\"plan\"}'" + } + ] + } + }, + "/agent/projects/{id}/messages": { + "post": { + "operationId": "agentSendMessage", + "tags": [ + "Agent" + ], + "summary": "Send the agent a message", + "description": "Saves the message and starts (or queues) the agent's turn. Returns 202 once the agent accepted it.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "description": "Project ID from POST /agent/projects.", + "pattern": "^[a-fA-F0-9]{24}$" + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AgentSendMessageRequest" + }, + "example": { + "message": "Add reminders by email", + "mode": "auto" + } + } + } + }, + "responses": { + "202": { + "description": "Accepted. Stream the reply from the events endpoint.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AgentMessageAccepted" + }, + "example": { + "sessionId": "64b7f3e1c2a9d5e6f8a05678" + } + } + } + }, + "400": { + "description": "Invalid request body.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + }, + "example": { + "code": "BAD_USER_INPUT", + "error": "mode must be one of auto, plan" + } + } + } + }, + "401": { + "description": "Missing, invalid, or ineligible authentication.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + }, + "examples": { + "missing_key": { + "summary": "No key sent", + "value": { + "error": "Missing API key", + "message": "Please provide an API key via Authorization: Bearer header or x-api-key header" + } + }, + "invalid_key": { + "summary": "Unknown key", + "value": { + "error": "Authentication failed", + "message": "Invalid API key" + } + } + } + } + } + }, + "402": { + "description": "Not enough credits on the account that pays for this project.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + }, + "example": { + "error": "Out of credits", + "code": "INSUFFICIENT_CREDITS" + } + } + } + }, + "403": { + "description": "The key's account is not an owner or member of this project with the needed role.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + }, + "example": { + "error": "Forbidden: you do not have access to this project", + "code": "FORBIDDEN" + } + } + } + }, + "404": { + "description": "No such project, or the session is not in it.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + }, + "example": { + "error": "Project not found", + "code": "NOT_FOUND" + } + } + } + }, + "429": { + "description": "More than 30 sendMessage per minute for this account. Retry-After says when to retry.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + }, + "example": { + "error": "Rate limit exceeded: 30 sendMessage requests per minute", + "code": "RATE_LIMITED" + } + } + }, + "headers": { + "Retry-After": { + "schema": { + "type": "integer" + }, + "description": "Seconds until the window resets." + } + } + } + }, + "security": [ + { + "apiKeyAuth": [] + }, + { + "xApiKey": [] + } + ], + "x-codeSamples": [ + { + "lang": "cURL", + "source": "curl --fail-with-body -X POST \"https://api.pre.dev/agent/projects/64b7f3e1c2a9d5e6f8a01234/messages\" \\\n -H \"Authorization: Bearer $PREDEV_API_KEY\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\"message\":\"Add reminders by email\"}'" + } + ] + } + }, + "/agent/projects/{id}/events": { + "get": { + "operationId": "agentEvents", + "tags": [ + "Agent" + ], + "summary": "Stream agent events (SSE)", + "description": "Server-Sent Events: message.delta, message, tool, status, done, cursor, error. A comment line (\": ping\") every 15 seconds keeps the connection open. Pass the last cursor (query or Last-Event-ID) to get every message that changed since, then live events.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "description": "Project ID from POST /agent/projects.", + "pattern": "^[a-fA-F0-9]{24}$" + } + }, + { + "name": "sessionId", + "in": "query", + "required": false, + "schema": { + "type": "string", + "description": "A chat session in the project. Default: the Main session.", + "pattern": "^[a-fA-F0-9]{24}$" + } + }, + { + "name": "cursor", + "in": "query", + "required": false, + "schema": { + "type": "string", + "description": "The data.cursor of the last cursor event you saw." + } + }, + { + "name": "Last-Event-ID", + "in": "header", + "required": false, + "schema": { + "type": "string", + "description": "Same as cursor; EventSource-style clients send it on reconnect." + } + } + ], + "responses": { + "200": { + "description": "SSE stream. Errors after the headers arrive as an error event.", + "content": { + "text/event-stream": { + "schema": { + "type": "string" + }, + "example": "id: W1siNjRiN2YiLDNdXQ\nevent: cursor\ndata: {\"cursor\":\"W1siNjRiN2YiLDNdXQ\"}\n\nevent: status\ndata: {\"state\":\"running\",\"agentStatus\":\"Planning\",\"runTitle\":null}\n\nevent: message.delta\ndata: {\"messageId\":\"64b7f3e1c2a9d5e6f8a01234\",\"delta\":\"I'll start with\"}\n\nevent: tool\ndata: {\"messageId\":\"64b7f3e1c2a9d5e6f8a05678\",\"tool\":\"write_file\",\"toolId\":\"t1\",\"text\":\"Using tool: write_file\",\"completed\":false}\n\nevent: message\ndata: {\"messageId\":\"64b7f3e1c2a9d5e6f8a01234\",\"role\":\"assistant\",\"content\":\"I'll start with the data model.\",\"completed\":true}\n\nevent: done\ndata: {\"state\":\"idle\"}\n\n" + } + } + }, + "401": { + "description": "Missing, invalid, or ineligible authentication.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + }, + "examples": { + "missing_key": { + "summary": "No key sent", + "value": { + "error": "Missing API key", + "message": "Please provide an API key via Authorization: Bearer header or x-api-key header" + } + }, + "invalid_key": { + "summary": "Unknown key", + "value": { + "error": "Authentication failed", + "message": "Invalid API key" + } + } + } + } + } + }, + "403": { + "description": "The key's account is not an owner or member of this project with the needed role.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + }, + "example": { + "error": "Forbidden: you do not have access to this project", + "code": "FORBIDDEN" + } + } + } + }, + "404": { + "description": "No such project, or the session is not in it.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + }, + "example": { + "error": "Project not found", + "code": "NOT_FOUND" + } + } + } + }, + "429": { + "description": "More than 30 events per minute for this account. Retry-After says when to retry.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + }, + "example": { + "error": "Rate limit exceeded: 30 events requests per minute", + "code": "RATE_LIMITED" + } + } + }, + "headers": { + "Retry-After": { + "schema": { + "type": "integer" + }, + "description": "Seconds until the window resets." + } + } + }, + "503": { + "description": "Too many open streams on this server. Retry shortly.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + }, + "example": { + "error": "Too many open streams. Retry shortly.", + "code": "BUSY" + } + } + } + } + }, + "security": [ + { + "apiKeyAuth": [] + }, + { + "xApiKey": [] + } + ], + "x-codeSamples": [ + { + "lang": "cURL", + "source": "curl --fail-with-body -N \"https://api.pre.dev/agent/projects/64b7f3e1c2a9d5e6f8a01234/events\" \\\n -H \"Authorization: Bearer $PREDEV_API_KEY\"" + } + ] + } + }, + "/agent/projects/{id}/build": { + "post": { + "operationId": "agentBuild", + "tags": [ + "Agent" + ], + "summary": "Build the next task, or all of them", + "description": "Starts a build run from the project's plan: the next task (or a custom one), or every remaining task with all: true.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "description": "Project ID from POST /agent/projects.", + "pattern": "^[a-fA-F0-9]{24}$" + } + } + ], + "requestBody": { + "required": false, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AgentBuildRequest" + }, + "example": { + "maxCredits": 50 + } + } + } + }, + "responses": { + "202": { + "description": "Build started.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AgentBuildAccepted" + }, + "example": { + "sessionId": "64b7f3e1c2a9d5e6f8a05678", + "kind": "next" + } + } + } + }, + "400": { + "description": "Invalid request body.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + }, + "example": { + "code": "BAD_USER_INPUT", + "error": "maxCredits must be a positive number" + } + } + } + }, + "401": { + "description": "Missing, invalid, or ineligible authentication.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + }, + "examples": { + "missing_key": { + "summary": "No key sent", + "value": { + "error": "Missing API key", + "message": "Please provide an API key via Authorization: Bearer header or x-api-key header" + } + }, + "invalid_key": { + "summary": "Unknown key", + "value": { + "error": "Authentication failed", + "message": "Invalid API key" + } + } + } + } + } + }, + "402": { + "description": "Not enough credits on the account that pays for this project.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + }, + "example": { + "error": "Out of credits", + "code": "INSUFFICIENT_CREDITS" + } + } + } + }, + "403": { + "description": "The key's account is not an owner or member of this project with the needed role.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + }, + "example": { + "error": "Forbidden: you do not have access to this project", + "code": "FORBIDDEN" + } + } + } + }, + "404": { + "description": "No such project, or the session is not in it.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + }, + "example": { + "error": "Project not found", + "code": "NOT_FOUND" + } + } + } + }, + "429": { + "description": "More than 20 buildNext per minute for this account. Retry-After says when to retry.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + }, + "example": { + "error": "Rate limit exceeded: 20 buildNext requests per minute", + "code": "RATE_LIMITED" + } + } + }, + "headers": { + "Retry-After": { + "schema": { + "type": "integer" + }, + "description": "Seconds until the window resets." + } + } + }, + "503": { + "description": "The project's agent could not be started. Retry.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + }, + "example": { + "error": "Build agent unavailable. No sandbox or BACKUP_AGENT_URL could handle the request.", + "code": "AGENT_UNAVAILABLE" + } + } + } + } + }, + "security": [ + { + "apiKeyAuth": [] + }, + { + "xApiKey": [] + } + ], + "x-codeSamples": [ + { + "lang": "cURL", + "source": "curl --fail-with-body -X POST \"https://api.pre.dev/agent/projects/64b7f3e1c2a9d5e6f8a01234/build\" \\\n -H \"Authorization: Bearer $PREDEV_API_KEY\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\"maxCredits\":50}'" + } + ] + } + }, + "/agent/projects/{id}/status": { + "get": { + "operationId": "agentStatus", + "tags": [ + "Agent" + ], + "summary": "Get project status", + "description": "Plan progress, whether the agent is running, and credits used so far.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "description": "Project ID from POST /agent/projects.", + "pattern": "^[a-fA-F0-9]{24}$" + } + }, + { + "name": "sessionId", + "in": "query", + "required": false, + "schema": { + "type": "string", + "description": "A chat session in the project. Default: the Main session.", + "pattern": "^[a-fA-F0-9]{24}$" + } + } + ], + "responses": { + "200": { + "description": "Current status.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AgentStatus" + }, + "example": { + "projectId": "64b7f3e1c2a9d5e6f8a01234", + "sessionId": "64b7f3e1c2a9d5e6f8a05678", + "state": "running", + "agentStatus": "Writing the habits API", + "runTitle": "Habit tracker", + "chatMode": "auto", + "progress": { + "percent": 40, + "done": 2, + "total": 5, + "left": 3, + "ready": 1 + }, + "summary": "2 of 5 features built", + "features": [ + { + "id": "f1", + "name": "Sign in", + "status": "works", + "statusText": "Works, checked 2 min ago", + "doneStories": 2, + "totalStories": 2 + } + ], + "creditsUsed": 12.5 + } + } + } + }, + "401": { + "description": "Missing, invalid, or ineligible authentication.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + }, + "examples": { + "missing_key": { + "summary": "No key sent", + "value": { + "error": "Missing API key", + "message": "Please provide an API key via Authorization: Bearer header or x-api-key header" + } + }, + "invalid_key": { + "summary": "Unknown key", + "value": { + "error": "Authentication failed", + "message": "Invalid API key" + } + } + } + } + } + }, + "403": { + "description": "The key's account is not an owner or member of this project with the needed role.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + }, + "example": { + "error": "Forbidden: you do not have access to this project", + "code": "FORBIDDEN" + } + } + } + }, + "404": { + "description": "No such project, or the session is not in it.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + }, + "example": { + "error": "Project not found", + "code": "NOT_FOUND" + } + } + } + }, + "429": { + "description": "More than 120 status per minute for this account. Retry-After says when to retry.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + }, + "example": { + "error": "Rate limit exceeded: 120 status requests per minute", + "code": "RATE_LIMITED" + } + } + }, + "headers": { + "Retry-After": { + "schema": { + "type": "integer" + }, + "description": "Seconds until the window resets." + } + } + } + }, + "security": [ + { + "apiKeyAuth": [] + }, + { + "xApiKey": [] + } + ], + "x-codeSamples": [ + { + "lang": "cURL", + "source": "curl --fail-with-body \"https://api.pre.dev/agent/projects/64b7f3e1c2a9d5e6f8a01234/status\" \\\n -H \"Authorization: Bearer $PREDEV_API_KEY\"" + } + ] + } + }, + "/agent/projects/{id}/stop": { + "post": { + "operationId": "agentStop", + "tags": [ + "Agent" + ], + "summary": "Stop the agent", + "description": "Stops the running turn or build. Work already saved stays.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "description": "Project ID from POST /agent/projects.", + "pattern": "^[a-fA-F0-9]{24}$" + } + } + ], + "requestBody": { + "required": false, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AgentStopRequest" + }, + "example": { + "sessionId": "64b7f3e1c2a9d5e6f8a05678" + } + } + } + }, + "responses": { + "200": { + "description": "Stopped, or nothing was running.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AgentStopResult" + }, + "example": { + "stopped": true, + "message": "Session stopped" + } + } + } + }, + "401": { + "description": "Missing, invalid, or ineligible authentication.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + }, + "examples": { + "missing_key": { + "summary": "No key sent", + "value": { + "error": "Missing API key", + "message": "Please provide an API key via Authorization: Bearer header or x-api-key header" + } + }, + "invalid_key": { + "summary": "Unknown key", + "value": { + "error": "Authentication failed", + "message": "Invalid API key" + } + } + } + } + } + }, + "403": { + "description": "The key's account is not an owner or member of this project with the needed role.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + }, + "example": { + "error": "Forbidden: you do not have access to this project", + "code": "FORBIDDEN" + } + } + } + }, + "404": { + "description": "No such project, or the session is not in it.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + }, + "example": { + "error": "Project not found", + "code": "NOT_FOUND" + } + } + } + }, + "429": { + "description": "More than 30 stop per minute for this account. Retry-After says when to retry.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + }, + "example": { + "error": "Rate limit exceeded: 30 stop requests per minute", + "code": "RATE_LIMITED" + } + } + }, + "headers": { + "Retry-After": { + "schema": { + "type": "integer" + }, + "description": "Seconds until the window resets." + } + } + } + }, + "security": [ + { + "apiKeyAuth": [] + }, + { + "xApiKey": [] + } + ], + "x-codeSamples": [ + { + "lang": "cURL", + "source": "curl --fail-with-body -X POST \"https://api.pre.dev/agent/projects/64b7f3e1c2a9d5e6f8a01234/stop\" \\\n -H \"Authorization: Bearer $PREDEV_API_KEY\" \\\n -H \"Content-Type: application/json\" \\\n -d '{}'" + } + ] + } } }, "components": { @@ -4710,10 +5661,310 @@ "description": "The plan as Markdown for a coding agent." } } + }, + "AgentCreateProjectRequest": { + "type": "object", + "required": [ + "prompt" + ], + "additionalProperties": false, + "properties": { + "prompt": { + "type": "string", + "minLength": 1, + "maxLength": 100000, + "description": "What to build, in plain words." + }, + "mode": { + "type": "string", + "enum": [ + "build", + "plan" + ], + "default": "build", + "description": "build starts building right away; plan writes the plan first." + }, + "model": { + "type": "string", + "maxLength": 200, + "description": "A model key; omit for the default. Premium models need a plan that includes them." + }, + "idempotencyKey": { + "type": "string", + "maxLength": 200, + "description": "Retrying with the same key returns the same project instead of creating another." + } + } + }, + "AgentProject": { + "type": "object", + "required": [ + "projectId", + "sessionId" + ], + "properties": { + "projectId": { + "type": "string", + "pattern": "^[a-fA-F0-9]{24}$" + }, + "sessionId": { + "type": [ + "string", + "null" + ], + "description": "The project's Main chat session." + } + } + }, + "AgentSendMessageRequest": { + "type": "object", + "required": [ + "message" + ], + "additionalProperties": false, + "properties": { + "message": { + "type": "string", + "minLength": 1, + "maxLength": 100000 + }, + "sessionId": { + "type": "string", + "pattern": "^[a-fA-F0-9]{24}$", + "description": "Default: the Main session." + }, + "mode": { + "type": "string", + "enum": [ + "auto", + "plan" + ], + "description": "auto lets the agent act; plan restricts it to planning. Sticks for the project until changed." + }, + "model": { + "type": "string", + "maxLength": 200, + "description": "Switch the project to this model key first." + } + } + }, + "AgentMessageAccepted": { + "type": "object", + "required": [ + "sessionId" + ], + "properties": { + "sessionId": { + "type": [ + "string", + "null" + ] + }, + "messageId": { + "type": "string", + "description": "The agent's reply message, when known before the call returned." + } + } + }, + "AgentBuildRequest": { + "type": "object", + "additionalProperties": false, + "properties": { + "all": { + "type": "boolean", + "default": false, + "description": "true builds every remaining task; false builds the next one." + }, + "task": { + "type": "string", + "maxLength": 100000, + "description": "Build next only: a custom task instead of the next planned one." + }, + "sessionId": { + "type": "string", + "pattern": "^[a-fA-F0-9]{24}$", + "description": "Build next only. Default: the Main session." + }, + "maxCredits": { + "type": "number", + "exclusiveMinimum": 0, + "description": "Stop the run once it has spent this many credits on the project." + } + } + }, + "AgentBuildAccepted": { + "type": "object", + "required": [ + "sessionId", + "kind" + ], + "properties": { + "sessionId": { + "type": [ + "string", + "null" + ] + }, + "kind": { + "type": "string", + "enum": [ + "next", + "all" + ] + }, + "message": { + "type": "string" + } + } + }, + "AgentFeatureStatus": { + "type": "object", + "required": [ + "id", + "name", + "status" + ], + "properties": { + "id": { + "type": "string" + }, + "name": { + "type": "string" + }, + "status": { + "type": "string" + }, + "statusText": { + "type": "string" + }, + "doneStories": { + "type": "integer" + }, + "totalStories": { + "type": "integer" + } + } + }, + "AgentStatus": { + "type": "object", + "required": [ + "projectId", + "state", + "progress", + "features", + "creditsUsed" + ], + "properties": { + "projectId": { + "type": "string" + }, + "sessionId": { + "type": [ + "string", + "null" + ] + }, + "state": { + "type": "string", + "enum": [ + "running", + "idle" + ] + }, + "agentStatus": { + "type": [ + "string", + "null" + ], + "description": "What the agent is doing now, in a few words." + }, + "runTitle": { + "type": [ + "string", + "null" + ] + }, + "chatMode": { + "type": "string", + "enum": [ + "auto", + "plan" + ] + }, + "progress": { + "type": "object", + "required": [ + "percent", + "done", + "total" + ], + "properties": { + "percent": { + "type": "number" + }, + "done": { + "type": "integer" + }, + "total": { + "type": "integer" + }, + "left": { + "type": "integer" + }, + "ready": { + "type": "integer", + "description": "Built and passing their feature checks." + } + } + }, + "summary": { + "type": "string" + }, + "features": { + "type": "array", + "items": { + "$ref": "#/components/schemas/AgentFeatureStatus" + } + }, + "creditsUsed": { + "type": "number", + "description": "Credits spent on this project so far." + } + } + }, + "AgentStopRequest": { + "type": "object", + "additionalProperties": false, + "properties": { + "sessionId": { + "type": "string", + "pattern": "^[a-fA-F0-9]{24}$", + "description": "Stop one session. Omit to stop every run on the project." + } + } + }, + "AgentStopResult": { + "type": "object", + "required": [ + "stopped", + "message" + ], + "properties": { + "stopped": { + "type": "boolean", + "description": "false when nothing was running." + }, + "message": { + "type": "string" + } + } } } }, "tags": [ + { + "name": "Agent" + }, { "name": "Specifications" }, diff --git a/api-reference/overview.mdx b/api-reference/overview.mdx index 77662b8..b5dbf68 100644 --- a/api-reference/overview.mdx +++ b/api-reference/overview.mdx @@ -1,6 +1,6 @@ --- title: "API overview" -description: "The public REST API for specifications, browser automation, AI model calls, and credit balances." +description: "The public REST API for the coding agent, specifications, browser automation, AI model calls, and credit balances." --- import ApiKeyLocation from "/snippets/api-key-location.mdx"; @@ -29,6 +29,19 @@ Read [authentication](/api-reference/authentication) and [errors](/api-reference | GET | `/find-specs` | [Search specifications](/architect-agent/api/find-specs) | | GET | `/credits-balance` | [Credit balance](/architect-agent/api/credits-balance) | +## Agent API + +| Method | Path | Reference | +| --- | --- | --- | +| POST | `/agent/projects` | [Create a project](/agent-api/create-project) | +| POST | `/agent/projects/{id}/messages` | [Send a message](/agent-api/send-message) | +| GET | `/agent/projects/{id}/events` | [Stream agent events (SSE)](/agent-api/events) | +| POST | `/agent/projects/{id}/build` | [Build the plan](/agent-api/build) | +| GET | `/agent/projects/{id}/status` | [Project status](/agent-api/status) | +| POST | `/agent/projects/{id}/stop` | [Stop the agent](/agent-api/stop) | + +See the [Agent API overview](/agent-api/overview) for the flow, access, and limits. + ## Browser Agents | Method | Path | Reference | @@ -60,7 +73,7 @@ Specifications, browser runs, and video generation run as jobs. All three follow ## 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 live browser URLs, existing-run SSE, and browser idempotency keys. +The [TypeScript SDK](/architect-agent/sdks/node) and [Python SDK](/architect-agent/sdks/python) wrap the Agent API, specification, and browser operations. Use direct HTTP for endpoints or headers without a wrapper, including live browser URLs, existing-run SSE, and browser idempotency keys. The [MCP server](/architect-agent/mcp-setup) exposes twelve primary tools, including the memory 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). diff --git a/architect-agent/overview.mdx b/architect-agent/overview.mdx index 683f89a..186427b 100644 --- a/architect-agent/overview.mdx +++ b/architect-agent/overview.mdx @@ -37,4 +37,4 @@ Times and credit usage are estimates, not fixed limits or quotes. Use the return - [Status and results](/architect-agent/api/spec-status): polling and failure handling. - [Project plan](/architect-agent/api/get-plan): what is built, what works, what is left, and where it lives in the code. - [List](/architect-agent/api/list-specs) or [search](/architect-agent/api/find-specs): retrieve existing work. -- [Python](/architect-agent/sdks/python) and [Node](/architect-agent/sdks/node): official SDKs. +- [Python](/architect-agent/sdks/python) and [TypeScript](/architect-agent/sdks/node): official SDKs. diff --git a/architect-agent/quickstart.mdx b/architect-agent/quickstart.mdx index 41f5226..65ba737 100644 --- a/architect-agent/quickstart.mdx +++ b/architect-agent/quickstart.mdx @@ -71,4 +71,4 @@ When `status` is `completed`, use: 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). +For a complete polling example, use the [Python SDK guide](/architect-agent/sdks/python) or [TypeScript SDK guide](/architect-agent/sdks/node). diff --git a/architect-agent/sdks/node.mdx b/architect-agent/sdks/node.mdx index 7406613..c7698ed 100644 --- a/architect-agent/sdks/node.mdx +++ b/architect-agent/sdks/node.mdx @@ -1,21 +1,80 @@ --- -title: "Node.js SDK" -description: "Generate specifications and run browser tasks with the published predev-api TypeScript client." +title: "TypeScript SDK" +description: "Build with the coding agent, generate specifications, and run browser tasks with the predev-api TypeScript client." icon: "node-js" --- -import SdkInstall from "/snippets/sdk-install.mdx"; +## Install - +```bash +npm install predev-api +``` -The package is ESM and supports Node.js 18+. This guide targets published **1.1.0**. +The package is ESM, ships its own type definitions, and supports Node.js 18+. This guide targets **1.2.0**. `client.agent` needs 1.2.0 or later. -## Generate and wait for a specification +## Set up the client ```typescript import { PredevAPI } from 'predev-api'; const client = new PredevAPI({ apiKey: process.env.PREDEV_API_KEY! }); +``` + +The constructor takes `apiKey` and an optional `baseUrl` (default `https://api.pre.dev`). It has no timeout, retry, or custom-header option. Use direct HTTP when you need those controls. Get a key from [Integrations](/api-reference/authentication). + +## Build with the agent + +`client.agent` runs the pre.dev coding agent: create a project from a prompt, stream its work, build the plan, and check progress. Each method calls one [Agent API](/agent-api/overview) endpoint. + +```typescript +// 1. Create a project. The agent starts planning right away. +const project = await client.agent.createProject({ + prompt: 'A habit tracker with daily streaks and reminders', + mode: 'plan', // 'build' (default) builds right away +}); +console.log('Save this project ID:', project.projectId); + +// 2. Stream the agent's work until this run is done. +for await (const ev of client.agent.stream(project.projectId)) { + if (ev.event === 'message.delta') process.stdout.write(ev.data.delta); + else if (ev.event === 'tool') console.log(`\n[${ev.data.tool}]`); + else if (ev.event === 'status') console.log(`\n(${ev.data.agentStatus ?? ev.data.state})`); +} + +// 3. Build the next task in the plan, capped at 50 credits, and follow it. +await client.agent.buildNext(project.projectId, { maxCredits: 50 }); +for await (const ev of client.agent.stream(project.projectId)) { + if (ev.event === 'message') console.log(ev.data.content); +} + +// 4. Check progress and spend. +const progress = await client.agent.status(project.projectId); +console.log(`${progress.progress.percent}% built, ${progress.creditsUsed} credits used`); +for (const feature of progress.features) console.log(feature.name, feature.statusText); +``` + +Steer the agent with `send`, and stop it with `stop`: + +```typescript +await client.agent.send(project.projectId, { message: 'Use email reminders, not push.' }); +await client.agent.stop(project.projectId); +``` + +| Method | Parameters | Return | +| --- | --- | --- | +| `agent.createProject(options)` | `prompt`; optional `mode` (`build` or `plan`), `model`, `idempotencyKey` | `Promise<{ projectId, sessionId }>` | +| `agent.send(projectId, options)` | `message`; optional `sessionId`, `mode` (`auto` or `plan`), `model` | `Promise<{ sessionId, messageId? }>` | +| `agent.stream(projectId, options)` | Optional `sessionId`, `cursor`, `untilDone` (default `true`), `maxReconnects` (default 5), `signal` | Async generator of events | +| `agent.buildNext(projectId, options)` | Optional `task`, `sessionId`, `maxCredits` | `Promise<{ sessionId, kind }>` | +| `agent.buildAll(projectId, options)` | Optional `maxCredits` | `Promise<{ sessionId, kind }>` | +| `agent.status(projectId, options)` | Optional `sessionId` | `Promise` | +| `agent.stop(projectId, options)` | Optional `sessionId` | `Promise<{ stopped, message }>` | + +`stream` yields `{ event, data }` for `message.delta`, `message`, `tool`, `status`, `done`, and `cursor` (see [the event contract](/agent-api/events#event-contract)). It skips heartbeats and ends after `done`. If the connection drops, it reconnects from the last cursor. To pick up later in another process, save the last `cursor` event's `data.cursor` and pass it as `cursor`. An `error` event raises an exception. Pass an `AbortSignal` as `signal` to stop listening early. + +## Specifications + +```typescript const job = await client.fastSpecAsync({ input: 'Build a team task manager with projects and assignees.', currentContext: 'Use TypeScript and preserve organization-scoped access.', @@ -39,8 +98,6 @@ const spec = await waitForSpec(); console.log(spec.codingAgentSpecMarkdown); ``` -## Method reference - | Method | Parameters | Return | | --- | --- | --- | | `fastSpec(options)` | `input`, optional `currentContext`, `docURLs`, `file` | `Promise` | @@ -50,30 +107,23 @@ console.log(spec.codingAgentSpecMarkdown); | `getSpecStatus(specId)` | Specification ID | `Promise` | | `listSpecs(params)` | Optional `limit`, `skip`, `endpoint`, `status` | `Promise` | | `findSpecs(params)` | Required `query`; same filters | `Promise` | -| `getCreditsBalance()` | None | `Promise` | -| `browserAgent(tasks, options)` | Task array; optional `concurrency`, `stream`, `async` | A Promise, or an async generator when `stream: true` | -| `getBrowserAgent(id, options)` | Run ID; optional `includeEvents` | A Promise of the run | -| `listBrowserAgents(params)` | Optional `limit`, `skip`, `status` | A Promise of `batches`, `total`, `hasMore` | -| `browserAgentStatus()` | None | A Promise of your queue and `cap` | -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. +A polling deadline does not abort an in-flight SDK request. -## Specification history and credits +### History ```typescript 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 +### 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. +Pass a **Blob with an accepted MIME type**. The `{ data: Buffer, name }` alternative is encoded as `application/octet-stream`, which the API's file filter does not accept. ```typescript import { readFile } from 'node:fs/promises'; @@ -89,7 +139,16 @@ 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). -## Run browser tasks and poll +## Browser agents + +| Method | Parameters | Return | +| --- | --- | --- | +| `browserAgent(tasks, options)` | Task array; optional `concurrency`, `stream`, `async` | A Promise, or an async generator when `stream: true` | +| `getBrowserAgent(id, options)` | Run ID; optional `includeEvents` | A Promise of the run | +| `listBrowserAgents(params)` | Optional `limit`, `skip`, `status` | A Promise of `batches`, `total`, `hasMore` | +| `browserAgentStatus()` | None | A Promise of your queue and `cap` | + +### Run tasks and poll ```typescript const tasks = [{ @@ -121,9 +180,9 @@ for (const task of run.results) { } ``` -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. 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. +Use batch `status` to detect completion and inspect every task result. The TypeScript declarations lag some REST fields, including running stubs and nullable result slots; guard missing values at runtime. 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 browser submission +### Stream a new submission ```typescript let sawDone = false; @@ -140,7 +199,7 @@ 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). -## Browser history and evidence +### History and evidence ```typescript const queue = await client.browserAgentStatus(); @@ -155,6 +214,15 @@ console.log(evidence.status); 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. +## Credits + +```typescript +const balance = await client.getCreditsBalance(); +console.log(balance.creditsRemaining); +``` + +`getCreditsBalance()` reads the key's account or organization balance. For one agent project's spend, read `creditsUsed` from `client.agent.status(projectId)`. + ## Errors ```typescript @@ -167,12 +235,14 @@ import { } from 'predev-api'; try { - await client.listSpecs({ limit: 20 }); + await client.agent.buildNext(project.projectId); } catch (error) { - if (error instanceof AuthenticationError) { - console.error('Check the API key and account access.'); + if (error instanceof InsufficientCreditsError) { + console.error(error.message, error.actionUrl); } else if (error instanceof RateLimitError) { console.error('Back off before retrying.'); + } else if (error instanceof AuthenticationError) { + console.error('Check the API key and account access.'); } else if (error instanceof PredevAPIError) { console.error(error.message); } else { @@ -183,9 +253,7 @@ try { try { await client.browserAgent(tasks, { async: true }); } catch (error) { - if (error instanceof InsufficientCreditsError) { - console.error(error.message, error.actionUrl); - } else if (error instanceof QueueFullError) { + if (error instanceof QueueFullError) { console.error('Wait for tasks to finish before submitting more work.'); } else if (error instanceof PredevAPIError) { console.error(error.message); @@ -195,6 +263,6 @@ try { } ``` -The base exception has no `statusCode` property. Browser gate errors have typed subclasses; see [errors and retries](/api-reference/errors). An Architect `402` without a machine-readable browser gate code raises `PredevAPIError`. 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. +The base exception has no `statusCode` property. Errors with a machine-readable `code` (`RATE_LIMITED`, `INSUFFICIENT_CREDITS`, `SUBSCRIPTION_REQUIRED`, `QUEUE_FULL`, `BATCH_TOO_LARGE`) raise typed subclasses. Any other code, such as the Agent API's `NOT_FOUND` or `FORBIDDEN`, raises `PredevAPIError` with the server's message. See [errors and retries](/api-reference/errors). Use [direct REST](/browser-agents/api/run-task#idempotency) for a browser idempotency key; `agent.createProject` takes its own `idempotencyKey`. See the [npm package](https://www.npmjs.com/package/predev-api) or the [SDK source](https://github.com/predotdev/predev-api). diff --git a/architect-agent/sdks/overview.mdx b/architect-agent/sdks/overview.mdx index 8ff666e..8403558 100644 --- a/architect-agent/sdks/overview.mdx +++ b/architect-agent/sdks/overview.mdx @@ -1,42 +1,91 @@ --- title: "SDKs" -description: "The official Node.js and Python SDKs for specifications and browser tasks." +description: "The official TypeScript and Python SDKs: build with the coding agent, generate specifications, and run browser tasks." --- import SdkInstall from "/snippets/sdk-install.mdx"; -Both SDKs use the package name **`predev-api`** and cover specification generation and Browser Agents. +Both SDKs use the package name **`predev-api`**. Each covers the coding agent (`client.agent`), specifications, browser agents, and the credit balance. + +## Install -| | Node.js / TypeScript | Python | +## Set up the client + + +```typescript TypeScript +import { PredevAPI } from 'predev-api'; + +const client = new PredevAPI({ apiKey: process.env.PREDEV_API_KEY! }); +``` +```python Python +import os +from predev_api import PredevAPI + +client = PredevAPI(api_key=os.environ["PREDEV_API_KEY"]) +``` + + +Use the API key from [Integrations](/api-reference/authentication). Both clients accept an optional base URL. Neither has a client-wide timeout, retry, or custom-header option. + +## Build with the agent + + +```typescript TypeScript +const { projectId } = await client.agent.createProject({ prompt: 'A habit tracker with streaks' }); +for await (const ev of client.agent.stream(projectId)) { + if (ev.event === 'message.delta') process.stdout.write(ev.data.delta); +} +await client.agent.buildNext(projectId); +console.log(await client.agent.status(projectId)); +``` +```python Python +project_id = client.agent.create_project("A habit tracker with streaks")["projectId"] +for event in client.agent.stream(project_id): + if event["event"] == "message.delta": + print(event["data"]["delta"], end="") +client.agent.build_next(project_id) +print(client.agent.status(project_id)) +``` + + +The [TypeScript](/architect-agent/sdks/node#build-with-the-agent) and [Python](/architect-agent/sdks/python#build-with-the-agent) guides have the full example. The REST endpoints are in the [Agent API](/agent-api/overview) reference. + +## By language + +| | TypeScript | Python | | --- | --- | --- | | 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 and browser results | JavaScript objects | Dictionaries | -| Credit balance | JavaScript object | `CreditsBalanceResponse` object | +| Runtime | Node.js 18+ (ESM) | Python 3.8+ | +| Calls | Promises | Blocking calls | +| Streams | Async generators | Iterators | +| Results | Typed JavaScript objects | Dictionaries (the credit balance is a `CreditsBalanceResponse` object) | -| Operation | Node | Python | +| Operation | TypeScript | Python | | --- | --- | --- | +| Create an agent project | `agent.createProject({ prompt })` | `agent.create_project(prompt)` | +| Message the agent | `agent.send(id, { message })` | `agent.send(id, message)` | +| Stream agent events | `agent.stream(id)` | `agent.stream(id)` | +| Build the plan | `agent.buildNext(id)`, `agent.buildAll(id)` | `agent.build_next(id)`, `agent.build_all(id)` | +| Agent progress and spend | `agent.status(id)` | `agent.status(id)` | +| Stop the agent | `agent.stop(id)` | `agent.stop(id)` | | Generate a spec | `fastSpec`, `deepSpec` | `fast_spec`, `deep_spec` | | Submit a spec and poll | `fastSpecAsync`, `getSpecStatus` | `fast_spec_async`, `get_spec_status` | | List or search specs | `listSpecs`, `findSpecs` | `list_specs`, `find_specs` | -| Read the credit balance | `getCreditsBalance()` | `get_credits_balance()` | | Run browser tasks | `browserAgent(tasks, options)` | `browser_agent(tasks, ...)` | -| Submit browser tasks asynchronously | `{ async: true }` | `run_async=True` | -| Stream a new browser submission | `{ stream: true }` → async generator | `stream=True` → iterator | -| Retrieve a browser run | `getBrowserAgent(id, options)` | `get_browser_agent(id, include_events=False)` | -| List browser runs | `listBrowserAgents(params)` | `list_browser_agents(...)` | +| Stream a new browser submission | `{ stream: true }` | `stream=True` | +| Retrieve or list browser runs | `getBrowserAgent`, `listBrowserAgents` | `get_browser_agent`, `list_browser_agents` | | Read your browser queue | `browserAgentStatus()` | `browser_agent_status()` | +| Read the credit balance | `getCreditsBalance()` | `get_credits_balance()` | -Both clients accept an API key and optional base URL. Neither exposes a client-wide timeout, retry, or arbitrary-header option. Use direct REST for live browser URLs, existing-run SSE, capacity statistics, and idempotency keys. +Use direct REST for live browser URLs, existing-run browser SSE, capacity statistics, and browser idempotency keys. - - Specifications, uploads, browser runs, streams, and errors. + + The agent, specifications, uploads, browser runs, streams, and errors. - Dictionary results, blocking calls, browser runs, and streaming iterators. + The same methods with dictionary results, blocking calls, and iterators. diff --git a/architect-agent/sdks/python.mdx b/architect-agent/sdks/python.mdx index 25fead7..2ea96be 100644 --- a/architect-agent/sdks/python.mdx +++ b/architect-agent/sdks/python.mdx @@ -1,23 +1,87 @@ --- title: "Python SDK" -description: "Generate specifications and run browser tasks with the published predev-api Python package." +description: "Build with the coding agent, generate specifications, and run browser tasks with the predev-api Python package." icon: "python" --- -import SdkInstall from "/snippets/sdk-install.mdx"; +## Install - +```bash +pip install predev-api +``` -Python 3.8+ is supported. This guide targets published **1.1.0**. +Python 3.8+ is supported. This guide targets **1.2.0**. `client.agent` needs 1.2.0 or later. -## Generate and wait for a specification +## Set up the client ```python import os import time + from predev_api import PredevAPI client = PredevAPI(api_key=os.environ["PREDEV_API_KEY"]) +``` + +The constructor takes `api_key` and an optional `base_url` (default `https://api.pre.dev`). Calls are ordinary blocking functions. There is no client-wide timeout or retry option. Get a key from [Integrations](/api-reference/authentication). + +## Build with the agent + +`client.agent` runs the pre.dev coding agent: create a project from a prompt, stream its work, build the plan, and check progress. Each method calls one [Agent API](/agent-api/overview) endpoint and returns a dictionary. + +```python +# 1. Create a project. The agent starts planning right away. +project = client.agent.create_project( + "A habit tracker with daily streaks and reminders", + mode="plan", # "build" (default) builds right away +) +project_id = project["projectId"] +print("Save this project ID:", project_id) + +# 2. Stream the agent's work until this run is done. +for event in client.agent.stream(project_id): + if event["event"] == "message.delta": + print(event["data"]["delta"], end="", flush=True) + elif event["event"] == "tool": + print(f"\n[{event['data']['tool']}]") + elif event["event"] == "status": + print(f"\n({event['data']['agentStatus'] or event['data']['state']})") + +# 3. Build the next task in the plan, capped at 50 credits, and follow it. +client.agent.build_next(project_id, max_credits=50) +for event in client.agent.stream(project_id): + if event["event"] == "message": + print(event["data"]["content"]) + +# 4. Check progress and spend. +progress = client.agent.status(project_id) +print(f"{progress['progress']['percent']}% built, {progress['creditsUsed']} credits used") +for feature in progress["features"]: + print(feature["name"], feature["statusText"]) +``` + +Steer the agent with `send`, and stop it with `stop`: + +```python +client.agent.send(project_id, "Use email reminders, not push.") +client.agent.stop(project_id) +``` + +| Method | Parameters | Returns | +| --- | --- | --- | +| `agent.create_project(prompt, ...)` | Optional `mode` (`"build"` or `"plan"`), `model`, `idempotency_key` | `{"projectId", "sessionId"}` | +| `agent.send(project_id, message, ...)` | Optional `session_id`, `mode` (`"auto"` or `"plan"`), `model` | `{"sessionId", "messageId"?}` | +| `agent.stream(project_id, ...)` | Optional `session_id`, `cursor`, `until_done=True`, `max_reconnects=5` | Iterator of events | +| `agent.build_next(project_id, ...)` | Optional `task`, `session_id`, `max_credits` | `{"sessionId", "kind"}` | +| `agent.build_all(project_id, ...)` | Optional `max_credits` | `{"sessionId", "kind"}` | +| `agent.status(project_id, ...)` | Optional `session_id` | Status dictionary | +| `agent.stop(project_id, ...)` | Optional `session_id` | `{"stopped", "message"}` | + +`stream` yields `{"event": ..., "data": {...}}` for `message.delta`, `message`, `tool`, `status`, `done`, and `cursor` (see [the event contract](/agent-api/events#event-contract)). It skips heartbeats and ends after `done`. If the connection drops, it reconnects from the last cursor. To pick up later in another process, save the last `cursor` event's `data["cursor"]` and pass it as `cursor=`. An `error` event raises an exception. + +## Specifications + +```python 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.", @@ -41,8 +105,6 @@ else: 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 | @@ -52,30 +114,22 @@ else: | `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 | -| `browser_agent(tasks, ...)` | Task list; optional `concurrency`, `stream=False`, `run_async=False` | Run dictionary, or an iterator when `stream=True` | -| `get_browser_agent(id, ...)` | Run ID; optional `include_events=False` | Run dictionary | -| `list_browser_agents(...)` | Optional `limit`, `skip`, `status` | Dictionary with `batches`, `total`, `hasMore` | -| `browser_agent_status()` | None | Dictionary with your queue and `cap` | -`*_async` methods and `run_async=True` submit server-side work and return its ID; they are ordinary blocking Python calls, not coroutines. Do not `await` them. Spec generation calls use a 300-second HTTP timeout and status, list, and search calls 60 seconds. Browser submissions use 300 seconds, retrieval and list 60 seconds, and queue status 30 seconds. A polling deadline is separate from an individual HTTP timeout, and there is no client-wide timeout or retry option. +`*_async` methods submit server-side work and return its ID; they are ordinary blocking Python calls, not coroutines. Do not `await` them. Spec generation calls use a 300-second HTTP timeout and status, list, and search calls 60 seconds. A polling deadline is separate from an individual HTTP timeout. -## Specification history and credits +### History ```python 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 +### 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: +The SDK accepts a file path or binary file object via `file`. 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 import json @@ -100,7 +154,18 @@ print(job["specId"]) See [accepted formats and limits](/architect-agent/inputs-and-outputs#upload-a-file). -## Run browser tasks and poll +## Browser agents + +| Method | Parameters | Runtime return | +| --- | --- | --- | +| `browser_agent(tasks, ...)` | Task list; optional `concurrency`, `stream=False`, `run_async=False` | Run dictionary, or an iterator when `stream=True` | +| `get_browser_agent(id, ...)` | Run ID; optional `include_events=False` | Run dictionary | +| `list_browser_agents(...)` | Optional `limit`, `skip`, `status` | Dictionary with `batches`, `total`, `hasMore` | +| `browser_agent_status()` | None | Dictionary with your queue and `cap` | + +Browser submissions use a 300-second HTTP timeout, retrieval and list 60 seconds, and queue status 30 seconds. `run_async=True` returns the run ID from a blocking call. + +### Run tasks and poll ```python tasks = [{ @@ -133,9 +198,9 @@ 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 such as `mode`, `maxSteps`, and `maxDurationSeconds`. +The SDK passes task dictionaries through to REST, including the per-task controls such as `mode`, `maxSteps`, and `maxDurationSeconds`. -## Stream a new browser submission +### Stream a new submission ```python saw_done = False @@ -152,7 +217,7 @@ if not saw_done: 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). -## Browser history and evidence +### History and evidence ```python queue = client.browser_agent_status() @@ -167,6 +232,15 @@ evidence = client.get_browser_agent(browser_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. +## Credits + +```python +balance = client.get_credits_balance() +print(balance.creditsRemaining) +``` + +`get_credits_balance()` reads the key's account or organization balance. For one agent project's spend, read `creditsUsed` from `client.agent.status(project_id)`. + ## Errors ```python @@ -179,24 +253,24 @@ from predev_api import ( ) try: - page = client.list_specs(limit=20) -except AuthenticationError: - print("Check the API key and account access.") + client.agent.build_next(project_id) +except InsufficientCreditsError as error: + print(str(error), error.action_url) except RateLimitError: print("Back off before retrying.") +except AuthenticationError: + print("Check the API key and account access.") except PredevAPIError as error: print(str(error)) try: browser_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)) ``` -The base exception has no `status_code` attribute. Browser gate errors have typed subclasses; see [errors and retries](/api-reference/errors). An Architect `402` without a machine-readable browser gate code raises `PredevAPIError`. 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. +The base exception has no `status_code` attribute. Errors with a machine-readable `code` (`RATE_LIMITED`, `INSUFFICIENT_CREDITS`, `SUBSCRIPTION_REQUIRED`, `QUEUE_FULL`, `BATCH_TOO_LARGE`) raise typed subclasses. Any other code, such as the Agent API's `NOT_FOUND` or `FORBIDDEN`, raises `PredevAPIError` with the server's message. See [errors and retries](/api-reference/errors). Use [direct REST](/browser-agents/api/run-task#idempotency) when a browser retry needs an idempotency key; `agent.create_project` takes its own `idempotency_key`. See the [PyPI package](https://pypi.org/project/predev-api/) or the [SDK source](https://github.com/predotdev/predev-api). diff --git a/docs.json b/docs.json index 62b1579..8c02718 100644 --- a/docs.json +++ b/docs.json @@ -436,6 +436,26 @@ "architect-agent/api/credits-balance" ] }, + { + "group": "SDKs", + "pages": [ + "architect-agent/sdks/overview", + "architect-agent/sdks/node", + "architect-agent/sdks/python" + ] + }, + { + "group": "Agent API", + "pages": [ + "agent-api/overview", + "agent-api/create-project", + "agent-api/send-message", + "agent-api/events", + "agent-api/build", + "agent-api/status", + "agent-api/stop" + ] + }, { "group": "Planning API", "pages": [ @@ -451,14 +471,6 @@ "architect-agent/api/find-specs" ] }, - { - "group": "SDKs", - "pages": [ - "architect-agent/sdks/overview", - "architect-agent/sdks/node", - "architect-agent/sdks/python" - ] - }, { "group": "MCP", "pages": [ diff --git a/llms.txt b/llms.txt index 44d2b10..4f3bec7 100644 --- a/llms.txt +++ b/llms.txt @@ -8,7 +8,7 @@ - [Guide for agents](https://docs.pre.dev/agents.md): Interfaces, the API key, plan access, five complete recipes, polling and error rules, and limits. - [skill.md](https://docs.pre.dev/skill.md): Short capability summary for agents. Install it with `npx skills add https://docs.pre.dev`. -- [REST API OpenAPI](https://docs.pre.dev/api-reference/openapi.json): Specifications, browser tasks, and the credit balance at `https://api.pre.dev`. +- [REST API OpenAPI](https://docs.pre.dev/api-reference/openapi.json): The Agent API, specifications, browser tasks, and the credit balance at `https://api.pre.dev`. - [AI Gateway OpenAPI](https://docs.pre.dev/api-reference/ai-gateway.openapi.json): Every operation under `https://api.pre.dev/v1`, with error examples. - Product MCP server: `npx -y @predotdev/mcp setup` adds it to every local coding agent, with every pre.dev tool plus the user's own Chrome (headless: command `npx -y @predotdev/mcp`, env `PREDEV_API_KEY`). Hosted: `https://api.pre.dev/mcp` (Streamable HTTP; OAuth, or `Authorization: Bearer `). Tools: https://api.pre.dev/mcp/info - Coding agent from a script or CI: `PREDEV_API_KEY=pdk_… predev run ""` in the repository; exit code `0` done, `1` failed, `2` not signed in. See https://docs.pre.dev/cli/overview#run-one-task-without-the-app @@ -67,16 +67,16 @@ - [API overview](https://docs.pre.dev/api-reference/overview.md): Base URLs, the key, and every REST endpoint. - [Get credit balance](https://docs.pre.dev/architect-agent/api/credits-balance.md): The credit balance for the key's account or organization. - [Architect API](https://docs.pre.dev/architect-agent/overview.md): Specifications as Markdown, JSON, architecture graphs, and estimates. -- [Spec inputs and outputs](https://docs.pre.dev/architect-agent/inputs-and-outputs.md): Context and files in; specifications, graphs, and documentation archives out. +- [Spec inputs and outputs](https://docs.pre.dev/architect-agent/inputs-and-outputs.md): Context and files in; specs, graphs, and doc archives out. - [Generate a Fast Spec](https://docs.pre.dev/architect-agent/api/fast-spec.md): POST /fast-spec: architecture, milestones, user stories, and acceptance criteria. - [Generate a Deep Spec](https://docs.pre.dev/architect-agent/api/deep-spec.md): POST /deep-spec: a detailed specification with subtasks. - [Get specification status](https://docs.pre.dev/architect-agent/api/spec-status.md): Progress, failures, or the finished specification. - [Get a project's plan](https://docs.pre.dev/architect-agent/api/get-plan.md): GET /get-plan: what is built, what works, what is left, and where it lives in the code. - [List specifications](https://docs.pre.dev/architect-agent/api/list-specs.md): Specification summaries with filters and pagination. - [Search specifications](https://docs.pre.dev/architect-agent/api/find-specs.md): Search specification inputs. -- [Browser Agents overview](https://docs.pre.dev/browser-agents/overview.md): Run browser workflows and extract structured data through REST, SDKs, or MCP, in the cloud or in your own Chrome. -- [Browser Agents Local](https://docs.pre.dev/browser-agents/local.md): Let any local coding agent use the Chrome you already have open, with your profiles and logins. Part of the pre.dev MCP server, set up with `npx -y @predotdev/mcp setup`. -- [Switch from Claude in Chrome](https://docs.pre.dev/browser-agents/switch-from-claude-in-chrome.md): Move a coding agent from Claude in Chrome to Browser Agents Local in two steps, with a tool-by-tool map. +- [Browser Agents overview](https://docs.pre.dev/browser-agents/overview.md): Browser workflows and structured extraction via REST, SDKs, or MCP. +- [Browser Agents Local](https://docs.pre.dev/browser-agents/local.md): Let any local coding agent use your open Chrome, with your logins, via `npx -y @predotdev/mcp setup`. +- [Switch from Claude in Chrome](https://docs.pre.dev/browser-agents/switch-from-claude-in-chrome.md): Move to Browser Agents Local in two steps, with a tool map. - [Run browser tasks](https://docs.pre.dev/browser-agents/api/run-task.md): POST /browser-agent: JSON, an async run ID, or a live SSE stream. - [Get run status and results](https://docs.pre.dev/browser-agents/api/task-status.md): A run's task outcomes, retries, and optional timeline. - [Stream an existing run](https://docs.pre.dev/browser-agents/api/stream-task.md): Snapshot, live SSE updates, and terminal status. @@ -84,8 +84,8 @@ - [List browser runs](https://docs.pre.dev/browser-agents/api/list-tasks.md): Browser run history with filters and pagination. - [Get your queue status](https://docs.pre.dev/browser-agents/api/queue-status.md): Your pending and running tasks and in-flight limit. - [Get service capacity](https://docs.pre.dev/browser-agents/api/capacity.md): Advisory service queue statistics. -- [Migrate a browser workflow](https://docs.pre.dev/browser-agents/migrate-from-browser-use.md): Move a locally managed browser workflow to pre.dev tasks. -- [AI Gateway overview](https://docs.pre.dev/ai-gateway/overview.md): Hundreds of models from every major lab through api.pre.dev/v1, on your key and credits. +- [Migrate a browser workflow](https://docs.pre.dev/browser-agents/migrate-from-browser-use.md): Move a local browser workflow to pre.dev. +- [AI Gateway overview](https://docs.pre.dev/ai-gateway/overview.md): Hundreds of models through api.pre.dev/v1 on your key and credits. - [Choose a model](https://docs.pre.dev/ai-gateway/models.md): Model ids from the catalog and their credit prices. - [Stream responses](https://docs.pre.dev/ai-gateway/streaming.md): SSE streams, usage in the final chunk, and the charge afterwards. - [Tools and structured output](https://docs.pre.dev/ai-gateway/tools-and-structured-output.md): Tool calling and JSON-schema output. @@ -116,10 +116,17 @@ - [List video models](https://docs.pre.dev/ai-gateway/api/video-models.md): GET /v1/videos/models, with per-second prices. - [Usage totals](https://docs.pre.dev/ai-gateway/api/usage.md): GET /v1/usage and the per-call headers. - [Generation stats](https://docs.pre.dev/ai-gateway/api/generation.md): GET /v1/generation: one call's stats and charge. -- [SDK overview](https://docs.pre.dev/architect-agent/sdks/overview.md): The Node.js and Python SDKs for specifications and browser tasks. -- [Node.js SDK](https://docs.pre.dev/architect-agent/sdks/node.md): The predev-api TypeScript client. -- [Python SDK](https://docs.pre.dev/architect-agent/sdks/python.md): The predev-api Python package. -- [Connect the MCP server](https://docs.pre.dev/architect-agent/mcp-setup.md): One command adds every pre.dev tool, plus the user's own Chrome, to every coding agent; or connect the hosted server. +- [SDK overview](https://docs.pre.dev/architect-agent/sdks/overview.md): The TypeScript and Python SDKs. +- [TypeScript SDK](https://docs.pre.dev/architect-agent/sdks/node.md): predev-api for Node.js. +- [Python SDK](https://docs.pre.dev/architect-agent/sdks/python.md): predev-api for Python. +- [Agent API](https://docs.pre.dev/agent-api/overview.md): Drive the coding agent over REST. +- [Create a project via API](https://docs.pre.dev/agent-api/create-project.md): POST /agent/projects. +- [Send a message](https://docs.pre.dev/agent-api/send-message.md): Start the agent's turn. +- [Stream agent events](https://docs.pre.dev/agent-api/events.md): SSE, resumable with a cursor. +- [Build the plan](https://docs.pre.dev/agent-api/build.md): Build next, a custom task, or all. +- [Get project status](https://docs.pre.dev/agent-api/status.md): Progress, running or idle, credits. +- [Stop the agent](https://docs.pre.dev/agent-api/stop.md): Stop a turn or build. +- [Connect the MCP server](https://docs.pre.dev/architect-agent/mcp-setup.md): One command adds every pre.dev tool and your Chrome to every coding agent, or use the hosted server. - [MCP tool reference](https://docs.pre.dev/mcp/tools.md): The twelve tools, including memory, exact input names, results, and deprecated aliases. ## Labs diff --git a/scripts/check-docs.mjs b/scripts/check-docs.mjs index 408e672..eef3cd9 100644 --- a/scripts/check-docs.mjs +++ b/scripts/check-docs.mjs @@ -195,7 +195,7 @@ for (const omitted of ['codingAgentSpecJson','humanSpecJson','codingAgentSpecMar const sourceIndex = process.argv.indexOf('--source-root'); if (sourceIndex !== -1) { const sourceRoot = path.resolve(process.argv[sourceIndex+1] || '..'); - const sources = await Promise.all(['api_endpoints.ts','browser_agents.ts'].map(f => fs.readFile(path.join(sourceRoot,'predev-app/backend/src/routes',f),'utf8'))); + const sources = await Promise.all(['api_endpoints.ts','browser_agents.ts','agent_api.ts'].map(f => fs.readFile(path.join(sourceRoot,'predev-app/backend/src/routes',f),'utf8'))); const routes = new Set(sources.flatMap(source => [...source.matchAll(/router\.(get|post|put|patch|delete)\(\s*['"]([^'"]+)/g)].map(([,method,url]) => `${method.toUpperCase()} ${url.replace(/:([\w]+)/g, '{$1}')}`))); // Internal agent media uploads (screenshots, browser-flow recordings) are // implementation endpoints, not public REST. diff --git a/scripts/check-node-examples.mjs b/scripts/check-node-examples.mjs index 64f5f58..4893a28 100644 --- a/scripts/check-node-examples.mjs +++ b/scripts/check-node-examples.mjs @@ -30,12 +30,38 @@ const json = value => new Response(JSON.stringify(value), {headers:{'Content-Typ let calls = 0; let uploads = 0; let streams = 0; +const agentCalls = []; +const agentProject = {projectId:id,sessionId:'507f1f77bcf86cd799439012'}; +const agentEvents = [ + ['cursor', {cursor:'c1'}], + ['status', {state:'running',agentStatus:'Planning',runTitle:null}], + ['message.delta', {messageId:id,delta:'Planning the habit tracker. '}], + ['tool', {messageId:id,tool:'write_file',toolId:'t1',text:'Using tool: write_file',completed:false}], + ['message', {messageId:id,role:'assistant',content:'Plan ready.',completed:true}], + ['done', {state:'idle'}], +]; +const agentStatus = {projectId:id,sessionId:agentProject.sessionId,state:'idle',agentStatus:null,runTitle:null,chatMode:'auto',progress:{percent:40,done:2,total:5,left:3,ready:1},summary:'2 of 5 built',features:[{id:'f1',name:'Sign in',status:'works',statusText:'Works',doneStories:2,totalStories:2}],creditsUsed:12.5}; const realFetch = globalThis.fetch; globalThis.fetch = async (url, options = {}) => { calls++; const parsed = new URL(url); assert.equal(parsed.origin, 'https://api.pre.dev'); assert.equal(new Headers(options.headers).get('Authorization'), 'Bearer docs-test-key'); + if (parsed.pathname.startsWith('/agent/projects')) { + const route = parsed.pathname.replace(id, ':id'); + agentCalls.push(`${options.method || 'GET'} ${route}`); + const body = options.body ? JSON.parse(options.body) : undefined; + if (route === '/agent/projects') { assert.ok(body.prompt); return json(agentProject); } + if (route === '/agent/projects/:id/messages') { assert.ok(body.message); return json({sessionId:agentProject.sessionId}); } + if (route === '/agent/projects/:id/build') { assert.equal(typeof body.all, 'boolean'); return json({sessionId:agentProject.sessionId,kind:body.all ? 'all' : 'next'}); } + if (route === '/agent/projects/:id/stop') return json({stopped:true,message:''}); + if (route === '/agent/projects/:id/status') return json(agentStatus); + if (route === '/agent/projects/:id/events') { + assert.equal(new Headers(options.headers).get('Accept'), 'text/event-stream'); + return new Response(': ping\n\n' + agentEvents.map(([event, data]) => `event: ${event}\ndata: ${JSON.stringify(data)}\n\n`).join(''), {headers:{'Content-Type':'text/event-stream'}}); + } + throw new Error(`Unmocked agent request: ${route}`); + } if (options.method === 'POST') { if (options.body instanceof FormData) { const file = options.body.get('file'); @@ -81,8 +107,12 @@ try { } assert.equal(uploads, 1); assert.equal(streams, 1); + // The agent walkthrough: create, two streams, build next, status, send, stop, and the error example's build. + for (const call of ['POST /agent/projects', 'GET /agent/projects/:id/events', 'POST /agent/projects/:id/build', 'GET /agent/projects/:id/status', 'POST /agent/projects/:id/messages', 'POST /agent/projects/:id/stop']) { + assert.ok(agentCalls.includes(call), `agent example never called ${call}`); + } assert.ok(calls >= 10); - console.log(`Node guide checks passed: ${sources.size} compiled guides, ${calls} mocked requests, multipart MIME and SSE verified`); + console.log(`Node guide checks passed: ${sources.size} compiled guides, ${calls} mocked requests (${agentCalls.length} agent), multipart MIME and SSE verified`); } finally { globalThis.fetch = realFetch; await fs.rm(temporary, {recursive:true,force:true}); diff --git a/scripts/check-python-examples.py b/scripts/check-python-examples.py index 7b2bb99..ce44bbc 100644 --- a/scripts/check-python-examples.py +++ b/scripts/check-python-examples.py @@ -22,6 +22,22 @@ calls = [] uploads = [] streams = [] +agent_calls = [] +AGENT_PROJECT = {"projectId": IDENTIFIER, "sessionId": "507f1f77bcf86cd799439012"} +AGENT_EVENTS = [ + ("cursor", {"cursor": "c1"}), + ("status", {"state": "running", "agentStatus": "Planning", "runTitle": None}), + ("message.delta", {"messageId": IDENTIFIER, "delta": "Planning the habit tracker. "}), + ("tool", {"messageId": IDENTIFIER, "tool": "write_file", "toolId": "t1", "text": "", "completed": False}), + ("message", {"messageId": IDENTIFIER, "role": "assistant", "content": "Plan ready.", "completed": True}), + ("done", {"state": "idle"}), +] +AGENT_STATUS = { + "projectId": IDENTIFIER, "sessionId": AGENT_PROJECT["sessionId"], "state": "idle", "agentStatus": None, + "runTitle": None, "chatMode": "auto", "progress": {"percent": 40, "done": 2, "total": 5, "left": 3, "ready": 1}, + "summary": "2 of 5 built", "creditsUsed": 12.5, + "features": [{"id": "f1", "name": "Sign in", "status": "works", "statusText": "Works", "doneStories": 2, "totalStories": 2}], +} def response(value): @@ -37,6 +53,8 @@ def send(method, url, **kwargs): assert parsed.scheme == "https" and parsed.netloc == "api.pre.dev" assert kwargs["headers"]["Authorization"] == "Bearer docs-test-key" calls.append((method, parsed.path)) + if parsed.path.startswith("/agent/projects"): + return agent(method, parsed.path.replace(IDENTIFIER, ":id"), kwargs) if method == "POST": if kwargs.get("files"): file = kwargs["files"]["file"] @@ -75,6 +93,34 @@ def send(method, url, **kwargs): raise AssertionError(f"Unmocked SDK request: {method} {parsed.path}") +def agent(method, route, kwargs): + agent_calls.append(f"{method} {route}") + body = kwargs.get("json") or {} + if route == "/agent/projects": + assert body["prompt"] + return response(AGENT_PROJECT) + if route == "/agent/projects/:id/messages": + assert body["message"] + return response({"sessionId": AGENT_PROJECT["sessionId"]}) + if route == "/agent/projects/:id/build": + assert isinstance(body["all"], bool) + return response({"sessionId": AGENT_PROJECT["sessionId"], "kind": "all" if body["all"] else "next"}) + if route == "/agent/projects/:id/stop": + return response({"stopped": True, "message": ""}) + if route == "/agent/projects/:id/status": + return response(AGENT_STATUS) + if route == "/agent/projects/:id/events": + assert kwargs.get("stream") is True + result = response({}) + result._content_consumed = True + lines = [": ping", ""] + for event, data in AGENT_EVENTS: + lines += ["event: " + event, "data: " + json.dumps(data), ""] + result.iter_lines = lambda **unused: iter(lines) + return result + raise AssertionError(f"Unmocked agent request: {method} {route}") + + def post(url, **kwargs): return send("POST", url, **kwargs) @@ -103,4 +149,7 @@ def reject_network(*args, **kwargs): exec(compile(code, guide, "exec"), {}) assert len(uploads) == 1 assert len(streams) == 1 +for call in ("POST /agent/projects", "GET /agent/projects/:id/events", "POST /agent/projects/:id/build", + "GET /agent/projects/:id/status", "POST /agent/projects/:id/messages", "POST /agent/projects/:id/stop"): + assert call in agent_calls, f"agent example never called {call}" print(f"Python guide checks passed: {len(guides)} guides, {len(calls)} mocked requests, dictionary responses, MIME and SSE verified") diff --git a/snippets/sdk-install.mdx b/snippets/sdk-install.mdx index 3c625e5..7120eef 100644 --- a/snippets/sdk-install.mdx +++ b/snippets/sdk-install.mdx @@ -1,5 +1,5 @@ -```bash Node.js +```bash TypeScript npm install predev-api ``` ```bash Python