From 7f1e269ab8212cd6c2b6dd1f232c72e22db955f5 Mon Sep 17 00:00:00 2001 From: Smoke Person Date: Sat, 5 Dec 2026 01:15:32 -0500 Subject: [PATCH 1/3] style(python): ruff-clean client.py before the agent change touches it Mechanical only: ruff 0.16.5 --fix + format (the changed-files gate enforces it on any touched file). `from __future__ import annotations` keeps the rewritten `X | None` annotations valid on Python 3.8/3.9 (setup.py python_requires >=3.8). The two findings ruff cannot fix are handled by hand: the upload file handle is closed by requests (noqa SIM115), and the JSON error-body parse catches ValueError instead of Exception. Unused exception imports dropped (still exported from predev_api/__init__.py). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01PwA31qPkrcHj7kogbsmWS4 --- predev-api-python/predev_api/client.py | 426 ++++++++++++------------- 1 file changed, 204 insertions(+), 222 deletions(-) diff --git a/predev-api-python/predev_api/client.py b/predev-api-python/predev_api/client.py index 7a5e8bf..56a6783 100644 --- a/predev-api-python/predev_api/client.py +++ b/predev-api-python/predev_api/client.py @@ -2,18 +2,19 @@ Client for the Pre.dev Architect API """ -from typing import Optional, Dict, Any, Literal, List, Union, BinaryIO, Iterator -from dataclasses import dataclass +from __future__ import annotations + import json +from collections.abc import Iterator +from dataclasses import dataclass +from typing import Any, BinaryIO, Literal + import requests + from .exceptions import ( - PredevAPIError, AuthenticationError, + PredevAPIError, RateLimitError, - SubscriptionRequiredError, - InsufficientCreditsError, - QueueFullError, - BatchTooLargeError, exception_for_code, ) @@ -21,13 +22,15 @@ @dataclass class AsyncResponse: """Async mode response class""" + specId: str - status: Literal['pending', 'processing', 'completed', 'failed'] + status: Literal["pending", "processing", "completed", "failed"] @dataclass class ZippedDocsUrl: """Zipped documentation URL class""" + platform: str masterZipShortUrl: str @@ -36,7 +39,7 @@ class ZippedDocsUrl: class SpecCoreFunctionality: name: str description: str - priority: Optional[str] = None + priority: str | None = None @dataclass @@ -49,9 +52,9 @@ class SpecTechStackItem: class SpecPersona: title: str description: str - primaryGoals: Optional[List[str]] = None - painPoints: Optional[List[str]] = None - keyTasks: Optional[List[str]] = None + primaryGoals: list[str] | None = None + painPoints: list[str] | None = None + keyTasks: list[str] | None = None @dataclass @@ -62,56 +65,56 @@ class SpecRole: @dataclass class CodingAgentSubTask: - id: Optional[str] = None + id: str | None = None description: str = "" complexity: str = "" @dataclass class CodingAgentStory: - id: Optional[str] = None + id: str | None = None title: str = "" - description: Optional[str] = None - acceptanceCriteria: Optional[List[str]] = None - complexity: Optional[str] = None - subTasks: Optional[List[CodingAgentSubTask]] = None + description: str | None = None + acceptanceCriteria: list[str] | None = None + complexity: str | None = None + subTasks: list[CodingAgentSubTask] | None = None @dataclass class CodingAgentMilestone: milestoneNumber: int = 0 description: str = "" - stories: Optional[List[CodingAgentStory]] = None + stories: list[CodingAgentStory] | None = None @dataclass class CodingAgentSpecJson: - title: Optional[str] = None + title: str | None = None executiveSummary: str = "" - coreFunctionalities: Optional[List[SpecCoreFunctionality]] = None - techStack: Optional[List[SpecTechStackItem]] = None - techStackGrouped: Optional[Dict[str, List[str]]] = None - milestones: Optional[List[CodingAgentMilestone]] = None + coreFunctionalities: list[SpecCoreFunctionality] | None = None + techStack: list[SpecTechStackItem] | None = None + techStackGrouped: dict[str, list[str]] | None = None + milestones: list[CodingAgentMilestone] | None = None @dataclass class HumanSpecSubTask: - id: Optional[str] = None + id: str | None = None description: str = "" hours: float = 0 complexity: str = "" - roles: Optional[List[SpecRole]] = None + roles: list[SpecRole] | None = None @dataclass class HumanSpecStory: - id: Optional[str] = None + id: str | None = None title: str = "" - description: Optional[str] = None - acceptanceCriteria: Optional[List[str]] = None + description: str | None = None + acceptanceCriteria: list[str] | None = None hours: float = 0 - complexity: Optional[str] = None - subTasks: Optional[List[HumanSpecSubTask]] = None + complexity: str | None = None + subTasks: list[HumanSpecSubTask] | None = None @dataclass @@ -119,46 +122,46 @@ class HumanSpecMilestone: milestoneNumber: int = 0 description: str = "" hours: float = 0 - stories: Optional[List[HumanSpecStory]] = None + stories: list[HumanSpecStory] | None = None @dataclass class HumanSpecJson: - title: Optional[str] = None + title: str | None = None executiveSummary: str = "" - coreFunctionalities: Optional[List[SpecCoreFunctionality]] = None - personas: Optional[List[SpecPersona]] = None - techStack: Optional[List[SpecTechStackItem]] = None - techStackGrouped: Optional[Dict[str, List[str]]] = None - milestones: Optional[List[HumanSpecMilestone]] = None - totalHours: Optional[float] = None - roles: Optional[List[SpecRole]] = None + coreFunctionalities: list[SpecCoreFunctionality] | None = None + personas: list[SpecPersona] | None = None + techStack: list[SpecTechStackItem] | None = None + techStackGrouped: dict[str, list[str]] | None = None + milestones: list[HumanSpecMilestone] | None = None + totalHours: float | None = None + roles: list[SpecRole] | None = None @dataclass class SpecGraphNode: id: str = "" label: str = "" - type: Optional[str] = None - description: Optional[str] = None + type: str | None = None + description: str | None = None # userFlowGraph: BFS depth from roles (roles = 0, flows >= 1, None when # unreachable). architectureGraph: C4 diagram level ("C1" | "C2"). - level: Optional[Union[int, str]] = None - hours: Optional[float] = None + level: int | str | None = None + hours: float | None = None @dataclass class SpecGraphEdge: source: str = "" target: str = "" - description: Optional[str] = None - edgeType: Optional[str] = None + description: str | None = None + edgeType: str | None = None @dataclass class SpecGraph: - nodes: Optional[List['SpecGraphNode']] = None - edges: Optional[List['SpecGraphEdge']] = None + nodes: list[SpecGraphNode] | None = None + edges: list[SpecGraphEdge] | None = None @dataclass @@ -180,57 +183,60 @@ class SpecEnrichedTechStackItem: useFor: str = "" reason: str = "" description: str = "" - link: Optional[str] = None - helpfulLinks: Optional[List['HelpfulLink']] = None - alternatives: Optional[List['AlternativeTechStackItemApi']] = None + link: str | None = None + helpfulLinks: list[HelpfulLink] | None = None + alternatives: list[AlternativeTechStackItemApi] | None = None @dataclass class SpecResponse: """Status check response class""" - _id: Optional[str] = None - created: Optional[str] = None - endpoint: Optional[Literal['fast_spec', 'deep_spec']] = None - input: Optional[str] = None - status: Optional[Literal['pending', - 'processing', 'completed', 'failed']] = None - success: Optional[bool] = None + _id: str | None = None + created: str | None = None - uploadedFileShortUrl: Optional[str] = None - uploadedFileName: Optional[str] = None - codingAgentSpecUrl: Optional[str] = None - humanSpecUrl: Optional[str] = None - totalHumanHours: Optional[int] = None - codingAgentSpecJson: Optional['CodingAgentSpecJson'] = None - codingAgentSpecMarkdown: Optional[str] = None - humanSpecJson: Optional['HumanSpecJson'] = None - humanSpecMarkdown: Optional[str] = None - executionTime: Optional[int] = None + endpoint: Literal["fast_spec", "deep_spec"] | None = None + input: str | None = None + status: Literal["pending", "processing", "completed", "failed"] | None = None + success: bool | None = None - architectureInfographicUrl: Optional[str] = None + uploadedFileShortUrl: str | None = None + uploadedFileName: str | None = None + codingAgentSpecUrl: str | None = None + humanSpecUrl: str | None = None + totalHumanHours: int | None = None + codingAgentSpecJson: CodingAgentSpecJson | None = None + codingAgentSpecMarkdown: str | None = None + humanSpecJson: HumanSpecJson | None = None + humanSpecMarkdown: str | None = None + executionTime: int | None = None - predevUrl: Optional[str] = None + architectureInfographicUrl: str | None = None - zippedDocsUrls: Optional[List['ZippedDocsUrl']] = None + predevUrl: str | None = None - errorMessage: Optional[str] = None - progress: Optional[int] = None # Overall progress percentage (0-100) - progressMessage: Optional[str] = None # Detailed progress message (e.g., "Generating User Stories...") + zippedDocsUrls: list[ZippedDocsUrl] | None = None + + errorMessage: str | None = None + progress: int | None = None # Overall progress percentage (0-100) + progressMessage: str | None = ( + None # Detailed progress message (e.g., "Generating User Stories...") + ) # Credit usage - available during processing (real-time accumulation) and on completion # Fast spec: typically ~5-10 credits, Deep spec: typically ~10-50 credits - creditsUsed: Optional[float] = None # Total credits consumed by this spec generation + creditsUsed: float | None = None # Total credits consumed by this spec generation # Graph data (only when completed) - userFlowGraph: Optional['SpecGraph'] = None - architectureGraph: Optional['SpecGraph'] = None - enrichedTechStack: Optional[List['SpecEnrichedTechStackItem']] = None + userFlowGraph: SpecGraph | None = None + architectureGraph: SpecGraph | None = None + enrichedTechStack: list[SpecEnrichedTechStackItem] | None = None @dataclass class ErrorResponse: """Error response class""" + error: str message: str @@ -238,7 +244,8 @@ class ErrorResponse: @dataclass class ListSpecsResponse: """List/Find specs response class""" - specs: List['SpecResponse'] + + specs: list[SpecResponse] total: int hasMore: bool @@ -246,6 +253,7 @@ class ListSpecsResponse: @dataclass class CreditsBalanceResponse: """Credits balance response class""" + success: bool creditsRemaining: int @@ -269,26 +277,22 @@ class PredevAPI: >>> print(result) """ - def __init__( - self, - api_key: str, - base_url: str = "https://api.pre.dev" - ): + def __init__(self, api_key: str, base_url: str = "https://api.pre.dev"): self.api_key = api_key self.base_url = base_url.rstrip("/") # Set up headers with Authorization Bearer token self.headers = { "Authorization": f"Bearer {api_key}", - "Content-Type": "application/json" + "Content-Type": "application/json", } def fast_spec( self, input_text: str, - current_context: Optional[str] = None, - doc_urls: Optional[List[str]] = None, - file: Optional[Union[str, BinaryIO]] = None + current_context: str | None = None, + doc_urls: list[str] | None = None, + file: str | BinaryIO | None = None, ) -> SpecResponse: """ Generate a fast specification for your project. @@ -322,15 +326,15 @@ def fast_spec( input_text=input_text, current_context=current_context, doc_urls=doc_urls, - file=file + file=file, ) def deep_spec( self, input_text: str, - current_context: Optional[str] = None, - doc_urls: Optional[List[str]] = None, - file: Optional[Union[str, BinaryIO]] = None + current_context: str | None = None, + doc_urls: list[str] | None = None, + file: str | BinaryIO | None = None, ) -> SpecResponse: """ Generate a deep specification for your project. @@ -365,15 +369,15 @@ def deep_spec( input_text=input_text, current_context=current_context, doc_urls=doc_urls, - file=file + file=file, ) def fast_spec_async( self, input_text: str, - current_context: Optional[str] = None, - doc_urls: Optional[List[str]] = None, - file: Optional[Union[str, BinaryIO]] = None + current_context: str | None = None, + doc_urls: list[str] | None = None, + file: str | BinaryIO | None = None, ) -> AsyncResponse: """ Generate a fast specification asynchronously for your project. @@ -410,15 +414,15 @@ def fast_spec_async( input_text=input_text, current_context=current_context, doc_urls=doc_urls, - file=file + file=file, ) def deep_spec_async( self, input_text: str, - current_context: Optional[str] = None, - doc_urls: Optional[List[str]] = None, - file: Optional[Union[str, BinaryIO]] = None + current_context: str | None = None, + doc_urls: list[str] | None = None, + file: str | BinaryIO | None = None, ) -> AsyncResponse: """ Generate a deep specification asynchronously for your project. @@ -455,7 +459,7 @@ def deep_spec_async( input_text=input_text, current_context=current_context, doc_urls=doc_urls, - file=file + file=file, ) def get_spec_status(self, spec_id: str) -> SpecResponse: @@ -483,15 +487,14 @@ def get_spec_status(self, spec_id: str) -> SpecResponse: self._handle_response(response) return response.json() except requests.RequestException as e: - raise PredevAPIError(f"Request failed: {str(e)}") from e + raise PredevAPIError(f"Request failed: {e!s}") from e def list_specs( self, - limit: Optional[int] = None, - skip: Optional[int] = None, - endpoint: Optional[Literal['fast_spec', 'deep_spec']] = None, - status: Optional[Literal['pending', - 'processing', 'completed', 'failed']] = None + limit: int | None = None, + skip: int | None = None, + endpoint: Literal["fast_spec", "deep_spec"] | None = None, + status: Literal["pending", "processing", "completed", "failed"] | None = None, ) -> ListSpecsResponse: """ List all specs with optional filtering and pagination. @@ -522,30 +525,30 @@ def list_specs( params = {} if limit is not None: - params['limit'] = limit + params["limit"] = limit if skip is not None: - params['skip'] = skip + params["skip"] = skip if endpoint is not None: - params['endpoint'] = endpoint + params["endpoint"] = endpoint if status is not None: - params['status'] = status + params["status"] = status try: response = requests.get( - url, headers=self.headers, params=params, timeout=60) + url, headers=self.headers, params=params, timeout=60 + ) self._handle_response(response) return response.json() except requests.RequestException as e: - raise PredevAPIError(f"Request failed: {str(e)}") from e + raise PredevAPIError(f"Request failed: {e!s}") from e def find_specs( self, query: str, - limit: Optional[int] = None, - skip: Optional[int] = None, - endpoint: Optional[Literal['fast_spec', 'deep_spec']] = None, - status: Optional[Literal['pending', - 'processing', 'completed', 'failed']] = None + limit: int | None = None, + skip: int | None = None, + endpoint: Literal["fast_spec", "deep_spec"] | None = None, + status: Literal["pending", "processing", "completed", "failed"] | None = None, ) -> ListSpecsResponse: """ Search for specs using regex patterns. @@ -574,24 +577,25 @@ def find_specs( >>> auth = client.find_specs(query='auth', status='completed') """ url = f"{self.base_url}/find-specs" - params = {'query': query} + params = {"query": query} if limit is not None: - params['limit'] = limit + params["limit"] = limit if skip is not None: - params['skip'] = skip + params["skip"] = skip if endpoint is not None: - params['endpoint'] = endpoint + params["endpoint"] = endpoint if status is not None: - params['status'] = status + params["status"] = status try: response = requests.get( - url, headers=self.headers, params=params, timeout=60) + url, headers=self.headers, params=params, timeout=60 + ) self._handle_response(response) return response.json() except requests.RequestException as e: - raise PredevAPIError(f"Request failed: {str(e)}") from e + raise PredevAPIError(f"Request failed: {e!s}") from e def get_credits_balance(self) -> CreditsBalanceResponse: """ @@ -615,15 +619,15 @@ def get_credits_balance(self) -> CreditsBalanceResponse: response = requests.get(url, headers=self.headers, timeout=60) self._handle_response(response) data = response.json() - return CreditsBalanceResponse(success=data['success'], creditsRemaining=data['creditsRemaining']) + return CreditsBalanceResponse( + success=data["success"], creditsRemaining=data["creditsRemaining"] + ) except requests.RequestException as e: - raise PredevAPIError(f"Request failed: {str(e)}") from e + raise PredevAPIError(f"Request failed: {e!s}") from e def get_browser_agent( - self, - batch_id: str, - include_events: bool = False - ) -> Dict[str, Any]: + self, batch_id: str, include_events: bool = False + ) -> dict[str, Any]: """ Get the status + results of a browser-agent batch by ID. @@ -645,14 +649,14 @@ def get_browser_agent( self._handle_response(response) return response.json() except requests.RequestException as e: - raise PredevAPIError(f"Request failed: {str(e)}") from e + raise PredevAPIError(f"Request failed: {e!s}") from e def list_browser_agents( self, - limit: Optional[int] = None, - skip: Optional[int] = None, - status: Optional[str] = None - ) -> Dict[str, Any]: + limit: int | None = None, + skip: int | None = None, + status: str | None = None, + ) -> dict[str, Any]: """ List browser-agent runs for the authenticated caller. Sorted by most recent. @@ -664,7 +668,7 @@ def list_browser_agents( Returns: Dict with keys: batches, total, hasMore """ - params: Dict[str, Any] = {} + params: dict[str, Any] = {} if limit is not None: params["limit"] = limit if skip is not None: @@ -673,13 +677,15 @@ def list_browser_agents( params["status"] = status url = f"{self.base_url}/list-browser-agents" try: - response = requests.get(url, headers=self.headers, params=params, timeout=60) + response = requests.get( + url, headers=self.headers, params=params, timeout=60 + ) self._handle_response(response) return response.json() except requests.RequestException as e: - raise PredevAPIError(f"Request failed: {str(e)}") from e + raise PredevAPIError(f"Request failed: {e!s}") from e - def browser_agent_status(self) -> Dict[str, Any]: + def browser_agent_status(self) -> dict[str, Any]: """ Caller's live queue snapshot. Useful for watching in-flight work against the per-user queue cap (1000 live tasks). @@ -693,15 +699,15 @@ def browser_agent_status(self) -> Dict[str, Any]: self._handle_response(response) return response.json() except requests.RequestException as e: - raise PredevAPIError(f"Request failed: {str(e)}") from e + raise PredevAPIError(f"Request failed: {e!s}") from e def browser_agent( self, - tasks: List[Dict[str, Any]], - concurrency: Optional[int] = None, + tasks: list[dict[str, Any]], + concurrency: int | None = None, stream: bool = False, - run_async: bool = False - ) -> Union[Dict[str, Any], Iterator[Dict[str, Any]]]: + run_async: bool = False, + ) -> dict[str, Any] | Iterator[dict[str, Any]]: """ Run browser-agent automation tasks - scrape data, fill forms, navigate pages. @@ -744,7 +750,7 @@ def browser_agent( return self._browser_agent_stream(tasks, concurrency) url = f"{self.base_url}/browser-agent" - payload: Dict[str, Any] = {"tasks": tasks} + payload: dict[str, Any] = {"tasks": tasks} if concurrency is not None: payload["concurrency"] = concurrency if run_async: @@ -752,34 +758,25 @@ def browser_agent( try: response = requests.post( - url, - headers=self.headers, - json=payload, - timeout=300 + url, headers=self.headers, json=payload, timeout=300 ) self._handle_response(response) return response.json() except requests.RequestException as e: - raise PredevAPIError(f"Request failed: {str(e)}") from e + raise PredevAPIError(f"Request failed: {e!s}") from e def _browser_agent_stream( - self, - tasks: List[Dict[str, Any]], - concurrency: Optional[int] = None - ) -> Iterator[Dict[str, Any]]: + self, tasks: list[dict[str, Any]], concurrency: int | None = None + ) -> Iterator[dict[str, Any]]: """SSE streaming implementation for browser_agent.""" url = f"{self.base_url}/browser-agent" - payload: Dict[str, Any] = {"tasks": tasks, "stream": True} + payload: dict[str, Any] = {"tasks": tasks, "stream": True} if concurrency is not None: payload["concurrency"] = concurrency try: response = requests.post( - url, - headers=self.headers, - json=payload, - stream=True, - timeout=300 + url, headers=self.headers, json=payload, stream=True, timeout=300 ) self._handle_response(response) @@ -808,25 +805,25 @@ def _browser_agent_stream( yield {"event": current_event, "data": data} current_event = "" except requests.RequestException as e: - raise PredevAPIError(f"Request failed: {str(e)}") from e + raise PredevAPIError(f"Request failed: {e!s}") from e def _make_request( self, endpoint: str, input_text: str, - current_context: Optional[str] = None, - doc_urls: Optional[List[str]] = None, - file: Optional[Union[str, BinaryIO]] = None + current_context: str | None = None, + doc_urls: list[str] | None = None, + file: str | BinaryIO | None = None, ) -> SpecResponse: """Make a POST request to the API.""" url = f"{self.base_url}{endpoint}" if file: - return self._make_request_with_file(url, input_text, current_context, doc_urls, file) + return self._make_request_with_file( + url, input_text, current_context, doc_urls, file + ) - payload = { - "input": input_text - } + payload = {"input": input_text} if current_context is not None: payload["currentContext"] = current_context @@ -836,34 +833,30 @@ def _make_request( try: response = requests.post( - url, - headers=self.headers, - json=payload, - timeout=300 + url, headers=self.headers, json=payload, timeout=300 ) self._handle_response(response) return response.json() except requests.RequestException as e: - raise PredevAPIError(f"Request failed: {str(e)}") from e + raise PredevAPIError(f"Request failed: {e!s}") from e def _make_request_async( self, endpoint: str, input_text: str, - current_context: Optional[str] = None, - doc_urls: Optional[List[str]] = None, - file: Optional[Union[str, BinaryIO]] = None + current_context: str | None = None, + doc_urls: list[str] | None = None, + file: str | BinaryIO | None = None, ) -> AsyncResponse: """Make an async POST request to the API.""" url = f"{self.base_url}{endpoint}" if file: - return self._make_request_with_file_async(url, input_text, current_context, doc_urls, file) + return self._make_request_with_file_async( + url, input_text, current_context, doc_urls, file + ) - payload = { - "input": input_text, - "async": True - } + payload = {"input": input_text, "async": True} if current_context is not None: payload["currentContext"] = current_context @@ -873,32 +866,30 @@ def _make_request_async( try: response = requests.post( - url, - headers=self.headers, - json=payload, - timeout=300 + url, headers=self.headers, json=payload, timeout=300 ) self._handle_response(response) return response.json() except requests.RequestException as e: - raise PredevAPIError(f"Request failed: {str(e)}") from e + raise PredevAPIError(f"Request failed: {e!s}") from e def _make_request_with_file( self, url: str, input_text: str, - current_context: Optional[str], - doc_urls: Optional[List[str]], - file: Union[str, BinaryIO] + current_context: str | None, + doc_urls: list[str] | None, + file: str | BinaryIO, ) -> SpecResponse: """Make a POST request with file upload.""" - headers = {key: value for key, value in self.headers.items() - if key.lower() != "content-type"} - - data = { - "input": input_text + headers = { + key: value + for key, value in self.headers.items() + if key.lower() != "content-type" } + data = {"input": input_text} + if current_context is not None: data["currentContext"] = current_context @@ -909,34 +900,30 @@ def _make_request_with_file( try: response = requests.post( - url, - headers=headers, - data=data, - files=files, - timeout=300 + url, headers=headers, data=data, files=files, timeout=300 ) self._handle_response(response) return response.json() except requests.RequestException as e: - raise PredevAPIError(f"Request failed: {str(e)}") from e + raise PredevAPIError(f"Request failed: {e!s}") from e def _make_request_with_file_async( self, url: str, input_text: str, - current_context: Optional[str], - doc_urls: Optional[List[str]], - file: Union[str, BinaryIO] + current_context: str | None, + doc_urls: list[str] | None, + file: str | BinaryIO, ) -> AsyncResponse: """Make an async POST request with file upload.""" - headers = {key: value for key, value in self.headers.items() - if key.lower() != "content-type"} - - data = { - "input": input_text, - "async": "true" + headers = { + key: value + for key, value in self.headers.items() + if key.lower() != "content-type" } + data = {"input": input_text, "async": "true"} + if current_context is not None: data["currentContext"] = current_context @@ -947,21 +934,18 @@ def _make_request_with_file_async( try: response = requests.post( - url, - headers=headers, - data=data, - files=files, - timeout=300 + url, headers=headers, data=data, files=files, timeout=300 ) self._handle_response(response) return response.json() except requests.RequestException as e: - raise PredevAPIError(f"Request failed: {str(e)}") from e + raise PredevAPIError(f"Request failed: {e!s}") from e - def _prepare_file(self, file: Union[str, BinaryIO]) -> Dict[str, Any]: + def _prepare_file(self, file: str | BinaryIO) -> dict[str, Any]: """Prepare file for multipart upload.""" if isinstance(file, str): - file_handle = open(file, "rb") + # requests reads and closes the handle when it sends the upload. + file_handle = open(file, "rb") # noqa: SIM115 filename = file.split("/")[-1] return {"file": (filename, file_handle)} else: @@ -987,11 +971,9 @@ def _handle_response(self, response: requests.Response) -> None: try: error_body = response.json() error_message = ( - error_body.get("error") - or error_body.get("message") - or str(error_body) + error_body.get("error") or error_body.get("message") or str(error_body) ) - except Exception: + except ValueError: # not JSON error_message = response.text or f"HTTP {response.status_code}" # Structured `code` wins — covers SUBSCRIPTION_REQUIRED / From ac0086bf1e958ca4609ec6d364cdd5733d26fb3a Mon Sep 17 00:00:00 2001 From: Smoke Person Date: Sat, 5 Dec 2026 01:15:42 -0500 Subject: [PATCH 2/3] feat: client.agent - build with the pre.dev agent (create, send, stream, build next/all, status, stop); 1.2.0 Both SDKs get an `agent` namespace over the new Agent API (/agent/projects/...): - Node: createProject, send, stream (async generator), buildNext, buildAll, status, stop; typed events and results - Python: create_project, send, stream (iterator), build_next, build_all, status, stop stream() parses SSE, skips heartbeats, ends after `done` by default, and reconnects from the last `cursor` event when the connection drops. Errors map to the existing typed exceptions ({ error, code } bodies). Tests mock HTTP (vitest 7, pytest 11). README sections in both packages. Version 1.2.0 (not published). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01PwA31qPkrcHj7kogbsmWS4 --- README.md | 33 +++ predev-api-node/README.md | 46 ++++ predev-api-node/package-lock.json | 4 +- predev-api-node/package.json | 2 +- predev-api-node/src/agent.test.ts | 130 ++++++++++ predev-api-node/src/agent.ts | 226 +++++++++++++++++ predev-api-node/src/client.ts | 8 + predev-api-node/src/index.ts | 15 ++ predev-api-node/src/types.ts | 104 ++++++++ predev-api-python/README.md | 49 ++++ predev-api-python/predev_api/__init__.py | 92 +++---- predev-api-python/predev_api/agent.py | 297 +++++++++++++++++++++++ predev-api-python/predev_api/client.py | 5 + predev-api-python/setup.py | 4 +- predev-api-python/tests/test_agent.py | 172 +++++++++++++ 15 files changed, 1137 insertions(+), 50 deletions(-) create mode 100644 predev-api-node/src/agent.test.ts create mode 100644 predev-api-node/src/agent.ts create mode 100644 predev-api-python/predev_api/agent.py create mode 100644 predev-api-python/tests/test_agent.py diff --git a/README.md b/README.md index 36ce3ae..6bc7190 100644 --- a/README.md +++ b/README.md @@ -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 @@ -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) diff --git a/predev-api-node/README.md b/predev-api-node/README.md index c236412..73aaf27 100644 --- a/predev-api-node/README.md +++ b/predev-api-node/README.md @@ -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. diff --git a/predev-api-node/package-lock.json b/predev-api-node/package-lock.json index e38c1b2..ab82135 100644 --- a/predev-api-node/package-lock.json +++ b/predev-api-node/package-lock.json @@ -1,12 +1,12 @@ { "name": "predev-api", - "version": "0.11.1", + "version": "1.2.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "predev-api", - "version": "0.11.1", + "version": "1.2.0", "license": "MIT", "devDependencies": { "@types/node": "^20.0.0", diff --git a/predev-api-node/package.json b/predev-api-node/package.json index 40d8b50..0a68f54 100644 --- a/predev-api-node/package.json +++ b/predev-api-node/package.json @@ -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", diff --git a/predev-api-node/src/agent.test.ts b/predev-api-node/src/agent.test.ts new file mode 100644 index 0000000..9435672 --- /dev/null +++ b/predev-api-node/src/agent.test.ts @@ -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({ + 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" }]); + }); +}); diff --git a/predev-api-node/src/agent.ts b/predev-api-node/src/agent.ts new file mode 100644 index 0000000..a66bb27 --- /dev/null +++ b/predev-api-node/src/agent.ts @@ -0,0 +1,226 @@ +/** + * `client.agent` — build with the pre.dev agent from code. + * + * Create a project from a prompt, talk to the agent, stream what it does, + * build the plan task by task, check progress and stop it. Every method calls + * the Agent API (`/agent/projects/...`) with the client's API key. + */ + +import type { + AgentBuildAccepted, + AgentBuildAllOptions, + AgentBuildNextOptions, + AgentCreateProjectOptions, + AgentEvent, + AgentMessageAccepted, + AgentProject, + AgentSendOptions, + AgentStatus, + AgentStopResult, + AgentStreamOptions, + ErrorResponse, +} from "./types.js"; +import { + AuthenticationError, + PredevAPIError, + RateLimitError, + exceptionForCode, +} from "./exceptions.js"; + +/** What the namespace needs from the client. */ +export interface AgentTransport { + baseUrl: string; + headers: Record; +} + +/** Turn a non-2xx response into the right typed exception. */ +export async function errorFromResponse(response: Response): Promise { + let body: ErrorResponse | undefined; + let message = `HTTP ${response.status}`; + try { + body = (await response.json()) as ErrorResponse; + message = body.error || body.message || JSON.stringify(body); + } catch { + /* keep `HTTP ` */ + } + if (body?.code) return exceptionForCode(body.code, message, body.actionUrl); + if (response.status === 401) return new AuthenticationError("Invalid API key"); + if (response.status === 429) return new RateLimitError(message); + return new PredevAPIError(`API request failed with status ${response.status}: ${message}`); +} + +/** One parsed Server-Sent Event. */ +export interface SSEFrame { + event: string; + data: string; + id?: string; +} + +/** Parse an SSE byte stream into frames (comments and `retry:` are skipped). */ +export async function* parseSSE(body: ReadableStream): AsyncGenerator { + const reader = body.getReader(); + const decoder = new TextDecoder(); + let buffer = ""; + let event = ""; + let data: string[] = []; + let id: string | undefined; + try { + while (true) { + const { done, value } = await reader.read(); + if (done) break; + buffer += decoder.decode(value, { stream: true }); + let nl: number; + while ((nl = buffer.indexOf("\n")) >= 0) { + const line = buffer.slice(0, nl).replace(/\r$/, ""); + buffer = buffer.slice(nl + 1); + if (line === "") { + if (data.length) yield { event: event || "message", data: data.join("\n"), ...(id ? { id } : {}) }; + event = ""; + data = []; + id = undefined; + } else if (line.startsWith(":")) { + continue; + } else if (line.startsWith("event:")) { + event = line.slice(6).trim(); + } else if (line.startsWith("data:")) { + data.push(line.slice(5).replace(/^ /, "")); + } else if (line.startsWith("id:")) { + id = line.slice(3).trim(); + } + } + } + } finally { + reader.releaseLock(); + } +} + +export class AgentClient { + constructor(private readonly transport: AgentTransport) {} + + private async request(method: "GET" | "POST", path: string, body?: unknown): Promise { + let response: Response; + try { + response = await fetch(`${this.transport.baseUrl}${path}`, { + method, + headers: this.transport.headers, + ...(body !== undefined ? { body: JSON.stringify(body) } : {}), + }); + } catch (error) { + throw new PredevAPIError(`Request failed: ${error instanceof Error ? error.message : String(error)}`); + } + if (!response.ok) throw await errorFromResponse(response); + return (await response.json()) as T; + } + + private projectPath(projectId: string, rest = ""): string { + return `/agent/projects/${encodeURIComponent(projectId)}${rest}`; + } + + /** + * Create a project from a prompt. The agent starts working right away. + * + * @example + * ```typescript + * const { projectId } = await client.agent.createProject({ prompt: "A habit tracker with streaks" }); + * ``` + */ + async createProject(options: AgentCreateProjectOptions): Promise { + return this.request("POST", "/agent/projects", options); + } + + /** + * Send the agent a message. Returns once the agent has accepted it (202); + * follow the reply with {@link stream}. + */ + async send(projectId: string, options: AgentSendOptions): Promise { + return this.request("POST", this.projectPath(projectId, "/messages"), options); + } + + /** Build the next task in the plan (or `task`, a custom one). */ + async buildNext(projectId: string, options: AgentBuildNextOptions = {}): Promise { + return this.request("POST", this.projectPath(projectId, "/build"), { ...options, all: false }); + } + + /** Build every remaining task in the plan. */ + async buildAll(projectId: string, options: AgentBuildAllOptions = {}): Promise { + return this.request("POST", this.projectPath(projectId, "/build"), { ...options, all: true }); + } + + /** Plan progress, whether the agent is running, and credits used so far. */ + async status(projectId: string, options: { sessionId?: string } = {}): Promise { + const query = options.sessionId ? `?sessionId=${encodeURIComponent(options.sessionId)}` : ""; + return this.request("GET", this.projectPath(projectId, `/status${query}`)); + } + + /** Stop the running agent (one session, or every run on the project). */ + async stop(projectId: string, options: { sessionId?: string } = {}): Promise { + return this.request("POST", this.projectPath(projectId, "/stop"), options); + } + + /** + * Stream what the agent does: `message.delta`, `message`, `tool`, + * `status`, `done` and `cursor` events. Ends after `done` unless + * `untilDone: false`; reconnects from the last cursor when the connection + * drops. + * + * @example + * ```typescript + * for await (const ev of client.agent.stream(projectId)) { + * if (ev.event === "message.delta") process.stdout.write(ev.data.delta); + * } + * ``` + */ + async *stream(projectId: string, options: AgentStreamOptions = {}): AsyncGenerator { + const untilDone = options.untilDone ?? true; + const maxReconnects = options.maxReconnects ?? 5; + let cursor = options.cursor; + let reconnects = 0; + while (true) { + const params = new URLSearchParams(); + if (options.sessionId) params.set("sessionId", options.sessionId); + if (cursor) params.set("cursor", cursor); + const qs = params.toString(); + let response: Response; + try { + response = await fetch(`${this.transport.baseUrl}${this.projectPath(projectId, `/events${qs ? `?${qs}` : ""}`)}`, { + method: "GET", + headers: { ...this.transport.headers, Accept: "text/event-stream" }, + signal: options.signal, + }); + } catch (error) { + if (options.signal?.aborted) return; + if (reconnects++ < maxReconnects) continue; + throw new PredevAPIError(`Request failed: ${error instanceof Error ? error.message : String(error)}`); + } + if (!response.ok) throw await errorFromResponse(response); + if (!response.body) throw new PredevAPIError("No response body"); + + try { + for await (const frame of parseSSE(response.body)) { + let data: any; + try { + data = JSON.parse(frame.data); + } catch { + continue; + } + if (frame.event === "error") { + throw exceptionForCode(data?.code, data?.error || data?.message || "Agent stream error", data?.actionUrl); + } + if (frame.event === "cursor" && data?.cursor) cursor = data.cursor; + reconnects = 0; + yield { event: frame.event, data } as AgentEvent; + if (frame.event === "done" && untilDone) return; + } + } catch (error) { + if (error instanceof PredevAPIError) throw error; + if (options.signal?.aborted) return; + if (reconnects++ >= maxReconnects) { + throw new PredevAPIError(`Stream failed: ${error instanceof Error ? error.message : String(error)}`); + } + continue; + } + // The server closed the stream cleanly: reconnect from the cursor. + if (options.signal?.aborted || reconnects++ >= maxReconnects) return; + } + } +} diff --git a/predev-api-node/src/client.ts b/predev-api-node/src/client.ts index a4d39c6..3416db9 100644 --- a/predev-api-node/src/client.ts +++ b/predev-api-node/src/client.ts @@ -24,6 +24,7 @@ import { RateLimitError, exceptionForCode, } from "./exceptions.js"; +import { AgentClient } from "./agent.js"; /** * Client for interacting with the Pre.dev Architect API. @@ -65,6 +66,12 @@ export class PredevAPI { private baseUrl: string; private headers: Record; + /** + * Build with the pre.dev agent: create a project, send messages, stream + * events, build the plan, check status, stop. + */ + readonly agent: AgentClient; + /** * Create a new Pre.dev API client * @@ -81,6 +88,7 @@ export class PredevAPI { Authorization: `Bearer ${this.apiKey}`, "Content-Type": "application/json", }; + this.agent = new AgentClient({ baseUrl: this.baseUrl, headers: this.headers }); } /** diff --git a/predev-api-node/src/index.ts b/predev-api-node/src/index.ts index ffe400f..0857209 100644 --- a/predev-api-node/src/index.ts +++ b/predev-api-node/src/index.ts @@ -5,6 +5,7 @@ */ export { PredevAPI } from "./client.js"; +export { AgentClient } from "./agent.js"; export { PredevAPIError, AuthenticationError, @@ -39,4 +40,18 @@ export type { BrowserAgentStreamResult, BrowserAgentSSEMessage, BrowserAgentStatus, + AgentProjectMode, + AgentChatMode, + AgentCreateProjectOptions, + AgentProject, + AgentSendOptions, + AgentMessageAccepted, + AgentBuildNextOptions, + AgentBuildAllOptions, + AgentBuildAccepted, + AgentFeatureStatus, + AgentStatus, + AgentStopResult, + AgentStreamOptions, + AgentEvent, } from "./types.js"; diff --git a/predev-api-node/src/types.ts b/predev-api-node/src/types.ts index 3e364af..1b400a3 100644 --- a/predev-api-node/src/types.ts +++ b/predev-api-node/src/types.ts @@ -322,3 +322,107 @@ export interface BrowserAgentStatus { total: number; cap: number; } + +// ── Agent API (build with the pre.dev agent) ──────────────────────────────── + +/** `build` starts building right away; `plan` writes the plan first (architect mode). */ +export type AgentProjectMode = "build" | "plan"; +/** Chat mode for a message: `auto` lets the agent act, `plan` restricts it to planning. */ +export type AgentChatMode = "auto" | "plan"; + +export interface AgentCreateProjectOptions { + /** What to build, in plain words. */ + prompt: string; + mode?: AgentProjectMode; + /** A model key such as `anthropic::claude-opus-4-5`; omit for the default. */ + model?: string; + /** Retrying with the same key returns the same project instead of a second one. */ + idempotencyKey?: string; +} + +export interface AgentProject { + projectId: string; + /** The project's Main chat session. */ + sessionId: string | null; +} + +export interface AgentSendOptions { + message: string; + /** Defaults to the project's Main session. */ + sessionId?: string; + mode?: AgentChatMode; + model?: string; +} + +export interface AgentMessageAccepted { + sessionId: string | null; + /** The agent's reply message id, when it was known before the call returned. */ + messageId?: string; +} + +export interface AgentBuildNextOptions { + /** A custom task to build instead of the next one in the plan. */ + task?: string; + sessionId?: string; + /** Stop the run once it has spent this many credits. */ + maxCredits?: number; +} + +export interface AgentBuildAllOptions { + maxCredits?: number; +} + +export interface AgentBuildAccepted { + sessionId: string | null; + kind: "next" | "all"; + message?: string; +} + +export interface AgentFeatureStatus { + id: string; + name: string; + status: string; + statusText: string; + doneStories: number; + totalStories: number; +} + +export interface AgentStatus { + projectId: string; + sessionId: string | null; + state: "running" | "idle"; + agentStatus: string | null; + runTitle: string | null; + chatMode: string; + progress: { percent: number; done: number; total: number; left: number; ready: number }; + summary: string; + features: AgentFeatureStatus[]; + creditsUsed: number; +} + +export interface AgentStopResult { + stopped: boolean; + message: string; +} + +export interface AgentStreamOptions { + sessionId?: string; + /** Resume after this cursor (from a previous `cursor` event). */ + cursor?: string; + /** End the iterator after the run's `done` event (default true). */ + untilDone?: boolean; + /** Reconnect from the last cursor when the connection drops (default 5 tries; 0 = never). */ + maxReconnects?: number; + signal?: AbortSignal; +} + +export type AgentEvent = + | { event: "message.delta"; data: { messageId: string; delta: string; subAgentId?: string } } + | { + event: "message"; + data: { messageId: string; role: string; content: string; completed: boolean; replayed?: boolean; subAgentId?: string }; + } + | { event: "tool"; data: { messageId: string; tool: string; toolId: string | null; text: string; completed: boolean } } + | { event: "status"; data: { state: "running" | "idle"; agentStatus: string | null; runTitle: string | null } } + | { event: "done"; data: { state: "idle" } } + | { event: "cursor"; data: { cursor: string } }; diff --git a/predev-api-python/README.md b/predev-api-python/README.md index 798980c..e9a9ef5 100644 --- a/predev-api-python/README.md +++ b/predev-api-python/README.md @@ -460,6 +460,55 @@ For more information about the Pre.dev Architect API, visit: For issues, questions, or contributions, please visit the [GitHub repository](https://github.com/predotdev/predev-api). +## 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. + +```python +import os +from predev_api import PredevAPI + +client = PredevAPI(api_key=os.environ["PREDEV_API_KEY"]) + +# 1. Create a project. The agent starts on it right away. +project = client.agent.create_project( + "A habit tracker with daily streaks and reminders", + mode="plan", # "build" (default) builds right away; "plan" plans first +) +project_id = project["projectId"] + +# 2. Stream the agent's work until the 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']}]") + +# 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"] == "status": + print(event["data"]["agentStatus"] or event["data"]["state"]) + +# 4. Check progress. +status = client.agent.status(project_id) +print(f"{status['progress']['percent']}% built, {status['creditsUsed']} credits used") +``` + +### Agent methods + +| Method | What it does | +| --- | --- | +| `agent.create_project(prompt, mode=None, model=None, idempotency_key=None)` | New project from a prompt. Returns `{"projectId", "sessionId"}`. | +| `agent.send(project_id, message, session_id=None, mode=None, model=None)` | Send a message (`mode`: `"auto"` or `"plan"`). Returns once the agent accepts it. | +| `agent.stream(project_id, session_id=None, cursor=None, until_done=True, max_reconnects=5)` | Iterator of `message.delta`, `message`, `tool`, `status`, `done`, `cursor` events. Ends after `done` by default and reconnects from the last cursor. | +| `agent.build_next(project_id, task=None, session_id=None, max_credits=None)` | Build the next task in the plan, or `task`. | +| `agent.build_all(project_id, max_credits=None)` | Build every remaining task. | +| `agent.status(project_id, session_id=None)` | `state` (`running`/`idle`), plan `progress`, `features`, `creditsUsed`. | +| `agent.stop(project_id, session_id=None)` | 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, interact, and/or extract data from any web page. Each task navigates a URL, performs actions, and optionally returns typed JSON. diff --git a/predev-api-python/predev_api/__init__.py b/predev-api-python/predev_api/__init__.py index 5b45168..4100b5b 100644 --- a/predev-api-python/predev_api/__init__.py +++ b/predev-api-python/predev_api/__init__.py @@ -4,69 +4,71 @@ Generate comprehensive software specifications using AI. """ +from .agent import AgentClient from .client import ( - PredevAPI, - ZippedDocsUrl, - SpecCoreFunctionality, - SpecTechStackItem, - SpecPersona, - SpecRole, - CodingAgentSubTask, - CodingAgentStory, + AlternativeTechStackItemApi, CodingAgentMilestone, CodingAgentSpecJson, - HumanSpecSubTask, - HumanSpecStory, - HumanSpecMilestone, - HumanSpecJson, - SpecResponse, - SpecGraphNode, - SpecGraphEdge, - SpecGraph, + CodingAgentStory, + CodingAgentSubTask, HelpfulLink, - AlternativeTechStackItemApi, + HumanSpecJson, + HumanSpecMilestone, + HumanSpecStory, + HumanSpecSubTask, + PredevAPI, + SpecCoreFunctionality, SpecEnrichedTechStackItem, + SpecGraph, + SpecGraphEdge, + SpecGraphNode, + SpecPersona, + SpecResponse, + SpecRole, + SpecTechStackItem, + ZippedDocsUrl, ) from .exceptions import ( - PredevAPIError, AuthenticationError, - RateLimitError, - SubscriptionRequiredError, + BatchTooLargeError, InsufficientCreditsError, + PredevAPIError, QueueFullError, - BatchTooLargeError, + RateLimitError, + SubscriptionRequiredError, exception_for_code, ) -__version__ = "1.1.0" +__version__ = "1.2.0" __all__ = [ - "PredevAPI", - "PredevAPIError", + "AgentClient", + "AlternativeTechStackItemApi", "AuthenticationError", - "RateLimitError", - "SubscriptionRequiredError", - "InsufficientCreditsError", - "QueueFullError", "BatchTooLargeError", - "exception_for_code", - "ZippedDocsUrl", - "SpecCoreFunctionality", - "SpecTechStackItem", - "SpecPersona", - "SpecRole", - "CodingAgentSubTask", - "CodingAgentStory", "CodingAgentMilestone", "CodingAgentSpecJson", - "HumanSpecSubTask", - "HumanSpecStory", - "HumanSpecMilestone", - "HumanSpecJson", - "SpecResponse", - "SpecGraphNode", - "SpecGraphEdge", - "SpecGraph", + "CodingAgentStory", + "CodingAgentSubTask", "HelpfulLink", - "AlternativeTechStackItemApi", + "HumanSpecJson", + "HumanSpecMilestone", + "HumanSpecStory", + "HumanSpecSubTask", + "InsufficientCreditsError", + "PredevAPI", + "PredevAPIError", + "QueueFullError", + "RateLimitError", + "SpecCoreFunctionality", "SpecEnrichedTechStackItem", + "SpecGraph", + "SpecGraphEdge", + "SpecGraphNode", + "SpecPersona", + "SpecResponse", + "SpecRole", + "SpecTechStackItem", + "SubscriptionRequiredError", + "ZippedDocsUrl", + "exception_for_code", ] diff --git a/predev-api-python/predev_api/agent.py b/predev-api-python/predev_api/agent.py new file mode 100644 index 0000000..caae518 --- /dev/null +++ b/predev-api-python/predev_api/agent.py @@ -0,0 +1,297 @@ +""" +``client.agent`` - build with the pre.dev agent from code. + +Create a project from a prompt, talk to the agent, stream what it does, build +the plan task by task, check progress and stop it. Every method calls the +Agent API (``/agent/projects/...``) with the client's API key. +""" + +from __future__ import annotations + +import json +from collections.abc import Iterator +from typing import TYPE_CHECKING, Any, Literal +from urllib.parse import quote + +import requests + +from .exceptions import ( + AuthenticationError, + PredevAPIError, + RateLimitError, + exception_for_code, +) + +if TYPE_CHECKING: + from .client import PredevAPI + +ProjectMode = Literal["build", "plan"] +ChatMode = Literal["auto", "plan"] + + +def _raise_for_response(response: requests.Response) -> None: + """Raise the typed exception for a non-2xx response.""" + if 200 <= response.status_code < 300: + return + body: Any = None + message = f"HTTP {response.status_code}" + try: + body = response.json() + if isinstance(body, dict): + message = body.get("error") or body.get("message") or str(body) + except ValueError: # not JSON + message = response.text or message + if isinstance(body, dict) and body.get("code"): + raise exception_for_code(body["code"], message, body.get("actionUrl")) + if response.status_code == 401: + raise AuthenticationError("Invalid API key") + if response.status_code == 429: + raise RateLimitError(message) + raise PredevAPIError( + f"API request failed with status {response.status_code}: {message}" + ) + + +def parse_sse(lines: Iterator[str]) -> Iterator[dict[str, Any]]: + """Parse SSE lines into ``{"event", "data", "id"?}`` frames. + + Comments (heartbeats) and ``retry:`` lines are skipped. + """ + event = "" + data: list[str] = [] + frame_id: str | None = None + for raw in lines: + line = raw.rstrip("\r") if raw is not None else "" + if line == "": + if data: + frame: dict[str, Any] = { + "event": event or "message", + "data": "\n".join(data), + } + if frame_id: + frame["id"] = frame_id + yield frame + event, data, frame_id = "", [], None + elif line.startswith(":"): + continue + elif line.startswith("event:"): + event = line[6:].strip() + elif line.startswith("data:"): + value = line[5:] + data.append(value.removeprefix(" ")) + elif line.startswith("id:"): + frame_id = line[3:].strip() + if data: + yield {"event": event or "message", "data": "\n".join(data)} + + +class AgentClient: + """The ``client.agent`` namespace. Create it through :class:`PredevAPI`. + + Example: + >>> client = PredevAPI(api_key="...") + >>> project = client.agent.create_project("A habit tracker with streaks") + >>> for event in client.agent.stream(project["projectId"]): + ... if event["event"] == "message.delta": + ... print(event["data"]["delta"], end="") + """ + + def __init__(self, client: PredevAPI): + self._client = client + + # -- plumbing --------------------------------------------------------- + + def _url(self, path: str) -> str: + return f"{self._client.base_url}{path}" + + def _project(self, project_id: str, rest: str = "") -> str: + return f"/agent/projects/{quote(project_id, safe='')}{rest}" + + def _post(self, path: str, payload: dict[str, Any]) -> dict[str, Any]: + try: + response = requests.post( + self._url(path), headers=self._client.headers, json=payload, timeout=120 + ) + except requests.RequestException as e: + raise PredevAPIError(f"Request failed: {e}") from e + _raise_for_response(response) + return response.json() + + def _get(self, path: str, params: dict[str, str] | None = None) -> dict[str, Any]: + try: + response = requests.get( + self._url(path), headers=self._client.headers, params=params, timeout=60 + ) + except requests.RequestException as e: + raise PredevAPIError(f"Request failed: {e}") from e + _raise_for_response(response) + return response.json() + + @staticmethod + def _compact(**fields: Any) -> dict[str, Any]: + return {k: v for k, v in fields.items() if v is not None} + + # -- methods ---------------------------------------------------------- + + def create_project( + self, + prompt: str, + mode: ProjectMode | None = None, + model: str | None = None, + idempotency_key: str | None = None, + ) -> dict[str, Any]: + """Create a project from a prompt. The agent starts working right away. + + Args: + prompt: What to build, in plain words. + mode: ``"build"`` (default) builds right away; ``"plan"`` plans first. + model: A model key; omit for the default. + idempotency_key: Retrying with the same key returns the same project. + + Returns: + ``{"projectId": str, "sessionId": str | None}`` + """ + return self._post( + "/agent/projects", + self._compact( + prompt=prompt, mode=mode, model=model, idempotencyKey=idempotency_key + ), + ) + + def send( + self, + project_id: str, + message: str, + session_id: str | None = None, + mode: ChatMode | None = None, + model: str | None = None, + ) -> dict[str, Any]: + """Send the agent a message. Returns once the agent accepted it. + + Follow the reply with :meth:`stream`. + + Returns: + ``{"sessionId": str | None, "messageId"?: str}`` + """ + return self._post( + self._project(project_id, "/messages"), + self._compact( + message=message, sessionId=session_id, mode=mode, model=model + ), + ) + + def build_next( + self, + project_id: str, + task: str | None = None, + session_id: str | None = None, + max_credits: float | None = None, + ) -> dict[str, Any]: + """Build the next task in the plan (or ``task``, a custom one). + + Args: + max_credits: Stop the run once it has spent this many credits. + """ + return self._post( + self._project(project_id, "/build"), + self._compact( + all=False, task=task, sessionId=session_id, maxCredits=max_credits + ), + ) + + def build_all( + self, project_id: str, max_credits: float | None = None + ) -> dict[str, Any]: + """Build every remaining task in the plan.""" + return self._post( + self._project(project_id, "/build"), + self._compact(all=True, maxCredits=max_credits), + ) + + def status(self, project_id: str, session_id: str | None = None) -> dict[str, Any]: + """Plan progress, whether the agent is running, and credits used so far. + + Returns: + ``{"state": "running" | "idle", "progress": {...}, "features": [...], + "creditsUsed": float, ...}`` + """ + params = {"sessionId": session_id} if session_id else None + return self._get(self._project(project_id, "/status"), params) + + def stop(self, project_id: str, session_id: str | None = None) -> dict[str, Any]: + """Stop the running agent (one session, or every run on the project). + + Returns: + ``{"stopped": bool, "message": str}`` + """ + return self._post( + self._project(project_id, "/stop"), self._compact(sessionId=session_id) + ) + + def stream( + self, + project_id: str, + session_id: str | None = None, + cursor: str | None = None, + until_done: bool = True, + max_reconnects: int = 5, + ) -> Iterator[dict[str, Any]]: + """Stream what the agent does. + + Yields ``{"event": str, "data": dict}`` for ``message.delta``, + ``message``, ``tool``, ``status``, ``done`` and ``cursor`` events. + Ends after ``done`` unless ``until_done=False``; reconnects from the + last cursor when the connection drops. + + Args: + cursor: Resume after this cursor (from a previous ``cursor`` event). + """ + reconnects = 0 + while True: + params = self._compact(sessionId=session_id, cursor=cursor) + headers = {**self._client.headers, "Accept": "text/event-stream"} + try: + response = requests.get( + self._url(self._project(project_id, "/events")), + headers=headers, + params=params or None, + stream=True, + timeout=(10, 60), + ) + except requests.RequestException as e: + if reconnects < max_reconnects: + reconnects += 1 + continue + raise PredevAPIError(f"Request failed: {e}") from e + _raise_for_response(response) + try: + for frame in parse_sse(response.iter_lines(decode_unicode=True)): + try: + data = json.loads(frame["data"]) + except ValueError: + continue + if frame["event"] == "error": + raise exception_for_code( + data.get("code"), + data.get("error") + or data.get("message") + or "Agent stream error", + data.get("actionUrl"), + ) + if frame["event"] == "cursor" and data.get("cursor"): + cursor = data["cursor"] + reconnects = 0 + yield {"event": frame["event"], "data": data} + if frame["event"] == "done" and until_done: + return + except requests.RequestException as e: + if reconnects >= max_reconnects: + raise PredevAPIError(f"Stream failed: {e}") from e + reconnects += 1 + continue + finally: + response.close() + # The server closed the stream cleanly: reconnect from the cursor. + if reconnects >= max_reconnects: + return + reconnects += 1 diff --git a/predev-api-python/predev_api/client.py b/predev-api-python/predev_api/client.py index 56a6783..31c9cde 100644 --- a/predev-api-python/predev_api/client.py +++ b/predev-api-python/predev_api/client.py @@ -11,6 +11,7 @@ import requests +from .agent import AgentClient from .exceptions import ( AuthenticationError, PredevAPIError, @@ -287,6 +288,10 @@ def __init__(self, api_key: str, base_url: str = "https://api.pre.dev"): "Content-Type": "application/json", } + #: Build with the pre.dev agent: create a project, send messages, + #: stream events, build the plan, check status, stop. + self.agent = AgentClient(self) + def fast_spec( self, input_text: str, diff --git a/predev-api-python/setup.py b/predev-api-python/setup.py index c958666..78606cb 100644 --- a/predev-api-python/setup.py +++ b/predev-api-python/setup.py @@ -2,14 +2,14 @@ Setup configuration for predev_api package """ -from setuptools import setup, find_packages +from setuptools import find_packages, setup with open("README.md", "r", encoding="utf-8") as fh: long_description = fh.read() setup( name="predev-api", - version="1.1.0", + version="1.2.0", author="Pre.dev", author_email="support@pre.dev", description="Python client for the Pre.dev Architect API - Generate comprehensive software specifications", diff --git a/predev-api-python/tests/test_agent.py b/predev-api-python/tests/test_agent.py new file mode 100644 index 0000000..e2a8b93 --- /dev/null +++ b/predev-api-python/tests/test_agent.py @@ -0,0 +1,172 @@ +"""Tests for client.agent (HTTP mocked).""" + +from unittest.mock import Mock, patch + +import pytest +import requests + +from predev_api import ( + AuthenticationError, + InsufficientCreditsError, + PredevAPI, + PredevAPIError, + RateLimitError, +) +from predev_api.agent import parse_sse + +BASE = "https://api.test" + + +def client(): + return PredevAPI(api_key="k", base_url=BASE + "/") + + +def response(status, body=None, lines=None): + r = Mock() + r.status_code = status + r.json.return_value = body if body is not None else {} + r.text = "" + r.iter_lines.return_value = iter(lines or []) + return r + + +@patch("predev_api.agent.requests.post") +def test_create_project_posts_prompt(mock_post): + mock_post.return_value = response(201, {"projectId": "p1", "sessionId": "s1"}) + out = client().agent.create_project( + "A todo app", mode="plan", idempotency_key="k-1" + ) + assert out == {"projectId": "p1", "sessionId": "s1"} + args, kwargs = mock_post.call_args + assert args[0] == f"{BASE}/agent/projects" + assert kwargs["headers"]["Authorization"] == "Bearer k" + assert kwargs["json"] == { + "prompt": "A todo app", + "mode": "plan", + "idempotencyKey": "k-1", + } + + +@patch("predev_api.agent.requests.get") +@patch("predev_api.agent.requests.post") +def test_send_build_status_stop_routes(mock_post, mock_get): + c = client() + mock_post.return_value = response(202, {"sessionId": "s1"}) + c.agent.send("p1", "Add login", mode="auto") + assert mock_post.call_args[0][0] == f"{BASE}/agent/projects/p1/messages" + assert mock_post.call_args[1]["json"] == {"message": "Add login", "mode": "auto"} + + c.agent.build_next("p1", task="Login form", max_credits=20) + assert mock_post.call_args[0][0] == f"{BASE}/agent/projects/p1/build" + assert mock_post.call_args[1]["json"] == { + "all": False, + "task": "Login form", + "maxCredits": 20, + } + + c.agent.build_all("p1") + assert mock_post.call_args[1]["json"] == {"all": True} + + mock_post.return_value = response(200, {"stopped": True, "message": ""}) + assert c.agent.stop("p1", session_id="s1") == {"stopped": True, "message": ""} + assert mock_post.call_args[0][0] == f"{BASE}/agent/projects/p1/stop" + assert mock_post.call_args[1]["json"] == {"sessionId": "s1"} + + mock_get.return_value = response(200, {"state": "idle", "creditsUsed": 3}) + assert c.agent.status("p1", session_id="s1")["creditsUsed"] == 3 + assert mock_get.call_args[0][0] == f"{BASE}/agent/projects/p1/status" + assert mock_get.call_args[1]["params"] == {"sessionId": "s1"} + + +@pytest.mark.parametrize( + ("status", "body", "exc"), + [ + (401, {"error": "Missing API key"}, AuthenticationError), + (429, {"error": "Rate limit", "code": "RATE_LIMITED"}, RateLimitError), + ( + 402, + {"error": "Out of credits", "code": "INSUFFICIENT_CREDITS"}, + InsufficientCreditsError, + ), + (404, {"error": "Project not found", "code": "NOT_FOUND"}, PredevAPIError), + ], +) +@patch("predev_api.agent.requests.post") +def test_errors_map_to_typed_exceptions(mock_post, status, body, exc): + mock_post.return_value = response(status, body) + with pytest.raises(exc) as info: + client().agent.build_next("p1") + if body.get("code"): + assert body["error"] in str(info.value) + + +@patch("predev_api.agent.requests.post") +def test_network_error_is_predev_error(mock_post): + mock_post.side_effect = requests.ConnectionError("reset") + with pytest.raises(PredevAPIError): + client().agent.send("p1", "hi") + + +@patch("predev_api.agent.requests.get") +def test_stream_yields_until_done(mock_get): + mock_get.return_value = response( + 200, + lines=[ + "retry: 3000", + "", + "id: c1", + "event: cursor", + 'data: {"cursor":"c1"}', + "", + ": ping 1", + "", + "event: message.delta", + 'data: {"messageId":"m1","delta":"Hi"}', + "", + "event: tool", + 'data: {"messageId":"t1","tool":"bash","toolId":null,"text":"","completed":false}', + "", + "event: done", + 'data: {"state":"idle"}', + "", + "event: status", + 'data: {"state":"idle"}', + "", + ], + ) + events = list(client().agent.stream("p1", session_id="s1")) + assert [e["event"] for e in events] == ["cursor", "message.delta", "tool", "done"] + assert events[1]["data"] == {"messageId": "m1", "delta": "Hi"} + assert mock_get.call_args[0][0] == f"{BASE}/agent/projects/p1/events" + assert mock_get.call_args[1]["params"] == {"sessionId": "s1"} + assert mock_get.call_args[1]["stream"] is True + + +@patch("predev_api.agent.requests.get") +def test_stream_resumes_from_cursor(mock_get): + mock_get.side_effect = [ + response(200, lines=["event: cursor", 'data: {"cursor":"abc"}', ""]), + response(200, lines=["event: done", 'data: {"state":"idle"}', ""]), + ] + events = [e["event"] for e in client().agent.stream("p1")] + assert events == ["cursor", "done"] + assert mock_get.call_args_list[1][1]["params"] == {"cursor": "abc"} + + +@patch("predev_api.agent.requests.get") +def test_stream_error_event_raises(mock_get): + mock_get.return_value = response( + 200, + lines=[ + "event: error", + 'data: {"error":"Could not open","code":"STREAM_FAILED"}', + "", + ], + ) + with pytest.raises(PredevAPIError, match="Could not open"): + list(client().agent.stream("p1")) + + +def test_parse_sse_multiline_and_id(): + frames = list(parse_sse(iter(["id: 7", "event: x", "data: a", "data: b", ""]))) + assert frames == [{"event": "x", "data": "a\nb", "id": "7"}] From 2f0deb8c17f93e9199b362ed39a666242041aa46 Mon Sep 17 00:00:00 2001 From: Smoke Person Date: Sat, 5 Dec 2026 01:15:42 -0500 Subject: [PATCH 3/3] ci: publish npm + PyPI from a v* tag (release.yml) Pushing `vX.Y.Z` checks the tag matches package.json, setup.py and __init__.py, runs make check, then publishes predev-api to npm (with provenance, NPM_TOKEN) and PyPI (PYPI_API_TOKEN). Documented under Releasing in the root README. scripts/deploy.sh stays for manual releases. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01PwA31qPkrcHj7kogbsmWS4 --- .github/workflows/release.yml | 83 +++++++++++++++++++++++++++ predev-api-python/tests/test_agent.py | 1 - 2 files changed, 83 insertions(+), 1 deletion(-) create mode 100644 .github/workflows/release.yml diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..5aec70e --- /dev/null +++ b/.github/workflows/release.yml @@ -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 }} diff --git a/predev-api-python/tests/test_agent.py b/predev-api-python/tests/test_agent.py index e2a8b93..c2817cf 100644 --- a/predev-api-python/tests/test_agent.py +++ b/predev-api-python/tests/test_agent.py @@ -4,7 +4,6 @@ import pytest import requests - from predev_api import ( AuthenticationError, InsufficientCreditsError,