render-lab-tasks-gmail 0.1.0__py3-none-any.whl

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.
@@ -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 GMAIL_RETRY
6
+ from .types import ArchiveInput, ArchiveResult
7
+
8
+
9
+ async def archive_impl(
10
+ ctx: TaskContext, input: ArchiveInput, *, deps: Deps | None = None
11
+ ) -> ArchiveResult:
12
+ async with dependencies(deps) as resolved:
13
+ return await resolved.gmail.archive(input)
14
+
15
+
16
+ @app.task(name="gmail.archive", retry=GMAIL_RETRY)
17
+ async def archive(ctx: TaskContext, input: ArchiveInput) -> ArchiveResult:
18
+ return await archive_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 AWAIT_REPLY_RETRY
6
+ from .types import AwaitReplyInput, GmailMessage
7
+
8
+
9
+ async def await_reply_impl(
10
+ ctx: TaskContext, input: AwaitReplyInput, *, deps: Deps | None = None
11
+ ) -> GmailMessage:
12
+ async with dependencies(deps) as resolved:
13
+ return await resolved.gmail.await_reply(input)
14
+
15
+
16
+ @app.task(name="gmail.awaitReply", retry=AWAIT_REPLY_RETRY)
17
+ async def await_reply(ctx: TaskContext, input: AwaitReplyInput) -> GmailMessage:
18
+ return await await_reply_impl(ctx, input)
@@ -0,0 +1,343 @@
1
+ """Injected vendor interface and one-attempt async HTTP adapter."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import base64
6
+ import math
7
+ import os
8
+ import re
9
+ from collections.abc import AsyncIterator, Mapping
10
+ from contextlib import asynccontextmanager
11
+ from dataclasses import dataclass
12
+ from typing import Any, Protocol
13
+
14
+ import httpx
15
+ from render_lab_tasks_core.google_auth import GoogleAccessToken
16
+ from render_lab_tasks_core.http import HttpClient, enc, nullish, pick, query
17
+
18
+ from . import types as t
19
+
20
+
21
+ def nonnegative_integer(value: float, name: str) -> int:
22
+ if isinstance(value, bool) or not math.isfinite(value) or value < 0 or int(value) != value:
23
+ raise ValueError(name + " must be a nonnegative integer")
24
+ return int(value)
25
+
26
+
27
+ def header(row: Any, name: str) -> str:
28
+ return next(
29
+ (
30
+ h.get("value", "")
31
+ for h in (row.get("payload") or {}).get("headers", [])
32
+ if h.get("name", "").lower() == name.lower()
33
+ ),
34
+ "",
35
+ )
36
+
37
+
38
+ def message(row: Any) -> t.GmailMessage:
39
+ return {
40
+ "id": nullish(row.get("id"), ""),
41
+ "threadId": nullish(row.get("threadId"), ""),
42
+ "from": header(row, "From"),
43
+ "subject": header(row, "Subject"),
44
+ "snippet": nullish(row.get("snippet"), ""),
45
+ "date": header(row, "Date"),
46
+ }
47
+
48
+
49
+ def body(payload: Any) -> str:
50
+ def find(part: Any, mime: str) -> str | None:
51
+ if part.get("mimeType") == mime and (part.get("body") or {}).get("data"):
52
+ return str(part["body"]["data"])
53
+ for child in part.get("parts", []):
54
+ data = find(child, mime)
55
+ if data is not None:
56
+ return data
57
+ return None
58
+
59
+ data = (
60
+ find(payload, "text/plain")
61
+ or find(payload, "text/html")
62
+ or (payload.get("body") or {}).get("data")
63
+ or ""
64
+ )
65
+ return base64.urlsafe_b64decode(data + "=" * (-len(data) % 4)).decode("utf-8", errors="replace")
66
+
67
+
68
+ def raw_message(to: str, subject: str, body: str, extra: Mapping[str, str] | None = None) -> str:
69
+ headers = {"To": to, "Subject": subject, **(extra or {})}
70
+ for name, value in headers.items():
71
+ if any(c in name + value for c in "\r\n"):
72
+ raise ValueError("Email headers must not contain CR or LF")
73
+ lines = ["To: " + to, "Subject: " + subject]
74
+ lines.extend(name + ": " + value for name, value in (extra or {}).items() if value)
75
+ lines.extend(["Content-Type: text/plain; charset=UTF-8", "MIME-Version: 1.0", "", body])
76
+ return base64.urlsafe_b64encode("\r\n".join(lines).encode()).decode().rstrip("=")
77
+
78
+
79
+ def reply_headers(row: Any) -> tuple[str, str, dict[str, str]]:
80
+ subject, id = header(row, "Subject"), header(row, "Message-ID")
81
+ references = " ".join(v for v in [header(row, "References"), id] if v)
82
+ return (
83
+ header(row, "From"),
84
+ subject if re.match("re:", subject, re.I) else "Re: " + subject,
85
+ {"In-Reply-To": id, "References": references},
86
+ )
87
+
88
+
89
+ class Port(Protocol):
90
+ async def archive(self, input: t.ArchiveInput) -> t.ArchiveResult: ...
91
+ async def await_reply(self, input: t.AwaitReplyInput) -> t.GmailMessage: ...
92
+ async def create_label(self, input: t.CreateLabelInput) -> t.CreateLabelResult: ...
93
+ async def draft(self, input: t.DraftInput) -> t.DraftResult: ...
94
+ async def draft_reply(self, input: t.DraftReplyInput) -> t.DraftReplyResult: ...
95
+ async def forward(self, input: t.ForwardInput) -> t.ThreadReplyResult: ...
96
+ async def get_full_thread(self, input: t.GetFullThreadInput) -> t.GmailFullThread: ...
97
+ async def get_message(self, input: t.GetMessageInput) -> t.GmailFullMessage: ...
98
+ async def get_thread(self, input: t.GetThreadInput) -> t.GmailThread: ...
99
+ async def label(self, input: t.LabelInput) -> t.LabelResult: ...
100
+ async def label_thread(self, input: t.LabelThreadInput) -> t.LabelThreadResult: ...
101
+ async def list_labels(self, input: t.ListLabelsInput) -> t.ListLabelsResult: ...
102
+ async def reply(self, input: t.ReplyInput) -> t.ThreadReplyResult: ...
103
+ async def search(self, input: t.SearchInput) -> list[t.GmailMessage]: ...
104
+ async def send(self, input: t.SendInput) -> t.SendResult: ...
105
+ async def trash(self, input: t.TrashInput) -> t.TrashResult: ...
106
+
107
+
108
+ @dataclass(frozen=True)
109
+ class Deps:
110
+ gmail: Port
111
+
112
+
113
+ class Client:
114
+ def __init__(self, http: httpx.AsyncClient, env: Mapping[str, str] | None = None) -> None:
115
+ self.env = os.environ if env is None else env
116
+ self.auth = GoogleAccessToken(http, self.env)
117
+ self.api = HttpClient(
118
+ http,
119
+ "https://gmail.googleapis.com/gmail/v1/users/me",
120
+ auth=self.auth.headers,
121
+ label="Gmail API",
122
+ )
123
+ self._self_address: str | None = None
124
+
125
+ async def _metadata(self, id: str, reply: bool = False) -> Any:
126
+ headers = (
127
+ ["From", "Subject", "Message-ID", "References"]
128
+ if reply
129
+ else ["From", "Subject", "Date"]
130
+ )
131
+ return await self.api.call(
132
+ "/messages/"
133
+ + enc(id)
134
+ + "?format=metadata"
135
+ + "".join("&metadataHeaders=" + enc(h) for h in headers)
136
+ )
137
+
138
+ async def search(self, input: t.SearchInput) -> list[t.GmailMessage]:
139
+ limit = int(input.get("limit", 20))
140
+ row = await self.api.call("/messages?" + query({"q": input["query"], "maxResults": limit}))
141
+ ids = [stub["id"] for stub in row.get("messages", []) if stub.get("id")][:limit]
142
+ return [message(await self._metadata(id)) for id in ids]
143
+
144
+ async def get_message(self, input: t.GetMessageInput) -> t.GmailFullMessage:
145
+ row = await self.api.call("/messages/" + enc(input["id"]) + "?format=full")
146
+ return {**message(row), "to": header(row, "To"), "body": body(row.get("payload") or {})}
147
+
148
+ async def get_thread(self, input: t.GetThreadInput) -> t.GmailThread:
149
+ row = await self.api.call("/threads/" + enc(input["id"]))
150
+ return {
151
+ "id": nullish(row.get("id"), input["id"]),
152
+ "messages": [message(m) for m in row.get("messages", [])],
153
+ }
154
+
155
+ async def get_full_thread(self, input: t.GetFullThreadInput) -> t.GmailFullThread:
156
+ max_messages = nonnegative_integer(input.get("maxMessages", 20), "maxMessages")
157
+ max_chars = nonnegative_integer(input.get("maxBodyChars", 20000), "maxBodyChars")
158
+ thread = await self.get_thread({"id": input["id"]})
159
+ dropped = max(0, len(thread["messages"]) - max_messages)
160
+ result: t.GmailFullThread = {"id": thread["id"], "messages": [], "truncated": dropped > 0}
161
+ for m in thread["messages"][dropped:]:
162
+ msg = await self.get_message({"id": m["id"]})
163
+ encoded = msg["body"].encode("utf-16-le")
164
+ if len(encoded) > max_chars * 2:
165
+ msg["body"] = encoded[: max_chars * 2].decode("utf-16-le", errors="ignore")
166
+ result["truncated"] = True
167
+ result["messages"].append(msg)
168
+ return result
169
+
170
+ async def draft(self, input: t.DraftInput) -> t.DraftResult:
171
+ row = await self.api.call(
172
+ "/drafts",
173
+ method="POST",
174
+ body={"message": {"raw": raw_message(input["to"], input["subject"], input["body"])}},
175
+ )
176
+ return {"draftId": nullish(row.get("id"), "")}
177
+
178
+ async def send(self, input: t.SendInput) -> t.SendResult:
179
+ row = await self.api.call(
180
+ "/messages/send",
181
+ method="POST",
182
+ body={"raw": raw_message(input["to"], input["subject"], input["body"])},
183
+ )
184
+ return {"messageId": nullish(row.get("id"), "")}
185
+
186
+ async def reply(self, input: t.ReplyInput) -> t.ThreadReplyResult:
187
+ orig = await self._metadata(input["messageId"], True)
188
+ to, subject, headers = reply_headers(orig)
189
+ payload = {
190
+ "raw": raw_message(to, subject, input["body"], headers),
191
+ **pick(orig, "threadId"),
192
+ }
193
+ row = await self.api.call("/messages/send", method="POST", body=payload)
194
+ return {
195
+ "messageId": nullish(row.get("id"), ""),
196
+ "threadId": nullish(row.get("threadId"), nullish(orig.get("threadId"), "")),
197
+ }
198
+
199
+ async def draft_reply(self, input: t.DraftReplyInput) -> t.DraftReplyResult:
200
+ if input.get("messageId"):
201
+ orig = await self._metadata(input["messageId"], True)
202
+ else:
203
+ thread = await self.api.call("/threads/" + enc(input["threadId"]))
204
+ messages = thread.get("messages", [])
205
+ if not messages:
206
+ raise ValueError(f"Gmail API: thread {input['threadId']} has no messages.")
207
+ if self._self_address is None:
208
+ profile = await self.api.call("/profile")
209
+ self._self_address = str(nullish(profile.get("emailAddress"), "")).lower()
210
+ me = self._self_address
211
+ orig = next(
212
+ (m for m in reversed(messages) if not me or me not in header(m, "From").lower()),
213
+ messages[-1],
214
+ )
215
+ to, subject, headers = reply_headers(orig)
216
+ if input.get("from"):
217
+ headers["From"] = input["from"]
218
+ row = await self.api.call(
219
+ "/drafts",
220
+ method="POST",
221
+ body={
222
+ "message": {
223
+ "threadId": input["threadId"],
224
+ "raw": raw_message(to, subject, input["body"], headers),
225
+ }
226
+ },
227
+ )
228
+ result: t.DraftReplyResult = {
229
+ "draftId": nullish(row.get("id"), ""),
230
+ "threadId": nullish((row.get("message") or {}).get("threadId"), input["threadId"]),
231
+ }
232
+ if "id" in (row.get("message") or {}):
233
+ result["messageId"] = row["message"]["id"]
234
+ return result
235
+
236
+ async def forward(self, input: t.ForwardInput) -> t.ThreadReplyResult:
237
+ full = await self.get_message({"id": input["messageId"]})
238
+ lines = [input["note"], ""] if input.get("note") else []
239
+ lines.extend(
240
+ [
241
+ "---------- Forwarded message ----------",
242
+ "From: " + full["from"],
243
+ "Date: " + full["date"],
244
+ "Subject: " + full["subject"],
245
+ "To: " + full["to"],
246
+ "",
247
+ full["body"],
248
+ ]
249
+ )
250
+ subject = (
251
+ full["subject"]
252
+ if re.match("fwd:", full["subject"], re.I)
253
+ else "Fwd: " + full["subject"]
254
+ )
255
+ row = await self.api.call(
256
+ "/messages/send",
257
+ method="POST",
258
+ body={"raw": raw_message(input["to"], subject, "\n".join(lines))},
259
+ )
260
+ return {
261
+ "messageId": nullish(row.get("id"), ""),
262
+ "threadId": nullish(row.get("threadId"), ""),
263
+ }
264
+
265
+ async def label(self, input: t.LabelInput) -> t.LabelResult:
266
+ await self.api.call(
267
+ "/messages/" + enc(input["messageId"]) + "/modify",
268
+ method="POST",
269
+ body={
270
+ "addLabelIds": input.get("addLabels", []),
271
+ "removeLabelIds": input.get("removeLabels", []),
272
+ },
273
+ )
274
+ return {"messageId": input["messageId"]}
275
+
276
+ async def label_thread(self, input: t.LabelThreadInput) -> t.LabelThreadResult:
277
+ await self.api.call(
278
+ "/threads/" + enc(input["threadId"]) + "/modify",
279
+ method="POST",
280
+ body={
281
+ "addLabelIds": input.get("addLabels", []),
282
+ "removeLabelIds": input.get("removeLabels", []),
283
+ },
284
+ )
285
+ return {"threadId": input["threadId"]}
286
+
287
+ async def list_labels(self, input: t.ListLabelsInput) -> t.ListLabelsResult:
288
+ row = await self.api.call("/labels")
289
+ return {
290
+ "labels": [
291
+ {"id": nullish(v.get("id"), ""), "name": nullish(v.get("name"), "")}
292
+ for v in row.get("labels", [])
293
+ ]
294
+ }
295
+
296
+ async def create_label(self, input: t.CreateLabelInput) -> t.CreateLabelResult:
297
+ row = await self.api.call("/labels", method="POST", body={"name": input["name"]})
298
+ return {"id": nullish(row.get("id"), ""), "name": nullish(row.get("name"), input["name"])}
299
+
300
+ async def archive(self, input: t.ArchiveInput) -> t.ArchiveResult:
301
+ await self.api.call(
302
+ "/messages/" + enc(input["messageId"]) + "/modify",
303
+ method="POST",
304
+ body={"removeLabelIds": ["INBOX"]},
305
+ )
306
+ return {"messageId": input["messageId"]}
307
+
308
+ async def trash(self, input: t.TrashInput) -> t.TrashResult:
309
+ row = await self.api.call("/messages/" + enc(input["messageId"]) + "/trash", method="POST")
310
+ return {"messageId": nullish(row.get("id"), input["messageId"])}
311
+
312
+ async def await_reply(self, input: t.AwaitReplyInput) -> t.GmailMessage:
313
+ parts = [input["query"]] if input.get("query") else []
314
+ if input.get("afterEpoch"):
315
+ parts.append("after:" + str(math.floor(input["afterEpoch"] / 1000)))
316
+ q = " ".join(parts).strip() or "newer_than:1d"
317
+ row = await self.api.call("/messages?" + query({"q": q, "maxResults": "10"}))
318
+ for stub in row.get("messages", []):
319
+ if not stub.get("id"):
320
+ continue
321
+ msg = message(await self._metadata(stub["id"]))
322
+ if input.get("threadId") and msg["threadId"] != input["threadId"]:
323
+ continue
324
+ return msg
325
+ raise RuntimeError(
326
+ "No reply yet for " + input.get("threadId", input.get("query", "the query"))
327
+ )
328
+
329
+
330
+ @asynccontextmanager
331
+ async def dependencies(deps: Deps | None) -> AsyncIterator[Deps]:
332
+ if deps is not None:
333
+ yield deps
334
+ else:
335
+ async with httpx.AsyncClient(
336
+ timeout=30, transport=httpx.AsyncHTTPTransport(retries=0)
337
+ ) as http:
338
+ yield Deps(gmail=Client(http))
339
+
340
+
341
+ GmailPort = Port
342
+ GmailClient = Client
343
+ GmailDeps = 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 GMAIL_RETRY
6
+ from .types import CreateLabelInput, CreateLabelResult
7
+
8
+
9
+ async def create_label_impl(
10
+ ctx: TaskContext, input: CreateLabelInput, *, deps: Deps | None = None
11
+ ) -> CreateLabelResult:
12
+ async with dependencies(deps) as resolved:
13
+ return await resolved.gmail.create_label(input)
14
+
15
+
16
+ @app.task(name="gmail.createLabel", retry=GMAIL_RETRY)
17
+ async def create_label(ctx: TaskContext, input: CreateLabelInput) -> CreateLabelResult:
18
+ return await create_label_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 GMAIL_RETRY
6
+ from .types import DraftInput, DraftResult
7
+
8
+
9
+ async def draft_impl(
10
+ ctx: TaskContext, input: DraftInput, *, deps: Deps | None = None
11
+ ) -> DraftResult:
12
+ async with dependencies(deps) as resolved:
13
+ return await resolved.gmail.draft(input)
14
+
15
+
16
+ @app.task(name="gmail.draft", retry=GMAIL_RETRY)
17
+ async def draft(ctx: TaskContext, input: DraftInput) -> DraftResult:
18
+ return await draft_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 GMAIL_RETRY
6
+ from .types import DraftReplyInput, DraftReplyResult
7
+
8
+
9
+ async def draft_reply_impl(
10
+ ctx: TaskContext, input: DraftReplyInput, *, deps: Deps | None = None
11
+ ) -> DraftReplyResult:
12
+ async with dependencies(deps) as resolved:
13
+ return await resolved.gmail.draft_reply(input)
14
+
15
+
16
+ @app.task(name="gmail.draftReply", retry=GMAIL_RETRY)
17
+ async def draft_reply(ctx: TaskContext, input: DraftReplyInput) -> DraftReplyResult:
18
+ return await draft_reply_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 GMAIL_RETRY
6
+ from .types import ForwardInput, ThreadReplyResult
7
+
8
+
9
+ async def forward_impl(
10
+ ctx: TaskContext, input: ForwardInput, *, deps: Deps | None = None
11
+ ) -> ThreadReplyResult:
12
+ async with dependencies(deps) as resolved:
13
+ return await resolved.gmail.forward(input)
14
+
15
+
16
+ @app.task(name="gmail.forward", retry=GMAIL_RETRY)
17
+ async def forward(ctx: TaskContext, input: ForwardInput) -> ThreadReplyResult:
18
+ return await forward_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 GMAIL_RETRY
6
+ from .types import GetFullThreadInput, GmailFullThread
7
+
8
+
9
+ async def get_full_thread_impl(
10
+ ctx: TaskContext, input: GetFullThreadInput, *, deps: Deps | None = None
11
+ ) -> GmailFullThread:
12
+ async with dependencies(deps) as resolved:
13
+ return await resolved.gmail.get_full_thread(input)
14
+
15
+
16
+ @app.task(name="gmail.getFullThread", retry=GMAIL_RETRY)
17
+ async def get_full_thread(ctx: TaskContext, input: GetFullThreadInput) -> GmailFullThread:
18
+ return await get_full_thread_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 GMAIL_RETRY
6
+ from .types import GetMessageInput, GmailFullMessage
7
+
8
+
9
+ async def get_message_impl(
10
+ ctx: TaskContext, input: GetMessageInput, *, deps: Deps | None = None
11
+ ) -> GmailFullMessage:
12
+ async with dependencies(deps) as resolved:
13
+ return await resolved.gmail.get_message(input)
14
+
15
+
16
+ @app.task(name="gmail.getMessage", retry=GMAIL_RETRY)
17
+ async def get_message(ctx: TaskContext, input: GetMessageInput) -> GmailFullMessage:
18
+ return await get_message_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 GMAIL_RETRY
6
+ from .types import GetThreadInput, GmailThread
7
+
8
+
9
+ async def get_thread_impl(
10
+ ctx: TaskContext, input: GetThreadInput, *, deps: Deps | None = None
11
+ ) -> GmailThread:
12
+ async with dependencies(deps) as resolved:
13
+ return await resolved.gmail.get_thread(input)
14
+
15
+
16
+ @app.task(name="gmail.getThread", retry=GMAIL_RETRY)
17
+ async def get_thread(ctx: TaskContext, input: GetThreadInput) -> GmailThread:
18
+ return await get_thread_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 GMAIL_RETRY
6
+ from .types import LabelInput, LabelResult
7
+
8
+
9
+ async def label_impl(
10
+ ctx: TaskContext, input: LabelInput, *, deps: Deps | None = None
11
+ ) -> LabelResult:
12
+ async with dependencies(deps) as resolved:
13
+ return await resolved.gmail.label(input)
14
+
15
+
16
+ @app.task(name="gmail.label", retry=GMAIL_RETRY)
17
+ async def label(ctx: TaskContext, input: LabelInput) -> LabelResult:
18
+ return await label_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 GMAIL_RETRY
6
+ from .types import LabelThreadInput, LabelThreadResult
7
+
8
+
9
+ async def label_thread_impl(
10
+ ctx: TaskContext, input: LabelThreadInput, *, deps: Deps | None = None
11
+ ) -> LabelThreadResult:
12
+ async with dependencies(deps) as resolved:
13
+ return await resolved.gmail.label_thread(input)
14
+
15
+
16
+ @app.task(name="gmail.labelThread", retry=GMAIL_RETRY)
17
+ async def label_thread(ctx: TaskContext, input: LabelThreadInput) -> LabelThreadResult:
18
+ return await label_thread_impl(ctx, input)
@@ -0,0 +1,16 @@
1
+ from render import TaskContext
2
+
3
+ from ._app import app
4
+ from .client import Deps, dependencies
5
+ from .retry import GMAIL_RETRY
6
+ from .types import ListLabelsResult
7
+
8
+
9
+ async def list_labels_impl(ctx: TaskContext, *, deps: Deps | None = None) -> ListLabelsResult:
10
+ async with dependencies(deps) as resolved:
11
+ return await resolved.gmail.list_labels({})
12
+
13
+
14
+ @app.task(name="gmail.listLabels", retry=GMAIL_RETRY)
15
+ async def list_labels(ctx: TaskContext) -> ListLabelsResult:
16
+ return await list_labels_impl(ctx)
File without changes
@@ -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 GMAIL_RETRY
6
+ from .types import ReplyInput, ThreadReplyResult
7
+
8
+
9
+ async def reply_impl(
10
+ ctx: TaskContext, input: ReplyInput, *, deps: Deps | None = None
11
+ ) -> ThreadReplyResult:
12
+ async with dependencies(deps) as resolved:
13
+ return await resolved.gmail.reply(input)
14
+
15
+
16
+ @app.task(name="gmail.reply", retry=GMAIL_RETRY)
17
+ async def reply(ctx: TaskContext, input: ReplyInput) -> ThreadReplyResult:
18
+ return await reply_impl(ctx, input)
@@ -0,0 +1,4 @@
1
+ from render import Retry
2
+
3
+ GMAIL_RETRY = Retry(max_retries=3, wait_duration_ms=1_000, backoff_scaling=2)
4
+ AWAIT_REPLY_RETRY = Retry(max_retries=240, wait_duration_ms=15000, 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 GMAIL_RETRY
6
+ from .types import GmailMessage, SearchInput
7
+
8
+
9
+ async def search_impl(
10
+ ctx: TaskContext, input: SearchInput, *, deps: Deps | None = None
11
+ ) -> list[GmailMessage]:
12
+ async with dependencies(deps) as resolved:
13
+ return await resolved.gmail.search(input)
14
+
15
+
16
+ @app.task(name="gmail.search", retry=GMAIL_RETRY)
17
+ async def search(ctx: TaskContext, input: SearchInput) -> list[GmailMessage]:
18
+ return await search_impl(ctx, input)
@@ -0,0 +1,16 @@
1
+ from render import TaskContext
2
+
3
+ from ._app import app
4
+ from .client import Deps, dependencies
5
+ from .retry import GMAIL_RETRY
6
+ from .types import SendInput, SendResult
7
+
8
+
9
+ async def send_impl(ctx: TaskContext, input: SendInput, *, deps: Deps | None = None) -> SendResult:
10
+ async with dependencies(deps) as resolved:
11
+ return await resolved.gmail.send(input)
12
+
13
+
14
+ @app.task(name="gmail.send", retry=GMAIL_RETRY)
15
+ async def send(ctx: TaskContext, input: SendInput) -> SendResult:
16
+ return await send_impl(ctx, input)
@@ -0,0 +1,53 @@
1
+ from ._app import app
2
+ from .archive import archive, archive_impl
3
+ from .await_reply import await_reply, await_reply_impl
4
+ from .create_label import create_label, create_label_impl
5
+ from .draft import draft, draft_impl
6
+ from .draft_reply import draft_reply, draft_reply_impl
7
+ from .forward import forward, forward_impl
8
+ from .get_full_thread import get_full_thread, get_full_thread_impl
9
+ from .get_message import get_message, get_message_impl
10
+ from .get_thread import get_thread, get_thread_impl
11
+ from .label import label, label_impl
12
+ from .label_thread import label_thread, label_thread_impl
13
+ from .list_labels import list_labels, list_labels_impl
14
+ from .reply import reply, reply_impl
15
+ from .search import search, search_impl
16
+ from .send import send, send_impl
17
+ from .trash import trash, trash_impl
18
+
19
+ __all__ = [
20
+ "app",
21
+ "archive",
22
+ "archive_impl",
23
+ "await_reply",
24
+ "await_reply_impl",
25
+ "create_label",
26
+ "create_label_impl",
27
+ "draft",
28
+ "draft_impl",
29
+ "draft_reply",
30
+ "draft_reply_impl",
31
+ "forward",
32
+ "forward_impl",
33
+ "get_full_thread",
34
+ "get_full_thread_impl",
35
+ "get_message",
36
+ "get_message_impl",
37
+ "get_thread",
38
+ "get_thread_impl",
39
+ "label",
40
+ "label_impl",
41
+ "label_thread",
42
+ "label_thread_impl",
43
+ "list_labels",
44
+ "list_labels_impl",
45
+ "reply",
46
+ "reply_impl",
47
+ "search",
48
+ "search_impl",
49
+ "send",
50
+ "send_impl",
51
+ "trash",
52
+ "trash_impl",
53
+ ]
@@ -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 GMAIL_RETRY
6
+ from .types import TrashInput, TrashResult
7
+
8
+
9
+ async def trash_impl(
10
+ ctx: TaskContext, input: TrashInput, *, deps: Deps | None = None
11
+ ) -> TrashResult:
12
+ async with dependencies(deps) as resolved:
13
+ return await resolved.gmail.trash(input)
14
+
15
+
16
+ @app.task(name="gmail.trash", retry=GMAIL_RETRY)
17
+ async def trash(ctx: TaskContext, input: TrashInput) -> TrashResult:
18
+ return await trash_impl(ctx, input)
@@ -0,0 +1,156 @@
1
+ """JSON contracts ported from the pinned TypeScript pack."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Never, NotRequired, TypedDict
6
+
7
+ GmailMessage = TypedDict(
8
+ "GmailMessage",
9
+ {"id": str, "threadId": str, "from": str, "subject": str, "snippet": str, "date": str},
10
+ )
11
+
12
+
13
+ class SearchInput(TypedDict):
14
+ query: str
15
+ limit: NotRequired[float]
16
+
17
+
18
+ class DraftInput(TypedDict):
19
+ to: str
20
+ subject: str
21
+ body: str
22
+
23
+
24
+ class DraftResult(TypedDict):
25
+ draftId: str
26
+
27
+
28
+ class SendInput(TypedDict):
29
+ to: str
30
+ subject: str
31
+ body: str
32
+
33
+
34
+ class SendResult(TypedDict):
35
+ messageId: str
36
+
37
+
38
+ class LabelInput(TypedDict):
39
+ messageId: str
40
+ addLabels: NotRequired[list[str]]
41
+ removeLabels: NotRequired[list[str]]
42
+
43
+
44
+ class LabelResult(TypedDict):
45
+ messageId: str
46
+
47
+
48
+ class GmailFullMessage(GmailMessage):
49
+ to: str
50
+ body: str
51
+
52
+
53
+ class GetMessageInput(TypedDict):
54
+ id: str
55
+
56
+
57
+ class GetThreadInput(TypedDict):
58
+ id: str
59
+
60
+
61
+ class GmailThread(TypedDict):
62
+ id: str
63
+ messages: list[GmailMessage]
64
+
65
+
66
+ class ReplyInput(TypedDict):
67
+ messageId: str
68
+ body: str
69
+
70
+
71
+ class ForwardInput(TypedDict):
72
+ messageId: str
73
+ to: str
74
+ note: NotRequired[str]
75
+
76
+
77
+ class ThreadReplyResult(TypedDict):
78
+ messageId: str
79
+ threadId: str
80
+
81
+
82
+ class CreateLabelInput(TypedDict):
83
+ name: str
84
+
85
+
86
+ class CreateLabelResult(TypedDict):
87
+ id: str
88
+ name: str
89
+
90
+
91
+ class ArchiveInput(TypedDict):
92
+ messageId: str
93
+
94
+
95
+ class ArchiveResult(TypedDict):
96
+ messageId: str
97
+
98
+
99
+ class TrashInput(TypedDict):
100
+ messageId: str
101
+
102
+
103
+ class TrashResult(TypedDict):
104
+ messageId: str
105
+
106
+
107
+ class AwaitReplyInput(TypedDict):
108
+ threadId: NotRequired[str]
109
+ query: NotRequired[str]
110
+ afterEpoch: NotRequired[float]
111
+
112
+
113
+ DraftReplyInput = TypedDict(
114
+ "DraftReplyInput",
115
+ {"threadId": str, "body": str, "messageId": NotRequired[str], "from": NotRequired[str]},
116
+ )
117
+
118
+
119
+ class DraftReplyResult(TypedDict):
120
+ draftId: str
121
+ threadId: str
122
+ messageId: NotRequired[str]
123
+
124
+
125
+ class GmailLabel(TypedDict):
126
+ id: str
127
+ name: str
128
+
129
+
130
+ class ListLabelsResult(TypedDict):
131
+ labels: list[GmailLabel]
132
+
133
+
134
+ class LabelThreadInput(TypedDict):
135
+ threadId: str
136
+ addLabels: NotRequired[list[str]]
137
+ removeLabels: NotRequired[list[str]]
138
+
139
+
140
+ class LabelThreadResult(TypedDict):
141
+ threadId: str
142
+
143
+
144
+ class GetFullThreadInput(TypedDict):
145
+ id: str
146
+ maxMessages: NotRequired[float]
147
+ maxBodyChars: NotRequired[float]
148
+
149
+
150
+ class GmailFullThread(TypedDict):
151
+ id: str
152
+ messages: list[GmailFullMessage]
153
+ truncated: bool
154
+
155
+
156
+ type ListLabelsInput = dict[str, Never]
@@ -0,0 +1,84 @@
1
+ Metadata-Version: 2.5
2
+ Name: render-lab-tasks-gmail
3
+ Version: 0.1.0
4
+ Summary: gmail 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==1.0.1
12
+ Description-Content-Type: text/markdown
13
+
14
+ # render-lab-tasks-gmail
15
+
16
+ Python port of all 16 registered tasks in the pinned TypeScript pack at
17
+ `45f9c2d44bd28e01ae9813e0d2ff56ee6c533816`. Python 3.12+.
18
+
19
+ Install this distribution and its dependencies:
20
+
21
+ ```sh
22
+ pip install render-lab-tasks-gmail==0.1.0
23
+ ```
24
+
25
+ Import definitions from `render_lab_tasks_gmail.tasks`; combine `app` objects
26
+ with `Workflows.from_workflows(...)`. JSON fields retain TS spelling; functions
27
+ use snake_case. Package root imports are inert.
28
+
29
+ ## Tasks
30
+
31
+ | Registered name | Python export (also exposes `_impl`) |
32
+ | --- | --- |
33
+ | `gmail.archive` | `archive` |
34
+ | `gmail.awaitReply` | `await_reply` |
35
+ | `gmail.createLabel` | `create_label` |
36
+ | `gmail.draft` | `draft` |
37
+ | `gmail.draftReply` | `draft_reply` |
38
+ | `gmail.forward` | `forward` |
39
+ | `gmail.getFullThread` | `get_full_thread` |
40
+ | `gmail.getMessage` | `get_message` |
41
+ | `gmail.getThread` | `get_thread` |
42
+ | `gmail.label` | `label` |
43
+ | `gmail.labelThread` | `label_thread` |
44
+ | `gmail.listLabels` | `list_labels` |
45
+ | `gmail.reply` | `reply` |
46
+ | `gmail.search` | `search` |
47
+ | `gmail.send` | `send` |
48
+ | `gmail.trash` | `trash` |
49
+
50
+ ## Dependencies and retries
51
+
52
+ Raw implementations accept context first and keyword-only `deps`. The `.client`
53
+ module exports typed `Port`, `Deps`, and `Client` classes. Inject a fake port, or
54
+ pass a caller-owned `httpx.AsyncClient` to `Client`. Default dependencies close
55
+ their client after one operation. Credentials resolve at first use. Transport
56
+ retries are disabled; `retry.py` owns durable policies. DTO types are in `.types`.
57
+ Requires core >=0.1.1.
58
+
59
+ ## Environment
60
+
61
+ | Variable | Contract |
62
+ | --- | --- |
63
+ | `GOOGLE_ACCESS_TOKEN` | Optional pre-issued token; takes precedence. |
64
+ | `GOOGLE_CLIENT_ID` | Required with secret and refresh token when no access token is supplied. |
65
+ | `GOOGLE_CLIENT_SECRET` | OAuth client secret for refresh. |
66
+ | `GOOGLE_REFRESH_TOKEN` | Refresh token granted the scopes for the operations you use. |
67
+
68
+ ## Verification and limitations
69
+
70
+ Reads, labels, drafts, sends, replies, forwards, and reply polling use Gmail v1.
71
+ Reply drafts prefer the latest inbound message and preserve MIME threading headers;
72
+ optional From must be a verified send-as address. Header CR/LF injection is rejected.
73
+ getFullThread defaults to 20 messages and 20,000 UTF-16 units per body; Python drops
74
+ a split surrogate pair rather than returning invalid Unicode and rejects invalid
75
+ limits. `list_labels_impl(ctx, *, deps=...)` and wrapped `list_labels(ctx)` take no
76
+ input, matching the TS operation. awaitReply checks one page of ten messages per
77
+ attempt; it does not independently verify sender identity. Send/draft/forward
78
+ retain retries and may duplicate mail after an ambiguous response. Use test mailboxes.
79
+
80
+ Shared fixtures execute the actual pinned TS implementations and compare Python
81
+ outputs and requests. Sanity's SDK calls are translated into separately asserted
82
+ REST requests. These are hermetic checks, not real account or hosted verification.
83
+ See [the testing backlog](https://github.com/render-lab/render-tasks-python/issues/1)
84
+ and the root verification tracker. Licensed under MIT.
@@ -0,0 +1,27 @@
1
+ render_lab_tasks_gmail/__init__.py,sha256=fGcyw3Sxjue9wB_1RdFbEFKm5DXSlw_6vD2ud03a6og,58
2
+ render_lab_tasks_gmail/_app.py,sha256=nkWSD_6eq3xzdPJ_G7z6d5mv8tSB-Rq21yp07usJihA,48
3
+ render_lab_tasks_gmail/archive.py,sha256=I-QlfMcZt_35nFeK5rO6nFonjhT6myhoyOOJsSYI7oI,556
4
+ render_lab_tasks_gmail/await_reply.py,sha256=TizgxNTKPqfqeloh6nf_xoKaTtJtmmNNYgS7723zpIc,593
5
+ render_lab_tasks_gmail/client.py,sha256=JJnnuw7PGu_WUWeWwaRHOENas-K57VWB1MfSfa-zTmY,13956
6
+ render_lab_tasks_gmail/create_label.py,sha256=hIh3OfiXnoKKdJ_-KAeWb7EZ0hAyYy416VRD_bKOzME,604
7
+ render_lab_tasks_gmail/draft.py,sha256=Zu0i8MIB2aYa2e4yQP8610R9rUOtv2frFFpnggyVtCs,534
8
+ render_lab_tasks_gmail/draft_reply.py,sha256=h1WrYqsQeN9kwz871_DViBzrgPD5kPGUk9iyqU4_0KM,593
9
+ render_lab_tasks_gmail/forward.py,sha256=lYgZVfc4a85CbCbRyFmC04PxDg_hqR_ckLmkvP9feb4,568
10
+ render_lab_tasks_gmail/get_full_thread.py,sha256=xoGD7gafTFPT_eAGP5HSkwF6sZsAeECRw2JeZuEWi20,618
11
+ render_lab_tasks_gmail/get_message.py,sha256=1bP-Pduoz9MgI4bqUMJSi9iML1LntIBZc2jwZC6cgyE,593
12
+ render_lab_tasks_gmail/get_thread.py,sha256=1nfotjUjmg27H5k0p_dy0O4DPZImTrBxEH_SA3CE7Ac,570
13
+ render_lab_tasks_gmail/label.py,sha256=8_bmkLGvlHeeboCnAkHrCG3ZQ9qEiOP2BJhlU0B1xFc,534
14
+ render_lab_tasks_gmail/label_thread.py,sha256=Sdin1T-eud_tP_dYdLbRpWMECKb7cr8G_yTPzwQSlU0,604
15
+ render_lab_tasks_gmail/list_labels.py,sha256=8Co01AzjYIKUDrgK11KO_NnwBUC7nf8RMtgJRAOeuzI,512
16
+ render_lab_tasks_gmail/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
17
+ render_lab_tasks_gmail/reply.py,sha256=FxJJ1ZJiPwE0czzejnC1XyuwosuqlKQiqx9l7aALPro,552
18
+ render_lab_tasks_gmail/retry.py,sha256=brhT-KvRbmxdv88tCiBJgiBfhlobu0b5M41FskbhrQs,190
19
+ render_lab_tasks_gmail/search.py,sha256=rm-6-sVPT_04bjZQ--R83UW3rSBDCphztya8RO61zLg,557
20
+ render_lab_tasks_gmail/send.py,sha256=julA84B-sT0BxRsiwFq3Z_PMqeXUYs9Q10OXef8WNSw,517
21
+ render_lab_tasks_gmail/tasks.py,sha256=CVBGLiTQSqPEo0603sI9nw3f-SVKzewg-bnx5cBZ2TI,1421
22
+ render_lab_tasks_gmail/trash.py,sha256=FHFD9Jshcu8FvXkrIA22FVB4oOrKgjhr-DA7cx_0auE,534
23
+ render_lab_tasks_gmail/types.py,sha256=nd-IDH5M-2Wg6xlCOvYuutZy5dqWD7XkBM-JlOTEJFw,2547
24
+ render_lab_tasks_gmail-0.1.0.dist-info/METADATA,sha256=eByPvyhEncl-foJPkLG2l1Yi5GN6-zIyeIy8hDQ5ft0,3508
25
+ render_lab_tasks_gmail-0.1.0.dist-info/WHEEL,sha256=zOwg4jB6zX2kU910N-cMawjivD6tO8NEWvE12je1bVk,87
26
+ render_lab_tasks_gmail-0.1.0.dist-info/licenses/LICENSE,sha256=LvmsuKGkhvlSISJRqvBIPUQ_BqVDFRe0RghPSmDebzU,1067
27
+ render_lab_tasks_gmail-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.32.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -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.