@fungi.computer/oyster 0.21.9 → 0.22.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,225 @@
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
+ /** How long an Agent has to answer before the interaction token lapses. */
27
+ export const DISCORD_ANSWER_WINDOW_MS = 13 * 60_000;
28
+ /** One settlement read waits at most this long (Shiitake allows 30 s). */
29
+ export const DISCORD_SETTLEMENT_POLL_MS = 25_000;
30
+ /** What a member is told when intake says no. */
31
+ export const discordDenial = {
32
+ unmapped: "This Agent is not available right now.",
33
+ suspended: "This Agent is paused.",
34
+ banned: "You cannot ask this Agent anything.",
35
+ too_long: "That message is too long.",
36
+ party_daily_limit: "You have reached today's limit. Try again tomorrow.",
37
+ new_party_limit: "This Agent is busy right now. Try again soon.",
38
+ rate_limited: "This Agent is busy right now. Try again soon.",
39
+ event_conflict: "That message could not be accepted.",
40
+ };
41
+ /** How far a request's signed timestamp may sit from now, in seconds. */
42
+ const SIGNATURE_MAX_SKEW_SECONDS = 300;
43
+ const optionSchema = z.object({
44
+ name: z.string(),
45
+ value: z.union([z.string(), z.number(), z.boolean()]).optional(),
46
+ });
47
+ const userSchema = z.object({ id: discordSnowflakeSchema });
48
+ const placeFields = {
49
+ id: discordSnowflakeSchema,
50
+ application_id: discordSnowflakeSchema,
51
+ token: z.string().min(1).max(512),
52
+ guild_id: discordSnowflakeSchema.optional(),
53
+ channel_id: discordSnowflakeSchema.optional(),
54
+ member: z.object({ user: userSchema }).optional(),
55
+ user: userSchema.optional(),
56
+ };
57
+ /** The interaction types we answer; any other type fails to decode. */
58
+ export const interactionSchema = z.discriminatedUnion("type", [
59
+ z.object({
60
+ type: z.literal(1),
61
+ id: discordSnowflakeSchema,
62
+ application_id: discordSnowflakeSchema,
63
+ }),
64
+ z.object({
65
+ ...placeFields,
66
+ type: z.literal(2),
67
+ data: z.object({
68
+ name: z.string(),
69
+ options: z.array(optionSchema).optional(),
70
+ }),
71
+ }),
72
+ z.object({
73
+ ...placeFields,
74
+ type: z.literal(3),
75
+ data: z.object({ custom_id: z.string() }),
76
+ }),
77
+ z.object({
78
+ ...placeFields,
79
+ type: z.literal(5),
80
+ data: z.object({
81
+ custom_id: z.string(),
82
+ components: z.array(z.object({
83
+ components: z.array(z.object({ custom_id: z.string(), value: z.string() })),
84
+ })),
85
+ }),
86
+ }),
87
+ ]);
88
+ function bytesOf(hex) {
89
+ const decoded = Hex.decode(hex);
90
+ return Result.isSuccess(decoded) ? new Uint8Array(decoded.success) : null;
91
+ }
92
+ /**
93
+ * Verify Discord's Ed25519 signature over `timestamp + body` with WebCrypto.
94
+ * The timestamp is also bounded, so a captured request cannot be replayed
95
+ * later.
96
+ */
97
+ export async function verifyDiscordRequest(input) {
98
+ if (input.signature === undefined || input.timestamp === undefined)
99
+ return "missing";
100
+ const signature = bytesOf(input.signature);
101
+ const publicKey = bytesOf(input.publicKey);
102
+ const signedAt = Number(input.timestamp);
103
+ if (signature === null || publicKey === null || !Number.isFinite(signedAt))
104
+ return "malformed";
105
+ if (Math.abs(input.nowSeconds - signedAt) > SIGNATURE_MAX_SKEW_SECONDS)
106
+ return "stale";
107
+ const key = await crypto.subtle.importKey("raw", publicKey, { name: "Ed25519" }, false, ["verify"]);
108
+ const valid = await crypto.subtle.verify("Ed25519", key, signature, new TextEncoder().encode(input.timestamp + input.body));
109
+ return valid ? "verified" : "invalid";
110
+ }
111
+ /** Interaction callback types we send. */
112
+ const CALLBACK = { pong: 1, message: 4, deferred: 5, modal: 9 };
113
+ /** Message flag: only the member who triggered the interaction sees it. */
114
+ const EPHEMERAL = 64;
115
+ /** The answer to Discord's endpoint check. */
116
+ export const pongResponse = { type: CALLBACK.pong };
117
+ /** Tell the member the Agent is working; the answer follows by webhook. */
118
+ export const deferredResponse = { type: CALLBACK.deferred };
119
+ /** A one-off notice only the member sees, such as a refusal. */
120
+ export function ephemeralResponse(content) {
121
+ return {
122
+ type: CALLBACK.message,
123
+ data: {
124
+ content: content.slice(0, DISCORD_MESSAGE_LIMIT),
125
+ flags: EPHEMERAL,
126
+ allowed_mentions: { parse: [] },
127
+ },
128
+ };
129
+ }
130
+ /** The modal a Reply button opens: one paragraph input. */
131
+ export const replyModalResponse = {
132
+ type: CALLBACK.modal,
133
+ data: {
134
+ custom_id: REPLY_ID,
135
+ title: "Reply",
136
+ components: [
137
+ {
138
+ type: 1,
139
+ components: [
140
+ {
141
+ type: 4,
142
+ custom_id: REPLY_TEXT_ID,
143
+ label: "Your reply",
144
+ style: 2,
145
+ min_length: 1,
146
+ max_length: DISCORD_ASK_LIMIT,
147
+ required: true,
148
+ },
149
+ ],
150
+ },
151
+ ],
152
+ },
153
+ };
154
+ /** The Reply button attached to every Agent answer. */
155
+ const replyRow = [
156
+ {
157
+ type: 1,
158
+ components: [{ type: 2, style: 2, label: "Reply", custom_id: REPLY_ID }],
159
+ },
160
+ ];
161
+ /** The body of a follow-up that fills the deferred message. */
162
+ function followUpBody(content, withReply) {
163
+ return {
164
+ content: content.slice(0, DISCORD_MESSAGE_LIMIT),
165
+ // Model text never pings anyone.
166
+ allowed_mentions: { parse: [] },
167
+ components: withReply ? replyRow : [],
168
+ };
169
+ }
170
+ /** Quote a member's modal reply so the thread reads in order. */
171
+ export function quoted(text) {
172
+ return text
173
+ .slice(0, 300)
174
+ .split("\n")
175
+ .map((line) => `> ${line}`)
176
+ .join("\n");
177
+ }
178
+ /**
179
+ * Fill the deferred message with the Agent's answer. The interaction token is
180
+ * the credential: no bot token is involved.
181
+ */
182
+ export async function patchOriginal(send, input) {
183
+ const response = await send(`${DISCORD_API}/webhooks/${input.applicationId}/${input.interactionToken}/messages/@original`, {
184
+ method: "PATCH",
185
+ headers: { "content-type": "application/json" },
186
+ body: JSON.stringify(followUpBody(input.content, input.withReply)),
187
+ signal: AbortSignal.timeout(15_000),
188
+ });
189
+ await response.body?.cancel();
190
+ return response.ok;
191
+ }
192
+ /** The `/ask` application command, as Discord registers it. */
193
+ const askCommand = {
194
+ name: ASK_COMMAND,
195
+ type: 1,
196
+ description: "Ask this Agent a question",
197
+ dm_permission: false,
198
+ options: [
199
+ {
200
+ type: 3,
201
+ name: ASK_OPTION,
202
+ description: "What do you want to ask?",
203
+ required: true,
204
+ min_length: 1,
205
+ max_length: DISCORD_ASK_LIMIT,
206
+ },
207
+ ],
208
+ };
209
+ /**
210
+ * Register `/ask` in one guild with the owner's bot token. Creating by name
211
+ * updates an existing `/ask` and leaves the owner's other commands alone.
212
+ */
213
+ export async function registerAskCommand(send, input) {
214
+ const response = await send(`${DISCORD_API}/applications/${input.applicationId}/guilds/${input.guildId}/commands`, {
215
+ method: "POST",
216
+ headers: {
217
+ authorization: `Bot ${input.botToken}`,
218
+ "content-type": "application/json",
219
+ },
220
+ body: JSON.stringify(askCommand),
221
+ signal: AbortSignal.timeout(15_000),
222
+ });
223
+ await response.body?.cancel();
224
+ return response.ok;
225
+ }
@@ -1,4 +1,5 @@
1
1
  import type { Api, Model } from "@earendil-works/pi-ai";
2
+ import { type StandaloneModelKeyProvider } from "./model-key-providers.js";
2
3
  import * as Schema from "effect/Schema";
3
4
  /**
4
5
  * A credential-source address, not credential material. `byok` names one of the
@@ -21,19 +22,6 @@ export declare class AgentModelRefused extends Error {
21
22
  readonly reason: AgentModelRefusal;
22
23
  constructor(reason: AgentModelRefusal);
23
24
  }
24
- /**
25
- * Pi 1.3's Model/getModels contract has no tool-calling flag (reasoning and
26
- * supportsStrictMode are not capability flags). Until it does, keep this small
27
- * Agent shortlist beside the existing catalog, never copy names or prices.
28
- * DeepSeek passed Grove's write/read proof on 2026-11-10; Granite failed its
29
- * first execute call. Kimi is the existing Workers AI Agent default. The other
30
- * entries are the providers' tool-capable Sonnet/Luna choices:
31
- * https://platform.claude.com/docs/en/agents-and-tools/tool-use/overview
32
- * https://platform.openai.com/docs/guides/function-calling
33
- * OpenRouter exposes that same Luna model. Other entries remain selectable as chat only;
34
- * this is an admission policy for Agents, not a claim they cannot chat.
35
- * Replace this fallback when Pi exposes its source's tool-calling flag.
36
- */
37
25
  export declare function agentModelSupportsTools(model: Pick<Model<Api>, "provider" | "id">): boolean;
38
26
  /** A supported model and Pi's USD prices per million tokens, without credentials. */
39
27
  export type SupportedAgentModel = Readonly<{
@@ -44,7 +32,7 @@ export type SupportedAgentModel = Readonly<{
44
32
  tools: boolean;
45
33
  }>;
46
34
  /** Pi's full catalog: verified tools first, then chat only; each group by price. */
47
- export declare function supportedAgentModels(provider: "anthropic" | "openai" | "openrouter" | "cloudflare-workers-ai"): Promise<readonly SupportedAgentModel[]>;
35
+ export declare function supportedAgentModels(provider: StandaloneModelKeyProvider): Promise<readonly SupportedAgentModel[]>;
48
36
  /**
49
37
  * An Agent with no saved choice runs on a model its host can reach, chosen when
50
38
  * it runs: Workers AI where a Cloudflare account answers, then the Fungi
@@ -1,6 +1,6 @@
1
1
  import { ModelPreferenceSchema } from "@fungi.computer/shiitake/model-preference";
2
2
  import { cloudflareWorkersAIProvider } from "@earendil-works/pi-ai/providers/cloudflare-workers-ai";
3
- import { isModelKeyProvider } from "@fungi.computer/veil/model-keys";
3
+ import { isStandaloneModelKeyProvider as isStandaloneProvider, } from "./model-key-providers.js";
4
4
  import * as Schema from "effect/Schema";
5
5
  /**
6
6
  * A credential-source address, not credential material. `byok` names one of the
@@ -27,21 +27,45 @@ const defaultChoice = {
27
27
  modelId: "@cf/moonshotai/kimi-k2.6",
28
28
  },
29
29
  };
30
- /** Pi's maintained catalog for a provider a key may be brought for. */
31
- async function byokCatalog(provider) {
32
- if (provider === "cloudflare-workers-ai")
33
- return cloudflareWorkersAIProvider().getModels();
34
- if (provider === "anthropic")
35
- return (await import("@earendil-works/pi-ai/providers/anthropic"))
36
- .anthropicProvider()
37
- .getModels();
38
- if (provider === "openai")
39
- return (await import("@earendil-works/pi-ai/providers/openai"))
40
- .openaiProvider()
41
- .getModels();
42
- return (await import("@earendil-works/pi-ai/providers/openrouter"))
30
+ /** Pi's maintained catalog for each provider a key may be brought for. */
31
+ const piCatalogs = {
32
+ "cloudflare-workers-ai": () => Promise.resolve(cloudflareWorkersAIProvider().getModels()),
33
+ anthropic: async () => (await import("@earendil-works/pi-ai/providers/anthropic"))
34
+ .anthropicProvider()
35
+ .getModels(),
36
+ openai: async () => (await import("@earendil-works/pi-ai/providers/openai"))
37
+ .openaiProvider()
38
+ .getModels(),
39
+ openrouter: async () => (await import("@earendil-works/pi-ai/providers/openrouter"))
43
40
  .openrouterProvider()
44
- .getModels();
41
+ .getModels(),
42
+ google: async () => (await import("@earendil-works/pi-ai/providers/google"))
43
+ .googleProvider()
44
+ .getModels(),
45
+ xai: async () => (await import("@earendil-works/pi-ai/providers/xai"))
46
+ .xaiProvider()
47
+ .getModels(),
48
+ groq: async () => (await import("@earendil-works/pi-ai/providers/groq"))
49
+ .groqProvider()
50
+ .getModels(),
51
+ mistral: async () => (await import("@earendil-works/pi-ai/providers/mistral"))
52
+ .mistralProvider()
53
+ .getModels(),
54
+ deepseek: async () => (await import("@earendil-works/pi-ai/providers/deepseek"))
55
+ .deepseekProvider()
56
+ .getModels(),
57
+ cerebras: async () => (await import("@earendil-works/pi-ai/providers/cerebras"))
58
+ .cerebrasProvider()
59
+ .getModels(),
60
+ together: async () => (await import("@earendil-works/pi-ai/providers/together"))
61
+ .togetherProvider()
62
+ .getModels(),
63
+ moonshotai: async () => (await import("@earendil-works/pi-ai/providers/moonshotai"))
64
+ .moonshotaiProvider()
65
+ .getModels(),
66
+ };
67
+ function byokCatalog(provider) {
68
+ return piCatalogs[provider]();
45
69
  }
46
70
  /**
47
71
  * Pi 1.3's Model/getModels contract has no tool-calling flag (reasoning and
@@ -56,20 +80,30 @@ async function byokCatalog(provider) {
56
80
  * this is an admission policy for Agents, not a claim they cannot chat.
57
81
  * Replace this fallback when Pi exposes its source's tool-calling flag.
58
82
  */
83
+ const agentToolModels = {
84
+ "cloudflare-workers-ai": [
85
+ "@cf/deepseek-ai/deepseek-v4-flash-0731",
86
+ "@cf/moonshotai/kimi-k2.6",
87
+ ],
88
+ anthropic: ["claude-sonnet-4-6"],
89
+ openai: ["gpt-6-luna", "openai/gpt-6-luna"],
90
+ openrouter: ["openai/gpt-6-luna"],
91
+ // Each is the provider's documented function-calling flagship; none has
92
+ // had a Grove write/read proof yet, unlike DeepSeek above.
93
+ google: ["gemini-2.5-pro"],
94
+ xai: ["grok-4.3"],
95
+ groq: ["openai/gpt-oss-120b", "llama-3.3-70b-versatile"],
96
+ mistral: ["mistral-large-latest", "mistral-medium-latest"],
97
+ deepseek: ["deepseek-v4-pro", "deepseek-flash"],
98
+ cerebras: ["gpt-oss-120b"],
99
+ together: ["openai/gpt-oss-120b"],
100
+ moonshotai: ["kimi-k3"],
101
+ };
59
102
  export function agentModelSupportsTools(model) {
60
- switch (model.provider) {
61
- case "cloudflare-workers-ai":
62
- return (model.id === "@cf/deepseek-ai/deepseek-v4-flash-0731" ||
63
- model.id === "@cf/moonshotai/kimi-k2.6");
64
- case "anthropic":
65
- return model.id === "claude-sonnet-4-6";
66
- case "openai":
67
- return model.id === "gpt-6-luna" || model.id === "openai/gpt-6-luna";
68
- case "openrouter":
69
- return model.id === "openai/gpt-6-luna";
70
- default:
71
- return false;
72
- }
103
+ if (!isStandaloneProvider(model.provider))
104
+ return false;
105
+ const admitted = agentToolModels[model.provider];
106
+ return admitted.includes(model.id);
73
107
  }
74
108
  /** Pi's full catalog: verified tools first, then chat only; each group by price. */
75
109
  export async function supportedAgentModels(provider) {
@@ -101,10 +135,7 @@ export async function resolveDefaultChoice(ready) {
101
135
  model: { providerId: "openai", modelId: "openai/gpt-6-luna" },
102
136
  };
103
137
  for (const { keyId, provider } of ready.keys) {
104
- if (provider !== "anthropic" &&
105
- provider !== "openai" &&
106
- provider !== "openrouter" &&
107
- provider !== "cloudflare-workers-ai")
138
+ if (!isStandaloneProvider(provider))
108
139
  continue;
109
140
  const catalog = (await byokCatalog(provider)).filter(agentModelSupportsTools);
110
141
  const model = catalog.find((entry) => "default" in entry && entry.default === true) ??
@@ -122,9 +153,8 @@ export async function resolveDefaultChoice(ready) {
122
153
  export async function selectAgentModel(choice) {
123
154
  const { providerId, modelId, reasoning } = choice.model;
124
155
  if (choice.keySource === "byok") {
125
- // Only a catalogued provider's own models; an OpenAI-compatible base has none.
126
- if (providerId !== "cloudflare-workers-ai" &&
127
- (!isModelKeyProvider(providerId) || providerId === "openai-compatible"))
156
+ // Only a catalogued provider's own models.
157
+ if (!isStandaloneProvider(providerId))
128
158
  throw new AgentModelRefused("unsupported_key_source");
129
159
  const found = (await byokCatalog(providerId)).find((item) => item.id === modelId);
130
160
  if (found === undefined || (reasoning !== undefined && !found.reasoning))
@@ -4,6 +4,9 @@ import { type ChannelConversation, type ChannelConversations } from "../channels
4
4
  import { type WebsiteTranscript } from "@fungi.computer/nacre/website-channels";
5
5
  import { type CreateWebsiteInput, type UpdateWebsiteInput, type WebsiteBinding } from "../channels/web-binding.js";
6
6
  import { type WebsiteRefusal, type WebsiteSite } from "./website-channels.js";
7
+ import { type CreateDiscordInput, type DiscordBinding, type UpdateDiscordInput } from "../channels/discord-binding.js";
8
+ import { type DiscordAsk } from "../channels/discord-interactions.js";
9
+ import { type DiscordRefusal } from "./discord-channels.js";
7
10
  import { type ProvenVisitor } from "./visitor-proof.js";
8
11
  import type { VisitorReadOptions } from "../channels/conversations.js";
9
12
  import { type StandaloneMachineLinkBindings, type StandaloneMachineJoinResult } from "./machine-link.js";
@@ -108,12 +111,12 @@ export declare abstract class StandaloneAgentBase<Env extends StandaloneAgentEnv
108
111
  /** The website bindings that name this Agent, as the directory last said. */
109
112
  private readonly websiteBindings;
110
113
  /** The owner's current record of one binding; hosts and tests supply it. */
111
- protected readChannelBinding(bindingId: string): Promise<WebsiteBinding | null>;
114
+ protected readChannelBinding(bindingId: string): Promise<WebsiteBinding | DiscordBinding | null>;
112
115
  /**
113
116
  * Read one binding afresh from its owner: suspension, persona and edits are
114
117
  * never stale. A binding that names another Agent is not this Agent's.
115
118
  */
116
- protected loadChannelBinding(bindingId: string): Promise<WebsiteBinding | null>;
119
+ protected loadChannelBinding(bindingId: string): Promise<WebsiteBinding | DiscordBinding | null>;
117
120
  /** A web host shares its edge's private assertion key with its Agent. */
118
121
  protected channelProofKey(): string | null;
119
122
  /**
@@ -130,6 +133,14 @@ export declare abstract class StandaloneAgentBase<Env extends StandaloneAgentEnv
130
133
  * visitor's Session adds the fixed channel rules and the owner's persona to
131
134
  * the Agent's own instructions, never replacing them. */
132
135
  protected channelInstructions(source: CloudflareShiitakeOptions["instructions"]): CloudflareShiitakeOptions["instructions"];
136
+ /**
137
+ * A verified Discord question for this Agent. The public edge has already
138
+ * checked the application's signature and the guild and channel; this
139
+ * accepts the work and returns at once, and the answer follows by the
140
+ * interaction webhook once the run settles.
141
+ */
142
+ askDiscord(bindingId: string, ask: DiscordAsk): void;
143
+ private answerDiscord;
133
144
  /** Owner read of one website's conversations; the host admits the owner first. */
134
145
  websiteConversations(bindingId: string): Promise<readonly ChannelConversation[]>;
135
146
  /** Owner read of one conversation of a website, from its Session. */
@@ -432,8 +443,29 @@ export declare class AgentDirectory extends DurableObject<StandaloneAgentEnv> {
432
443
  websiteCreate(principal: TenantPrincipal, input: CreateWebsiteInput, requestId: string): WebsiteBinding | WebsiteRefusal;
433
444
  /** Owner-only edit, fenced by the version the owner last read. */
434
445
  websiteUpdate(principal: TenantPrincipal, bindingId: string, input: UpdateWebsiteInput): WebsiteBinding | WebsiteRefusal;
435
- /** Host-only: the binding a website Agent serves, read fresh on every use. */
436
- websiteBinding(bindingId: string): WebsiteBinding | null;
446
+ private discordOwner;
447
+ private discords;
448
+ private discordVault;
449
+ /** Owner read of every Discord application bound to one of this tenant's Agents. */
450
+ discordList(principal: TenantPrincipal): readonly DiscordBinding[] | DiscordRefusal;
451
+ /**
452
+ * Owner-only: bind the owner's own Discord application to a chosen Agent. The
453
+ * bot token is sealed under the instance credential key before the binding
454
+ * exists and is never returned, listed or logged.
455
+ */
456
+ discordCreate(principal: TenantPrincipal, input: CreateDiscordInput, requestId: string): Promise<DiscordBinding | DiscordRefusal>;
457
+ /** Owner-only edit, fenced by the version the owner last read. */
458
+ discordUpdate(principal: TenantPrincipal, bindingId: string, input: UpdateDiscordInput): Promise<DiscordBinding | DiscordRefusal>;
459
+ /**
460
+ * Owner-only: register `/ask` in each bound guild with the sealed bot token,
461
+ * which stays inside this call. Discord says which guilds took it.
462
+ */
463
+ discordRegisterCommands(principal: TenantPrincipal, bindingId: string): Promise<Readonly<{
464
+ registered: readonly string[];
465
+ failed: readonly string[];
466
+ }> | DiscordRefusal>;
467
+ /** Host-only: the website or Discord binding an Agent serves, read fresh on every use. */
468
+ channelBinding(bindingId: string): WebsiteBinding | DiscordBinding | null;
437
469
  /** Host-only public lookup: a site key resolves to its site, or to nothing. */
438
470
  websiteSite(siteKey: string): WebsiteSite | null;
439
471
  websiteMint(bindingId: string, siteKey: string, addressHash: string): Promise<import("../channels/visitors.js").VisitorGrant>;