@fungi.computer/oyster 0.21.9 → 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.
- package/dist/agents.d.ts +1 -0
- package/dist/agents.js +4 -9
- package/dist/channels/binding.d.ts +1 -0
- package/dist/channels/binding.js +3 -1
- package/dist/channels/conversations.d.ts +1 -0
- package/dist/channels/conversations.js +15 -1
- package/dist/channels/discord-binding.d.ts +132 -0
- package/dist/channels/discord-binding.js +234 -0
- package/dist/channels/discord-interactions.d.ts +253 -0
- package/dist/channels/discord-interactions.js +325 -0
- package/dist/channels/discord-replies.d.ts +65 -0
- package/dist/channels/discord-replies.js +182 -0
- package/dist/embed-metafiles.js +1 -1
- package/dist/embed-scripts.js +1 -1
- package/dist/page-script.js +1 -1
- package/dist/standalone/agent-model-choice.d.ts +2 -14
- package/dist/standalone/agent-model-choice.js +65 -35
- package/dist/standalone/agents.d.ts +60 -9
- package/dist/standalone/agents.js +244 -11
- package/dist/standalone/app-builds-binding.js +1 -1
- package/dist/standalone/discord-channels.d.ts +89 -0
- package/dist/standalone/discord-channels.js +260 -0
- package/dist/standalone/model-key-providers.d.ts +13 -0
- package/dist/standalone/model-key-providers.js +11 -0
- package/dist/standalone/model-key-vault.d.ts +9 -5
- package/dist/standalone/model-key-vault.js +9 -9
- package/dist/standalone/owner-routes.js +4 -1
- package/dist/standalone/registry.d.ts +5 -2
- package/dist/standalone/registry.js +6 -4
- package/dist/standalone/website-channels.js +2 -2
- package/dist/standalone/worker-routes.d.ts +2 -0
- package/dist/standalone/worker-routes.js +1 -0
- package/dist/standalone/worker.js +4 -0
- package/docs/api/agents.md +36 -10
- package/docs/api/workers-git.md +7 -7
- package/package.json +12 -12
|
@@ -0,0 +1,253 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
/**
|
|
3
|
+
* Discord's HTTP interactions, as one Agent channel needs them: verify the
|
|
4
|
+
* Ed25519 signature of a request, decode only the fields we use, and build
|
|
5
|
+
* the few responses and follow-ups we send. No Gateway and no Message Content
|
|
6
|
+
* intent: members reach the Agent through the `/ask` command and a Reply
|
|
7
|
+
* button that opens a modal.
|
|
8
|
+
*/
|
|
9
|
+
/** The one command; an owner registers it in each bound guild. */
|
|
10
|
+
export declare const ASK_COMMAND = "ask";
|
|
11
|
+
/** The one option of `/ask`. */
|
|
12
|
+
export declare const ASK_OPTION = "question";
|
|
13
|
+
/** The Reply button and its modal share one custom id. */
|
|
14
|
+
export declare const REPLY_ID = "reply";
|
|
15
|
+
/** The modal's single text input. */
|
|
16
|
+
export declare const REPLY_TEXT_ID = "text";
|
|
17
|
+
/** The longest question or reply Discord lets a member type here. */
|
|
18
|
+
export declare const DISCORD_ASK_LIMIT = 1000;
|
|
19
|
+
/** One settlement read waits at most this long (Shiitake allows 30 s). */
|
|
20
|
+
export declare const DISCORD_SETTLEMENT_WAIT_MS = 8000;
|
|
21
|
+
/** One verified question, as the public edge hands it to the Agent. */
|
|
22
|
+
export type DiscordAsk = Readonly<{
|
|
23
|
+
interactionId: string;
|
|
24
|
+
applicationId: string;
|
|
25
|
+
/** Credential for the follow-up webhook; never stored. */
|
|
26
|
+
interactionToken: string;
|
|
27
|
+
guildId: string;
|
|
28
|
+
channelId: string;
|
|
29
|
+
userId: string;
|
|
30
|
+
text: string;
|
|
31
|
+
/** What the member goes by, if Discord said; never their id. */
|
|
32
|
+
displayName?: string | undefined;
|
|
33
|
+
/** The member's own words, quoted above the answer of a modal reply. */
|
|
34
|
+
echo?: string | undefined;
|
|
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;
|
|
44
|
+
/** What a member is told when intake says no. */
|
|
45
|
+
export declare const discordDenial: {
|
|
46
|
+
readonly unmapped: "This Agent is not available right now.";
|
|
47
|
+
readonly suspended: "This Agent is paused.";
|
|
48
|
+
readonly banned: "You cannot ask this Agent anything.";
|
|
49
|
+
readonly too_long: "That message is too long.";
|
|
50
|
+
readonly party_daily_limit: "You have reached today's limit. Try again tomorrow.";
|
|
51
|
+
readonly new_party_limit: "This Agent is busy right now. Try again soon.";
|
|
52
|
+
readonly rate_limited: "This Agent is busy right now. Try again soon.";
|
|
53
|
+
readonly event_conflict: "That message could not be accepted.";
|
|
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>;
|
|
68
|
+
/** The interaction types we answer; any other type fails to decode. */
|
|
69
|
+
export declare const interactionSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
|
|
70
|
+
type: z.ZodLiteral<1>;
|
|
71
|
+
id: z.ZodString;
|
|
72
|
+
application_id: z.ZodString;
|
|
73
|
+
}, z.core.$strip>, z.ZodObject<{
|
|
74
|
+
type: z.ZodLiteral<2>;
|
|
75
|
+
data: z.ZodObject<{
|
|
76
|
+
name: z.ZodString;
|
|
77
|
+
options: z.ZodOptional<z.ZodArray<z.ZodObject<{
|
|
78
|
+
name: z.ZodString;
|
|
79
|
+
value: z.ZodOptional<z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodBoolean]>>;
|
|
80
|
+
}, z.core.$strip>>>;
|
|
81
|
+
}, z.core.$strip>;
|
|
82
|
+
id: z.ZodString;
|
|
83
|
+
application_id: z.ZodString;
|
|
84
|
+
token: z.ZodString;
|
|
85
|
+
guild_id: z.ZodOptional<z.ZodString>;
|
|
86
|
+
channel_id: z.ZodOptional<z.ZodString>;
|
|
87
|
+
member: z.ZodOptional<z.ZodObject<{
|
|
88
|
+
user: z.ZodObject<{
|
|
89
|
+
id: z.ZodString;
|
|
90
|
+
username: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
91
|
+
global_name: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
92
|
+
}, z.core.$strip>;
|
|
93
|
+
nick: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
94
|
+
}, z.core.$strip>>;
|
|
95
|
+
user: z.ZodOptional<z.ZodObject<{
|
|
96
|
+
id: z.ZodString;
|
|
97
|
+
username: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
98
|
+
global_name: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
99
|
+
}, z.core.$strip>>;
|
|
100
|
+
}, z.core.$strip>, z.ZodObject<{
|
|
101
|
+
type: z.ZodLiteral<3>;
|
|
102
|
+
data: z.ZodObject<{
|
|
103
|
+
custom_id: z.ZodString;
|
|
104
|
+
}, z.core.$strip>;
|
|
105
|
+
id: z.ZodString;
|
|
106
|
+
application_id: z.ZodString;
|
|
107
|
+
token: z.ZodString;
|
|
108
|
+
guild_id: z.ZodOptional<z.ZodString>;
|
|
109
|
+
channel_id: z.ZodOptional<z.ZodString>;
|
|
110
|
+
member: z.ZodOptional<z.ZodObject<{
|
|
111
|
+
user: z.ZodObject<{
|
|
112
|
+
id: z.ZodString;
|
|
113
|
+
username: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
114
|
+
global_name: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
115
|
+
}, z.core.$strip>;
|
|
116
|
+
nick: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
117
|
+
}, z.core.$strip>>;
|
|
118
|
+
user: z.ZodOptional<z.ZodObject<{
|
|
119
|
+
id: z.ZodString;
|
|
120
|
+
username: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
121
|
+
global_name: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
122
|
+
}, z.core.$strip>>;
|
|
123
|
+
}, z.core.$strip>, z.ZodObject<{
|
|
124
|
+
type: z.ZodLiteral<5>;
|
|
125
|
+
data: z.ZodObject<{
|
|
126
|
+
custom_id: z.ZodString;
|
|
127
|
+
components: z.ZodArray<z.ZodObject<{
|
|
128
|
+
components: z.ZodArray<z.ZodObject<{
|
|
129
|
+
custom_id: z.ZodString;
|
|
130
|
+
value: z.ZodString;
|
|
131
|
+
}, z.core.$strip>>;
|
|
132
|
+
}, z.core.$strip>>;
|
|
133
|
+
}, z.core.$strip>;
|
|
134
|
+
id: z.ZodString;
|
|
135
|
+
application_id: z.ZodString;
|
|
136
|
+
token: z.ZodString;
|
|
137
|
+
guild_id: z.ZodOptional<z.ZodString>;
|
|
138
|
+
channel_id: z.ZodOptional<z.ZodString>;
|
|
139
|
+
member: z.ZodOptional<z.ZodObject<{
|
|
140
|
+
user: z.ZodObject<{
|
|
141
|
+
id: z.ZodString;
|
|
142
|
+
username: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
143
|
+
global_name: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
144
|
+
}, z.core.$strip>;
|
|
145
|
+
nick: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
146
|
+
}, z.core.$strip>>;
|
|
147
|
+
user: z.ZodOptional<z.ZodObject<{
|
|
148
|
+
id: z.ZodString;
|
|
149
|
+
username: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
150
|
+
global_name: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
151
|
+
}, z.core.$strip>>;
|
|
152
|
+
}, z.core.$strip>], "type">;
|
|
153
|
+
/** Why a request's signature was refused. */
|
|
154
|
+
export type SignatureRefusal = "missing" | "malformed" | "stale" | "invalid";
|
|
155
|
+
/**
|
|
156
|
+
* Verify Discord's Ed25519 signature over `timestamp + body` with WebCrypto.
|
|
157
|
+
* The timestamp is also bounded, so a captured request cannot be replayed
|
|
158
|
+
* later.
|
|
159
|
+
*/
|
|
160
|
+
export declare function verifyDiscordRequest(input: Readonly<{
|
|
161
|
+
publicKey: string;
|
|
162
|
+
signature: string | undefined;
|
|
163
|
+
timestamp: string | undefined;
|
|
164
|
+
body: string;
|
|
165
|
+
nowSeconds: number;
|
|
166
|
+
}>): Promise<"verified" | SignatureRefusal>;
|
|
167
|
+
/** The answer to Discord's endpoint check. */
|
|
168
|
+
export declare const pongResponse: {
|
|
169
|
+
readonly type: 1;
|
|
170
|
+
};
|
|
171
|
+
/** Tell the member the Agent is working; the answer follows by webhook. */
|
|
172
|
+
export declare const deferredResponse: {
|
|
173
|
+
readonly type: 5;
|
|
174
|
+
};
|
|
175
|
+
/** A one-off notice only the member sees, such as a refusal. */
|
|
176
|
+
export declare function ephemeralResponse(content: string): {
|
|
177
|
+
readonly type: 4;
|
|
178
|
+
readonly data: {
|
|
179
|
+
readonly content: string;
|
|
180
|
+
readonly flags: 64;
|
|
181
|
+
readonly allowed_mentions: {
|
|
182
|
+
readonly parse: readonly [];
|
|
183
|
+
};
|
|
184
|
+
};
|
|
185
|
+
};
|
|
186
|
+
/** The modal a Reply button opens: one paragraph input. */
|
|
187
|
+
export declare const replyModalResponse: {
|
|
188
|
+
readonly type: 9;
|
|
189
|
+
readonly data: {
|
|
190
|
+
readonly custom_id: "reply";
|
|
191
|
+
readonly title: "Reply";
|
|
192
|
+
readonly components: readonly [{
|
|
193
|
+
readonly type: 1;
|
|
194
|
+
readonly components: readonly [{
|
|
195
|
+
readonly type: 4;
|
|
196
|
+
readonly custom_id: "text";
|
|
197
|
+
readonly label: "Your reply";
|
|
198
|
+
readonly style: 2;
|
|
199
|
+
readonly min_length: 1;
|
|
200
|
+
readonly max_length: 1000;
|
|
201
|
+
readonly required: true;
|
|
202
|
+
}];
|
|
203
|
+
}];
|
|
204
|
+
};
|
|
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[];
|
|
213
|
+
/** Quote a member's modal reply so the thread reads in order. */
|
|
214
|
+
export declare function quoted(text: string): string;
|
|
215
|
+
/**
|
|
216
|
+
* Fill the deferred message with the Agent's answer. The interaction token is
|
|
217
|
+
* the credential: no bot token is involved.
|
|
218
|
+
*/
|
|
219
|
+
export declare function patchOriginal(send: typeof fetch, input: Readonly<{
|
|
220
|
+
applicationId: string;
|
|
221
|
+
interactionToken: string;
|
|
222
|
+
content: string;
|
|
223
|
+
withReply: 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;
|
|
244
|
+
/**
|
|
245
|
+
* Register `/ask` in one guild with the owner's bot token. Creating by name
|
|
246
|
+
* updates an existing `/ask` and leaves the owner's other commands alone.
|
|
247
|
+
*/
|
|
248
|
+
export declare function registerAskCommand(send: typeof fetch, input: Readonly<{
|
|
249
|
+
applicationId: string;
|
|
250
|
+
guildId: string;
|
|
251
|
+
botToken: string;
|
|
252
|
+
}>): Promise<boolean>;
|
|
253
|
+
export {};
|
|
@@ -0,0 +1,325 @@
|
|
|
1
|
+
import { Hex } from "effect/encoding";
|
|
2
|
+
import * as Result from "effect/Result";
|
|
3
|
+
import { z } from "zod";
|
|
4
|
+
import { discordSnowflakeSchema } from "./binding.js";
|
|
5
|
+
/**
|
|
6
|
+
* Discord's HTTP interactions, as one Agent channel needs them: verify the
|
|
7
|
+
* Ed25519 signature of a request, decode only the fields we use, and build
|
|
8
|
+
* the few responses and follow-ups we send. No Gateway and no Message Content
|
|
9
|
+
* intent: members reach the Agent through the `/ask` command and a Reply
|
|
10
|
+
* button that opens a modal.
|
|
11
|
+
*/
|
|
12
|
+
/** The one command; an owner registers it in each bound guild. */
|
|
13
|
+
export const ASK_COMMAND = "ask";
|
|
14
|
+
/** The one option of `/ask`. */
|
|
15
|
+
export const ASK_OPTION = "question";
|
|
16
|
+
/** The Reply button and its modal share one custom id. */
|
|
17
|
+
export const REPLY_ID = "reply";
|
|
18
|
+
/** The modal's single text input. */
|
|
19
|
+
export const REPLY_TEXT_ID = "text";
|
|
20
|
+
/** Discord rejects a message over 2,000 characters. */
|
|
21
|
+
const DISCORD_MESSAGE_LIMIT = 2_000;
|
|
22
|
+
/** The longest question or reply Discord lets a member type here. */
|
|
23
|
+
export const DISCORD_ASK_LIMIT = 1_000;
|
|
24
|
+
/** Discord API version the follow-up and registration calls pin. */
|
|
25
|
+
const DISCORD_API = "https://discord.com/api/v10";
|
|
26
|
+
/** One settlement read waits at most this long (Shiitake allows 30 s). */
|
|
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
|
+
}
|
|
40
|
+
/** What a member is told when intake says no. */
|
|
41
|
+
export const discordDenial = {
|
|
42
|
+
unmapped: "This Agent is not available right now.",
|
|
43
|
+
suspended: "This Agent is paused.",
|
|
44
|
+
banned: "You cannot ask this Agent anything.",
|
|
45
|
+
too_long: "That message is too long.",
|
|
46
|
+
party_daily_limit: "You have reached today's limit. Try again tomorrow.",
|
|
47
|
+
new_party_limit: "This Agent is busy right now. Try again soon.",
|
|
48
|
+
rate_limited: "This Agent is busy right now. Try again soon.",
|
|
49
|
+
event_conflict: "That message could not be accepted.",
|
|
50
|
+
};
|
|
51
|
+
/** How far a request's signed timestamp may sit from now, in seconds. */
|
|
52
|
+
const SIGNATURE_MAX_SKEW_SECONDS = 300;
|
|
53
|
+
const optionSchema = z.object({
|
|
54
|
+
name: z.string(),
|
|
55
|
+
value: z.union([z.string(), z.number(), z.boolean()]).optional(),
|
|
56
|
+
});
|
|
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
|
+
});
|
|
67
|
+
const placeFields = {
|
|
68
|
+
id: discordSnowflakeSchema,
|
|
69
|
+
application_id: discordSnowflakeSchema,
|
|
70
|
+
token: z.string().min(1).max(512),
|
|
71
|
+
guild_id: discordSnowflakeSchema.optional(),
|
|
72
|
+
channel_id: discordSnowflakeSchema.optional(),
|
|
73
|
+
member: memberSchema.optional(),
|
|
74
|
+
user: userSchema.optional(),
|
|
75
|
+
};
|
|
76
|
+
/** The interaction types we answer; any other type fails to decode. */
|
|
77
|
+
export const interactionSchema = z.discriminatedUnion("type", [
|
|
78
|
+
z.object({
|
|
79
|
+
type: z.literal(1),
|
|
80
|
+
id: discordSnowflakeSchema,
|
|
81
|
+
application_id: discordSnowflakeSchema,
|
|
82
|
+
}),
|
|
83
|
+
z.object({
|
|
84
|
+
...placeFields,
|
|
85
|
+
type: z.literal(2),
|
|
86
|
+
data: z.object({
|
|
87
|
+
name: z.string(),
|
|
88
|
+
options: z.array(optionSchema).optional(),
|
|
89
|
+
}),
|
|
90
|
+
}),
|
|
91
|
+
z.object({
|
|
92
|
+
...placeFields,
|
|
93
|
+
type: z.literal(3),
|
|
94
|
+
data: z.object({ custom_id: z.string() }),
|
|
95
|
+
}),
|
|
96
|
+
z.object({
|
|
97
|
+
...placeFields,
|
|
98
|
+
type: z.literal(5),
|
|
99
|
+
data: z.object({
|
|
100
|
+
custom_id: z.string(),
|
|
101
|
+
components: z.array(z.object({
|
|
102
|
+
components: z.array(z.object({ custom_id: z.string(), value: z.string() })),
|
|
103
|
+
})),
|
|
104
|
+
}),
|
|
105
|
+
}),
|
|
106
|
+
]);
|
|
107
|
+
function bytesOf(hex) {
|
|
108
|
+
const decoded = Hex.decode(hex);
|
|
109
|
+
return Result.isSuccess(decoded) ? new Uint8Array(decoded.success) : null;
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* Verify Discord's Ed25519 signature over `timestamp + body` with WebCrypto.
|
|
113
|
+
* The timestamp is also bounded, so a captured request cannot be replayed
|
|
114
|
+
* later.
|
|
115
|
+
*/
|
|
116
|
+
export async function verifyDiscordRequest(input) {
|
|
117
|
+
if (input.signature === undefined || input.timestamp === undefined)
|
|
118
|
+
return "missing";
|
|
119
|
+
const signature = bytesOf(input.signature);
|
|
120
|
+
const publicKey = bytesOf(input.publicKey);
|
|
121
|
+
const signedAt = Number(input.timestamp);
|
|
122
|
+
if (signature === null || publicKey === null || !Number.isFinite(signedAt))
|
|
123
|
+
return "malformed";
|
|
124
|
+
if (Math.abs(input.nowSeconds - signedAt) > SIGNATURE_MAX_SKEW_SECONDS)
|
|
125
|
+
return "stale";
|
|
126
|
+
const key = await crypto.subtle.importKey("raw", publicKey, { name: "Ed25519" }, false, ["verify"]);
|
|
127
|
+
const valid = await crypto.subtle.verify("Ed25519", key, signature, new TextEncoder().encode(input.timestamp + input.body));
|
|
128
|
+
return valid ? "verified" : "invalid";
|
|
129
|
+
}
|
|
130
|
+
/** Interaction callback types we send. */
|
|
131
|
+
const CALLBACK = { pong: 1, message: 4, deferred: 5, modal: 9 };
|
|
132
|
+
/** Message flag: only the member who triggered the interaction sees it. */
|
|
133
|
+
const EPHEMERAL = 64;
|
|
134
|
+
/** The answer to Discord's endpoint check. */
|
|
135
|
+
export const pongResponse = { type: CALLBACK.pong };
|
|
136
|
+
/** Tell the member the Agent is working; the answer follows by webhook. */
|
|
137
|
+
export const deferredResponse = { type: CALLBACK.deferred };
|
|
138
|
+
/** A one-off notice only the member sees, such as a refusal. */
|
|
139
|
+
export function ephemeralResponse(content) {
|
|
140
|
+
return {
|
|
141
|
+
type: CALLBACK.message,
|
|
142
|
+
data: {
|
|
143
|
+
content: content.slice(0, DISCORD_MESSAGE_LIMIT),
|
|
144
|
+
flags: EPHEMERAL,
|
|
145
|
+
allowed_mentions: { parse: [] },
|
|
146
|
+
},
|
|
147
|
+
};
|
|
148
|
+
}
|
|
149
|
+
/** The modal a Reply button opens: one paragraph input. */
|
|
150
|
+
export const replyModalResponse = {
|
|
151
|
+
type: CALLBACK.modal,
|
|
152
|
+
data: {
|
|
153
|
+
custom_id: REPLY_ID,
|
|
154
|
+
title: "Reply",
|
|
155
|
+
components: [
|
|
156
|
+
{
|
|
157
|
+
type: 1,
|
|
158
|
+
components: [
|
|
159
|
+
{
|
|
160
|
+
type: 4,
|
|
161
|
+
custom_id: REPLY_TEXT_ID,
|
|
162
|
+
label: "Your reply",
|
|
163
|
+
style: 2,
|
|
164
|
+
min_length: 1,
|
|
165
|
+
max_length: DISCORD_ASK_LIMIT,
|
|
166
|
+
required: true,
|
|
167
|
+
},
|
|
168
|
+
],
|
|
169
|
+
},
|
|
170
|
+
],
|
|
171
|
+
},
|
|
172
|
+
};
|
|
173
|
+
/** The Reply button attached to every Agent answer. */
|
|
174
|
+
const replyRow = [
|
|
175
|
+
{
|
|
176
|
+
type: 1,
|
|
177
|
+
components: [{ type: 2, style: 2, label: "Reply", custom_id: REPLY_ID }],
|
|
178
|
+
},
|
|
179
|
+
];
|
|
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. */
|
|
213
|
+
function followUpBody(content, withReply) {
|
|
214
|
+
return {
|
|
215
|
+
content,
|
|
216
|
+
// Model text never pings anyone.
|
|
217
|
+
allowed_mentions: { parse: [] },
|
|
218
|
+
components: withReply ? replyRow : [],
|
|
219
|
+
};
|
|
220
|
+
}
|
|
221
|
+
/** Quote a member's modal reply so the thread reads in order. */
|
|
222
|
+
export function quoted(text) {
|
|
223
|
+
return text
|
|
224
|
+
.slice(0, 300)
|
|
225
|
+
.split("\n")
|
|
226
|
+
.map((line) => `> ${line}`)
|
|
227
|
+
.join("\n");
|
|
228
|
+
}
|
|
229
|
+
/**
|
|
230
|
+
* Fill the deferred message with the Agent's answer. The interaction token is
|
|
231
|
+
* the credential: no bot token is involved.
|
|
232
|
+
*/
|
|
233
|
+
export async function patchOriginal(send, input) {
|
|
234
|
+
const response = await send(`${DISCORD_API}/webhooks/${input.applicationId}/${input.interactionToken}/messages/@original`, {
|
|
235
|
+
method: "PATCH",
|
|
236
|
+
headers: { "content-type": "application/json" },
|
|
237
|
+
body: JSON.stringify(followUpBody(input.content, input.withReply)),
|
|
238
|
+
signal: AbortSignal.timeout(15_000),
|
|
239
|
+
});
|
|
240
|
+
await response.body?.cancel();
|
|
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
|
+
}
|
|
291
|
+
}
|
|
292
|
+
/** The `/ask` application command, as Discord registers it. */
|
|
293
|
+
const askCommand = {
|
|
294
|
+
name: ASK_COMMAND,
|
|
295
|
+
type: 1,
|
|
296
|
+
description: "Ask this Agent a question",
|
|
297
|
+
dm_permission: false,
|
|
298
|
+
options: [
|
|
299
|
+
{
|
|
300
|
+
type: 3,
|
|
301
|
+
name: ASK_OPTION,
|
|
302
|
+
description: "What do you want to ask?",
|
|
303
|
+
required: true,
|
|
304
|
+
min_length: 1,
|
|
305
|
+
max_length: DISCORD_ASK_LIMIT,
|
|
306
|
+
},
|
|
307
|
+
],
|
|
308
|
+
};
|
|
309
|
+
/**
|
|
310
|
+
* Register `/ask` in one guild with the owner's bot token. Creating by name
|
|
311
|
+
* updates an existing `/ask` and leaves the owner's other commands alone.
|
|
312
|
+
*/
|
|
313
|
+
export async function registerAskCommand(send, input) {
|
|
314
|
+
const response = await send(`${DISCORD_API}/applications/${input.applicationId}/guilds/${input.guildId}/commands`, {
|
|
315
|
+
method: "POST",
|
|
316
|
+
headers: {
|
|
317
|
+
authorization: `Bot ${input.botToken}`,
|
|
318
|
+
"content-type": "application/json",
|
|
319
|
+
},
|
|
320
|
+
body: JSON.stringify(askCommand),
|
|
321
|
+
signal: AbortSignal.timeout(15_000),
|
|
322
|
+
});
|
|
323
|
+
await response.body?.cancel();
|
|
324
|
+
return response.ok;
|
|
325
|
+
}
|
|
@@ -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>;
|