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,238 @@
|
|
|
1
|
+
"""Transactional completion for reaction_awaits (selection or timeout)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import logging
|
|
6
|
+
from typing import Any
|
|
7
|
+
from uuid import UUID
|
|
8
|
+
|
|
9
|
+
import discord
|
|
10
|
+
from continuum_task_server import TaskServer
|
|
11
|
+
from continuum_task_server.exceptions import ContinuumError
|
|
12
|
+
|
|
13
|
+
import continuum_task_server_bundle.discord.reaction_await_db as db
|
|
14
|
+
import continuum_task_server_bundle.discord.reaction_await_logic as logic
|
|
15
|
+
from continuum_task_server_bundle.discord.methods import _await_on_discord_client, get_message_container_by_ids
|
|
16
|
+
|
|
17
|
+
logger = logging.getLogger(__name__)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _resolve_member(
|
|
21
|
+
client: discord.Client,
|
|
22
|
+
*,
|
|
23
|
+
guild_id: int | None,
|
|
24
|
+
user_id: int,
|
|
25
|
+
) -> discord.Member | None:
|
|
26
|
+
if guild_id is None:
|
|
27
|
+
return None
|
|
28
|
+
guild = client.get_guild(guild_id)
|
|
29
|
+
if guild is None:
|
|
30
|
+
return None
|
|
31
|
+
member = guild.get_member(user_id)
|
|
32
|
+
if member is not None:
|
|
33
|
+
return member
|
|
34
|
+
try:
|
|
35
|
+
return _await_on_discord_client(client, guild.fetch_member(user_id), timeout=15.0)
|
|
36
|
+
except Exception:
|
|
37
|
+
logger.debug("fetch_member failed guild=%s user=%s", guild_id, user_id)
|
|
38
|
+
return None
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
async def _edit_prompt_async(
|
|
42
|
+
client: discord.Client,
|
|
43
|
+
row: dict[str, Any],
|
|
44
|
+
*,
|
|
45
|
+
reaction: str,
|
|
46
|
+
) -> None:
|
|
47
|
+
container = get_message_container_by_ids(
|
|
48
|
+
client,
|
|
49
|
+
int(row["channel_id"]),
|
|
50
|
+
int(row["thread_id"]) if row.get("thread_id") is not None else None,
|
|
51
|
+
)
|
|
52
|
+
message = await container.fetch_message(int(row["prompt_message_id"]))
|
|
53
|
+
new_content = logic.edited_prompt_content(str(row["prompt_content"]), reaction)
|
|
54
|
+
await message.edit(content=new_content)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _edit_prompt_sync(client: discord.Client, row: dict[str, Any], *, reaction: str) -> None:
|
|
58
|
+
_await_on_discord_client(client, _edit_prompt_async(client, row, reaction=reaction), timeout=30.0)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def try_complete_reaction_await(
|
|
62
|
+
server: TaskServer,
|
|
63
|
+
client: discord.Client,
|
|
64
|
+
row_id: UUID,
|
|
65
|
+
*,
|
|
66
|
+
emoji: discord.PartialEmoji | str,
|
|
67
|
+
user_id: int,
|
|
68
|
+
guild_id: int | None = None,
|
|
69
|
+
heartbeat_after: bool = True,
|
|
70
|
+
) -> bool:
|
|
71
|
+
"""Attempt to complete on a qualifying reaction. Returns True if this call completed the row."""
|
|
72
|
+
if client.user is not None and user_id == client.user.id:
|
|
73
|
+
return False
|
|
74
|
+
|
|
75
|
+
canon = logic.canonical_from_discord_emoji(emoji)
|
|
76
|
+
|
|
77
|
+
queue_item_id: UUID | None = None
|
|
78
|
+
completed_qid: UUID | None = None
|
|
79
|
+
completion_payload: dict[str, Any] | None = None
|
|
80
|
+
row_snapshot: dict[str, Any] | None = None
|
|
81
|
+
|
|
82
|
+
with db.connect() as conn:
|
|
83
|
+
with conn.transaction():
|
|
84
|
+
with conn.cursor() as cur:
|
|
85
|
+
cur.execute(
|
|
86
|
+
"""
|
|
87
|
+
SELECT * FROM reaction_awaits
|
|
88
|
+
WHERE id = %s AND status = 'active'
|
|
89
|
+
FOR UPDATE
|
|
90
|
+
""",
|
|
91
|
+
(str(row_id),),
|
|
92
|
+
)
|
|
93
|
+
row = cur.fetchone()
|
|
94
|
+
if not row:
|
|
95
|
+
return False
|
|
96
|
+
|
|
97
|
+
allowed = db.parse_allowed_emojis(row.get("allowed_emojis"))
|
|
98
|
+
if not logic.emoji_matches(allowed, emoji):
|
|
99
|
+
return False
|
|
100
|
+
|
|
101
|
+
filter_user_id = logic.parse_filter_user_id(row)
|
|
102
|
+
filter_role_id = logic.parse_filter_role_id(row)
|
|
103
|
+
member = _resolve_member(
|
|
104
|
+
client, guild_id=guild_id, user_id=user_id
|
|
105
|
+
)
|
|
106
|
+
if not logic.user_passes_filters(
|
|
107
|
+
member,
|
|
108
|
+
filter_user_id=filter_user_id,
|
|
109
|
+
filter_role_id=filter_role_id,
|
|
110
|
+
reactor_user_id=user_id,
|
|
111
|
+
):
|
|
112
|
+
return False
|
|
113
|
+
|
|
114
|
+
queue_item_id = row["queue_item_id"]
|
|
115
|
+
if isinstance(queue_item_id, str):
|
|
116
|
+
queue_item_id = UUID(queue_item_id)
|
|
117
|
+
|
|
118
|
+
cur.execute(
|
|
119
|
+
"""
|
|
120
|
+
UPDATE reaction_awaits
|
|
121
|
+
SET status = 'completed',
|
|
122
|
+
completed_at = now(),
|
|
123
|
+
selected_reaction = %s,
|
|
124
|
+
selected_user_id = %s
|
|
125
|
+
WHERE id = %s AND status = 'active'
|
|
126
|
+
RETURNING queue_item_id, prompt_message_id, prompt_content,
|
|
127
|
+
channel_id, thread_id
|
|
128
|
+
""",
|
|
129
|
+
(canon, user_id, str(row_id)),
|
|
130
|
+
)
|
|
131
|
+
done = cur.fetchone()
|
|
132
|
+
if not done:
|
|
133
|
+
return False
|
|
134
|
+
|
|
135
|
+
completed_qid = UUID(str(done["queue_item_id"]))
|
|
136
|
+
row_snapshot = dict(done)
|
|
137
|
+
completion_payload = {
|
|
138
|
+
"success": True,
|
|
139
|
+
"timed_out": False,
|
|
140
|
+
"reaction": canon,
|
|
141
|
+
"message_id": str(done["prompt_message_id"]),
|
|
142
|
+
"user_id": str(user_id),
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
if row_snapshot is not None:
|
|
146
|
+
try:
|
|
147
|
+
_edit_prompt_sync(client, row_snapshot, reaction=canon)
|
|
148
|
+
except Exception:
|
|
149
|
+
logger.exception("edit prompt failed for reaction_await %s", row_id)
|
|
150
|
+
|
|
151
|
+
if heartbeat_after and queue_item_id is not None:
|
|
152
|
+
try:
|
|
153
|
+
server.client.queue.heartbeat(queue_item_id)
|
|
154
|
+
except ContinuumError as e:
|
|
155
|
+
logger.warning("heartbeat failed for %s: %s", queue_item_id, e)
|
|
156
|
+
|
|
157
|
+
if completed_qid is not None and completion_payload is not None:
|
|
158
|
+
try:
|
|
159
|
+
server.complete_queue_item(completed_qid, output_data=completion_payload)
|
|
160
|
+
except ContinuumError as e:
|
|
161
|
+
logger.error("complete_queue_item failed for %s: %s", completed_qid, e)
|
|
162
|
+
return True
|
|
163
|
+
|
|
164
|
+
return False
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def try_complete_timeout(
|
|
168
|
+
server: TaskServer,
|
|
169
|
+
client: discord.Client,
|
|
170
|
+
row_id: UUID,
|
|
171
|
+
*,
|
|
172
|
+
heartbeat_after: bool = False,
|
|
173
|
+
) -> bool:
|
|
174
|
+
"""Complete an active await when deadline has passed. Returns True if completed."""
|
|
175
|
+
queue_item_id: UUID | None = None
|
|
176
|
+
completed_qid: UUID | None = None
|
|
177
|
+
completion_payload: dict[str, Any] | None = None
|
|
178
|
+
now = db.utcnow()
|
|
179
|
+
|
|
180
|
+
with db.connect() as conn:
|
|
181
|
+
with conn.transaction():
|
|
182
|
+
with conn.cursor() as cur:
|
|
183
|
+
cur.execute(
|
|
184
|
+
"""
|
|
185
|
+
SELECT * FROM reaction_awaits
|
|
186
|
+
WHERE id = %s AND status = 'active'
|
|
187
|
+
FOR UPDATE
|
|
188
|
+
""",
|
|
189
|
+
(str(row_id),),
|
|
190
|
+
)
|
|
191
|
+
row = cur.fetchone()
|
|
192
|
+
if not row:
|
|
193
|
+
return False
|
|
194
|
+
|
|
195
|
+
if not logic.should_complete_timeout(
|
|
196
|
+
deadline_at=row["deadline_at"], now=now
|
|
197
|
+
):
|
|
198
|
+
return False
|
|
199
|
+
|
|
200
|
+
queue_item_id = row["queue_item_id"]
|
|
201
|
+
if isinstance(queue_item_id, str):
|
|
202
|
+
queue_item_id = UUID(queue_item_id)
|
|
203
|
+
|
|
204
|
+
cur.execute(
|
|
205
|
+
"""
|
|
206
|
+
UPDATE reaction_awaits
|
|
207
|
+
SET status = 'completed', completed_at = now()
|
|
208
|
+
WHERE id = %s AND status = 'active'
|
|
209
|
+
RETURNING queue_item_id, prompt_message_id
|
|
210
|
+
""",
|
|
211
|
+
(str(row_id),),
|
|
212
|
+
)
|
|
213
|
+
done = cur.fetchone()
|
|
214
|
+
if not done:
|
|
215
|
+
return False
|
|
216
|
+
|
|
217
|
+
completed_qid = UUID(str(done["queue_item_id"]))
|
|
218
|
+
completion_payload = {
|
|
219
|
+
"success": True,
|
|
220
|
+
"timed_out": True,
|
|
221
|
+
"reaction": None,
|
|
222
|
+
"message_id": str(done["prompt_message_id"]),
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
if heartbeat_after and queue_item_id is not None:
|
|
226
|
+
try:
|
|
227
|
+
server.client.queue.heartbeat(queue_item_id)
|
|
228
|
+
except ContinuumError as e:
|
|
229
|
+
logger.warning("heartbeat failed for %s: %s", queue_item_id, e)
|
|
230
|
+
|
|
231
|
+
if completed_qid is not None and completion_payload is not None:
|
|
232
|
+
try:
|
|
233
|
+
server.complete_queue_item(completed_qid, output_data=completion_payload)
|
|
234
|
+
except ContinuumError as e:
|
|
235
|
+
logger.error("complete_queue_item failed for %s: %s", completed_qid, e)
|
|
236
|
+
return True
|
|
237
|
+
|
|
238
|
+
return False
|
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
"""PostgreSQL persistence for durable ask / reaction awaits."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
from datetime import datetime, timedelta, timezone
|
|
7
|
+
from os import getenv
|
|
8
|
+
from typing import Any
|
|
9
|
+
from uuid import UUID
|
|
10
|
+
|
|
11
|
+
import psycopg
|
|
12
|
+
from psycopg.rows import dict_row
|
|
13
|
+
from psycopg.types.json import Json
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def database_url() -> str | None:
|
|
17
|
+
url = getenv("DATABASE_URL")
|
|
18
|
+
return url if url else None
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def connect():
|
|
22
|
+
url = database_url()
|
|
23
|
+
if not url:
|
|
24
|
+
raise RuntimeError("DATABASE_URL is not set")
|
|
25
|
+
return psycopg.connect(url, row_factory=dict_row)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def insert_reaction_await(
|
|
29
|
+
*,
|
|
30
|
+
queue_item_id: UUID,
|
|
31
|
+
channel_id: int,
|
|
32
|
+
thread_id: int | None,
|
|
33
|
+
prompt_message_id: int,
|
|
34
|
+
prompt_content: str,
|
|
35
|
+
allowed_emojis: list[str],
|
|
36
|
+
filter_user_id: int | None,
|
|
37
|
+
filter_role_id: int | None,
|
|
38
|
+
timeout_seconds: float,
|
|
39
|
+
poll_interval_seconds: float,
|
|
40
|
+
) -> bool:
|
|
41
|
+
"""Insert a new await row. Returns True if inserted, False if queue_item_id already exists."""
|
|
42
|
+
deadline = timedelta(seconds=timeout_seconds)
|
|
43
|
+
with connect() as conn:
|
|
44
|
+
with conn.transaction():
|
|
45
|
+
with conn.cursor() as cur:
|
|
46
|
+
cur.execute(
|
|
47
|
+
"""
|
|
48
|
+
INSERT INTO reaction_awaits (
|
|
49
|
+
queue_item_id,
|
|
50
|
+
channel_id,
|
|
51
|
+
thread_id,
|
|
52
|
+
prompt_message_id,
|
|
53
|
+
prompt_content,
|
|
54
|
+
allowed_emojis,
|
|
55
|
+
filter_user_id,
|
|
56
|
+
filter_role_id,
|
|
57
|
+
timeout_seconds,
|
|
58
|
+
poll_interval_seconds,
|
|
59
|
+
deadline_at,
|
|
60
|
+
next_poll_at
|
|
61
|
+
)
|
|
62
|
+
VALUES (
|
|
63
|
+
%s, %s, %s, %s, %s, %s, %s, %s, %s, %s,
|
|
64
|
+
now() + %s::interval,
|
|
65
|
+
now()
|
|
66
|
+
)
|
|
67
|
+
ON CONFLICT (queue_item_id) DO NOTHING
|
|
68
|
+
RETURNING id
|
|
69
|
+
""",
|
|
70
|
+
(
|
|
71
|
+
str(queue_item_id),
|
|
72
|
+
channel_id,
|
|
73
|
+
thread_id,
|
|
74
|
+
prompt_message_id,
|
|
75
|
+
prompt_content,
|
|
76
|
+
Json(allowed_emojis),
|
|
77
|
+
filter_user_id,
|
|
78
|
+
filter_role_id,
|
|
79
|
+
timeout_seconds,
|
|
80
|
+
poll_interval_seconds,
|
|
81
|
+
deadline,
|
|
82
|
+
),
|
|
83
|
+
)
|
|
84
|
+
row = cur.fetchone()
|
|
85
|
+
return row is not None
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def list_active_for_prompt_message(message_id: int) -> list[dict[str, Any]]:
|
|
89
|
+
with connect() as conn:
|
|
90
|
+
with conn.transaction():
|
|
91
|
+
with conn.cursor() as cur:
|
|
92
|
+
cur.execute(
|
|
93
|
+
"""
|
|
94
|
+
SELECT * FROM reaction_awaits
|
|
95
|
+
WHERE status = 'active' AND prompt_message_id = %(mid)s
|
|
96
|
+
""",
|
|
97
|
+
{"mid": message_id},
|
|
98
|
+
)
|
|
99
|
+
return list(cur.fetchall())
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def claim_due_reaction_awaits(*, limit: int = 10) -> list[dict[str, Any]]:
|
|
103
|
+
with connect() as conn:
|
|
104
|
+
with conn.transaction():
|
|
105
|
+
with conn.cursor() as cur:
|
|
106
|
+
cur.execute(
|
|
107
|
+
"""
|
|
108
|
+
WITH picked AS (
|
|
109
|
+
SELECT id
|
|
110
|
+
FROM reaction_awaits
|
|
111
|
+
WHERE status = 'active' AND next_poll_at <= now()
|
|
112
|
+
ORDER BY next_poll_at
|
|
113
|
+
FOR UPDATE SKIP LOCKED
|
|
114
|
+
LIMIT %(lim)s
|
|
115
|
+
)
|
|
116
|
+
UPDATE reaction_awaits r
|
|
117
|
+
SET next_poll_at = now() + (r.poll_interval_seconds * INTERVAL '1 second')
|
|
118
|
+
FROM picked p
|
|
119
|
+
WHERE r.id = p.id AND r.status = 'active'
|
|
120
|
+
RETURNING r.*
|
|
121
|
+
""",
|
|
122
|
+
{"lim": limit},
|
|
123
|
+
)
|
|
124
|
+
return list(cur.fetchall())
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def delete_by_queue_item_id(queue_item_id: UUID) -> int:
|
|
128
|
+
"""Delete the await row for this queue item. Returns rows deleted (0 or 1)."""
|
|
129
|
+
with connect() as conn:
|
|
130
|
+
with conn.transaction():
|
|
131
|
+
with conn.cursor() as cur:
|
|
132
|
+
cur.execute(
|
|
133
|
+
"""
|
|
134
|
+
DELETE FROM reaction_awaits
|
|
135
|
+
WHERE queue_item_id = %s
|
|
136
|
+
""",
|
|
137
|
+
(str(queue_item_id),),
|
|
138
|
+
)
|
|
139
|
+
return int(cur.rowcount or 0)
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def mark_failed(*, row_id: UUID, error: dict[str, Any]) -> UUID | None:
|
|
143
|
+
with connect() as conn:
|
|
144
|
+
with conn.transaction():
|
|
145
|
+
with conn.cursor() as cur:
|
|
146
|
+
cur.execute(
|
|
147
|
+
"""
|
|
148
|
+
UPDATE reaction_awaits
|
|
149
|
+
SET status = 'failed',
|
|
150
|
+
completed_at = now(),
|
|
151
|
+
error_json = %s
|
|
152
|
+
WHERE id = %s AND status = 'active'
|
|
153
|
+
RETURNING queue_item_id
|
|
154
|
+
""",
|
|
155
|
+
(Json(error), str(row_id)),
|
|
156
|
+
)
|
|
157
|
+
one = cur.fetchone()
|
|
158
|
+
if not one:
|
|
159
|
+
return None
|
|
160
|
+
return UUID(str(one["queue_item_id"]))
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def utcnow() -> datetime:
|
|
164
|
+
return datetime.now(timezone.utc)
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def parse_allowed_emojis(raw: Any) -> list[str]:
|
|
168
|
+
if raw is None:
|
|
169
|
+
return []
|
|
170
|
+
if isinstance(raw, list):
|
|
171
|
+
return [str(x) for x in raw]
|
|
172
|
+
if isinstance(raw, str):
|
|
173
|
+
return json.loads(raw)
|
|
174
|
+
return list(raw)
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
"""Real-time path: complete reaction awaits from Discord gateway events."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import logging
|
|
7
|
+
from uuid import UUID
|
|
8
|
+
|
|
9
|
+
import discord
|
|
10
|
+
from continuum_task_server import TaskServer
|
|
11
|
+
|
|
12
|
+
import continuum_task_server_bundle.discord.reaction_await_db as db
|
|
13
|
+
from continuum_task_server_bundle.discord.reaction_await_apply import try_complete_reaction_await
|
|
14
|
+
|
|
15
|
+
logger = logging.getLogger(__name__)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
async def handle_raw_reaction_add(
|
|
19
|
+
server: TaskServer,
|
|
20
|
+
client: discord.Client,
|
|
21
|
+
payload: discord.RawReactionActionEvent,
|
|
22
|
+
) -> None:
|
|
23
|
+
if not db.database_url():
|
|
24
|
+
return
|
|
25
|
+
if client.user is not None and payload.user_id == client.user.id:
|
|
26
|
+
return
|
|
27
|
+
|
|
28
|
+
rows = db.list_active_for_prompt_message(int(payload.message_id))
|
|
29
|
+
if not rows:
|
|
30
|
+
return
|
|
31
|
+
|
|
32
|
+
loop = asyncio.get_running_loop()
|
|
33
|
+
guild_id = payload.guild_id
|
|
34
|
+
for row in rows:
|
|
35
|
+
row_id = UUID(str(row["id"]))
|
|
36
|
+
await loop.run_in_executor(
|
|
37
|
+
None,
|
|
38
|
+
lambda rid=row_id, pl=payload: try_complete_reaction_await(
|
|
39
|
+
server,
|
|
40
|
+
client,
|
|
41
|
+
rid,
|
|
42
|
+
emoji=pl.emoji,
|
|
43
|
+
user_id=int(pl.user_id),
|
|
44
|
+
guild_id=guild_id,
|
|
45
|
+
heartbeat_after=True,
|
|
46
|
+
),
|
|
47
|
+
)
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
"""Pure helpers for reaction await matching and completion rules."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
from datetime import datetime
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
import discord
|
|
10
|
+
|
|
11
|
+
_MAX_EMOJIS = 20
|
|
12
|
+
_CUSTOM_EMOJI_RE = re.compile(r"^<(?P<animated>a)?:(?P<name>[\w~]+):(?P<id>\d+)>$")
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def normalize_emoji_input(raw: Any) -> str:
|
|
16
|
+
"""Convert user input to canonical emoji string (unicode or name:id for custom)."""
|
|
17
|
+
if isinstance(raw, dict):
|
|
18
|
+
name = raw.get("name")
|
|
19
|
+
eid = raw.get("id")
|
|
20
|
+
if name is None or eid is None:
|
|
21
|
+
raise RuntimeError("custom emoji object requires name and id")
|
|
22
|
+
return f"{name}:{int(eid)}"
|
|
23
|
+
if isinstance(raw, (int, float)):
|
|
24
|
+
raw = str(int(raw))
|
|
25
|
+
s = str(raw).strip()
|
|
26
|
+
if not s:
|
|
27
|
+
raise RuntimeError("emoji must be non-empty")
|
|
28
|
+
m = _CUSTOM_EMOJI_RE.match(s)
|
|
29
|
+
if m:
|
|
30
|
+
return f"{m.group('name')}:{m.group('id')}"
|
|
31
|
+
if ":" in s and s.split(":")[-1].isdigit():
|
|
32
|
+
parts = s.split(":")
|
|
33
|
+
if len(parts) >= 2 and parts[-1].isdigit():
|
|
34
|
+
return f"{':'.join(parts[:-1])}:{parts[-1]}"
|
|
35
|
+
return s
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def normalize_emoji_list(raw: Any) -> list[str]:
|
|
39
|
+
if raw is None:
|
|
40
|
+
raise RuntimeError("emojis or reactions is required")
|
|
41
|
+
if not isinstance(raw, list):
|
|
42
|
+
raise RuntimeError("emojis must be a JSON array")
|
|
43
|
+
if len(raw) < 1:
|
|
44
|
+
raise RuntimeError("emojis must be non-empty")
|
|
45
|
+
if len(raw) > _MAX_EMOJIS:
|
|
46
|
+
raise RuntimeError(f"emojis: at most {_MAX_EMOJIS} allowed")
|
|
47
|
+
out: list[str] = []
|
|
48
|
+
seen: set[str] = set()
|
|
49
|
+
for item in raw:
|
|
50
|
+
canon = normalize_emoji_input(item)
|
|
51
|
+
if canon not in seen:
|
|
52
|
+
seen.add(canon)
|
|
53
|
+
out.append(canon)
|
|
54
|
+
return out
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def canonical_from_discord_emoji(emoji: discord.PartialEmoji | str) -> str:
|
|
58
|
+
if isinstance(emoji, str):
|
|
59
|
+
m = _CUSTOM_EMOJI_RE.match(emoji.strip())
|
|
60
|
+
if m:
|
|
61
|
+
return f"{m.group('name')}:{m.group('id')}"
|
|
62
|
+
return emoji.strip()
|
|
63
|
+
if emoji.id is not None:
|
|
64
|
+
return f"{emoji.name}:{emoji.id}"
|
|
65
|
+
return str(emoji)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def emoji_matches(allowed: list[str], emoji: discord.PartialEmoji | str) -> bool:
|
|
69
|
+
canon = canonical_from_discord_emoji(emoji)
|
|
70
|
+
return canon in allowed
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def parse_filter_user_id(row: dict[str, Any]) -> int | None:
|
|
74
|
+
raw = row.get("filter_user_id")
|
|
75
|
+
if raw is None:
|
|
76
|
+
return None
|
|
77
|
+
return int(raw)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def parse_filter_role_id(row: dict[str, Any]) -> int | None:
|
|
81
|
+
raw = row.get("filter_role_id")
|
|
82
|
+
if raw is None:
|
|
83
|
+
return None
|
|
84
|
+
return int(raw)
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def user_passes_filters(
|
|
88
|
+
member: discord.Member | None,
|
|
89
|
+
*,
|
|
90
|
+
filter_user_id: int | None,
|
|
91
|
+
filter_role_id: int | None,
|
|
92
|
+
reactor_user_id: int,
|
|
93
|
+
) -> bool:
|
|
94
|
+
if filter_user_id is not None and reactor_user_id != filter_user_id:
|
|
95
|
+
return False
|
|
96
|
+
if filter_role_id is None:
|
|
97
|
+
return True
|
|
98
|
+
if member is None:
|
|
99
|
+
return False
|
|
100
|
+
return any(r.id == filter_role_id for r in member.roles)
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def should_complete_timeout(*, deadline_at: datetime, now: datetime) -> bool:
|
|
104
|
+
if deadline_at.tzinfo is None:
|
|
105
|
+
deadline_at = deadline_at.replace(tzinfo=now.tzinfo)
|
|
106
|
+
return now >= deadline_at
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def edited_prompt_content(prompt_content: str, reaction: str) -> str:
|
|
110
|
+
return f"[{reaction}] {prompt_content}"
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def emoji_for_discord_api(canon: str) -> str | discord.PartialEmoji:
|
|
114
|
+
if ":" in canon:
|
|
115
|
+
name, id_str = canon.rsplit(":", 1)
|
|
116
|
+
if id_str.isdigit():
|
|
117
|
+
return discord.PartialEmoji(name=name, id=int(id_str))
|
|
118
|
+
return canon
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
"""Background polling for Postgres-backed ask / reaction awaits."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import logging
|
|
6
|
+
from typing import Any
|
|
7
|
+
from uuid import UUID
|
|
8
|
+
|
|
9
|
+
import discord
|
|
10
|
+
from continuum_task_server import TaskServer
|
|
11
|
+
from continuum_task_server.exceptions import ContinuumError
|
|
12
|
+
|
|
13
|
+
import continuum_task_server_bundle.discord.reaction_await_db as db
|
|
14
|
+
import continuum_task_server_bundle.discord.reaction_await_logic as logic
|
|
15
|
+
from continuum_task_server_bundle.discord.await_cleanup import heartbeat_claim_or_drop
|
|
16
|
+
from continuum_task_server_bundle.discord.discord_ready import discord_usable
|
|
17
|
+
from continuum_task_server_bundle.discord.methods import _await_on_discord_client, get_message_container_by_ids
|
|
18
|
+
from continuum_task_server_bundle.discord.reaction_await_apply import try_complete_reaction_await, try_complete_timeout
|
|
19
|
+
|
|
20
|
+
logger = logging.getLogger(__name__)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _fail_row(
|
|
24
|
+
server: TaskServer,
|
|
25
|
+
row_id: UUID,
|
|
26
|
+
message: str,
|
|
27
|
+
*,
|
|
28
|
+
type_name: str = "RuntimeError",
|
|
29
|
+
) -> None:
|
|
30
|
+
err = {"error": message, "type": type_name}
|
|
31
|
+
updated = db.mark_failed(row_id=row_id, error=err)
|
|
32
|
+
if updated is None:
|
|
33
|
+
return
|
|
34
|
+
try:
|
|
35
|
+
server.fail_queue_item(updated, error=err)
|
|
36
|
+
except ContinuumError as e:
|
|
37
|
+
logger.error("fail_queue_item failed for %s: %s", updated, e)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
async def _scan_message_reactions(
|
|
41
|
+
client: discord.Client,
|
|
42
|
+
message: discord.Message,
|
|
43
|
+
allowed: list[str],
|
|
44
|
+
) -> list[tuple[discord.PartialEmoji | str, int]]:
|
|
45
|
+
"""Return (emoji, user_id) pairs for qualifying reactions on the message."""
|
|
46
|
+
out: list[tuple[discord.PartialEmoji | str, int]] = []
|
|
47
|
+
bot_id = client.user.id if client.user else None
|
|
48
|
+
for reaction in message.reactions:
|
|
49
|
+
if not logic.emoji_matches(allowed, reaction.emoji):
|
|
50
|
+
continue
|
|
51
|
+
async for user in reaction.users():
|
|
52
|
+
if bot_id is not None and user.id == bot_id:
|
|
53
|
+
continue
|
|
54
|
+
out.append((reaction.emoji, user.id))
|
|
55
|
+
return out
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _process_row(server: TaskServer, client: discord.Client, row: dict[str, Any]) -> None:
|
|
59
|
+
row_id = UUID(str(row["id"]))
|
|
60
|
+
qid = row["queue_item_id"]
|
|
61
|
+
if isinstance(qid, str):
|
|
62
|
+
qid = UUID(qid)
|
|
63
|
+
|
|
64
|
+
if not heartbeat_claim_or_drop(server, qid):
|
|
65
|
+
return
|
|
66
|
+
|
|
67
|
+
now = db.utcnow()
|
|
68
|
+
if logic.should_complete_timeout(deadline_at=row["deadline_at"], now=now):
|
|
69
|
+
try_complete_timeout(server, client, row_id, heartbeat_after=False)
|
|
70
|
+
return
|
|
71
|
+
|
|
72
|
+
try:
|
|
73
|
+
container = get_message_container_by_ids(
|
|
74
|
+
client,
|
|
75
|
+
int(row["channel_id"]),
|
|
76
|
+
int(row["thread_id"]) if row.get("thread_id") is not None else None,
|
|
77
|
+
)
|
|
78
|
+
except RuntimeError as e:
|
|
79
|
+
_fail_row(server, row_id, str(e))
|
|
80
|
+
return
|
|
81
|
+
|
|
82
|
+
allowed = db.parse_allowed_emojis(row.get("allowed_emojis"))
|
|
83
|
+
guild_id: int | None = None
|
|
84
|
+
if hasattr(container, "guild") and container.guild is not None:
|
|
85
|
+
guild_id = container.guild.id
|
|
86
|
+
|
|
87
|
+
try:
|
|
88
|
+
message = _await_on_discord_client(
|
|
89
|
+
client,
|
|
90
|
+
container.fetch_message(int(row["prompt_message_id"])),
|
|
91
|
+
timeout=60.0,
|
|
92
|
+
)
|
|
93
|
+
pairs = _await_on_discord_client(
|
|
94
|
+
client,
|
|
95
|
+
_scan_message_reactions(client, message, allowed),
|
|
96
|
+
timeout=120.0,
|
|
97
|
+
)
|
|
98
|
+
except Exception as e:
|
|
99
|
+
logger.exception("Discord reaction scan failed for row %s", row_id)
|
|
100
|
+
_fail_row(server, row_id, str(e), type_name=type(e).__name__)
|
|
101
|
+
return
|
|
102
|
+
|
|
103
|
+
for emoji, user_id in pairs:
|
|
104
|
+
if try_complete_reaction_await(
|
|
105
|
+
server,
|
|
106
|
+
client,
|
|
107
|
+
row_id,
|
|
108
|
+
emoji=emoji,
|
|
109
|
+
user_id=user_id,
|
|
110
|
+
guild_id=guild_id,
|
|
111
|
+
heartbeat_after=False,
|
|
112
|
+
):
|
|
113
|
+
return
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def poll_reaction_awaits_tick(server: TaskServer, client: discord.Client) -> None:
|
|
117
|
+
if not db.database_url():
|
|
118
|
+
return
|
|
119
|
+
if not discord_usable(client):
|
|
120
|
+
return
|
|
121
|
+
try:
|
|
122
|
+
rows = db.claim_due_reaction_awaits(limit=15)
|
|
123
|
+
except Exception:
|
|
124
|
+
logger.exception("claim_due_reaction_awaits failed")
|
|
125
|
+
return
|
|
126
|
+
|
|
127
|
+
for row in rows:
|
|
128
|
+
try:
|
|
129
|
+
_process_row(server, client, row)
|
|
130
|
+
except Exception:
|
|
131
|
+
logger.exception("process reaction_await row %s failed", row.get("id"))
|