continuum-task-server-bundle 1.0.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.
- continuum_task_server_bundle/__init__.py +1 -0
- continuum_task_server_bundle/daytona/__init__.py +4 -0
- continuum_task_server_bundle/daytona/common.py +534 -0
- continuum_task_server_bundle/daytona/create_sandbox.py +166 -0
- continuum_task_server_bundle/daytona/dispatch.py +125 -0
- continuum_task_server_bundle/daytona/execute_sandbox.py +243 -0
- continuum_task_server_bundle/daytona/filesystem.py +330 -0
- continuum_task_server_bundle/daytona/fs_edit.py +127 -0
- continuum_task_server_bundle/daytona/git_ops.py +585 -0
- continuum_task_server_bundle/daytona/github_app.py +207 -0
- continuum_task_server_bundle/daytona/manage_sandbox.py +104 -0
- continuum_task_server_bundle/daytona/plugin.py +18 -0
- continuum_task_server_bundle/daytona/s3_transfer.py +207 -0
- continuum_task_server_bundle/discord/__init__.py +4 -0
- continuum_task_server_bundle/discord/attachment_registry_db.py +127 -0
- continuum_task_server_bundle/discord/attachment_resolve.py +213 -0
- continuum_task_server_bundle/discord/await_cleanup.py +105 -0
- continuum_task_server_bundle/discord/discord_ready.py +39 -0
- continuum_task_server_bundle/discord/message_await_apply.py +143 -0
- continuum_task_server_bundle/discord/message_await_db.py +197 -0
- continuum_task_server_bundle/discord/message_await_inbound.py +54 -0
- continuum_task_server_bundle/discord/message_await_logic.py +133 -0
- continuum_task_server_bundle/discord/message_await_poller.py +122 -0
- continuum_task_server_bundle/discord/message_chunking.py +45 -0
- continuum_task_server_bundle/discord/methods.py +408 -0
- continuum_task_server_bundle/discord/plugin.py +105 -0
- continuum_task_server_bundle/discord/reaction_await_apply.py +238 -0
- continuum_task_server_bundle/discord/reaction_await_db.py +174 -0
- continuum_task_server_bundle/discord/reaction_await_inbound.py +47 -0
- continuum_task_server_bundle/discord/reaction_await_logic.py +118 -0
- continuum_task_server_bundle/discord/reaction_await_poller.py +131 -0
- continuum_task_server_bundle/discord/s3_attachment_config.py +25 -0
- continuum_task_server_bundle/discord/s3_message_attachments.py +139 -0
- continuum_task_server_bundle/discord/sql/001_message_awaits.sql +112 -0
- continuum_task_server_bundle/discord/sql/002_reaction_awaits.sql +61 -0
- continuum_task_server_bundle/github/__init__.py +4 -0
- continuum_task_server_bundle/github/awaits/__init__.py +1 -0
- continuum_task_server_bundle/github/awaits/apply.py +92 -0
- continuum_task_server_bundle/github/awaits/cleanup.py +94 -0
- continuum_task_server_bundle/github/awaits/db.py +220 -0
- continuum_task_server_bundle/github/awaits/evaluators.py +325 -0
- continuum_task_server_bundle/github/awaits/fetch.py +192 -0
- continuum_task_server_bundle/github/awaits/poller.py +82 -0
- continuum_task_server_bundle/github/awaits/register.py +37 -0
- continuum_task_server_bundle/github/ci_status.py +70 -0
- continuum_task_server_bundle/github/comment_normalize.py +76 -0
- continuum_task_server_bundle/github/errors.py +52 -0
- continuum_task_server_bundle/github/github_app.py +291 -0
- continuum_task_server_bundle/github/github_http.py +377 -0
- continuum_task_server_bundle/github/methods/__init__.py +90 -0
- continuum_task_server_bundle/github/methods/_common.py +183 -0
- continuum_task_server_bundle/github/methods/awaits.py +107 -0
- continuum_task_server_bundle/github/methods/ci.py +158 -0
- continuum_task_server_bundle/github/methods/comments.py +214 -0
- continuum_task_server_bundle/github/methods/credentials.py +59 -0
- continuum_task_server_bundle/github/methods/issues.py +131 -0
- continuum_task_server_bundle/github/methods/pulls.py +329 -0
- continuum_task_server_bundle/github/methods/repos.py +424 -0
- continuum_task_server_bundle/github/methods/search.py +109 -0
- continuum_task_server_bundle/github/plugin.py +91 -0
- continuum_task_server_bundle/github/sql/001_github_awaits.sql +65 -0
- continuum_task_server_bundle/github/webhook_server.py +126 -0
- continuum_task_server_bundle/jira/__init__.py +4 -0
- continuum_task_server_bundle/jira/await_poller.py +236 -0
- continuum_task_server_bundle/jira/await_store.py +271 -0
- continuum_task_server_bundle/jira/config.py +68 -0
- continuum_task_server_bundle/jira/jira_client.py +382 -0
- continuum_task_server_bundle/jira/methods.py +246 -0
- continuum_task_server_bundle/jira/plugin.py +86 -0
- continuum_task_server_bundle/jira/sql/001_jira_issue_comment_waits.sql +19 -0
- continuum_task_server_bundle/jira/webhook.py +70 -0
- continuum_task_server_bundle/openrouter/__init__.py +4 -0
- continuum_task_server_bundle/openrouter/chat_service.py +1037 -0
- continuum_task_server_bundle/openrouter/chat_store.py +849 -0
- continuum_task_server_bundle/openrouter/environment.py +29 -0
- continuum_task_server_bundle/openrouter/handler.py +59 -0
- continuum_task_server_bundle/openrouter/image_context.py +207 -0
- continuum_task_server_bundle/openrouter/openrouter_client.py +324 -0
- continuum_task_server_bundle/openrouter/plugin.py +37 -0
- continuum_task_server_bundle/openrouter/prompt_projection.py +417 -0
- continuum_task_server_bundle/openrouter/sql/chat.sql +50 -0
- continuum_task_server_bundle/openrouter/sql/migrate_prune_then_chunk_v1.sql +11 -0
- continuum_task_server_bundle/roblox/__init__.py +4 -0
- continuum_task_server_bundle/roblox/open_cloud.py +335 -0
- continuum_task_server_bundle/roblox/plugin.py +30 -0
- continuum_task_server_bundle/roblox/storage_s3.py +55 -0
- continuum_task_server_bundle-1.0.0.dist-info/METADATA +109 -0
- continuum_task_server_bundle-1.0.0.dist-info/RECORD +90 -0
- continuum_task_server_bundle-1.0.0.dist-info/WHEEL +5 -0
- continuum_task_server_bundle-1.0.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,408 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
from datetime import timezone
|
|
3
|
+
from io import BytesIO
|
|
4
|
+
from typing import Any
|
|
5
|
+
|
|
6
|
+
import discord
|
|
7
|
+
|
|
8
|
+
from continuum_task_server_bundle.discord import attachment_registry_db
|
|
9
|
+
from continuum_task_server_bundle.discord import message_await_db
|
|
10
|
+
from continuum_task_server_bundle.discord import reaction_await_db
|
|
11
|
+
import continuum_task_server_bundle.discord.reaction_await_logic as reaction_logic
|
|
12
|
+
from continuum_task_server_bundle.discord.message_chunking import split_message_for_discord
|
|
13
|
+
from continuum_task_server_bundle.discord.s3_message_attachments import download_s3_attachment_bodies_for_send
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _await_on_discord_client(client: discord.Client, coro, *, timeout=30.0):
|
|
17
|
+
loop = client.loop
|
|
18
|
+
if loop is None or not loop.is_running():
|
|
19
|
+
raise RuntimeError("Discord client is not running yet")
|
|
20
|
+
return asyncio.run_coroutine_threadsafe(coro, loop).result(timeout=timeout)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def get_message_container_by_ids(
|
|
24
|
+
client: discord.Client,
|
|
25
|
+
channel_id: int,
|
|
26
|
+
thread_id: int | None,
|
|
27
|
+
) -> discord.abc.Messageable:
|
|
28
|
+
channel = client.get_channel(channel_id)
|
|
29
|
+
if channel is None:
|
|
30
|
+
raise RuntimeError(
|
|
31
|
+
f"Discord channel {channel_id} not found (check id and intents)"
|
|
32
|
+
)
|
|
33
|
+
if thread_id is None:
|
|
34
|
+
return channel
|
|
35
|
+
thread = channel.get_thread(thread_id)
|
|
36
|
+
if thread is None:
|
|
37
|
+
raise RuntimeError(
|
|
38
|
+
f"Discord thread {thread_id} not found (check id and intents)"
|
|
39
|
+
)
|
|
40
|
+
return thread
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def resolve_message_container_for_await(
|
|
44
|
+
client: discord.Client, input_data: dict
|
|
45
|
+
) -> tuple[discord.abc.Messageable, int, int | None]:
|
|
46
|
+
"""Return (messageable, channel_id for DB, thread_id for DB or None)."""
|
|
47
|
+
channel_id = input_data.get("channel_id")
|
|
48
|
+
thread_id = input_data.get("thread_id")
|
|
49
|
+
|
|
50
|
+
if channel_id is not None:
|
|
51
|
+
channel = client.get_channel(int(channel_id))
|
|
52
|
+
if channel is None:
|
|
53
|
+
raise RuntimeError(
|
|
54
|
+
f"Discord channel {channel_id} not found (check id and intents)"
|
|
55
|
+
)
|
|
56
|
+
if thread_id is not None:
|
|
57
|
+
thread = channel.get_thread(int(thread_id))
|
|
58
|
+
if thread is None:
|
|
59
|
+
raise RuntimeError(
|
|
60
|
+
f"Discord thread {thread_id} not found (check id and intents)"
|
|
61
|
+
)
|
|
62
|
+
return thread, int(channel_id), int(thread_id)
|
|
63
|
+
return channel, int(channel_id), None
|
|
64
|
+
|
|
65
|
+
if thread_id is not None:
|
|
66
|
+
thread = client.get_thread(int(thread_id))
|
|
67
|
+
if thread is None:
|
|
68
|
+
raise RuntimeError(
|
|
69
|
+
f"Discord thread {thread_id} not found (check id and intents)"
|
|
70
|
+
)
|
|
71
|
+
parent = thread.parent
|
|
72
|
+
if parent is None:
|
|
73
|
+
raise RuntimeError("Thread has no parent channel")
|
|
74
|
+
return thread, int(parent.id), int(thread_id)
|
|
75
|
+
|
|
76
|
+
raise RuntimeError("Channel or thread ID is required")
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _attachment_to_public_dict(
|
|
80
|
+
message: discord.Message, attachment: discord.Attachment
|
|
81
|
+
) -> dict[str, Any]:
|
|
82
|
+
ref = attachment_registry_db.ensure_attachment_ref(
|
|
83
|
+
channel_id=int(message.channel.id),
|
|
84
|
+
message_id=int(message.id),
|
|
85
|
+
discord_attachment_id=int(attachment.id),
|
|
86
|
+
filename=attachment.filename or "",
|
|
87
|
+
size=int(attachment.size or 0),
|
|
88
|
+
content_type=attachment.content_type,
|
|
89
|
+
ephemeral=bool(attachment.ephemeral),
|
|
90
|
+
)
|
|
91
|
+
return {
|
|
92
|
+
"attachment_ref": str(ref) if ref is not None else None,
|
|
93
|
+
"discord_attachment_id": str(attachment.id),
|
|
94
|
+
"message_id": str(message.id),
|
|
95
|
+
"channel_id": str(message.channel.id),
|
|
96
|
+
"filename": attachment.filename,
|
|
97
|
+
"size": attachment.size,
|
|
98
|
+
"content_type": attachment.content_type,
|
|
99
|
+
"ephemeral": attachment.ephemeral,
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def message_to_dict(message: discord.Message) -> dict[str, Any]:
|
|
104
|
+
created = message.created_at
|
|
105
|
+
if created.tzinfo is None:
|
|
106
|
+
created = created.replace(tzinfo=timezone.utc)
|
|
107
|
+
else:
|
|
108
|
+
created = created.astimezone(timezone.utc)
|
|
109
|
+
return {
|
|
110
|
+
"id": str(message.id),
|
|
111
|
+
"content": message.content,
|
|
112
|
+
"author_id": str(message.author.id),
|
|
113
|
+
"author_display_name": message.author.display_name,
|
|
114
|
+
# Webhook messages are not human-authored even when represented by a User.
|
|
115
|
+
"author_is_bot": bool(message.author.bot or message.webhook_id is not None),
|
|
116
|
+
"channel_id": str(message.channel.id),
|
|
117
|
+
"created_at": created.isoformat(),
|
|
118
|
+
"attachments": [_attachment_to_public_dict(message, a) for a in message.attachments],
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
async def _fetch_history_after(
|
|
123
|
+
container: discord.abc.Messageable,
|
|
124
|
+
*,
|
|
125
|
+
after_id: int,
|
|
126
|
+
limit: int,
|
|
127
|
+
) -> list[discord.Message]:
|
|
128
|
+
out: list[discord.Message] = []
|
|
129
|
+
async for m in container.history(limit=limit, after=discord.Object(id=after_id)):
|
|
130
|
+
out.append(m)
|
|
131
|
+
return out
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def send_message(client: discord.Client, input_data: dict) -> dict:
|
|
135
|
+
print("Sending message", input_data)
|
|
136
|
+
|
|
137
|
+
channel_id = input_data.get("channel_id")
|
|
138
|
+
thread_id = input_data.get("thread_id")
|
|
139
|
+
|
|
140
|
+
message_context = None
|
|
141
|
+
|
|
142
|
+
if channel_id is not None:
|
|
143
|
+
channel = client.get_channel(int(channel_id))
|
|
144
|
+
|
|
145
|
+
if channel is None:
|
|
146
|
+
raise RuntimeError(
|
|
147
|
+
f"Discord channel {channel_id} not found (check id and intents)"
|
|
148
|
+
)
|
|
149
|
+
|
|
150
|
+
message_context = channel
|
|
151
|
+
|
|
152
|
+
if thread_id is not None:
|
|
153
|
+
thread = channel.get_thread(int(thread_id))
|
|
154
|
+
|
|
155
|
+
if thread is None:
|
|
156
|
+
raise RuntimeError(
|
|
157
|
+
f"Discord thread {thread_id} not found (check id and intents)"
|
|
158
|
+
)
|
|
159
|
+
|
|
160
|
+
message_context = thread
|
|
161
|
+
|
|
162
|
+
if message_context is None:
|
|
163
|
+
raise RuntimeError("Channel or thread ID is required")
|
|
164
|
+
|
|
165
|
+
text = input_data.get("text")
|
|
166
|
+
s3_bodies = download_s3_attachment_bodies_for_send(input_data)
|
|
167
|
+
|
|
168
|
+
if text is None and not s3_bodies:
|
|
169
|
+
raise RuntimeError("text is required unless s3_attachments is non-empty")
|
|
170
|
+
|
|
171
|
+
content = "" if text is None else text
|
|
172
|
+
chunks = split_message_for_discord(content)
|
|
173
|
+
|
|
174
|
+
sent_messages: list[discord.Message] = []
|
|
175
|
+
for index, chunk in enumerate(chunks):
|
|
176
|
+
is_last = index == len(chunks) - 1
|
|
177
|
+
if is_last and s3_bodies:
|
|
178
|
+
files = [
|
|
179
|
+
discord.File(BytesIO(body), filename=name) for body, name in s3_bodies
|
|
180
|
+
]
|
|
181
|
+
if len(files) == 1:
|
|
182
|
+
sent = _await_on_discord_client(
|
|
183
|
+
client, message_context.send(content=chunk, file=files[0])
|
|
184
|
+
)
|
|
185
|
+
else:
|
|
186
|
+
sent = _await_on_discord_client(
|
|
187
|
+
client, message_context.send(content=chunk, files=files)
|
|
188
|
+
)
|
|
189
|
+
else:
|
|
190
|
+
sent = _await_on_discord_client(client, message_context.send(chunk))
|
|
191
|
+
sent_messages.append(sent)
|
|
192
|
+
|
|
193
|
+
return {
|
|
194
|
+
"success": True,
|
|
195
|
+
"message_id": str(sent_messages[-1].id),
|
|
196
|
+
"message_ids": [str(m.id) for m in sent_messages],
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def create_thread(client: discord.Client, input_data: dict) -> dict:
|
|
201
|
+
channel_id = input_data.get("channel_id")
|
|
202
|
+
|
|
203
|
+
if channel_id is None:
|
|
204
|
+
raise RuntimeError("Channel ID is required")
|
|
205
|
+
|
|
206
|
+
channel = client.get_channel(int(channel_id))
|
|
207
|
+
|
|
208
|
+
if channel is None:
|
|
209
|
+
raise RuntimeError(
|
|
210
|
+
f"Discord channel {channel_id} not found (check id and intents)"
|
|
211
|
+
)
|
|
212
|
+
|
|
213
|
+
thread_name = input_data.get("thread_name", "New Thread")
|
|
214
|
+
|
|
215
|
+
parent_message_id = input_data.get("parent_message_id")
|
|
216
|
+
parent_message = None
|
|
217
|
+
|
|
218
|
+
if parent_message_id is not None:
|
|
219
|
+
parent_message = _await_on_discord_client(
|
|
220
|
+
client, channel.fetch_message(int(parent_message_id))
|
|
221
|
+
)
|
|
222
|
+
|
|
223
|
+
if parent_message is not None:
|
|
224
|
+
thread = _await_on_discord_client(
|
|
225
|
+
client,
|
|
226
|
+
channel.create_thread(name=thread_name, message=parent_message),
|
|
227
|
+
)
|
|
228
|
+
else:
|
|
229
|
+
thread = _await_on_discord_client(
|
|
230
|
+
client,
|
|
231
|
+
channel.create_thread(
|
|
232
|
+
name=thread_name, type=discord.ChannelType.public_thread
|
|
233
|
+
),
|
|
234
|
+
)
|
|
235
|
+
|
|
236
|
+
return {
|
|
237
|
+
"success": True,
|
|
238
|
+
"thread_id": str(thread.id),
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
# Durable await_messages: parameters (input_data JSON)
|
|
243
|
+
# - after_message_id / message_cutoff_id (optional): only messages after this id
|
|
244
|
+
# - limit / message_limit: max messages returned
|
|
245
|
+
# - channel_id, thread_id: location (thread-only allowed; parent channel is stored)
|
|
246
|
+
# - timeout / timeout_seconds: wall-clock deadline from registration
|
|
247
|
+
# - poll_interval / poll_interval_seconds: Discord poll spacing
|
|
248
|
+
# - ignore_own_bot_messages / ignore_own_bot (optional, default true): exclude this bot's messages.
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
def _normalize_ignore_message_ids(raw: Any) -> list[str]:
|
|
252
|
+
if raw is None:
|
|
253
|
+
return []
|
|
254
|
+
if not isinstance(raw, list):
|
|
255
|
+
raise RuntimeError("ignore_message_ids must be a JSON array")
|
|
256
|
+
if len(raw) > 10:
|
|
257
|
+
raise RuntimeError("ignore_message_ids: at most 10 message ids allowed")
|
|
258
|
+
out: list[str] = []
|
|
259
|
+
for x in raw:
|
|
260
|
+
if x is None:
|
|
261
|
+
continue
|
|
262
|
+
try:
|
|
263
|
+
out.append(str(int(str(x))))
|
|
264
|
+
except (TypeError, ValueError) as e:
|
|
265
|
+
raise RuntimeError(f"ignore_message_ids: invalid id {x!r}") from e
|
|
266
|
+
return out
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
def _coerce_ignore_own_bot_messages(raw: Any) -> bool:
|
|
270
|
+
if raw is None:
|
|
271
|
+
return True
|
|
272
|
+
if isinstance(raw, bool):
|
|
273
|
+
return raw
|
|
274
|
+
if isinstance(raw, str):
|
|
275
|
+
s = raw.strip().lower()
|
|
276
|
+
if s in ("0", "false", "no", "off"):
|
|
277
|
+
return False
|
|
278
|
+
if s in ("1", "true", "yes", "on"):
|
|
279
|
+
return True
|
|
280
|
+
return bool(raw)
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
def await_messages(client: discord.Client, item) -> None:
|
|
284
|
+
"""Register a Postgres-backed await; Continuum item is completed by the poller."""
|
|
285
|
+
if not message_await_db.database_url():
|
|
286
|
+
raise RuntimeError("DATABASE_URL is not set (required for await_messages)")
|
|
287
|
+
|
|
288
|
+
input_data = item.input_data_json or {}
|
|
289
|
+
_container, channel_id, thread_id = resolve_message_container_for_await(
|
|
290
|
+
client, input_data
|
|
291
|
+
)
|
|
292
|
+
|
|
293
|
+
raw_cutoff = input_data.get("after_message_id")
|
|
294
|
+
if raw_cutoff is None:
|
|
295
|
+
raw_cutoff = input_data.get("message_cutoff_id")
|
|
296
|
+
after_message_id = int(raw_cutoff) if raw_cutoff is not None else None
|
|
297
|
+
|
|
298
|
+
message_limit = int(input_data.get("message_limit", input_data.get("limit", 50)))
|
|
299
|
+
timeout_seconds = float(
|
|
300
|
+
input_data.get("timeout_seconds", input_data.get("timeout", 60.0))
|
|
301
|
+
)
|
|
302
|
+
poll_interval_seconds = float(
|
|
303
|
+
input_data.get(
|
|
304
|
+
"poll_interval_seconds",
|
|
305
|
+
input_data.get("poll_interval", 60.0),
|
|
306
|
+
)
|
|
307
|
+
)
|
|
308
|
+
quiet_period_seconds = float(
|
|
309
|
+
input_data.get(
|
|
310
|
+
"quiet_period_seconds",
|
|
311
|
+
input_data.get("quiet_period", 0.0),
|
|
312
|
+
)
|
|
313
|
+
)
|
|
314
|
+
|
|
315
|
+
ignore_message_ids = _normalize_ignore_message_ids(
|
|
316
|
+
input_data.get("ignore_message_ids")
|
|
317
|
+
)
|
|
318
|
+
ignore_own_bot_messages = _coerce_ignore_own_bot_messages(
|
|
319
|
+
input_data.get("ignore_own_bot_messages", input_data.get("ignore_own_bot"))
|
|
320
|
+
)
|
|
321
|
+
|
|
322
|
+
message_await_db.insert_message_await(
|
|
323
|
+
queue_item_id=item.id,
|
|
324
|
+
channel_id=channel_id,
|
|
325
|
+
thread_id=thread_id,
|
|
326
|
+
after_message_id=after_message_id,
|
|
327
|
+
message_limit=message_limit,
|
|
328
|
+
timeout_seconds=timeout_seconds,
|
|
329
|
+
poll_interval_seconds=poll_interval_seconds,
|
|
330
|
+
quiet_period_seconds=quiet_period_seconds,
|
|
331
|
+
ignore_message_ids=ignore_message_ids,
|
|
332
|
+
ignore_own_bot_messages=ignore_own_bot_messages,
|
|
333
|
+
)
|
|
334
|
+
|
|
335
|
+
|
|
336
|
+
def _optional_snowflake_id(raw: Any, field_name: str) -> int | None:
|
|
337
|
+
if raw is None:
|
|
338
|
+
return None
|
|
339
|
+
try:
|
|
340
|
+
return int(str(raw))
|
|
341
|
+
except (TypeError, ValueError) as e:
|
|
342
|
+
raise RuntimeError(f"{field_name}: invalid id {raw!r}") from e
|
|
343
|
+
|
|
344
|
+
|
|
345
|
+
def ask(client: discord.Client, item) -> None:
|
|
346
|
+
"""Post a prompt with reactions and register a Postgres-backed reaction await."""
|
|
347
|
+
if not reaction_await_db.database_url():
|
|
348
|
+
raise RuntimeError("DATABASE_URL is not set (required for ask)")
|
|
349
|
+
|
|
350
|
+
input_data = item.input_data_json or {}
|
|
351
|
+
container, channel_id, thread_id = resolve_message_container_for_await(
|
|
352
|
+
client, input_data
|
|
353
|
+
)
|
|
354
|
+
|
|
355
|
+
text = input_data.get("content")
|
|
356
|
+
if text is None:
|
|
357
|
+
text = input_data.get("text")
|
|
358
|
+
if text is None:
|
|
359
|
+
raise RuntimeError("content or text is required")
|
|
360
|
+
|
|
361
|
+
allowed = reaction_logic.normalize_emoji_list(
|
|
362
|
+
input_data.get("emojis", input_data.get("reactions"))
|
|
363
|
+
)
|
|
364
|
+
|
|
365
|
+
timeout_seconds = float(
|
|
366
|
+
input_data.get("timeout_seconds", input_data.get("timeout", 300.0))
|
|
367
|
+
)
|
|
368
|
+
poll_interval_seconds = float(
|
|
369
|
+
input_data.get(
|
|
370
|
+
"poll_interval_seconds",
|
|
371
|
+
input_data.get("poll_interval", 60.0),
|
|
372
|
+
)
|
|
373
|
+
)
|
|
374
|
+
|
|
375
|
+
filter_user_id = _optional_snowflake_id(
|
|
376
|
+
input_data.get("filter_user_id", input_data.get("user_id")),
|
|
377
|
+
"filter_user_id",
|
|
378
|
+
)
|
|
379
|
+
filter_role_id = _optional_snowflake_id(
|
|
380
|
+
input_data.get("filter_role_id", input_data.get("role_id")),
|
|
381
|
+
"filter_role_id",
|
|
382
|
+
)
|
|
383
|
+
|
|
384
|
+
chunks = split_message_for_discord(str(text))
|
|
385
|
+
sent_messages: list[discord.Message] = []
|
|
386
|
+
for chunk in chunks:
|
|
387
|
+
sent = _await_on_discord_client(client, container.send(chunk))
|
|
388
|
+
sent_messages.append(sent)
|
|
389
|
+
|
|
390
|
+
prompt = sent_messages[-1]
|
|
391
|
+
prompt_content = prompt.content if prompt.content else str(text)
|
|
392
|
+
|
|
393
|
+
for canon in allowed:
|
|
394
|
+
emoji = reaction_logic.emoji_for_discord_api(canon)
|
|
395
|
+
_await_on_discord_client(client, prompt.add_reaction(emoji))
|
|
396
|
+
|
|
397
|
+
reaction_await_db.insert_reaction_await(
|
|
398
|
+
queue_item_id=item.id,
|
|
399
|
+
channel_id=channel_id,
|
|
400
|
+
thread_id=thread_id,
|
|
401
|
+
prompt_message_id=int(prompt.id),
|
|
402
|
+
prompt_content=prompt_content,
|
|
403
|
+
allowed_emojis=allowed,
|
|
404
|
+
filter_user_id=filter_user_id,
|
|
405
|
+
filter_role_id=filter_role_id,
|
|
406
|
+
timeout_seconds=timeout_seconds,
|
|
407
|
+
poll_interval_seconds=poll_interval_seconds,
|
|
408
|
+
)
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
"""Discord task registration, gateway and poller lifecycle."""
|
|
2
|
+
import asyncio
|
|
3
|
+
import logging
|
|
4
|
+
import threading
|
|
5
|
+
import time
|
|
6
|
+
from os import getenv
|
|
7
|
+
|
|
8
|
+
import discord
|
|
9
|
+
from .attachment_resolve import resolve_attachment_to_s3
|
|
10
|
+
from .await_cleanup import drop_await_rows
|
|
11
|
+
from .discord_ready import discord_usable, wait_for_discord_ready
|
|
12
|
+
from .message_await_inbound import handle_incoming_message_for_awaits
|
|
13
|
+
from .message_await_poller import run_message_await_poller
|
|
14
|
+
from .methods import ask, await_messages, create_thread, send_message
|
|
15
|
+
from .reaction_await_inbound import handle_raw_reaction_add
|
|
16
|
+
|
|
17
|
+
logger = logging.getLogger(__name__)
|
|
18
|
+
|
|
19
|
+
class _DiscordService:
|
|
20
|
+
def __init__(self, server, client, token):
|
|
21
|
+
self.server, self.client, self.token = server, client, token
|
|
22
|
+
self.stop_event = threading.Event()
|
|
23
|
+
self.gateway = None
|
|
24
|
+
self.poller = None
|
|
25
|
+
self.gateway_error = None
|
|
26
|
+
|
|
27
|
+
def _run_gateway(self):
|
|
28
|
+
try:
|
|
29
|
+
self.client.run(self.token)
|
|
30
|
+
except Exception as exc:
|
|
31
|
+
self.gateway_error = exc
|
|
32
|
+
logger.error("Discord gateway stopped: %s", type(exc).__name__)
|
|
33
|
+
|
|
34
|
+
def start(self):
|
|
35
|
+
if not self.token:
|
|
36
|
+
raise RuntimeError("DISCORD_TOKEN is required")
|
|
37
|
+
self.gateway = threading.Thread(target=self._run_gateway, name="discord-gateway", daemon=True)
|
|
38
|
+
self.gateway.start()
|
|
39
|
+
deadline = time.monotonic() + 120
|
|
40
|
+
while not discord_usable(self.client):
|
|
41
|
+
if not self.gateway.is_alive():
|
|
42
|
+
raise RuntimeError("Discord gateway exited before it was ready") from self.gateway_error
|
|
43
|
+
if time.monotonic() >= deadline:
|
|
44
|
+
raise RuntimeError("Discord client did not become ready within 120s")
|
|
45
|
+
time.sleep(0.1)
|
|
46
|
+
self.poller = threading.Thread(target=run_message_await_poller, args=(self.server, self.client), kwargs={"stop_event": self.stop_event}, name="discord-await-poller", daemon=True)
|
|
47
|
+
self.poller.start()
|
|
48
|
+
|
|
49
|
+
def stop(self):
|
|
50
|
+
self.stop_event.set()
|
|
51
|
+
loop = self.client.loop
|
|
52
|
+
if isinstance(loop, asyncio.AbstractEventLoop) and loop.is_running():
|
|
53
|
+
future = asyncio.run_coroutine_threadsafe(self.client.close(), loop)
|
|
54
|
+
future.result(timeout=10)
|
|
55
|
+
for thread in (self.poller, self.gateway):
|
|
56
|
+
if thread is not None and thread.ident is not None:
|
|
57
|
+
thread.join(timeout=10)
|
|
58
|
+
if thread.is_alive():
|
|
59
|
+
raise RuntimeError(f"{thread.name} did not stop")
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def register_discord(host, *, client=None, token=None, concurrency=1):
|
|
63
|
+
server = host.server
|
|
64
|
+
if client is None:
|
|
65
|
+
intents = discord.Intents.default()
|
|
66
|
+
intents.message_content = True
|
|
67
|
+
client = discord.Client(intents=intents)
|
|
68
|
+
service = _DiscordService(server, client, getenv("DISCORD_TOKEN") if token is None else token)
|
|
69
|
+
|
|
70
|
+
@client.event
|
|
71
|
+
async def on_message(message):
|
|
72
|
+
await handle_incoming_message_for_awaits(server, client, message)
|
|
73
|
+
|
|
74
|
+
@client.event
|
|
75
|
+
async def on_raw_reaction_add(payload):
|
|
76
|
+
await handle_raw_reaction_add(server, client, payload)
|
|
77
|
+
|
|
78
|
+
def handle(item, context):
|
|
79
|
+
context.on_cancelled(lambda: drop_await_rows(item.id))
|
|
80
|
+
wait_for_discord_ready(client, timeout=120.0)
|
|
81
|
+
if context.is_cancelled():
|
|
82
|
+
return
|
|
83
|
+
version = server.client.task_items.versions.get_by_id(item.task_item_version_id)
|
|
84
|
+
method = (version.item_definition_json or {}).get("method", "send_message")
|
|
85
|
+
if method == "send_message":
|
|
86
|
+
result = send_message(client, item.input_data_json)
|
|
87
|
+
elif method == "create_thread":
|
|
88
|
+
result = create_thread(client, item.input_data_json)
|
|
89
|
+
elif method == "await_messages":
|
|
90
|
+
await_messages(client, item)
|
|
91
|
+
result = None
|
|
92
|
+
elif method == "ask":
|
|
93
|
+
ask(client, item)
|
|
94
|
+
result = None
|
|
95
|
+
elif method == "resolve_attachment_to_s3":
|
|
96
|
+
result = resolve_attachment_to_s3(client, item.input_data_json)
|
|
97
|
+
else:
|
|
98
|
+
result = {"success": False, "error": "Method not found"}
|
|
99
|
+
if context.is_cancelled():
|
|
100
|
+
drop_await_rows(item.id)
|
|
101
|
+
elif result is not None:
|
|
102
|
+
server.complete_queue_item(item.id, output_data=result)
|
|
103
|
+
|
|
104
|
+
server.register("discord", handle, auto_complete=False, occupy_slot_until_complete=False, concurrency=concurrency)
|
|
105
|
+
host.add_service("discord", service)
|