@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.
@@ -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,41 @@ 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
+ /** What a member is told on the original message when an answer will take longer. */
236
+ export declare const STILL_WORKING_TEXT = "Still working on this. I will post the answer in this channel when it is ready.";
237
+ /**
238
+ * Post a normal channel message as the owner's bot, for an answer that
239
+ * outlived its interaction token. The bot token is the credential and never
240
+ * leaves the host call; the member is mentioned so they are told it arrived.
241
+ */
242
+ export declare function postChannelMessage(send: typeof fetch, input: Readonly<{
243
+ channelId: string;
244
+ botToken: string;
245
+ content: string;
246
+ withReply: boolean;
247
+ /** Mention this member, and only them. */
248
+ mentionUserId: string | null;
249
+ }>): Promise<"delivered" | "gone" | "retry">;
250
+ /**
251
+ * Tell the member why an answer did not come, in plain words and with what to
252
+ * do next. The host's own failure diagnostic names the cause; provider prose
253
+ * never reaches a member.
254
+ */
255
+ export declare function discordFailureText(terminal: Readonly<{
256
+ outcome: "completed" | "cancelled" | "failed" | "interrupted";
257
+ diagnostic: string | null;
258
+ }>): string;
182
259
  /**
183
260
  * Register `/ask` in one guild with the owner's bot token. Creating by name
184
261
  * updates an existing `/ask` and leaves the owner's other commands alone.
@@ -188,3 +265,4 @@ export declare function registerAskCommand(send: typeof fetch, input: Readonly<{
188
265
  guildId: string;
189
266
  botToken: string;
190
267
  }>): Promise<boolean>;
268
+ 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,85 @@ 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
+ /** What a member is told on the original message when an answer will take longer. */
263
+ export const STILL_WORKING_TEXT = "Still working on this. I will post the answer in this channel when it is ready.";
264
+ /**
265
+ * Post a normal channel message as the owner's bot, for an answer that
266
+ * outlived its interaction token. The bot token is the credential and never
267
+ * leaves the host call; the member is mentioned so they are told it arrived.
268
+ */
269
+ export async function postChannelMessage(send, input) {
270
+ const response = await send(`${DISCORD_API}/channels/${input.channelId}/messages`, {
271
+ method: "POST",
272
+ headers: {
273
+ authorization: `Bot ${input.botToken}`,
274
+ "content-type": "application/json",
275
+ },
276
+ body: JSON.stringify({
277
+ ...followUpBody(input.content, input.withReply),
278
+ allowed_mentions: {
279
+ parse: [],
280
+ users: input.mentionUserId === null ? [] : [input.mentionUserId],
281
+ },
282
+ }),
283
+ signal: AbortSignal.timeout(15_000),
284
+ });
285
+ await response.body?.cancel();
286
+ // 401, 403 and 404: the bot is not allowed in that channel, or it is gone.
287
+ if (response.ok)
288
+ return "delivered";
289
+ return [401, 403, 404].includes(response.status) ? "gone" : "retry";
290
+ }
291
+ const failureCode = /^Model request failed \(([\w-]+)\)/u;
292
+ /**
293
+ * Tell the member why an answer did not come, in plain words and with what to
294
+ * do next. The host's own failure diagnostic names the cause; provider prose
295
+ * never reaches a member.
296
+ */
297
+ export function discordFailureText(terminal) {
298
+ if (terminal.outcome === "cancelled")
299
+ return "That run was cancelled.";
300
+ if (terminal.outcome === "interrupted")
301
+ return "The run was interrupted before it finished. Ask again.";
302
+ if (terminal.outcome === "completed")
303
+ return "The Agent finished without a reply. Try asking again.";
304
+ switch (failureCode.exec(terminal.diagnostic ?? "")?.[1]) {
305
+ case "setup_required":
306
+ return "No model is connected to this Agent yet. Ask its owner to connect one, then ask again.";
307
+ case "usage-limit-reached":
308
+ return "The model provider says its usage limit or credit is used up. Ask the owner to check the provider account, then try again.";
309
+ case "rate-limit":
310
+ case "overloaded":
311
+ case "provider_unavailable":
312
+ return "The model provider is busy or unavailable right now. Try again in a minute.";
313
+ case "provider_rejected":
314
+ return "The model provider refused the request. Ask the owner to check the model connection.";
315
+ case "tools_unsupported":
316
+ return "This Agent's model cannot use tools. Ask the owner to pick another model.";
317
+ default:
318
+ return "Something went wrong while answering. Try again; if it keeps happening, tell the owner.";
319
+ }
191
320
  }
192
321
  /** The `/ask` application command, as Discord registers it. */
193
322
  const askCommand = {
@@ -0,0 +1,73 @@
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 refuses every way of reaching the member; 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
+ /** Whether the interaction token still works; past it, only the channel does. */
26
+ tokenLive: boolean;
27
+ /** The token is about to lapse and the member has not been told it is still working. */
28
+ stillWorkingDue: boolean;
29
+ }>;
30
+ /** One reply that never reached Discord, as the owner's list shows it. */
31
+ export type DiscordClosedReply = Readonly<{
32
+ interactionId: string;
33
+ /** What the member goes by; never their id. */
34
+ label: string;
35
+ state: "expired" | "failed";
36
+ closedAt: number;
37
+ }>;
38
+ /** The pending-reply store and the host work that pays it off. */
39
+ export declare function createDiscordReplies(options: Readonly<{
40
+ sql: ConversationSql;
41
+ now: () => number;
42
+ /** One delivery attempt; it may itself call `attach`. */
43
+ deliver: (reply: DiscordPendingReply & Readonly<{
44
+ interactionId: string;
45
+ }>) => Promise<DiscordDelivery>;
46
+ onExpired: (interactionId: string) => void;
47
+ }>): {
48
+ /** Owe one reply. A second record of the same interaction is the first. */
49
+ record: (bindingId: string, ask: DiscordAsk) => void;
50
+ /** The member has been told the run is still going. */
51
+ markStillWorking: (interactionId: string) => void;
52
+ /** Discord no longer knows the token: only the channel reaches the member now. */
53
+ tokenGone: (interactionId: string) => void;
54
+ /** Remember how many messages of the answer Discord has. */
55
+ progress: (interactionId: string, parts: number) => void;
56
+ /** Replies of one binding that never reached Discord, newest first. */
57
+ closed: (bindingId: string) => readonly DiscordClosedReply[];
58
+ /** Remember which command answers this interaction. */
59
+ attach: (interactionId: string, accepted: Readonly<{
60
+ sessionId: string;
61
+ commandId: string;
62
+ }>) => void;
63
+ /** Host work on the Agent's one durable wake. */
64
+ work: {
65
+ pending: () => {
66
+ due: boolean;
67
+ nextWakeAt: number | null;
68
+ };
69
+ run: () => Promise<void>;
70
+ };
71
+ };
72
+ /** The Discord reply store. */
73
+ export type DiscordReplies = ReturnType<typeof createDiscordReplies>;