@fungi.computer/oyster 0.22.0 → 0.24.0

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,207 @@
1
+ import { z } from "zod";
2
+ /**
3
+ * The Discord replies an Agent still owes. An interaction token is valid for
4
+ * about 15 minutes: until then the answer fills the original message. A run
5
+ * that needs longer says it is still working before the token lapses, and its
6
+ * answer then arrives as a normal channel message. One row per interaction
7
+ * keeps the debt in the Agent's own store, so an evicted run still answers
8
+ * after the Agent wakes. A row names no secret once it is closed, and a closed
9
+ * row says honestly why: `expired` (no answer within two hours) or `failed`
10
+ * (delivery kept failing).
11
+ */
12
+ /** The interaction token window we honour, a little under Discord's 15 minutes. */
13
+ const DISCORD_REPLY_WINDOW_MS = 14 * 60_000;
14
+ /** When a run still going tells the member so, safely inside the token window. */
15
+ const STILL_WORKING_AFTER_MS = 12 * 60_000;
16
+ /** How long an answer may take before the reply is given up as expired. */
17
+ const CHANNEL_WINDOW_MS = 2 * 3_600_000;
18
+ /** How soon a run past the token window is looked at again. */
19
+ const SLOW_POLL_MS = 10_000;
20
+ /** How long a closed row stays readable before it is pruned. */
21
+ const CLOSED_RETENTION_MS = 7 * 86_400_000;
22
+ /** Delivery attempts after which a reply is given up as failed. */
23
+ const MAX_DELIVERY_ATTEMPTS = 5;
24
+ /** Rows one pass works on, so a pass stays bounded. */
25
+ const PASS_LIMIT = 4;
26
+ /** How soon an unsettled run is looked at again. */
27
+ const POLL_MS = 1_000;
28
+ const pendingRow = z.strictObject({
29
+ interaction_id: z.string(),
30
+ binding_id: z.string(),
31
+ application_id: z.string(),
32
+ token: z.string(),
33
+ guild_id: z.string(),
34
+ channel_id: z.string(),
35
+ user_id: z.string(),
36
+ text: z.string(),
37
+ echo: z.string().nullable(),
38
+ display_name: z.string().nullable(),
39
+ session_id: z.string().nullable(),
40
+ command_id: z.string().nullable(),
41
+ attempts: z.number().int().nonnegative(),
42
+ delivered_parts: z.number().int().nonnegative(),
43
+ still_working: z.union([z.literal(0), z.literal(1)]),
44
+ created_at: z.number().int(),
45
+ expires_at: z.number().int(),
46
+ });
47
+ const closedRow = z.strictObject({
48
+ interaction_id: z.string(),
49
+ display_name: z.string().nullable(),
50
+ state: z.enum(["expired", "failed"]),
51
+ closed_at: z.number().int(),
52
+ });
53
+ const dueRow = z.strictObject({ due: z.number().int().nullable() });
54
+ /** The pending-reply store and the host work that pays it off. */
55
+ export function createDiscordReplies(options) {
56
+ const { sql } = options;
57
+ const ensure = () => {
58
+ sql.exec(`CREATE TABLE IF NOT EXISTS oyster_discord_replies (
59
+ interaction_id TEXT PRIMARY KEY,
60
+ binding_id TEXT NOT NULL,
61
+ application_id TEXT NOT NULL,
62
+ token TEXT NOT NULL,
63
+ guild_id TEXT NOT NULL,
64
+ channel_id TEXT NOT NULL,
65
+ user_id TEXT NOT NULL,
66
+ text TEXT NOT NULL,
67
+ echo TEXT,
68
+ display_name TEXT,
69
+ delivered_parts INTEGER NOT NULL DEFAULT 0,
70
+ still_working INTEGER NOT NULL DEFAULT 0,
71
+ session_id TEXT,
72
+ command_id TEXT,
73
+ state TEXT NOT NULL CHECK (state IN ('waiting','expired','failed')),
74
+ attempts INTEGER NOT NULL,
75
+ created_at INTEGER NOT NULL,
76
+ expires_at INTEGER NOT NULL,
77
+ next_at INTEGER NOT NULL,
78
+ closed_at INTEGER
79
+ ) STRICT`);
80
+ };
81
+ const close = (interactionId, state) => {
82
+ sql.exec("UPDATE oyster_discord_replies SET state=?, token='', text='', echo=NULL, closed_at=? WHERE interaction_id=?", state, options.now(), interactionId);
83
+ };
84
+ const reschedule = (interactionId, at, attempts) => {
85
+ sql.exec("UPDATE oyster_discord_replies SET next_at=?, attempts=? WHERE interaction_id=?", at, attempts, interactionId);
86
+ };
87
+ let active;
88
+ const pass = async () => {
89
+ ensure();
90
+ const now = options.now();
91
+ sql.exec("DELETE FROM oyster_discord_replies WHERE state!='waiting' AND closed_at<?", now - CLOSED_RETENTION_MS);
92
+ const rows = sql
93
+ .exec("SELECT interaction_id,binding_id,application_id,token,guild_id,channel_id,user_id,text,echo,display_name,session_id,command_id,attempts,delivered_parts,still_working,created_at,expires_at FROM oyster_discord_replies WHERE state='waiting' AND next_at<=? ORDER BY next_at LIMIT ?", now, PASS_LIMIT)
94
+ .toArray()
95
+ .map((raw) => pendingRow.parse(raw));
96
+ for (const row of rows) {
97
+ const at = options.now();
98
+ if (at >= row.created_at + CHANNEL_WINDOW_MS) {
99
+ close(row.interaction_id, "expired");
100
+ options.onExpired(row.interaction_id);
101
+ continue;
102
+ }
103
+ const tokenLive = at < row.expires_at;
104
+ const delivery = await options.deliver({
105
+ interactionId: row.interaction_id,
106
+ bindingId: row.binding_id,
107
+ ask: {
108
+ interactionId: row.interaction_id,
109
+ applicationId: row.application_id,
110
+ interactionToken: row.token,
111
+ guildId: row.guild_id,
112
+ channelId: row.channel_id,
113
+ userId: row.user_id,
114
+ text: row.text,
115
+ echo: row.echo ?? undefined,
116
+ displayName: row.display_name ?? undefined,
117
+ },
118
+ accepted: row.session_id !== null && row.command_id !== null
119
+ ? { sessionId: row.session_id, commandId: row.command_id }
120
+ : null,
121
+ attempts: row.attempts,
122
+ deliveredParts: row.delivered_parts,
123
+ tokenLive,
124
+ stillWorkingDue: tokenLive &&
125
+ row.still_working === 0 &&
126
+ at >= row.created_at + STILL_WORKING_AFTER_MS,
127
+ });
128
+ switch (delivery) {
129
+ case "delivered":
130
+ sql.exec("DELETE FROM oyster_discord_replies WHERE interaction_id=?", row.interaction_id);
131
+ break;
132
+ case "waiting":
133
+ reschedule(row.interaction_id, options.now() + (tokenLive ? POLL_MS : SLOW_POLL_MS), row.attempts);
134
+ break;
135
+ case "gone":
136
+ close(row.interaction_id, "expired");
137
+ options.onExpired(row.interaction_id);
138
+ break;
139
+ case "retry":
140
+ if (row.attempts + 1 >= MAX_DELIVERY_ATTEMPTS)
141
+ close(row.interaction_id, "failed");
142
+ else
143
+ reschedule(row.interaction_id, options.now() + 1_000 * 2 ** (row.attempts + 1), row.attempts + 1);
144
+ break;
145
+ }
146
+ }
147
+ };
148
+ return {
149
+ /** Owe one reply. A second record of the same interaction is the first. */
150
+ record: (bindingId, ask) => {
151
+ ensure();
152
+ const now = options.now();
153
+ sql.exec("INSERT OR IGNORE INTO oyster_discord_replies (interaction_id,binding_id,application_id,token,guild_id,channel_id,user_id,text,echo,display_name,state,attempts,created_at,expires_at,next_at) VALUES (?,?,?,?,?,?,?,?,?,?,'waiting',0,?,?,?)", ask.interactionId, bindingId, ask.applicationId, ask.interactionToken, ask.guildId, ask.channelId, ask.userId, ask.text, ask.echo ?? null, ask.displayName ?? null, now, now + DISCORD_REPLY_WINDOW_MS, now);
154
+ },
155
+ /** The member has been told the run is still going. */
156
+ markStillWorking: (interactionId) => {
157
+ sql.exec("UPDATE oyster_discord_replies SET still_working=1 WHERE interaction_id=?", interactionId);
158
+ },
159
+ /** Discord no longer knows the token: only the channel reaches the member now. */
160
+ tokenGone: (interactionId) => {
161
+ sql.exec("UPDATE oyster_discord_replies SET expires_at=? WHERE interaction_id=?", options.now(), interactionId);
162
+ },
163
+ /** Remember how many messages of the answer Discord has. */
164
+ progress: (interactionId, parts) => {
165
+ sql.exec("UPDATE oyster_discord_replies SET delivered_parts=? WHERE interaction_id=?", parts, interactionId);
166
+ },
167
+ /** Replies of one binding that never reached Discord, newest first. */
168
+ closed: (bindingId) => {
169
+ ensure();
170
+ return sql
171
+ .exec("SELECT interaction_id,display_name,state,closed_at FROM oyster_discord_replies WHERE binding_id=? AND state!='waiting' ORDER BY closed_at DESC LIMIT 50", bindingId)
172
+ .toArray()
173
+ .map((raw) => {
174
+ const row = closedRow.parse(raw);
175
+ return {
176
+ interactionId: row.interaction_id,
177
+ label: row.display_name ?? "Discord member",
178
+ state: row.state,
179
+ closedAt: row.closed_at,
180
+ };
181
+ });
182
+ },
183
+ /** Remember which command answers this interaction. */
184
+ attach: (interactionId, accepted) => {
185
+ sql.exec("UPDATE oyster_discord_replies SET session_id=?, command_id=? WHERE interaction_id=?", accepted.sessionId, accepted.commandId, interactionId);
186
+ },
187
+ /** Host work on the Agent's one durable wake. */
188
+ work: {
189
+ pending: () => {
190
+ ensure();
191
+ const row = dueRow.parse(sql
192
+ .exec("SELECT MIN(next_at) AS due FROM oyster_discord_replies WHERE state='waiting'")
193
+ .toArray()[0]);
194
+ return {
195
+ due: row.due !== null && row.due <= options.now(),
196
+ nextWakeAt: row.due,
197
+ };
198
+ },
199
+ run: () => {
200
+ // Passes never overlap, so one reply is never delivered twice at once.
201
+ const next = (active ?? Promise.resolve()).then(pass, pass);
202
+ active = next;
203
+ return next;
204
+ },
205
+ },
206
+ };
207
+ }