render-lab-tasks-exa 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.
Files changed (25) hide show
  1. render_lab_tasks_exa-0.1.0/.gitignore +11 -0
  2. render_lab_tasks_exa-0.1.0/LICENSE +21 -0
  3. render_lab_tasks_exa-0.1.0/PKG-INFO +93 -0
  4. render_lab_tasks_exa-0.1.0/README.md +79 -0
  5. render_lab_tasks_exa-0.1.0/pyproject.toml +23 -0
  6. render_lab_tasks_exa-0.1.0/src/render_lab_tasks_exa/__init__.py +1 -0
  7. render_lab_tasks_exa-0.1.0/src/render_lab_tasks_exa/_app.py +3 -0
  8. render_lab_tasks_exa-0.1.0/src/render_lab_tasks_exa/answer.py +18 -0
  9. render_lab_tasks_exa-0.1.0/src/render_lab_tasks_exa/await_agent.py +18 -0
  10. render_lab_tasks_exa-0.1.0/src/render_lab_tasks_exa/await_webset.py +18 -0
  11. render_lab_tasks_exa-0.1.0/src/render_lab_tasks_exa/cancel_agent.py +18 -0
  12. render_lab_tasks_exa-0.1.0/src/render_lab_tasks_exa/cancel_webset.py +18 -0
  13. render_lab_tasks_exa-0.1.0/src/render_lab_tasks_exa/client.py +406 -0
  14. render_lab_tasks_exa-0.1.0/src/render_lab_tasks_exa/create_webset.py +18 -0
  15. render_lab_tasks_exa-0.1.0/src/render_lab_tasks_exa/create_webset_monitor.py +20 -0
  16. render_lab_tasks_exa-0.1.0/src/render_lab_tasks_exa/delete_webset.py +18 -0
  17. render_lab_tasks_exa-0.1.0/src/render_lab_tasks_exa/get_contents.py +18 -0
  18. render_lab_tasks_exa-0.1.0/src/render_lab_tasks_exa/list_webset_items.py +18 -0
  19. render_lab_tasks_exa-0.1.0/src/render_lab_tasks_exa/py.typed +0 -0
  20. render_lab_tasks_exa-0.1.0/src/render_lab_tasks_exa/retry.py +7 -0
  21. render_lab_tasks_exa-0.1.0/src/render_lab_tasks_exa/search.py +18 -0
  22. render_lab_tasks_exa-0.1.0/src/render_lab_tasks_exa/start_agent.py +18 -0
  23. render_lab_tasks_exa-0.1.0/src/render_lab_tasks_exa/tasks.py +41 -0
  24. render_lab_tasks_exa-0.1.0/src/render_lab_tasks_exa/types.py +275 -0
  25. render_lab_tasks_exa-0.1.0/src/render_lab_tasks_exa/webhooks.py +62 -0
@@ -0,0 +1,11 @@
1
+ .venv/
2
+ __pycache__/
3
+ *.py[cod]
4
+ .pytest_cache/
5
+ .mypy_cache/
6
+ .ruff_cache/
7
+ dist/
8
+ *.egg-info/
9
+ .env
10
+ .env.*
11
+ !.env.example
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Render Lab
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 to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,93 @@
1
+ Metadata-Version: 2.5
2
+ Name: render-lab-tasks-exa
3
+ Version: 0.1.0
4
+ Summary: exa tasks for Render Workflows
5
+ Project-URL: Repository, https://github.com/render-lab/render-tasks-python
6
+ License-Expression: MIT
7
+ License-File: LICENSE
8
+ Requires-Python: >=3.12
9
+ Requires-Dist: httpx<0.29,>=0.28
10
+ Requires-Dist: render-lab-tasks-core<0.2,>=0.1.1
11
+ Requires-Dist: render-lab-triggers<0.2,>=0.1.0
12
+ Requires-Dist: render==1.0.1
13
+ Description-Content-Type: text/markdown
14
+
15
+ # render-lab-tasks-exa
16
+
17
+ Unreleased Python port: **12 registered tasks** from
18
+ [render-lab/render-tasks](https://github.com/render-lab/render-tasks/tree/45f9c2d44bd28e01ae9813e0d2ff56ee6c533816/packages/tasks-exa).
19
+ Python 3.12+, Render SDK 1.0.1. Requires core 0.1.1 or later.
20
+
21
+ From the repository root:
22
+
23
+ ```sh
24
+ uv sync --all-packages --locked
25
+ ```
26
+
27
+ Import `render_lab_tasks_exa.tasks` to register tasks. The package root is inert.
28
+ Compose the exported `app` with `Workflows.from_workflows`; call tasks through
29
+ `ctx.run`. Every operation also exports `*_impl(ctx, input, *, deps=None)` for
30
+ injection. `Client(http, env)` accepts a caller-owned HTTPX client, and
31
+ `Deps(exa=client)` injects it. Default dependencies open and close the HTTP
32
+ client per invocation; credentials are read lazily at use. No HTTP retries or
33
+ background vendor polling occur; `retry.py` owns the durable retry policies.
34
+
35
+ ## Task surface
36
+
37
+ | Registered task | Python export |
38
+ | --- | --- |
39
+ | `exa.answer` | `answer` |
40
+ | `exa.awaitAgent` | `await_agent` |
41
+ | `exa.awaitWebset` | `await_webset` |
42
+ | `exa.cancelAgent` | `cancel_agent` |
43
+ | `exa.cancelWebset` | `cancel_webset` |
44
+ | `exa.createWebset` | `create_webset` |
45
+ | `exa.createWebsetMonitor` | `create_webset_monitor` |
46
+ | `exa.deleteWebset` | `delete_webset` |
47
+ | `exa.getContents` | `get_contents` |
48
+ | `exa.listWebsetItems` | `list_webset_items` |
49
+ | `exa.search` | `search` |
50
+ | `exa.startAgent` | `start_agent` |
51
+
52
+ Typed JSON inputs and results are in `types.py`. Task names and JSON field names
53
+ match the pinned source; Python function names use snake_case.
54
+
55
+ ## Environment
56
+
57
+ | Variable | Requirement |
58
+ | --- | --- |
59
+ | `EXA_API_KEY` | Required at first API call. |
60
+
61
+ ## Behavior and limits
62
+
63
+ Uses direct HTTP matching exa-js 2.16.0 requests rather than installing a Python vendor SDK. Search defaults to text with maxCharacters 10000 when contents is omitted; answer uses model exa and stream false. Search/contents/answers enforce content-character budgets; agent results and Webset pages enforce output-byte budgets. Websets use stable externalId values and recover duplicate-create 409s by reading that ID. Missing/already-terminal cancellations normalize 404/409. Unknown agent states become queued and unknown Webset states become pending, matching the source. Answer text itself is not covered by the citation-content budget; this inherited limitation needs a separate bound before production use.
64
+
65
+ ## Verification
66
+
67
+ All registered tasks have hermetic contract fixtures executed independently against
68
+ the pinned TS implementation. SDK-backed tasks also have explicit HTTP request
69
+ fixtures. See `tests/test_batch3_contracts.py` and `tests/test_batch3_edges.py`.
70
+ These are not live vendor results.
71
+
72
+ Vendor webhooks subpaths and other registration-free TS exports are outside this
73
+ batch unless explicitly listed above. Full registered-task coverage does not
74
+ imply all supporting exports are ported.
75
+
76
+ Pending scopes, test resources, replay, and hosted checks are in the
77
+ [live-testing backlog](https://github.com/render-lab/render-tasks-python/issues/1)
78
+ and [verification tracker](../../docs/verification-tracker.md).
79
+
80
+ ## Webhook adapter
81
+
82
+ `render_lab_tasks_exa.webhooks.exa_websets_adapter(on_event, ...)` returns a
83
+ registration-free adapter for `render_lab_triggers`. The callback receives the
84
+ verified event and returns `{"task": "namespace.task", "args": [event]}` or `None`.
85
+ The signing credential `EXA_WEBHOOK_SECRET` is read inside verification unless
86
+ provided explicitly. Importing this module does not register tasks. Signature
87
+ checks use the raw body; live delivery remains in the testing backlog.
88
+
89
+ ## Installation
90
+
91
+ ```sh
92
+ pip install render-lab-tasks-exa==0.1.0
93
+ ```
@@ -0,0 +1,79 @@
1
+ # render-lab-tasks-exa
2
+
3
+ Unreleased Python port: **12 registered tasks** from
4
+ [render-lab/render-tasks](https://github.com/render-lab/render-tasks/tree/45f9c2d44bd28e01ae9813e0d2ff56ee6c533816/packages/tasks-exa).
5
+ Python 3.12+, Render SDK 1.0.1. Requires core 0.1.1 or later.
6
+
7
+ From the repository root:
8
+
9
+ ```sh
10
+ uv sync --all-packages --locked
11
+ ```
12
+
13
+ Import `render_lab_tasks_exa.tasks` to register tasks. The package root is inert.
14
+ Compose the exported `app` with `Workflows.from_workflows`; call tasks through
15
+ `ctx.run`. Every operation also exports `*_impl(ctx, input, *, deps=None)` for
16
+ injection. `Client(http, env)` accepts a caller-owned HTTPX client, and
17
+ `Deps(exa=client)` injects it. Default dependencies open and close the HTTP
18
+ client per invocation; credentials are read lazily at use. No HTTP retries or
19
+ background vendor polling occur; `retry.py` owns the durable retry policies.
20
+
21
+ ## Task surface
22
+
23
+ | Registered task | Python export |
24
+ | --- | --- |
25
+ | `exa.answer` | `answer` |
26
+ | `exa.awaitAgent` | `await_agent` |
27
+ | `exa.awaitWebset` | `await_webset` |
28
+ | `exa.cancelAgent` | `cancel_agent` |
29
+ | `exa.cancelWebset` | `cancel_webset` |
30
+ | `exa.createWebset` | `create_webset` |
31
+ | `exa.createWebsetMonitor` | `create_webset_monitor` |
32
+ | `exa.deleteWebset` | `delete_webset` |
33
+ | `exa.getContents` | `get_contents` |
34
+ | `exa.listWebsetItems` | `list_webset_items` |
35
+ | `exa.search` | `search` |
36
+ | `exa.startAgent` | `start_agent` |
37
+
38
+ Typed JSON inputs and results are in `types.py`. Task names and JSON field names
39
+ match the pinned source; Python function names use snake_case.
40
+
41
+ ## Environment
42
+
43
+ | Variable | Requirement |
44
+ | --- | --- |
45
+ | `EXA_API_KEY` | Required at first API call. |
46
+
47
+ ## Behavior and limits
48
+
49
+ Uses direct HTTP matching exa-js 2.16.0 requests rather than installing a Python vendor SDK. Search defaults to text with maxCharacters 10000 when contents is omitted; answer uses model exa and stream false. Search/contents/answers enforce content-character budgets; agent results and Webset pages enforce output-byte budgets. Websets use stable externalId values and recover duplicate-create 409s by reading that ID. Missing/already-terminal cancellations normalize 404/409. Unknown agent states become queued and unknown Webset states become pending, matching the source. Answer text itself is not covered by the citation-content budget; this inherited limitation needs a separate bound before production use.
50
+
51
+ ## Verification
52
+
53
+ All registered tasks have hermetic contract fixtures executed independently against
54
+ the pinned TS implementation. SDK-backed tasks also have explicit HTTP request
55
+ fixtures. See `tests/test_batch3_contracts.py` and `tests/test_batch3_edges.py`.
56
+ These are not live vendor results.
57
+
58
+ Vendor webhooks subpaths and other registration-free TS exports are outside this
59
+ batch unless explicitly listed above. Full registered-task coverage does not
60
+ imply all supporting exports are ported.
61
+
62
+ Pending scopes, test resources, replay, and hosted checks are in the
63
+ [live-testing backlog](https://github.com/render-lab/render-tasks-python/issues/1)
64
+ and [verification tracker](../../docs/verification-tracker.md).
65
+
66
+ ## Webhook adapter
67
+
68
+ `render_lab_tasks_exa.webhooks.exa_websets_adapter(on_event, ...)` returns a
69
+ registration-free adapter for `render_lab_triggers`. The callback receives the
70
+ verified event and returns `{"task": "namespace.task", "args": [event]}` or `None`.
71
+ The signing credential `EXA_WEBHOOK_SECRET` is read inside verification unless
72
+ provided explicitly. Importing this module does not register tasks. Signature
73
+ checks use the raw body; live delivery remains in the testing backlog.
74
+
75
+ ## Installation
76
+
77
+ ```sh
78
+ pip install render-lab-tasks-exa==0.1.0
79
+ ```
@@ -0,0 +1,23 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.27,<2"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "render-lab-tasks-exa"
7
+ version = "0.1.0"
8
+ description = "exa tasks for Render Workflows"
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ license-files = ["LICENSE"]
12
+ requires-python = ">=3.12"
13
+ dependencies = ["render-lab-triggers>=0.1.0,<0.2", "render==1.0.1", "httpx>=0.28,<0.29", "render-lab-tasks-core>=0.1.1,<0.2"]
14
+
15
+ [project.urls]
16
+ Repository = "https://github.com/render-lab/render-tasks-python"
17
+
18
+ [tool.uv.sources]
19
+ render-lab-triggers = { workspace = true }
20
+ render-lab-tasks-core = { workspace = true }
21
+
22
+ [tool.hatch.build.targets.wheel]
23
+ packages = ["src/render_lab_tasks_exa"]
@@ -0,0 +1 @@
1
+ """Import .tasks explicitly to register durable tasks."""
@@ -0,0 +1,3 @@
1
+ from render import Workflows
2
+
3
+ app = Workflows()
@@ -0,0 +1,18 @@
1
+ from render import TaskContext
2
+
3
+ from ._app import app
4
+ from .client import Deps, dependencies
5
+ from .retry import EXA_READ_RETRY
6
+ from .types import AnswerInput, AnswerResult
7
+
8
+
9
+ async def answer_impl(
10
+ ctx: TaskContext, input: AnswerInput, *, deps: Deps | None = None
11
+ ) -> AnswerResult:
12
+ async with dependencies(deps) as resolved:
13
+ return await resolved.exa.answer(input)
14
+
15
+
16
+ @app.task(name="exa.answer", retry=EXA_READ_RETRY)
17
+ async def answer(ctx: TaskContext, input: AnswerInput) -> AnswerResult:
18
+ return await answer_impl(ctx, input)
@@ -0,0 +1,18 @@
1
+ from render import TaskContext
2
+
3
+ from ._app import app
4
+ from .client import Deps, dependencies
5
+ from .retry import EXA_AWAIT_RETRY
6
+ from .types import AgentResult, AwaitAgentInput
7
+
8
+
9
+ async def await_agent_impl(
10
+ ctx: TaskContext, input: AwaitAgentInput, *, deps: Deps | None = None
11
+ ) -> AgentResult:
12
+ async with dependencies(deps) as resolved:
13
+ return await resolved.exa.await_agent(input)
14
+
15
+
16
+ @app.task(name="exa.awaitAgent", retry=EXA_AWAIT_RETRY)
17
+ async def await_agent(ctx: TaskContext, input: AwaitAgentInput) -> AgentResult:
18
+ return await await_agent_impl(ctx, input)
@@ -0,0 +1,18 @@
1
+ from render import TaskContext
2
+
3
+ from ._app import app
4
+ from .client import Deps, dependencies
5
+ from .retry import EXA_AWAIT_RETRY
6
+ from .types import AwaitWebsetInput, WebsetDTO
7
+
8
+
9
+ async def await_webset_impl(
10
+ ctx: TaskContext, input: AwaitWebsetInput, *, deps: Deps | None = None
11
+ ) -> WebsetDTO:
12
+ async with dependencies(deps) as resolved:
13
+ return await resolved.exa.await_webset(input)
14
+
15
+
16
+ @app.task(name="exa.awaitWebset", retry=EXA_AWAIT_RETRY)
17
+ async def await_webset(ctx: TaskContext, input: AwaitWebsetInput) -> WebsetDTO:
18
+ return await await_webset_impl(ctx, input)
@@ -0,0 +1,18 @@
1
+ from render import TaskContext
2
+
3
+ from ._app import app
4
+ from .client import Deps, dependencies
5
+ from .retry import EXA_CANCEL_RETRY
6
+ from .types import CancelAgentInput, CancelAgentResult
7
+
8
+
9
+ async def cancel_agent_impl(
10
+ ctx: TaskContext, input: CancelAgentInput, *, deps: Deps | None = None
11
+ ) -> CancelAgentResult:
12
+ async with dependencies(deps) as resolved:
13
+ return await resolved.exa.cancel_agent(input)
14
+
15
+
16
+ @app.task(name="exa.cancelAgent", retry=EXA_CANCEL_RETRY)
17
+ async def cancel_agent(ctx: TaskContext, input: CancelAgentInput) -> CancelAgentResult:
18
+ return await cancel_agent_impl(ctx, input)
@@ -0,0 +1,18 @@
1
+ from render import TaskContext
2
+
3
+ from ._app import app
4
+ from .client import Deps, dependencies
5
+ from .retry import EXA_CANCEL_RETRY
6
+ from .types import CancelWebsetInput, CancelWebsetResult
7
+
8
+
9
+ async def cancel_webset_impl(
10
+ ctx: TaskContext, input: CancelWebsetInput, *, deps: Deps | None = None
11
+ ) -> CancelWebsetResult:
12
+ async with dependencies(deps) as resolved:
13
+ return await resolved.exa.cancel_webset(input)
14
+
15
+
16
+ @app.task(name="exa.cancelWebset", retry=EXA_CANCEL_RETRY)
17
+ async def cancel_webset(ctx: TaskContext, input: CancelWebsetInput) -> CancelWebsetResult:
18
+ return await cancel_webset_impl(ctx, input)
@@ -0,0 +1,406 @@
1
+ """Injected vendor interface and one-attempt async HTTP adapter."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ from collections.abc import AsyncIterator, Mapping, Sequence
8
+ from contextlib import asynccontextmanager
9
+ from dataclasses import dataclass
10
+ from typing import Any, Protocol, cast
11
+
12
+ import httpx
13
+ from render_lab_tasks_core.http import (
14
+ ApiError,
15
+ HttpClient,
16
+ enc,
17
+ js_string,
18
+ nullish,
19
+ pick,
20
+ query,
21
+ required,
22
+ )
23
+
24
+ from . import types as t
25
+
26
+
27
+ def obj(value: Any) -> dict[str, Any]:
28
+ return value if isinstance(value, dict) else {}
29
+
30
+
31
+ def array(value: Any) -> list[Any]:
32
+ return value if isinstance(value, list) else []
33
+
34
+
35
+ def without(value: Mapping[str, Any], *keys: str) -> dict[str, Any]:
36
+ return {k: v for k, v in value.items() if k not in keys}
37
+
38
+
39
+ def cost(row: Mapping[str, Any]) -> Any:
40
+ value = obj(row.get("costDollars")).get("total")
41
+ return value if isinstance(value, (int, float)) and not isinstance(value, bool) else None
42
+
43
+
44
+ def document(row: Mapping[str, Any]) -> t.ExaDocument:
45
+ return cast(
46
+ t.ExaDocument,
47
+ {
48
+ "id": row["id"],
49
+ "url": row["url"],
50
+ "title": nullish(row.get("title"), ""),
51
+ "publishedDate": row.get("publishedDate"),
52
+ "author": row.get("author"),
53
+ **pick(row, "text", "highlights", "summary"),
54
+ },
55
+ )
56
+
57
+
58
+ def content_budget(docs: Sequence[t.ExaDocument], maximum: float, op: str, hint: str) -> None:
59
+ strings = [
60
+ v for d in docs for v in [d.get("text", ""), d.get("summary", ""), *d.get("highlights", [])]
61
+ ]
62
+ n = sum(len(v.encode("utf-16-le")) // 2 for v in strings)
63
+ if n > maximum:
64
+ raise ValueError(
65
+ f"{op} returned {n} content characters, over the "
66
+ f"maxContentChars limit of {js_string(maximum)}. {hint}"
67
+ )
68
+
69
+
70
+ def output_budget(value: Any, maximum: float, op: str, hint: str) -> None:
71
+ n = len(json.dumps(value, ensure_ascii=False, separators=(",", ":"), allow_nan=False).encode())
72
+ if n > maximum:
73
+ raise ValueError(
74
+ f"{op} returned {n} bytes, over the maxOutputBytes limit "
75
+ f"of {js_string(maximum)}. {hint}"
76
+ )
77
+
78
+
79
+ def agent_status(value: Any) -> t.AgentStatus:
80
+ return (
81
+ cast(t.AgentStatus, value)
82
+ if value in ("queued", "running", "completed", "failed", "cancelled")
83
+ else "queued"
84
+ )
85
+
86
+
87
+ def webset(value: Any) -> t.WebsetDTO:
88
+ row = obj(value)
89
+ status = row.get("status")
90
+ return {
91
+ "id": row["id"],
92
+ "externalId": nullish(row.get("externalId"), ""),
93
+ "status": status if status in ("idle", "pending", "running", "paused") else "pending",
94
+ "title": row.get("title"),
95
+ "dashboardUrl": row.get("dashboardUrl"),
96
+ "createdAt": row["createdAt"],
97
+ "updatedAt": row["updatedAt"],
98
+ }
99
+
100
+
101
+ def item(row: Mapping[str, Any]) -> t.WebsetItem:
102
+ props = obj(row.get("properties"))
103
+ values = row.get("enrichments")
104
+ enriched = (
105
+ {
106
+ obj(v)["id"] if isinstance(obj(v).get("id"), str) else str(i): v
107
+ for i, v in enumerate(values)
108
+ }
109
+ if isinstance(values, list)
110
+ else obj(values)
111
+ )
112
+ title = next(
113
+ (
114
+ v
115
+ for v in (
116
+ obj(props.get("company")).get("name"),
117
+ obj(props.get("article")).get("title"),
118
+ obj(props.get("custom")).get("title"),
119
+ props.get("title"),
120
+ )
121
+ if v is not None
122
+ ),
123
+ "",
124
+ )
125
+ return {
126
+ "id": row["id"],
127
+ "websetId": row["websetId"],
128
+ "url": props["url"] if isinstance(props.get("url"), str) else "",
129
+ "title": title,
130
+ "entity": props,
131
+ "enrichments": enriched,
132
+ "createdAt": row["createdAt"],
133
+ "updatedAt": row["updatedAt"],
134
+ }
135
+
136
+
137
+ class Port(Protocol):
138
+ async def answer(self, input: t.AnswerInput) -> t.AnswerResult: ...
139
+ async def await_agent(self, input: t.AwaitAgentInput) -> t.AgentResult: ...
140
+ async def await_webset(self, input: t.AwaitWebsetInput) -> t.WebsetDTO: ...
141
+ async def cancel_agent(self, input: t.CancelAgentInput) -> t.CancelAgentResult: ...
142
+ async def cancel_webset(self, input: t.CancelWebsetInput) -> t.CancelWebsetResult: ...
143
+ async def create_webset(self, input: t.CreateWebsetInput) -> t.WebsetDTO: ...
144
+ async def create_webset_monitor(
145
+ self, input: t.CreateWebsetMonitorInput
146
+ ) -> t.WebsetMonitorDTO: ...
147
+ async def delete_webset(self, input: t.DeleteWebsetInput) -> t.DeleteWebsetResult: ...
148
+ async def get_contents(self, input: t.GetContentsInput) -> t.ContentsResult: ...
149
+ async def list_webset_items(self, input: t.ListWebsetItemsInput) -> t.WebsetItemsPage: ...
150
+ async def search(self, input: t.SearchInput) -> t.SearchResult: ...
151
+ async def start_agent(self, input: t.StartAgentInput) -> t.AgentRunRef: ...
152
+
153
+
154
+ @dataclass(frozen=True)
155
+ class Deps:
156
+ exa: Port
157
+
158
+
159
+ class Client:
160
+ def __init__(self, http: httpx.AsyncClient, env: Mapping[str, str] | None = None) -> None:
161
+ self.env = os.environ if env is None else env
162
+ self.api = HttpClient(
163
+ http,
164
+ "https://api.exa.ai",
165
+ auth=lambda: {"x-api-key": required(self.env, "EXA_API_KEY")},
166
+ label="Exa API",
167
+ )
168
+
169
+ async def search(self, input: t.SearchInput) -> t.SearchResult:
170
+ body = without(input, "maxContentChars")
171
+ body.setdefault("contents", {"text": {"maxCharacters": 10000}})
172
+ row = obj(await self.api.call("/search", method="POST", body=body))
173
+ docs = [document(v) for v in array(row.get("results"))]
174
+ content_budget(
175
+ docs, input["maxContentChars"], "exa.search", "Reduce numResults or maxContentChars."
176
+ )
177
+ return {
178
+ "requestId": row["requestId"],
179
+ "searchType": nullish(row.get("resolvedSearchType"), input.get("type", "auto")),
180
+ "results": docs,
181
+ "costDollars": cost(row),
182
+ }
183
+
184
+ async def get_contents(self, input: t.GetContentsInput) -> t.ContentsResult:
185
+ if not input["urls"]:
186
+ raise ValueError("Must provide at least one URL")
187
+ row = obj(
188
+ await self.api.call("/contents", method="POST", body=without(input, "maxContentChars"))
189
+ )
190
+ docs = [document(v) for v in array(row.get("results"))]
191
+ content_budget(
192
+ docs,
193
+ input["maxContentChars"],
194
+ "exa.getContents",
195
+ "Request fewer URLs or reduce maxContentChars.",
196
+ )
197
+ statuses: list[t.ContentsResultStatusesItem] = []
198
+ for value in array(row.get("statuses")):
199
+ status: t.ContentsResultStatusesItem = {
200
+ "id": value["id"],
201
+ "status": "error" if value.get("status") == "error" else "success",
202
+ }
203
+ if value.get("error") is not None:
204
+ error = obj(value["error"])
205
+ status["error"] = {
206
+ "tag": nullish(error.get("tag"), ""),
207
+ "httpStatusCode": error.get("httpStatusCode"),
208
+ }
209
+ statuses.append(status)
210
+ return {
211
+ "requestId": row["requestId"],
212
+ "results": docs,
213
+ "statuses": statuses,
214
+ "costDollars": cost(row),
215
+ }
216
+
217
+ async def answer(self, input: t.AnswerInput) -> t.AnswerResult:
218
+ row = obj(
219
+ await self.api.call(
220
+ "/answer",
221
+ method="POST",
222
+ body={
223
+ "query": input["query"],
224
+ "text": input.get("includeCitationText", False),
225
+ "stream": False,
226
+ "model": "exa",
227
+ },
228
+ )
229
+ )
230
+ docs = [document(v) for v in array(row.get("citations"))]
231
+ content_budget(
232
+ docs,
233
+ input["maxContentChars"],
234
+ "exa.answer",
235
+ "Set includeCitationText to false or reduce maxContentChars.",
236
+ )
237
+ return {
238
+ "requestId": nullish(row.get("requestId"), ""),
239
+ "answer": row.get("answer"),
240
+ "citations": docs,
241
+ "costDollars": cost(row),
242
+ }
243
+
244
+ async def start_agent(self, input: t.StartAgentInput) -> t.AgentRunRef:
245
+ row = obj(await self.api.call("/agent/runs", method="POST", body=input))
246
+ return {"runId": row["id"], "status": agent_status(row.get("status"))}
247
+
248
+ async def await_agent(self, input: t.AwaitAgentInput) -> t.AgentResult:
249
+ row = obj(await self.api.call("/agent/runs/" + enc(input["runId"])))
250
+ status = agent_status(row.get("status"))
251
+ if status in ("queued", "running"):
252
+ raise RuntimeError(f"Exa agent {input['runId']} is still {status}.")
253
+ if status in ("failed", "cancelled"):
254
+ error = obj(row.get("error")).get("message")
255
+ raise RuntimeError(
256
+ error
257
+ if isinstance(error, str) and error
258
+ else f"Exa agent run {row['id']} ended with status {row.get('status')}."
259
+ )
260
+ output = obj(row.get("output"))
261
+ grounding: list[t.AgentGrounding] = [
262
+ {
263
+ "field": g["field"],
264
+ "citations": [
265
+ {"url": c["url"], "title": nullish(c.get("title"), "")} for c in g["citations"]
266
+ ],
267
+ "confidence": g.get("confidence")
268
+ if g.get("confidence") in ("low", "medium", "high")
269
+ else None,
270
+ }
271
+ for g in array(output.get("grounding"))
272
+ ]
273
+ result: t.AgentResult = {
274
+ "runId": row["id"],
275
+ "status": "completed",
276
+ "text": output.get("text"),
277
+ "structured": output.get("structured"),
278
+ "grounding": grounding,
279
+ "costDollars": cost(row),
280
+ }
281
+ output_budget(
282
+ result,
283
+ input["maxOutputBytes"],
284
+ "exa.awaitAgent",
285
+ "Narrow the agent output schema or raise maxOutputBytes.",
286
+ )
287
+ return result
288
+
289
+ async def _terminal(self, path: str, method: str) -> None:
290
+ try:
291
+ await self.api.call(path, method=method, response_type="text")
292
+ except ApiError as error:
293
+ if error.status not in (404, 409):
294
+ raise
295
+
296
+ async def cancel_agent(self, input: t.CancelAgentInput) -> t.CancelAgentResult:
297
+ await self._terminal("/agent/runs/" + enc(input["runId"]) + "/cancel", "POST")
298
+ return {"runId": input["runId"], "status": "cancelled"}
299
+
300
+ async def create_webset(self, input: t.CreateWebsetInput) -> t.WebsetDTO:
301
+ if not input["externalId"].strip():
302
+ raise ValueError(
303
+ "exa.createWebset requires a non-blank externalId to recover duplicate creates."
304
+ )
305
+ body = {
306
+ "externalId": input["externalId"],
307
+ "search": pick(input, "query", "count", "criteria", "entity"),
308
+ **pick(input, "enrichments", "metadata"),
309
+ }
310
+ try:
311
+ row = await self.api.call("/websets/v0/websets", method="POST", body=body)
312
+ except ApiError as error:
313
+ if error.status != 409:
314
+ raise
315
+ row = await self.api.call("/websets/v0/websets/" + enc(input["externalId"]))
316
+ return webset(row)
317
+
318
+ async def await_webset(self, input: t.AwaitWebsetInput) -> t.WebsetDTO:
319
+ result = webset(await self.api.call("/websets/v0/websets/" + enc(input["websetId"])))
320
+ if result["status"] == "idle":
321
+ return result
322
+ raise RuntimeError(f"Exa Webset {input['websetId']} is {result['status']}.")
323
+
324
+ async def cancel_webset(self, input: t.CancelWebsetInput) -> t.CancelWebsetResult:
325
+ await self._terminal("/websets/v0/websets/" + enc(input["websetId"]) + "/cancel", "POST")
326
+ return {"websetId": input["websetId"], "status": "idle"}
327
+
328
+ async def delete_webset(self, input: t.DeleteWebsetInput) -> t.DeleteWebsetResult:
329
+ await self._terminal("/websets/v0/websets/" + enc(input["websetId"]), "DELETE")
330
+ return {"websetId": input["websetId"], "deleted": True}
331
+
332
+ async def list_webset_items(self, input: t.ListWebsetItemsInput) -> t.WebsetItemsPage:
333
+ params: dict[str, Any] = {}
334
+ if input.get("cursor"):
335
+ params["cursor"] = input["cursor"]
336
+ if input["limit"]:
337
+ params["limit"] = input["limit"]
338
+ row = obj(
339
+ await self.api.call(
340
+ "/websets/v0/websets/"
341
+ + enc(input["websetId"])
342
+ + "/items"
343
+ + ("?" + query(params) if params else "")
344
+ )
345
+ )
346
+ result: t.WebsetItemsPage = {
347
+ "items": [item(v) for v in row["data"]],
348
+ "nextCursor": row.get("nextCursor"),
349
+ "hasMore": row["hasMore"],
350
+ }
351
+ output_budget(
352
+ result,
353
+ input["maxOutputBytes"],
354
+ "exa.listWebsetItems",
355
+ "Reduce limit or raise maxOutputBytes.",
356
+ )
357
+ return result
358
+
359
+ async def create_webset_monitor(self, input: t.CreateWebsetMonitorInput) -> t.WebsetMonitorDTO:
360
+ if len(input["cron"].split()) != 5:
361
+ raise ValueError("exa.createWebsetMonitor requires a five-field Unix cron expression.")
362
+ row = obj(
363
+ await self.api.call(
364
+ "/websets/v0/monitors",
365
+ method="POST",
366
+ body={
367
+ "websetId": input["websetId"],
368
+ "cadence": {
369
+ "cron": input["cron"],
370
+ "timezone": input.get("timezone", "Etc/UTC"),
371
+ },
372
+ "behavior": {
373
+ "type": "search",
374
+ "config": {
375
+ "behavior": input.get("behavior", "append"),
376
+ "count": input["count"],
377
+ "query": input["query"],
378
+ },
379
+ },
380
+ },
381
+ )
382
+ )
383
+ return {
384
+ "id": row["id"],
385
+ "websetId": row["websetId"],
386
+ "status": "disabled" if row.get("status") == "disabled" else "enabled",
387
+ "cron": row["cadence"]["cron"],
388
+ "timezone": row["cadence"]["timezone"],
389
+ "nextRunAt": row.get("nextRunAt"),
390
+ }
391
+
392
+
393
+ @asynccontextmanager
394
+ async def dependencies(deps: Deps | None) -> AsyncIterator[Deps]:
395
+ if deps is not None:
396
+ yield deps
397
+ else:
398
+ async with httpx.AsyncClient(
399
+ timeout=30, transport=httpx.AsyncHTTPTransport(retries=0)
400
+ ) as http:
401
+ yield Deps(exa=Client(http))
402
+
403
+
404
+ ExaPort = Port
405
+ ExaClient = Client
406
+ ExaDeps = Deps
@@ -0,0 +1,18 @@
1
+ from render import TaskContext
2
+
3
+ from ._app import app
4
+ from .client import Deps, dependencies
5
+ from .retry import EXA_IDEMPOTENT_WRITE_RETRY
6
+ from .types import CreateWebsetInput, WebsetDTO
7
+
8
+
9
+ async def create_webset_impl(
10
+ ctx: TaskContext, input: CreateWebsetInput, *, deps: Deps | None = None
11
+ ) -> WebsetDTO:
12
+ async with dependencies(deps) as resolved:
13
+ return await resolved.exa.create_webset(input)
14
+
15
+
16
+ @app.task(name="exa.createWebset", retry=EXA_IDEMPOTENT_WRITE_RETRY)
17
+ async def create_webset(ctx: TaskContext, input: CreateWebsetInput) -> WebsetDTO:
18
+ return await create_webset_impl(ctx, input)
@@ -0,0 +1,20 @@
1
+ from render import TaskContext
2
+
3
+ from ._app import app
4
+ from .client import Deps, dependencies
5
+ from .retry import EXA_CREATE_RETRY
6
+ from .types import CreateWebsetMonitorInput, WebsetMonitorDTO
7
+
8
+
9
+ async def create_webset_monitor_impl(
10
+ ctx: TaskContext, input: CreateWebsetMonitorInput, *, deps: Deps | None = None
11
+ ) -> WebsetMonitorDTO:
12
+ async with dependencies(deps) as resolved:
13
+ return await resolved.exa.create_webset_monitor(input)
14
+
15
+
16
+ @app.task(name="exa.createWebsetMonitor", retry=EXA_CREATE_RETRY)
17
+ async def create_webset_monitor(
18
+ ctx: TaskContext, input: CreateWebsetMonitorInput
19
+ ) -> WebsetMonitorDTO:
20
+ return await create_webset_monitor_impl(ctx, input)
@@ -0,0 +1,18 @@
1
+ from render import TaskContext
2
+
3
+ from ._app import app
4
+ from .client import Deps, dependencies
5
+ from .retry import EXA_CANCEL_RETRY
6
+ from .types import DeleteWebsetInput, DeleteWebsetResult
7
+
8
+
9
+ async def delete_webset_impl(
10
+ ctx: TaskContext, input: DeleteWebsetInput, *, deps: Deps | None = None
11
+ ) -> DeleteWebsetResult:
12
+ async with dependencies(deps) as resolved:
13
+ return await resolved.exa.delete_webset(input)
14
+
15
+
16
+ @app.task(name="exa.deleteWebset", retry=EXA_CANCEL_RETRY)
17
+ async def delete_webset(ctx: TaskContext, input: DeleteWebsetInput) -> DeleteWebsetResult:
18
+ return await delete_webset_impl(ctx, input)
@@ -0,0 +1,18 @@
1
+ from render import TaskContext
2
+
3
+ from ._app import app
4
+ from .client import Deps, dependencies
5
+ from .retry import EXA_READ_RETRY
6
+ from .types import ContentsResult, GetContentsInput
7
+
8
+
9
+ async def get_contents_impl(
10
+ ctx: TaskContext, input: GetContentsInput, *, deps: Deps | None = None
11
+ ) -> ContentsResult:
12
+ async with dependencies(deps) as resolved:
13
+ return await resolved.exa.get_contents(input)
14
+
15
+
16
+ @app.task(name="exa.getContents", retry=EXA_READ_RETRY)
17
+ async def get_contents(ctx: TaskContext, input: GetContentsInput) -> ContentsResult:
18
+ return await get_contents_impl(ctx, input)
@@ -0,0 +1,18 @@
1
+ from render import TaskContext
2
+
3
+ from ._app import app
4
+ from .client import Deps, dependencies
5
+ from .retry import EXA_READ_RETRY
6
+ from .types import ListWebsetItemsInput, WebsetItemsPage
7
+
8
+
9
+ async def list_webset_items_impl(
10
+ ctx: TaskContext, input: ListWebsetItemsInput, *, deps: Deps | None = None
11
+ ) -> WebsetItemsPage:
12
+ async with dependencies(deps) as resolved:
13
+ return await resolved.exa.list_webset_items(input)
14
+
15
+
16
+ @app.task(name="exa.listWebsetItems", retry=EXA_READ_RETRY)
17
+ async def list_webset_items(ctx: TaskContext, input: ListWebsetItemsInput) -> WebsetItemsPage:
18
+ return await list_webset_items_impl(ctx, input)
@@ -0,0 +1,7 @@
1
+ from render import Retry
2
+
3
+ EXA_READ_RETRY = Retry(max_retries=3, wait_duration_ms=1000, backoff_scaling=2)
4
+ EXA_AWAIT_RETRY = Retry(max_retries=360, wait_duration_ms=10000, backoff_scaling=1)
5
+ EXA_CANCEL_RETRY = Retry(max_retries=3, wait_duration_ms=1000, backoff_scaling=2)
6
+ EXA_IDEMPOTENT_WRITE_RETRY = Retry(max_retries=3, wait_duration_ms=1000, backoff_scaling=2)
7
+ EXA_CREATE_RETRY = Retry(max_retries=0, wait_duration_ms=0, backoff_scaling=1)
@@ -0,0 +1,18 @@
1
+ from render import TaskContext
2
+
3
+ from ._app import app
4
+ from .client import Deps, dependencies
5
+ from .retry import EXA_READ_RETRY
6
+ from .types import SearchInput, SearchResult
7
+
8
+
9
+ async def search_impl(
10
+ ctx: TaskContext, input: SearchInput, *, deps: Deps | None = None
11
+ ) -> SearchResult:
12
+ async with dependencies(deps) as resolved:
13
+ return await resolved.exa.search(input)
14
+
15
+
16
+ @app.task(name="exa.search", retry=EXA_READ_RETRY)
17
+ async def search(ctx: TaskContext, input: SearchInput) -> SearchResult:
18
+ return await search_impl(ctx, input)
@@ -0,0 +1,18 @@
1
+ from render import TaskContext
2
+
3
+ from ._app import app
4
+ from .client import Deps, dependencies
5
+ from .retry import EXA_CREATE_RETRY
6
+ from .types import AgentRunRef, StartAgentInput
7
+
8
+
9
+ async def start_agent_impl(
10
+ ctx: TaskContext, input: StartAgentInput, *, deps: Deps | None = None
11
+ ) -> AgentRunRef:
12
+ async with dependencies(deps) as resolved:
13
+ return await resolved.exa.start_agent(input)
14
+
15
+
16
+ @app.task(name="exa.startAgent", retry=EXA_CREATE_RETRY)
17
+ async def start_agent(ctx: TaskContext, input: StartAgentInput) -> AgentRunRef:
18
+ return await start_agent_impl(ctx, input)
@@ -0,0 +1,41 @@
1
+ from ._app import app
2
+ from .answer import answer, answer_impl
3
+ from .await_agent import await_agent, await_agent_impl
4
+ from .await_webset import await_webset, await_webset_impl
5
+ from .cancel_agent import cancel_agent, cancel_agent_impl
6
+ from .cancel_webset import cancel_webset, cancel_webset_impl
7
+ from .create_webset import create_webset, create_webset_impl
8
+ from .create_webset_monitor import create_webset_monitor, create_webset_monitor_impl
9
+ from .delete_webset import delete_webset, delete_webset_impl
10
+ from .get_contents import get_contents, get_contents_impl
11
+ from .list_webset_items import list_webset_items, list_webset_items_impl
12
+ from .search import search, search_impl
13
+ from .start_agent import start_agent, start_agent_impl
14
+
15
+ __all__ = [
16
+ "app",
17
+ "answer",
18
+ "answer_impl",
19
+ "await_agent",
20
+ "await_agent_impl",
21
+ "await_webset",
22
+ "await_webset_impl",
23
+ "cancel_agent",
24
+ "cancel_agent_impl",
25
+ "cancel_webset",
26
+ "cancel_webset_impl",
27
+ "create_webset",
28
+ "create_webset_impl",
29
+ "create_webset_monitor",
30
+ "create_webset_monitor_impl",
31
+ "delete_webset",
32
+ "delete_webset_impl",
33
+ "get_contents",
34
+ "get_contents_impl",
35
+ "list_webset_items",
36
+ "list_webset_items_impl",
37
+ "search",
38
+ "search_impl",
39
+ "start_agent",
40
+ "start_agent_impl",
41
+ ]
@@ -0,0 +1,275 @@
1
+ """JSON contracts ported from the pinned TypeScript pack."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Literal, NotRequired, TypedDict
6
+
7
+
8
+ class ContentsResultStatusesItemError(TypedDict):
9
+ tag: str
10
+ httpStatusCode: float | None
11
+
12
+
13
+ class CreateWebsetInputEntity(TypedDict):
14
+ type: str
15
+
16
+
17
+ class AgentGroundingCitationsItem(TypedDict):
18
+ url: str
19
+ title: str
20
+
21
+
22
+ class ContentsResultStatusesItem(TypedDict):
23
+ id: str
24
+ status: Literal["success"] | Literal["error"]
25
+ error: NotRequired[ContentsResultStatusesItemError]
26
+
27
+
28
+ class ExaContentsOptionsSummaryVariant2(TypedDict):
29
+ query: NotRequired[str]
30
+
31
+
32
+ class ExaContentsOptionsHighlightsVariant2(TypedDict):
33
+ query: NotRequired[str]
34
+ numSentences: NotRequired[float]
35
+
36
+
37
+ class ExaContentsOptionsTextVariant2(TypedDict):
38
+ maxCharacters: float
39
+
40
+
41
+ type JsonPrimitive = str | float | bool | None
42
+
43
+ type JsonValue = JsonPrimitive | list[JsonValue] | dict[str, JsonValue]
44
+
45
+ type JsonObject = dict[str, JsonValue]
46
+
47
+ type ExaSearchType = (
48
+ Literal["auto"]
49
+ | Literal["fast"]
50
+ | Literal["deep-lite"]
51
+ | Literal["deep"]
52
+ | Literal["deep-reasoning"]
53
+ | Literal["instant"]
54
+ )
55
+
56
+
57
+ class ExaDocument(TypedDict):
58
+ id: str
59
+ url: str
60
+ title: str
61
+ publishedDate: str | None
62
+ author: str | None
63
+ text: NotRequired[str]
64
+ highlights: NotRequired[list[str]]
65
+ summary: NotRequired[str]
66
+
67
+
68
+ class ExaContentsOptions(TypedDict):
69
+ text: NotRequired[bool | ExaContentsOptionsTextVariant2]
70
+ highlights: NotRequired[bool | ExaContentsOptionsHighlightsVariant2]
71
+ summary: NotRequired[bool | ExaContentsOptionsSummaryVariant2]
72
+
73
+
74
+ class SearchInput(TypedDict):
75
+ query: str
76
+ type: NotRequired[ExaSearchType]
77
+ numResults: float
78
+ includeDomains: NotRequired[list[str]]
79
+ excludeDomains: NotRequired[list[str]]
80
+ startPublishedDate: NotRequired[str]
81
+ endPublishedDate: NotRequired[str]
82
+ contents: NotRequired[ExaContentsOptions]
83
+ maxContentChars: float
84
+
85
+
86
+ class SearchResult(TypedDict):
87
+ requestId: str
88
+ searchType: str
89
+ results: list[ExaDocument]
90
+ costDollars: float | None
91
+
92
+
93
+ class GetContentsInput(ExaContentsOptions):
94
+ urls: list[str]
95
+ maxContentChars: float
96
+
97
+
98
+ class ContentsResult(TypedDict):
99
+ requestId: str
100
+ results: list[ExaDocument]
101
+ statuses: list[ContentsResultStatusesItem]
102
+ costDollars: float | None
103
+
104
+
105
+ class AnswerInput(TypedDict):
106
+ query: str
107
+ includeCitationText: NotRequired[bool]
108
+ maxContentChars: float
109
+
110
+
111
+ class AnswerResult(TypedDict):
112
+ requestId: str
113
+ answer: JsonValue
114
+ citations: list[ExaDocument]
115
+ costDollars: float | None
116
+
117
+
118
+ type AgentEffort = (
119
+ Literal["minimal"]
120
+ | Literal["low"]
121
+ | Literal["medium"]
122
+ | Literal["high"]
123
+ | Literal["xhigh"]
124
+ | Literal["auto"]
125
+ )
126
+
127
+ type AgentStatus = (
128
+ Literal["queued"]
129
+ | Literal["running"]
130
+ | Literal["completed"]
131
+ | Literal["failed"]
132
+ | Literal["cancelled"]
133
+ )
134
+
135
+
136
+ class StartAgentInput(TypedDict):
137
+ query: str
138
+ outputSchema: NotRequired[JsonObject]
139
+ effort: NotRequired[AgentEffort]
140
+ previousRunId: NotRequired[str]
141
+
142
+
143
+ class AgentRunRef(TypedDict):
144
+ runId: str
145
+ status: AgentStatus
146
+
147
+
148
+ class AgentPendingState(TypedDict):
149
+ runId: str
150
+ status: Literal["queued"] | Literal["running"]
151
+
152
+
153
+ class AwaitAgentInput(TypedDict):
154
+ runId: str
155
+ maxOutputBytes: float
156
+
157
+
158
+ class AgentGrounding(TypedDict):
159
+ field: str
160
+ citations: list[AgentGroundingCitationsItem]
161
+ confidence: Literal["low"] | Literal["medium"] | Literal["high"] | None
162
+
163
+
164
+ class AgentResult(TypedDict):
165
+ runId: str
166
+ status: Literal["completed"]
167
+ text: str | None
168
+ structured: JsonValue | None
169
+ grounding: list[AgentGrounding]
170
+ costDollars: float | None
171
+
172
+
173
+ class CancelAgentInput(TypedDict):
174
+ runId: str
175
+
176
+
177
+ class CancelAgentResult(TypedDict):
178
+ runId: str
179
+ status: Literal["cancelled"]
180
+
181
+
182
+ class WebsetCriterion(TypedDict):
183
+ description: str
184
+
185
+
186
+ class WebsetEnrichment(TypedDict):
187
+ description: str
188
+ format: Literal["text"] | Literal["number"] | Literal["date"] | Literal["boolean"]
189
+
190
+
191
+ class CreateWebsetInput(TypedDict):
192
+ externalId: str
193
+ query: str
194
+ count: float
195
+ criteria: NotRequired[list[WebsetCriterion]]
196
+ entity: NotRequired[CreateWebsetInputEntity]
197
+ enrichments: NotRequired[list[WebsetEnrichment]]
198
+ metadata: NotRequired[dict[str, str]]
199
+
200
+
201
+ type WebsetStatus = Literal["idle"] | Literal["pending"] | Literal["running"] | Literal["paused"]
202
+
203
+
204
+ class WebsetDTO(TypedDict):
205
+ id: str
206
+ externalId: str
207
+ status: WebsetStatus
208
+ title: str | None
209
+ dashboardUrl: str | None
210
+ createdAt: str
211
+ updatedAt: str
212
+
213
+
214
+ class AwaitWebsetInput(TypedDict):
215
+ websetId: str
216
+
217
+
218
+ class CancelWebsetInput(TypedDict):
219
+ websetId: str
220
+
221
+
222
+ class CancelWebsetResult(TypedDict):
223
+ websetId: str
224
+ status: Literal["idle"]
225
+
226
+
227
+ class WebsetItem(TypedDict):
228
+ id: str
229
+ websetId: str
230
+ url: str
231
+ title: str
232
+ entity: JsonObject
233
+ enrichments: JsonObject
234
+ createdAt: str
235
+ updatedAt: str
236
+
237
+
238
+ class ListWebsetItemsInput(TypedDict):
239
+ websetId: str
240
+ cursor: NotRequired[str]
241
+ limit: float
242
+ maxOutputBytes: float
243
+
244
+
245
+ class WebsetItemsPage(TypedDict):
246
+ items: list[WebsetItem]
247
+ nextCursor: str | None
248
+ hasMore: bool
249
+
250
+
251
+ class CreateWebsetMonitorInput(TypedDict):
252
+ websetId: str
253
+ cron: str
254
+ timezone: NotRequired[str]
255
+ query: str
256
+ count: float
257
+ behavior: NotRequired[Literal["append"] | Literal["override"]]
258
+
259
+
260
+ class WebsetMonitorDTO(TypedDict):
261
+ id: str
262
+ websetId: str
263
+ status: Literal["enabled"] | Literal["disabled"]
264
+ cron: str
265
+ timezone: str
266
+ nextRunAt: str | None
267
+
268
+
269
+ class DeleteWebsetInput(TypedDict):
270
+ websetId: str
271
+
272
+
273
+ class DeleteWebsetResult(TypedDict):
274
+ websetId: str
275
+ deleted: Literal[True]
@@ -0,0 +1,62 @@
1
+ """Registration-free exa webhook verification and event mapping."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import time
7
+ from collections.abc import Callable
8
+
9
+ from render_lab_tasks_core.signatures import digest, safe_equal, signature_parts, within_window
10
+ from render_lab_triggers.types import Adapter, Json, WebhookContext, WebhookDispatch, WebhookRequest
11
+
12
+ type OnEvent = Callable[[dict[str, Json]], WebhookDispatch | None]
13
+
14
+
15
+ def verify_exa_signature(
16
+ secret: str,
17
+ raw_body: str,
18
+ signature: str | None,
19
+ *,
20
+ now_seconds: Callable[[], float] | None = None,
21
+ tolerance_seconds: float = 300,
22
+ ) -> bool:
23
+ clock = now_seconds if now_seconds is not None else (lambda: int(time.time()))
24
+ parts = signature_parts(signature)
25
+ timestamp = parts.get("t", [""])[-1]
26
+ signatures = parts.get("v1", [])
27
+ if not timestamp or not signatures or not within_window(timestamp, clock(), tolerance_seconds):
28
+ return False
29
+ expected = digest(secret, f"{timestamp}.{raw_body}")
30
+ return any(safe_equal(value, expected) for value in signatures)
31
+
32
+
33
+ def exa_websets_adapter(
34
+ on_event: OnEvent,
35
+ *,
36
+ secret: str | None = None,
37
+ now_seconds: Callable[[], float] | None = None,
38
+ tolerance_seconds: float = 300,
39
+ ) -> Adapter:
40
+ def verify(req: WebhookRequest) -> bool:
41
+ key = secret if secret is not None else os.getenv("EXA_WEBHOOK_SECRET")
42
+ return bool(key) and (
43
+ verify_exa_signature(
44
+ key or "",
45
+ req["rawBody"],
46
+ req["headers"].get("exa-signature"),
47
+ now_seconds=now_seconds,
48
+ tolerance_seconds=tolerance_seconds,
49
+ )
50
+ )
51
+
52
+ def map_event(ctx: WebhookContext) -> WebhookDispatch | None:
53
+ payload = ctx["body"] if ctx["body"] is not None else {}
54
+ fields = payload if isinstance(payload, dict) else {}
55
+ return on_event(
56
+ {
57
+ "type": (fields.get("type") if fields.get("type") is not None else ""),
58
+ "payload": payload,
59
+ }
60
+ )
61
+
62
+ return Adapter(verify, map_event)