@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.
Files changed (36) hide show
  1. package/dist/agents.d.ts +1 -0
  2. package/dist/agents.js +4 -9
  3. package/dist/channels/binding.d.ts +1 -0
  4. package/dist/channels/binding.js +3 -1
  5. package/dist/channels/conversations.d.ts +1 -0
  6. package/dist/channels/conversations.js +15 -1
  7. package/dist/channels/discord-binding.d.ts +132 -0
  8. package/dist/channels/discord-binding.js +234 -0
  9. package/dist/channels/discord-interactions.d.ts +253 -0
  10. package/dist/channels/discord-interactions.js +325 -0
  11. package/dist/channels/discord-replies.d.ts +65 -0
  12. package/dist/channels/discord-replies.js +182 -0
  13. package/dist/embed-metafiles.js +1 -1
  14. package/dist/embed-scripts.js +1 -1
  15. package/dist/page-script.js +1 -1
  16. package/dist/standalone/agent-model-choice.d.ts +2 -14
  17. package/dist/standalone/agent-model-choice.js +65 -35
  18. package/dist/standalone/agents.d.ts +60 -9
  19. package/dist/standalone/agents.js +244 -11
  20. package/dist/standalone/app-builds-binding.js +1 -1
  21. package/dist/standalone/discord-channels.d.ts +89 -0
  22. package/dist/standalone/discord-channels.js +260 -0
  23. package/dist/standalone/model-key-providers.d.ts +13 -0
  24. package/dist/standalone/model-key-providers.js +11 -0
  25. package/dist/standalone/model-key-vault.d.ts +9 -5
  26. package/dist/standalone/model-key-vault.js +9 -9
  27. package/dist/standalone/owner-routes.js +4 -1
  28. package/dist/standalone/registry.d.ts +5 -2
  29. package/dist/standalone/registry.js +6 -4
  30. package/dist/standalone/website-channels.js +2 -2
  31. package/dist/standalone/worker-routes.d.ts +2 -0
  32. package/dist/standalone/worker-routes.js +1 -0
  33. package/dist/standalone/worker.js +4 -0
  34. package/docs/api/agents.md +36 -10
  35. package/docs/api/workers-git.md +7 -7
  36. package/package.json +12 -12
@@ -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,10 +133,36 @@ 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"];
133
- /** Owner read of one website's conversations; the host admits the owner first. */
134
- websiteConversations(bindingId: string): Promise<readonly ChannelConversation[]>;
135
- /** Owner read of one conversation of a website, from its Session. */
136
- websiteTranscript(bindingId: string, sessionId: string): Promise<WebsiteTranscript | null>;
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. The reply
139
+ * is recorded as owed before anything else, then paid off by the Agent's
140
+ * durable host work: an Agent evicted mid-run still answers when it wakes.
141
+ */
142
+ askDiscord(bindingId: string, ask: DiscordAsk): void;
143
+ private discordReplyOwner;
144
+ private discordReplies;
145
+ /** The Discord replies this Agent owes; a full option override must run it. */
146
+ protected discordReplyWork(): {
147
+ pending: () => {
148
+ due: boolean;
149
+ nextWakeAt: number | null;
150
+ };
151
+ run: () => Promise<void>;
152
+ };
153
+ /** Replies of one Discord binding that never reached Discord; the host admits the owner first. */
154
+ discordUndelivered(bindingId: string): Promise<readonly Readonly<{
155
+ interactionId: string;
156
+ label: string;
157
+ state: "expired" | "failed";
158
+ closedAt: number;
159
+ }>[]>;
160
+ /** One attempt at one owed reply; intake is idempotent per interaction. */
161
+ private deliverDiscord;
162
+ /** Owner read of one binding's conversations; the host admits the owner first. */
163
+ bindingConversations(bindingId: string): Promise<readonly ChannelConversation[]>;
164
+ /** Owner read of one conversation of a binding, from its Session. */
165
+ bindingTranscript(bindingId: string, sessionId: string): Promise<WebsiteTranscript | null>;
137
166
  private channelBinding;
138
167
  private channelSessionDoor;
139
168
  /**
@@ -262,7 +291,8 @@ export declare abstract class StandaloneAgentBase<Env extends StandaloneAgentEnv
262
291
  invalidateMcpConnections(): void;
263
292
  /**
264
293
  * A full override must retain channelSource and channelInstructions:
265
- * dropping them removes a suspended website's run refusal and turn capture.
294
+ * dropping them removes a suspended website's run refusal and turn capture,
295
+ * and it must run discordReplyWork or an evicted Discord run never answers.
266
296
  */
267
297
  protected shiitakeOptions(): Promise<CloudflareShiitakeOptions>;
268
298
  /** Send an installation-admitted message through fleet Session operations. */
@@ -432,8 +462,29 @@ export declare class AgentDirectory extends DurableObject<StandaloneAgentEnv> {
432
462
  websiteCreate(principal: TenantPrincipal, input: CreateWebsiteInput, requestId: string): WebsiteBinding | WebsiteRefusal;
433
463
  /** Owner-only edit, fenced by the version the owner last read. */
434
464
  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;
465
+ private discordOwner;
466
+ private discords;
467
+ private discordVault;
468
+ /** Owner read of every Discord application bound to one of this tenant's Agents. */
469
+ discordList(principal: TenantPrincipal): readonly DiscordBinding[] | DiscordRefusal;
470
+ /**
471
+ * Owner-only: bind the owner's own Discord application to a chosen Agent. The
472
+ * bot token is sealed under the instance credential key before the binding
473
+ * exists and is never returned, listed or logged.
474
+ */
475
+ discordCreate(principal: TenantPrincipal, input: CreateDiscordInput, requestId: string): Promise<DiscordBinding | DiscordRefusal>;
476
+ /** Owner-only edit, fenced by the version the owner last read. */
477
+ discordUpdate(principal: TenantPrincipal, bindingId: string, input: UpdateDiscordInput): Promise<DiscordBinding | DiscordRefusal>;
478
+ /**
479
+ * Owner-only: register `/ask` in each bound guild with the sealed bot token,
480
+ * which stays inside this call. Discord says which guilds took it.
481
+ */
482
+ discordRegisterCommands(principal: TenantPrincipal, bindingId: string): Promise<Readonly<{
483
+ registered: readonly string[];
484
+ failed: readonly string[];
485
+ }> | DiscordRefusal>;
486
+ /** Host-only: the website or Discord binding an Agent serves, read fresh on every use. */
487
+ channelBinding(bindingId: string): WebsiteBinding | DiscordBinding | null;
437
488
  /** Host-only public lookup: a site key resolves to its site, or to nothing. */
438
489
  websiteSite(siteKey: string): WebsiteSite | null;
439
490
  websiteMint(bindingId: string, siteKey: string, addressHash: string): Promise<import("../channels/visitors.js").VisitorGrant>;
@@ -12,6 +12,10 @@ import { transcriptLine, } from "@fungi.computer/nacre/website-channels";
12
12
  import { personChannelInstructions, } from "../channels/web-binding.js";
13
13
  import { decideChannelRunSafely } from "../channels/run-decision.js";
14
14
  import { createWebsiteChannelOwner, websiteOutcome, } from "./website-channels.js";
15
+ import { createDiscordReplies, } from "../channels/discord-replies.js";
16
+ import { isDiscordBinding, createDiscordBindings, createDiscordInputSchema, updateDiscordInputSchema, } from "../channels/discord-binding.js";
17
+ import { DISCORD_SETTLEMENT_WAIT_MS, discordDenial, discordFailureText, patchOriginal, postFollowUp, quoted, splitDiscordMessage, registerAskCommand, } from "../channels/discord-interactions.js";
18
+ import { discordOutcome, sealDiscordToken, } from "./discord-channels.js";
15
19
  import { channelSessionDoor } from "./channel-session-door.js";
16
20
  import { createAuthenticatedVisitorChannel } from "../channels/visitor-channel.js";
17
21
  import { verifyVisitor } from "./visitor-proof.js";
@@ -36,6 +40,7 @@ import { homeContract } from "@fungi.computer/shiitake-extensions/home";
36
40
  import { DurableObject } from "cloudflare:workers";
37
41
  import { ShiitakeDO } from "@fungi.computer/shiitake/cloudflare";
38
42
  import { agentStoreKeeping } from "./agent-store.js";
43
+ import { CredentialError, } from "@fungi.computer/veil/credential-store";
39
44
  import { createInstanceCredentialStore, createModelKeyVault, ModelKeyRefused, } from "./model-key-vault.js";
40
45
  import { agentArchiveOwner } from "./agent-archive-owner.js";
41
46
  import { agentArchiveProjection } from "../agent-archive-projection.js";
@@ -297,7 +302,7 @@ export class StandaloneAgentBase extends ShiitakeDO {
297
302
  websiteBindings = new Map();
298
303
  /** The owner's current record of one binding; hosts and tests supply it. */
299
304
  readChannelBinding(bindingId) {
300
- return agentDirectoryForScope(this.env, tenantScope(defaultTenant, this.env.OYSTER_ORIGIN)).websiteBinding(bindingId);
305
+ return agentDirectoryForScope(this.env, tenantScope(defaultTenant, this.env.OYSTER_ORIGIN)).channelBinding(bindingId);
301
306
  }
302
307
  /**
303
308
  * Read one binding afresh from its owner: suspension, persona and edits are
@@ -362,19 +367,132 @@ export class StandaloneAgentBase extends ShiitakeDO {
362
367
  throw new Error("Website channel binding is unavailable");
363
368
  const base = await source.load(input);
364
369
  return {
365
- revision: `${base.revision}+website-${String(decision.binding.authorityVersion)}`,
370
+ revision: `${base.revision}+${decision.binding.selector.provider}-${String(decision.binding.authorityVersion)}`,
366
371
  text: `${base.text}\n\n${personChannelInstructions(decision.binding.persona)}`,
367
372
  };
368
373
  },
369
374
  };
370
375
  }
371
- /** Owner read of one website's conversations; the host admits the owner first. */
372
- async websiteConversations(bindingId) {
376
+ /**
377
+ * A verified Discord question for this Agent. The public edge has already
378
+ * checked the application's signature and the guild and channel. The reply
379
+ * is recorded as owed before anything else, then paid off by the Agent's
380
+ * durable host work: an Agent evicted mid-run still answers when it wakes.
381
+ */
382
+ askDiscord(bindingId, ask) {
383
+ this.discordReplies().record(bindingId, ask);
384
+ this.ctx.waitUntil(this.wakeRuntime().catch((cause) => {
385
+ console.error("discord reply wake failed", cause);
386
+ }));
387
+ }
388
+ discordReplyOwner;
389
+ discordReplies() {
390
+ return (this.discordReplyOwner ??= createDiscordReplies({
391
+ sql: this.ctx.storage.sql,
392
+ now: () => Date.now(),
393
+ deliver: (reply) => this.deliverDiscord(reply),
394
+ onExpired: (interactionId) => {
395
+ console.warn("discord reply expired undelivered", interactionId);
396
+ },
397
+ }));
398
+ }
399
+ /** The Discord replies this Agent owes; a full option override must run it. */
400
+ discordReplyWork() {
401
+ return this.discordReplies().work;
402
+ }
403
+ /** Replies of one Discord binding that never reached Discord; the host admits the owner first. */
404
+ async discordUndelivered(bindingId) {
405
+ const binding = await this.loadChannelBinding(bindingId);
406
+ return binding === null ? [] : this.discordReplies().closed(bindingId);
407
+ }
408
+ /** One attempt at one owed reply; intake is idempotent per interaction. */
409
+ async deliverDiscord(reply) {
410
+ const { ask } = reply;
411
+ const sayPart = async (content, first, withReply) => {
412
+ try {
413
+ return await (first ? patchOriginal : postFollowUp)(fetch, {
414
+ applicationId: ask.applicationId,
415
+ interactionToken: ask.interactionToken,
416
+ content,
417
+ withReply,
418
+ });
419
+ }
420
+ catch (cause) {
421
+ console.warn("discord reply delivery failed", cause instanceof Error ? cause.name : "unknown");
422
+ return "retry";
423
+ }
424
+ };
425
+ const say = (content, withReply) => sayPart(content, true, withReply);
426
+ const binding = await this.loadChannelBinding(reply.bindingId);
427
+ if (binding === null ||
428
+ !isDiscordBinding(binding) ||
429
+ binding.lifecycle !== "active")
430
+ return say("This Agent is not available right now.", false);
431
+ let accepted = reply.accepted;
432
+ if (accepted === null) {
433
+ const result = await this.channelConversations().receive({
434
+ bindingId: reply.bindingId,
435
+ conversation: `${ask.guildId}:${ask.channelId}:${ask.userId}`,
436
+ eventId: ask.interactionId,
437
+ party: {
438
+ kind: "discord-user",
439
+ guildId: ask.guildId,
440
+ userId: ask.userId,
441
+ displayName: ask.displayName,
442
+ },
443
+ text: ask.text,
444
+ });
445
+ if (result.kind === "denied")
446
+ return say(discordDenial[result.reason], false);
447
+ if (result.kind === "held")
448
+ return say("A person has taken over this conversation.", false);
449
+ accepted = { sessionId: result.sessionId, commandId: result.commandId };
450
+ this.discordReplies().attach(reply.interactionId, accepted);
451
+ }
452
+ const session = (await this.shiitake()).session(accepted.sessionId);
453
+ const settlement = await session.readSettlement(accepted.commandId, {
454
+ timeoutMs: DISCORD_SETTLEMENT_WAIT_MS,
455
+ });
456
+ if (settlement === undefined)
457
+ return "waiting";
458
+ const answered = settlement.terminal.outcome === "completed" &&
459
+ settlement.content.trim().length > 0;
460
+ if (!answered) {
461
+ // The host words a model failure on the run's last assistant message;
462
+ // the settlement's own diagnostic only names the runtime's reason.
463
+ const { messages } = await session.read({ limit: 20 });
464
+ const modelFailure = messages
465
+ .toReversed()
466
+ .find(({ value }) => value.role === "assistant" && value.errorMessage !== undefined);
467
+ return say(discordFailureText({
468
+ outcome: settlement.terminal.outcome,
469
+ diagnostic: modelFailure?.value.role === "assistant"
470
+ ? (modelFailure.value.errorMessage ?? null)
471
+ : settlement.terminal.diagnostic,
472
+ }), false);
473
+ }
474
+ // The member's own quoted words open the first message; the answer follows
475
+ // in as many messages as it takes, in order.
476
+ const parts = splitDiscordMessage(ask.echo === undefined
477
+ ? settlement.content
478
+ : `${quoted(ask.echo)}\n\n${settlement.content}`);
479
+ let done = reply.deliveredParts;
480
+ for (; done < parts.length; done += 1) {
481
+ const last = done === parts.length - 1;
482
+ const outcome = await sayPart(parts[done] ?? "", done === 0, last);
483
+ if (outcome !== "delivered")
484
+ return outcome;
485
+ this.discordReplies().progress(reply.interactionId, done + 1);
486
+ }
487
+ return "delivered";
488
+ }
489
+ /** Owner read of one binding's conversations; the host admits the owner first. */
490
+ async bindingConversations(bindingId) {
373
491
  const binding = await this.loadChannelBinding(bindingId);
374
492
  return binding === null ? [] : this.channelConversations().list(bindingId);
375
493
  }
376
- /** Owner read of one conversation of a website, from its Session. */
377
- async websiteTranscript(bindingId, sessionId) {
494
+ /** Owner read of one conversation of a binding, from its Session. */
495
+ async bindingTranscript(bindingId, sessionId) {
378
496
  const binding = await this.loadChannelBinding(bindingId);
379
497
  const conversation = this.channelConversations().sessionConversation(sessionId);
380
498
  if (binding === null || conversation?.bindingId !== bindingId)
@@ -1047,7 +1165,8 @@ export class StandaloneAgentBase extends ShiitakeDO {
1047
1165
  }
1048
1166
  /**
1049
1167
  * A full override must retain channelSource and channelInstructions:
1050
- * dropping them removes a suspended website's run refusal and turn capture.
1168
+ * dropping them removes a suspended website's run refusal and turn capture,
1169
+ * and it must run discordReplyWork or an evicted Discord run never answers.
1051
1170
  */
1052
1171
  async shiitakeOptions() {
1053
1172
  const [{ oysterAgentExtensions }, { Knapsack }, { agentMcpSourceOptions }, { mcpRequestData },] = await Promise.all([
@@ -1181,7 +1300,11 @@ export class StandaloneAgentBase extends ShiitakeDO {
1181
1300
  this.archiveControl().assertOpen();
1182
1301
  },
1183
1302
  },
1184
- hostWork: [...keeping.hostWork, this.archiveControl().work],
1303
+ hostWork: [
1304
+ ...keeping.hostWork,
1305
+ this.archiveControl().work,
1306
+ this.discordReplyWork(),
1307
+ ],
1185
1308
  };
1186
1309
  }
1187
1310
  /** Send an installation-admitted message through fleet Session operations. */
@@ -1733,9 +1856,119 @@ export class AgentDirectory extends DurableObject {
1733
1856
  return { error: "not_granted" };
1734
1857
  return websiteOutcome(() => this.websites().bindings.update(bindingId, input));
1735
1858
  }
1736
- /** Host-only: the binding a website Agent serves, read fresh on every use. */
1737
- websiteBinding(bindingId) {
1738
- return this.websites().bindings.read(bindingId);
1859
+ discordOwner;
1860
+ discords() {
1861
+ return (this.discordOwner ??= createDiscordBindings({
1862
+ sql: this.ctx.storage.sql,
1863
+ transactionSync: (body) => this.ctx.storage.transactionSync(body),
1864
+ agentExists: (agentId) => this.has(agentId),
1865
+ }));
1866
+ }
1867
+ discordVault() {
1868
+ return createInstanceCredentialStore({
1869
+ credentialKey: this.env.OYSTER_CREDENTIAL_KEY,
1870
+ storage: credentialStorage(this.ctx.storage),
1871
+ });
1872
+ }
1873
+ /** Owner read of every Discord application bound to one of this tenant's Agents. */
1874
+ discordList(principal) {
1875
+ if (!oysterPrincipalIsOwner(principal))
1876
+ return { error: "not_granted" };
1877
+ return this.discords().list();
1878
+ }
1879
+ /**
1880
+ * Owner-only: bind the owner's own Discord application to a chosen Agent. The
1881
+ * bot token is sealed under the instance credential key before the binding
1882
+ * exists and is never returned, listed or logged.
1883
+ */
1884
+ async discordCreate(principal, input, requestId) {
1885
+ if (!oysterPrincipalIsOwner(principal))
1886
+ return { error: "not_granted" };
1887
+ const parsed = createDiscordInputSchema.safeParse(input);
1888
+ if (!parsed.success)
1889
+ return { error: "invalid_input" };
1890
+ const { botToken, ...facts } = parsed.data;
1891
+ const bindings = this.discords();
1892
+ // A replay of a created binding returns it without sealing the token again.
1893
+ const replayed = discordOutcome(() => bindings.replay(facts, requestId));
1894
+ if (replayed !== null)
1895
+ return replayed;
1896
+ const sealed = await sealDiscordToken(this.discordVault(), botToken);
1897
+ if ("error" in sealed)
1898
+ return sealed;
1899
+ const outcome = discordOutcome(() => bindings.create(facts, sealed.credentialId, requestId));
1900
+ if ("error" in outcome)
1901
+ await this.discordVault().remove(sealed.credentialId);
1902
+ return outcome;
1903
+ }
1904
+ /** Owner-only edit, fenced by the version the owner last read. */
1905
+ async discordUpdate(principal, bindingId, input) {
1906
+ if (!oysterPrincipalIsOwner(principal))
1907
+ return { error: "not_granted" };
1908
+ const parsed = updateDiscordInputSchema.safeParse(input);
1909
+ if (!parsed.success)
1910
+ return { error: "invalid_input" };
1911
+ const { botToken, ...edit } = parsed.data;
1912
+ const bindings = this.discords();
1913
+ const previous = bindings.tokenCredentialId(bindingId);
1914
+ if (previous === null)
1915
+ return { error: "not_found" };
1916
+ let replacement = null;
1917
+ if (botToken !== undefined) {
1918
+ const sealed = await sealDiscordToken(this.discordVault(), botToken);
1919
+ if ("error" in sealed)
1920
+ return sealed;
1921
+ replacement = sealed.credentialId;
1922
+ }
1923
+ const outcome = discordOutcome(() => bindings.update(bindingId, edit, replacement));
1924
+ // Exactly one of the old and the new credential survives the edit.
1925
+ if (replacement !== null)
1926
+ await this.discordVault().remove("error" in outcome ? replacement : previous);
1927
+ return outcome;
1928
+ }
1929
+ /**
1930
+ * Owner-only: register `/ask` in each bound guild with the sealed bot token,
1931
+ * which stays inside this call. Discord says which guilds took it.
1932
+ */
1933
+ async discordRegisterCommands(principal, bindingId) {
1934
+ if (!oysterPrincipalIsOwner(principal))
1935
+ return { error: "not_granted" };
1936
+ const binding = this.discords().read(bindingId);
1937
+ const credentialId = this.discords().tokenCredentialId(bindingId);
1938
+ if (binding === null || credentialId === null)
1939
+ return { error: "not_found" };
1940
+ const registered = [];
1941
+ const failed = [];
1942
+ try {
1943
+ await this.discordVault().withSecret(credentialId, async (botToken) => {
1944
+ for (const guildId of binding.selector.guildIds) {
1945
+ const took = await registerAskCommand(fetch, {
1946
+ applicationId: binding.selector.applicationId,
1947
+ guildId,
1948
+ botToken,
1949
+ }).catch((cause) => {
1950
+ // Transport text can echo request headers; log only the kind.
1951
+ console.warn("discord command registration failed", guildId, cause instanceof Error ? cause.name : "unknown");
1952
+ return false;
1953
+ });
1954
+ if (took)
1955
+ registered.push(guildId);
1956
+ else
1957
+ failed.push(guildId);
1958
+ }
1959
+ });
1960
+ }
1961
+ catch (error) {
1962
+ if (error instanceof CredentialError)
1963
+ return { error: "custody_unavailable" };
1964
+ throw error;
1965
+ }
1966
+ return { registered, failed };
1967
+ }
1968
+ /** Host-only: the website or Discord binding an Agent serves, read fresh on every use. */
1969
+ channelBinding(bindingId) {
1970
+ return (this.websites().bindings.read(bindingId) ??
1971
+ this.discords().read(bindingId));
1739
1972
  }
1740
1973
  /** Host-only public lookup: a site key resolves to its site, or to nothing. */
1741
1974
  websiteSite(siteKey) {
@@ -175,13 +175,13 @@ export async function dispatchAppsBuildsBinding(env, scope, frame, props, method
175
175
  appId,
176
176
  sourceRevision: input.sourceRevision,
177
177
  requestedBy,
178
+ callerInstallationId: frame.facts.selection.owner.id,
178
179
  };
179
180
  if (input.installationId !== undefined && workflowRequestId === undefined)
180
181
  throw new AppInstanceError("revoked");
181
182
  if (workflowRequestId !== undefined) {
182
183
  request.workflow = {
183
184
  requestId: workflowRequestId,
184
- callerInstallationId: frame.facts.selection.owner.id,
185
185
  };
186
186
  if (input.installationId !== undefined)
187
187
  request.workflow.installationId = input.installationId;