Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
83 changes: 83 additions & 0 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
# Publish both SDKs when a version tag is pushed: `git tag v1.2.0 && git push origin v1.2.0`.
# The tag must match the version in predev-api-node/package.json,
# predev-api-python/setup.py and predev_api/__init__.py, or nothing publishes.
# Secrets: NPM_TOKEN (npm automation token), PYPI_API_TOKEN (PyPI API token).
name: release

on:
push:
tags: ["v*"]

concurrency:
group: release-${{ github.ref }}
cancel-in-progress: false

jobs:
verify:
runs-on: ubuntu-latest
timeout-minutes: 10
outputs:
version: ${{ steps.version.outputs.version }}
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- uses: astral-sh/setup-uv@v10.0.1
- id: version
name: Tag matches every package version
run: |
tag="${GITHUB_REF_NAME#v}"
node_v=$(node -p "require('./predev-api-node/package.json').version")
py_setup=$(sed -n 's/.*version="\([^"]*\)".*/\1/p' predev-api-python/setup.py | head -1)
py_init=$(sed -n 's/^__version__ = "\([^"]*\)"/\1/p' predev-api-python/predev_api/__init__.py)
echo "tag=$tag node=$node_v setup.py=$py_setup __init__=$py_init"
if [ "$tag" != "$node_v" ] || [ "$tag" != "$py_setup" ] || [ "$tag" != "$py_init" ]; then
echo "::error::tag v$tag does not match the package versions"
exit 1
fi
echo "version=$tag" >> "$GITHUB_OUTPUT"
- run: make check

npm:
needs: verify
runs-on: ubuntu-latest
timeout-minutes: 10
permissions:
contents: read
id-token: write # npm provenance
defaults:
run:
working-directory: predev-api-node
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 20
registry-url: https://registry.npmjs.org
- run: npm ci
- run: npm test
- run: npm run build
- run: npm publish --provenance --access public
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}

pypi:
needs: verify
runs-on: ubuntu-latest
timeout-minutes: 10
permissions:
contents: read
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: "3.12"
- name: Build sdist + wheel
working-directory: predev-api-python
run: |
python -m pip install --upgrade build
python -m build
- uses: pypa/gh-action-pypi-publish@release/v1
with:
packages-dir: predev-api-python/dist
password: ${{ secrets.PYPI_API_TOKEN }}
33 changes: 33 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ const result = await predev.fastSpec({ input: 'Build a task management app' });

Both libraries provide:

- **Build with the agent** (`client.agent`): create a project from a prompt, stream the agent's work, build the plan, check status and credits
- **Fast Spec Generation**: Comprehensive specifications quickly - perfect for MVPs and prototypes
- **Deep Spec Generation**: Ultra-detailed specifications for complex systems with enterprise-grade depth
- **Async Spec Generation**: Non-blocking async methods for long-running requests
Expand Down Expand Up @@ -140,6 +141,38 @@ status = predev.get_spec_status("spec_id")
const status = await predev.getSpecStatus("spec_id");
```

### Build with the agent

```typescript
const { projectId } = await predev.agent.createProject({ prompt: 'A habit tracker' });
for await (const ev of predev.agent.stream(projectId)) {
if (ev.event === 'message.delta') process.stdout.write(ev.data.delta);
}
await predev.agent.buildNext(projectId);
console.log(await predev.agent.status(projectId));
```

```python
project_id = predev.agent.create_project("A habit tracker")["projectId"]
for event in predev.agent.stream(project_id):
if event["event"] == "message.delta":
print(event["data"]["delta"], end="")
predev.agent.build_next(project_id)
print(predev.agent.status(project_id))
```

Methods: `createProject` / `create_project`, `send`, `stream`, `buildNext` / `build_next`, `buildAll` / `build_all`, `status`, `stop`. See each package README.

## 🚢 Releasing

Releases publish from CI (`.github/workflows/release.yml`) when a `v*` tag is pushed:

1. Bump the version in `predev-api-node/package.json`, `predev-api-python/setup.py` and `predev-api-python/predev_api/__init__.py` (all three must match), merge to `main`.
2. Tag the merge commit and push the tag: `git tag v1.2.0 && git push origin v1.2.0`.
3. The workflow checks the tag matches all three versions, runs `make check`, then publishes `predev-api` to npm (with provenance) and to PyPI.

Repo secrets: `NPM_TOKEN` (npm automation token for `predev-api`) and `PYPI_API_TOKEN` (PyPI API token scoped to `predev-api`). `scripts/deploy.sh` remains for manual releases.

## 📖 Documentation

- [Pre.dev API Documentation](https://docs.pre.dev)
Expand Down
46 changes: 46 additions & 0 deletions predev-api-node/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -380,6 +380,52 @@ interface HumanSpecJson {
roles: SpecRole[];
}
```
## Build with the agent

`client.agent` drives the pre.dev coding agent: create a project from a prompt, stream what the agent does, build the plan task by task, and check progress.

```typescript
import { PredevAPI } from "predev-api";

const client = new PredevAPI({ apiKey: process.env.PREDEV_API_KEY! });

// 1. Create a project. The agent starts on it right away.
const { projectId } = await client.agent.createProject({
prompt: "A habit tracker with daily streaks and reminders",
mode: "plan", // "build" (default) builds right away; "plan" plans first
});

// 2. Stream the agent's work until the run is done.
for await (const ev of client.agent.stream(projectId)) {
if (ev.event === "message.delta") process.stdout.write(ev.data.delta);
if (ev.event === "tool") console.log(`\n[${ev.data.tool}]`);
}

// 3. Build the next task in the plan, capped at 50 credits, and follow it.
await client.agent.buildNext(projectId, { maxCredits: 50 });
for await (const ev of client.agent.stream(projectId)) {
if (ev.event === "status") console.log(ev.data.agentStatus ?? ev.data.state);
}

// 4. Check progress.
const status = await client.agent.status(projectId);
console.log(`${status.progress.percent}% built, ${status.creditsUsed} credits used`);
```

### Agent methods

| Method | What it does |
| --- | --- |
| `agent.createProject({ prompt, mode?, model?, idempotencyKey? })` | New project from a prompt. Returns `{ projectId, sessionId }`. |
| `agent.send(projectId, { message, sessionId?, mode?, model? })` | Send a message (`mode`: `"auto"` or `"plan"`). Returns once the agent accepts it. |
| `agent.stream(projectId, { sessionId?, cursor?, untilDone?, maxReconnects?, signal? })` | Async iterator of `message.delta`, `message`, `tool`, `status`, `done`, `cursor` events. Ends after `done` by default and reconnects from the last cursor. |
| `agent.buildNext(projectId, { task?, sessionId?, maxCredits? })` | Build the next task in the plan, or `task`. |
| `agent.buildAll(projectId, { maxCredits? })` | Build every remaining task. |
| `agent.status(projectId, { sessionId? })` | `state` (`running`/`idle`), plan `progress`, `features`, `creditsUsed`. |
| `agent.stop(projectId, { sessionId? })` | Stop the running agent. |

To resume a stream later, keep the last `cursor` event's `data.cursor` and pass it as `cursor`: you get every message that changed since, then live events.

## Browser Tasks

Run browser automation — navigate to, interact with, and/or extract data from any web page. Each task navigates a URL, optionally performs actions, and returns typed JSON.
Expand Down
4 changes: 2 additions & 2 deletions predev-api-node/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion predev-api-node/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "predev-api",
"version": "1.1.0",
"version": "1.2.0",
"description": "TypeScript/Node.js client for the Pre.dev Architect API - Generate comprehensive software specifications",
"main": "./dist/index.js",
"types": "./dist/index.d.ts",
Expand Down
130 changes: 130 additions & 0 deletions predev-api-node/src/agent.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
/**
* Tests for client.agent (HTTP mocked).
*/

import { describe, it, expect, beforeEach, vi } from "vitest";
import { PredevAPI } from "./client";
import { parseSSE } from "./agent";
import { AuthenticationError, InsufficientCreditsError, PredevAPIError, RateLimitError } from "./exceptions";

const fetchMock = vi.fn();
global.fetch = fetchMock as any;

const json = (status: number, body: unknown) =>
({ ok: status >= 200 && status < 300, status, json: async () => body }) as unknown as Response;

const sse = (...chunks: string[]) => {
const encoder = new TextEncoder();
const body = new ReadableStream<Uint8Array>({
start(controller) {
for (const c of chunks) controller.enqueue(encoder.encode(c));
controller.close();
},
});
return { ok: true, status: 200, body } as unknown as Response;
};

const client = () => new PredevAPI({ apiKey: "k", baseUrl: "https://api.test/" });
const lastCall = () => fetchMock.mock.calls[fetchMock.mock.calls.length - 1];

describe("client.agent", () => {
beforeEach(() => fetchMock.mockReset());

it("createProject posts the prompt with the API key", async () => {
fetchMock.mockResolvedValueOnce(json(201, { projectId: "p1", sessionId: "s1" }));
const out = await client().agent.createProject({ prompt: "A todo app", mode: "plan", idempotencyKey: "k-1" });
expect(out).toEqual({ projectId: "p1", sessionId: "s1" });
const [url, init] = lastCall();
expect(url).toBe("https://api.test/agent/projects");
expect(init.method).toBe("POST");
expect(init.headers.Authorization).toBe("Bearer k");
expect(JSON.parse(init.body)).toEqual({ prompt: "A todo app", mode: "plan", idempotencyKey: "k-1" });
});

it("send, buildNext, buildAll, status and stop hit their routes", async () => {
const c = client();
fetchMock.mockResolvedValueOnce(json(202, { sessionId: "s1" }));
await c.agent.send("p1", { message: "Add login", mode: "auto" });
expect(lastCall()[0]).toBe("https://api.test/agent/projects/p1/messages");
expect(JSON.parse(lastCall()[1].body)).toEqual({ message: "Add login", mode: "auto" });

fetchMock.mockResolvedValueOnce(json(202, { sessionId: "s1", kind: "next" }));
await c.agent.buildNext("p1", { task: "Login form", maxCredits: 20 });
expect(lastCall()[0]).toBe("https://api.test/agent/projects/p1/build");
expect(JSON.parse(lastCall()[1].body)).toEqual({ task: "Login form", maxCredits: 20, all: false });

fetchMock.mockResolvedValueOnce(json(202, { sessionId: null, kind: "all" }));
await c.agent.buildAll("p1");
expect(JSON.parse(lastCall()[1].body)).toEqual({ all: true });

fetchMock.mockResolvedValueOnce(json(200, { state: "idle", creditsUsed: 3 }));
const status = await c.agent.status("p1", { sessionId: "s1" });
expect(status.creditsUsed).toBe(3);
expect(lastCall()[0]).toBe("https://api.test/agent/projects/p1/status?sessionId=s1");
expect(lastCall()[1].method).toBe("GET");

fetchMock.mockResolvedValueOnce(json(200, { stopped: true, message: "" }));
expect((await c.agent.stop("p1")).stopped).toBe(true);
expect(lastCall()[0]).toBe("https://api.test/agent/projects/p1/stop");
});

it("maps errors to typed exceptions", async () => {
fetchMock.mockResolvedValueOnce(json(401, { error: "Missing API key" }));
await expect(client().agent.status("p1")).rejects.toBeInstanceOf(AuthenticationError);
fetchMock.mockResolvedValueOnce(json(429, { error: "Rate limit exceeded", code: "RATE_LIMITED" }));
await expect(client().agent.send("p1", { message: "x" })).rejects.toBeInstanceOf(RateLimitError);
fetchMock.mockResolvedValueOnce(json(402, { error: "Out of credits", code: "INSUFFICIENT_CREDITS" }));
await expect(client().agent.buildNext("p1")).rejects.toBeInstanceOf(InsufficientCreditsError);
fetchMock.mockResolvedValueOnce(json(404, { error: "Project not found", code: "NOT_FOUND" }));
await expect(client().agent.status("nope")).rejects.toThrow("Project not found");
fetchMock.mockRejectedValueOnce(new Error("ECONNRESET"));
await expect(client().agent.status("p1")).rejects.toBeInstanceOf(PredevAPIError);
});

it("stream yields events until done and skips heartbeats", async () => {
fetchMock.mockResolvedValueOnce(
sse(
"retry: 3000\n\n",
'id: c1\nevent: cursor\ndata: {"cursor":"c1"}\n\n',
'event: status\ndata: {"state":"running","agentStatus":"Thinking","runTitle":null}\n\n',
": ping 1\n\n",
'event: message.delta\ndata: {"messageId":"m1","del',
'ta":"Hi"}\n\nevent: tool\ndata: {"messageId":"t1","tool":"bash","toolId":null,"text":"","completed":false}\n\n',
'event: done\ndata: {"state":"idle"}\n\n',
'event: status\ndata: {"state":"idle"}\n\n'
)
);
const events = [];
for await (const ev of client().agent.stream("p1", { sessionId: "s1" })) events.push(ev);
expect(events.map(e => e.event)).toEqual(["cursor", "status", "message.delta", "tool", "done"]);
expect(events[2].data).toEqual({ messageId: "m1", delta: "Hi" });
expect(lastCall()[0]).toBe("https://api.test/agent/projects/p1/events?sessionId=s1");
expect(lastCall()[1].headers.Accept).toBe("text/event-stream");
});

it("stream reconnects from the last cursor when the connection ends early", async () => {
fetchMock
.mockResolvedValueOnce(sse('event: cursor\ndata: {"cursor":"abc"}\n\n'))
.mockResolvedValueOnce(sse('event: done\ndata: {"state":"idle"}\n\n'));
const events = [];
for await (const ev of client().agent.stream("p1")) events.push(ev.event);
expect(events).toEqual(["cursor", "done"]);
expect(fetchMock.mock.calls[1][0]).toBe("https://api.test/agent/projects/p1/events?cursor=abc");
});

it("stream raises an error event as a typed exception", async () => {
fetchMock.mockResolvedValueOnce(sse('event: error\ndata: {"error":"Could not open","code":"STREAM_FAILED"}\n\n'));
const run = async () => {
for await (const _ of client().agent.stream("p1")) {
/* drain */
}
};
await expect(run()).rejects.toThrow("Could not open");
});

it("parseSSE joins multi-line data and keeps ids", async () => {
const frames = [];
for await (const f of parseSSE(sse("id: 7\nevent: x\ndata: a\ndata: b\n\n").body!)) frames.push(f);
expect(frames).toEqual([{ event: "x", data: "a\nb", id: "7" }]);
});
});
Loading
Loading