@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
@@ -0,0 +1,89 @@
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 { WebsiteTranscript } from "@fungi.computer/nacre/website-channels";
5
+ import type { DiscordClosedReply } from "../channels/discord-replies.js";
6
+ import type { OysterEnv } from "../host.js";
7
+ import { type TenantPrincipal } from "../tenant.js";
8
+ import type { StandaloneAgentsEnv } from "./agents.js";
9
+ /** Why an owner's Discord command was refused. */
10
+ export type DiscordRefusal = Readonly<{
11
+ error: "not_granted" | "not_found" | "version_conflict" | "request_conflict" | "application_taken" | "invalid_input" | "custody_unavailable" | "limit";
12
+ }>;
13
+ /** Run one binding command, turning its closed failures into data. */
14
+ export declare function discordOutcome<T>(command: () => T): T | DiscordRefusal;
15
+ /** Seal one bot token; the credential id is all that leaves custody. */
16
+ export declare function sealDiscordToken(vault: CredentialStore, botToken: string): Promise<Readonly<{
17
+ credentialId: string;
18
+ }> | DiscordRefusal>;
19
+ /** What the owner's Discord controls call on the directory. */
20
+ export type DiscordDirectoryDoor = Readonly<{
21
+ list: () => Promise<readonly Readonly<{
22
+ agentId: string;
23
+ name: string;
24
+ }>[]>;
25
+ discordList: (principal: TenantPrincipal) => Promise<readonly DiscordBinding[] | DiscordRefusal>;
26
+ discordCreate: (principal: TenantPrincipal, input: CreateDiscordInput, requestId: string) => Promise<DiscordBinding | DiscordRefusal>;
27
+ discordUpdate: (principal: TenantPrincipal, bindingId: string, input: UpdateDiscordInput) => Promise<DiscordBinding | DiscordRefusal>;
28
+ discordRegisterCommands: (principal: TenantPrincipal, bindingId: string) => Promise<Readonly<{
29
+ registered: readonly string[];
30
+ failed: readonly string[];
31
+ }> | DiscordRefusal>;
32
+ }>;
33
+ /** What the owner's Discord routes need from the directory. */
34
+ export type StandaloneDiscordControl = Readonly<{
35
+ read: (principal: TenantPrincipal) => Promise<Readonly<{
36
+ interactionsOrigin: string;
37
+ agents: readonly Readonly<{
38
+ agentId: string;
39
+ name: string;
40
+ }>[];
41
+ discords: readonly DiscordBinding[];
42
+ }>>;
43
+ create: (principal: TenantPrincipal, input: CreateDiscordInput, requestId: string) => Promise<DiscordBinding | DiscordRefusal>;
44
+ update: (principal: TenantPrincipal, bindingId: string, input: UpdateDiscordInput) => Promise<DiscordBinding | DiscordRefusal>;
45
+ registerCommands: (principal: TenantPrincipal, bindingId: string) => Promise<Readonly<{
46
+ registered: readonly string[];
47
+ failed: readonly string[];
48
+ }> | DiscordRefusal>;
49
+ conversations: (principal: TenantPrincipal, bindingId: string) => Promise<readonly Readonly<{
50
+ sessionId: string;
51
+ label: string;
52
+ lastEventAt: number;
53
+ }>[]>;
54
+ transcript: (principal: TenantPrincipal, bindingId: string, sessionId: string) => Promise<WebsiteTranscript | null>;
55
+ undelivered: (principal: TenantPrincipal, bindingId: string) => Promise<readonly DiscordClosedReply[]>;
56
+ }>;
57
+ /** The owner's Discord controls over the directory. */
58
+ export declare function standaloneDiscordControl(env: Pick<StandaloneAgentsEnv, "AGENTS" | "OYSTER_ORIGIN">, directoryOf: () => DiscordDirectoryDoor): StandaloneDiscordControl;
59
+ /**
60
+ * The owner's Discord controls. Each route is owner-direct: an App cannot bind
61
+ * a Discord application, or replace its sealed token, on the owner's behalf.
62
+ */
63
+ export declare function standaloneDiscordRoutes(control: StandaloneDiscordControl): Routes<OysterEnv>;
64
+ /** The host values the public interactions door needs. */
65
+ type StandaloneDiscordEnv = Pick<StandaloneAgentsEnv, "AGENTS" | "AGENT_DIRECTORY" | "OYSTER_ORIGIN">;
66
+ /**
67
+ * The public Discord door: one URL per bound application, which the owner
68
+ * pastes into the Discord developer portal as its Interactions Endpoint URL.
69
+ * Every request proves itself with the application's Ed25519 signature before
70
+ * anything is decoded; the Agent is reached only after the guild and channel
71
+ * pass the owner's allowlist.
72
+ */
73
+ export declare function standaloneDiscordApp(): import("hono/hono-base").HonoBase<{
74
+ Bindings: StandaloneDiscordEnv;
75
+ }, {
76
+ "/api/discord/interactions/:bindingId": {
77
+ $post: {
78
+ input: {
79
+ param: {
80
+ bindingId: string;
81
+ };
82
+ };
83
+ output: {};
84
+ outputFormat: string;
85
+ status: import("hono/utils/http-status").StatusCode;
86
+ };
87
+ };
88
+ }, "/", "/api/discord/interactions/:bindingId">;
89
+ export {};
@@ -0,0 +1,260 @@
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, discordDisplayName, 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
+ // Only a binding the directory knows names an Agent whose conversations are read.
50
+ const agentOf = async (principal, bindingId) => {
51
+ const listed = await directoryOf().discordList(principal);
52
+ const binding = "error" in listed
53
+ ? undefined
54
+ : listed.find((item) => item.bindingId === bindingId);
55
+ return binding === undefined ? null : env.AGENTS.getByName(binding.agentId);
56
+ };
57
+ return {
58
+ read: async (principal) => {
59
+ const listed = await directoryOf().discordList(principal);
60
+ return {
61
+ interactionsOrigin: env.OYSTER_ORIGIN,
62
+ agents: (await directoryOf().list()).map(({ agentId, name }) => ({
63
+ agentId,
64
+ name,
65
+ })),
66
+ discords: "error" in listed ? [] : listed,
67
+ };
68
+ },
69
+ create: (principal, input, requestId) => directoryOf().discordCreate(principal, input, requestId),
70
+ update: (principal, bindingId, input) => directoryOf().discordUpdate(principal, bindingId, input),
71
+ registerCommands: (principal, bindingId) => directoryOf().discordRegisterCommands(principal, bindingId),
72
+ conversations: async (principal, bindingId) => {
73
+ const agent = await agentOf(principal, bindingId);
74
+ return agent === null
75
+ ? []
76
+ : (await agent.bindingConversations(bindingId)).map(({ sessionId, label, lastEventAt }) => ({
77
+ sessionId,
78
+ label,
79
+ lastEventAt,
80
+ }));
81
+ },
82
+ transcript: async (principal, bindingId, sessionId) => {
83
+ const agent = await agentOf(principal, bindingId);
84
+ return agent === null
85
+ ? null
86
+ : agent.bindingTranscript(bindingId, sessionId);
87
+ },
88
+ undelivered: async (principal, bindingId) => {
89
+ const agent = await agentOf(principal, bindingId);
90
+ return agent === null ? [] : agent.discordUndelivered(bindingId);
91
+ },
92
+ };
93
+ }
94
+ const refusalStatus = {
95
+ not_granted: 403,
96
+ not_found: 404,
97
+ version_conflict: 409,
98
+ request_conflict: 409,
99
+ application_taken: 409,
100
+ invalid_input: 400,
101
+ custody_unavailable: 503,
102
+ limit: 409,
103
+ };
104
+ function refused(value) {
105
+ return "error" in value;
106
+ }
107
+ /**
108
+ * The owner's Discord controls. Each route is owner-direct: an App cannot bind
109
+ * a Discord application, or replace its sealed token, on the owner's behalf.
110
+ */
111
+ export function standaloneDiscordRoutes(control) {
112
+ const table = routes();
113
+ // A body that is not JSON is a malformed request, not a thrown failure.
114
+ const parseBody = async (context) => {
115
+ const decoded = Schema.decodeUnknownOption(Schema.fromJsonString(Schema.Json))(await context.req.text());
116
+ return Option.isSome(decoded)
117
+ ? { ok: true, value: decoded.value }
118
+ : { ok: false };
119
+ };
120
+ table.get("/api/discord", owner("direct"), async (context, { principal }) => {
121
+ context.header("Cache-Control", "no-store");
122
+ return context.json(await control.read(principal));
123
+ });
124
+ table.post("/api/discord", owner("direct"), async (context, { principal }) => {
125
+ context.header("Cache-Control", "no-store");
126
+ const body = await parseBody(context);
127
+ if (!body.ok)
128
+ return context.json({ error: "invalid_input" }, 400);
129
+ const parsed = createDiscordInputSchema.safeParse(body.value);
130
+ if (!parsed.success)
131
+ return context.json({ error: "invalid_input" }, 400);
132
+ const result = await control.create(principal, parsed.data, context.req.header("x-request-id") ?? "");
133
+ return refused(result)
134
+ ? context.json(result, refusalStatus[result.error])
135
+ : context.json({ binding: result }, 201);
136
+ });
137
+ table.put("/api/discord/:bindingId", owner("direct"), async (context, { principal }) => {
138
+ context.header("Cache-Control", "no-store");
139
+ const body = await parseBody(context);
140
+ if (!body.ok)
141
+ return context.json({ error: "invalid_input" }, 400);
142
+ const parsed = updateDiscordInputSchema.safeParse(body.value);
143
+ if (!parsed.success)
144
+ return context.json({ error: "invalid_input" }, 400);
145
+ const result = await control.update(principal, context.req.param("bindingId"), parsed.data);
146
+ return refused(result)
147
+ ? context.json(result, refusalStatus[result.error])
148
+ : context.json({ binding: result });
149
+ });
150
+ table.post("/api/discord/:bindingId/commands", owner("direct"), async (context, { principal }) => {
151
+ context.header("Cache-Control", "no-store");
152
+ const result = await control.registerCommands(principal, context.req.param("bindingId"));
153
+ return "error" in result
154
+ ? context.json(result, refusalStatus[result.error])
155
+ : context.json(result);
156
+ });
157
+ table.get("/api/discord/:bindingId/conversations", owner("direct"), async (context, { principal }) => {
158
+ context.header("Cache-Control", "no-store");
159
+ return context.json({
160
+ conversations: await control.conversations(principal, context.req.param("bindingId")),
161
+ });
162
+ });
163
+ table.get("/api/discord/:bindingId/undelivered", owner("direct"), async (context, { principal }) => {
164
+ context.header("Cache-Control", "no-store");
165
+ return context.json({
166
+ undelivered: await control.undelivered(principal, context.req.param("bindingId")),
167
+ });
168
+ });
169
+ table.get("/api/discord/:bindingId/conversations/:sessionId", owner("direct"), async (context, { principal }) => {
170
+ context.header("Cache-Control", "no-store");
171
+ const transcript = await control.transcript(principal, context.req.param("bindingId"), context.req.param("sessionId"));
172
+ return transcript === null
173
+ ? context.json({ error: "not_found" }, 404)
174
+ : context.json(transcript);
175
+ });
176
+ return table;
177
+ }
178
+ /** A request body larger than this is not a Discord interaction. */
179
+ const INTERACTION_BODY_LIMIT = 100_000;
180
+ const decodeJson = Schema.decodeUnknownOption(Schema.fromJsonString(Schema.Json));
181
+ /**
182
+ * The public Discord door: one URL per bound application, which the owner
183
+ * pastes into the Discord developer portal as its Interactions Endpoint URL.
184
+ * Every request proves itself with the application's Ed25519 signature before
185
+ * anything is decoded; the Agent is reached only after the guild and channel
186
+ * pass the owner's allowlist.
187
+ */
188
+ export function standaloneDiscordApp() {
189
+ return new Hono().post("/api/discord/interactions/:bindingId", async (context) => {
190
+ const { env } = context;
191
+ const found = await agentDirectoryForScope(env, tenantScope(defaultTenant, env.OYSTER_ORIGIN)).channelBinding(context.req.param("bindingId"));
192
+ if (found === null || !isDiscordBinding(found))
193
+ return context.json({ error: "not_found" }, 404);
194
+ const binding = found;
195
+ const body = await context.req.text();
196
+ if (body.length > INTERACTION_BODY_LIMIT)
197
+ return context.json({ error: "too_large" }, 413);
198
+ const verdict = await verifyDiscordRequest({
199
+ publicKey: binding.selector.publicKey,
200
+ signature: context.req.header("x-signature-ed25519"),
201
+ timestamp: context.req.header("x-signature-timestamp"),
202
+ body,
203
+ nowSeconds: Date.now() / 1_000,
204
+ });
205
+ if (verdict !== "verified")
206
+ return context.text("invalid request signature", 401);
207
+ const json = decodeJson(body);
208
+ const decoded = interactionSchema.safeParse(Option.getOrUndefined(json));
209
+ if (!decoded.success)
210
+ return context.json({ error: "invalid_interaction" }, 400);
211
+ const interaction = decoded.data;
212
+ if (interaction.type === 1)
213
+ return context.json(pongResponse);
214
+ if (interaction.application_id !== binding.selector.applicationId)
215
+ return context.json({ error: "wrong_application" }, 400);
216
+ if (binding.lifecycle !== "active")
217
+ return context.json(ephemeralResponse("This Agent is paused."));
218
+ const userId = interaction.member?.user.id ?? interaction.user?.id;
219
+ const { guild_id: guildId, channel_id: channelId } = interaction;
220
+ if (guildId === undefined ||
221
+ channelId === undefined ||
222
+ userId === undefined)
223
+ return context.json(ephemeralResponse("Ask in a server channel, not in a direct message."));
224
+ if (!discordPlaceAllowed(binding.selector, { guildId, channelId }))
225
+ return context.json(ephemeralResponse("This channel is not set up for this Agent."));
226
+ const ask = (text, echo) => {
227
+ const trimmed = text.trim();
228
+ if (trimmed.length === 0 || trimmed.length > DISCORD_ASK_LIMIT)
229
+ return context.json(ephemeralResponse("Keep it between 1 and 1,000 characters."));
230
+ const question = {
231
+ interactionId: interaction.id,
232
+ applicationId: binding.selector.applicationId,
233
+ interactionToken: interaction.token,
234
+ guildId,
235
+ channelId,
236
+ userId,
237
+ text: trimmed,
238
+ displayName: discordDisplayName(interaction),
239
+ echo,
240
+ };
241
+ // The answer outlives Discord's three seconds; it follows by webhook.
242
+ context.executionCtx.waitUntil(Promise.resolve(env.AGENTS.getByName(binding.agentId).askDiscord(binding.bindingId, question)));
243
+ return context.json(deferredResponse);
244
+ };
245
+ if (interaction.type === 2) {
246
+ if (interaction.data.name !== ASK_COMMAND)
247
+ return context.json(ephemeralResponse("Unknown command."));
248
+ const option = interaction.data.options?.find(({ name }) => name === ASK_OPTION);
249
+ return ask(z.string().catch("").parse(option?.value));
250
+ }
251
+ if (interaction.data.custom_id !== REPLY_ID)
252
+ return context.json(ephemeralResponse("Unknown action."));
253
+ if (interaction.type === 3)
254
+ return context.json(replyModalResponse);
255
+ const reply = interaction.data.components
256
+ .flatMap((row) => row.components)
257
+ .find(({ custom_id: id }) => id === REPLY_TEXT_ID);
258
+ return ask(reply?.value ?? "", reply?.value.trim());
259
+ });
260
+ }
@@ -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
  }
@@ -211,10 +211,13 @@ export declare abstract class StandaloneRegistry extends OysterRegistry implemen
211
211
  appId: string;
212
212
  sourceRevision: string;
213
213
  requestedBy: string;
214
+ /**
215
+ * The installation whose admitted APPS call asks; it must own the source.
216
+ * Omitted only by the host owner's own HTTP build route.
217
+ */
218
+ callerInstallationId?: string;
214
219
  workflow?: {
215
220
  requestId: string;
216
- /** The installation whose admitted Workflow node asks; it must own the source. */
217
- callerInstallationId: string;
218
221
  installationId?: string;
219
222
  };
220
223
  }): Promise<OysterBuildStartResult>;
@@ -416,11 +416,13 @@ export class StandaloneRegistry extends OysterRegistry {
416
416
  sourceRevision: input.sourceRevision,
417
417
  requestedBy: input.requestedBy,
418
418
  };
419
+ // An APPS caller builds only its own installation's registered App. A
420
+ // foreign or template App reads as unregistered, never as another's
421
+ // existence.
422
+ if (input.callerInstallationId !== undefined &&
423
+ !sourceOwnedBy(builds.readSource(input.appId), input.callerInstallationId))
424
+ return { kind: "refused", reason: "no_source" };
419
425
  if (input.workflow !== undefined) {
420
- // A Workflow builds only its own installation's registered App. A
421
- // foreign App reads as unregistered, never as another's existence.
422
- if (!sourceOwnedBy(builds.readSource(input.appId), input.workflow.callerInstallationId))
423
- return { kind: "refused", reason: "no_source" };
424
426
  request.requestId = input.workflow.requestId;
425
427
  if (input.workflow.installationId !== undefined)
426
428
  request.installAt = input.workflow.installationId;
@@ -178,7 +178,7 @@ export function standaloneWebsiteControl(env, directoryOf) {
178
178
  const agent = await agentOf(principal, bindingId);
179
179
  return agent === null
180
180
  ? []
181
- : (await agent.websiteConversations(bindingId)).map(({ sessionId, label, lastEventAt }) => ({
181
+ : (await agent.bindingConversations(bindingId)).map(({ sessionId, label, lastEventAt }) => ({
182
182
  sessionId,
183
183
  label,
184
184
  lastEventAt,
@@ -188,7 +188,7 @@ export function standaloneWebsiteControl(env, directoryOf) {
188
188
  const agent = await agentOf(principal, bindingId);
189
189
  return agent === null
190
190
  ? null
191
- : agent.websiteTranscript(bindingId, sessionId);
191
+ : agent.bindingTranscript(bindingId, sessionId);
192
192
  },
193
193
  };
194
194
  }
@@ -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));
@@ -31,6 +31,7 @@ import { serveDoors } from "../authorization.js";
31
31
  import { standaloneWorkerRoutes } from "./worker-routes.js";
32
32
  import { HTTPException } from "hono/http-exception";
33
33
  import { standaloneOwnerRoutes } from "./owner-routes.js";
34
+ import { standaloneDiscordApp } from "./discord-channels.js";
34
35
  import { standaloneWebsiteApp, } from "./website-channels.js";
35
36
  import { standaloneComputerSelection } from "./computer-fleet.js";
36
37
  import { serveOysterComputerEgress, } from "./computer-egress.js";
@@ -168,6 +169,8 @@ export class OysterComputerEgress extends WorkerEntrypoint {
168
169
  }
169
170
  /** The public website channel: one edge, authenticated per request. */
170
171
  const website = standaloneWebsiteApp();
172
+ /** The public Discord channel: one signed door per bound application. */
173
+ const discord = standaloneDiscordApp();
171
174
  const standaloneWorkerErrorHandler = (error, context) => {
172
175
  if (error instanceof StandaloneSeedConfigurationChanged) {
173
176
  const { refusal } = error;
@@ -197,6 +200,7 @@ export default {
197
200
  return serveDoors(standaloneWorkerRoutes({
198
201
  machineLink: (incoming) => serveDoors(standaloneMachineLinkRoutes(env).onError(standaloneWorkerErrorHandler)).fetch(incoming, env, context),
199
202
  website: (incoming) => Promise.resolve(website.fetch(incoming, env, context)),
203
+ discord: (incoming) => Promise.resolve(discord.fetch(incoming, env, context)),
200
204
  localBackendDial: async (incoming) => {
201
205
  const dial = ownerLocalBackendDialPath.exec(new URL(incoming.url).pathname);
202
206
  // Only a Computer this Oyster owns is addressed; no stray object is made.
@@ -330,9 +330,23 @@ type OysterAgents = Readonly<{
330
330
  media: "ready" | "missing";
331
331
  }>
332
332
  >;
333
- modelKeys: Promise<readonly ModelKeyRecord[]>;
333
+ modelKeys: Promise<
334
+ readonly Readonly<{
335
+ keyId: string;
336
+ provider: StandaloneModelKeyProvider;
337
+ label: string;
338
+ createdAt: number;
339
+ validatedAt: number;
340
+ }>[]
341
+ >;
334
342
  sealModelKey: Promise<
335
- | ModelKeyRecord
343
+ | Readonly<{
344
+ keyId: string;
345
+ provider: StandaloneModelKeyProvider;
346
+ label: string;
347
+ createdAt: number;
348
+ validatedAt: number;
349
+ }>
336
350
  | Readonly<{
337
351
  error: ModelKeyRefusal;
338
352
  }>
@@ -434,6 +448,18 @@ Stable reason for rejecting a model or credential source before a run.
434
448
 
435
449
  ---
436
450
 
451
+ ### StandaloneModelKeyProvider
452
+
453
+ ```ts
454
+ type StandaloneModelKeyProvider =
455
+ CatalogModelKeyProvider | "cloudflare-workers-ai";
456
+ ```
457
+
458
+ Standalone custody takes every catalog provider's API key, plus an owner's
459
+ Cloudflare account and token.
460
+
461
+ ---
462
+
437
463
  ### ModelKeyRefusal
438
464
 
439
465
  ```ts
@@ -454,16 +480,16 @@ Why a key could not be stored or used; stable, secret-free.
454
480
  ### ModelKeyRecord
455
481
 
456
482
  ```ts
457
- type ModelKeyRecord = Omit<HostedModelKeyRecord, "provider"> & object;
483
+ type ModelKeyRecord = Readonly<{
484
+ keyId: string;
485
+ provider: StandaloneModelKeyProvider;
486
+ label: string;
487
+ createdAt: number;
488
+ validatedAt: number;
489
+ }>;
458
490
  ```
459
491
 
460
- Standalone custody also accepts an owner’s Cloudflare account and token.
461
-
462
- #### Type Declaration
463
-
464
- | Name | Type |
465
- | ---------- | ------------------------------------------------------------------- |
466
- | `provider` | `HostedModelKeyRecord`\[`"provider"`\] \| `"cloudflare-workers-ai"` |
492
+ A stored key as the owner sees it: no secret, no custody locator.
467
493
 
468
494
  ---
469
495