@fungi.computer/oyster 0.21.8 → 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.
@@ -12,6 +12,9 @@ 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 { isDiscordBinding, createDiscordBindings, createDiscordInputSchema, updateDiscordInputSchema, } from "../channels/discord-binding.js";
16
+ import { DISCORD_ANSWER_WINDOW_MS, DISCORD_SETTLEMENT_POLL_MS, discordDenial, patchOriginal, quoted, registerAskCommand, } from "../channels/discord-interactions.js";
17
+ import { discordOutcome, sealDiscordToken, } from "./discord-channels.js";
15
18
  import { channelSessionDoor } from "./channel-session-door.js";
16
19
  import { createAuthenticatedVisitorChannel } from "../channels/visitor-channel.js";
17
20
  import { verifyVisitor } from "./visitor-proof.js";
@@ -36,6 +39,7 @@ import { homeContract } from "@fungi.computer/shiitake-extensions/home";
36
39
  import { DurableObject } from "cloudflare:workers";
37
40
  import { ShiitakeDO } from "@fungi.computer/shiitake/cloudflare";
38
41
  import { agentStoreKeeping } from "./agent-store.js";
42
+ import { CredentialError, } from "@fungi.computer/veil/credential-store";
39
43
  import { createInstanceCredentialStore, createModelKeyVault, ModelKeyRefused, } from "./model-key-vault.js";
40
44
  import { agentArchiveOwner } from "./agent-archive-owner.js";
41
45
  import { agentArchiveProjection } from "../agent-archive-projection.js";
@@ -297,7 +301,7 @@ export class StandaloneAgentBase extends ShiitakeDO {
297
301
  websiteBindings = new Map();
298
302
  /** The owner's current record of one binding; hosts and tests supply it. */
299
303
  readChannelBinding(bindingId) {
300
- return agentDirectoryForScope(this.env, tenantScope(defaultTenant, this.env.OYSTER_ORIGIN)).websiteBinding(bindingId);
304
+ return agentDirectoryForScope(this.env, tenantScope(defaultTenant, this.env.OYSTER_ORIGIN)).channelBinding(bindingId);
301
305
  }
302
306
  /**
303
307
  * Read one binding afresh from its owner: suspension, persona and edits are
@@ -362,12 +366,69 @@ export class StandaloneAgentBase extends ShiitakeDO {
362
366
  throw new Error("Website channel binding is unavailable");
363
367
  const base = await source.load(input);
364
368
  return {
365
- revision: `${base.revision}+website-${String(decision.binding.authorityVersion)}`,
369
+ revision: `${base.revision}+${decision.binding.selector.provider}-${String(decision.binding.authorityVersion)}`,
366
370
  text: `${base.text}\n\n${personChannelInstructions(decision.binding.persona)}`,
367
371
  };
368
372
  },
369
373
  };
370
374
  }
375
+ /**
376
+ * A verified Discord question for this Agent. The public edge has already
377
+ * checked the application's signature and the guild and channel; this
378
+ * accepts the work and returns at once, and the answer follows by the
379
+ * interaction webhook once the run settles.
380
+ */
381
+ askDiscord(bindingId, ask) {
382
+ this.ctx.waitUntil(this.answerDiscord(bindingId, ask).catch((cause) => {
383
+ console.error("discord answer failed", cause);
384
+ }));
385
+ }
386
+ async answerDiscord(bindingId, ask) {
387
+ const say = (content, withReply) => patchOriginal(fetch, {
388
+ applicationId: ask.applicationId,
389
+ interactionToken: ask.interactionToken,
390
+ content,
391
+ withReply,
392
+ });
393
+ const binding = await this.loadChannelBinding(bindingId);
394
+ if (binding === null ||
395
+ !isDiscordBinding(binding) ||
396
+ binding.lifecycle !== "active") {
397
+ await say("This Agent is not available right now.", false);
398
+ return;
399
+ }
400
+ const result = await this.channelConversations().receive({
401
+ bindingId,
402
+ conversation: `${ask.guildId}:${ask.channelId}:${ask.userId}`,
403
+ eventId: ask.interactionId,
404
+ party: {
405
+ kind: "discord-user",
406
+ guildId: ask.guildId,
407
+ userId: ask.userId,
408
+ },
409
+ text: ask.text,
410
+ });
411
+ if (result.kind === "denied") {
412
+ await say(discordDenial[result.reason], false);
413
+ return;
414
+ }
415
+ if (result.kind === "held") {
416
+ await say("A person has taken over this conversation.", false);
417
+ return;
418
+ }
419
+ const session = (await this.shiitake()).session(result.sessionId);
420
+ const deadline = Date.now() + DISCORD_ANSWER_WINDOW_MS;
421
+ let settlement;
422
+ while (settlement === undefined && Date.now() < deadline)
423
+ settlement = await session.readSettlement(result.commandId, {
424
+ timeoutMs: DISCORD_SETTLEMENT_POLL_MS,
425
+ });
426
+ const answer = settlement?.terminal.outcome === "completed" &&
427
+ settlement.content.trim().length > 0
428
+ ? settlement.content
429
+ : "I could not answer that. Please try again.";
430
+ await say(ask.echo === undefined ? answer : `${quoted(ask.echo)}\n\n${answer}`, true);
431
+ }
371
432
  /** Owner read of one website's conversations; the host admits the owner first. */
372
433
  async websiteConversations(bindingId) {
373
434
  const binding = await this.loadChannelBinding(bindingId);
@@ -1733,9 +1794,119 @@ export class AgentDirectory extends DurableObject {
1733
1794
  return { error: "not_granted" };
1734
1795
  return websiteOutcome(() => this.websites().bindings.update(bindingId, input));
1735
1796
  }
1736
- /** Host-only: the binding a website Agent serves, read fresh on every use. */
1737
- websiteBinding(bindingId) {
1738
- return this.websites().bindings.read(bindingId);
1797
+ discordOwner;
1798
+ discords() {
1799
+ return (this.discordOwner ??= createDiscordBindings({
1800
+ sql: this.ctx.storage.sql,
1801
+ transactionSync: (body) => this.ctx.storage.transactionSync(body),
1802
+ agentExists: (agentId) => this.has(agentId),
1803
+ }));
1804
+ }
1805
+ discordVault() {
1806
+ return createInstanceCredentialStore({
1807
+ credentialKey: this.env.OYSTER_CREDENTIAL_KEY,
1808
+ storage: credentialStorage(this.ctx.storage),
1809
+ });
1810
+ }
1811
+ /** Owner read of every Discord application bound to one of this tenant's Agents. */
1812
+ discordList(principal) {
1813
+ if (!oysterPrincipalIsOwner(principal))
1814
+ return { error: "not_granted" };
1815
+ return this.discords().list();
1816
+ }
1817
+ /**
1818
+ * Owner-only: bind the owner's own Discord application to a chosen Agent. The
1819
+ * bot token is sealed under the instance credential key before the binding
1820
+ * exists and is never returned, listed or logged.
1821
+ */
1822
+ async discordCreate(principal, input, requestId) {
1823
+ if (!oysterPrincipalIsOwner(principal))
1824
+ return { error: "not_granted" };
1825
+ const parsed = createDiscordInputSchema.safeParse(input);
1826
+ if (!parsed.success)
1827
+ return { error: "invalid_input" };
1828
+ const { botToken, ...facts } = parsed.data;
1829
+ const bindings = this.discords();
1830
+ // A replay of a created binding returns it without sealing the token again.
1831
+ const replayed = discordOutcome(() => bindings.replay(facts, requestId));
1832
+ if (replayed !== null)
1833
+ return replayed;
1834
+ const sealed = await sealDiscordToken(this.discordVault(), botToken);
1835
+ if ("error" in sealed)
1836
+ return sealed;
1837
+ const outcome = discordOutcome(() => bindings.create(facts, sealed.credentialId, requestId));
1838
+ if ("error" in outcome)
1839
+ await this.discordVault().remove(sealed.credentialId);
1840
+ return outcome;
1841
+ }
1842
+ /** Owner-only edit, fenced by the version the owner last read. */
1843
+ async discordUpdate(principal, bindingId, input) {
1844
+ if (!oysterPrincipalIsOwner(principal))
1845
+ return { error: "not_granted" };
1846
+ const parsed = updateDiscordInputSchema.safeParse(input);
1847
+ if (!parsed.success)
1848
+ return { error: "invalid_input" };
1849
+ const { botToken, ...edit } = parsed.data;
1850
+ const bindings = this.discords();
1851
+ const previous = bindings.tokenCredentialId(bindingId);
1852
+ if (previous === null)
1853
+ return { error: "not_found" };
1854
+ let replacement = null;
1855
+ if (botToken !== undefined) {
1856
+ const sealed = await sealDiscordToken(this.discordVault(), botToken);
1857
+ if ("error" in sealed)
1858
+ return sealed;
1859
+ replacement = sealed.credentialId;
1860
+ }
1861
+ const outcome = discordOutcome(() => bindings.update(bindingId, edit, replacement));
1862
+ // Exactly one of the old and the new credential survives the edit.
1863
+ if (replacement !== null)
1864
+ await this.discordVault().remove("error" in outcome ? replacement : previous);
1865
+ return outcome;
1866
+ }
1867
+ /**
1868
+ * Owner-only: register `/ask` in each bound guild with the sealed bot token,
1869
+ * which stays inside this call. Discord says which guilds took it.
1870
+ */
1871
+ async discordRegisterCommands(principal, bindingId) {
1872
+ if (!oysterPrincipalIsOwner(principal))
1873
+ return { error: "not_granted" };
1874
+ const binding = this.discords().read(bindingId);
1875
+ const credentialId = this.discords().tokenCredentialId(bindingId);
1876
+ if (binding === null || credentialId === null)
1877
+ return { error: "not_found" };
1878
+ const registered = [];
1879
+ const failed = [];
1880
+ try {
1881
+ await this.discordVault().withSecret(credentialId, async (botToken) => {
1882
+ for (const guildId of binding.selector.guildIds) {
1883
+ const took = await registerAskCommand(fetch, {
1884
+ applicationId: binding.selector.applicationId,
1885
+ guildId,
1886
+ botToken,
1887
+ }).catch((cause) => {
1888
+ // Transport text can echo request headers; log only the kind.
1889
+ console.warn("discord command registration failed", guildId, cause instanceof Error ? cause.name : "unknown");
1890
+ return false;
1891
+ });
1892
+ if (took)
1893
+ registered.push(guildId);
1894
+ else
1895
+ failed.push(guildId);
1896
+ }
1897
+ });
1898
+ }
1899
+ catch (error) {
1900
+ if (error instanceof CredentialError)
1901
+ return { error: "custody_unavailable" };
1902
+ throw error;
1903
+ }
1904
+ return { registered, failed };
1905
+ }
1906
+ /** Host-only: the website or Discord binding an Agent serves, read fresh on every use. */
1907
+ channelBinding(bindingId) {
1908
+ return (this.websites().bindings.read(bindingId) ??
1909
+ this.discords().read(bindingId));
1739
1910
  }
1740
1911
  /** Host-only public lookup: a site key resolves to its site, or to nothing. */
1741
1912
  websiteSite(siteKey) {
@@ -442,6 +442,9 @@ export class ComputerDO extends NativeComputerDO {
442
442
  return this.#backends;
443
443
  }
444
444
  #accept(authority, action) {
445
+ // A fleet Computer that predates the name record learns its name from the
446
+ // first grant that names it, once the namespace verifies the claim.
447
+ this.claimComputerName(authority.computerId);
445
448
  if (checkComputerGrant(authority, {
446
449
  computerId: this.#id(),
447
450
  action,
@@ -0,0 +1,67 @@
1
+ import { type CredentialStore } from "@fungi.computer/veil/credential-store";
2
+ import { type Routes } from "../authorization.js";
3
+ import { type CreateDiscordInput, type DiscordBinding, type UpdateDiscordInput } from "../channels/discord-binding.js";
4
+ import type { OysterEnv } from "../host.js";
5
+ import { type TenantPrincipal } from "../tenant.js";
6
+ import { agentDirectoryForScope } from "./agent-directory.js";
7
+ import type { StandaloneAgentsEnv } from "./agents.js";
8
+ /** Why an owner's Discord command was refused. */
9
+ export type DiscordRefusal = Readonly<{
10
+ error: "not_granted" | "not_found" | "version_conflict" | "request_conflict" | "application_taken" | "invalid_input" | "custody_unavailable" | "limit";
11
+ }>;
12
+ /** Run one binding command, turning its closed failures into data. */
13
+ export declare function discordOutcome<T>(command: () => T): T | DiscordRefusal;
14
+ /** Seal one bot token; the credential id is all that leaves custody. */
15
+ export declare function sealDiscordToken(vault: CredentialStore, botToken: string): Promise<Readonly<{
16
+ credentialId: string;
17
+ }> | DiscordRefusal>;
18
+ /** What the owner's Discord routes need from the directory. */
19
+ export type StandaloneDiscordControl = Readonly<{
20
+ read: (principal: TenantPrincipal) => Promise<Readonly<{
21
+ interactionsOrigin: string;
22
+ agents: readonly Readonly<{
23
+ agentId: string;
24
+ name: string;
25
+ }>[];
26
+ discords: readonly DiscordBinding[];
27
+ }>>;
28
+ create: (principal: TenantPrincipal, input: CreateDiscordInput, requestId: string) => Promise<DiscordBinding | DiscordRefusal>;
29
+ update: (principal: TenantPrincipal, bindingId: string, input: UpdateDiscordInput) => Promise<DiscordBinding | DiscordRefusal>;
30
+ registerCommands: (principal: TenantPrincipal, bindingId: string) => Promise<Readonly<{
31
+ registered: readonly string[];
32
+ failed: readonly string[];
33
+ }> | DiscordRefusal>;
34
+ }>;
35
+ /** The owner's Discord controls over the directory. */
36
+ export declare function standaloneDiscordControl(env: Pick<StandaloneAgentsEnv, "OYSTER_ORIGIN">, directoryOf: () => ReturnType<typeof agentDirectoryForScope>): StandaloneDiscordControl;
37
+ /**
38
+ * The owner's Discord controls. Each route is owner-direct: an App cannot bind
39
+ * a Discord application, or replace its sealed token, on the owner's behalf.
40
+ */
41
+ export declare function standaloneDiscordRoutes(control: StandaloneDiscordControl): Routes<OysterEnv>;
42
+ /** The host values the public interactions door needs. */
43
+ type StandaloneDiscordEnv = Pick<StandaloneAgentsEnv, "AGENTS" | "AGENT_DIRECTORY" | "OYSTER_ORIGIN">;
44
+ /**
45
+ * The public Discord door: one URL per bound application, which the owner
46
+ * pastes into the Discord developer portal as its Interactions Endpoint URL.
47
+ * Every request proves itself with the application's Ed25519 signature before
48
+ * anything is decoded; the Agent is reached only after the guild and channel
49
+ * pass the owner's allowlist.
50
+ */
51
+ export declare function standaloneDiscordApp(): import("hono/hono-base").HonoBase<{
52
+ Bindings: StandaloneDiscordEnv;
53
+ }, {
54
+ "/api/discord/interactions/:bindingId": {
55
+ $post: {
56
+ input: {
57
+ param: {
58
+ bindingId: string;
59
+ };
60
+ };
61
+ output: {};
62
+ outputFormat: string;
63
+ status: import("hono/utils/http-status").StatusCode;
64
+ };
65
+ };
66
+ }, "/", "/api/discord/interactions/:bindingId">;
67
+ export {};
@@ -0,0 +1,212 @@
1
+ /**
2
+ * The standalone Discord channel: the owner brings their own Discord
3
+ * application and puts one of their Agents behind it. The directory owns the
4
+ * bindings; the bot token is sealed in the instance credential store and never
5
+ * leaves it except inside a request to Discord. Fungi holds no Discord
6
+ * credential.
7
+ */
8
+ import { Hono } from "hono";
9
+ import * as Option from "effect/Option";
10
+ import * as Schema from "effect/Schema";
11
+ import { z } from "zod";
12
+ import { CredentialError, } from "@fungi.computer/veil/credential-store";
13
+ import { owner, routes } from "../authorization.js";
14
+ import { createDiscordInputSchema, DiscordBindingError, updateDiscordInputSchema, discordPlaceAllowed, isDiscordBinding, } from "../channels/discord-binding.js";
15
+ import { DISCORD_ASK_LIMIT, ASK_COMMAND, ASK_OPTION, REPLY_ID, REPLY_TEXT_ID, deferredResponse, ephemeralResponse, interactionSchema, pongResponse, replyModalResponse, verifyDiscordRequest, } from "../channels/discord-interactions.js";
16
+ import { defaultTenant, tenantScope } from "../tenant.js";
17
+ import { agentDirectoryForScope } from "./agent-directory.js";
18
+ /** Run one binding command, turning its closed failures into data. */
19
+ export function discordOutcome(command) {
20
+ try {
21
+ return command();
22
+ }
23
+ catch (error) {
24
+ if (error instanceof DiscordBindingError)
25
+ return { error: error.code };
26
+ throw error;
27
+ }
28
+ }
29
+ /** Seal one bot token; the credential id is all that leaves custody. */
30
+ export async function sealDiscordToken(vault, botToken) {
31
+ try {
32
+ const record = await vault.put({
33
+ kind: "discord-bot-token",
34
+ label: "Discord bot token",
35
+ secret: botToken,
36
+ });
37
+ return { credentialId: record.credentialId };
38
+ }
39
+ catch (error) {
40
+ if (error instanceof CredentialError)
41
+ return {
42
+ error: error.code === "limit" ? "limit" : "custody_unavailable",
43
+ };
44
+ throw error;
45
+ }
46
+ }
47
+ /** The owner's Discord controls over the directory. */
48
+ export function standaloneDiscordControl(env, directoryOf) {
49
+ return {
50
+ read: async (principal) => {
51
+ const listed = await directoryOf().discordList(principal);
52
+ return {
53
+ interactionsOrigin: env.OYSTER_ORIGIN,
54
+ agents: (await directoryOf().list()).map(({ agentId, name }) => ({
55
+ agentId,
56
+ name,
57
+ })),
58
+ discords: "error" in listed ? [] : listed,
59
+ };
60
+ },
61
+ create: (principal, input, requestId) => directoryOf().discordCreate(principal, input, requestId),
62
+ update: (principal, bindingId, input) => directoryOf().discordUpdate(principal, bindingId, input),
63
+ registerCommands: (principal, bindingId) => directoryOf().discordRegisterCommands(principal, bindingId),
64
+ };
65
+ }
66
+ const refusalStatus = {
67
+ not_granted: 403,
68
+ not_found: 404,
69
+ version_conflict: 409,
70
+ request_conflict: 409,
71
+ application_taken: 409,
72
+ invalid_input: 400,
73
+ custody_unavailable: 503,
74
+ limit: 409,
75
+ };
76
+ function refused(value) {
77
+ return "error" in value;
78
+ }
79
+ /**
80
+ * The owner's Discord controls. Each route is owner-direct: an App cannot bind
81
+ * a Discord application, or replace its sealed token, on the owner's behalf.
82
+ */
83
+ export function standaloneDiscordRoutes(control) {
84
+ const table = routes();
85
+ // A body that is not JSON is a malformed request, not a thrown failure.
86
+ const parseBody = async (context) => {
87
+ const decoded = Schema.decodeUnknownOption(Schema.fromJsonString(Schema.Json))(await context.req.text());
88
+ return Option.isSome(decoded)
89
+ ? { ok: true, value: decoded.value }
90
+ : { ok: false };
91
+ };
92
+ table.get("/api/discord", owner("direct"), async (context, { principal }) => {
93
+ context.header("Cache-Control", "no-store");
94
+ return context.json(await control.read(principal));
95
+ });
96
+ table.post("/api/discord", owner("direct"), async (context, { principal }) => {
97
+ context.header("Cache-Control", "no-store");
98
+ const body = await parseBody(context);
99
+ if (!body.ok)
100
+ return context.json({ error: "invalid_input" }, 400);
101
+ const parsed = createDiscordInputSchema.safeParse(body.value);
102
+ if (!parsed.success)
103
+ return context.json({ error: "invalid_input" }, 400);
104
+ const result = await control.create(principal, parsed.data, context.req.header("x-request-id") ?? "");
105
+ return refused(result)
106
+ ? context.json(result, refusalStatus[result.error])
107
+ : context.json({ binding: result }, 201);
108
+ });
109
+ table.put("/api/discord/:bindingId", owner("direct"), async (context, { principal }) => {
110
+ context.header("Cache-Control", "no-store");
111
+ const body = await parseBody(context);
112
+ if (!body.ok)
113
+ return context.json({ error: "invalid_input" }, 400);
114
+ const parsed = updateDiscordInputSchema.safeParse(body.value);
115
+ if (!parsed.success)
116
+ return context.json({ error: "invalid_input" }, 400);
117
+ const result = await control.update(principal, context.req.param("bindingId"), parsed.data);
118
+ return refused(result)
119
+ ? context.json(result, refusalStatus[result.error])
120
+ : context.json({ binding: result });
121
+ });
122
+ table.post("/api/discord/:bindingId/commands", owner("direct"), async (context, { principal }) => {
123
+ context.header("Cache-Control", "no-store");
124
+ const result = await control.registerCommands(principal, context.req.param("bindingId"));
125
+ return "error" in result
126
+ ? context.json(result, refusalStatus[result.error])
127
+ : context.json(result);
128
+ });
129
+ return table;
130
+ }
131
+ /** A request body larger than this is not a Discord interaction. */
132
+ const INTERACTION_BODY_LIMIT = 100_000;
133
+ const decodeJson = Schema.decodeUnknownOption(Schema.fromJsonString(Schema.Json));
134
+ /**
135
+ * The public Discord door: one URL per bound application, which the owner
136
+ * pastes into the Discord developer portal as its Interactions Endpoint URL.
137
+ * Every request proves itself with the application's Ed25519 signature before
138
+ * anything is decoded; the Agent is reached only after the guild and channel
139
+ * pass the owner's allowlist.
140
+ */
141
+ export function standaloneDiscordApp() {
142
+ return new Hono().post("/api/discord/interactions/:bindingId", async (context) => {
143
+ const { env } = context;
144
+ const found = await agentDirectoryForScope(env, tenantScope(defaultTenant, env.OYSTER_ORIGIN)).channelBinding(context.req.param("bindingId"));
145
+ if (found === null || !isDiscordBinding(found))
146
+ return context.json({ error: "not_found" }, 404);
147
+ const binding = found;
148
+ const body = await context.req.text();
149
+ if (body.length > INTERACTION_BODY_LIMIT)
150
+ return context.json({ error: "too_large" }, 413);
151
+ const verdict = await verifyDiscordRequest({
152
+ publicKey: binding.selector.publicKey,
153
+ signature: context.req.header("x-signature-ed25519"),
154
+ timestamp: context.req.header("x-signature-timestamp"),
155
+ body,
156
+ nowSeconds: Date.now() / 1_000,
157
+ });
158
+ if (verdict !== "verified")
159
+ return context.text("invalid request signature", 401);
160
+ const json = decodeJson(body);
161
+ const decoded = interactionSchema.safeParse(Option.getOrUndefined(json));
162
+ if (!decoded.success)
163
+ return context.json({ error: "invalid_interaction" }, 400);
164
+ const interaction = decoded.data;
165
+ if (interaction.type === 1)
166
+ return context.json(pongResponse);
167
+ if (interaction.application_id !== binding.selector.applicationId)
168
+ return context.json({ error: "wrong_application" }, 400);
169
+ if (binding.lifecycle !== "active")
170
+ return context.json(ephemeralResponse("This Agent is paused."));
171
+ const userId = interaction.member?.user.id ?? interaction.user?.id;
172
+ const { guild_id: guildId, channel_id: channelId } = interaction;
173
+ if (guildId === undefined ||
174
+ channelId === undefined ||
175
+ userId === undefined)
176
+ return context.json(ephemeralResponse("Ask in a server channel, not in a direct message."));
177
+ if (!discordPlaceAllowed(binding.selector, { guildId, channelId }))
178
+ return context.json(ephemeralResponse("This channel is not set up for this Agent."));
179
+ const ask = (text, echo) => {
180
+ const trimmed = text.trim();
181
+ if (trimmed.length === 0 || trimmed.length > DISCORD_ASK_LIMIT)
182
+ return context.json(ephemeralResponse("Keep it between 1 and 1,000 characters."));
183
+ const question = {
184
+ interactionId: interaction.id,
185
+ applicationId: binding.selector.applicationId,
186
+ interactionToken: interaction.token,
187
+ guildId,
188
+ channelId,
189
+ userId,
190
+ text: trimmed,
191
+ echo,
192
+ };
193
+ // The answer outlives Discord's three seconds; it follows by webhook.
194
+ context.executionCtx.waitUntil(Promise.resolve(env.AGENTS.getByName(binding.agentId).askDiscord(binding.bindingId, question)));
195
+ return context.json(deferredResponse);
196
+ };
197
+ if (interaction.type === 2) {
198
+ if (interaction.data.name !== ASK_COMMAND)
199
+ return context.json(ephemeralResponse("Unknown command."));
200
+ const option = interaction.data.options?.find(({ name }) => name === ASK_OPTION);
201
+ return ask(z.string().catch("").parse(option?.value));
202
+ }
203
+ if (interaction.data.custom_id !== REPLY_ID)
204
+ return context.json(ephemeralResponse("Unknown action."));
205
+ if (interaction.type === 3)
206
+ return context.json(replyModalResponse);
207
+ const reply = interaction.data.components
208
+ .flatMap((row) => row.components)
209
+ .find(({ custom_id: id }) => id === REPLY_TEXT_ID);
210
+ return ask(reply?.value ?? "", reply?.value.trim());
211
+ });
212
+ }
@@ -0,0 +1,13 @@
1
+ import { type CatalogModelKeyProvider } from "@fungi.computer/veil/model-keys";
2
+ /**
3
+ * Standalone custody takes every catalog provider's API key, plus an owner's
4
+ * Cloudflare account and token.
5
+ */
6
+ export type StandaloneModelKeyProvider = CatalogModelKeyProvider | "cloudflare-workers-ai";
7
+ export declare const isStandaloneModelKeyProvider: (value: string) => value is StandaloneModelKeyProvider;
8
+ /** What the owner may connect, in display order; the Settings form is built from it. */
9
+ export declare const modelKeyProviderChoices: readonly Readonly<{
10
+ id: StandaloneModelKeyProvider;
11
+ label: string;
12
+ accountId: boolean;
13
+ }>[];
@@ -0,0 +1,11 @@
1
+ import { catalogModelKeyProviders, isCatalogModelKeyProvider, } from "@fungi.computer/veil/model-keys";
2
+ export const isStandaloneModelKeyProvider = (value) => value === "cloudflare-workers-ai" || isCatalogModelKeyProvider(value);
3
+ /** What the owner may connect, in display order; the Settings form is built from it. */
4
+ export const modelKeyProviderChoices = [
5
+ {
6
+ id: "cloudflare-workers-ai",
7
+ label: "Cloudflare Workers AI",
8
+ accountId: true,
9
+ },
10
+ ...Object.entries(catalogModelKeyProviders).flatMap(([id, { label }]) => isCatalogModelKeyProvider(id) ? [{ id, label, accountId: false }] : []),
11
+ ];
@@ -1,5 +1,5 @@
1
1
  import { type CredentialRecord, type CredentialStorage } from "@fungi.computer/veil/credential-store";
2
- import { type ModelKeyRecord as HostedModelKeyRecord } from "@fungi.computer/veil/model-keys";
2
+ import { type StandaloneModelKeyProvider } from "./model-key-providers.js";
3
3
  /**
4
4
  * This instance's own model-key owner. Provider API keys are sealed (AES-GCM)
5
5
  * under a key derived from the instance master secret, a host secret that never
@@ -12,10 +12,14 @@ export declare class ModelKeyRefused extends Error {
12
12
  readonly reason: ModelKeyRefusal;
13
13
  constructor(reason: ModelKeyRefusal);
14
14
  }
15
- /** Standalone custody also accepts an owner’s Cloudflare account and token. */
16
- export type ModelKeyRecord = Omit<HostedModelKeyRecord, "provider"> & {
17
- readonly provider: HostedModelKeyRecord["provider"] | "cloudflare-workers-ai";
18
- };
15
+ /** A stored key as the owner sees it: no secret, no custody locator. */
16
+ export type ModelKeyRecord = Readonly<{
17
+ keyId: string;
18
+ provider: StandaloneModelKeyProvider;
19
+ label: string;
20
+ createdAt: number;
21
+ validatedAt: number;
22
+ }>;
19
23
  /** What the owner submits to seal one provider key. */
20
24
  export type ModelKeySealInput = Readonly<{
21
25
  provider: string;
@@ -1,6 +1,7 @@
1
1
  import * as Schema from "effect/Schema";
2
2
  import { createCredentialSealer, createCredentialStore, CredentialError, } from "@fungi.computer/veil/credential-store";
3
- import { isModelKeyProvider, modelKeyForwardedHeaders, modelKeyBaseUrl, modelKeyTarget, modelKeyValidationRequest, modelKeyValidationResult, } from "@fungi.computer/veil/model-keys";
3
+ import { modelKeyAuthenticated, modelKeyForwardedHeaders, modelKeyBaseUrl, modelKeyTarget, modelKeyValidationRequest, modelKeyValidationResult, } from "@fungi.computer/veil/model-keys";
4
+ import { isStandaloneModelKeyProvider, } from "./model-key-providers.js";
4
5
  export class ModelKeyRefused extends Error {
5
6
  reason;
6
7
  constructor(reason) {
@@ -9,7 +10,7 @@ export class ModelKeyRefused extends Error {
9
10
  this.name = "ModelKeyRefused";
10
11
  }
11
12
  }
12
- const isProvider = (value) => value === "cloudflare-workers-ai" || isModelKeyProvider(value);
13
+ const isProvider = isStandaloneModelKeyProvider;
13
14
  const cloudflareCredentialSchema = Schema.Struct({
14
15
  apiKey: Schema.NonEmptyString,
15
16
  accountId: Schema.String.check(Schema.isPattern(/^[a-f0-9]{32}$/u)),
@@ -47,14 +48,14 @@ const publicRecord = (record) => ({
47
48
  createdAt: record.createdAt,
48
49
  validatedAt: record.validatedAt,
49
50
  });
50
- /** Anthropic authenticates with `x-api-key`; the others take a bearer token. */
51
+ /** Cloudflare takes a bearer token; a catalog provider names its own header. */
51
52
  function authenticated(provider, headers, apiKey) {
52
- const next = new Headers(headers);
53
- if (provider === "anthropic")
54
- next.set("x-api-key", apiKey);
55
- else
53
+ if (provider === "cloudflare-workers-ai") {
54
+ const next = new Headers(headers);
56
55
  next.set("authorization", `Bearer ${apiKey}`);
57
- return next;
56
+ return next;
57
+ }
58
+ return modelKeyAuthenticated(provider, headers, apiKey);
58
59
  }
59
60
  /**
60
61
  * The instance's one encrypted credential store. Listing and removal need no
@@ -100,7 +101,6 @@ export function createModelKeyVault(options) {
100
101
  async seal(input) {
101
102
  const { provider, label, apiKey } = input;
102
103
  if (!isProvider(provider) ||
103
- provider === "openai-compatible" ||
104
104
  label.length === 0 ||
105
105
  label.length > 64 ||
106
106
  apiKey.length === 0 ||
@@ -6,6 +6,7 @@ import { standaloneBuildRoutes } from "./builds.js";
6
6
  import { trialStarterRoutes } from "./trial-starters.js";
7
7
  import { standaloneComputerFleetRoutes } from "./computer-fleet.js";
8
8
  import { standaloneWorkflowWebhookControls } from "./workflow-webhooks.js";
9
+ import { standaloneDiscordControl, standaloneDiscordRoutes, } from "./discord-channels.js";
9
10
  import { standaloneWebsiteControl, standaloneWebsiteRoutes, } from "./website-channels.js";
10
11
  /** Every owner route the standalone root adds to its tenant host. */
11
12
  export function standaloneOwnerRoutes(env, scope, hostFor) {
@@ -24,6 +25,8 @@ export function standaloneOwnerRoutes(env, scope, hostFor) {
24
25
  .include(standaloneWorkflowWebhookControls(env, hostFor));
25
26
  // A website is served from the default tenant's directory, which owns it.
26
27
  return scope.tenantId === defaultTenant
27
- ? owned.include(standaloneWebsiteRoutes(standaloneWebsiteControl(env, directory)))
28
+ ? owned
29
+ .include(standaloneWebsiteRoutes(standaloneWebsiteControl(env, directory)))
30
+ .include(standaloneDiscordRoutes(standaloneDiscordControl(env, directory)))
28
31
  : owned;
29
32
  }
@@ -13,6 +13,8 @@ export type StandaloneWorkerRoutePorts = Readonly<{
13
13
  machineLink: (request: Request) => Promise<Response>;
14
14
  /** The public website channel: launcher, visitor document and visitor API. */
15
15
  website: (request: Request) => Promise<Response>;
16
+ /** A bound Discord application's signed interactions. */
17
+ discord: (request: Request) => Promise<Response>;
16
18
  /** A machine's signed dial to its attached Computer, verified by that Computer. */
17
19
  localBackendDial: (request: Request) => Promise<Response>;
18
20
  /** Signed Workflow webhook delivery, verified by the library's run owner. */
@@ -7,6 +7,7 @@ export function standaloneWorkerRoutes(ports) {
7
7
  .all("/embed/*", door("a website visitor; the edge checks the site key and origin"), (context) => ports.website(context.req.raw))
8
8
  .all("/styles.css", door("the website chat's public stylesheet"), (context) => ports.website(context.req.raw))
9
9
  .all("/api/embed/*", door("a website visitor; the edge checks the site key, origin and bearer"), (context) => ports.website(context.req.raw))
10
+ .all("/api/discord/interactions/:bindingId", door("a Discord application; the edge verifies its Ed25519 signature"), (context) => ports.discord(context.req.raw))
10
11
  .all("/api/computers/:computerId/backends/:backendId/connect", door("an attached machine's dial; the Computer verifies its Seam signature"), (context) => ports.localBackendDial(context.req.raw))
11
12
  .include(ports.workflowWebhooks)
12
13
  .all("*", door("the selected tenant's own declared host table"), (context) => ports.tenant(context.req.raw));