@tansy/ai 0.0.0-stage → 0.1.1

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 (70) hide show
  1. package/CHANGELOG.md +9 -0
  2. package/LICENSE +21 -0
  3. package/README.md +12 -2
  4. package/admin.d.ts +2 -0
  5. package/admin.js +17 -0
  6. package/ai.css +280 -0
  7. package/api.d.ts +91 -0
  8. package/api.js +79 -0
  9. package/assistant.d.ts +3 -0
  10. package/assistant.js +290 -0
  11. package/attach.d.ts +48 -0
  12. package/attach.js +141 -0
  13. package/attachments.d.ts +34 -0
  14. package/attachments.js +66 -0
  15. package/chats.d.ts +35 -0
  16. package/chats.js +78 -0
  17. package/client.d.ts +3 -0
  18. package/client.js +88 -0
  19. package/composer.d.ts +38 -0
  20. package/composer.js +155 -0
  21. package/errors.d.ts +5 -0
  22. package/errors.js +25 -0
  23. package/history.d.ts +15 -0
  24. package/history.js +47 -0
  25. package/icons.generated.d.ts +5 -0
  26. package/icons.generated.js +66 -0
  27. package/images.d.ts +21 -0
  28. package/images.js +23 -0
  29. package/index.d.ts +26 -0
  30. package/index.js +701 -0
  31. package/logic.d.ts +77 -0
  32. package/logic.js +166 -0
  33. package/markdown.d.ts +38 -0
  34. package/markdown.js +142 -0
  35. package/media.d.ts +24 -0
  36. package/media.js +64 -0
  37. package/messages.d.ts +891 -0
  38. package/messages.js +689 -0
  39. package/models.d.ts +7 -0
  40. package/models.js +47 -0
  41. package/package.json +46 -4
  42. package/parts.d.ts +59 -0
  43. package/parts.js +110 -0
  44. package/provider.d.ts +134 -0
  45. package/provider.js +117 -0
  46. package/role.d.ts +24 -0
  47. package/role.js +25 -0
  48. package/workflow/check.d.ts +46 -0
  49. package/workflow/check.js +63 -0
  50. package/workflow/client.d.ts +90 -0
  51. package/workflow/client.js +51 -0
  52. package/workflow/editor.d.ts +13 -0
  53. package/workflow/editor.js +133 -0
  54. package/workflow/engine.d.ts +232 -0
  55. package/workflow/engine.js +779 -0
  56. package/workflow/icons.d.ts +26 -0
  57. package/workflow/icons.js +67 -0
  58. package/workflow/model-picker.d.ts +22 -0
  59. package/workflow/model-picker.js +69 -0
  60. package/workflow/page.d.ts +3 -0
  61. package/workflow/page.js +118 -0
  62. package/workflow/routes.d.ts +12 -0
  63. package/workflow/routes.js +418 -0
  64. package/workflow/run.d.ts +8 -0
  65. package/workflow/run.js +162 -0
  66. package/workflow/schema.d.ts +183 -0
  67. package/workflow/schema.js +143 -0
  68. package/workflow/templates.d.ts +9 -0
  69. package/workflow/templates.js +81 -0
  70. package/workflow/workflow.css +241 -0
package/models.d.ts ADDED
@@ -0,0 +1,7 @@
1
+ import { type AiProvider, type AiSettings, type ModelCapabilities, type ModelChoice } from "./provider";
2
+ import type { Catalog } from "./workflow/check";
3
+ export declare function listModels(provider: AiProvider, settings: AiSettings): Promise<ModelChoice[]>;
4
+ /** What a model can do: as its provider lists it, or as its id suggests when it isn't listed. */
5
+ export declare function capabilitiesOf(provider: AiProvider, settings: AiSettings, modelId: string): Promise<ModelCapabilities>;
6
+ /** Every provider's models with what each can do, or why they couldn't be listed. Never a key. */
7
+ export declare function catalogOf(providers: AiProvider[], settings: AiSettings): Promise<Catalog>;
package/models.js ADDED
@@ -0,0 +1,47 @@
1
+ import { createHash } from "node:crypto";
2
+ import { guessCapabilities } from "./provider";
3
+ /** A provider's models, listed at most every few minutes for the menus that offer them. */
4
+ const MODELS_FOR = 10 * 60 * 1000;
5
+ const modelLists = new Map();
6
+ export function listModels(provider, settings) {
7
+ // Keyed by the settings too, so a new key or server lists again. Only a hash is kept.
8
+ const key = `${provider.id}:${createHash("sha256").update(JSON.stringify(settings)).digest("hex")}`;
9
+ const cached = modelLists.get(key);
10
+ if (cached && Date.now() - cached.at < MODELS_FOR)
11
+ return cached.options;
12
+ const options = provider.models(settings).then((list) => list.slice(0, 2000));
13
+ options.catch(() => modelLists.delete(key));
14
+ if (modelLists.size > 50)
15
+ modelLists.clear();
16
+ modelLists.set(key, { at: Date.now(), options });
17
+ return options;
18
+ }
19
+ /** What a model can do: as its provider lists it, or as its id suggests when it isn't listed. */
20
+ export async function capabilitiesOf(provider, settings, modelId) {
21
+ if (provider.models) {
22
+ try {
23
+ const found = (await listModels(provider, settings)).find((model) => model.value === modelId);
24
+ if (found?.capabilities)
25
+ return found.capabilities;
26
+ }
27
+ catch {
28
+ // The list is only a better guess; the id still says something.
29
+ }
30
+ }
31
+ return guessCapabilities(modelId);
32
+ }
33
+ /** Every provider's models with what each can do, or why they couldn't be listed. Never a key. */
34
+ export async function catalogOf(providers, settings) {
35
+ const entries = await Promise.all(providers.map(async (provider) => {
36
+ const entry = { id: provider.id, label: provider.label, icon: provider.icon, ready: provider.ready(settings), images: Boolean(provider.imageModel), defaultModel: provider.defaultModel };
37
+ if (!entry.ready || !provider.models)
38
+ return { ...entry, models: null };
39
+ try {
40
+ return { ...entry, models: await listModels(provider, settings) };
41
+ }
42
+ catch (error) {
43
+ return { ...entry, models: null, error: error instanceof Error ? error.message : "The models couldn't be listed." };
44
+ }
45
+ }));
46
+ return { providers: entries };
47
+ }
package/package.json CHANGED
@@ -1,6 +1,48 @@
1
1
  {
2
2
  "name": "@tansy/ai",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "An AI assistant for tansy on the Vercel AI SDK: chat that can create and edit content, filling forms, and writing fields, with any model provider. Add a provider package, such as @tansy/ai-openai.",
5
+ "keywords": [
6
+ "tansy",
7
+ "tansy-plugin",
8
+ "cms",
9
+ "nextjs"
10
+ ],
11
+ "license": "MIT",
12
+ "author": "Mohamed Salah <mohamedsalahsebai@gmail.com>",
13
+ "homepage": "https://github.com/mhmdsalahsebai/tansy",
14
+ "repository": {
15
+ "type": "git",
16
+ "url": "git+https://github.com/mhmdsalahsebai/tansy.git",
17
+ "directory": "plugins/ai"
18
+ },
19
+ "bugs": "https://github.com/mhmdsalahsebai/tansy/issues",
20
+ "exports": {
21
+ ".": {
22
+ "types": "./index.d.ts",
23
+ "default": "./index.js"
24
+ },
25
+ "./admin": {
26
+ "types": "./admin.d.ts",
27
+ "default": "./admin.js"
28
+ },
29
+ "./client": {
30
+ "types": "./client.d.ts",
31
+ "default": "./client.js"
32
+ },
33
+ "./provider": {
34
+ "types": "./provider.d.ts",
35
+ "default": "./provider.js"
36
+ }
37
+ },
38
+ "peerDependencies": {
39
+ "next": "^16.4.6",
40
+ "react": "^19.3.0",
41
+ "tansy": "^0.1.1"
42
+ },
43
+ "dependencies": {
44
+ "@ai-sdk/react": "^4.0.176",
45
+ "ai": "^7.0.172",
46
+ "zod": "^4.6.7"
47
+ }
48
+ }
package/parts.d.ts ADDED
@@ -0,0 +1,59 @@
1
+ import type { UIMessage } from "ai";
2
+ import { useT } from "tansy/admin";
3
+ import { type ReactNode, type RefObject } from "react";
4
+ export type Part = UIMessage["parts"][number];
5
+ export type ToolPart = Extract<Part, {
6
+ type: "dynamic-tool";
7
+ }>;
8
+ export type ReasoningPart = Extract<Part, {
9
+ type: "reasoning";
10
+ }>;
11
+ export type T = ReturnType<typeof useT>["t"];
12
+ export declare const Icon: ({ children, className }: {
13
+ children: ReactNode;
14
+ className?: string;
15
+ }) => import("react").JSX.Element;
16
+ export declare const Spark: ({ className }: {
17
+ className?: string;
18
+ }) => import("react").JSX.Element;
19
+ export declare const ArrowUp: () => import("react").JSX.Element;
20
+ export declare const ArrowDown: () => import("react").JSX.Element;
21
+ export declare const StopSquare: () => import("react").JSX.Element;
22
+ export declare const Plus: () => import("react").JSX.Element;
23
+ export declare const Copy: () => import("react").JSX.Element;
24
+ export declare const Check: () => import("react").JSX.Element;
25
+ export declare const Cross: () => import("react").JSX.Element;
26
+ export declare const Retry: () => import("react").JSX.Element;
27
+ export declare const Chevron: ({ open }: {
28
+ open: boolean;
29
+ }) => import("react").JSX.Element;
30
+ export declare const ChevronDown: () => import("react").JSX.Element;
31
+ export declare const Pause: () => import("react").JSX.Element;
32
+ export declare const Trash: () => import("react").JSX.Element;
33
+ export declare const Search: () => import("react").JSX.Element;
34
+ export declare const Panel: () => import("react").JSX.Element;
35
+ export declare const Brain: () => import("react").JSX.Element;
36
+ export declare const Shield: () => import("react").JSX.Element;
37
+ export declare const Cube: () => import("react").JSX.Element;
38
+ /** Closes a menu on Escape or a click outside it. */
39
+ export declare function useDismiss(ref: RefObject<HTMLElement | null>, open: boolean, close: () => void): void;
40
+ /** A button that copies text, and says so for a moment. */
41
+ export declare function CopyButton({ text, label }: {
42
+ text: string;
43
+ label?: boolean;
44
+ }): import("react").JSX.Element;
45
+ export declare const renderCode: (code: string, language: string, key: string) => import("react").JSX.Element;
46
+ /** What the model thought before answering: one quiet line, open while it thinks, folded once it's done. */
47
+ export declare function Thinking({ part }: {
48
+ part: ReasoningPart;
49
+ }): import("react").JSX.Element | null;
50
+ export declare function ToolCard({ part, respond }: {
51
+ part: ToolPart;
52
+ respond: (id: string, approved: boolean) => void;
53
+ }): import("react").JSX.Element;
54
+ export declare const textOf: (message: UIMessage) => string;
55
+ /** One answer's parts, in the order they came. */
56
+ export declare function AnswerParts({ message, respond }: {
57
+ message: UIMessage;
58
+ respond: (id: string, approved: boolean) => void;
59
+ }): import("react").JSX.Element;
package/parts.js ADDED
@@ -0,0 +1,110 @@
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 { useEffect, useRef, useState } from "react";
5
+ import { Markdown } from "./markdown";
6
+ import { PictureCard } from "./attach";
7
+ /* Icons, drawn on a 16 by 16 box with the current text colour. */
8
+ export const Icon = ({ children, className }) => (_jsx("svg", { className: `ai-icon ${className ?? ""}`, viewBox: "0 0 16 16", fill: "none", stroke: "currentColor", strokeWidth: "1.5", strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": "true", children: children }));
9
+ export const Spark = ({ className }) => (_jsx("svg", { className: `ai-icon ${className ?? ""}`, viewBox: "0 0 16 16", fill: "currentColor", "aria-hidden": "true", children: _jsx("path", { d: "M8 1.25a.75.75 0 0 1 .72.54l.9 3.06a2.25 2.25 0 0 0 1.53 1.53l3.06.9a.75.75 0 0 1 0 1.44l-3.06.9a2.25 2.25 0 0 0-1.53 1.53l-.9 3.06a.75.75 0 0 1-1.44 0l-.9-3.06a2.25 2.25 0 0 0-1.53-1.53l-3.06-.9a.75.75 0 0 1 0-1.44l3.06-.9a2.25 2.25 0 0 0 1.53-1.53l.9-3.06A.75.75 0 0 1 8 1.25Z" }) }));
10
+ export const ArrowUp = () => _jsx(Icon, { children: _jsx("path", { d: "M8 13V3M3.5 7.5 8 3l4.5 4.5" }) });
11
+ export const ArrowDown = () => _jsx(Icon, { children: _jsx("path", { d: "M8 3v10M3.5 8.5 8 13l4.5-4.5" }) });
12
+ export const StopSquare = () => _jsx("svg", { className: "ai-icon", viewBox: "0 0 16 16", fill: "currentColor", "aria-hidden": "true", children: _jsx("rect", { x: "4", y: "4", width: "8", height: "8", rx: "1.5" }) });
13
+ export const Plus = () => _jsx(Icon, { children: _jsx("path", { d: "M8 3v10M3 8h10" }) });
14
+ export const Copy = () => _jsxs(Icon, { children: [_jsx("rect", { x: "5.5", y: "5.5", width: "8", height: "8", rx: "1.5" }), _jsx("path", { d: "M10.5 5.5V4A1.5 1.5 0 0 0 9 2.5H4A1.5 1.5 0 0 0 2.5 4v5A1.5 1.5 0 0 0 4 10.5h1.5" })] });
15
+ export const Check = () => _jsx(Icon, { children: _jsx("path", { d: "m3.5 8.5 3 3 6-7" }) });
16
+ export const Cross = () => _jsx(Icon, { children: _jsx("path", { d: "m4.5 4.5 7 7M11.5 4.5l-7 7" }) });
17
+ export const Retry = () => _jsx(Icon, { children: _jsx("path", { d: "M2.75 8a5.25 5.25 0 1 0 1.6-3.77M2.75 2.75v2.5h2.5" }) });
18
+ export const Chevron = ({ open }) => _jsx(Icon, { className: open ? "ai-chevron ai-chevron-open" : "ai-chevron", children: _jsx("path", { d: "m6 4 4 4-4 4" }) });
19
+ export const ChevronDown = () => _jsx(Icon, { className: "ai-caret", children: _jsx("path", { d: "m4.5 6.5 3.5 3.5 3.5-3.5" }) });
20
+ export const Pause = () => _jsx(Icon, { children: _jsx("path", { d: "M6 4.5v7M10 4.5v7" }) });
21
+ export const Trash = () => _jsx(Icon, { children: _jsx("path", { d: "M3 4.5h10M6.5 4.5V3h3v1.5M4.5 4.5l.6 8.1a1 1 0 0 0 1 .9h3.8a1 1 0 0 0 1-.9l.6-8.1" }) });
22
+ export const Search = () => _jsxs(Icon, { children: [_jsx("circle", { cx: "7", cy: "7", r: "4.25" }), _jsx("path", { d: "m10.25 10.25 3.25 3.25" })] });
23
+ export const Panel = () => _jsxs(Icon, { children: [_jsx("rect", { x: "2", y: "2.75", width: "12", height: "10.5", rx: "2" }), _jsx("path", { d: "M6 2.75v10.5" })] });
24
+ export const Brain = () => _jsx(Icon, { children: _jsx("path", { d: "M6 13.25V2.75M6 2.75a2.25 2.25 0 0 0-2.25 2.25 2 2 0 0 0-1.25 3 2.25 2.25 0 0 0 1.5 3.5A2 2 0 0 0 6 13.25M10 13.25V2.75M10 2.75A2.25 2.25 0 0 1 12.25 5a2 2 0 0 1 1.25 3 2.25 2.25 0 0 1-1.5 3.5A2 2 0 0 1 10 13.25" }) });
25
+ export const Shield = () => _jsx(Icon, { children: _jsx("path", { d: "M8 1.75 13 3.75v4c0 3-2.1 5.4-5 6.5-2.9-1.1-5-3.5-5-6.5v-4L8 1.75Z" }) });
26
+ export const Cube = () => _jsx(Icon, { children: _jsx("path", { d: "M8 1.75 13.5 4.75v6.5L8 14.25l-5.5-3v-6.5L8 1.75ZM2.5 4.75 8 7.75l5.5-3M8 7.75v6.5" }) });
27
+ /** Closes a menu on Escape or a click outside it. */
28
+ export function useDismiss(ref, open, close) {
29
+ useEffect(() => {
30
+ if (!open)
31
+ return;
32
+ const onPointer = (event) => { if (!ref.current?.contains(event.target))
33
+ close(); };
34
+ const onKey = (event) => { if (event.key === "Escape") {
35
+ event.stopPropagation();
36
+ close();
37
+ } };
38
+ document.addEventListener("pointerdown", onPointer);
39
+ document.addEventListener("keydown", onKey);
40
+ return () => { document.removeEventListener("pointerdown", onPointer); document.removeEventListener("keydown", onKey); };
41
+ }, [ref, open, close]);
42
+ }
43
+ /** A button that copies text, and says so for a moment. */
44
+ export function CopyButton({ text, label }) {
45
+ const { t } = useT();
46
+ const [copied, setCopied] = useState(false);
47
+ useEffect(() => {
48
+ if (!copied)
49
+ return;
50
+ const timer = setTimeout(() => setCopied(false), 1500);
51
+ return () => clearTimeout(timer);
52
+ }, [copied]);
53
+ const name = copied ? t("ext.ai.assistant.copied") : t("ext.ai.assistant.copy");
54
+ return (_jsxs("button", { type: "button", className: "ai-ghost", "aria-label": name, title: name, onClick: () => void navigator.clipboard?.writeText(text).then(() => setCopied(true), () => undefined), children: [copied ? _jsx(Check, {}) : _jsx(Copy, {}), label && _jsx("span", { children: name })] }));
55
+ }
56
+ function CodeBlock({ code, language }) {
57
+ return (_jsxs("div", { className: "ai-code", children: [_jsxs("div", { className: "ai-code-head", children: [_jsx("span", { children: language }), _jsx(CopyButton, { text: code, label: true })] }), _jsx("pre", { children: _jsx("code", { children: code }) })] }));
58
+ }
59
+ export const renderCode = (code, language, key) => _jsx(CodeBlock, { code: code, language: language }, key);
60
+ /** What the model thought before answering: one quiet line, open while it thinks, folded once it's done. */
61
+ export function Thinking({ part }) {
62
+ const { t } = useT();
63
+ const active = part.state === "streaming";
64
+ const [open, setOpen] = useState(null);
65
+ const body = useRef(null);
66
+ const shown = open ?? active;
67
+ // While it streams, keep its latest lines in view inside the folded box.
68
+ useEffect(() => { if (active && body.current)
69
+ body.current.scrollTop = body.current.scrollHeight; }, [active, part.text]);
70
+ if (!part.text.trim() && !active)
71
+ return null;
72
+ return (_jsxs("div", { className: `ai-thinking${active ? " ai-thinking-active" : ""}`, children: [_jsxs("button", { type: "button", className: "ai-thinking-head", "aria-expanded": shown, onClick: () => setOpen(!shown), children: [_jsx(Brain, {}), _jsx("span", { children: active ? t("ext.ai.assistant.thinking") : t("ext.ai.assistant.thought") }), _jsx(Chevron, { open: shown })] }), shown && _jsx("div", { ref: body, className: "ai-thinking-body", children: part.text })] }));
73
+ }
74
+ const VERBS = new Set(["generate_image", "create_record", "update_record", "delete_record", "list_records", "get_record", "list_collections", "describe_collection"]);
75
+ /** "lms_create_course" as "Lms create course", for tools without a verb in the messages. */
76
+ const titleOf = (t, name) => (VERBS.has(name) ? t(`ext.ai.tool.verbs.${name}`) : `${name.charAt(0).toUpperCase()}${name.slice(1).replaceAll("_", " ")}`);
77
+ function summaryOf(t, input) {
78
+ if (!input || typeof input !== "object")
79
+ return "";
80
+ const value = input;
81
+ const data = (value.data && typeof value.data === "object" ? value.data : value);
82
+ const name = [data.title, data.name].find((item) => typeof item === "string" && item);
83
+ return [typeof value.collection === "string" ? t("ext.ai.tool.in", { collection: value.collection }) : "", typeof value.id === "number" ? `#${value.id}` : "", name ? `“${String(name)}”` : ""].filter(Boolean).join(" ");
84
+ }
85
+ export function ToolCard({ part, respond }) {
86
+ const { t } = useT();
87
+ const [open, setOpen] = useState(false);
88
+ const failed = part.state === "output-error" || (part.state === "output-available" && Boolean(part.output?.error));
89
+ const asking = part.state === "approval-requested";
90
+ const state = asking ? "ask" : part.state === "output-denied" ? "denied" : failed ? "failed" : part.state === "output-available" ? "done" : "working";
91
+ const status = t(`ext.ai.tool.${asking ? "waiting" : state === "denied" ? "notDone" : state}`);
92
+ const error = part.state === "output-error" ? part.errorText : failed ? String(part.output.error?.message ?? "") : "";
93
+ const hasDetails = part.input !== undefined;
94
+ return (_jsxs("div", { className: `ai-tool ai-tool-${state}`, children: [_jsxs("button", { type: "button", className: "ai-tool-head", "aria-expanded": open, disabled: !hasDetails, onClick: () => setOpen(!open), children: [_jsx("span", { className: "ai-tool-mark", children: state === "working" ? _jsx("span", { className: "ai-spinner" }) : state === "done" ? _jsx(Check, {}) : state === "failed" || state === "denied" ? _jsx(Cross, {}) : _jsx(Pause, {}) }), _jsxs("span", { className: "ai-tool-title", children: [titleOf(t, part.toolName), " ", _jsx("span", { className: "ai-tool-summary", children: summaryOf(t, part.input) })] }), _jsx("span", { className: "ai-tool-status", children: status }), hasDetails && _jsx(Chevron, { open: open })] }), error && _jsx("p", { className: "ai-tool-error", children: error }), open && _jsx("pre", { className: "ai-tool-detail", children: JSON.stringify({ input: part.input, ...(part.state === "output-available" ? { result: part.output } : {}) }, null, 2) }), asking && !part.approval.isAutomatic && (_jsxs("div", { className: "ai-tool-actions", children: [_jsxs("button", { type: "button", className: "ai-btn ai-btn-primary", onClick: () => respond(part.approval.id, true), children: [_jsx(Check, {}), t("ext.ai.tool.approve")] }), _jsx("button", { type: "button", className: "ai-btn", onClick: () => respond(part.approval.id, false), children: t("ext.ai.tool.deny") })] }))] }));
95
+ }
96
+ export const textOf = (message) => message.parts.map((part) => (part.type === "text" ? part.text : "")).filter(Boolean).join("\n\n");
97
+ /** One answer's parts, in the order they came. */
98
+ export function AnswerParts({ message, respond }) {
99
+ return (_jsx(_Fragment, { children: message.parts.map((part, at) => {
100
+ if (part.type === "text")
101
+ return part.text ? _jsx("div", { className: "ai-prose", children: _jsx(Markdown, { text: part.text, renderCode: renderCode }) }, at) : null;
102
+ if (part.type === "reasoning")
103
+ return _jsx(Thinking, { part: part }, at);
104
+ if (part.type === "dynamic-tool" && part.toolName === "generate_image" && part.state !== "approval-requested" && part.state !== "output-denied")
105
+ return _jsx(PictureCard, { part: part }, part.toolCallId);
106
+ if (part.type === "dynamic-tool")
107
+ return _jsx(ToolCard, { part: part, respond: respond }, part.toolCallId);
108
+ return null;
109
+ }) }));
110
+ }
package/provider.d.ts ADDED
@@ -0,0 +1,134 @@
1
+ import type { ImageModel, LanguageModel } from "ai";
2
+ import type { Messages, PluginSettingField } from "tansy/plugin";
3
+ /**
4
+ * What a model provider adapter implements, such as @tansy/ai-openai. The AI plugin
5
+ * keeps everything providers share: the tools, the prompts, the routes and the dashboard.
6
+ * An adapter only turns its settings into an AI SDK model. See docs/plugins/ai.md.
7
+ */
8
+ /** The AI plugin's own settings, and each installed provider's, by name. */
9
+ export interface AiSettings {
10
+ /** The id of the provider in use. */
11
+ provider: string;
12
+ /** The model for the assistant. Empty uses the provider's default. */
13
+ model: string;
14
+ /** A cheaper, quicker model for writing one field. Empty uses `model`. */
15
+ fastModel: string;
16
+ /** Whether people choose the model and thinking in the chat. */
17
+ chooseModel: boolean;
18
+ /** How long the assistant thinks by default: "provider-default", "none", "low", "medium" or "high". */
19
+ reasoning: string;
20
+ /** The role the AI acts with, by name. Empty uses ai-assistant. */
21
+ role?: string;
22
+ /** Whether people choose that role in the chat. */
23
+ chooseRole?: boolean;
24
+ /** The provider that draws pictures in the chat. "same" uses `provider`. */
25
+ imageProvider?: string;
26
+ /** The model that draws pictures in the chat. Empty means the chat doesn't draw. */
27
+ imageModel?: string;
28
+ /** The site's own guidance, added to every prompt: tone, audience, house style. */
29
+ instructions: string;
30
+ maxSteps: number;
31
+ maxOutputTokens: number;
32
+ [name: string]: unknown;
33
+ }
34
+ export interface AiProvider {
35
+ /** Lowercase letters and digits, such as "openai". Every setting's name starts with it. */
36
+ id: string;
37
+ label: string;
38
+ /** The model used when the settings name none. */
39
+ defaultModel: string;
40
+ /** Its keys and options under AI → Settings. */
41
+ settings(): PluginSettingField[];
42
+ /**
43
+ * Its settings' words in other interface languages, by language code, as
44
+ * `{ ar: { settings: { <name>: { label, description } } } }`. AI adds them to its own
45
+ * `messages`, and the setting's `label` and `description` cover any language missing.
46
+ */
47
+ messages?: Record<string, Messages>;
48
+ /** Whether what it needs is set. */
49
+ ready(settings: AiSettings): boolean;
50
+ /** The AI SDK model for an id, such as "gpt-6-astra". */
51
+ model(settings: AiSettings, modelId: string): LanguageModel;
52
+ /**
53
+ * The AI SDK image model for an id, such as "gpt-image-2", for workflows that draw
54
+ * pictures. Undefined for an id that isn't one: a language model that answers with images,
55
+ * such as Gemini's, is then asked through `model`.
56
+ */
57
+ imageModel?(settings: AiSettings, modelId: string): ImageModel | undefined;
58
+ /**
59
+ * The provider's icon from @lobehub/icons, such as "openai" or "claude". The dashboard
60
+ * knows the icons of the providers Tansy ships, so only another adapter needs it.
61
+ */
62
+ icon?: string;
63
+ /**
64
+ * The models its key can use, for the model settings to offer. Throws a ModelListError
65
+ * with a message for the person when they can't be listed. Without it, people type the id.
66
+ */
67
+ models?(settings: AiSettings): Promise<ModelChoice[]>;
68
+ }
69
+ /** What a model reads or writes. */
70
+ export type Modality = "text" | "image" | "audio" | "video" | "file";
71
+ /**
72
+ * What a model can do, as its provider's API says, or as its id suggests when the API says
73
+ * nothing. A missing field is unknown, which workflows allow with a warning.
74
+ */
75
+ export interface ModelCapabilities {
76
+ input?: Modality[];
77
+ output?: Modality[];
78
+ /** Calls tools, which the assistant needs. */
79
+ tools?: boolean;
80
+ /** Thinks before it answers. */
81
+ reasoning?: boolean;
82
+ /** Answers in a JSON shape it's given, which workflows need to write records. */
83
+ structured?: boolean;
84
+ /** Read from the provider's API, rather than guessed from the id. */
85
+ reported?: boolean;
86
+ }
87
+ export interface ModelChoice {
88
+ value: string;
89
+ label?: string;
90
+ capabilities?: ModelCapabilities;
91
+ }
92
+ /** Why a provider's models couldn't be listed, in words for the person choosing one. */
93
+ export declare class ModelListError extends Error {
94
+ }
95
+ /**
96
+ * The models an OpenAI-style API lists at `<baseUrl>/models`, as OpenAI, OpenRouter, Groq,
97
+ * Mistral, xAI, DeepSeek, Ollama, LM Studio and vLLM do. `label` names a model from what
98
+ * the API says about it, such as OpenRouter's name and price.
99
+ */
100
+ export declare function openAiModels(baseUrl: string, apiKey: string | undefined, options?: {
101
+ label?: (model: Record<string, unknown>) => string | undefined;
102
+ capabilities?: (model: Record<string, unknown>) => ModelCapabilities | undefined;
103
+ fetcher?: typeof fetch;
104
+ }): Promise<ModelChoice[]>;
105
+ /** Fetches a provider's JSON with a timeout, throwing a ModelListError in words for the person. */
106
+ export declare function fetchModelsJson(url: string, init?: RequestInit, fetcher?: typeof fetch): Promise<Record<string, unknown>>;
107
+ /**
108
+ * What a model can do, from its id alone, for providers whose API lists only ids. Families
109
+ * that draw pictures, read images or think are known by name; anything else is a text model
110
+ * whose tools and structured answers are unknown.
111
+ */
112
+ export declare function guessCapabilities(id: string): ModelCapabilities;
113
+ /** Models the assistant can chat with: those that answer in text and, as far as is known, call tools. */
114
+ export declare const chatModels: (models: ModelChoice[]) => ModelChoice[];
115
+ /** Models that draw: image models, and language models that answer with pictures. */
116
+ export declare const imageModels: (models: ModelChoice[]) => ModelChoice[];
117
+ /** Modalities as an API writes them, such as OpenRouter's ["text", "image"]. */
118
+ export declare const modalities: (value: unknown) => Modality[] | undefined;
119
+ /**
120
+ * An image model for an OpenAI-style chat API that answers with pictures when asked for the
121
+ * "image" modality, as OpenRouter does for Gemini, GPT and FLUX image models. The pictures
122
+ * come back as data URLs on the message.
123
+ */
124
+ export declare function chatImageModel(options: {
125
+ provider: string;
126
+ baseUrl: string;
127
+ apiKey: string;
128
+ modelId: string;
129
+ headers?: Record<string, string>;
130
+ fetcher?: typeof fetch;
131
+ }): ImageModel;
132
+ /** Types an adapter. */
133
+ export declare const defineAiProvider: (provider: AiProvider) => AiProvider;
134
+ export declare const str: (value: unknown) => string;
package/provider.js ADDED
@@ -0,0 +1,117 @@
1
+ /** Why a provider's models couldn't be listed, in words for the person choosing one. */
2
+ export class ModelListError extends Error {
3
+ }
4
+ /**
5
+ * The models an OpenAI-style API lists at `<baseUrl>/models`, as OpenAI, OpenRouter, Groq,
6
+ * Mistral, xAI, DeepSeek, Ollama, LM Studio and vLLM do. `label` names a model from what
7
+ * the API says about it, such as OpenRouter's name and price.
8
+ */
9
+ export async function openAiModels(baseUrl, apiKey, options = {}) {
10
+ const fetcher = options.fetcher ?? fetch;
11
+ let response;
12
+ try {
13
+ response = await fetcher(`${baseUrl.replace(/\/+$/, "")}/models`, { headers: apiKey ? { authorization: `Bearer ${apiKey}` } : {}, signal: AbortSignal.timeout(15_000) });
14
+ }
15
+ catch {
16
+ throw new ModelListError("The provider couldn't be reached.");
17
+ }
18
+ if (response.status === 401 || response.status === 403)
19
+ throw new ModelListError("The provider refused the key. Check it, and save it first.");
20
+ if (!response.ok)
21
+ throw new ModelListError(`The provider answered ${response.status}.`);
22
+ const json = (await response.json().catch(() => null));
23
+ if (!Array.isArray(json?.data))
24
+ throw new ModelListError("The provider's answer wasn't a list of models.");
25
+ return json.data
26
+ .filter((model) => Boolean(model) && typeof model.id === "string")
27
+ .map((model) => ({ value: model.id, label: options.label?.(model), capabilities: options.capabilities ? options.capabilities(model) : guessCapabilities(model.id) }))
28
+ .filter((model) => !isUnusable(model.capabilities))
29
+ .sort((a, b) => a.value.localeCompare(b.value));
30
+ }
31
+ /** Fetches a provider's JSON with a timeout, throwing a ModelListError in words for the person. */
32
+ export async function fetchModelsJson(url, init = {}, fetcher = fetch) {
33
+ let response;
34
+ try {
35
+ response = await fetcher(url, { ...init, signal: AbortSignal.timeout(15_000) });
36
+ }
37
+ catch {
38
+ throw new ModelListError("The provider couldn't be reached.");
39
+ }
40
+ if (response.status === 400 || response.status === 401 || response.status === 403)
41
+ throw new ModelListError("The provider refused the key. Check it, and save it first.");
42
+ if (!response.ok)
43
+ throw new ModelListError(`The provider answered ${response.status}.`);
44
+ const json = (await response.json().catch(() => null));
45
+ if (!json || typeof json !== "object")
46
+ throw new ModelListError("The provider's answer wasn't a list of models.");
47
+ return json;
48
+ }
49
+ /**
50
+ * What a model can do, from its id alone, for providers whose API lists only ids. Families
51
+ * that draw pictures, read images or think are known by name; anything else is a text model
52
+ * whose tools and structured answers are unknown.
53
+ */
54
+ export function guessCapabilities(id) {
55
+ const name = id.toLowerCase().split("/").pop() ?? "";
56
+ if (/(^|[-_])(whisper|tts|transcribe|embed|embedding|moderation|rerank|guard|realtime|audio|search-preview|computer-use)([-_.:]|$)/.test(name) || /^(text-embedding|omni-moderation|babbage|davinci|distil-whisper)/.test(name))
57
+ return { input: ["audio"], output: ["audio"] };
58
+ if (/^(gpt-image|dall-e|imagen|flux|stable-diffusion|sd3|sdxl|ideogram|recraft|seedream|grok-\d+(\.\d+)?-image|grok-2-image|grok-imagine-image)/.test(name) || /(^|-)image-(gen|generation)/.test(name))
59
+ return { input: ["text"], output: ["image"] };
60
+ const imageOut = /gemini-[\w.-]*image|nano-banana/.test(name);
61
+ const vision = /^(gpt-4o|gpt-4\.1|gpt-[5-9]|o[1-9]|claude|gemini|gemma-3|grok-[2-9]|pixtral|mistral-(medium|large|small)-(2|3|latest)|llama-4|qwen[\w.-]*vl|llava|kimi)/.test(name) || /vision|-vl\b/.test(name);
62
+ const reasoning = /^(o[1-9]|gpt-[5-9]|claude-(opus|sonnet)-[4-9]|claude-[3-9]-7|gemini-(2\.5|[3-9])|grok-[3-9]|deepseek-r|qwq|magistral|kimi-k2-thinking)/.test(name) || /reason|think/.test(name);
63
+ return {
64
+ input: vision ? ["text", "image"] : ["text"],
65
+ output: imageOut ? ["text", "image"] : ["text"],
66
+ ...(reasoning ? { reasoning: true } : {}),
67
+ ...(/^(gpt-[4-9]|o[1-9]|claude|gemini|grok|mistral|magistral|codestral|deepseek|llama-3\.[1-9]|llama-4|qwen|kimi)/.test(name) ? { tools: true, structured: true } : {}),
68
+ };
69
+ }
70
+ /** Speech, embeddings and moderation: models nothing in the CMS can use. */
71
+ const isUnusable = (capabilities) => Boolean(capabilities?.output?.length) && !capabilities.output.includes("text") && !capabilities.output.includes("image");
72
+ /** Models the assistant can chat with: those that answer in text and, as far as is known, call tools. */
73
+ export const chatModels = (models) => models.filter((model) => {
74
+ const output = model.capabilities?.output;
75
+ return (!output || output.includes("text")) && model.capabilities?.tools !== false;
76
+ });
77
+ /** Models that draw: image models, and language models that answer with pictures. */
78
+ export const imageModels = (models) => models.filter((model) => model.capabilities?.output?.includes("image"));
79
+ /** Modalities as an API writes them, such as OpenRouter's ["text", "image"]. */
80
+ export const modalities = (value) => {
81
+ if (!Array.isArray(value))
82
+ return undefined;
83
+ const known = new Set(["text", "image", "audio", "video", "file"]);
84
+ return value.filter((item) => typeof item === "string" && known.has(item));
85
+ };
86
+ /**
87
+ * An image model for an OpenAI-style chat API that answers with pictures when asked for the
88
+ * "image" modality, as OpenRouter does for Gemini, GPT and FLUX image models. The pictures
89
+ * come back as data URLs on the message.
90
+ */
91
+ export function chatImageModel(options) {
92
+ const fetcher = options.fetcher ?? fetch;
93
+ return {
94
+ specificationVersion: "v4",
95
+ provider: options.provider,
96
+ modelId: options.modelId,
97
+ maxImagesPerCall: 1,
98
+ async doGenerate({ prompt, aspectRatio, abortSignal }) {
99
+ const response = await fetcher(`${options.baseUrl.replace(/\/+$/, "")}/chat/completions`, {
100
+ method: "POST",
101
+ headers: { "content-type": "application/json", authorization: `Bearer ${options.apiKey}`, ...options.headers },
102
+ body: JSON.stringify({ model: options.modelId, modalities: ["image", "text"], messages: [{ role: "user", content: prompt ?? "" }], ...(aspectRatio ? { image_config: { aspect_ratio: aspectRatio } } : {}) }),
103
+ signal: abortSignal,
104
+ });
105
+ if (!response.ok)
106
+ throw Object.assign(new Error(`The provider answered ${response.status}.`), { statusCode: response.status, isRetryable: response.status === 429 || response.status >= 500 });
107
+ const json = (await response.json());
108
+ const images = (json.choices?.[0]?.message?.images ?? []).map((image) => image.image_url?.url ?? "").filter((url) => url.startsWith("data:")).map((url) => url.slice(url.indexOf(",") + 1));
109
+ if (!images.length)
110
+ throw new Error("The model answered without a picture.");
111
+ return { images, warnings: [], response: { timestamp: new Date(), modelId: options.modelId, headers: undefined } };
112
+ },
113
+ };
114
+ }
115
+ /** Types an adapter. */
116
+ export const defineAiProvider = (provider) => provider;
117
+ export const str = (value) => (typeof value === "string" ? value.trim() : "");
package/role.d.ts ADDED
@@ -0,0 +1,24 @@
1
+ import type { PluginRole } from "tansy/plugin";
2
+ import type { AiSettings } from "./provider";
3
+ /** The role the AI acts with until an owner chooses another. */
4
+ export declare const ASSISTANT_ROLE = "ai-assistant";
5
+ /** A role's name, as the CMS stores them. */
6
+ export declare const ROLE_NAME: RegExp;
7
+ /**
8
+ * Created once, and then the owner's to change under Dashboard → Roles like any other. It
9
+ * reads and drafts content, and nothing else: no deleting, no schemas, users, settings,
10
+ * roles or keys. The AI never gets more than the person using it either, and every change
11
+ * still waits for that person to approve it.
12
+ */
13
+ export declare const assistantRole: PluginRole;
14
+ /**
15
+ * Who may give the AI a role other than the site's: whoever may give people roles, admins by
16
+ * default. Anyone else's assistant acts with the role chosen under AI → Settings.
17
+ */
18
+ export declare const GIVE_ROLE = "user:set-role";
19
+ /** Whether this caller may choose the AI's role. */
20
+ export declare const givesRoles: (principal: {
21
+ permissions: ReadonlySet<string>;
22
+ }) => boolean;
23
+ /** The role the AI acts with: the one chosen in the chat while people may choose, else the settings', else its own. */
24
+ export declare const roleFor: (settings: Pick<AiSettings, "role" | "chooseRole">, picked?: string | null) => string;
package/role.js ADDED
@@ -0,0 +1,25 @@
1
+ /** The role the AI acts with until an owner chooses another. */
2
+ export const ASSISTANT_ROLE = "ai-assistant";
3
+ /** A role's name, as the CMS stores them. */
4
+ export const ROLE_NAME = /^[a-z][a-z0-9_-]{1,39}$/;
5
+ /**
6
+ * Created once, and then the owner's to change under Dashboard → Roles like any other. It
7
+ * reads and drafts content, and nothing else: no deleting, no schemas, users, settings,
8
+ * roles or keys. The AI never gets more than the person using it either, and every change
9
+ * still waits for that person to approve it.
10
+ */
11
+ export const assistantRole = {
12
+ name: ASSISTANT_ROLE,
13
+ label: "AI assistant",
14
+ description: "What the AI may do for the person using it, never more than their own access: read and draft content. It can't delete, or change schemas, users, settings or roles.",
15
+ permissions: ["collection:read", "record:list", "record:read", "record:create", "record:update", "file:list", "file:read", "locale:edit"],
16
+ };
17
+ /**
18
+ * Who may give the AI a role other than the site's: whoever may give people roles, admins by
19
+ * default. Anyone else's assistant acts with the role chosen under AI → Settings.
20
+ */
21
+ export const GIVE_ROLE = "user:set-role";
22
+ /** Whether this caller may choose the AI's role. */
23
+ export const givesRoles = (principal) => principal.permissions.has(GIVE_ROLE);
24
+ /** The role the AI acts with: the one chosen in the chat while people may choose, else the settings', else its own. */
25
+ export const roleFor = (settings, picked) => (settings.chooseRole !== false && picked) || (typeof settings.role === "string" && settings.role.trim()) || ASSISTANT_ROLE;
@@ -0,0 +1,46 @@
1
+ import type { ModelCapabilities, ModelChoice } from "../provider";
2
+ import type { Task, Workflow } from "./schema";
3
+ /**
4
+ * Whether a workflow's agents can do what it asks of them, as their providers' APIs report.
5
+ * Shared by the server, which refuses to run a workflow with errors, and the dashboard,
6
+ * which shows the same problems as it is edited.
7
+ */
8
+ /** A provider as the dashboard sees it: its models and what each can do. Never its key. */
9
+ export interface CatalogEntry {
10
+ id: string;
11
+ label: string;
12
+ icon?: string;
13
+ ready: boolean;
14
+ /** Whether it has image models of its own, beside language models that answer with pictures. */
15
+ images: boolean;
16
+ defaultModel: string;
17
+ models: ModelChoice[] | null;
18
+ error?: string;
19
+ }
20
+ export interface Catalog {
21
+ providers: CatalogEntry[];
22
+ /** The roles a workflow can act with, and the one AI → Settings chooses. */
23
+ roles?: Array<{
24
+ name: string;
25
+ label: string;
26
+ description?: string;
27
+ }>;
28
+ /** Whether the person may choose that role: whoever may give people roles. */
29
+ chooseRole?: boolean;
30
+ defaultRole?: string;
31
+ }
32
+ /** Whether a model can do a task: yes, no, or unknown when its provider doesn't say. */
33
+ export type Support = "yes" | "no" | "unknown";
34
+ export declare function supports(capabilities: ModelCapabilities | undefined, task: Task): Support;
35
+ export interface Problem {
36
+ path: string;
37
+ message: string;
38
+ level: "error" | "warning";
39
+ }
40
+ /** What each agent does in the workflow. */
41
+ export declare function tasksOf(workflow: Pick<Workflow, "planner" | "steps">): Map<string, Set<Task>>;
42
+ /**
43
+ * A model the provider says can't do a task is an error. One it says nothing about is a
44
+ * warning, and runs anyway.
45
+ */
46
+ export declare function checkWorkflow(workflow: Pick<Workflow, "agents" | "planner" | "steps">, catalog: Catalog): Problem[];