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,25 @@
|
|
|
1
|
+
"""Optional S3 settings for attachment archival (resolve_attachment_to_s3)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from os import getenv
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def s3_bucket() -> str | None:
|
|
9
|
+
b = getenv("S3_ATTACHMENTS_BUCKET")
|
|
10
|
+
return b if b else None
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def s3_prefix() -> str:
|
|
14
|
+
p = getenv("S3_ATTACHMENTS_PREFIX", "discord-attachments/")
|
|
15
|
+
if not p.endswith("/"):
|
|
16
|
+
p += "/"
|
|
17
|
+
return p
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def aws_region() -> str | None:
|
|
21
|
+
return getenv("AWS_REGION") or getenv("AWS_DEFAULT_REGION")
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def s3_configured() -> bool:
|
|
25
|
+
return bool(s3_bucket())
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
"""Download objects from S3 for send_message (optional attachments)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
from typing import Any
|
|
7
|
+
from uuid import UUID
|
|
8
|
+
|
|
9
|
+
import continuum_task_server_bundle.discord.attachment_registry_db as reg
|
|
10
|
+
import continuum_task_server_bundle.discord.message_await_db as mdb
|
|
11
|
+
import continuum_task_server_bundle.discord.s3_attachment_config as s3cfg
|
|
12
|
+
def _s3_client():
|
|
13
|
+
import boto3
|
|
14
|
+
|
|
15
|
+
extra: dict[str, Any] = {}
|
|
16
|
+
region = s3cfg.aws_region()
|
|
17
|
+
if region:
|
|
18
|
+
extra["region_name"] = region
|
|
19
|
+
return boto3.client("s3", **extra)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _get_object_bytes(bucket: str, key: str) -> bytes:
|
|
23
|
+
s3 = _s3_client()
|
|
24
|
+
resp = s3.get_object(Bucket=bucket, Key=key)
|
|
25
|
+
return resp["Body"].read()
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _parse_s3_uri(uri: str) -> tuple[str, str]:
|
|
29
|
+
"""Parse s3://bucket/object-key into (bucket, key). Key may contain slashes."""
|
|
30
|
+
u = uri.strip()
|
|
31
|
+
if not u.lower().startswith("s3://"):
|
|
32
|
+
raise ValueError("s3_uri must start with s3://")
|
|
33
|
+
rest = u[5:]
|
|
34
|
+
slash = rest.find("/")
|
|
35
|
+
if slash <= 0 or slash == len(rest) - 1:
|
|
36
|
+
raise ValueError("s3_uri must be s3://bucket-name/object-key")
|
|
37
|
+
bucket = rest[:slash].strip()
|
|
38
|
+
key = rest[slash + 1 :].lstrip("/")
|
|
39
|
+
if not bucket or not key:
|
|
40
|
+
raise ValueError("s3_uri has empty bucket or key")
|
|
41
|
+
return bucket, key
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _filename_for_discord(*, explicit: str | None, s3_key: str, fallback: str) -> str:
|
|
45
|
+
if explicit and explicit.strip():
|
|
46
|
+
return os.path.basename(explicit.strip()) or "file"
|
|
47
|
+
base = os.path.basename(s3_key.rstrip("/")) or "file"
|
|
48
|
+
if base and base != "/":
|
|
49
|
+
return base
|
|
50
|
+
return fallback or "file"
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def download_s3_attachment_bodies_for_send(input_data: dict) -> list[tuple[bytes, str]]:
|
|
54
|
+
"""Return (bytes, discord_filename) for each entry in input_data['s3_attachments']."""
|
|
55
|
+
raw = input_data.get("s3_attachments")
|
|
56
|
+
if not raw:
|
|
57
|
+
return []
|
|
58
|
+
if not isinstance(raw, list):
|
|
59
|
+
raise RuntimeError("s3_attachments must be a JSON array")
|
|
60
|
+
if len(raw) > 10:
|
|
61
|
+
raise RuntimeError("s3_attachments: at most 10 files allowed")
|
|
62
|
+
|
|
63
|
+
out: list[tuple[bytes, str]] = []
|
|
64
|
+
default_bucket = s3cfg.s3_bucket()
|
|
65
|
+
|
|
66
|
+
for i, item in enumerate(raw):
|
|
67
|
+
if not isinstance(item, dict):
|
|
68
|
+
raise RuntimeError(f"s3_attachments[{i}] must be a JSON object")
|
|
69
|
+
|
|
70
|
+
explicit_name = item.get("filename")
|
|
71
|
+
if explicit_name is not None and not isinstance(explicit_name, str):
|
|
72
|
+
raise RuntimeError(f"s3_attachments[{i}].filename must be a string")
|
|
73
|
+
|
|
74
|
+
ref_raw = item.get("attachment_ref")
|
|
75
|
+
if ref_raw is not None:
|
|
76
|
+
if not mdb.database_url():
|
|
77
|
+
raise RuntimeError("DATABASE_URL is not set (required for attachment_ref in s3_attachments)")
|
|
78
|
+
try:
|
|
79
|
+
ref_uuid = UUID(str(ref_raw))
|
|
80
|
+
except (ValueError, TypeError) as e:
|
|
81
|
+
raise RuntimeError(f"s3_attachments[{i}]: invalid attachment_ref") from e
|
|
82
|
+
row = reg.get_by_ref(attachment_ref=ref_uuid)
|
|
83
|
+
if row is None:
|
|
84
|
+
raise RuntimeError(f"s3_attachments[{i}]: unknown attachment_ref")
|
|
85
|
+
bucket = row.get("s3_bucket")
|
|
86
|
+
key = row.get("s3_key")
|
|
87
|
+
if not bucket or not key:
|
|
88
|
+
raise RuntimeError(
|
|
89
|
+
f"s3_attachments[{i}]: attachment_ref has no S3 location yet; "
|
|
90
|
+
"call resolve_attachment_to_s3 first"
|
|
91
|
+
)
|
|
92
|
+
reg_name = row.get("filename") or ""
|
|
93
|
+
fname = _filename_for_discord(
|
|
94
|
+
explicit=explicit_name, s3_key=key, fallback=reg_name
|
|
95
|
+
)
|
|
96
|
+
body = _get_object_bytes(bucket, key)
|
|
97
|
+
out.append((body, fname))
|
|
98
|
+
continue
|
|
99
|
+
|
|
100
|
+
uri_raw = item.get("s3_uri")
|
|
101
|
+
if uri_raw is not None:
|
|
102
|
+
if not isinstance(uri_raw, str):
|
|
103
|
+
raise RuntimeError(f"s3_attachments[{i}].s3_uri must be a string")
|
|
104
|
+
try:
|
|
105
|
+
bucket, key = _parse_s3_uri(uri_raw)
|
|
106
|
+
except ValueError as e:
|
|
107
|
+
raise RuntimeError(f"s3_attachments[{i}]: invalid s3_uri") from e
|
|
108
|
+
fname = _filename_for_discord(
|
|
109
|
+
explicit=explicit_name, s3_key=key, fallback="file"
|
|
110
|
+
)
|
|
111
|
+
body = _get_object_bytes(bucket, key)
|
|
112
|
+
out.append((body, fname))
|
|
113
|
+
continue
|
|
114
|
+
|
|
115
|
+
key = item.get("s3_key")
|
|
116
|
+
if not key or not isinstance(key, str):
|
|
117
|
+
raise RuntimeError(
|
|
118
|
+
f"s3_attachments[{i}]: use s3_uri, or s3_key (with optional s3_bucket), or attachment_ref"
|
|
119
|
+
)
|
|
120
|
+
|
|
121
|
+
bucket = item.get("s3_bucket")
|
|
122
|
+
if bucket is not None:
|
|
123
|
+
if not isinstance(bucket, str):
|
|
124
|
+
raise RuntimeError(f"s3_attachments[{i}].s3_bucket must be a string")
|
|
125
|
+
bucket = bucket.strip()
|
|
126
|
+
if not bucket:
|
|
127
|
+
bucket = default_bucket
|
|
128
|
+
if not bucket:
|
|
129
|
+
raise RuntimeError(
|
|
130
|
+
f"s3_attachments[{i}]: set s3_bucket on the entry or S3_ATTACHMENTS_BUCKET in the environment"
|
|
131
|
+
)
|
|
132
|
+
|
|
133
|
+
fname = _filename_for_discord(
|
|
134
|
+
explicit=explicit_name, s3_key=key, fallback="file"
|
|
135
|
+
)
|
|
136
|
+
body = _get_object_bytes(bucket, key)
|
|
137
|
+
out.append((body, fname))
|
|
138
|
+
|
|
139
|
+
return out
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
-- message_awaits: durable state for Continuum queue items waiting on Discord messages.
|
|
2
|
+
--
|
|
3
|
+
-- Apply (dev / reset): psql "$DATABASE_URL" -v ON_ERROR_STOP=1 -f db/001_message_awaits.sql
|
|
4
|
+
--
|
|
5
|
+
-- Requires PostgreSQL 13+ (gen_random_uuid() without extensions). For PG 12, add:
|
|
6
|
+
-- CREATE EXTENSION IF NOT EXISTS pgcrypto;
|
|
7
|
+
-- and keep DEFAULT gen_random_uuid().
|
|
8
|
+
|
|
9
|
+
DROP TABLE IF EXISTS message_awaits CASCADE;
|
|
10
|
+
DROP TABLE IF EXISTS discord_attachment_registry CASCADE;
|
|
11
|
+
|
|
12
|
+
CREATE TABLE message_awaits (
|
|
13
|
+
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
14
|
+
|
|
15
|
+
-- Continuum queue item this await belongs to (one row per item; idempotent INSERT).
|
|
16
|
+
queue_item_id UUID NOT NULL UNIQUE,
|
|
17
|
+
|
|
18
|
+
-- Discord target: messages match message.channel.id to thread_id OR (when null) channel_id.
|
|
19
|
+
channel_id BIGINT NOT NULL,
|
|
20
|
+
thread_id BIGINT,
|
|
21
|
+
|
|
22
|
+
-- Optional exclusive lower bound (snowflake); combined in app with last_message_snowflake / registered_at.
|
|
23
|
+
after_message_id BIGINT,
|
|
24
|
+
|
|
25
|
+
-- Up to 10 Discord message snowflakes (JSON array of strings/numbers) excluded from merge and on_message.
|
|
26
|
+
ignore_message_ids JSONB NOT NULL DEFAULT '[]'::jsonb
|
|
27
|
+
CHECK (
|
|
28
|
+
jsonb_typeof(ignore_message_ids) = 'array'
|
|
29
|
+
AND jsonb_array_length(ignore_message_ids) <= 10
|
|
30
|
+
),
|
|
31
|
+
|
|
32
|
+
-- When true, messages authored by this bot user are excluded (merge + inbound).
|
|
33
|
+
ignore_own_bot_messages BOOLEAN NOT NULL DEFAULT true,
|
|
34
|
+
|
|
35
|
+
registered_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
|
36
|
+
|
|
37
|
+
message_limit INTEGER NOT NULL DEFAULT 50
|
|
38
|
+
CHECK (message_limit >= 1),
|
|
39
|
+
|
|
40
|
+
timeout_seconds DOUBLE PRECISION NOT NULL
|
|
41
|
+
CHECK (timeout_seconds > 0),
|
|
42
|
+
|
|
43
|
+
-- Default spacing for reconciliation polls + Continuum heartbeats while idle / no quiet window.
|
|
44
|
+
poll_interval_seconds DOUBLE PRECISION NOT NULL
|
|
45
|
+
CHECK (poll_interval_seconds > 0),
|
|
46
|
+
|
|
47
|
+
-- After the latest merged message, wait this long before completing (chatbot debounce).
|
|
48
|
+
quiet_period_seconds DOUBLE PRECISION NOT NULL DEFAULT 0
|
|
49
|
+
CHECK (quiet_period_seconds >= 0),
|
|
50
|
+
|
|
51
|
+
deadline_at TIMESTAMPTZ NOT NULL,
|
|
52
|
+
|
|
53
|
+
-- When the worker should claim this row again (history fetch, heartbeat, timeout check).
|
|
54
|
+
next_poll_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
|
55
|
+
|
|
56
|
+
messages_json JSONB NOT NULL DEFAULT '[]'::jsonb,
|
|
57
|
+
|
|
58
|
+
last_message_snowflake BIGINT,
|
|
59
|
+
last_message_at TIMESTAMPTZ,
|
|
60
|
+
|
|
61
|
+
status TEXT NOT NULL DEFAULT 'active'
|
|
62
|
+
CHECK (status IN ('active', 'completed', 'failed')),
|
|
63
|
+
|
|
64
|
+
completed_at TIMESTAMPTZ,
|
|
65
|
+
error_json JSONB
|
|
66
|
+
);
|
|
67
|
+
|
|
68
|
+
COMMENT ON TABLE message_awaits IS
|
|
69
|
+
'In-flight Discord message awaits for Continuum queue items; workers claim rows when next_poll_at <= now().';
|
|
70
|
+
|
|
71
|
+
COMMENT ON COLUMN message_awaits.queue_item_id IS 'Continuum QueueItem.id; unique so registration is idempotent.';
|
|
72
|
+
COMMENT ON COLUMN message_awaits.next_poll_at IS 'Claim when <= now(); claim query advances by poll_interval_seconds.';
|
|
73
|
+
COMMENT ON COLUMN message_awaits.messages_json IS 'Accumulated messages [{id, content, author_id, channel_id, created_at}, ...].';
|
|
74
|
+
COMMENT ON COLUMN message_awaits.ignore_message_ids IS 'JSON array of message snowflake ids to ignore (max 10); e.g. agent replies already sent.';
|
|
75
|
+
COMMENT ON COLUMN message_awaits.ignore_own_bot_messages IS 'If true, exclude messages whose author is the logged-in bot user.';
|
|
76
|
+
|
|
77
|
+
-- Poller: next due row among actives
|
|
78
|
+
CREATE INDEX message_awaits_active_next_poll_idx
|
|
79
|
+
ON message_awaits (next_poll_at ASC)
|
|
80
|
+
WHERE status = 'active';
|
|
81
|
+
|
|
82
|
+
-- on_message routing: awaits on a guild text channel (no thread filter)
|
|
83
|
+
CREATE INDEX message_awaits_active_channel_idx
|
|
84
|
+
ON message_awaits (channel_id)
|
|
85
|
+
WHERE status = 'active' AND thread_id IS NULL;
|
|
86
|
+
|
|
87
|
+
-- on_message routing: awaits on a thread (message.channel.id is the thread snowflake)
|
|
88
|
+
CREATE INDEX message_awaits_active_thread_idx
|
|
89
|
+
ON message_awaits (thread_id)
|
|
90
|
+
WHERE status = 'active' AND thread_id IS NOT NULL;
|
|
91
|
+
|
|
92
|
+
-- Stable refs for Discord attachments (optional S3 archival via resolve_attachment_to_s3).
|
|
93
|
+
CREATE TABLE discord_attachment_registry (
|
|
94
|
+
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
95
|
+
channel_id BIGINT NOT NULL,
|
|
96
|
+
message_id BIGINT NOT NULL,
|
|
97
|
+
discord_attachment_id BIGINT NOT NULL,
|
|
98
|
+
filename TEXT NOT NULL DEFAULT '',
|
|
99
|
+
size BIGINT NOT NULL DEFAULT 0,
|
|
100
|
+
content_type TEXT,
|
|
101
|
+
ephemeral BOOLEAN NOT NULL DEFAULT false,
|
|
102
|
+
s3_bucket TEXT,
|
|
103
|
+
s3_key TEXT,
|
|
104
|
+
s3_uri TEXT,
|
|
105
|
+
archived_at TIMESTAMPTZ,
|
|
106
|
+
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
|
107
|
+
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
|
108
|
+
UNIQUE (channel_id, message_id, discord_attachment_id)
|
|
109
|
+
);
|
|
110
|
+
|
|
111
|
+
COMMENT ON TABLE discord_attachment_registry IS
|
|
112
|
+
'Maps Discord (channel_id, message_id, attachment_id) to attachment_ref (id); optional S3 fields after resolve_attachment_to_s3.';
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
-- reaction_awaits: durable state for Continuum queue items waiting on Discord reactions.
|
|
2
|
+
--
|
|
3
|
+
-- Apply (additive): psql "$DATABASE_URL" -v ON_ERROR_STOP=1 -f db/002_reaction_awaits.sql
|
|
4
|
+
--
|
|
5
|
+
-- Requires PostgreSQL 13+ (gen_random_uuid() without extensions).
|
|
6
|
+
|
|
7
|
+
CREATE TABLE IF NOT EXISTS reaction_awaits (
|
|
8
|
+
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
9
|
+
|
|
10
|
+
queue_item_id UUID NOT NULL UNIQUE,
|
|
11
|
+
|
|
12
|
+
channel_id BIGINT NOT NULL,
|
|
13
|
+
thread_id BIGINT,
|
|
14
|
+
|
|
15
|
+
prompt_message_id BIGINT NOT NULL,
|
|
16
|
+
prompt_content TEXT NOT NULL,
|
|
17
|
+
|
|
18
|
+
allowed_emojis JSONB NOT NULL
|
|
19
|
+
CHECK (
|
|
20
|
+
jsonb_typeof(allowed_emojis) = 'array'
|
|
21
|
+
AND jsonb_array_length(allowed_emojis) >= 1
|
|
22
|
+
AND jsonb_array_length(allowed_emojis) <= 20
|
|
23
|
+
),
|
|
24
|
+
|
|
25
|
+
filter_user_id BIGINT,
|
|
26
|
+
filter_role_id BIGINT,
|
|
27
|
+
|
|
28
|
+
registered_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
|
29
|
+
|
|
30
|
+
timeout_seconds DOUBLE PRECISION NOT NULL
|
|
31
|
+
CHECK (timeout_seconds > 0),
|
|
32
|
+
|
|
33
|
+
poll_interval_seconds DOUBLE PRECISION NOT NULL DEFAULT 60
|
|
34
|
+
CHECK (poll_interval_seconds > 0),
|
|
35
|
+
|
|
36
|
+
deadline_at TIMESTAMPTZ NOT NULL,
|
|
37
|
+
next_poll_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
|
38
|
+
|
|
39
|
+
status TEXT NOT NULL DEFAULT 'active'
|
|
40
|
+
CHECK (status IN ('active', 'completed', 'failed')),
|
|
41
|
+
|
|
42
|
+
completed_at TIMESTAMPTZ,
|
|
43
|
+
selected_reaction TEXT,
|
|
44
|
+
selected_user_id BIGINT,
|
|
45
|
+
error_json JSONB
|
|
46
|
+
);
|
|
47
|
+
|
|
48
|
+
COMMENT ON TABLE reaction_awaits IS
|
|
49
|
+
'In-flight Discord reaction awaits for Continuum ask tasks; workers claim rows when next_poll_at <= now().';
|
|
50
|
+
|
|
51
|
+
COMMENT ON COLUMN reaction_awaits.queue_item_id IS 'Continuum QueueItem.id; unique so registration is idempotent.';
|
|
52
|
+
COMMENT ON COLUMN reaction_awaits.allowed_emojis IS 'Canonical emoji strings the bot added as reactions (max 20).';
|
|
53
|
+
COMMENT ON COLUMN reaction_awaits.next_poll_at IS 'Claim when <= now(); claim query advances by poll_interval_seconds.';
|
|
54
|
+
|
|
55
|
+
CREATE INDEX IF NOT EXISTS reaction_awaits_active_next_poll_idx
|
|
56
|
+
ON reaction_awaits (next_poll_at ASC)
|
|
57
|
+
WHERE status = 'active';
|
|
58
|
+
|
|
59
|
+
CREATE INDEX IF NOT EXISTS reaction_awaits_active_prompt_message_idx
|
|
60
|
+
ON reaction_awaits (prompt_message_id)
|
|
61
|
+
WHERE status = 'active';
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
"""Transactional completion for github_awaits.
|
|
2
|
+
|
|
3
|
+
Each call takes one Postgres transaction: ``SELECT ... FOR UPDATE`` on the row
|
|
4
|
+
(only ``status = 'active'``), evaluate in memory, then a single conditional
|
|
5
|
+
``UPDATE``. Continuum complete/fail runs after the transaction commits.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import logging
|
|
11
|
+
from datetime import datetime, timedelta
|
|
12
|
+
from typing import Any
|
|
13
|
+
from uuid import UUID
|
|
14
|
+
|
|
15
|
+
from continuum_task_server import TaskServer
|
|
16
|
+
from continuum_task_server.exceptions import ContinuumError
|
|
17
|
+
from psycopg.types.json import Json
|
|
18
|
+
|
|
19
|
+
import continuum_task_server_bundle.github.awaits.db as db
|
|
20
|
+
from continuum_task_server_bundle.github.awaits.evaluators import evaluate
|
|
21
|
+
|
|
22
|
+
logger = logging.getLogger(__name__)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def apply_github_await(
|
|
26
|
+
server: TaskServer,
|
|
27
|
+
row_id: UUID,
|
|
28
|
+
fetched: dict[str, Any],
|
|
29
|
+
etags: dict[str, str] | None = None,
|
|
30
|
+
*,
|
|
31
|
+
now: datetime | None = None,
|
|
32
|
+
) -> None:
|
|
33
|
+
now = now or db.utcnow()
|
|
34
|
+
completed_qid: UUID | None = None
|
|
35
|
+
completion_payload: dict[str, Any] | None = None
|
|
36
|
+
|
|
37
|
+
with db.connect() as conn:
|
|
38
|
+
with conn.transaction():
|
|
39
|
+
with conn.cursor() as cur:
|
|
40
|
+
cur.execute(
|
|
41
|
+
"""
|
|
42
|
+
SELECT * FROM github_awaits
|
|
43
|
+
WHERE id = %s AND status = 'active'
|
|
44
|
+
FOR UPDATE
|
|
45
|
+
""",
|
|
46
|
+
(str(row_id),),
|
|
47
|
+
)
|
|
48
|
+
row = cur.fetchone()
|
|
49
|
+
if not row:
|
|
50
|
+
return
|
|
51
|
+
|
|
52
|
+
result = evaluate(row, fetched, now=now)
|
|
53
|
+
if result.complete:
|
|
54
|
+
cur.execute(
|
|
55
|
+
"""
|
|
56
|
+
UPDATE github_awaits
|
|
57
|
+
SET status = 'completed',
|
|
58
|
+
completed_at = now(),
|
|
59
|
+
state_json = %s
|
|
60
|
+
WHERE id = %s AND status = 'active'
|
|
61
|
+
RETURNING queue_item_id
|
|
62
|
+
""",
|
|
63
|
+
(Json(result.state), str(row_id)),
|
|
64
|
+
)
|
|
65
|
+
done = cur.fetchone()
|
|
66
|
+
if done:
|
|
67
|
+
completed_qid = UUID(str(done["queue_item_id"]))
|
|
68
|
+
completion_payload = result.output
|
|
69
|
+
else:
|
|
70
|
+
poll_seconds = result.next_poll_seconds
|
|
71
|
+
if poll_seconds is None:
|
|
72
|
+
poll_seconds = float(row["poll_interval_seconds"])
|
|
73
|
+
next_poll_at = now + timedelta(seconds=max(0.0, float(poll_seconds)))
|
|
74
|
+
merged_etags = dict(row.get("etags_json") or {})
|
|
75
|
+
if etags:
|
|
76
|
+
merged_etags.update({key: value for key, value in etags.items() if value})
|
|
77
|
+
cur.execute(
|
|
78
|
+
"""
|
|
79
|
+
UPDATE github_awaits
|
|
80
|
+
SET state_json = %s,
|
|
81
|
+
etags_json = %s,
|
|
82
|
+
next_poll_at = %s
|
|
83
|
+
WHERE id = %s AND status = 'active'
|
|
84
|
+
""",
|
|
85
|
+
(Json(result.state), Json(merged_etags), next_poll_at, str(row_id)),
|
|
86
|
+
)
|
|
87
|
+
|
|
88
|
+
if completed_qid is not None and completion_payload is not None:
|
|
89
|
+
try:
|
|
90
|
+
server.complete_queue_item(completed_qid, output_data=completion_payload)
|
|
91
|
+
except ContinuumError as exc:
|
|
92
|
+
logger.error("complete_queue_item failed for %s: %s", completed_qid, exc)
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
"""Drop github_awaits rows when a Continuum queue item is no longer ours."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import logging
|
|
6
|
+
from typing import Any
|
|
7
|
+
from uuid import UUID
|
|
8
|
+
|
|
9
|
+
from continuum_task_server import TaskServer, TaskStatus
|
|
10
|
+
from continuum_task_server.exceptions import (
|
|
11
|
+
ContinuumError,
|
|
12
|
+
ForbiddenError,
|
|
13
|
+
NotFoundError,
|
|
14
|
+
RateLimitError,
|
|
15
|
+
ServerError,
|
|
16
|
+
TransportError,
|
|
17
|
+
UnauthorizedError,
|
|
18
|
+
)
|
|
19
|
+
from continuum_task_server.models import QueueItem
|
|
20
|
+
|
|
21
|
+
import continuum_task_server_bundle.github.awaits.db as db
|
|
22
|
+
logger = logging.getLogger(__name__)
|
|
23
|
+
|
|
24
|
+
_TRANSIENT = (UnauthorizedError, ForbiddenError, RateLimitError, ServerError, TransportError)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def drop_await_rows(queue_item_id: UUID) -> None:
|
|
28
|
+
"""Delete the github_awaits row for this queue item."""
|
|
29
|
+
if not db.database_url():
|
|
30
|
+
return
|
|
31
|
+
try:
|
|
32
|
+
deleted = db.delete_by_queue_item_id(queue_item_id)
|
|
33
|
+
except Exception:
|
|
34
|
+
logger.exception("delete github_awaits failed for %s", queue_item_id)
|
|
35
|
+
return
|
|
36
|
+
if deleted:
|
|
37
|
+
logger.info("dropped github await for %s", queue_item_id)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def heartbeat_claim_or_drop(server: TaskServer, queue_item_id: UUID) -> bool:
|
|
41
|
+
"""Heartbeat the item. Drop the await unless it is still STARTED with no control.
|
|
42
|
+
|
|
43
|
+
Returns True if GitHub polling should continue for this row.
|
|
44
|
+
"""
|
|
45
|
+
claim = _active_claim(server, queue_item_id)
|
|
46
|
+
token = None if claim is None else getattr(claim, "claim_token", None)
|
|
47
|
+
latest: QueueItem | None = None
|
|
48
|
+
try:
|
|
49
|
+
latest = server.client.queue.heartbeat(queue_item_id, claim_token=token)
|
|
50
|
+
except ContinuumError as exc:
|
|
51
|
+
if isinstance(exc, _TRANSIENT):
|
|
52
|
+
logger.warning("heartbeat failed for %s: %s", queue_item_id, exc)
|
|
53
|
+
return True
|
|
54
|
+
logger.info("heartbeat failed for %s: %s", queue_item_id, exc)
|
|
55
|
+
try:
|
|
56
|
+
latest = server.client.queue.get_by_id(queue_item_id)
|
|
57
|
+
except NotFoundError:
|
|
58
|
+
_drop_and_release(queue_item_id, claim, reason="not found")
|
|
59
|
+
return False
|
|
60
|
+
except ContinuumError as exc2:
|
|
61
|
+
logger.warning("get_by_id failed for %s: %s", queue_item_id, exc2)
|
|
62
|
+
return True
|
|
63
|
+
|
|
64
|
+
if latest is None:
|
|
65
|
+
_drop_and_release(queue_item_id, claim, reason="empty heartbeat")
|
|
66
|
+
return False
|
|
67
|
+
|
|
68
|
+
control = latest.control_request
|
|
69
|
+
if latest.task_status is not TaskStatus.STARTED or (control is not None and control != ""):
|
|
70
|
+
_drop_and_release(
|
|
71
|
+
queue_item_id,
|
|
72
|
+
claim,
|
|
73
|
+
reason=f"status={latest.task_status} control={control!r}",
|
|
74
|
+
)
|
|
75
|
+
return False
|
|
76
|
+
return True
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _drop_and_release(queue_item_id: UUID, claim: Any, *, reason: str) -> None:
|
|
80
|
+
logger.info("queue item %s not runnable (%s); dropping await row", queue_item_id, reason)
|
|
81
|
+
drop_await_rows(queue_item_id)
|
|
82
|
+
completed = getattr(claim, "completed", None)
|
|
83
|
+
if claim is None or (completed is not None and completed.is_set()):
|
|
84
|
+
return
|
|
85
|
+
signal = getattr(claim, "signal_control", None)
|
|
86
|
+
if callable(signal):
|
|
87
|
+
signal()
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _active_claim(server: TaskServer, queue_item_id: UUID) -> Any:
|
|
91
|
+
active = getattr(server, "_active", None)
|
|
92
|
+
if not isinstance(active, dict):
|
|
93
|
+
return None
|
|
94
|
+
return active.get(queue_item_id)
|