@fungi.computer/tourtois 0.6.0 → 0.8.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.
@@ -4,8 +4,9 @@ import { SectionHeading } from "@fungi.computer/caps/blocks/section-heading";
4
4
  import { AppDesktopSettings, } from "./AppDesktopSettings.js";
5
5
  import { addressKey, } from "@fungi.computer/nacre/app-directory";
6
6
  import { useCallback, useEffect, useMemo, useRef, useState } from "react";
7
- import { AgentMcpServers } from "./AgentMcpServers.js";
7
+ import { Connections } from "./Connections.js";
8
8
  import { Keys } from "./Keys.js";
9
+ import { ModelKeys } from "./ModelKeys.js";
9
10
  import { AppIcon } from "./app-icon.js";
10
11
  import { AvatarSettings } from "./member-avatar.js";
11
12
  import { SettingsNavigation } from "./SettingsNavigation.js";
@@ -24,7 +25,7 @@ export function SystemSettings({ location: requestedLocation, sections: ceiling,
24
25
  const location = requestedLocation !== null && sections.includes(requestedLocation.category)
25
26
  ? requestedLocation
26
27
  : null;
27
- const { agentMcpServers, keys, appPermissions: AppPermissions, appAdvanced: AppAdvanced, } = ports;
28
+ const { connections, keys, appPermissions: AppPermissions, appAdvanced: AppAdvanced, } = ports;
28
29
  const avatar = location?.category === "avatar";
29
30
  const connectors = location?.category === "connectors";
30
31
  const computersSection = location?.category === "computers";
@@ -132,9 +133,7 @@ export function SystemSettings({ location: requestedLocation, sections: ceiling,
132
133
  appCount,
133
134
  defaultAppCount: ports.summary?.defaultAppCount ?? null,
134
135
  computerCount: ports.summary?.computerCount ?? null,
135
- }, onNavigate: onNavigate })) : null, avatar && ports.avatar !== undefined ? (_jsx("div", { className: "tourtois-settings-content", children: _jsx(AvatarSettings, { save: ports.avatar.save }) })) : null, connectors && agentMcpServers !== undefined ? (_jsx(AgentMcpServers, { port: agentMcpServers })) : null, connectors &&
136
- agentMcpServers === undefined &&
137
- ports.connectors !== undefined ? (_jsx(ports.connectors, { target: location.target, onNavigate: onNavigate })) : null, location?.category === "selling" && ports.selling !== undefined ? (_jsx(ports.selling, { appId: location.appId, onNavigate: onNavigate })) : null, computersSection && ports.computers !== undefined ? (_jsx("div", { className: "tourtois-settings-content", children: _jsx(ports.computers, {}) })) : null, keysSection && keys !== undefined ? (_jsx(Keys, { port: keys, apps: keyableApps })) : null, location?.category === "channels" &&
136
+ }, onNavigate: onNavigate })) : null, avatar && ports.avatar !== undefined ? (_jsx("div", { className: "tourtois-settings-content", children: _jsx(AvatarSettings, { save: ports.avatar.save }) })) : null, connectors && connections !== undefined ? (location.target.kind === "list" ? (_jsx(Connections, { port: connections, target: location.target, onNavigate: onNavigate })) : connections.hostSections ? (_jsx(connections.hostSections, { target: location.target, onNavigate: onNavigate })) : null) : null, location?.category === "selling" && ports.selling !== undefined ? (_jsx(ports.selling, { appId: location.appId, onNavigate: onNavigate })) : null, computersSection && ports.computers !== undefined ? (_jsx("div", { className: "tourtois-settings-content", children: _jsx(ports.computers, {}) })) : null, keysSection && keys !== undefined ? (_jsx(Keys, { port: keys, apps: keyableApps })) : null, keysSection && ports.modelKeys !== undefined ? (_jsx(ModelKeys, { port: ports.modelKeys })) : null, location?.category === "channels" &&
138
137
  ports.channels !== undefined ? (_jsx(ports.channels, {})) : null, defaults && ports.defaults !== undefined ? (_jsx("div", { className: "tourtois-settings-content", children: _jsx(ports.defaults, { onAccepted: onAccepted }) })) : null, appSection && appKey === null ? (_jsxs("section", { className: "tourtois-settings-content", "aria-label": "Choose an App", children: [_jsx(SectionHeading, { className: "tourtois-settings-app-heading", children: desktopOnly ? "App desktop" : "App permissions" }), _jsx(DataList, { density: "compact", "aria-label": "Apps to review", children: apps.map((app) => (_jsx(DataRow, { className: "p-0", children: _jsx(ActionRow, { label: app.displayName ?? app.appId, icon: _jsx(AppIcon, { roles: app.roles, icon: app.icon }), onClick: () => {
139
138
  onNavigate({
140
139
  category: "apps",
@@ -0,0 +1,131 @@
1
+ import { type WebsiteConversation, type WebsiteSite, type WebsiteTranscript } from "@fungi.computer/nacre/website-channels";
2
+ import { type ReactNode } from "react";
3
+ export type { WebsiteConversation, WebsiteSite, WebsiteTranscript };
4
+ /** An Agent a website can be bound to. */
5
+ export type WebsiteAgent = Readonly<{
6
+ agentId: string;
7
+ name: string;
8
+ }>;
9
+ /** Everything one host knows about its websites. */
10
+ export type WebsiteDirectory = Readonly<{
11
+ /** The host's own address, where the launcher and visitor API are served. */
12
+ embedOrigin: string;
13
+ agents: readonly WebsiteAgent[];
14
+ sites: readonly WebsiteSite[];
15
+ }>;
16
+ /** What an owner may change about one website. */
17
+ export type WebsiteChange = Readonly<{
18
+ lifecycle?: "active" | "suspended";
19
+ turnstile?: boolean;
20
+ rotateSiteKey?: true;
21
+ }>;
22
+ /** A new website: the Agent visitors talk to, where it appears and its brief. */
23
+ export type NewWebsite = Readonly<{
24
+ agentId: string;
25
+ origins: readonly string[];
26
+ persona: string;
27
+ }>;
28
+ /** Host-supplied owner controls over its websites, not a second inventory. */
29
+ export type WebsiteChannelsPort = Readonly<{
30
+ /** Names this host's data; two hosts never share a cache entry. */
31
+ scope: string;
32
+ read(): Promise<WebsiteDirectory>;
33
+ create(input: NewWebsite, requestId: string): Promise<WebsiteSite>;
34
+ update(bindingId: string, expectedVersion: number, change: WebsiteChange): Promise<WebsiteSite>;
35
+ conversations(site: WebsiteSite): Promise<readonly WebsiteConversation[]>;
36
+ transcript(site: WebsiteSite, sessionId: string): Promise<WebsiteTranscript>;
37
+ }>;
38
+ /** What the owner typed in the address field, read the way the host will. */
39
+ export type WebsiteAddresses = {
40
+ kind: "parsed";
41
+ origins: string[];
42
+ } | {
43
+ kind: "invalid";
44
+ message: string;
45
+ };
46
+ /**
47
+ * Read the owner's typed addresses, then run the web origin schema on each.
48
+ * Settings only forgives typing: a bare host gains `https://` and a lone
49
+ * trailing `/` is dropped, so a pasted home-page link works. Anything the
50
+ * schema refuses is named on the field instead of sent.
51
+ */
52
+ export declare function parseWebsiteAddresses(text: string): WebsiteAddresses;
53
+ /** The loader tag an owner pastes, as coloured runs; joined, they are the tag. */
54
+ export declare function websiteEmbedSnippet(embedOrigin: string, siteKey: string): readonly [{
55
+ readonly kind: "tag";
56
+ readonly text: "<script";
57
+ }, {
58
+ readonly kind: "text";
59
+ readonly text: "\n ";
60
+ }, {
61
+ readonly kind: "attribute";
62
+ readonly text: "src";
63
+ }, {
64
+ readonly kind: "tag";
65
+ readonly text: "=";
66
+ }, {
67
+ readonly kind: "string";
68
+ readonly text: `"${string}/embed/v1.js"`;
69
+ }, {
70
+ readonly kind: "text";
71
+ readonly text: "\n ";
72
+ }, {
73
+ readonly kind: "attribute";
74
+ readonly text: "data-site";
75
+ }, {
76
+ readonly kind: "tag";
77
+ readonly text: "=";
78
+ }, {
79
+ readonly kind: "string";
80
+ readonly text: `"${string}"`;
81
+ }, {
82
+ readonly kind: "text";
83
+ readonly text: "\n ";
84
+ }, {
85
+ readonly kind: "attribute";
86
+ readonly text: "data-theme";
87
+ }, {
88
+ readonly kind: "tag";
89
+ readonly text: "=";
90
+ }, {
91
+ readonly kind: "string";
92
+ readonly text: "\"auto\"";
93
+ }, {
94
+ readonly kind: "text";
95
+ readonly text: "\n ";
96
+ }, {
97
+ readonly kind: "attribute";
98
+ readonly text: "async";
99
+ }, {
100
+ readonly kind: "text";
101
+ readonly text: "\n";
102
+ }, {
103
+ readonly kind: "tag";
104
+ readonly text: "></script>";
105
+ }];
106
+ /** Bind owner website controls to this trusted shell's own host. */
107
+ export declare function createOysterWebsiteChannelsPort(origin: URL): WebsiteChannelsPort;
108
+ /** Host copy that differs by what a visitor can reach. */
109
+ export type WebsiteChannelsCopy = Readonly<{
110
+ /** Opening paragraphs under the heading. */
111
+ intro: ReactNode;
112
+ /** What a visitor sees and what limits apply, for one Agent. */
113
+ visitors: (agentName: string) => ReactNode;
114
+ /** What a visitor's chat can trigger, for one Agent. */
115
+ reach: (agentName: string) => ReactNode;
116
+ }>;
117
+ /**
118
+ * Owner Settings for website chat: bind an Agent to a website, copy the code
119
+ * to paste there, pause it, require a security check, change its site key and
120
+ * read what visitors said. Hosts supply the port and the copy that differs.
121
+ */
122
+ export declare function WebsiteChannels({ port, copy, assistant, siteNotice, children, }: {
123
+ port: WebsiteChannelsPort;
124
+ copy: WebsiteChannelsCopy;
125
+ /** A host's own way to make the first Agent; absent means create one in Agents. */
126
+ assistant?: (done: () => void, cancel: () => void) => ReactNode;
127
+ /** A host's note under one website, such as an Agent delivery state. */
128
+ siteNotice?: (site: WebsiteSite) => ReactNode;
129
+ /** Further sections the host keeps under the websites. */
130
+ children?: ReactNode;
131
+ }): import("react/jsx-runtime").JSX.Element;
@@ -0,0 +1,372 @@
1
+ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
2
+ import { AppError } from "@fungi.computer/agar";
3
+ import { SectionHeading } from "@fungi.computer/caps/blocks/section-heading";
4
+ import { Button } from "@fungi.computer/caps/components/button";
5
+ import { CopyField } from "@fungi.computer/caps/components/copy-field";
6
+ import { DataList, DataListHeading, DataRow, FactRow, } from "@fungi.computer/caps/components/data-list";
7
+ import { FormFooter } from "@fungi.computer/caps/components/field";
8
+ import { CheckKey } from "@fungi.computer/caps/components/icon-checkbox";
9
+ import { InlineCode } from "@fungi.computer/caps/components/inline-code";
10
+ import { KeycapButton } from "@fungi.computer/caps/components/keycap";
11
+ import { Prose } from "@fungi.computer/caps/components/prose";
12
+ import { Status } from "@fungi.computer/caps/components/status";
13
+ import { SchemaForm, field, sections, useSchemaForm, } from "@fungi.computer/caps/form";
14
+ import { webOriginProblem, webOriginSchema, websiteConversationSchema, websiteSiteSchema, websiteTranscriptSchema, } from "@fungi.computer/nacre/website-channels";
15
+ import { Sigil } from "@fungi.computer/sigils";
16
+ import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
17
+ import { useId, useMemo, useState } from "react";
18
+ import * as z from "zod";
19
+ import { tourtoisQueryKeys } from "./queries.js";
20
+ import { requestIds } from "./team-directory.js";
21
+ const exampleAddress = "https://example.com";
22
+ /**
23
+ * Read the owner's typed addresses, then run the web origin schema on each.
24
+ * Settings only forgives typing: a bare host gains `https://` and a lone
25
+ * trailing `/` is dropped, so a pasted home-page link works. Anything the
26
+ * schema refuses is named on the field instead of sent.
27
+ */
28
+ export function parseWebsiteAddresses(text) {
29
+ const entries = text.split(/[\s,]+/u).filter(Boolean);
30
+ if (entries.length === 0)
31
+ return {
32
+ kind: "invalid",
33
+ message: `Enter your website's address, like ${exampleAddress}.`,
34
+ };
35
+ if (entries.length > 16)
36
+ return { kind: "invalid", message: "Add up to 16 addresses." };
37
+ const origins = [];
38
+ for (const entry of entries) {
39
+ const typed = entry.includes("://") ? entry : `https://${entry}`;
40
+ const result = webOriginSchema.safeParse(typed.replace(/(?<=[^/])\/$/u, ""));
41
+ if (!result.success)
42
+ return {
43
+ kind: "invalid",
44
+ message: addressProblem(entry, webOriginProblem(result.error)),
45
+ };
46
+ if (!origins.includes(result.data))
47
+ origins.push(result.data);
48
+ }
49
+ return { kind: "parsed", origins };
50
+ }
51
+ function addressProblem(entry, problem) {
52
+ switch (problem) {
53
+ case "insecure":
54
+ return "Use https:// — the chat only runs on secure websites.";
55
+ case "credentials":
56
+ return `Leave the sign-in out of “${entry}”.`;
57
+ case "path":
58
+ return `Use just the website, without a page or query, like ${exampleAddress}.`;
59
+ case "tooLong":
60
+ return "That address is too long.";
61
+ case "notUrl":
62
+ case "notAllowed":
63
+ return `“${entry}” is not a web address. Try ${exampleAddress}.`;
64
+ }
65
+ }
66
+ /** The loader tag an owner pastes, as coloured runs; joined, they are the tag. */
67
+ export function websiteEmbedSnippet(embedOrigin, siteKey) {
68
+ return [
69
+ { kind: "tag", text: "<script" },
70
+ { kind: "text", text: "\n " },
71
+ { kind: "attribute", text: "src" },
72
+ { kind: "tag", text: "=" },
73
+ { kind: "string", text: `"${embedOrigin}/embed/v1.js"` },
74
+ { kind: "text", text: "\n " },
75
+ { kind: "attribute", text: "data-site" },
76
+ { kind: "tag", text: "=" },
77
+ { kind: "string", text: `"${siteKey}"` },
78
+ { kind: "text", text: "\n " },
79
+ { kind: "attribute", text: "data-theme" },
80
+ { kind: "tag", text: "=" },
81
+ { kind: "string", text: '"auto"' },
82
+ { kind: "text", text: "\n " },
83
+ { kind: "attribute", text: "async" },
84
+ { kind: "text", text: "\n" },
85
+ { kind: "tag", text: "></script>" },
86
+ ];
87
+ }
88
+ const directoryWire = z.object({
89
+ embedOrigin: z.url(),
90
+ agents: z.array(z.object({ agentId: z.string(), name: z.string() })),
91
+ websites: z.array(websiteSiteSchema),
92
+ });
93
+ const siteChange = z.object({ binding: websiteSiteSchema });
94
+ const conversationList = z.object({
95
+ conversations: z.array(websiteConversationSchema),
96
+ });
97
+ async function request(url, init) {
98
+ const response = await fetch(url, {
99
+ ...init,
100
+ headers: {
101
+ Accept: "application/json",
102
+ "Content-Type": "application/json",
103
+ ...Object.fromEntries(new Headers(init?.headers)),
104
+ },
105
+ credentials: "same-origin",
106
+ cache: "no-store",
107
+ redirect: "error",
108
+ });
109
+ if (!response.ok)
110
+ throw new AppError(`Website request refused (${String(response.status)}).`, {
111
+ code: response.status === 401 || response.status === 403
112
+ ? "CAPABILITY_DENIED"
113
+ : "HOST_FAILURE",
114
+ retryable: response.status >= 500,
115
+ });
116
+ return response;
117
+ }
118
+ /** Bind owner website controls to this trusted shell's own host. */
119
+ export function createOysterWebsiteChannelsPort(origin) {
120
+ const send = (path, init) => request(new URL(path, origin), init);
121
+ const site = (bindingId) => `/api/websites/${encodeURIComponent(bindingId)}`;
122
+ return {
123
+ scope: origin.origin,
124
+ read: async () => {
125
+ const wire = directoryWire.parse(await (await send("/api/websites")).json());
126
+ return {
127
+ embedOrigin: wire.embedOrigin,
128
+ agents: wire.agents,
129
+ sites: wire.websites,
130
+ };
131
+ },
132
+ create: async (input, requestId) => {
133
+ const response = await send("/api/websites", {
134
+ method: "POST",
135
+ headers: { "x-request-id": requestId },
136
+ body: JSON.stringify({
137
+ agentId: input.agentId,
138
+ selector: { provider: "web", origins: input.origins },
139
+ persona: input.persona,
140
+ }),
141
+ });
142
+ return siteChange.parse(await response.json()).binding;
143
+ },
144
+ update: async (bindingId, expectedVersion, change) => {
145
+ const response = await send(site(bindingId), {
146
+ method: "PUT",
147
+ body: JSON.stringify({ expectedVersion, ...change }),
148
+ });
149
+ return siteChange.parse(await response.json()).binding;
150
+ },
151
+ conversations: async ({ bindingId }) => conversationList.parse(await (await send(`${site(bindingId)}/conversations`)).json()).conversations,
152
+ transcript: async ({ bindingId }, sessionId) => websiteTranscriptSchema.parse(await (await send(`${site(bindingId)}/conversations/${encodeURIComponent(sessionId)}`)).json()),
153
+ };
154
+ }
155
+ const siteHost = (origin) => origin.replace(/^https?:\/\//u, "");
156
+ /**
157
+ * Owner Settings for website chat: bind an Agent to a website, copy the code
158
+ * to paste there, pause it, require a security check, change its site key and
159
+ * read what visitors said. Hosts supply the port and the copy that differs.
160
+ */
161
+ export function WebsiteChannels({ port, copy, assistant, siteNotice, children, }) {
162
+ const directory = useQuery({
163
+ queryKey: tourtoisQueryKeys.websiteChannels(port.scope),
164
+ retry: false,
165
+ queryFn: () => port.read(),
166
+ });
167
+ const [adding, setAdding] = useState(false);
168
+ const [creatingAssistant, setCreatingAssistant] = useState(false);
169
+ const [guided, setGuided] = useState(false);
170
+ const [createdSite, setCreatedSite] = useState(null);
171
+ const [openSite, setOpenSite] = useState(null);
172
+ const agents = directory.data?.agents ?? [];
173
+ return (_jsxs("section", { className: "tourtois-settings-content tourtois-websites grid gap-md", "aria-label": "Channels", children: [_jsxs("header", { className: "grid gap-xs", children: [_jsx(SectionHeading, { children: "Channels" }), _jsx(DataListHeading, { level: 3, children: "Website" }), copy.intro] }), directory.isPending ? _jsx("p", { role: "status", children: "Loading Channels\u2026" }) : null, directory.isError ? (_jsxs("div", { role: "alert", children: [_jsx("p", { children: "Channels could not be loaded. Your saved settings have not changed." }), _jsx(Button, { onClick: () => {
174
+ void directory.refetch();
175
+ }, children: "Retry Channels" })] })) : null, directory.data ? (_jsxs(_Fragment, { children: [directory.data.sites.length > 0 ? (_jsx(DataList, { "aria-label": "Saved websites", children: directory.data.sites.map((site) => (_jsx(WebsiteRow, { port: port, copy: copy, site: site, notice: siteNotice?.(site), embedOrigin: directory.data.embedOrigin, open: openSite === site.bindingId, justCreated: createdSite === site.bindingId, onOpenChange: (open) => {
176
+ setOpenSite(open ? site.bindingId : null);
177
+ }, agentName: agents.find((agent) => agent.agentId === site.agentId)
178
+ ?.name ?? "Unavailable Agent" }, site.bindingId))) })) : adding ? null : (_jsx("p", { className: "text-sm", children: "No websites yet." })), creatingAssistant && assistant !== undefined ? (assistant(() => {
179
+ // The new Agent must be in the list the form chooses from.
180
+ void directory.refetch().then(() => {
181
+ setCreatingAssistant(false);
182
+ setAdding(true);
183
+ });
184
+ }, () => {
185
+ setCreatingAssistant(false);
186
+ setGuided(false);
187
+ })) : adding ? (_jsx(AddWebsite, { port: port, agents: agents, guided: guided, onDone: (bindingId) => {
188
+ setAdding(false);
189
+ setGuided(false);
190
+ if (bindingId) {
191
+ setOpenSite(bindingId);
192
+ setCreatedSite(bindingId);
193
+ }
194
+ } })) : agents.length === 0 && assistant === undefined ? (_jsx("p", { className: "text-sm", children: "Create an Agent first; a website needs one to talk to visitors." })) : (_jsx("div", { className: "flex justify-end", children: _jsx(Button, { onClick: () => {
195
+ if (agents.length === 0) {
196
+ setCreatingAssistant(true);
197
+ setGuided(true);
198
+ }
199
+ else
200
+ setAdding(true);
201
+ }, children: agents.length === 0
202
+ ? "Set up a website assistant"
203
+ : "Add website" }) }))] })) : null, children] }));
204
+ }
205
+ function AddWebsite({ port, agents, guided, onDone, }) {
206
+ const cache = useQueryClient();
207
+ const schema = useMemo(() => z
208
+ .object({
209
+ agentId: z.string().meta(field({
210
+ label: "Agent",
211
+ help: "Visitors chat with this Agent.",
212
+ kind: "select",
213
+ section: "website",
214
+ options: Object.fromEntries(agents.map((agent) => [agent.agentId, agent.name])),
215
+ })),
216
+ addresses: z
217
+ .string()
218
+ .transform((text, context) => {
219
+ const parsed = parseWebsiteAddresses(text);
220
+ if (parsed.kind === "parsed")
221
+ return parsed.origins;
222
+ context.addIssue({ code: "custom", message: parsed.message });
223
+ return z.NEVER;
224
+ })
225
+ .meta(field({
226
+ label: "Website address",
227
+ help: "Starts with https://. Separate more than one with commas.",
228
+ kind: "url",
229
+ autoComplete: "url",
230
+ placeholder: "https://example.com",
231
+ required: true,
232
+ section: "website",
233
+ })),
234
+ persona: z
235
+ .string()
236
+ .max(4_000)
237
+ .meta(field({
238
+ label: "What should the Agent do here?",
239
+ help: "Its brief for this website. Visitors don't see it.",
240
+ kind: "textarea",
241
+ optional: true,
242
+ rows: 3,
243
+ maxLength: 4_000,
244
+ placeholder: "Answer questions about our services.",
245
+ section: "website",
246
+ })),
247
+ })
248
+ .meta(sections({
249
+ website: {
250
+ title: guided
251
+ ? "2. Add your website and instructions"
252
+ : "Add a website",
253
+ description: "Use the address visitors open, including https and www. Add facts such as shop hours and delivery rules; the assistant does not read your pages automatically. You get the code to paste next.",
254
+ },
255
+ })), [agents, guided]);
256
+ const create = useMutation({
257
+ mutationFn: (input) => port.create({
258
+ agentId: input.agentId,
259
+ origins: input.origins,
260
+ persona: input.persona,
261
+ }, input.requestId),
262
+ onSuccess: async (site) => {
263
+ await cache.invalidateQueries({
264
+ queryKey: tourtoisQueryKeys.websiteChannels(port.scope),
265
+ });
266
+ onDone(site.bindingId);
267
+ },
268
+ });
269
+ const model = useSchemaForm({
270
+ schema,
271
+ defaultValues: {
272
+ agentId: agents[0]?.agentId ?? "",
273
+ addresses: "",
274
+ persona: "",
275
+ },
276
+ onSubmit: async (value) => {
277
+ try {
278
+ await create.mutateAsync({
279
+ requestId: requestIds.request.generate(),
280
+ agentId: value.agentId,
281
+ origins: value.addresses,
282
+ persona: value.persona,
283
+ });
284
+ return { kind: "saved" };
285
+ }
286
+ catch (cause) {
287
+ return {
288
+ kind: "refused",
289
+ error: cause instanceof Error
290
+ ? cause.message
291
+ : "The website could not be added. Try the saved request again.",
292
+ };
293
+ }
294
+ },
295
+ });
296
+ return (_jsx(SchemaForm, { model: model, layout: "columns", "aria-label": "Add a website", disabled: create.isPending, footer: _jsxs(FormFooter, { error: create.error?.message ?? model.error, children: [_jsx(Button, { type: "button", variant: "ghost", onClick: () => {
297
+ onDone(null);
298
+ }, children: "Cancel" }), create.isError ? (_jsx(Button, { type: "button", variant: "outline", onClick: () => {
299
+ create.mutate(create.variables);
300
+ }, children: "Retry saved request" })) : null, _jsx(Button, { type: "submit", children: create.isPending ? "Adding website…" : "Add website" })] }) }));
301
+ }
302
+ function WebsiteRow({ port, copy, site, notice, embedOrigin, agentName, open, justCreated, onOpenChange, }) {
303
+ const cache = useQueryClient();
304
+ const guideId = useId();
305
+ const key = tourtoisQueryKeys.websiteChannels(port.scope);
306
+ const [confirmingKey, setConfirmingKey] = useState(false);
307
+ const patch = useMutation({
308
+ // Edits queue per website; each sends the last version the host acknowledged.
309
+ scope: { id: JSON.stringify([port.scope, site.bindingId]) },
310
+ mutationFn: (change) => {
311
+ const current = cache
312
+ .getQueryData(key)
313
+ ?.sites.find((item) => item.bindingId === site.bindingId);
314
+ if (!current)
315
+ throw new Error("Website unavailable. Reload before changing it.");
316
+ return port.update(site.bindingId, current.authorityVersion, change);
317
+ },
318
+ onSettled: () => cache.invalidateQueries({ queryKey: key }),
319
+ });
320
+ const { origins, siteKey, turnstile } = site.selector;
321
+ const snippet = websiteEmbedSnippet(embedOrigin, siteKey);
322
+ const active = site.lifecycle === "active";
323
+ const hosts = origins.map(siteHost).join(", ");
324
+ return (_jsx(DataRow, { children: _jsxs("div", { className: "tourtois-connector-row grid gap-md", children: [_jsxs("div", { className: "tourtois-website-summary", children: [_jsx(Sigil, { name: "agent", size: 28 }), _jsxs("div", { className: "min-w-0 flex-1", children: [_jsx(DataListHeading, { level: 3, children: agentName }), _jsx("p", { className: "tourtois-website-hosts text-sm", children: hosts })] }), _jsx(Status, { appearance: "chip", label: active ? "Active" : "Paused", size: "compact", tone: active ? "success" : "neutral" }), _jsx(Button, { variant: "outline", size: "sm", "aria-controls": guideId, "aria-expanded": open, "aria-label": `${open ? "Close" : "Set up"} ${agentName} on ${hosts}`, onClick: () => {
325
+ onOpenChange(!open);
326
+ }, children: open ? "Close" : "Set up" })] }), open ? (_jsxs("div", { className: "tourtois-connector-row-details tourtois-website-guide", id: guideId, children: [_jsxs(Prose, { className: "tourtois-website-doc", children: [_jsx("h4", { children: justCreated
327
+ ? "3. Install and test chat"
328
+ : "Add it to your website" }), _jsxs("ol", { children: [_jsxs("li", { children: [_jsx("p", { children: _jsx("strong", { children: "Copy this code." }) }), _jsx(CopyField, { className: "not-prose", layout: "block", title: "HTML", label: "Copy snippet", tokens: snippet, "aria-label": `Embed snippet for ${agentName}` })] }), _jsx("li", { children: _jsxs("p", { children: [_jsxs("strong", { children: ["Paste it into your pages, just before", " ", _jsx(InlineCode, { children: "</body>" }), "."] }), " ", "If your site has a shared layout, template or footer, paste it there once. Site builders call this \u201Ccustom code\u201D or \u201Cfooter code\u201D."] }) }), _jsx("li", { children: _jsxs("p", { children: [_jsx("strong", { children: "Publish, then open your site." }), " A chat button appears in the bottom-right corner. Open it and send a message; ", agentName, " replies."] }) })] }), _jsxs("details", { children: [_jsx("summary", { children: "WordPress installation steps" }), _jsxs("ol", { children: [_jsx("li", { children: "In WordPress, open Pages and edit the page where you want chat. Add a Custom HTML block: type /html and press Enter." }), _jsx("li", { children: "Open Edit HTML and choose the HTML tab. Paste the whole copied code, including the script tags. Choose Update." }), _jsx("li", { children: "Save or publish the page, then open its public address in a private browser window and send a test message." })] }), _jsx("p", { children: "A Custom HTML block adds chat to only this page. For every page, use your host\u2019s shared footer-code setting or the WPCode plugin\u2019s Header & Footer screen." }), _jsx("p", { children: "If WordPress removes the script when you save, ask your site administrator to install it. Some accounts cannot save scripts. You do not need a plugin when your account can save the Custom HTML block." }), _jsx("p", { children: _jsx("a", { href: "https://docs.fungi.computer/guides/wordpress-agent/", children: "Full WordPress guide" }) })] }), _jsxs("p", { className: "tourtois-website-note", children: ["The chat only appears on", " ", origins.map((origin, index) => (_jsxs("span", { children: [index > 0 ? ", " : null, _jsx(InlineCode, { children: origin })] }, origin))), ". To try it somewhere else first, add that address as another website."] }), _jsx("h4", { children: "What visitors see" }), _jsx("p", { children: copy.visitors(agentName) }), _jsx("h4", { children: "What visitors can trigger" }), _jsx("p", { children: copy.reach(agentName) })] }), _jsxs(DataList, { density: "compact", "aria-label": `Website status for ${agentName}`, children: [_jsx(FactRow, { icon: _jsx(Sigil, { name: "agent" }), label: "Agent", children: agentName }), _jsx(FactRow, { icon: _jsx(Sigil, { name: "internet" }), label: "Site key", children: _jsx(InlineCode, { children: siteKey }) }), _jsx(FactRow, { icon: _jsx(Sigil, { name: "chat" }), label: active ? "Chat is live" : "Chat is paused", children: _jsxs("span", { className: "tourtois-website-fact", children: [_jsx("span", { className: "text-sm", children: active
329
+ ? "Pause to stop new messages without removing the code."
330
+ : "Visitors can’t send messages until you resume it." }), _jsx(KeycapButton, { density: "compact", label: active ? "Pause website" : "Resume website", disabled: patch.isPending, onClick: () => {
331
+ patch.mutate({
332
+ lifecycle: active ? "suspended" : "active",
333
+ });
334
+ } })] }) }), _jsx(FactRow, { icon: _jsx(Sigil, { name: "restricted" }), label: "Security check", children: _jsx(CheckKey, { label: "Require a security check", hint: "Visitors pass a Cloudflare Turnstile check before they can chat. This host needs its Turnstile keys.", checked: turnstile === true, disabled: patch.isPending, onChange: (event) => {
335
+ patch.mutate({ turnstile: event.currentTarget.checked });
336
+ } }) }), _jsx(FactRow, { icon: _jsx(Sigil, { name: "loop" }), label: "New site key", children: _jsxs("span", { className: "tourtois-website-fact", children: [_jsx("span", { className: "text-sm", children: "Make a new key if the old code leaked. The code on your website stops working until you paste the new one." }), confirmingKey ? (_jsxs("span", { className: "flex flex-wrap items-center gap-sm", children: [_jsx(Status, { glyph: "dot", label: "This replaces the key now", tone: "warning" }), _jsx(KeycapButton, { density: "compact", label: "Make a new key", tone: "destructive", disabled: patch.isPending, onClick: () => {
337
+ patch.mutate({ rotateSiteKey: true });
338
+ setConfirmingKey(false);
339
+ } }), _jsx(KeycapButton, { density: "compact", label: "Keep this key", onClick: () => {
340
+ setConfirmingKey(false);
341
+ } })] })) : (_jsx(KeycapButton, { density: "compact", label: "New site key", disabled: patch.isPending, onClick: () => {
342
+ setConfirmingKey(true);
343
+ } }))] }) })] }), notice, patch.isError ? _jsx("p", { role: "alert", children: patch.error.message }) : null, _jsx(Conversations, { port: port, site: site })] })) : null] }) }));
344
+ }
345
+ function Conversations({ port, site, }) {
346
+ const { bindingId } = site;
347
+ const [shown, setShown] = useState(false);
348
+ const [reading, setReading] = useState(null);
349
+ const list = useQuery({
350
+ queryKey: tourtoisQueryKeys.websiteConversations(port.scope, bindingId),
351
+ enabled: shown,
352
+ retry: false,
353
+ queryFn: () => port.conversations(site),
354
+ });
355
+ const transcript = useQuery({
356
+ queryKey: tourtoisQueryKeys.websiteTranscript(port.scope, bindingId, reading ?? ""),
357
+ enabled: reading !== null,
358
+ retry: false,
359
+ queryFn: () => reading === null
360
+ ? Promise.reject(new Error("No conversation is open"))
361
+ : port.transcript(site, reading),
362
+ });
363
+ return (_jsxs("section", { className: "grid gap-sm", "aria-label": "Conversations", children: [_jsx(DataListHeading, { level: 3, children: "Conversations" }), shown ? null : (_jsx(KeycapButton, { density: "compact", label: "Show conversations", onClick: () => {
364
+ setShown(true);
365
+ } })), list.isPending && shown ? _jsx("p", { role: "status", children: "Loading\u2026" }) : null, list.isError ? (_jsx("p", { role: "alert", children: "Conversations could not be loaded." })) : null, list.data?.length === 0 ? (_jsx("p", { className: "text-sm", children: "No visitor has written yet." })) : null, list.data !== undefined && list.data.length > 0 ? (_jsx(DataList, { density: "compact", "aria-label": "Website conversations", children: list.data.map((conversation) => (_jsx(FactRow, { label: conversation.label, children: _jsxs("span", { className: "flex flex-wrap items-center gap-sm", children: [_jsx("span", { className: "text-sm", children: new Date(conversation.lastEventAt).toLocaleString() }), _jsx(KeycapButton, { density: "compact", label: reading === conversation.sessionId
366
+ ? "Close transcript"
367
+ : "Read transcript", "aria-label": `${reading === conversation.sessionId ? "Close" : "Read"} transcript of ${conversation.label}`, onClick: () => {
368
+ setReading(reading === conversation.sessionId
369
+ ? null
370
+ : conversation.sessionId);
371
+ } })] }) }, conversation.sessionId))) })) : null, reading !== null && transcript.isPending ? (_jsx("p", { role: "status", children: "Loading\u2026" })) : null, transcript.isError ? (_jsx("p", { role: "alert", children: "This conversation could not be read." })) : null, reading !== null && transcript.data ? (_jsx("ol", { "aria-label": "Transcript", className: "grid gap-xs", children: transcript.data.lines.map((line, index) => (_jsxs("li", { className: "text-sm", children: [_jsxs("strong", { children: [line.role === "visitor" ? "Visitor" : "Agent", ":"] }), " ", line.text] }, `${String(index)}-${line.role}`))) })) : null] }));
372
+ }