@fungi.computer/oyster 0.10.0 → 0.11.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 (63) hide show
  1. package/README.md +33 -2
  2. package/dist/agents.d.ts +66 -22
  3. package/dist/agents.js +128 -38
  4. package/dist/authorization.d.ts +25 -3
  5. package/dist/authorization.js +47 -14
  6. package/dist/browser/capability-source.d.ts +23 -5
  7. package/dist/browser/capability-source.js +19 -22
  8. package/dist/browser/index.d.ts +2 -1
  9. package/dist/browser/index.js +1 -0
  10. package/dist/browser/live-view.d.ts +38 -0
  11. package/dist/browser/live-view.js +179 -0
  12. package/dist/channels/binding.d.ts +2 -0
  13. package/dist/channels/run-decision.d.ts +33 -0
  14. package/dist/channels/run-decision.js +25 -0
  15. package/dist/channels/visitor-channel.d.ts +84 -14
  16. package/dist/channels/visitor-channel.js +55 -32
  17. package/dist/channels/visitor-edge.d.ts +18 -2
  18. package/dist/channels/visitor-edge.js +67 -5
  19. package/dist/channels/visitors.d.ts +4 -0
  20. package/dist/channels/visitors.js +22 -1
  21. package/dist/channels/web-binding.d.ts +117 -0
  22. package/dist/channels/web-binding.js +227 -0
  23. package/dist/embed-metafiles.d.ts +8 -0
  24. package/dist/embed-metafiles.js +2 -0
  25. package/dist/embed-scripts.d.ts +8 -0
  26. package/dist/embed-scripts.js +3 -0
  27. package/dist/host.d.ts +3 -1
  28. package/dist/host.js +6 -1
  29. package/dist/page/embed-challenge.d.ts +19 -0
  30. package/dist/page/embed-challenge.js +45 -0
  31. package/dist/page/embed-error.d.ts +2 -0
  32. package/dist/page/embed-error.js +16 -0
  33. package/dist/page/embed-loader-protocol.d.ts +12 -0
  34. package/dist/page/embed-loader-protocol.js +29 -0
  35. package/dist/standalone/agent-connections.d.ts +22 -19
  36. package/dist/standalone/agent-connections.js +150 -106
  37. package/dist/standalone/agents.d.ts +168 -14
  38. package/dist/standalone/agents.js +310 -17
  39. package/dist/standalone/browser.d.ts +14 -2
  40. package/dist/standalone/browser.js +52 -4
  41. package/dist/standalone/channel-session-door.d.ts +4 -0
  42. package/dist/standalone/channel-session-door.js +72 -0
  43. package/dist/standalone/owner-routes.d.ts +4 -3
  44. package/dist/standalone/owner-routes.js +7 -1
  45. package/dist/standalone/visitor-edge.d.ts +36 -0
  46. package/dist/standalone/visitor-edge.js +67 -0
  47. package/dist/standalone/visitor-proof.d.ts +23 -0
  48. package/dist/standalone/visitor-proof.js +67 -0
  49. package/dist/standalone/website-channels.d.ts +134 -0
  50. package/dist/standalone/website-channels.js +262 -0
  51. package/dist/standalone/worker-routes.d.ts +4 -1
  52. package/dist/standalone/worker-routes.js +3 -0
  53. package/dist/standalone/worker.d.ts +2 -1
  54. package/dist/standalone/worker.js +4 -0
  55. package/dist/testing/capabilities.d.ts +3 -0
  56. package/dist/testing/capabilities.js +1 -0
  57. package/dist/testing/installation.d.ts +4 -2
  58. package/dist/testing/installation.js +7 -2
  59. package/dist/workers-git.js +2 -2
  60. package/docs/api/agents.md +103 -36
  61. package/docs/api/browser.md +115 -8
  62. package/docs/api/workers-git.md +6 -6
  63. package/package.json +31 -6
@@ -0,0 +1,36 @@
1
+ import type { Context, Env as HonoEnv } from "hono";
2
+ import type { ConversationBinding } from "../channels/binding.js";
3
+ import { type EdgeVerifiedVisitor, type VisitorSiteFacts, type VisitorTurnstile } from "../channels/visitor-edge.js";
4
+ import type { AuthenticatedChannelVisitor } from "../channels/visitor-channel.js";
5
+ import type { ChannelVisitors } from "../channels/visitors.js";
6
+ import type { StandaloneAgentBase } from "./agents.js";
7
+ /** The central owner keeps every binding's visitor families and address caps.
8
+ * A Durable Object can supply these four RPCs; no token store lives in Agents. */
9
+ export type StandaloneVisitorIdentity = Pick<ChannelVisitors, "mint" | "refresh" | "rotate" | "authenticate">;
10
+ export type StandaloneVisitorAgent = Pick<StandaloneAgentBase, "sendChannelVisitor" | "withdrawChannelVisitor" | "latestPendingChannelVisitor" | "openChannelVisitor" | "watchChannelVisitor">;
11
+ /** A web binding and the Agent it puts in front of visitors. */
12
+ export type StandaloneVisitorBinding = ConversationBinding & Readonly<{
13
+ agentId: string;
14
+ }>;
15
+ /** A resolved site: the binding the edge enforces and the chrome it serves. */
16
+ export type StandaloneVisitorSite = Readonly<{
17
+ binding: StandaloneVisitorBinding;
18
+ facts: VisitorSiteFacts;
19
+ }>;
20
+ /**
21
+ * Web sites with central identity and one dedicated Agent per site. The host
22
+ * supplies the address salt, the site lookup and the Agent; the edge
23
+ * authenticates before selecting an Agent and never sends a bearer into it.
24
+ */
25
+ export declare function standaloneVisitorEdge<E extends HonoEnv>(host: {
26
+ /** Re-read on every request and stream beat; suspension never freezes. */
27
+ site: (context: Context<E>, siteKey: string) => StandaloneVisitorSite | null | Promise<StandaloneVisitorSite | null>;
28
+ visitors: (context: Context<E>) => StandaloneVisitorIdentity;
29
+ agent: (context: Context<E>, binding: StandaloneVisitorBinding, visitor: EdgeVerifiedVisitor<AuthenticatedChannelVisitor>) => StandaloneVisitorAgent | Promise<StandaloneVisitorAgent>;
30
+ /** Private host secret shared with the Agent subclass, never the browser. */
31
+ proofKey: (context: Context<E>) => string;
32
+ addressHash: (context: Context<E>) => Promise<string>;
33
+ turnstile: (context: Context<E>) => VisitorTurnstile;
34
+ assetPath: (kind: "widget" | "styles") => string;
35
+ onError: (error: Error, context: Context<E>) => Response | Promise<Response>;
36
+ }): import("hono").Hono<E, import("hono/types").BlankSchema, "/">;
@@ -0,0 +1,67 @@
1
+ import { createVisitorEdge, } from "../channels/visitor-edge.js";
2
+ import { proveVisitor } from "./visitor-proof.js";
3
+ /**
4
+ * Web sites with central identity and one dedicated Agent per site. The host
5
+ * supplies the address salt, the site lookup and the Agent; the edge
6
+ * authenticates before selecting an Agent and never sends a bearer into it.
7
+ */
8
+ export function standaloneVisitorEdge(host) {
9
+ const identityDoor = (context, site) => ({
10
+ [Symbol.dispose]: () => undefined,
11
+ readChannelSite: ({ bindingId, siteKey: key }) => Promise.resolve(bindingId === site.bindingId &&
12
+ site.binding.selector.provider === "web" &&
13
+ key === site.binding.selector.siteKey &&
14
+ site.binding.lifecycle === "active"
15
+ ? site.facts
16
+ : null),
17
+ mintChannelVisitor: ({ siteKey: key, addressHash }) => host.visitors(context).mint(site.binding, key, addressHash),
18
+ refreshChannelVisitor: ({ refreshSecret }) => host.visitors(context).refresh(site.binding, refreshSecret),
19
+ rotateChannelVisitor: ({ siteKey: key, accessToken, addressHash }) => host
20
+ .visitors(context)
21
+ .rotate(site.binding, key, accessToken, addressHash),
22
+ sendAsChannelVisitor: () => Promise.resolve({ kind: "unauthorized" }),
23
+ withdrawAsChannelVisitor: () => Promise.resolve({ kind: "unauthorized" }),
24
+ latestPendingAsChannelVisitor: () => Promise.resolve({ kind: "unauthorized" }),
25
+ openVisitorSession: () => Promise.resolve({ kind: "unauthorized" }),
26
+ watchAsChannelVisitor: () => Promise.resolve({ kind: "unauthorized" }),
27
+ // The old GET /conversation has no standalone caller. Do not invent an
28
+ // unauthenticated site-wide transcript for a per-visitor Agent directory.
29
+ readAsChannelVisitor: () => Promise.resolve({ kind: "unauthorized" }),
30
+ });
31
+ return createVisitorEdge({
32
+ resolveSite: async (context, key) => {
33
+ const resolved = await host.site(context, key);
34
+ if (resolved === null)
35
+ return null;
36
+ const { binding, facts } = resolved;
37
+ return binding.selector.provider === "web" &&
38
+ binding.selector.siteKey === key
39
+ ? { bindingId: binding.bindingId, binding, facts }
40
+ : null;
41
+ },
42
+ openSite: (context, site) => Promise.resolve(identityDoor(context, site)),
43
+ authenticateVisitor: (context, site, token) => host.visitors(context).authenticate(site.bindingId, token),
44
+ openChannel: async (context, site, visitor) => {
45
+ const proven = await proveVisitor(site.bindingId, visitor, host.proofKey(context));
46
+ const agent = await host.agent(context, site.binding, visitor);
47
+ const identity = identityDoor(context, site);
48
+ return {
49
+ [Symbol.dispose]: () => undefined,
50
+ readChannelSite: identity.readChannelSite,
51
+ mintChannelVisitor: identity.mintChannelVisitor,
52
+ refreshChannelVisitor: identity.refreshChannelVisitor,
53
+ rotateChannelVisitor: identity.rotateChannelVisitor,
54
+ readAsChannelVisitor: identity.readAsChannelVisitor,
55
+ sendAsChannelVisitor: ({ requestId, text }) => agent.sendChannelVisitor(site.bindingId, proven, requestId, text),
56
+ withdrawAsChannelVisitor: ({ requestId }) => agent.withdrawChannelVisitor(site.bindingId, proven, requestId),
57
+ latestPendingAsChannelVisitor: () => agent.latestPendingChannelVisitor(site.bindingId, proven),
58
+ openVisitorSession: ({ options }) => agent.openChannelVisitor(site.bindingId, proven, options),
59
+ watchAsChannelVisitor: () => agent.watchChannelVisitor(site.bindingId, proven),
60
+ };
61
+ },
62
+ addressHash: host.addressHash,
63
+ turnstile: host.turnstile,
64
+ assetPath: host.assetPath,
65
+ onError: host.onError,
66
+ });
67
+ }
@@ -0,0 +1,23 @@
1
+ import { z } from "zod";
2
+ import type { AuthenticatedChannelVisitor } from "../channels/visitor-channel.js";
3
+ import type { EdgeVerifiedVisitor } from "../channels/visitor-edge.js";
4
+ /** An internal, short-lived assertion, not the visitor's bearer. The Worker
5
+ * and its Agent owner receive the same host secret; no public route reads it.
6
+ * This is required because a TypeScript brand disappears over DO RPC. */
7
+ declare const proofSchema: z.ZodObject<{
8
+ visitorId: z.ZodString;
9
+ addressHash: z.ZodString;
10
+ bindingId: z.ZodString;
11
+ expiresAt: z.ZodNumber;
12
+ signature: z.ZodBase64URL;
13
+ }, z.core.$strict>;
14
+ export type ProvenVisitor = AuthenticatedChannelVisitor & Readonly<{
15
+ edgeProof: z.infer<typeof proofSchema>;
16
+ }>;
17
+ /** The edge calls this only after the central visitor owner authenticated
18
+ * this request. Neither bearer nor proof key crosses to the public client. */
19
+ export declare function proveVisitor(bindingId: string, visitor: EdgeVerifiedVisitor<AuthenticatedChannelVisitor>, secret: string, now?: number): Promise<ProvenVisitor>;
20
+ /** Every public Agent RPC must verify before accessing a conversation or
21
+ * running a model. A forged or stale identity cannot cross the DO boundary. */
22
+ export declare function verifyVisitor(bindingId: string, value: unknown, secret: string | null, now?: number): Promise<ProvenVisitor>;
23
+ export {};
@@ -0,0 +1,67 @@
1
+ import { z } from "zod";
2
+ /** An internal, short-lived assertion, not the visitor's bearer. The Worker
3
+ * and its Agent owner receive the same host secret; no public route reads it.
4
+ * This is required because a TypeScript brand disappears over DO RPC. */
5
+ const proofSchema = z.strictObject({
6
+ visitorId: z.string().min(1).max(160),
7
+ addressHash: z.string().min(1).max(160),
8
+ bindingId: z.string().min(1).max(160),
9
+ expiresAt: z.number().int().nonnegative(),
10
+ signature: z.base64url().length(43),
11
+ });
12
+ const encoder = new TextEncoder();
13
+ const maxAge = 30_000;
14
+ const input = (proof) => JSON.stringify([
15
+ "oyster:website-visitor:v1",
16
+ proof.bindingId,
17
+ proof.visitorId,
18
+ proof.addressHash,
19
+ proof.expiresAt,
20
+ ]);
21
+ async function keyFor(secret) {
22
+ if (encoder.encode(secret).length < 32)
23
+ throw new Error("Website channel proof key is unavailable");
24
+ return crypto.subtle.importKey("raw", encoder.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign", "verify"]);
25
+ }
26
+ /** The edge calls this only after the central visitor owner authenticated
27
+ * this request. Neither bearer nor proof key crosses to the public client. */
28
+ export async function proveVisitor(bindingId, visitor, secret, now = Date.now()) {
29
+ const fields = {
30
+ bindingId,
31
+ visitorId: visitor.visitorId,
32
+ addressHash: visitor.addressHash,
33
+ expiresAt: now + maxAge,
34
+ };
35
+ const bytes = new Uint8Array(await crypto.subtle.sign("HMAC", await keyFor(secret), encoder.encode(input(fields))));
36
+ const signature = btoa(String.fromCharCode(...bytes))
37
+ .replaceAll("+", "-")
38
+ .replaceAll("/", "_")
39
+ .replace(/=+$/u, "");
40
+ return { ...visitor, edgeProof: { ...fields, signature } };
41
+ }
42
+ /** Every public Agent RPC must verify before accessing a conversation or
43
+ * running a model. A forged or stale identity cannot cross the DO boundary. */
44
+ export async function verifyVisitor(bindingId, value, secret, now = Date.now()) {
45
+ const visitor = z
46
+ .strictObject({
47
+ visitorId: z.string().min(1).max(160),
48
+ addressHash: z.string().min(1).max(160),
49
+ expiresAt: z.number().int().nonnegative(),
50
+ edgeProof: proofSchema,
51
+ })
52
+ .safeParse(value);
53
+ if (!visitor.success ||
54
+ secret === null ||
55
+ visitor.data.edgeProof.bindingId !== bindingId ||
56
+ visitor.data.edgeProof.visitorId !== visitor.data.visitorId ||
57
+ visitor.data.edgeProof.addressHash !== visitor.data.addressHash ||
58
+ visitor.data.expiresAt < now ||
59
+ visitor.data.edgeProof.expiresAt < now ||
60
+ visitor.data.edgeProof.expiresAt > now + maxAge)
61
+ throw new Error("Website channel identity is unauthorized");
62
+ const { signature, ...fields } = visitor.data.edgeProof;
63
+ const bytes = Uint8Array.from(atob(signature.replaceAll("-", "+").replaceAll("_", "/") + "="), (char) => char.charCodeAt(0));
64
+ if (!(await crypto.subtle.verify("HMAC", await keyFor(secret), bytes, encoder.encode(input(fields)))))
65
+ throw new Error("Website channel identity is unauthorized");
66
+ return visitor.data;
67
+ }
@@ -0,0 +1,134 @@
1
+ import type { Avatar } from "@fungi.computer/sprite/avatar";
2
+ import { type Routes } from "../authorization.js";
3
+ import { type CreateWebsiteInput, type UpdateWebsiteInput, type WebsiteBinding } from "../channels/web-binding.js";
4
+ import type { VisitorSql } from "../channels/visitors.js";
5
+ import type { VisitorSiteFacts } from "../channels/visitor-edge.js";
6
+ import type { WebsiteTranscript } from "@fungi.computer/nacre/website-channels";
7
+ import type { OysterEnv } from "../host.js";
8
+ import { type TenantPrincipal } from "../tenant.js";
9
+ import { agentDirectoryForScope } from "./agent-directory.js";
10
+ import type { StandaloneAgentsEnv } from "./agents.js";
11
+ /** A public site: its binding and the chrome a visitor sees. */
12
+ export type WebsiteSite = Readonly<{
13
+ binding: WebsiteBinding;
14
+ facts: VisitorSiteFacts;
15
+ }>;
16
+ /** The chosen Agent's public face, or null when it is no longer in the directory. */
17
+ export type WebsiteAgentIdentity = Readonly<{
18
+ name: string;
19
+ avatar: Avatar;
20
+ }>;
21
+ /**
22
+ * The directory's website owner: bindings and visitor identities on its own
23
+ * store, with the chosen Agent's identity read from the directory itself.
24
+ */
25
+ export declare function createWebsiteChannelOwner(options: Readonly<{
26
+ sql: VisitorSql;
27
+ transactionSync: <T>(body: () => T) => T;
28
+ agentExists: (agentId: string) => boolean;
29
+ agentIdentity: (agentId: string) => WebsiteAgentIdentity | null;
30
+ }>): {
31
+ bindings: {
32
+ read: (bindingId: string) => WebsiteBinding | null;
33
+ readBySiteKey: (siteKey: string) => WebsiteBinding | null;
34
+ list: () => readonly WebsiteBinding[];
35
+ create: (rawInput: CreateWebsiteInput, requestId: string) => WebsiteBinding;
36
+ update: (bindingId: string, rawInput: UpdateWebsiteInput) => WebsiteBinding;
37
+ };
38
+ visitors: {
39
+ ensure: () => void;
40
+ mint: (binding: import("../channels/binding.js").ConversationBinding | null, siteKey: string, addressHash: string) => Promise<import("../channels/visitors.js").VisitorGrant>;
41
+ refresh: (binding: import("../channels/binding.js").ConversationBinding | null, refreshSecret: string) => Promise<import("../channels/visitors.js").VisitorGrant>;
42
+ authenticate: (bindingId: string, accessToken: string) => Promise<Readonly<{
43
+ visitorId: string;
44
+ expiresAt: number;
45
+ addressHash: string;
46
+ }> | null>;
47
+ live: (bindingId: string, visitorId: string) => boolean;
48
+ forget: (visitorId: string) => void;
49
+ rotate: (binding: import("../channels/binding.js").ConversationBinding | null, siteKey: string, token: string, addressHash: string) => Promise<import("../channels/visitors.js").VisitorGrant | Readonly<{
50
+ kind: "unauthorized";
51
+ }>>;
52
+ };
53
+ /** A public site key resolves only to an active site with a live Agent. */
54
+ site: (siteKey: string) => WebsiteSite | null;
55
+ };
56
+ /** The directory's website owner. */
57
+ export type WebsiteChannelOwner = ReturnType<typeof createWebsiteChannelOwner>;
58
+ /** Why an owner's website command was refused. */
59
+ export type WebsiteRefusal = Readonly<{
60
+ error: "not_granted" | "not_found" | "version_conflict" | "request_conflict" | "invalid_input";
61
+ }>;
62
+ /** Run one binding command, turning its closed failures into data. */
63
+ export declare function websiteOutcome<T>(command: () => T): T | WebsiteRefusal;
64
+ /** The host secrets a website needs; absent or short means the edge is closed. */
65
+ export type StandaloneWebsiteEnv = Pick<StandaloneAgentsEnv, "AGENTS" | "AGENT_DIRECTORY" | "OYSTER_ORIGIN" | "OYSTER_WEBSITE_PROOF_KEY"> & Readonly<{
66
+ /** Host secret (at least 32 bytes) salting the visitor address hash. */
67
+ OYSTER_WEBSITE_ADDRESS_KEY?: string;
68
+ TURNSTILE?: string;
69
+ TURNSTILE_SITE_KEY?: string;
70
+ TURNSTILE_SECRET_KEY?: string;
71
+ }>;
72
+ /**
73
+ * The public website surface, on the same paths as Hub's: the launcher, the
74
+ * visitor document and the visitor API. Every visitor request authenticates
75
+ * once here; Agents receive only a signed, short-lived assertion.
76
+ */
77
+ export declare function standaloneWebsiteApp(): import("hono/hono-base").HonoBase<{
78
+ Bindings: StandaloneWebsiteEnv;
79
+ }, import("hono/types").MergeSchemaPath<import("hono/types").BlankSchema, "/"> | ({
80
+ "/embed/v1.js": {
81
+ $get: {
82
+ input: {};
83
+ output: {};
84
+ outputFormat: string;
85
+ status: import("hono/utils/http-status").StatusCode;
86
+ };
87
+ };
88
+ } & {
89
+ "/embed/widget.js": {
90
+ $get: {
91
+ input: {};
92
+ output: {};
93
+ outputFormat: string;
94
+ status: import("hono/utils/http-status").StatusCode;
95
+ };
96
+ };
97
+ } & {
98
+ "/styles.css": {
99
+ $get: {
100
+ input: {};
101
+ output: {};
102
+ outputFormat: string;
103
+ status: import("hono/utils/http-status").StatusCode;
104
+ };
105
+ };
106
+ }), "/", "/styles.css">;
107
+ /** What the owner's website routes need from the directory and the Agents. */
108
+ export type StandaloneWebsiteControl = Readonly<{
109
+ read: (principal: TenantPrincipal) => Promise<Readonly<{
110
+ embedOrigin: string;
111
+ agents: readonly Readonly<{
112
+ agentId: string;
113
+ name: string;
114
+ }>[];
115
+ websites: readonly WebsiteBinding[];
116
+ }>>;
117
+ create: (principal: TenantPrincipal, input: CreateWebsiteInput, requestId: string) => Promise<WebsiteBinding | WebsiteRefusal>;
118
+ update: (principal: TenantPrincipal, bindingId: string, input: UpdateWebsiteInput) => Promise<WebsiteBinding | WebsiteRefusal>;
119
+ conversations: (principal: TenantPrincipal, bindingId: string) => Promise<readonly Readonly<{
120
+ sessionId: string;
121
+ label: string;
122
+ lastEventAt: number;
123
+ }>[]>;
124
+ transcript: (principal: TenantPrincipal, bindingId: string, sessionId: string) => Promise<WebsiteTranscript | null>;
125
+ }>;
126
+ /** What the owner's website controls need from their host. */
127
+ export type StandaloneWebsiteControlEnv = Pick<StandaloneAgentsEnv, "AGENTS" | "OYSTER_ORIGIN">;
128
+ /** The owner's website controls over the directory and each website's Agent. */
129
+ export declare function standaloneWebsiteControl(env: StandaloneWebsiteControlEnv, directoryOf: () => ReturnType<typeof agentDirectoryForScope>): StandaloneWebsiteControl;
130
+ /**
131
+ * The owner's website controls. Each route is owner-direct: an App cannot
132
+ * create a public surface, or read what its visitors said, on the owner's behalf.
133
+ */
134
+ export declare function standaloneWebsiteRoutes(control: StandaloneWebsiteControl): Routes<OysterEnv>;
@@ -0,0 +1,262 @@
1
+ /**
2
+ * The standalone website channel: an owner puts a chat with one of their
3
+ * Agents on a separate website. The directory owns the bindings and the
4
+ * anonymous visitor identities; each website is served by a dedicated Agent
5
+ * instance (never the owner's own Agent), and the public edge authenticates a
6
+ * visitor once before any Agent is selected.
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 { owner, routes } from "../authorization.js";
13
+ import { createWebsiteBindings, createWebsiteInputSchema, updateWebsiteInputSchema, WebsiteBindingError, } from "../channels/web-binding.js";
14
+ import { createChannelVisitors } from "../channels/visitors.js";
15
+ import { readTurnstileConfiguration } from "../turnstile.js";
16
+ import { tenantScope, defaultTenant } from "../tenant.js";
17
+ import { agentDirectoryForScope } from "./agent-directory.js";
18
+ import { standaloneVisitorEdge } from "./visitor-edge.js";
19
+ /**
20
+ * The directory's website owner: bindings and visitor identities on its own
21
+ * store, with the chosen Agent's identity read from the directory itself.
22
+ */
23
+ export function createWebsiteChannelOwner(options) {
24
+ const bindings = createWebsiteBindings(options);
25
+ const visitors = createChannelVisitors({
26
+ sql: options.sql,
27
+ transactionSync: options.transactionSync,
28
+ now: () => Date.now(),
29
+ });
30
+ return {
31
+ bindings,
32
+ visitors,
33
+ /** A public site key resolves only to an active site with a live Agent. */
34
+ site: (siteKey) => {
35
+ const binding = bindings.readBySiteKey(siteKey);
36
+ if (binding === null)
37
+ return null;
38
+ const agent = options.agentIdentity(binding.agentId);
39
+ if (agent === null)
40
+ return null;
41
+ const { origins, accent, turnstile } = binding.selector;
42
+ const facts = { ...agent, origins };
43
+ if (accent !== undefined)
44
+ facts.accent = accent;
45
+ if (turnstile === true)
46
+ facts.turnstile = true;
47
+ return { binding, facts };
48
+ },
49
+ };
50
+ }
51
+ /** Run one binding command, turning its closed failures into data. */
52
+ export function websiteOutcome(command) {
53
+ try {
54
+ return command();
55
+ }
56
+ catch (error) {
57
+ if (error instanceof WebsiteBindingError)
58
+ return { error: error.code };
59
+ throw error;
60
+ }
61
+ }
62
+ /** The website channel is not configured on this Oyster. */
63
+ class WebsiteConfigurationError extends Error {
64
+ constructor() {
65
+ super("Website channel host secrets are unavailable or invalid");
66
+ this.name = "WebsiteConfigurationError";
67
+ }
68
+ }
69
+ const hostKeySchema = z
70
+ .string()
71
+ .refine((value) => new TextEncoder().encode(value).byteLength >= 32);
72
+ function hostKey(value) {
73
+ const parsed = hostKeySchema.safeParse(value);
74
+ if (!parsed.success)
75
+ throw new WebsiteConfigurationError();
76
+ return parsed.data;
77
+ }
78
+ /** Rate-limit key: the client address hashed under a daily-rotating salt. */
79
+ async function addressHash(env, address) {
80
+ const key = await crypto.subtle.importKey("raw", new TextEncoder().encode(hostKey(env.OYSTER_WEBSITE_ADDRESS_KEY)), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
81
+ const day = new Date().toISOString().slice(0, 10);
82
+ const signature = await crypto.subtle.sign("HMAC", key, new TextEncoder().encode(`${day}:${address ?? "unknown"}`));
83
+ return Array.from(new Uint8Array(signature).slice(0, 16), (byte) => byte.toString(16).padStart(2, "0")).join("");
84
+ }
85
+ const defaultDirectory = (env) => agentDirectoryForScope(env, tenantScope(defaultTenant, env.OYSTER_ORIGIN));
86
+ const embedAssets = async () => import("#embed-scripts");
87
+ const scriptHeaders = {
88
+ "content-type": "text/javascript; charset=utf-8",
89
+ "cache-control": "public, max-age=300",
90
+ "x-content-type-options": "nosniff",
91
+ };
92
+ /**
93
+ * The public website surface, on the same paths as Hub's: the launcher, the
94
+ * visitor document and the visitor API. Every visitor request authenticates
95
+ * once here; Agents receive only a signed, short-lived assertion.
96
+ */
97
+ export function standaloneWebsiteApp() {
98
+ const resolve = (context) => context.env;
99
+ const edge = standaloneVisitorEdge({
100
+ site: (context, siteKey) => defaultDirectory(resolve(context)).websiteSite(siteKey),
101
+ visitors: (context) => {
102
+ const directory = defaultDirectory(resolve(context));
103
+ return {
104
+ mint: (site, siteKey, address) => directory.websiteMint(site?.bindingId ?? "", siteKey, address),
105
+ refresh: (site, secret) => directory.websiteRefresh(site?.bindingId ?? "", secret),
106
+ rotate: (site, siteKey, token, address) => directory.websiteRotate(site?.bindingId ?? "", siteKey, token, address),
107
+ authenticate: (bindingId, token) => directory.websiteAuthenticate(bindingId, token),
108
+ };
109
+ },
110
+ // Visitors reach the chosen Agent itself, with its own tools.
111
+ agent: (context, binding) => resolve(context).AGENTS.getByName(binding.agentId),
112
+ proofKey: (context) => hostKey(resolve(context).OYSTER_WEBSITE_PROOF_KEY),
113
+ addressHash: (context) => addressHash(resolve(context), context.req.header("cf-connecting-ip")),
114
+ turnstile: (context) => {
115
+ const env = resolve(context);
116
+ return {
117
+ configuration: readTurnstileConfiguration(env, env.OYSTER_ORIGIN),
118
+ timeoutMs: 5_000,
119
+ onError: (cause) => {
120
+ console.error("website turnstile verification failed", cause);
121
+ },
122
+ };
123
+ },
124
+ assetPath: (kind) => kind === "widget" ? "/embed/widget.js" : "/styles.css",
125
+ onError: (error, context) => {
126
+ if (error instanceof WebsiteConfigurationError)
127
+ return context.json({ error: "website_unavailable" }, 503);
128
+ console.error(error);
129
+ return context.json({ error: "internal" }, 500);
130
+ },
131
+ });
132
+ return new Hono()
133
+ .get("/embed/v1.js", async () => {
134
+ const { embedLoaderScript } = await embedAssets();
135
+ return new Response(embedLoaderScript, { headers: scriptHeaders });
136
+ })
137
+ .get("/embed/widget.js", async () => {
138
+ const { embedWidgetScript } = await embedAssets();
139
+ return new Response(embedWidgetScript, { headers: scriptHeaders });
140
+ })
141
+ .get("/styles.css", async () => {
142
+ const { embedStyles } = await embedAssets();
143
+ return new Response(embedStyles, {
144
+ headers: {
145
+ "content-type": "text/css; charset=utf-8",
146
+ "cache-control": "public, max-age=300",
147
+ "x-content-type-options": "nosniff",
148
+ },
149
+ });
150
+ })
151
+ .route("/", edge);
152
+ }
153
+ /** The owner's website controls over the directory and each website's Agent. */
154
+ export function standaloneWebsiteControl(env, directoryOf) {
155
+ // Only a binding the directory knows names an Agent whose conversations are read.
156
+ const agentOf = async (principal, bindingId) => {
157
+ const listed = await directoryOf().websiteList(principal);
158
+ const binding = "error" in listed
159
+ ? undefined
160
+ : listed.find((item) => item.bindingId === bindingId);
161
+ return binding === undefined ? null : env.AGENTS.getByName(binding.agentId);
162
+ };
163
+ return {
164
+ read: async (principal) => {
165
+ const listed = await directoryOf().websiteList(principal);
166
+ return {
167
+ embedOrigin: env.OYSTER_ORIGIN,
168
+ agents: (await directoryOf().list()).map(({ agentId, name }) => ({
169
+ agentId,
170
+ name,
171
+ })),
172
+ websites: "error" in listed ? [] : listed,
173
+ };
174
+ },
175
+ create: (principal, input, requestId) => directoryOf().websiteCreate(principal, input, requestId),
176
+ update: (principal, bindingId, input) => directoryOf().websiteUpdate(principal, bindingId, input),
177
+ conversations: async (principal, bindingId) => {
178
+ const agent = await agentOf(principal, bindingId);
179
+ return agent === null
180
+ ? []
181
+ : (await agent.websiteConversations(bindingId)).map(({ sessionId, label, lastEventAt }) => ({
182
+ sessionId,
183
+ label,
184
+ lastEventAt,
185
+ }));
186
+ },
187
+ transcript: async (principal, bindingId, sessionId) => {
188
+ const agent = await agentOf(principal, bindingId);
189
+ return agent === null
190
+ ? null
191
+ : agent.websiteTranscript(bindingId, sessionId);
192
+ },
193
+ };
194
+ }
195
+ const refusalStatus = {
196
+ not_granted: 403,
197
+ not_found: 404,
198
+ version_conflict: 409,
199
+ request_conflict: 409,
200
+ invalid_input: 400,
201
+ };
202
+ function refused(value) {
203
+ return "error" in value;
204
+ }
205
+ /**
206
+ * The owner's website controls. Each route is owner-direct: an App cannot
207
+ * create a public surface, or read what its visitors said, on the owner's behalf.
208
+ */
209
+ export function standaloneWebsiteRoutes(control) {
210
+ const table = routes();
211
+ // A body that is not JSON is a malformed request, not a thrown failure.
212
+ const parseBody = async (context) => {
213
+ const decoded = Schema.decodeUnknownOption(Schema.fromJsonString(Schema.Json))(await context.req.text());
214
+ return Option.isSome(decoded)
215
+ ? { ok: true, value: decoded.value }
216
+ : { ok: false };
217
+ };
218
+ table.get("/api/websites", owner("direct"), async (context, { principal }) => {
219
+ context.header("Cache-Control", "no-store");
220
+ return context.json(await control.read(principal));
221
+ });
222
+ table.post("/api/websites", owner("direct"), async (context, { principal }) => {
223
+ context.header("Cache-Control", "no-store");
224
+ const body = await parseBody(context);
225
+ if (!body.ok)
226
+ return context.json({ error: "invalid_input" }, 400);
227
+ const parsed = createWebsiteInputSchema.safeParse(body.value);
228
+ if (!parsed.success)
229
+ return context.json({ error: "invalid_input" }, 400);
230
+ const result = await control.create(principal, parsed.data, context.req.header("x-request-id") ?? "");
231
+ return refused(result)
232
+ ? context.json(result, refusalStatus[result.error])
233
+ : context.json({ binding: result }, 201);
234
+ });
235
+ table.put("/api/websites/:bindingId", owner("direct"), async (context, { principal }) => {
236
+ context.header("Cache-Control", "no-store");
237
+ const body = await parseBody(context);
238
+ if (!body.ok)
239
+ return context.json({ error: "invalid_input" }, 400);
240
+ const parsed = updateWebsiteInputSchema.safeParse(body.value);
241
+ if (!parsed.success)
242
+ return context.json({ error: "invalid_input" }, 400);
243
+ const result = await control.update(principal, context.req.param("bindingId"), parsed.data);
244
+ return refused(result)
245
+ ? context.json(result, refusalStatus[result.error])
246
+ : context.json({ binding: result });
247
+ });
248
+ table.get("/api/websites/:bindingId/conversations", owner("direct"), async (context, { principal }) => {
249
+ context.header("Cache-Control", "no-store");
250
+ return context.json({
251
+ conversations: await control.conversations(principal, context.req.param("bindingId")),
252
+ });
253
+ });
254
+ table.get("/api/websites/:bindingId/conversations/:sessionId", owner("direct"), async (context, { principal }) => {
255
+ context.header("Cache-Control", "no-store");
256
+ const transcript = await control.transcript(principal, context.req.param("bindingId"), context.req.param("sessionId"));
257
+ return transcript === null
258
+ ? context.json({ error: "not_found" }, 404)
259
+ : context.json(transcript);
260
+ });
261
+ return table;
262
+ }
@@ -1,6 +1,7 @@
1
1
  /**
2
2
  * The standalone Worker's top-level table, before any tenant is selected:
3
- * device enrollment and links, attached-machine dials, signed Workflow webhook delivery, then the
3
+ * device enrollment and links, the public website visitor surface, attached-machine
4
+ * dials, signed Workflow webhook delivery, then the
4
5
  * selected tenant's own declared host table for every other path. The Worker
5
6
  * and the authorization law both compose it here.
6
7
  */
@@ -10,6 +11,8 @@ import { type Routes } from "../authorization.js";
10
11
  export type StandaloneWorkerRoutePorts = Readonly<{
11
12
  /** The machine-link doors' own table, served for this request. */
12
13
  machineLink: (request: Request) => Promise<Response>;
14
+ /** The public website channel: launcher, visitor document and visitor API. */
15
+ website: (request: Request) => Promise<Response>;
13
16
  /** A machine's signed dial to its attached Computer, verified by that Computer. */
14
17
  localBackendDial: (request: Request) => Promise<Response>;
15
18
  /** Signed Workflow webhook delivery, verified by the library's run owner. */
@@ -4,6 +4,9 @@ export function standaloneWorkerRoutes(ports) {
4
4
  return routes()
5
5
  .all("/local/mesh/join", door("machine enrollment; the join route verifies its key"), (context) => ports.machineLink(context.req.raw))
6
6
  .all("/api/teams/:teamId/local/mesh/:deviceId/connect", door("a machine link; the device's link verifies Seam"), (context) => ports.machineLink(context.req.raw))
7
+ .all("/embed/*", door("a website visitor; the edge checks the site key and origin"), (context) => ports.website(context.req.raw))
8
+ .all("/styles.css", door("the website chat's public stylesheet"), (context) => ports.website(context.req.raw))
9
+ .all("/api/embed/*", door("a website visitor; the edge checks the site key, origin and bearer"), (context) => ports.website(context.req.raw))
7
10
  .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))
8
11
  .include(ports.workflowWebhooks)
9
12
  .all("*", door("the selected tenant's own declared host table"), (context) => ports.tenant(context.req.raw));
@@ -16,12 +16,13 @@ import { type StandaloneTenancyEnv } from "./tenancy.js";
16
16
  export { StandaloneTenants } from "./tenancy.js";
17
17
  import { type StandaloneMachineLinkBindings } from "./machine-link.js";
18
18
  export { MachineLinkDO } from "./machine-link.js";
19
+ import { type StandaloneWebsiteEnv } from "./website-channels.js";
19
20
  import { type OysterComputerEgressProps } from "./computer-egress.js";
20
21
  import type { AppSourceBindingEnv } from "./app-source.js";
21
22
  export { StandaloneGraphWorkflow } from "./workflows.js";
22
23
  export { MediaOperationDO } from "@fungi.computer/darkroom/cloudflare";
23
24
  /** Every binding the standalone Bonsai root receives. */
24
- export type StandaloneEnv = OysterGitWorkerEnv & StandaloneTenancyEnv & StandaloneComputerEnv & StandaloneAgentsEnv & StandaloneMachineLinkBindings & OysterMediaEnv & StandaloneWorkflowEnv & AppSourceBindingEnv & {
25
+ export type StandaloneEnv = OysterGitWorkerEnv & StandaloneTenancyEnv & StandaloneComputerEnv & StandaloneAgentsEnv & StandaloneWebsiteEnv & StandaloneMachineLinkBindings & OysterMediaEnv & StandaloneWorkflowEnv & AppSourceBindingEnv & {
25
26
  OYSTER_HOME_INSTALLATION: string;
26
27
  /** `disabled` closes the Computer's public download lane. */
27
28
  COMPUTER_PUBLIC_EGRESS?: string;