@fungi.computer/oyster 0.22.0 → 0.23.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.
@@ -50,6 +50,7 @@ export declare const channelPartySchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
50
50
  kind: z.ZodLiteral<"discord-user">;
51
51
  guildId: z.ZodString;
52
52
  userId: z.ZodString;
53
+ displayName: z.ZodOptional<z.ZodString>;
53
54
  }, z.core.$strict>, z.ZodObject<{
54
55
  kind: z.ZodLiteral<"email-sender">;
55
56
  address: z.ZodEmail;
@@ -61,6 +61,8 @@ export const channelPartySchema = z.discriminatedUnion("kind", [
61
61
  kind: z.literal("discord-user"),
62
62
  guildId: discordSnowflakeSchema,
63
63
  userId: discordSnowflakeSchema,
64
+ /** What the member goes by in Discord, as of their latest message. */
65
+ displayName: z.string().min(1).max(80).optional(),
64
66
  }),
65
67
  z.strictObject({
66
68
  kind: z.literal("email-sender"),
@@ -84,7 +86,7 @@ export function partyLabel(party) {
84
86
  case "visitor":
85
87
  return `Visitor ${party.visitorId.slice(-4)}`;
86
88
  case "discord-user":
87
- return `Discord user ${party.userId}`;
89
+ return party.displayName ?? "Discord member";
88
90
  case "email-sender":
89
91
  return party.dmarc === "pass"
90
92
  ? party.address
@@ -45,6 +45,7 @@ declare const inboundEventSchema: z.ZodObject<{
45
45
  kind: z.ZodLiteral<"discord-user">;
46
46
  guildId: z.ZodString;
47
47
  userId: z.ZodString;
48
+ displayName: z.ZodOptional<z.ZodString>;
48
49
  }, z.core.$strict>, z.ZodObject<{
49
50
  kind: z.ZodLiteral<"email-sender">;
50
51
  address: z.ZodEmail;
@@ -232,13 +232,27 @@ export function createChannelConversations(options) {
232
232
  .toArray()
233
233
  .map((raw) => sessionIdRow.parse(raw).session_id);
234
234
  };
235
+ /** A Discord member's name may change; each message carries the latest. */
236
+ const refreshName = (existing, party) => {
237
+ if (existing.party.kind !== "discord-user" ||
238
+ party.kind !== "discord-user" ||
239
+ party.displayName === undefined ||
240
+ party.displayName === existing.party.displayName)
241
+ return existing;
242
+ const renamed = { ...existing.party, displayName: party.displayName };
243
+ sql.exec("UPDATE hub_channel_conversations SET party_json=? WHERE session_id=?", JSON.stringify(renamed), existing.sessionId);
244
+ return { ...existing, party: renamed, label: partyLabel(renamed) };
245
+ };
235
246
  /** Open (or find) the conversation Session without submitting work. */
236
247
  const open = async (binding, conversation, party) => {
237
248
  if (isBanned(binding.bindingId, conversation))
238
249
  return { kind: "denied", reason: "banned" };
239
250
  const existing = findConversation(binding.bindingId, conversation);
240
251
  if (existing !== null)
241
- return { kind: "open", conversation: existing };
252
+ return {
253
+ kind: "open",
254
+ conversation: refreshName(existing, party),
255
+ };
242
256
  const limits = limitsOf(binding);
243
257
  const now = options.now();
244
258
  if (count("SELECT COUNT(*) AS count FROM hub_channel_conversations WHERE binding_id=? AND created_at>?", binding.bindingId, now - HOUR_MS) >= limits.newPartiesPerHour)
@@ -16,10 +16,8 @@ export declare const REPLY_ID = "reply";
16
16
  export declare const REPLY_TEXT_ID = "text";
17
17
  /** The longest question or reply Discord lets a member type here. */
18
18
  export declare const DISCORD_ASK_LIMIT = 1000;
19
- /** How long an Agent has to answer before the interaction token lapses. */
20
- export declare const DISCORD_ANSWER_WINDOW_MS: number;
21
19
  /** One settlement read waits at most this long (Shiitake allows 30 s). */
22
- export declare const DISCORD_SETTLEMENT_POLL_MS = 25000;
20
+ export declare const DISCORD_SETTLEMENT_WAIT_MS = 8000;
23
21
  /** One verified question, as the public edge hands it to the Agent. */
24
22
  export type DiscordAsk = Readonly<{
25
23
  interactionId: string;
@@ -30,9 +28,19 @@ export type DiscordAsk = Readonly<{
30
28
  channelId: string;
31
29
  userId: string;
32
30
  text: string;
31
+ /** What the member goes by, if Discord said; never their id. */
32
+ displayName?: string | undefined;
33
33
  /** The member's own words, quoted above the answer of a modal reply. */
34
34
  echo?: string | undefined;
35
35
  }>;
36
+ /**
37
+ * What a member goes by: their nickname in the server, else their display
38
+ * name, else `@username`. Absent when Discord sent none of them.
39
+ */
40
+ export declare function discordDisplayName(who: Readonly<{
41
+ member?: z.infer<typeof memberSchema> | undefined;
42
+ user?: z.infer<typeof userSchema> | undefined;
43
+ }>): string | undefined;
36
44
  /** What a member is told when intake says no. */
37
45
  export declare const discordDenial: {
38
46
  readonly unmapped: "This Agent is not available right now.";
@@ -44,6 +52,19 @@ export declare const discordDenial: {
44
52
  readonly rate_limited: "This Agent is busy right now. Try again soon.";
45
53
  readonly event_conflict: "That message could not be accepted.";
46
54
  };
55
+ declare const userSchema: z.ZodObject<{
56
+ id: z.ZodString;
57
+ username: z.ZodOptional<z.ZodNullable<z.ZodString>>;
58
+ global_name: z.ZodOptional<z.ZodNullable<z.ZodString>>;
59
+ }, z.core.$strip>;
60
+ declare const memberSchema: z.ZodObject<{
61
+ user: z.ZodObject<{
62
+ id: z.ZodString;
63
+ username: z.ZodOptional<z.ZodNullable<z.ZodString>>;
64
+ global_name: z.ZodOptional<z.ZodNullable<z.ZodString>>;
65
+ }, z.core.$strip>;
66
+ nick: z.ZodOptional<z.ZodNullable<z.ZodString>>;
67
+ }, z.core.$strip>;
47
68
  /** The interaction types we answer; any other type fails to decode. */
48
69
  export declare const interactionSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
49
70
  type: z.ZodLiteral<1>;
@@ -66,10 +87,15 @@ export declare const interactionSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
66
87
  member: z.ZodOptional<z.ZodObject<{
67
88
  user: z.ZodObject<{
68
89
  id: z.ZodString;
90
+ username: z.ZodOptional<z.ZodNullable<z.ZodString>>;
91
+ global_name: z.ZodOptional<z.ZodNullable<z.ZodString>>;
69
92
  }, z.core.$strip>;
93
+ nick: z.ZodOptional<z.ZodNullable<z.ZodString>>;
70
94
  }, z.core.$strip>>;
71
95
  user: z.ZodOptional<z.ZodObject<{
72
96
  id: z.ZodString;
97
+ username: z.ZodOptional<z.ZodNullable<z.ZodString>>;
98
+ global_name: z.ZodOptional<z.ZodNullable<z.ZodString>>;
73
99
  }, z.core.$strip>>;
74
100
  }, z.core.$strip>, z.ZodObject<{
75
101
  type: z.ZodLiteral<3>;
@@ -84,10 +110,15 @@ export declare const interactionSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
84
110
  member: z.ZodOptional<z.ZodObject<{
85
111
  user: z.ZodObject<{
86
112
  id: z.ZodString;
113
+ username: z.ZodOptional<z.ZodNullable<z.ZodString>>;
114
+ global_name: z.ZodOptional<z.ZodNullable<z.ZodString>>;
87
115
  }, z.core.$strip>;
116
+ nick: z.ZodOptional<z.ZodNullable<z.ZodString>>;
88
117
  }, z.core.$strip>>;
89
118
  user: z.ZodOptional<z.ZodObject<{
90
119
  id: z.ZodString;
120
+ username: z.ZodOptional<z.ZodNullable<z.ZodString>>;
121
+ global_name: z.ZodOptional<z.ZodNullable<z.ZodString>>;
91
122
  }, z.core.$strip>>;
92
123
  }, z.core.$strip>, z.ZodObject<{
93
124
  type: z.ZodLiteral<5>;
@@ -108,10 +139,15 @@ export declare const interactionSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
108
139
  member: z.ZodOptional<z.ZodObject<{
109
140
  user: z.ZodObject<{
110
141
  id: z.ZodString;
142
+ username: z.ZodOptional<z.ZodNullable<z.ZodString>>;
143
+ global_name: z.ZodOptional<z.ZodNullable<z.ZodString>>;
111
144
  }, z.core.$strip>;
145
+ nick: z.ZodOptional<z.ZodNullable<z.ZodString>>;
112
146
  }, z.core.$strip>>;
113
147
  user: z.ZodOptional<z.ZodObject<{
114
148
  id: z.ZodString;
149
+ username: z.ZodOptional<z.ZodNullable<z.ZodString>>;
150
+ global_name: z.ZodOptional<z.ZodNullable<z.ZodString>>;
115
151
  }, z.core.$strip>>;
116
152
  }, z.core.$strip>], "type">;
117
153
  /** Why a request's signature was refused. */
@@ -167,6 +203,13 @@ export declare const replyModalResponse: {
167
203
  }];
168
204
  };
169
205
  };
206
+ /**
207
+ * Split an answer into messages Discord accepts, in order, losing nothing but
208
+ * the whitespace at each cut. A cut prefers a blank line, then a line, then a
209
+ * space, and only then falls inside a word. An answer past ten messages ends
210
+ * with a notice that the rest is cut.
211
+ */
212
+ export declare function splitDiscordMessage(text: string, limit?: number): readonly string[];
170
213
  /** Quote a member's modal reply so the thread reads in order. */
171
214
  export declare function quoted(text: string): string;
172
215
  /**
@@ -178,7 +221,26 @@ export declare function patchOriginal(send: typeof fetch, input: Readonly<{
178
221
  interactionToken: string;
179
222
  content: string;
180
223
  withReply: boolean;
181
- }>): Promise<boolean>;
224
+ }>): Promise<"delivered" | "gone" | "retry">;
225
+ /**
226
+ * Send one more message under the same interaction, after the original. The
227
+ * interaction token is the credential here too.
228
+ */
229
+ export declare function postFollowUp(send: typeof fetch, input: Readonly<{
230
+ applicationId: string;
231
+ interactionToken: string;
232
+ content: string;
233
+ withReply: boolean;
234
+ }>): Promise<"delivered" | "gone" | "retry">;
235
+ /**
236
+ * Tell the member why an answer did not come, in plain words and with what to
237
+ * do next. The host's own failure diagnostic names the cause; provider prose
238
+ * never reaches a member.
239
+ */
240
+ export declare function discordFailureText(terminal: Readonly<{
241
+ outcome: "completed" | "cancelled" | "failed" | "interrupted";
242
+ diagnostic: string | null;
243
+ }>): string;
182
244
  /**
183
245
  * Register `/ask` in one guild with the owner's bot token. Creating by name
184
246
  * updates an existing `/ask` and leaves the owner's other commands alone.
@@ -188,3 +250,4 @@ export declare function registerAskCommand(send: typeof fetch, input: Readonly<{
188
250
  guildId: string;
189
251
  botToken: string;
190
252
  }>): Promise<boolean>;
253
+ export {};
@@ -23,10 +23,20 @@ const DISCORD_MESSAGE_LIMIT = 2_000;
23
23
  export const DISCORD_ASK_LIMIT = 1_000;
24
24
  /** Discord API version the follow-up and registration calls pin. */
25
25
  const DISCORD_API = "https://discord.com/api/v10";
26
- /** How long an Agent has to answer before the interaction token lapses. */
27
- export const DISCORD_ANSWER_WINDOW_MS = 13 * 60_000;
28
26
  /** One settlement read waits at most this long (Shiitake allows 30 s). */
29
- export const DISCORD_SETTLEMENT_POLL_MS = 25_000;
27
+ export const DISCORD_SETTLEMENT_WAIT_MS = 8_000;
28
+ /**
29
+ * What a member goes by: their nickname in the server, else their display
30
+ * name, else `@username`. Absent when Discord sent none of them.
31
+ */
32
+ export function discordDisplayName(who) {
33
+ const user = who.member?.user ?? who.user;
34
+ const name = [who.member?.nick, user?.global_name]
35
+ .map((candidate) => candidate?.trim())
36
+ .find((candidate) => candidate !== undefined && candidate !== "") ??
37
+ (user?.username?.trim() ? `@${user.username.trim()}` : undefined);
38
+ return name?.slice(0, 80);
39
+ }
30
40
  /** What a member is told when intake says no. */
31
41
  export const discordDenial = {
32
42
  unmapped: "This Agent is not available right now.",
@@ -44,14 +54,23 @@ const optionSchema = z.object({
44
54
  name: z.string(),
45
55
  value: z.union([z.string(), z.number(), z.boolean()]).optional(),
46
56
  });
47
- const userSchema = z.object({ id: discordSnowflakeSchema });
57
+ const userSchema = z.object({
58
+ id: discordSnowflakeSchema,
59
+ username: z.string().nullish(),
60
+ global_name: z.string().nullish(),
61
+ });
62
+ const memberSchema = z.object({
63
+ user: userSchema,
64
+ /** The member's nickname in this server. */
65
+ nick: z.string().nullish(),
66
+ });
48
67
  const placeFields = {
49
68
  id: discordSnowflakeSchema,
50
69
  application_id: discordSnowflakeSchema,
51
70
  token: z.string().min(1).max(512),
52
71
  guild_id: discordSnowflakeSchema.optional(),
53
72
  channel_id: discordSnowflakeSchema.optional(),
54
- member: z.object({ user: userSchema }).optional(),
73
+ member: memberSchema.optional(),
55
74
  user: userSchema.optional(),
56
75
  };
57
76
  /** The interaction types we answer; any other type fails to decode. */
@@ -158,10 +177,42 @@ const replyRow = [
158
177
  components: [{ type: 2, style: 2, label: "Reply", custom_id: REPLY_ID }],
159
178
  },
160
179
  ];
161
- /** The body of a follow-up that fills the deferred message. */
180
+ /** Most messages one answer may fill; past it the last one says the rest is cut. */
181
+ const DISCORD_MAX_PARTS = 10;
182
+ const CONTINUES = "\n\n… (the rest of this answer is too long for Discord)";
183
+ /**
184
+ * Split an answer into messages Discord accepts, in order, losing nothing but
185
+ * the whitespace at each cut. A cut prefers a blank line, then a line, then a
186
+ * space, and only then falls inside a word. An answer past ten messages ends
187
+ * with a notice that the rest is cut.
188
+ */
189
+ export function splitDiscordMessage(text, limit = DISCORD_MESSAGE_LIMIT) {
190
+ const parts = [];
191
+ let rest = text.trim();
192
+ while (rest.length > limit) {
193
+ const room = parts.length === DISCORD_MAX_PARTS - 1 ? limit - CONTINUES.length : limit;
194
+ const window = rest.slice(0, room);
195
+ const floor = Math.floor(room * 0.5);
196
+ const cut = [
197
+ window.lastIndexOf("\n\n"),
198
+ window.lastIndexOf("\n"),
199
+ window.lastIndexOf(" "),
200
+ ].find((at) => at >= floor);
201
+ if (parts.length === DISCORD_MAX_PARTS - 1) {
202
+ parts.push(`${window.trimEnd()}${CONTINUES}`);
203
+ return parts;
204
+ }
205
+ const end = cut ?? room;
206
+ parts.push(rest.slice(0, end).trimEnd());
207
+ rest = rest.slice(end).trimStart();
208
+ }
209
+ parts.push(rest);
210
+ return parts;
211
+ }
212
+ /** The body of a follow-up message; its content is already within Discord's bound. */
162
213
  function followUpBody(content, withReply) {
163
214
  return {
164
- content: content.slice(0, DISCORD_MESSAGE_LIMIT),
215
+ content,
165
216
  // Model text never pings anyone.
166
217
  allowed_mentions: { parse: [] },
167
218
  components: withReply ? replyRow : [],
@@ -187,7 +238,56 @@ export async function patchOriginal(send, input) {
187
238
  signal: AbortSignal.timeout(15_000),
188
239
  });
189
240
  await response.body?.cancel();
190
- return response.ok;
241
+ // Discord answers 401, 403 or 404 for a token that lapsed or never was.
242
+ if (response.ok)
243
+ return "delivered";
244
+ return [401, 403, 404].includes(response.status) ? "gone" : "retry";
245
+ }
246
+ /**
247
+ * Send one more message under the same interaction, after the original. The
248
+ * interaction token is the credential here too.
249
+ */
250
+ export async function postFollowUp(send, input) {
251
+ const response = await send(`${DISCORD_API}/webhooks/${input.applicationId}/${input.interactionToken}`, {
252
+ method: "POST",
253
+ headers: { "content-type": "application/json" },
254
+ body: JSON.stringify(followUpBody(input.content, input.withReply)),
255
+ signal: AbortSignal.timeout(15_000),
256
+ });
257
+ await response.body?.cancel();
258
+ if (response.ok)
259
+ return "delivered";
260
+ return [401, 403, 404].includes(response.status) ? "gone" : "retry";
261
+ }
262
+ const failureCode = /^Model request failed \(([\w-]+)\)/u;
263
+ /**
264
+ * Tell the member why an answer did not come, in plain words and with what to
265
+ * do next. The host's own failure diagnostic names the cause; provider prose
266
+ * never reaches a member.
267
+ */
268
+ export function discordFailureText(terminal) {
269
+ if (terminal.outcome === "cancelled")
270
+ return "That run was cancelled.";
271
+ if (terminal.outcome === "interrupted")
272
+ return "The run was interrupted before it finished. Ask again.";
273
+ if (terminal.outcome === "completed")
274
+ return "The Agent finished without a reply. Try asking again.";
275
+ switch (failureCode.exec(terminal.diagnostic ?? "")?.[1]) {
276
+ case "setup_required":
277
+ return "No model is connected to this Agent yet. Ask its owner to connect one, then ask again.";
278
+ case "usage-limit-reached":
279
+ return "The model provider says its usage limit or credit is used up. Ask the owner to check the provider account, then try again.";
280
+ case "rate-limit":
281
+ case "overloaded":
282
+ case "provider_unavailable":
283
+ return "The model provider is busy or unavailable right now. Try again in a minute.";
284
+ case "provider_rejected":
285
+ return "The model provider refused the request. Ask the owner to check the model connection.";
286
+ case "tools_unsupported":
287
+ return "This Agent's model cannot use tools. Ask the owner to pick another model.";
288
+ default:
289
+ return "Something went wrong while answering. Try again; if it keeps happening, tell the owner.";
290
+ }
191
291
  }
192
292
  /** The `/ask` application command, as Discord registers it. */
193
293
  const askCommand = {
@@ -0,0 +1,65 @@
1
+ import type { DiscordAsk } from "./discord-interactions.js";
2
+ import type { ConversationSql } from "./conversations.js";
3
+ /** What one delivery attempt found. */
4
+ export type DiscordDelivery =
5
+ /** The answer, or a refusal, reached Discord; the debt is paid. */
6
+ "delivered"
7
+ /** The run has not settled yet; look again soon. */
8
+ | "waiting"
9
+ /** Discord no longer knows the token; nothing more can be sent. */
10
+ | "gone"
11
+ /** A transient failure; try again with backoff. */
12
+ | "retry";
13
+ /** One reply still owed. */
14
+ export type DiscordPendingReply = Readonly<{
15
+ bindingId: string;
16
+ ask: DiscordAsk;
17
+ /** Known once intake accepted the question; recovery skips intake then. */
18
+ accepted: Readonly<{
19
+ sessionId: string;
20
+ commandId: string;
21
+ }> | null;
22
+ attempts: number;
23
+ /** Messages of the answer Discord already has; a retry resumes after them. */
24
+ deliveredParts: number;
25
+ }>;
26
+ /** One reply that never reached Discord, as the owner's list shows it. */
27
+ export type DiscordClosedReply = Readonly<{
28
+ interactionId: string;
29
+ /** What the member goes by; never their id. */
30
+ label: string;
31
+ state: "expired" | "failed";
32
+ closedAt: number;
33
+ }>;
34
+ /** The pending-reply store and the host work that pays it off. */
35
+ export declare function createDiscordReplies(options: Readonly<{
36
+ sql: ConversationSql;
37
+ now: () => number;
38
+ /** One delivery attempt; it may itself call `attach`. */
39
+ deliver: (reply: DiscordPendingReply & Readonly<{
40
+ interactionId: string;
41
+ }>) => Promise<DiscordDelivery>;
42
+ onExpired: (interactionId: string) => void;
43
+ }>): {
44
+ /** Owe one reply. A second record of the same interaction is the first. */
45
+ record: (bindingId: string, ask: DiscordAsk) => void;
46
+ /** Remember how many messages of the answer Discord has. */
47
+ progress: (interactionId: string, parts: number) => void;
48
+ /** Replies of one binding that never reached Discord, newest first. */
49
+ closed: (bindingId: string) => readonly DiscordClosedReply[];
50
+ /** Remember which command answers this interaction. */
51
+ attach: (interactionId: string, accepted: Readonly<{
52
+ sessionId: string;
53
+ commandId: string;
54
+ }>) => void;
55
+ /** Host work on the Agent's one durable wake. */
56
+ work: {
57
+ pending: () => {
58
+ due: boolean;
59
+ nextWakeAt: number | null;
60
+ };
61
+ run: () => Promise<void>;
62
+ };
63
+ };
64
+ /** The Discord reply store. */
65
+ export type DiscordReplies = ReturnType<typeof createDiscordReplies>;
@@ -0,0 +1,182 @@
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 the answer is delivered or the token lapses, one row
5
+ * per interaction keeps the debt in the Agent's own store, so an evicted run
6
+ * still answers after the Agent wakes. A row names no secret once it is
7
+ * closed, and a closed row says honestly why: `expired` (the token lapsed or
8
+ * Discord no longer knew it) or `failed` (delivery kept failing).
9
+ */
10
+ /** The token window we honour, a little under Discord's own 15 minutes. */
11
+ const DISCORD_REPLY_WINDOW_MS = 14 * 60_000;
12
+ /** How long a closed row stays readable before it is pruned. */
13
+ const CLOSED_RETENTION_MS = 7 * 86_400_000;
14
+ /** Delivery attempts after which a reply is given up as failed. */
15
+ const MAX_DELIVERY_ATTEMPTS = 5;
16
+ /** Rows one pass works on, so a pass stays bounded. */
17
+ const PASS_LIMIT = 4;
18
+ /** How soon an unsettled run is looked at again. */
19
+ const POLL_MS = 1_000;
20
+ const pendingRow = z.strictObject({
21
+ interaction_id: z.string(),
22
+ binding_id: z.string(),
23
+ application_id: z.string(),
24
+ token: z.string(),
25
+ guild_id: z.string(),
26
+ channel_id: z.string(),
27
+ user_id: z.string(),
28
+ text: z.string(),
29
+ echo: z.string().nullable(),
30
+ display_name: z.string().nullable(),
31
+ session_id: z.string().nullable(),
32
+ command_id: z.string().nullable(),
33
+ attempts: z.number().int().nonnegative(),
34
+ delivered_parts: z.number().int().nonnegative(),
35
+ expires_at: z.number().int(),
36
+ });
37
+ const closedRow = z.strictObject({
38
+ interaction_id: z.string(),
39
+ display_name: z.string().nullable(),
40
+ state: z.enum(["expired", "failed"]),
41
+ closed_at: z.number().int(),
42
+ });
43
+ const dueRow = z.strictObject({ due: z.number().int().nullable() });
44
+ /** The pending-reply store and the host work that pays it off. */
45
+ export function createDiscordReplies(options) {
46
+ const { sql } = options;
47
+ const ensure = () => {
48
+ sql.exec(`CREATE TABLE IF NOT EXISTS oyster_discord_replies (
49
+ interaction_id TEXT PRIMARY KEY,
50
+ binding_id TEXT NOT NULL,
51
+ application_id TEXT NOT NULL,
52
+ token TEXT NOT NULL,
53
+ guild_id TEXT NOT NULL,
54
+ channel_id TEXT NOT NULL,
55
+ user_id TEXT NOT NULL,
56
+ text TEXT NOT NULL,
57
+ echo TEXT,
58
+ display_name TEXT,
59
+ delivered_parts INTEGER NOT NULL DEFAULT 0,
60
+ session_id TEXT,
61
+ command_id TEXT,
62
+ state TEXT NOT NULL CHECK (state IN ('waiting','expired','failed')),
63
+ attempts INTEGER NOT NULL,
64
+ created_at INTEGER NOT NULL,
65
+ expires_at INTEGER NOT NULL,
66
+ next_at INTEGER NOT NULL,
67
+ closed_at INTEGER
68
+ ) STRICT`);
69
+ };
70
+ const close = (interactionId, state) => {
71
+ sql.exec("UPDATE oyster_discord_replies SET state=?, token='', text='', echo=NULL, closed_at=? WHERE interaction_id=?", state, options.now(), interactionId);
72
+ };
73
+ const reschedule = (interactionId, at, attempts) => {
74
+ sql.exec("UPDATE oyster_discord_replies SET next_at=?, attempts=? WHERE interaction_id=?", at, attempts, interactionId);
75
+ };
76
+ let active;
77
+ const pass = async () => {
78
+ ensure();
79
+ const now = options.now();
80
+ sql.exec("DELETE FROM oyster_discord_replies WHERE state!='waiting' AND closed_at<?", now - CLOSED_RETENTION_MS);
81
+ const rows = sql
82
+ .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,expires_at FROM oyster_discord_replies WHERE state='waiting' AND next_at<=? ORDER BY next_at LIMIT ?", now, PASS_LIMIT)
83
+ .toArray()
84
+ .map((raw) => pendingRow.parse(raw));
85
+ for (const row of rows) {
86
+ if (options.now() >= row.expires_at) {
87
+ close(row.interaction_id, "expired");
88
+ options.onExpired(row.interaction_id);
89
+ continue;
90
+ }
91
+ const delivery = await options.deliver({
92
+ interactionId: row.interaction_id,
93
+ bindingId: row.binding_id,
94
+ ask: {
95
+ interactionId: row.interaction_id,
96
+ applicationId: row.application_id,
97
+ interactionToken: row.token,
98
+ guildId: row.guild_id,
99
+ channelId: row.channel_id,
100
+ userId: row.user_id,
101
+ text: row.text,
102
+ echo: row.echo ?? undefined,
103
+ displayName: row.display_name ?? undefined,
104
+ },
105
+ accepted: row.session_id !== null && row.command_id !== null
106
+ ? { sessionId: row.session_id, commandId: row.command_id }
107
+ : null,
108
+ attempts: row.attempts,
109
+ deliveredParts: row.delivered_parts,
110
+ });
111
+ switch (delivery) {
112
+ case "delivered":
113
+ sql.exec("DELETE FROM oyster_discord_replies WHERE interaction_id=?", row.interaction_id);
114
+ break;
115
+ case "waiting":
116
+ reschedule(row.interaction_id, options.now() + POLL_MS, row.attempts);
117
+ break;
118
+ case "gone":
119
+ close(row.interaction_id, "expired");
120
+ options.onExpired(row.interaction_id);
121
+ break;
122
+ case "retry":
123
+ if (row.attempts + 1 >= MAX_DELIVERY_ATTEMPTS)
124
+ close(row.interaction_id, "failed");
125
+ else
126
+ reschedule(row.interaction_id, options.now() + 1_000 * 2 ** (row.attempts + 1), row.attempts + 1);
127
+ break;
128
+ }
129
+ }
130
+ };
131
+ return {
132
+ /** Owe one reply. A second record of the same interaction is the first. */
133
+ record: (bindingId, ask) => {
134
+ ensure();
135
+ const now = options.now();
136
+ 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);
137
+ },
138
+ /** Remember how many messages of the answer Discord has. */
139
+ progress: (interactionId, parts) => {
140
+ sql.exec("UPDATE oyster_discord_replies SET delivered_parts=? WHERE interaction_id=?", parts, interactionId);
141
+ },
142
+ /** Replies of one binding that never reached Discord, newest first. */
143
+ closed: (bindingId) => {
144
+ ensure();
145
+ return sql
146
+ .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)
147
+ .toArray()
148
+ .map((raw) => {
149
+ const row = closedRow.parse(raw);
150
+ return {
151
+ interactionId: row.interaction_id,
152
+ label: row.display_name ?? "Discord member",
153
+ state: row.state,
154
+ closedAt: row.closed_at,
155
+ };
156
+ });
157
+ },
158
+ /** Remember which command answers this interaction. */
159
+ attach: (interactionId, accepted) => {
160
+ sql.exec("UPDATE oyster_discord_replies SET session_id=?, command_id=? WHERE interaction_id=?", accepted.sessionId, accepted.commandId, interactionId);
161
+ },
162
+ /** Host work on the Agent's one durable wake. */
163
+ work: {
164
+ pending: () => {
165
+ ensure();
166
+ const row = dueRow.parse(sql
167
+ .exec("SELECT MIN(next_at) AS due FROM oyster_discord_replies WHERE state='waiting'")
168
+ .toArray()[0]);
169
+ return {
170
+ due: row.due !== null && row.due <= options.now(),
171
+ nextWakeAt: row.due,
172
+ };
173
+ },
174
+ run: () => {
175
+ // Passes never overlap, so one reply is never delivered twice at once.
176
+ const next = (active ?? Promise.resolve()).then(pass, pass);
177
+ active = next;
178
+ return next;
179
+ },
180
+ },
181
+ };
182
+ }