@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
package/dist/agents.d.ts
CHANGED
|
@@ -2,6 +2,7 @@ import type { AppSetup } from "@fungi.computer/agar";
|
|
|
2
2
|
import type { TenantPrincipal } from "./tenant.js";
|
|
3
3
|
import type { ModelKeyRecord, ModelKeyRefusal, ModelKeySealInput } from "./standalone/model-key-vault.js";
|
|
4
4
|
export type { ModelKeyRecord, ModelKeyRefusal, ModelKeySealInput, } from "./standalone/model-key-vault.js";
|
|
5
|
+
export type { StandaloneModelKeyProvider } from "./standalone/model-key-providers.js";
|
|
5
6
|
import { type Routes } from "./authorization.js";
|
|
6
7
|
import type { AppToolPolicy } from "./apps/tools.js";
|
|
7
8
|
import * as Schema from "effect/Schema";
|
package/dist/agents.js
CHANGED
|
@@ -4,6 +4,7 @@ import { z } from "zod";
|
|
|
4
4
|
import {} from "./host.js";
|
|
5
5
|
import { agentAvatarSchema } from "./agent-avatars.js";
|
|
6
6
|
import { computerTargetParam } from "./computer-target.js";
|
|
7
|
+
import { modelKeyProviderChoices } from "./standalone/model-key-providers.js";
|
|
7
8
|
import { supportedAgentModels } from "./standalone/agent-model-choice.js";
|
|
8
9
|
import { agentAvatar, agentList, agentManage, agentRename, agentSessionRead, agentSessionWrite, agentToolPolicy, } from "@fungi.computer/agar/agents";
|
|
9
10
|
/** At most this many connections per Agent. */
|
|
@@ -374,12 +375,11 @@ export function agentApprovalRoutes(agents) {
|
|
|
374
375
|
})));
|
|
375
376
|
const keys = await agents.modelKeys();
|
|
376
377
|
const providers = [...new Set(keys.map((key) => key.provider))];
|
|
377
|
-
const catalogs = Object.fromEntries(await Promise.all(providers
|
|
378
|
-
.filter((provider) => provider !== "openai-compatible")
|
|
379
|
-
.map(async (provider) => [provider, await supportedAgentModels(provider)])));
|
|
378
|
+
const catalogs = Object.fromEntries(await Promise.all(providers.map(async (provider) => [provider, await supportedAgentModels(provider)])));
|
|
380
379
|
return Response.json({
|
|
381
380
|
agents: rows,
|
|
382
381
|
catalogs,
|
|
382
|
+
providers: modelKeyProviderChoices,
|
|
383
383
|
models: (await agents.setup()).models,
|
|
384
384
|
});
|
|
385
385
|
})
|
|
@@ -422,12 +422,7 @@ export function agentApprovalRoutes(agents) {
|
|
|
422
422
|
}
|
|
423
423
|
const keyIdPattern = /^cred_[A-Za-z0-9_-]{1,64}$/u;
|
|
424
424
|
const sealRequestSchema = Schema.Struct({
|
|
425
|
-
provider: Schema.Literals(
|
|
426
|
-
"anthropic",
|
|
427
|
-
"openai",
|
|
428
|
-
"openrouter",
|
|
429
|
-
"cloudflare-workers-ai",
|
|
430
|
-
]),
|
|
425
|
+
provider: Schema.Literals(modelKeyProviderChoices.map((choice) => choice.id)),
|
|
431
426
|
accountId: Schema.optional(Schema.String.check(Schema.isPattern(/^[a-f0-9]{32}$/u))),
|
|
432
427
|
label: Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(64)),
|
|
433
428
|
apiKey: Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(16_384)),
|
|
@@ -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;
|
package/dist/channels/binding.js
CHANGED
|
@@ -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
|
|
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 {
|
|
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)
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import type { VisitorSql } from "./visitors.js";
|
|
3
|
+
/** The exact selector of a Discord binding; secrets are never part of it. */
|
|
4
|
+
declare const discordSelectorSchema: z.ZodObject<{
|
|
5
|
+
provider: z.ZodLiteral<"discord">;
|
|
6
|
+
applicationId: z.ZodString;
|
|
7
|
+
publicKey: z.ZodPipe<z.ZodString, z.ZodTransform<string, string>>;
|
|
8
|
+
guildIds: z.ZodArray<z.ZodString>;
|
|
9
|
+
channelIds: z.ZodArray<z.ZodString>;
|
|
10
|
+
}, z.core.$strict>;
|
|
11
|
+
/** One parsed Discord selector. */
|
|
12
|
+
export type DiscordSelector = z.infer<typeof discordSelectorSchema>;
|
|
13
|
+
/** A Discord application's Agent: one owner Agent behind one application. */
|
|
14
|
+
declare const discordBindingSchema: z.ZodObject<{
|
|
15
|
+
bindingId: z.ZodString;
|
|
16
|
+
agentId: z.ZodString;
|
|
17
|
+
selector: z.ZodObject<{
|
|
18
|
+
provider: z.ZodLiteral<"discord">;
|
|
19
|
+
applicationId: z.ZodString;
|
|
20
|
+
publicKey: z.ZodPipe<z.ZodString, z.ZodTransform<string, string>>;
|
|
21
|
+
guildIds: z.ZodArray<z.ZodString>;
|
|
22
|
+
channelIds: z.ZodArray<z.ZodString>;
|
|
23
|
+
}, z.core.$strict>;
|
|
24
|
+
lifecycle: z.ZodEnum<{
|
|
25
|
+
active: "active";
|
|
26
|
+
suspended: "suspended";
|
|
27
|
+
}>;
|
|
28
|
+
authorityVersion: z.ZodNumber;
|
|
29
|
+
persona: z.ZodString;
|
|
30
|
+
}, z.core.$strict>;
|
|
31
|
+
/** One Discord binding. */
|
|
32
|
+
export type DiscordBinding = z.infer<typeof discordBindingSchema>;
|
|
33
|
+
/** Owner input for a new Discord binding, the bot token included. */
|
|
34
|
+
export declare const createDiscordInputSchema: z.ZodObject<{
|
|
35
|
+
agentId: z.ZodString;
|
|
36
|
+
applicationId: z.ZodString;
|
|
37
|
+
publicKey: z.ZodPipe<z.ZodString, z.ZodTransform<string, string>>;
|
|
38
|
+
guildIds: z.ZodArray<z.ZodString>;
|
|
39
|
+
channelIds: z.ZodDefault<z.ZodArray<z.ZodString>>;
|
|
40
|
+
persona: z.ZodDefault<z.ZodString>;
|
|
41
|
+
botToken: z.ZodString;
|
|
42
|
+
}, z.core.$strict>;
|
|
43
|
+
/** Owner input for a new Discord binding. */
|
|
44
|
+
export type CreateDiscordInput = z.input<typeof createDiscordInputSchema>;
|
|
45
|
+
declare const discordFactsSchema: z.ZodObject<{
|
|
46
|
+
agentId: z.ZodString;
|
|
47
|
+
publicKey: z.ZodPipe<z.ZodString, z.ZodTransform<string, string>>;
|
|
48
|
+
applicationId: z.ZodString;
|
|
49
|
+
guildIds: z.ZodArray<z.ZodString>;
|
|
50
|
+
channelIds: z.ZodDefault<z.ZodArray<z.ZodString>>;
|
|
51
|
+
persona: z.ZodDefault<z.ZodString>;
|
|
52
|
+
}, z.core.$strict>;
|
|
53
|
+
/** The same input without the secret, which is sealed before the binding exists. */
|
|
54
|
+
type DiscordBindingFacts = z.input<typeof discordFactsSchema>;
|
|
55
|
+
/** Owner edit of one Discord binding, fenced by the version the owner last read. */
|
|
56
|
+
export declare const updateDiscordInputSchema: z.ZodObject<{
|
|
57
|
+
expectedVersion: z.ZodNumber;
|
|
58
|
+
publicKey: z.ZodOptional<z.ZodPipe<z.ZodString, z.ZodTransform<string, string>>>;
|
|
59
|
+
guildIds: z.ZodOptional<z.ZodArray<z.ZodString>>;
|
|
60
|
+
channelIds: z.ZodOptional<z.ZodArray<z.ZodString>>;
|
|
61
|
+
persona: z.ZodOptional<z.ZodString>;
|
|
62
|
+
lifecycle: z.ZodOptional<z.ZodEnum<{
|
|
63
|
+
active: "active";
|
|
64
|
+
suspended: "suspended";
|
|
65
|
+
}>>;
|
|
66
|
+
botToken: z.ZodOptional<z.ZodString>;
|
|
67
|
+
}, z.core.$strict>;
|
|
68
|
+
/** Owner edit of one Discord binding. */
|
|
69
|
+
export type UpdateDiscordInput = z.input<typeof updateDiscordInputSchema>;
|
|
70
|
+
declare const discordEditSchema: z.ZodObject<{
|
|
71
|
+
lifecycle: z.ZodOptional<z.ZodEnum<{
|
|
72
|
+
active: "active";
|
|
73
|
+
suspended: "suspended";
|
|
74
|
+
}>>;
|
|
75
|
+
expectedVersion: z.ZodNumber;
|
|
76
|
+
publicKey: z.ZodOptional<z.ZodPipe<z.ZodString, z.ZodTransform<string, string>>>;
|
|
77
|
+
guildIds: z.ZodOptional<z.ZodArray<z.ZodString>>;
|
|
78
|
+
channelIds: z.ZodOptional<z.ZodArray<z.ZodString>>;
|
|
79
|
+
persona: z.ZodOptional<z.ZodString>;
|
|
80
|
+
}, z.core.$strict>;
|
|
81
|
+
type DiscordEdit = z.input<typeof discordEditSchema>;
|
|
82
|
+
/** Closed owner failures; routes map each to one status. */
|
|
83
|
+
export declare class DiscordBindingError extends Error {
|
|
84
|
+
readonly code: "not_found" | "version_conflict" | "request_conflict" | "application_taken" | "invalid_input";
|
|
85
|
+
constructor(code: "not_found" | "version_conflict" | "request_conflict" | "application_taken" | "invalid_input");
|
|
86
|
+
}
|
|
87
|
+
/** Is this standalone channel binding a Discord application's? */
|
|
88
|
+
export declare function isDiscordBinding(binding: Readonly<{
|
|
89
|
+
selector: Readonly<{
|
|
90
|
+
provider: string;
|
|
91
|
+
}>;
|
|
92
|
+
}>): binding is DiscordBinding;
|
|
93
|
+
/**
|
|
94
|
+
* Does this guild and channel belong to the binding? An interaction outside
|
|
95
|
+
* the owner's allowlist is not this Agent's to answer.
|
|
96
|
+
*/
|
|
97
|
+
export declare function discordPlaceAllowed(selector: DiscordSelector, place: Readonly<{
|
|
98
|
+
guildId: string;
|
|
99
|
+
channelId: string;
|
|
100
|
+
}>): boolean;
|
|
101
|
+
/**
|
|
102
|
+
* One standalone owner's Discord bindings, behind a SQL port. The owner
|
|
103
|
+
* authorizes the caller; this module fences versions and keeps one binding
|
|
104
|
+
* per Discord application.
|
|
105
|
+
*/
|
|
106
|
+
export declare function createDiscordBindings(options: Readonly<{
|
|
107
|
+
sql: VisitorSql;
|
|
108
|
+
transactionSync: <T>(body: () => T) => T;
|
|
109
|
+
/** Whether the Agent is in this owner's directory. */
|
|
110
|
+
agentExists: (agentId: string) => boolean;
|
|
111
|
+
}>): {
|
|
112
|
+
read: (bindingId: string) => DiscordBinding | null;
|
|
113
|
+
list: () => readonly DiscordBinding[];
|
|
114
|
+
/** Host-only: the sealed credential that holds this binding's bot token. */
|
|
115
|
+
tokenCredentialId: (bindingId: string) => string | null;
|
|
116
|
+
/**
|
|
117
|
+
* The binding this request already created, or null for a new request. A
|
|
118
|
+
* replay must not seal the token again; changed facts conflict.
|
|
119
|
+
*/
|
|
120
|
+
replay: (rawFacts: DiscordBindingFacts, requestId: string) => DiscordBinding | null;
|
|
121
|
+
/**
|
|
122
|
+
* Create once per request identity; a replay returns the first result. The
|
|
123
|
+
* secret is already sealed: `facts` carry none and `tokenCredentialId`
|
|
124
|
+
* names it.
|
|
125
|
+
*/
|
|
126
|
+
create: (rawFacts: DiscordBindingFacts, tokenCredentialId: string, requestId: string) => DiscordBinding;
|
|
127
|
+
/** Apply one edit; a replaced token's new credential id is already sealed. */
|
|
128
|
+
update: (bindingId: string, rawEdit: DiscordEdit, replacementCredentialId: string | null) => DiscordBinding;
|
|
129
|
+
};
|
|
130
|
+
/** The standalone Discord binding owner. */
|
|
131
|
+
export type DiscordBindings = ReturnType<typeof createDiscordBindings>;
|
|
132
|
+
export {};
|
|
@@ -0,0 +1,234 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { discordSnowflakeSchema } from "./binding.js";
|
|
3
|
+
import { channelIds } from "./ids.js";
|
|
4
|
+
/**
|
|
5
|
+
* The Discord channel's neutral binding rules. The owner brings their own
|
|
6
|
+
* Discord application: its id and public key are facts of the binding, and its
|
|
7
|
+
* bot token is sealed elsewhere and only named here by an owner-only column.
|
|
8
|
+
* Fungi holds no Discord credential of its own.
|
|
9
|
+
*/
|
|
10
|
+
/** Ed25519 public key of a Discord application: 32 bytes, as 64 hex digits. */
|
|
11
|
+
const publicKeySchema = z
|
|
12
|
+
.string()
|
|
13
|
+
.regex(/^[0-9a-f]{64}$/iu, "Public key must be 64 hex digits")
|
|
14
|
+
.transform((value) => value.toLowerCase());
|
|
15
|
+
const guildIdsSchema = z.array(discordSnowflakeSchema).min(1).max(16);
|
|
16
|
+
/** Empty means every channel of the bound guilds. */
|
|
17
|
+
const channelIdsSchema = z.array(discordSnowflakeSchema).max(64);
|
|
18
|
+
/** The bot token as Discord issues it: dot-separated base64url segments. */
|
|
19
|
+
const discordBotTokenSchema = z
|
|
20
|
+
.string()
|
|
21
|
+
.regex(/^[\w-]{10,64}\.[\w-]{4,16}\.[\w-]{20,128}$/u, "Invalid bot token");
|
|
22
|
+
/** The exact selector of a Discord binding; secrets are never part of it. */
|
|
23
|
+
const discordSelectorSchema = z.strictObject({
|
|
24
|
+
provider: z.literal("discord"),
|
|
25
|
+
applicationId: discordSnowflakeSchema,
|
|
26
|
+
publicKey: publicKeySchema,
|
|
27
|
+
guildIds: guildIdsSchema,
|
|
28
|
+
channelIds: channelIdsSchema,
|
|
29
|
+
});
|
|
30
|
+
/** A Discord application's Agent: one owner Agent behind one application. */
|
|
31
|
+
const discordBindingSchema = z.strictObject({
|
|
32
|
+
bindingId: z
|
|
33
|
+
.string()
|
|
34
|
+
.refine((value) => channelIds.binding.is(value), "Invalid binding"),
|
|
35
|
+
agentId: z.string().min(1).max(256),
|
|
36
|
+
selector: discordSelectorSchema,
|
|
37
|
+
lifecycle: z.enum(["active", "suspended"]),
|
|
38
|
+
/** Increments on every owner edit of this binding. */
|
|
39
|
+
authorityVersion: z.number().int().positive(),
|
|
40
|
+
/** Owner persona text, placed after the fixed channel preamble. */
|
|
41
|
+
persona: z.string().max(4_000),
|
|
42
|
+
});
|
|
43
|
+
/** Owner input for a new Discord binding, the bot token included. */
|
|
44
|
+
export const createDiscordInputSchema = z.strictObject({
|
|
45
|
+
agentId: z.string().min(1).max(256),
|
|
46
|
+
applicationId: discordSnowflakeSchema,
|
|
47
|
+
publicKey: publicKeySchema,
|
|
48
|
+
guildIds: guildIdsSchema,
|
|
49
|
+
channelIds: channelIdsSchema.default([]),
|
|
50
|
+
persona: z.string().max(4_000).default(""),
|
|
51
|
+
botToken: discordBotTokenSchema,
|
|
52
|
+
});
|
|
53
|
+
const discordFactsSchema = createDiscordInputSchema.omit({ botToken: true });
|
|
54
|
+
/** Owner edit of one Discord binding, fenced by the version the owner last read. */
|
|
55
|
+
export const updateDiscordInputSchema = z.strictObject({
|
|
56
|
+
expectedVersion: z.number().int().positive(),
|
|
57
|
+
publicKey: publicKeySchema.optional(),
|
|
58
|
+
guildIds: guildIdsSchema.optional(),
|
|
59
|
+
channelIds: channelIdsSchema.optional(),
|
|
60
|
+
persona: z.string().max(4_000).optional(),
|
|
61
|
+
lifecycle: z.enum(["active", "suspended"]).optional(),
|
|
62
|
+
/** Replace the sealed bot token. */
|
|
63
|
+
botToken: discordBotTokenSchema.optional(),
|
|
64
|
+
});
|
|
65
|
+
const discordEditSchema = updateDiscordInputSchema.omit({ botToken: true });
|
|
66
|
+
/** Closed owner failures; routes map each to one status. */
|
|
67
|
+
export class DiscordBindingError extends Error {
|
|
68
|
+
code;
|
|
69
|
+
constructor(code) {
|
|
70
|
+
super(code);
|
|
71
|
+
this.code = code;
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
/** Is this standalone channel binding a Discord application's? */
|
|
75
|
+
export function isDiscordBinding(binding) {
|
|
76
|
+
return binding.selector.provider === "discord";
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* Does this guild and channel belong to the binding? An interaction outside
|
|
80
|
+
* the owner's allowlist is not this Agent's to answer.
|
|
81
|
+
*/
|
|
82
|
+
export function discordPlaceAllowed(selector, place) {
|
|
83
|
+
return (selector.guildIds.includes(place.guildId) &&
|
|
84
|
+
(selector.channelIds.length === 0 ||
|
|
85
|
+
selector.channelIds.includes(place.channelId)));
|
|
86
|
+
}
|
|
87
|
+
const payloadRow = z.strictObject({ payload: z.string() });
|
|
88
|
+
const receiptRow = payloadRow.extend({ input_json: z.string().nullable() });
|
|
89
|
+
const tokenRow = z.strictObject({ token_credential_id: z.string() });
|
|
90
|
+
const requestIdSchema = z.string().min(1).max(128);
|
|
91
|
+
/**
|
|
92
|
+
* One standalone owner's Discord bindings, behind a SQL port. The owner
|
|
93
|
+
* authorizes the caller; this module fences versions and keeps one binding
|
|
94
|
+
* per Discord application.
|
|
95
|
+
*/
|
|
96
|
+
export function createDiscordBindings(options) {
|
|
97
|
+
const { sql } = options;
|
|
98
|
+
const ensure = () => {
|
|
99
|
+
sql.exec(`CREATE TABLE IF NOT EXISTS oyster_discord_bindings (
|
|
100
|
+
binding_id TEXT PRIMARY KEY,
|
|
101
|
+
agent_id TEXT NOT NULL,
|
|
102
|
+
application_id TEXT NOT NULL UNIQUE,
|
|
103
|
+
token_credential_id TEXT NOT NULL,
|
|
104
|
+
request_id TEXT UNIQUE,
|
|
105
|
+
input_json TEXT,
|
|
106
|
+
payload TEXT NOT NULL
|
|
107
|
+
) STRICT`);
|
|
108
|
+
};
|
|
109
|
+
const decode = (raw) => discordBindingSchema.parse(JSON.parse(raw.payload));
|
|
110
|
+
const read = (bindingId) => {
|
|
111
|
+
ensure();
|
|
112
|
+
const row = sql
|
|
113
|
+
.exec("SELECT payload FROM oyster_discord_bindings WHERE binding_id=?", bindingId)
|
|
114
|
+
.toArray()[0];
|
|
115
|
+
return row === undefined ? null : decode(payloadRow.parse(row));
|
|
116
|
+
};
|
|
117
|
+
const receipt = (requestId) => {
|
|
118
|
+
ensure();
|
|
119
|
+
const row = sql
|
|
120
|
+
.exec("SELECT input_json,payload FROM oyster_discord_bindings WHERE request_id=?", requestId)
|
|
121
|
+
.toArray()[0];
|
|
122
|
+
return row === undefined ? null : receiptRow.parse(row);
|
|
123
|
+
};
|
|
124
|
+
return {
|
|
125
|
+
read,
|
|
126
|
+
list: () => {
|
|
127
|
+
ensure();
|
|
128
|
+
return sql
|
|
129
|
+
.exec("SELECT payload FROM oyster_discord_bindings ORDER BY binding_id")
|
|
130
|
+
.toArray()
|
|
131
|
+
.map((row) => decode(payloadRow.parse(row)));
|
|
132
|
+
},
|
|
133
|
+
/** Host-only: the sealed credential that holds this binding's bot token. */
|
|
134
|
+
tokenCredentialId: (bindingId) => {
|
|
135
|
+
ensure();
|
|
136
|
+
const row = sql
|
|
137
|
+
.exec("SELECT token_credential_id FROM oyster_discord_bindings WHERE binding_id=?", bindingId)
|
|
138
|
+
.toArray()[0];
|
|
139
|
+
return row === undefined ? null : tokenRow.parse(row).token_credential_id;
|
|
140
|
+
},
|
|
141
|
+
/**
|
|
142
|
+
* The binding this request already created, or null for a new request. A
|
|
143
|
+
* replay must not seal the token again; changed facts conflict.
|
|
144
|
+
*/
|
|
145
|
+
replay: (rawFacts, requestId) => {
|
|
146
|
+
const parsed = discordFactsSchema.safeParse(rawFacts);
|
|
147
|
+
const identity = requestIdSchema.safeParse(requestId);
|
|
148
|
+
if (!parsed.success || !identity.success)
|
|
149
|
+
throw new DiscordBindingError("invalid_input");
|
|
150
|
+
const prior = receipt(identity.data);
|
|
151
|
+
if (prior === null)
|
|
152
|
+
return null;
|
|
153
|
+
if (prior.input_json !== JSON.stringify(parsed.data))
|
|
154
|
+
throw new DiscordBindingError("request_conflict");
|
|
155
|
+
return decode(prior);
|
|
156
|
+
},
|
|
157
|
+
/**
|
|
158
|
+
* Create once per request identity; a replay returns the first result. The
|
|
159
|
+
* secret is already sealed: `facts` carry none and `tokenCredentialId`
|
|
160
|
+
* names it.
|
|
161
|
+
*/
|
|
162
|
+
create: (rawFacts, tokenCredentialId, requestId) => {
|
|
163
|
+
const parsed = discordFactsSchema.safeParse(rawFacts);
|
|
164
|
+
const identity = requestIdSchema.safeParse(requestId);
|
|
165
|
+
if (!parsed.success || !identity.success)
|
|
166
|
+
throw new DiscordBindingError("invalid_input");
|
|
167
|
+
const input = parsed.data;
|
|
168
|
+
const inputJson = JSON.stringify(input);
|
|
169
|
+
return options.transactionSync(() => {
|
|
170
|
+
ensure();
|
|
171
|
+
const prior = receipt(identity.data);
|
|
172
|
+
if (prior !== null) {
|
|
173
|
+
if (prior.input_json !== inputJson)
|
|
174
|
+
throw new DiscordBindingError("request_conflict");
|
|
175
|
+
return decode(prior);
|
|
176
|
+
}
|
|
177
|
+
if (!options.agentExists(input.agentId))
|
|
178
|
+
throw new DiscordBindingError("not_found");
|
|
179
|
+
const taken = sql
|
|
180
|
+
.exec("SELECT 1 FROM oyster_discord_bindings WHERE application_id=?", input.applicationId)
|
|
181
|
+
.toArray();
|
|
182
|
+
if (taken.length > 0)
|
|
183
|
+
throw new DiscordBindingError("application_taken");
|
|
184
|
+
const binding = discordBindingSchema.parse({
|
|
185
|
+
bindingId: channelIds.binding.generate(),
|
|
186
|
+
agentId: input.agentId,
|
|
187
|
+
selector: {
|
|
188
|
+
provider: "discord",
|
|
189
|
+
applicationId: input.applicationId,
|
|
190
|
+
publicKey: input.publicKey,
|
|
191
|
+
guildIds: input.guildIds,
|
|
192
|
+
channelIds: input.channelIds,
|
|
193
|
+
},
|
|
194
|
+
lifecycle: "active",
|
|
195
|
+
authorityVersion: 1,
|
|
196
|
+
persona: input.persona,
|
|
197
|
+
});
|
|
198
|
+
sql.exec("INSERT INTO oyster_discord_bindings (binding_id,agent_id,application_id,token_credential_id,request_id,input_json,payload) VALUES (?,?,?,?,?,?,?)", binding.bindingId, binding.agentId, input.applicationId, tokenCredentialId, identity.data, inputJson, JSON.stringify(binding));
|
|
199
|
+
return binding;
|
|
200
|
+
});
|
|
201
|
+
},
|
|
202
|
+
/** Apply one edit; a replaced token's new credential id is already sealed. */
|
|
203
|
+
update: (bindingId, rawEdit, replacementCredentialId) => {
|
|
204
|
+
const parsed = discordEditSchema.safeParse(rawEdit);
|
|
205
|
+
if (!parsed.success)
|
|
206
|
+
throw new DiscordBindingError("invalid_input");
|
|
207
|
+
const edit = parsed.data;
|
|
208
|
+
return options.transactionSync(() => {
|
|
209
|
+
const current = read(bindingId);
|
|
210
|
+
if (current === null)
|
|
211
|
+
throw new DiscordBindingError("not_found");
|
|
212
|
+
if (current.authorityVersion !== edit.expectedVersion)
|
|
213
|
+
throw new DiscordBindingError("version_conflict");
|
|
214
|
+
const next = discordBindingSchema.parse({
|
|
215
|
+
...current,
|
|
216
|
+
selector: {
|
|
217
|
+
...current.selector,
|
|
218
|
+
publicKey: edit.publicKey ?? current.selector.publicKey,
|
|
219
|
+
guildIds: edit.guildIds ?? current.selector.guildIds,
|
|
220
|
+
channelIds: edit.channelIds ?? current.selector.channelIds,
|
|
221
|
+
},
|
|
222
|
+
lifecycle: edit.lifecycle ?? current.lifecycle,
|
|
223
|
+
persona: edit.persona ?? current.persona,
|
|
224
|
+
authorityVersion: current.authorityVersion + 1,
|
|
225
|
+
});
|
|
226
|
+
if (replacementCredentialId === null)
|
|
227
|
+
sql.exec("UPDATE oyster_discord_bindings SET payload=? WHERE binding_id=?", JSON.stringify(next), bindingId);
|
|
228
|
+
else
|
|
229
|
+
sql.exec("UPDATE oyster_discord_bindings SET payload=?, token_credential_id=? WHERE binding_id=?", JSON.stringify(next), replacementCredentialId, bindingId);
|
|
230
|
+
return next;
|
|
231
|
+
});
|
|
232
|
+
},
|
|
233
|
+
};
|
|
234
|
+
}
|