vangrex 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
File without changes
vangrex-0.1.0/LICENSE ADDED
@@ -0,0 +1,22 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Mohammed Maaz
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished
11
+ to do so, subject to the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be included in all
14
+ copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ SOFTWARE.
vangrex-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,39 @@
1
+ Metadata-Version: 2.5
2
+ Name: vangrex
3
+ Version: 0.1.0
4
+ Summary: Official Python SDK for the Vangrex AI workflow platform
5
+ Project-URL: Homepage, https://vangrex.com
6
+ Project-URL: Repository, https://github.com/Maaz2623/vangrex-v4
7
+ Author: Mohammed Maaz
8
+ License: MIT
9
+ License-File: LICENSE
10
+ Keywords: agents,ai,automation,vangrex,workflow
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: License :: OSI Approved :: MIT License
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3 :: Only
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Requires-Python: >=3.10
21
+ Requires-Dist: httpx<1.0.0,>=0.27.0
22
+ Provides-Extra: dev
23
+ Requires-Dist: pytest-asyncio<2.0,>=0.23; extra == 'dev'
24
+ Requires-Dist: pytest<9.0,>=8.0; extra == 'dev'
25
+ Requires-Dist: respx<1.0,>=0.21; extra == 'dev'
26
+ Requires-Dist: ruff<1.0,>=0.6; extra == 'dev'
27
+ Description-Content-Type: text/markdown
28
+
29
+ # Vangrex Python SDK
30
+
31
+ Official Python SDK for the Vangrex AI workflow platform.
32
+
33
+ Trigger Vangrex workflows from your Python applications and consume execution updates in real time.
34
+
35
+ ## Installation
36
+
37
+ ```bash
38
+ pip install vangrex
39
+ ```
@@ -0,0 +1,11 @@
1
+ # Vangrex Python SDK
2
+
3
+ Official Python SDK for the Vangrex AI workflow platform.
4
+
5
+ Trigger Vangrex workflows from your Python applications and consume execution updates in real time.
6
+
7
+ ## Installation
8
+
9
+ ```bash
10
+ pip install vangrex
11
+ ```
@@ -0,0 +1,78 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+
6
+ [project]
7
+ name = "vangrex"
8
+ version = "0.1.0"
9
+ description = "Official Python SDK for the Vangrex AI workflow platform"
10
+ readme = "README.md"
11
+ requires-python = ">=3.10"
12
+ license = { text = "MIT" }
13
+
14
+ authors = [
15
+ { name = "Mohammed Maaz" }
16
+ ]
17
+
18
+ dependencies = [
19
+ "httpx>=0.27.0,<1.0.0"
20
+ ]
21
+
22
+ keywords = [
23
+ "vangrex",
24
+ "ai",
25
+ "workflow",
26
+ "automation",
27
+ "agents"
28
+ ]
29
+
30
+ classifiers = [
31
+ "Development Status :: 4 - Beta",
32
+ "Intended Audience :: Developers",
33
+ "License :: OSI Approved :: MIT License",
34
+ "Programming Language :: Python :: 3",
35
+ "Programming Language :: Python :: 3 :: Only",
36
+ "Programming Language :: Python :: 3.10",
37
+ "Programming Language :: Python :: 3.11",
38
+ "Programming Language :: Python :: 3.12",
39
+ "Programming Language :: Python :: 3.13",
40
+ ]
41
+
42
+
43
+ [project.optional-dependencies]
44
+ dev = [
45
+ "pytest>=8.0,<9.0",
46
+ "pytest-asyncio>=0.23,<2.0",
47
+ "respx>=0.21,<1.0",
48
+ "ruff>=0.6,<1.0",
49
+ ]
50
+
51
+
52
+ [project.urls]
53
+ Homepage = "https://vangrex.com"
54
+ Repository = "https://github.com/Maaz2623/vangrex-v4"
55
+
56
+
57
+ [tool.hatch.build.targets.wheel]
58
+ packages = ["vangrex"]
59
+
60
+
61
+ [tool.ruff]
62
+ line-length = 88
63
+ target-version = "py310"
64
+
65
+
66
+ [tool.ruff.lint]
67
+ select = [
68
+ "E",
69
+ "F",
70
+ "I",
71
+ "UP",
72
+ "B",
73
+ ]
74
+
75
+
76
+ [tool.pytest.ini_options]
77
+ testpaths = ["tests"]
78
+ asyncio_mode = "auto"
@@ -0,0 +1,66 @@
1
+ import httpx
2
+ import pytest
3
+ import respx
4
+
5
+ from vangrex import AsyncVangrex
6
+
7
+
8
+ @pytest.mark.asyncio
9
+ @respx.mock
10
+ async def test_async_run_workflow():
11
+ respx.post(
12
+ "https://api.vangrex.com/api/v1/workflows/workflow-123/executions"
13
+ ).mock(
14
+ return_value=httpx.Response(
15
+ 200,
16
+ json={
17
+ "executionId": "execution-123",
18
+ "status": "pending",
19
+ },
20
+ )
21
+ )
22
+
23
+ client = AsyncVangrex(api_key="vx_test")
24
+
25
+ result = await client.workflows.run(
26
+ "workflow-123",
27
+ {"message": "hello"},
28
+ )
29
+
30
+ assert result.execution_id == "execution-123"
31
+ assert result.status == "pending"
32
+
33
+ await client.close()
34
+
35
+
36
+ @pytest.mark.asyncio
37
+ @respx.mock
38
+ async def test_async_get_execution():
39
+ respx.get(
40
+ "https://api.vangrex.com/api/v1/executions/execution-123"
41
+ ).mock(
42
+ return_value=httpx.Response(
43
+ 200,
44
+ json={
45
+ "id": "execution-123",
46
+ "workflowId": "workflow-123",
47
+ "status": "success",
48
+ "input": {},
49
+ "output": {"result": "done"},
50
+ "error": None,
51
+ "startedAt": None,
52
+ "completedAt": None,
53
+ "createdAt": "2026-09-11T10:00:00Z",
54
+ },
55
+ )
56
+ )
57
+
58
+ client = AsyncVangrex(api_key="vx_test")
59
+
60
+ execution = await client.executions.get("execution-123")
61
+
62
+ assert execution.id == "execution-123"
63
+ assert execution.status == "success"
64
+ assert execution.output == {"result": "done"}
65
+
66
+ await client.close()
@@ -0,0 +1,37 @@
1
+ import httpx
2
+ import pytest
3
+ import respx
4
+
5
+ from vangrex import Vangrex, VangrexError
6
+
7
+
8
+ @respx.mock
9
+ def test_api_error():
10
+ respx.get(
11
+ "https://api.vangrex.com/api/v1/executions/bad-execution"
12
+ ).mock(
13
+ return_value=httpx.Response(
14
+ 404,
15
+ json={
16
+ "error": "Execution not found",
17
+ },
18
+ )
19
+ )
20
+
21
+ client = Vangrex(api_key="vx_test")
22
+
23
+ with pytest.raises(VangrexError) as exc_info:
24
+ client.executions.get("bad-execution")
25
+
26
+ error = exc_info.value
27
+
28
+ assert error.status == 404
29
+ assert error.message == "Execution not found"
30
+ assert error.body == {"error": "Execution not found"}
31
+
32
+ client.close()
33
+
34
+
35
+ def test_empty_api_key():
36
+ with pytest.raises(ValueError):
37
+ Vangrex(api_key="")
@@ -0,0 +1,73 @@
1
+ import httpx
2
+ import respx
3
+
4
+ from vangrex import Vangrex
5
+
6
+
7
+ @respx.mock
8
+ def test_get_execution():
9
+ respx.get(
10
+ "https://api.vangrex.com/api/v1/executions/execution-123"
11
+ ).mock(
12
+ return_value=httpx.Response(
13
+ 200,
14
+ json={
15
+ "id": "execution-123",
16
+ "workflowId": "workflow-123",
17
+ "status": "success",
18
+ "input": {"message": "hello"},
19
+ "output": {"result": "world"},
20
+ "error": None,
21
+ "startedAt": "2026-09-11T10:00:00Z",
22
+ "completedAt": "2026-09-11T10:00:03Z",
23
+ "createdAt": "2026-09-11T10:00:00Z",
24
+ },
25
+ )
26
+ )
27
+
28
+ client = Vangrex(api_key="vx_test")
29
+
30
+ execution = client.executions.get("execution-123")
31
+
32
+ assert execution.id == "execution-123"
33
+ assert execution.workflow_id == "workflow-123"
34
+ assert execution.status == "success"
35
+ assert execution.output == {"result": "world"}
36
+
37
+ client.close()
38
+
39
+
40
+ @respx.mock
41
+ def test_execution_events():
42
+ respx.get(
43
+ "https://api.vangrex.com/api/v1/executions/execution-123/events"
44
+ ).mock(
45
+ return_value=httpx.Response(
46
+ 200,
47
+ headers={"Content-Type": "text/event-stream"},
48
+ content=(
49
+ b'data: {"id":"event-1","executionId":"execution-123",'
50
+ b'"workflowId":"workflow-123","type":"execution.started",'
51
+ b'"timestamp":"2026-09-11T10:00:00Z","data":{}}\n\n'
52
+ b'data: {"id":"event-2","executionId":"execution-123",'
53
+ b'"workflowId":"workflow-123","type":"node.completed",'
54
+ b'"timestamp":"2026-09-11T10:00:01Z",'
55
+ b'"data":{"nodeId":"node-1","status":"success",'
56
+ b'"output":{"value":42}}}\n\n'
57
+ ),
58
+ )
59
+ )
60
+
61
+ client = Vangrex(api_key="vx_test")
62
+
63
+ events = list(client.executions.events("execution-123"))
64
+
65
+ assert len(events) == 2
66
+
67
+ assert events[0].type == "execution.started"
68
+
69
+ assert events[1].type == "node.completed"
70
+ assert events[1].data.node_id == "node-1"
71
+ assert events[1].data.output == {"value": 42}
72
+
73
+ client.close()
@@ -0,0 +1,47 @@
1
+ import httpx
2
+ import respx
3
+
4
+ from vangrex import Vangrex
5
+
6
+
7
+ @respx.mock
8
+ def test_run_workflow():
9
+ route = respx.post(
10
+ "https://api.vangrex.com/api/v1/workflows/workflow-123/executions"
11
+ ).mock(
12
+ return_value=httpx.Response(
13
+ 200,
14
+ json={
15
+ "executionId": "execution-123",
16
+ "status": "pending",
17
+ },
18
+ )
19
+ )
20
+
21
+ client = Vangrex(api_key="vx_test")
22
+
23
+ result = client.workflows.run(
24
+ "workflow-123",
25
+ {"message": "hello"},
26
+ )
27
+
28
+ assert result.execution_id == "execution-123"
29
+ assert result.status == "pending"
30
+
31
+ assert route.called
32
+ assert route.calls[0].request.headers["Authorization"] == "Bearer vx_test"
33
+
34
+ client.close()
35
+
36
+
37
+ def test_invalid_workflow_id():
38
+ client = Vangrex(api_key="vx_test")
39
+
40
+ try:
41
+ client.workflows.run("")
42
+ except ValueError as exc:
43
+ assert str(exc) == "workflow_id must be a non-empty string"
44
+ else:
45
+ raise AssertionError("Expected ValueError")
46
+
47
+ client.close()
@@ -0,0 +1,105 @@
1
+ from .client import (
2
+ AsyncVangrexClient,
3
+ VangrexClient,
4
+ )
5
+ from .errors import VangrexError
6
+ from .executions import (
7
+ AsyncExecutionsResource,
8
+ ExecutionsResource,
9
+ )
10
+ from .types import (
11
+ Execution,
12
+ ExecutionEvent,
13
+ ExecutionEventData,
14
+ ExecutionEventType,
15
+ ExecutionStatus,
16
+ RunWorkflowResponse,
17
+ )
18
+ from .workflows import (
19
+ AsyncWorkflowsResource,
20
+ WorkflowsResource,
21
+ )
22
+
23
+
24
+ class Vangrex:
25
+ """
26
+ Official Vangrex Python SDK.
27
+ """
28
+
29
+ def __init__(
30
+ self,
31
+ api_key: str,
32
+ *,
33
+ base_url: str = "https://api.vangrex.com",
34
+ timeout: float = 30.0,
35
+ ) -> None:
36
+ self._client = VangrexClient(
37
+ api_key,
38
+ base_url=base_url,
39
+ timeout=timeout,
40
+ )
41
+
42
+ self.workflows = WorkflowsResource(self._client)
43
+ self.executions = ExecutionsResource(self._client)
44
+
45
+ def close(self) -> None:
46
+ self._client.close()
47
+
48
+ def __enter__(self) -> "Vangrex":
49
+ return self
50
+
51
+ def __exit__(self, *args: object) -> None:
52
+ self.close()
53
+
54
+
55
+ class AsyncVangrex:
56
+ """
57
+ Asynchronous Vangrex Python SDK.
58
+ """
59
+
60
+ def __init__(
61
+ self,
62
+ api_key: str,
63
+ *,
64
+ base_url: str = "https://api.vangrex.com",
65
+ timeout: float = 30.0,
66
+ ) -> None:
67
+ self._client = AsyncVangrexClient(
68
+ api_key,
69
+ base_url=base_url,
70
+ timeout=timeout,
71
+ )
72
+
73
+ self.workflows = AsyncWorkflowsResource(self._client)
74
+ self.executions = AsyncExecutionsResource(self._client)
75
+
76
+ async def close(self) -> None:
77
+ await self._client.close()
78
+
79
+ async def __aenter__(self) -> "AsyncVangrex":
80
+ return self
81
+
82
+ async def __aexit__(self, *args: object) -> None:
83
+ await self.close()
84
+
85
+
86
+ __all__ = [
87
+ "Vangrex",
88
+ "AsyncVangrex",
89
+ "VangrexClient",
90
+ "AsyncVangrexClient",
91
+ "VangrexError",
92
+ "WorkflowsResource",
93
+ "AsyncWorkflowsResource",
94
+ "ExecutionsResource",
95
+ "AsyncExecutionsResource",
96
+ "RunWorkflowResponse",
97
+ "Execution",
98
+ "ExecutionEvent",
99
+ "ExecutionEventData",
100
+ "ExecutionEventType",
101
+ "ExecutionStatus",
102
+ ]
103
+
104
+
105
+ VERSION = "0.1.0"
@@ -0,0 +1,278 @@
1
+ from __future__ import annotations
2
+
3
+ from collections.abc import AsyncIterator, Iterator
4
+ from typing import Any, TypeVar
5
+
6
+ import httpx
7
+
8
+ from .errors import VangrexError
9
+
10
+ T = TypeVar("T")
11
+
12
+
13
+ DEFAULT_BASE_URL = "https://api.vangrex.com"
14
+
15
+
16
+ class VangrexClient:
17
+ """
18
+ Low-level synchronous HTTP client for the Vangrex API.
19
+ """
20
+
21
+ def __init__(
22
+ self,
23
+ api_key: str,
24
+ *,
25
+ base_url: str = DEFAULT_BASE_URL,
26
+ timeout: float = 30.0,
27
+ ) -> None:
28
+ if not isinstance(api_key, str) or not api_key.strip():
29
+ raise ValueError("api_key must be a non-empty string")
30
+
31
+ self.api_key = api_key
32
+ self.base_url = base_url.rstrip("/")
33
+
34
+ self._http = httpx.Client(
35
+ base_url=self.base_url,
36
+ timeout=timeout,
37
+ headers={
38
+ "Authorization": f"Bearer {self.api_key}",
39
+ "Content-Type": "application/json",
40
+ "Accept": "application/json",
41
+ },
42
+ )
43
+
44
+ def request(
45
+ self,
46
+ method: str,
47
+ path: str,
48
+ *,
49
+ json: Any = None,
50
+ headers: dict[str, str] | None = None,
51
+ ) -> Any:
52
+ response = self._http.request(
53
+ method,
54
+ path,
55
+ json=json,
56
+ headers=headers,
57
+ )
58
+
59
+ return self._handle_response(response)
60
+
61
+ def get(
62
+ self,
63
+ path: str,
64
+ *,
65
+ headers: dict[str, str] | None = None,
66
+ ) -> Any:
67
+ return self.request("GET", path, headers=headers)
68
+
69
+ def post(
70
+ self,
71
+ path: str,
72
+ *,
73
+ json: Any = None,
74
+ headers: dict[str, str] | None = None,
75
+ ) -> Any:
76
+ return self.request("POST", path, json=json, headers=headers)
77
+
78
+ def stream(
79
+ self,
80
+ path: str,
81
+ *,
82
+ headers: dict[str, str] | None = None,
83
+ ) -> Iterator[str]:
84
+ stream_headers = {
85
+ "Accept": "text/event-stream",
86
+ **(headers or {}),
87
+ }
88
+
89
+ with self._http.stream(
90
+ "GET",
91
+ path,
92
+ headers=stream_headers,
93
+ ) as response:
94
+ self._raise_for_status(response)
95
+
96
+ yield from response.iter_lines()
97
+
98
+ @staticmethod
99
+ def _raise_for_status(response: httpx.Response) -> None:
100
+ if response.is_success:
101
+ return
102
+
103
+ body: Any = None
104
+
105
+ try:
106
+ body = response.json()
107
+ except ValueError:
108
+ body = response.text
109
+
110
+ message = (
111
+ body.get("error")
112
+ if isinstance(body, dict) and isinstance(body.get("error"), str)
113
+ else f"Request failed with status {response.status_code}"
114
+ )
115
+
116
+ raise VangrexError(
117
+ message,
118
+ status=response.status_code,
119
+ body=body,
120
+ )
121
+
122
+ @classmethod
123
+ def _handle_response(cls, response: httpx.Response) -> Any:
124
+ cls._raise_for_status(response)
125
+
126
+ if not response.content:
127
+ return None
128
+
129
+ try:
130
+ return response.json()
131
+ except ValueError as exc:
132
+ raise VangrexError(
133
+ "Vangrex API returned an invalid JSON response",
134
+ status=response.status_code,
135
+ body=response.text,
136
+ ) from exc
137
+
138
+ def close(self) -> None:
139
+ self._http.close()
140
+
141
+ def __enter__(self) -> VangrexClient:
142
+ return self
143
+
144
+ def __exit__(self, *args: Any) -> None:
145
+ self.close()
146
+
147
+
148
+ class AsyncVangrexClient:
149
+ """
150
+ Low-level asynchronous HTTP client for the Vangrex API.
151
+ """
152
+
153
+ def __init__(
154
+ self,
155
+ api_key: str,
156
+ *,
157
+ base_url: str = DEFAULT_BASE_URL,
158
+ timeout: float = 30.0,
159
+ ) -> None:
160
+ if not isinstance(api_key, str) or not api_key.strip():
161
+ raise ValueError("api_key must be a non-empty string")
162
+
163
+ self.api_key = api_key
164
+ self.base_url = base_url.rstrip("/")
165
+
166
+ self._http = httpx.AsyncClient(
167
+ base_url=self.base_url,
168
+ timeout=timeout,
169
+ headers={
170
+ "Authorization": f"Bearer {self.api_key}",
171
+ "Content-Type": "application/json",
172
+ "Accept": "application/json",
173
+ },
174
+ )
175
+
176
+ async def request(
177
+ self,
178
+ method: str,
179
+ path: str,
180
+ *,
181
+ json: Any = None,
182
+ headers: dict[str, str] | None = None,
183
+ ) -> Any:
184
+ response = await self._http.request(
185
+ method,
186
+ path,
187
+ json=json,
188
+ headers=headers,
189
+ )
190
+
191
+ return await self._handle_response(response)
192
+
193
+ async def get(
194
+ self,
195
+ path: str,
196
+ *,
197
+ headers: dict[str, str] | None = None,
198
+ ) -> Any:
199
+ return await self.request("GET", path, headers=headers)
200
+
201
+ async def post(
202
+ self,
203
+ path: str,
204
+ *,
205
+ json: Any = None,
206
+ headers: dict[str, str] | None = None,
207
+ ) -> Any:
208
+ return await self.request("POST", path, json=json, headers=headers)
209
+
210
+ async def stream(
211
+ self,
212
+ path: str,
213
+ *,
214
+ headers: dict[str, str] | None = None,
215
+ ) -> AsyncIterator[str]:
216
+ stream_headers = {
217
+ "Accept": "text/event-stream",
218
+ **(headers or {}),
219
+ }
220
+
221
+ async with self._http.stream(
222
+ "GET",
223
+ path,
224
+ headers=stream_headers,
225
+ ) as response:
226
+ self._raise_for_status(response)
227
+
228
+ async for line in response.aiter_lines():
229
+ yield line
230
+
231
+ @staticmethod
232
+ def _raise_for_status(response: httpx.Response) -> None:
233
+ if response.is_success:
234
+ return
235
+
236
+ body: Any = None
237
+
238
+ try:
239
+ body = response.json()
240
+ except ValueError:
241
+ body = response.text
242
+
243
+ message = (
244
+ body.get("error")
245
+ if isinstance(body, dict) and isinstance(body.get("error"), str)
246
+ else f"Request failed with status {response.status_code}"
247
+ )
248
+
249
+ raise VangrexError(
250
+ message,
251
+ status=response.status_code,
252
+ body=body,
253
+ )
254
+
255
+ @classmethod
256
+ async def _handle_response(cls, response: httpx.Response) -> Any:
257
+ cls._raise_for_status(response)
258
+
259
+ if not response.content:
260
+ return None
261
+
262
+ try:
263
+ return response.json()
264
+ except ValueError as exc:
265
+ raise VangrexError(
266
+ "Vangrex API returned an invalid JSON response",
267
+ status=response.status_code,
268
+ body=response.text,
269
+ ) from exc
270
+
271
+ async def close(self) -> None:
272
+ await self._http.aclose()
273
+
274
+ async def __aenter__(self) -> AsyncVangrexClient:
275
+ return self
276
+
277
+ async def __aexit__(self, *args: Any) -> None:
278
+ await self.close()
@@ -0,0 +1,26 @@
1
+ from typing import Any
2
+
3
+
4
+ class VangrexError(Exception):
5
+ """
6
+ Error raised when a Vangrex API request fails.
7
+ """
8
+
9
+ def __init__(
10
+ self,
11
+ message: str,
12
+ *,
13
+ status: int | None = None,
14
+ body: Any = None,
15
+ ) -> None:
16
+ super().__init__(message)
17
+
18
+ self.message = message
19
+ self.status = status
20
+ self.body = body
21
+
22
+ def __str__(self) -> str:
23
+ if self.status is not None:
24
+ return f"{self.message} (HTTP {self.status})"
25
+
26
+ return self.message
@@ -0,0 +1,155 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ from collections.abc import AsyncIterator, Iterator
5
+ from typing import Any
6
+
7
+ from .client import AsyncVangrexClient, VangrexClient
8
+ from .types import Execution, ExecutionEvent, ExecutionEventData
9
+
10
+
11
+ class ExecutionsResource:
12
+ def __init__(self, client: VangrexClient) -> None:
13
+ self._client = client
14
+
15
+ def get(self, execution_id: str) -> Execution:
16
+ self._validate_execution_id(execution_id)
17
+
18
+ response = self._client.get(
19
+ f"/api/v1/executions/{execution_id}"
20
+ )
21
+
22
+ return self._parse_execution(response)
23
+
24
+ def events(self, execution_id: str) -> Iterator[ExecutionEvent]:
25
+ self._validate_execution_id(execution_id)
26
+
27
+ data_lines: list[str] = []
28
+
29
+ for line in self._client.stream(
30
+ f"/api/v1/executions/{execution_id}/events"
31
+ ):
32
+ # SSE comments / keep-alives
33
+ if line.startswith(":"):
34
+ continue
35
+
36
+ if line.startswith("data:"):
37
+ data_lines.append(line[5:].lstrip())
38
+ continue
39
+
40
+ # An empty line terminates an SSE event.
41
+ if not line.strip():
42
+ if data_lines:
43
+ event = self._parse_event("\n".join(data_lines))
44
+
45
+ if event is not None:
46
+ yield event
47
+
48
+ data_lines.clear()
49
+
50
+ # Handle a final event without a trailing blank line.
51
+ if data_lines:
52
+ event = self._parse_event("\n".join(data_lines))
53
+
54
+ if event is not None:
55
+ yield event
56
+
57
+ @staticmethod
58
+ def _validate_execution_id(execution_id: str) -> None:
59
+ if not isinstance(execution_id, str) or not execution_id.strip():
60
+ raise ValueError("execution_id must be a non-empty string")
61
+
62
+ @staticmethod
63
+ def _parse_execution(data: dict[str, Any]) -> Execution:
64
+ return Execution(
65
+ id=data["id"],
66
+ workflow_id=data["workflowId"],
67
+ status=data["status"],
68
+ input=data.get("input"),
69
+ output=data.get("output"),
70
+ error=data.get("error"),
71
+ started_at=data.get("startedAt"),
72
+ completed_at=data.get("completedAt"),
73
+ created_at=data["createdAt"],
74
+ )
75
+
76
+ @staticmethod
77
+ def _parse_event(raw: str) -> ExecutionEvent | None:
78
+ try:
79
+ data = json.loads(raw)
80
+ except json.JSONDecodeError:
81
+ # Match the TypeScript SDK behaviour:
82
+ # malformed events should not break the stream.
83
+ return None
84
+
85
+ event_data = data.get("data") or {}
86
+
87
+ return ExecutionEvent(
88
+ id=data["id"],
89
+ execution_id=data["executionId"],
90
+ workflow_id=data["workflowId"],
91
+ type=data["type"],
92
+ timestamp=data["timestamp"],
93
+ data=ExecutionEventData(
94
+ node_id=event_data.get("nodeId"),
95
+ status=event_data.get("status"),
96
+ output=event_data.get("output"),
97
+ error=event_data.get("error"),
98
+ ),
99
+ )
100
+
101
+
102
+ class AsyncExecutionsResource:
103
+ def __init__(self, client: AsyncVangrexClient) -> None:
104
+ self._client = client
105
+
106
+ async def get(self, execution_id: str) -> Execution:
107
+ self._validate_execution_id(execution_id)
108
+
109
+ response = await self._client.get(
110
+ f"/api/v1/executions/{execution_id}"
111
+ )
112
+
113
+ return ExecutionsResource._parse_execution(response)
114
+
115
+ async def events(
116
+ self,
117
+ execution_id: str,
118
+ ) -> AsyncIterator[ExecutionEvent]:
119
+ self._validate_execution_id(execution_id)
120
+
121
+ data_lines: list[str] = []
122
+
123
+ async for line in self._client.stream(
124
+ f"/api/v1/executions/{execution_id}/events"
125
+ ):
126
+ if line.startswith(":"):
127
+ continue
128
+
129
+ if line.startswith("data:"):
130
+ data_lines.append(line[5:].lstrip())
131
+ continue
132
+
133
+ if not line.strip():
134
+ if data_lines:
135
+ event = ExecutionsResource._parse_event(
136
+ "\n".join(data_lines)
137
+ )
138
+
139
+ if event is not None:
140
+ yield event
141
+
142
+ data_lines.clear()
143
+
144
+ if data_lines:
145
+ event = ExecutionsResource._parse_event(
146
+ "\n".join(data_lines)
147
+ )
148
+
149
+ if event is not None:
150
+ yield event
151
+
152
+ @staticmethod
153
+ def _validate_execution_id(execution_id: str) -> None:
154
+ if not isinstance(execution_id, str) or not execution_id.strip():
155
+ raise ValueError("execution_id must be a non-empty string")
@@ -0,0 +1,57 @@
1
+ from dataclasses import dataclass
2
+ from typing import Any, Literal
3
+
4
+ ExecutionStatus = Literal[
5
+ "pending",
6
+ "running",
7
+ "success",
8
+ "error",
9
+ "cancelled",
10
+ ]
11
+
12
+ ExecutionEventType = Literal[
13
+ "execution.started",
14
+ "node.started",
15
+ "node.output",
16
+ "node.completed",
17
+ "node.failed",
18
+ "execution.completed",
19
+ "execution.failed",
20
+ ]
21
+
22
+
23
+ @dataclass(frozen=True)
24
+ class RunWorkflowResponse:
25
+ execution_id: str
26
+ status: str
27
+
28
+
29
+ @dataclass(frozen=True)
30
+ class Execution:
31
+ id: str
32
+ workflow_id: str
33
+ status: ExecutionStatus
34
+ input: Any
35
+ output: Any
36
+ error: Any
37
+ started_at: str | None
38
+ completed_at: str | None
39
+ created_at: str
40
+
41
+
42
+ @dataclass(frozen=True)
43
+ class ExecutionEventData:
44
+ node_id: str | None = None
45
+ status: str | None = None
46
+ output: Any = None
47
+ error: Any = None
48
+
49
+
50
+ @dataclass(frozen=True)
51
+ class ExecutionEvent:
52
+ id: str
53
+ execution_id: str
54
+ workflow_id: str
55
+ type: ExecutionEventType
56
+ timestamp: str
57
+ data: ExecutionEventData
@@ -0,0 +1,60 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Any
4
+
5
+ from .client import AsyncVangrexClient, VangrexClient
6
+ from .types import RunWorkflowResponse
7
+
8
+
9
+ class WorkflowsResource:
10
+ def __init__(self, client: VangrexClient) -> None:
11
+ self._client = client
12
+
13
+ def run(
14
+ self,
15
+ workflow_id: str,
16
+ input: Any = None,
17
+ ) -> RunWorkflowResponse:
18
+ self._validate_workflow_id(workflow_id)
19
+
20
+ response = self._client.post(
21
+ f"/api/v1/workflows/{workflow_id}/executions",
22
+ json={
23
+ "input": {} if input is None else input,
24
+ },
25
+ )
26
+
27
+ return RunWorkflowResponse(
28
+ execution_id=response["executionId"],
29
+ status=response["status"],
30
+ )
31
+
32
+ @staticmethod
33
+ def _validate_workflow_id(workflow_id: str) -> None:
34
+ if not isinstance(workflow_id, str) or not workflow_id.strip():
35
+ raise ValueError("workflow_id must be a non-empty string")
36
+
37
+
38
+ class AsyncWorkflowsResource:
39
+ def __init__(self, client: AsyncVangrexClient) -> None:
40
+ self._client = client
41
+
42
+ async def run(
43
+ self,
44
+ workflow_id: str,
45
+ input: Any = None,
46
+ ) -> RunWorkflowResponse:
47
+ if not isinstance(workflow_id, str) or not workflow_id.strip():
48
+ raise ValueError("workflow_id must be a non-empty string")
49
+
50
+ response = await self._client.post(
51
+ f"/api/v1/workflows/{workflow_id}/executions",
52
+ json={
53
+ "input": {} if input is None else input,
54
+ },
55
+ )
56
+
57
+ return RunWorkflowResponse(
58
+ execution_id=response["executionId"],
59
+ status=response["status"],
60
+ )