@tansy/ai 0.0.0-stage → 0.1.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 (69) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +12 -2
  3. package/admin.d.ts +2 -0
  4. package/admin.js +17 -0
  5. package/ai.css +280 -0
  6. package/api.d.ts +91 -0
  7. package/api.js +79 -0
  8. package/assistant.d.ts +3 -0
  9. package/assistant.js +290 -0
  10. package/attach.d.ts +48 -0
  11. package/attach.js +141 -0
  12. package/attachments.d.ts +34 -0
  13. package/attachments.js +66 -0
  14. package/chats.d.ts +35 -0
  15. package/chats.js +78 -0
  16. package/client.d.ts +3 -0
  17. package/client.js +88 -0
  18. package/composer.d.ts +38 -0
  19. package/composer.js +155 -0
  20. package/errors.d.ts +5 -0
  21. package/errors.js +25 -0
  22. package/history.d.ts +15 -0
  23. package/history.js +47 -0
  24. package/icons.generated.d.ts +5 -0
  25. package/icons.generated.js +66 -0
  26. package/images.d.ts +21 -0
  27. package/images.js +23 -0
  28. package/index.d.ts +26 -0
  29. package/index.js +701 -0
  30. package/logic.d.ts +77 -0
  31. package/logic.js +166 -0
  32. package/markdown.d.ts +38 -0
  33. package/markdown.js +142 -0
  34. package/media.d.ts +24 -0
  35. package/media.js +64 -0
  36. package/messages.d.ts +891 -0
  37. package/messages.js +689 -0
  38. package/models.d.ts +7 -0
  39. package/models.js +47 -0
  40. package/package.json +46 -4
  41. package/parts.d.ts +59 -0
  42. package/parts.js +110 -0
  43. package/provider.d.ts +134 -0
  44. package/provider.js +117 -0
  45. package/role.d.ts +24 -0
  46. package/role.js +25 -0
  47. package/workflow/check.d.ts +46 -0
  48. package/workflow/check.js +63 -0
  49. package/workflow/client.d.ts +90 -0
  50. package/workflow/client.js +51 -0
  51. package/workflow/editor.d.ts +13 -0
  52. package/workflow/editor.js +133 -0
  53. package/workflow/engine.d.ts +232 -0
  54. package/workflow/engine.js +779 -0
  55. package/workflow/icons.d.ts +26 -0
  56. package/workflow/icons.js +67 -0
  57. package/workflow/model-picker.d.ts +22 -0
  58. package/workflow/model-picker.js +69 -0
  59. package/workflow/page.d.ts +3 -0
  60. package/workflow/page.js +118 -0
  61. package/workflow/routes.d.ts +12 -0
  62. package/workflow/routes.js +418 -0
  63. package/workflow/run.d.ts +8 -0
  64. package/workflow/run.js +162 -0
  65. package/workflow/schema.d.ts +183 -0
  66. package/workflow/schema.js +143 -0
  67. package/workflow/templates.d.ts +9 -0
  68. package/workflow/templates.js +81 -0
  69. package/workflow/workflow.css +241 -0
package/chats.js ADDED
@@ -0,0 +1,78 @@
1
+ import { createHash } from "node:crypto";
2
+ import { attachmentIds, attachmentStore } from "./attachments";
3
+ /**
4
+ * Each person's assistant conversations, in the plugin's store: a JSON value per chat,
5
+ * under a key only that person's id leads to. Nobody else's chats can be named, read
6
+ * or deleted, whatever permissions they hold.
7
+ */
8
+ /** A chat id as the browser makes it. */
9
+ export const CHAT_ID = /^[A-Za-z0-9_-]{1,64}$/;
10
+ /** Kept per person. Saving one more drops the least recently used. */
11
+ export const MAX_CHATS = 100;
12
+ /** Below the store's 256 KiB a value. A longer chat keeps its most recent messages. */
13
+ const MAX_BYTES = 240 * 1024;
14
+ const TITLE_LENGTH = 80;
15
+ /** The person's id as a store key: ids from sign-in providers can hold any character. */
16
+ const owner = (userId) => createHash("sha256").update(userId).digest("hex").slice(0, 32);
17
+ const chatKey = (userId, id) => `chat/${owner(userId)}/${id}`;
18
+ const metaKey = (userId, id) => `meta/${owner(userId)}/${id}`;
19
+ /** The first thing the person asked, on one line. */
20
+ export function titleOf(messages) {
21
+ const first = messages.find((message) => message.role === "user");
22
+ const text = first?.parts.map((part) => (part.type === "text" ? part.text : "")).join(" ").replace(/\s+/g, " ").trim() ?? "";
23
+ return text.length > TITLE_LENGTH ? `${text.slice(0, TITLE_LENGTH - 1)}…` : text || "New chat";
24
+ }
25
+ /**
26
+ * The whole conversation after a turn. The browser sends only its latest messages, so the
27
+ * stored ones before them are kept. Anything stored from where they start is replaced by
28
+ * the turn's messages, which also drops an answer the person asked to try again.
29
+ */
30
+ export function mergeHistory(stored, finished) {
31
+ const start = finished.length ? stored.findIndex((message) => message.id === finished[0].id) : -1;
32
+ return start > 0 ? [...stored.slice(0, start), ...finished] : finished;
33
+ }
34
+ /** Drops the oldest messages until the chat fits in one stored value. */
35
+ export function fitted(messages) {
36
+ let kept = messages;
37
+ while (kept.length > 1 && Buffer.byteLength(JSON.stringify(kept)) > MAX_BYTES)
38
+ kept = kept.slice(Math.max(1, Math.floor(kept.length / 10)));
39
+ return Buffer.byteLength(JSON.stringify(kept)) > MAX_BYTES ? [] : kept;
40
+ }
41
+ const isChat = (value) => Boolean(value && typeof value === "object" && Array.isArray(value.messages));
42
+ export function chatStore(store) {
43
+ async function list(userId) {
44
+ const rows = await store.list(`meta/${owner(userId)}/`);
45
+ return rows
46
+ .map(({ key, value }) => ({ id: key.slice(key.lastIndexOf("/") + 1), ...value }))
47
+ .sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));
48
+ }
49
+ async function get(userId, id) {
50
+ const value = await store.get(chatKey(userId, id));
51
+ return isChat(value) ? { ...value, id } : null;
52
+ }
53
+ /** Deletes a chat with the files attached to it and the pictures drawn in it. */
54
+ async function remove(userId, id) {
55
+ const chat = await get(userId, id);
56
+ const files = attachmentStore(store);
57
+ for (const attachment of attachmentIds(chat?.messages))
58
+ await files.remove(userId, attachment);
59
+ await store.delete(chatKey(userId, id));
60
+ await store.delete(metaKey(userId, id));
61
+ }
62
+ /** Saves a turn of the conversation. */
63
+ async function save(userId, id, finished) {
64
+ const previous = await get(userId, id);
65
+ const messages = fitted(mergeHistory(previous?.messages ?? [], finished));
66
+ if (!messages.length)
67
+ return;
68
+ const summary = { title: previous?.title ?? titleOf(messages), updatedAt: new Date().toISOString() };
69
+ await store.set(chatKey(userId, id), { ...summary, messages });
70
+ await store.set(metaKey(userId, id), summary);
71
+ if (!previous) {
72
+ const all = await list(userId);
73
+ for (const old of all.slice(MAX_CHATS))
74
+ await remove(userId, old.id);
75
+ }
76
+ }
77
+ return { list, get, save, remove };
78
+ }
package/client.d.ts ADDED
@@ -0,0 +1,3 @@
1
+ import "./ai.css";
2
+ declare const _default: import("tansy/admin").AdminClientParts;
3
+ export default _default;
package/client.js ADDED
@@ -0,0 +1,88 @@
1
+ "use client";
2
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
3
+ import { Button, defineAdminClient, useT } from "tansy/admin";
4
+ import { useEffect, useState } from "react";
5
+ import { aiStatus, post } from "./api";
6
+ import "./ai.css";
7
+ /** Whether to offer AI here at all: the person may use it, and a provider is set up. */
8
+ function useReady() {
9
+ const [ready, setReady] = useState(false);
10
+ useEffect(() => { void aiStatus().then((status) => setReady(Boolean(status?.ready))); }, []);
11
+ return ready;
12
+ }
13
+ /** Under the record's fields: describe the record, and the form fills in for review. Nothing is saved. */
14
+ function FillPanel({ collection, values, setValues }) {
15
+ const ready = useReady();
16
+ const { t } = useT();
17
+ const [prompt, setPrompt] = useState("");
18
+ const [busy, setBusy] = useState(false);
19
+ const [note, setNote] = useState(null);
20
+ if (!ready)
21
+ return null;
22
+ const fill = async () => {
23
+ setBusy(true);
24
+ setNote(null);
25
+ try {
26
+ const result = await post("/fill", { collection: collection.slug, prompt, values });
27
+ const count = Object.keys(result.values).length;
28
+ setValues(result.values);
29
+ setNote({ error: false, text: count ? t("ext.ai.fill.filled", { count }) : t("ext.ai.fill.nothing") });
30
+ }
31
+ catch (error) {
32
+ setNote({ error: true, text: error.message });
33
+ }
34
+ finally {
35
+ setBusy(false);
36
+ }
37
+ };
38
+ return (_jsxs("section", { className: "ai-panel", children: [_jsx("label", { htmlFor: "ai-fill-prompt", className: "cms-label", children: t("ext.ai.fill.title") }), _jsx("textarea", { id: "ai-fill-prompt", className: "cms-input cms-mt-1", rows: 3, value: prompt, placeholder: t("ext.ai.fill.placeholder"), onChange: (event) => setPrompt(event.target.value) }), _jsx(Button, { variant: "secondary", className: "cms-mt-1", disabled: busy || !prompt.trim(), onClick: () => void fill(), children: busy ? t("ext.ai.fill.busy") : t("ext.ai.fill.button") }), note && _jsx("p", { className: note.error ? "cms-error cms-mt-1" : "cms-hint cms-mt-1", children: note.text })] }));
39
+ }
40
+ const ACTIONS = [
41
+ { action: "write", needsText: false },
42
+ { action: "improve", needsText: true },
43
+ { action: "shorten", needsText: true },
44
+ { action: "expand", needsText: true },
45
+ { action: "fix", needsText: true },
46
+ { action: "translate", needsText: true },
47
+ ];
48
+ const hasText = (value) => (typeof value === "string" ? Boolean(value.trim()) : Boolean(value && typeof value === "object"));
49
+ /** By a text field: write it, or rework what's there. The result lands in the form, unsaved. */
50
+ function WriteMenu({ collection, field, value, values, setValue }) {
51
+ const ready = useReady();
52
+ const { t } = useT();
53
+ const [open, setOpen] = useState(false);
54
+ const [instruction, setInstruction] = useState("");
55
+ const [busy, setBusy] = useState(null);
56
+ const [error, setError] = useState(null);
57
+ if (!ready)
58
+ return null;
59
+ const run = async (action) => {
60
+ let asked = instruction.trim();
61
+ if (action === "translate" && !asked) {
62
+ asked = window.prompt(t("ext.ai.write.whichLanguage"))?.trim() ?? "";
63
+ if (!asked)
64
+ return;
65
+ asked = `Translate into ${asked}.`;
66
+ }
67
+ setBusy(action);
68
+ setError(null);
69
+ try {
70
+ const result = await post("/write", { collection: collection.slug, field: field.name, action, instruction: asked || undefined, value, values });
71
+ if (result.value !== null && result.value !== undefined)
72
+ setValue(result.value);
73
+ setOpen(false);
74
+ setInstruction("");
75
+ }
76
+ catch (failure) {
77
+ setError(failure.message);
78
+ }
79
+ finally {
80
+ setBusy(null);
81
+ }
82
+ };
83
+ return (_jsxs("span", { className: "ai-write", children: [_jsxs("button", { type: "button", className: "cms-field-action", "aria-expanded": open, onClick: () => setOpen(!open), children: ["\u2726 ", t("ext.ai.actions.ai-write")] }), open && (_jsxs("div", { className: "ai-write-menu", role: "menu", children: [_jsx("input", { className: "cms-input", value: instruction, placeholder: t("ext.ai.write.instruction"), onChange: (event) => setInstruction(event.target.value) }), ACTIONS.filter((item) => !item.needsText || hasText(value)).map((item) => (_jsx("button", { type: "button", role: "menuitem", className: "ai-write-item", disabled: busy !== null, onClick: () => void run(item.action), children: busy === item.action ? t("ext.ai.write.working") : t(`ext.ai.write.${item.action}`) }, item.action))), error && _jsx("p", { className: "cms-error", children: error })] }))] }));
84
+ }
85
+ export default defineAdminClient({
86
+ recordPanels: [{ id: "ai-fill", component: FillPanel }],
87
+ fieldActions: [{ id: "ai-write", label: "AI", permission: "ext.ai:use", types: ["text", "rich_text"], component: WriteMenu }],
88
+ });
package/composer.d.ts ADDED
@@ -0,0 +1,38 @@
1
+ import { type RefObject } from "react";
2
+ import { type AiStatus, type ProviderChoice, type Reasoning } from "./api";
3
+ import { type Attachments } from "./attach";
4
+ /**
5
+ * What the person chose in the chat. `provider` null is the site's provider, `model` null
6
+ * that provider's own model, and `role` null the site's role.
7
+ */
8
+ export interface Choice {
9
+ provider: string | null;
10
+ model: string | null;
11
+ reasoning: Reasoning;
12
+ role: string | null;
13
+ }
14
+ /** The provider the chat uses: the one chosen while it's still set up, else the site's. */
15
+ export declare function activeProvider(status: AiStatus, provider: string | null): ProviderChoice;
16
+ /** Picks the chat's provider, when more than one is set up. Choosing another starts on its own model. */
17
+ export declare function ProviderMenu({ status, value, onChange }: {
18
+ status: AiStatus;
19
+ value: string | null;
20
+ onChange: (provider: string | null) => void;
21
+ }): import("react").JSX.Element | null;
22
+ /** The box people type in: grows with the text, sends on Enter, and turns its button into Stop while answering. */
23
+ export declare function Composer({ value, onChange, onSend, onStop, busy, disabled, autoFocus, status, choice, onChoice, inputRef, attachments }: {
24
+ value: string;
25
+ onChange: (value: string) => void;
26
+ onSend: () => void;
27
+ onStop: () => void;
28
+ busy: boolean;
29
+ disabled: boolean;
30
+ autoFocus?: boolean;
31
+ status: AiStatus;
32
+ choice: Choice;
33
+ onChoice: (choice: Choice) => void;
34
+ /** The text box, for a suggestion that puts words in it and leaves the cursor at their end. */
35
+ inputRef?: RefObject<HTMLTextAreaElement | null>;
36
+ /** Files going with the next message. */
37
+ attachments: Attachments;
38
+ }): import("react").JSX.Element;
package/composer.js ADDED
@@ -0,0 +1,155 @@
1
+ "use client";
2
+ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
3
+ import { useT } from "tansy/admin";
4
+ import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
5
+ import { chatModels, chatRoles } from "./api";
6
+ import { ArrowUp, Brain, Check, ChevronDown, Search, Shield, StopSquare, useDismiss } from "./parts";
7
+ import { ModelIcon, ProviderIcon } from "./workflow/icons";
8
+ import { AttachButton, PendingFiles } from "./attach";
9
+ /** The provider the chat uses: the one chosen while it's still set up, else the site's. */
10
+ export function activeProvider(status, provider) {
11
+ const site = { id: status.provider ?? "", label: status.providerLabel ?? "", icon: status.providerIcon, model: status.model, listsModels: Boolean(status.listsModels) };
12
+ return (provider && status.providers?.find((item) => item.id === provider)) || site;
13
+ }
14
+ /** Picks the chat's provider, when more than one is set up. Choosing another starts on its own model. */
15
+ export function ProviderMenu({ status, value, onChange }) {
16
+ const { t } = useT();
17
+ const [open, setOpen] = useState(false);
18
+ const root = useRef(null);
19
+ const close = useCallback(() => setOpen(false), []);
20
+ useDismiss(root, open, close);
21
+ const providers = status.providers ?? [];
22
+ if (!status.ready || !status.chooseModel || providers.length < 2)
23
+ return null;
24
+ const current = activeProvider(status, value);
25
+ return (_jsxs("div", { ref: root, className: "ai-menu-root", children: [_jsxs("button", { type: "button", className: "ai-pill", "aria-haspopup": "menu", "aria-expanded": open, title: t("ext.ai.composer.provider"), onClick: () => setOpen(!open), children: [_jsx(ProviderIcon, { provider: current.id, icon: current.icon, size: 16 }), _jsx("span", { className: "ai-pill-text", children: current.label }), _jsx(ChevronDown, {})] }), open && (_jsxs("div", { className: "ai-menu ai-menu-providers", role: "menu", "aria-label": t("ext.ai.composer.provider"), children: [_jsx("p", { className: "ai-menu-heading", children: t("ext.ai.composer.provider") }), providers.map((provider) => {
26
+ const selected = provider.id === current.id;
27
+ return (_jsxs("button", { type: "button", role: "menuitemradio", "aria-checked": selected, className: "ai-menu-item", onClick: () => { onChange(provider.id === status.provider ? null : provider.id); close(); }, children: [_jsx(ProviderIcon, { provider: provider.id, icon: provider.icon, size: 18 }), _jsxs("span", { className: "ai-menu-text", children: [_jsx("span", { className: "ai-menu-label", children: provider.label }), provider.id === status.provider && _jsx("span", { className: "ai-menu-detail", children: t("ext.ai.composer.siteProvider") })] }), selected && _jsx(Check, {})] }, provider.id));
28
+ })] }))] }));
29
+ }
30
+ const REASONING = ["provider-default", "none", "low", "medium", "high"];
31
+ /** "anthropic/claude-opus-5-5" as "claude-opus-5-5", for a button with little room. The full id is its title. */
32
+ const shortName = (id) => id.split("/").pop() || id;
33
+ /** At most this many models in the menu at once; searching narrows the rest. */
34
+ const SHOWN = 200;
35
+ /** Picks the chat's model from what the chosen provider lists, or any id typed in. */
36
+ function ModelMenu({ status, provider, value, onChange }) {
37
+ const { t } = useT();
38
+ const [open, setOpen] = useState(false);
39
+ const [query, setQuery] = useState("");
40
+ const [models, setModels] = useState(null);
41
+ const [active, setActive] = useState(0);
42
+ const root = useRef(null);
43
+ const list = useRef(null);
44
+ const close = useCallback(() => { setOpen(false); setQuery(""); setActive(0); }, []);
45
+ useDismiss(root, open, close);
46
+ useEffect(() => {
47
+ if (!open || models !== null || !provider.listsModels)
48
+ return;
49
+ let live = true;
50
+ void chatModels(provider.id === status.provider ? null : provider.id).then((result) => { if (live)
51
+ setModels("options" in result ? result.options : result.error); });
52
+ return () => { live = false; };
53
+ }, [open, models, provider.listsModels, provider.id, status.provider]);
54
+ const options = useMemo(() => {
55
+ const words = query.trim().toLowerCase();
56
+ const all = Array.isArray(models) ? models : [];
57
+ const found = words ? all.filter((model) => `${model.value} ${model.label ?? ""}`.toLowerCase().includes(words)) : all;
58
+ const typed = query.trim();
59
+ const items = [];
60
+ if (!words)
61
+ items.push({ value: null, label: provider.id === status.provider ? t("ext.ai.composer.siteModel") : t("ext.ai.composer.providerModel"), detail: provider.model });
62
+ if (typed && !all.some((model) => model.value === typed))
63
+ items.push({ value: typed, label: t("ext.ai.composer.useTyped", { model: typed }) });
64
+ for (const model of found.slice(0, SHOWN))
65
+ items.push({ value: model.value, label: model.label && model.label !== model.value ? model.label : model.value, detail: model.label && model.label !== model.value ? model.value : undefined });
66
+ return items;
67
+ }, [models, query, provider.id, provider.model, status.provider, t]);
68
+ useEffect(() => { list.current?.querySelector(`[data-index="${active}"]`)?.scrollIntoView({ block: "nearest" }); }, [active]);
69
+ const pick = (model) => { onChange(model); close(); };
70
+ const current = value ?? provider.model ?? "";
71
+ return (_jsxs("div", { ref: root, className: "ai-menu-root", children: [_jsxs("button", { type: "button", className: "ai-pill", "aria-haspopup": "listbox", "aria-expanded": open, title: current, onClick: () => (open ? close() : setOpen(true)), children: [_jsx(ModelIcon, { model: current, provider: provider.id, icon: provider.icon, size: 16 }), _jsx("span", { className: "ai-pill-text", children: shortName(current) || t("ext.ai.composer.model") }), _jsx(ChevronDown, {})] }), open && (_jsxs("div", { className: "ai-menu ai-menu-models", role: "dialog", "aria-label": t("ext.ai.composer.model"), children: [_jsxs("label", { className: "ai-menu-search", children: [_jsx(Search, {}), _jsx("input", { autoFocus: true, value: query, placeholder: t("ext.ai.composer.searchModels"), "aria-label": t("ext.ai.composer.searchModels"), onChange: (event) => { setQuery(event.target.value); setActive(0); }, onKeyDown: (event) => {
72
+ if (event.key === "ArrowDown") {
73
+ event.preventDefault();
74
+ setActive((at) => Math.min(at + 1, options.length - 1));
75
+ }
76
+ else if (event.key === "ArrowUp") {
77
+ event.preventDefault();
78
+ setActive((at) => Math.max(at - 1, 0));
79
+ }
80
+ else if (event.key === "Enter") {
81
+ event.preventDefault();
82
+ const option = options[active];
83
+ if (option)
84
+ pick(option.value);
85
+ }
86
+ } })] }), _jsx("ul", { ref: list, className: "ai-menu-list", role: "listbox", "aria-label": t("ext.ai.composer.model"), children: options.map((option, index) => {
87
+ const selected = option.value === value;
88
+ return (_jsxs("li", { role: "option", "aria-selected": selected, "data-index": index, className: index === active ? "ai-menu-item ai-menu-active" : "ai-menu-item", onPointerMove: () => setActive(index), onClick: () => pick(option.value), children: [_jsx(ModelIcon, { model: option.value ?? provider.model ?? "", provider: provider.id, icon: provider.icon, size: 18 }), _jsxs("span", { className: "ai-menu-text", children: [_jsx("span", { className: "ai-menu-label", children: option.label }), option.detail && _jsx("span", { className: "ai-menu-detail", children: option.detail })] }), selected && _jsx(Check, {})] }, option.value ?? "site"));
89
+ }) }), provider.listsModels && models === null && _jsx("p", { className: "ai-menu-note", role: "status", children: t("ext.ai.composer.loadingModels") }), typeof models === "string" && _jsx("p", { className: "ai-menu-note", role: "status", children: models }), Array.isArray(models) && query.trim() && options.length <= 1 && _jsx("p", { className: "ai-menu-note", children: t("ext.ai.composer.noModels") })] }))] }));
90
+ }
91
+ /** The role the assistant acts with in this chat. Any role can only narrow the person's own access. */
92
+ function RoleMenu({ status, value, onChange }) {
93
+ const { t } = useT();
94
+ const [open, setOpen] = useState(false);
95
+ const [roles, setRoles] = useState(null);
96
+ const root = useRef(null);
97
+ const close = useCallback(() => setOpen(false), []);
98
+ useDismiss(root, open, close);
99
+ // Listed once, so the pill can show the role's name rather than its id.
100
+ useEffect(() => { void chatRoles().then((result) => setRoles("options" in result ? result.options : result.error)); }, []);
101
+ const list = Array.isArray(roles) ? roles : [];
102
+ const labelOf = (name) => list.find((role) => role.value === name)?.label ?? name ?? "";
103
+ const current = labelOf(value ?? status.role);
104
+ return (_jsxs("div", { ref: root, className: "ai-menu-root", children: [_jsxs("button", { type: "button", className: value ? "ai-pill ai-pill-on" : "ai-pill", "aria-haspopup": "menu", "aria-expanded": open, title: t("ext.ai.composer.roleTitle"), onClick: () => setOpen(!open), children: [_jsx(Shield, {}), _jsx("span", { className: "ai-pill-text", children: current || t("ext.ai.composer.role") }), _jsx(ChevronDown, {})] }), open && (_jsxs("div", { className: "ai-menu ai-menu-roles", role: "menu", "aria-label": t("ext.ai.composer.role"), children: [_jsx("p", { className: "ai-menu-heading", children: t("ext.ai.composer.roleTitle") }), _jsxs("div", { className: "ai-menu-scroll", children: [_jsxs("button", { type: "button", role: "menuitemradio", "aria-checked": value === null, className: "ai-menu-item", onClick: () => { onChange(null); close(); }, children: [_jsxs("span", { className: "ai-menu-text", children: [_jsx("span", { className: "ai-menu-label", children: t("ext.ai.composer.siteRole") }), _jsx("span", { className: "ai-menu-detail", children: labelOf(status.role) })] }), value === null && _jsx(Check, {})] }), list.map((role) => (_jsxs("button", { type: "button", role: "menuitemradio", "aria-checked": role.value === value, className: "ai-menu-item", title: role.description, onClick: () => { onChange(role.value); close(); }, children: [_jsxs("span", { className: "ai-menu-text", children: [_jsx("span", { className: "ai-menu-label", children: role.label }), role.description && _jsx("span", { className: "ai-menu-detail", children: role.description })] }), role.value === value && _jsx(Check, {})] }, role.value)))] }), roles === null && _jsx("p", { className: "ai-menu-note", role: "status", children: t("ext.ai.composer.loadingRoles") }), typeof roles === "string" && _jsx("p", { className: "ai-menu-note", role: "status", children: t("ext.ai.composer.rolesFailed") })] }))] }));
105
+ }
106
+ /** How long the model thinks before it answers. */
107
+ function ThinkingMenu({ value, onChange }) {
108
+ const { t } = useT();
109
+ const [open, setOpen] = useState(false);
110
+ const root = useRef(null);
111
+ const close = useCallback(() => setOpen(false), []);
112
+ useDismiss(root, open, close);
113
+ const on = value !== "none" && value !== "provider-default";
114
+ return (_jsxs("div", { ref: root, className: "ai-menu-root", children: [_jsxs("button", { type: "button", className: on ? "ai-pill ai-pill-on" : "ai-pill", "aria-haspopup": "menu", "aria-expanded": open, title: t("ext.ai.composer.thinking"), onClick: () => setOpen(!open), children: [_jsx(Brain, {}), _jsx("span", { className: "ai-pill-text", children: value === "provider-default" ? t("ext.ai.composer.thinking") : t(`ext.ai.composer.reasoning.${value}`) }), _jsx(ChevronDown, {})] }), open && (_jsxs("div", { className: "ai-menu ai-menu-thinking", role: "menu", "aria-label": t("ext.ai.composer.thinking"), children: [_jsx("p", { className: "ai-menu-heading", children: t("ext.ai.composer.thinking") }), REASONING.map((level) => (_jsxs("button", { type: "button", role: "menuitemradio", "aria-checked": level === value, className: "ai-menu-item", onClick: () => { onChange(level); close(); }, children: [_jsxs("span", { className: "ai-menu-text", children: [_jsx("span", { className: "ai-menu-label", children: t(`ext.ai.composer.reasoning.${level}`) }), _jsx("span", { className: "ai-menu-detail", children: t(`ext.ai.composer.reasoningHint.${level}`) })] }), level === value && _jsx(Check, {})] }, level)))] }))] }));
115
+ }
116
+ /** The box people type in: grows with the text, sends on Enter, and turns its button into Stop while answering. */
117
+ export function Composer({ value, onChange, onSend, onStop, busy, disabled, autoFocus, status, choice, onChoice, inputRef, attachments }) {
118
+ const { t } = useT();
119
+ const own = useRef(null);
120
+ const box = inputRef ?? own;
121
+ useLayoutEffect(() => {
122
+ const element = box.current;
123
+ if (!element)
124
+ return;
125
+ element.style.height = "auto";
126
+ element.style.height = `${Math.min(element.scrollHeight, 288)}px`;
127
+ }, [value]);
128
+ // Back to typing once an answer ends.
129
+ useEffect(() => { if (!busy && !disabled && autoFocus)
130
+ box.current?.focus({ preventScroll: true }); }, [busy, disabled, autoFocus]);
131
+ const [dragging, setDragging] = useState(false);
132
+ const canAttach = status.ready && !disabled && Boolean(attachments.capabilities);
133
+ const sendable = (Boolean(value.trim()) || attachments.ready) && !attachments.uploading;
134
+ return (_jsxs("form", { className: dragging ? "ai-compose ai-compose-drop" : "ai-compose", onSubmit: (event) => { event.preventDefault(); if (sendable)
135
+ onSend(); }, onClick: (event) => { if (event.target === event.currentTarget)
136
+ box.current?.focus(); }, onDragOver: (event) => { if (canAttach && event.dataTransfer.types.includes("Files")) {
137
+ event.preventDefault();
138
+ setDragging(true);
139
+ } }, onDragLeave: (event) => { if (!event.currentTarget.contains(event.relatedTarget))
140
+ setDragging(false); }, onDrop: (event) => { if (!canAttach)
141
+ return; event.preventDefault(); setDragging(false); attachments.add(Array.from(event.dataTransfer.files)); }, children: [dragging && _jsx("p", { className: "ai-drop-note", "aria-hidden": "true", children: t("ext.ai.attach.drop") }), _jsx(PendingFiles, { attachments: attachments }), _jsx("textarea", { ref: box, className: "ai-input", rows: 1, value: value, disabled: disabled, autoFocus: autoFocus, "aria-label": t("ext.ai.assistant.placeholder"), placeholder: t("ext.ai.assistant.placeholder"), onChange: (event) => onChange(event.target.value), onKeyDown: (event) => { if (event.key === "Enter" && !event.shiftKey && !event.nativeEvent.isComposing) {
142
+ event.preventDefault();
143
+ if (sendable)
144
+ onSend();
145
+ } }, onPaste: (event) => {
146
+ // A picture pasted from the clipboard is attached, as in other chat apps. Text pastes as usual.
147
+ const files = Array.from(event.clipboardData.files);
148
+ if (!canAttach || !files.length)
149
+ return;
150
+ event.preventDefault();
151
+ attachments.add(files);
152
+ } }), _jsxs("div", { className: "ai-compose-bar", children: [_jsxs("div", { className: "ai-compose-tools", children: [status.ready && _jsx(AttachButton, { attachments: attachments, disabled: disabled }), status.ready && status.chooseModel && (_jsxs(_Fragment, { children: [_jsx(ModelMenu, { status: status, provider: activeProvider(status, choice.provider), value: choice.model, onChange: (model) => onChoice({ ...choice, model }) }, choice.provider ?? "site"), _jsx(ThinkingMenu, { value: choice.reasoning, onChange: (reasoning) => onChoice({ ...choice, reasoning }) })] })), status.ready && !status.chooseModel && status.model && _jsxs("span", { className: "ai-pill ai-pill-static", title: status.model, children: [_jsx(ModelIcon, { model: status.model, provider: status.provider ?? "", icon: status.providerIcon, size: 16 }), _jsx("span", { className: "ai-pill-text", children: shortName(status.model) })] }), status.ready && status.chooseRole && _jsx(RoleMenu, { status: status, value: choice.role, onChange: (role) => onChoice({ ...choice, role }) })] }), busy
153
+ ? _jsx("button", { type: "button", className: "ai-send ai-send-stop", "aria-label": t("ext.ai.assistant.stop"), title: t("ext.ai.assistant.stop"), onClick: onStop, children: _jsx(StopSquare, {}) })
154
+ : _jsx("button", { type: "submit", className: "ai-send", "aria-label": t("ext.ai.assistant.send"), title: `${t("ext.ai.assistant.send")} · ${t("ext.ai.assistant.hint")}`, disabled: disabled || !sendable, children: _jsx(ArrowUp, {}) })] })] }));
155
+ }
package/errors.d.ts ADDED
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Why the provider refused, in its own words when it gave them, such as a used-up quota or
3
+ * an unknown model, so the owner can act on it. Anything that looks like a key is hidden.
4
+ */
5
+ export declare function providerReason(error: unknown): string;
package/errors.js ADDED
@@ -0,0 +1,25 @@
1
+ const PROVIDER_FAILED = "The AI provider couldn't answer just now. Check AI → Settings, or try again in a moment.";
2
+ /**
3
+ * Why the provider refused, in its own words when it gave them, such as a used-up quota or
4
+ * an unknown model, so the owner can act on it. Anything that looks like a key is hidden.
5
+ */
6
+ export function providerReason(error) {
7
+ let found = error;
8
+ for (let depth = 0; found && typeof found.statusCode !== "number" && depth < 5; depth++) {
9
+ found = (found.lastError ?? found.cause);
10
+ }
11
+ if (!found || typeof found.statusCode !== "number")
12
+ return PROVIDER_FAILED;
13
+ let said = "";
14
+ try {
15
+ const body = JSON.parse(String(found.responseBody ?? ""));
16
+ said = String((typeof body.error === "object" ? body.error?.message : body.error) ?? body.message ?? "");
17
+ }
18
+ catch {
19
+ said = typeof found.message === "string" ? found.message : "";
20
+ }
21
+ said = said.replace(/[A-Za-z0-9_\-*.]{24,}/g, "…").trim().slice(0, 300);
22
+ if (found.statusCode === 401 || found.statusCode === 403)
23
+ return `The AI provider refused the key${said ? `: ${said}` : ""}. Check it under AI → Settings.`;
24
+ return said ? `The AI provider answered ${found.statusCode}: ${said}` : PROVIDER_FAILED;
25
+ }
package/history.d.ts ADDED
@@ -0,0 +1,15 @@
1
+ import type { ChatSummary } from "./api";
2
+ type Group = "today" | "yesterday" | "week" | "month" | "older";
3
+ /** Which heading a chat goes under, by when it was last used, from the start of today. */
4
+ export declare function groupOf(updatedAt: string, now?: Date): Group;
5
+ /** Saved chats, newest first under day headings, with a search, as a side panel of the assistant. */
6
+ export declare function History({ chats, loaded, current, onOpen, onDelete, onNew, onClose }: {
7
+ chats: ChatSummary[];
8
+ loaded: boolean;
9
+ current?: string;
10
+ onOpen: (id: string) => void;
11
+ onDelete: (id: string) => void;
12
+ onNew: () => void;
13
+ onClose: () => void;
14
+ }): import("react").JSX.Element;
15
+ export {};
package/history.js ADDED
@@ -0,0 +1,47 @@
1
+ "use client";
2
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
3
+ import { useT } from "tansy/admin";
4
+ import { useMemo, useState } from "react";
5
+ import { Cross, Plus, Search, Trash } from "./parts";
6
+ const GROUPS = ["today", "yesterday", "week", "month", "older"];
7
+ const DAY = 24 * 60 * 60 * 1000;
8
+ /** Which heading a chat goes under, by when it was last used, from the start of today. */
9
+ export function groupOf(updatedAt, now = new Date()) {
10
+ const today = new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime();
11
+ const at = new Date(updatedAt).getTime();
12
+ if (at >= today)
13
+ return "today";
14
+ if (at >= today - DAY)
15
+ return "yesterday";
16
+ if (at >= today - 7 * DAY)
17
+ return "week";
18
+ if (at >= today - 30 * DAY)
19
+ return "month";
20
+ return "older";
21
+ }
22
+ /** One saved chat. Delete asks again in place, so a stray click loses nothing. */
23
+ function ChatRow({ chat, current, onOpen, onDelete }) {
24
+ const { t } = useT();
25
+ const [confirming, setConfirming] = useState(false);
26
+ return (_jsxs("li", { className: current ? "ai-chat ai-chat-current" : "ai-chat", onMouseLeave: () => setConfirming(false), children: [_jsx("button", { type: "button", className: "ai-chat-open", "aria-current": current ? "page" : undefined, title: chat.title, onClick: onOpen, children: _jsx("span", { className: "ai-chat-name", children: chat.title }) }), confirming
27
+ ? (_jsxs("span", { className: "ai-chat-confirm", children: [_jsx("button", { type: "button", className: "ai-chat-delete", onClick: onDelete, children: t("ext.ai.history.delete") }), _jsx("button", { type: "button", className: "ai-ghost ai-ghost-icon", "aria-label": t("ext.ai.history.cancel"), title: t("ext.ai.history.cancel"), onClick: () => setConfirming(false), children: _jsx(Cross, {}) })] }))
28
+ : _jsx("button", { type: "button", className: "ai-ghost ai-ghost-icon ai-chat-action", "aria-label": t("ext.ai.assistant.deleteChat", { title: chat.title }), title: t("ext.ai.assistant.deleteChat", { title: chat.title }), onClick: () => setConfirming(true), children: _jsx(Trash, {}) })] }));
29
+ }
30
+ /** Saved chats, newest first under day headings, with a search, as a side panel of the assistant. */
31
+ export function History({ chats, loaded, current, onOpen, onDelete, onNew, onClose }) {
32
+ const { t } = useT();
33
+ const [query, setQuery] = useState("");
34
+ const groups = useMemo(() => {
35
+ const words = query.trim().toLowerCase();
36
+ const found = words ? chats.filter((chat) => chat.title.toLowerCase().includes(words)) : chats;
37
+ const now = new Date();
38
+ const by = new Map();
39
+ for (const chat of found) {
40
+ const group = groupOf(chat.updatedAt, now);
41
+ by.set(group, [...(by.get(group) ?? []), chat]);
42
+ }
43
+ return GROUPS.filter((group) => by.has(group)).map((group) => ({ group, chats: by.get(group) }));
44
+ }, [chats, query]);
45
+ return (_jsxs("aside", { className: "ai-side", "aria-label": t("ext.ai.history.title"), children: [_jsxs("div", { className: "ai-side-head", children: [_jsxs("button", { type: "button", className: "ai-side-new", onClick: onNew, children: [_jsx("span", { className: "ai-side-new-mark", children: _jsx(Plus, {}) }), t("ext.ai.assistant.newChat")] }), _jsx("button", { type: "button", className: "ai-ghost ai-ghost-icon ai-side-close", "aria-label": t("ext.ai.history.hide"), title: t("ext.ai.history.hide"), onClick: onClose, children: _jsx(Cross, {}) })] }), chats.length > 0 && (_jsxs("label", { className: "ai-side-search", children: [_jsx(Search, {}), _jsx("input", { type: "search", value: query, placeholder: t("ext.ai.history.search"), "aria-label": t("ext.ai.history.search"), onChange: (event) => setQuery(event.target.value), onKeyDown: (event) => { if (event.key === "Escape")
46
+ setQuery(""); } })] })), _jsxs("nav", { className: "ai-side-list", children: [groups.map(({ group, chats: list }) => (_jsxs("section", { className: "ai-side-group", "aria-label": t(`ext.ai.history.groups.${group}`), children: [_jsx("h2", { className: "ai-side-heading", children: t(`ext.ai.history.groups.${group}`) }), _jsx("ul", { children: list.map((chat) => _jsx(ChatRow, { chat: chat, current: chat.id === current, onOpen: () => onOpen(chat.id), onDelete: () => onDelete(chat.id) }, chat.id)) })] }, group))), loaded && chats.length === 0 && _jsx("p", { className: "ai-side-empty", children: t("ext.ai.history.empty") }), chats.length > 0 && groups.length === 0 && _jsx("p", { className: "ai-side-empty", children: t("ext.ai.history.noMatches") })] })] }));
47
+ }
@@ -0,0 +1,5 @@
1
+ /** Each icon's SVG, and whether it is one colour (currentColor), which then follows the text. */
2
+ export declare const ICONS: Record<string, {
3
+ svg: string;
4
+ mono: boolean;
5
+ }>;