@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
@@ -0,0 +1,63 @@
1
+ export function supports(capabilities, task) {
2
+ const output = capabilities?.output;
3
+ if (task === "image") {
4
+ if (!output)
5
+ return "unknown";
6
+ return output.includes("image") ? "yes" : "no";
7
+ }
8
+ if (output && !output.includes("text"))
9
+ return "no";
10
+ // Writing records and plans needs an answer in a given JSON shape.
11
+ if (task !== "judge" && capabilities?.structured === false)
12
+ return "no";
13
+ return output ? "yes" : "unknown";
14
+ }
15
+ const TASK_WORDS = { write: "write records", judge: "judge drafts", plan: "plan the work", image: "draw pictures" };
16
+ /** What each agent does in the workflow. */
17
+ export function tasksOf(workflow) {
18
+ const uses = new Map();
19
+ const add = (agent, task) => uses.set(agent, (uses.get(agent) ?? new Set()).add(task));
20
+ if (workflow.planner)
21
+ add(workflow.planner.agent, "plan");
22
+ for (const step of workflow.steps) {
23
+ for (const writer of step.writers)
24
+ add(writer, "write");
25
+ if (step.judge)
26
+ add(step.judge.agent, "judge");
27
+ for (const image of step.images ?? [])
28
+ for (const artist of image.artists)
29
+ add(artist, "image");
30
+ }
31
+ return uses;
32
+ }
33
+ /**
34
+ * A model the provider says can't do a task is an error. One it says nothing about is a
35
+ * warning, and runs anyway.
36
+ */
37
+ export function checkWorkflow(workflow, catalog) {
38
+ const problems = [];
39
+ const uses = tasksOf(workflow);
40
+ const providers = new Map(catalog.providers.map((entry) => [entry.id, entry]));
41
+ workflow.agents.forEach((agent, index) => {
42
+ const path = `agents.${index}`;
43
+ const entry = providers.get(agent.provider);
44
+ if (!entry)
45
+ return problems.push({ path, level: "error", message: `${agent.name}: the provider "${agent.provider}" isn't installed.` });
46
+ if (!entry.ready)
47
+ return problems.push({ path, level: "error", message: `${agent.name}: ${entry.label} isn't set up. Add its key under AI → Settings.` });
48
+ const tasks = uses.get(agent.id);
49
+ if (!tasks?.size)
50
+ return problems.push({ path, level: "warning", message: `${agent.name} has nothing to do in any step.` });
51
+ const model = entry.models?.find((choice) => choice.value === agent.model);
52
+ if (entry.models && !model)
53
+ return problems.push({ path, level: "warning", message: `${agent.name}: ${entry.label} doesn't list "${agent.model}", so what it can do is unknown.` });
54
+ for (const task of tasks) {
55
+ const support = supports(model?.capabilities, task);
56
+ if (support === "no")
57
+ problems.push({ path, level: "error", message: `${agent.name}: ${agent.model} can't ${TASK_WORDS[task]}, as ${entry.label} reports it.` });
58
+ else if (support === "unknown" && task === "image")
59
+ problems.push({ path, level: "warning", message: `${agent.name}: ${entry.label} doesn't say whether ${agent.model} can draw pictures.` });
60
+ }
61
+ });
62
+ return problems;
63
+ }
@@ -0,0 +1,90 @@
1
+ import type { Catalog, Problem } from "./check";
2
+ import type { Run, RunSummary } from "./engine";
3
+ import type { Workflow, WorkflowInput } from "./schema";
4
+ export type { Catalog, CatalogEntry, Problem } from "./check";
5
+ export type { Run, RunItem, RunSummary, RunTask, LogEntry } from "./engine";
6
+ export type { Agent, Step, Workflow, WorkflowInput } from "./schema";
7
+ export interface WorkflowSummary {
8
+ id: string;
9
+ name: string;
10
+ description: string;
11
+ agents: number;
12
+ steps: number;
13
+ updatedAt: string;
14
+ updatedBy: string;
15
+ }
16
+ export interface CollectionInfo {
17
+ slug: string;
18
+ name: string;
19
+ type?: string;
20
+ readOnly?: boolean;
21
+ }
22
+ export interface FieldInfo {
23
+ name: string;
24
+ type: string;
25
+ label?: string;
26
+ description?: string;
27
+ required?: boolean;
28
+ readonly?: boolean;
29
+ schema?: Record<string, unknown>;
30
+ blocks?: Array<{
31
+ name: string;
32
+ fields: Array<{
33
+ name: string;
34
+ type: string;
35
+ }>;
36
+ }>;
37
+ }
38
+ /** An error the route gave, with its details: the workflow's problems, or what was created before a failure. */
39
+ export declare class ApiError extends Error {
40
+ readonly code: string;
41
+ readonly details?: unknown | undefined;
42
+ constructor(message: string, code: string, details?: unknown | undefined);
43
+ }
44
+ export declare const listWorkflows: () => Promise<{
45
+ workflows: WorkflowSummary[];
46
+ runs: RunSummary[];
47
+ }>;
48
+ export declare const loadCatalog: () => Promise<Catalog & {
49
+ collections: CollectionInfo[];
50
+ }>;
51
+ export declare const loadCollection: (slug: string) => Promise<{
52
+ slug: string;
53
+ name: string;
54
+ fields: FieldInfo[];
55
+ }>;
56
+ export declare const loadWorkflow: (id: string) => Promise<{
57
+ workflow: Workflow;
58
+ }>;
59
+ export declare const saveWorkflow: (workflow: WorkflowInput) => Promise<{
60
+ workflow: Workflow;
61
+ problems: Problem[];
62
+ }>;
63
+ export declare const deleteWorkflow: (id: string) => Promise<{
64
+ deleted: true;
65
+ }>;
66
+ export declare const startRun: (id: string, inputs: Record<string, string>) => Promise<{
67
+ run: RunSummary;
68
+ }>;
69
+ export declare const loadRun: (id: string, values?: boolean) => Promise<{
70
+ run: Run;
71
+ driving: boolean;
72
+ values?: Record<string, Record<string, string>>;
73
+ }>;
74
+ export declare const cancelRun: (id: string) => Promise<unknown>;
75
+ export declare const retryRun: (id: string) => Promise<unknown>;
76
+ export declare const regenerateItem: (id: string, item: string) => Promise<unknown>;
77
+ export declare const deleteRun: (id: string) => Promise<unknown>;
78
+ export declare const commitRun: (id: string, body: {
79
+ include?: string[];
80
+ files: Record<string, string>;
81
+ }) => Promise<{
82
+ created: Array<{
83
+ item: string;
84
+ collection: string;
85
+ id: number;
86
+ }>;
87
+ }>;
88
+ export declare const imageUrl: (run: string, image: string) => string;
89
+ /** Uploads one of a run's pictures to the site's files, as the person, and gives its file id. */
90
+ export declare function uploadImage(run: string, image: string, name: string): Promise<string>;
@@ -0,0 +1,51 @@
1
+ "use client";
2
+ import { apiPath } from "tansy/admin";
3
+ /** An error the route gave, with its details: the workflow's problems, or what was created before a failure. */
4
+ export class ApiError extends Error {
5
+ code;
6
+ details;
7
+ constructor(message, code, details) {
8
+ super(message);
9
+ this.code = code;
10
+ this.details = details;
11
+ }
12
+ }
13
+ async function call(path, init = {}) {
14
+ const response = await fetch(apiPath(`/ext/ai${path}`), { cache: "no-store", ...init, headers: init.body ? { "content-type": "application/json", ...init.headers } : init.headers }).catch(() => null);
15
+ if (!response)
16
+ throw new ApiError("The server couldn't be reached.", "NETWORK");
17
+ const json = (await response.json().catch(() => null));
18
+ if (!response.ok)
19
+ throw new ApiError(json?.error?.message ?? "That didn't work. Try again in a moment.", json?.error?.code ?? "FAILED", json?.error?.details);
20
+ return json;
21
+ }
22
+ const json = (method, body) => ({ method, ...(body === undefined ? {} : { body: JSON.stringify(body) }) });
23
+ export const listWorkflows = () => call("/workflows");
24
+ export const loadCatalog = () => call("/workflows/catalog");
25
+ export const loadCollection = (slug) => call(`/workflows/collections/${encodeURIComponent(slug)}`);
26
+ export const loadWorkflow = (id) => call(`/workflows/${encodeURIComponent(id)}`);
27
+ export const saveWorkflow = (workflow) => call(`/workflows/${encodeURIComponent(workflow.id)}`, json("PUT", workflow));
28
+ export const deleteWorkflow = (id) => call(`/workflows/${encodeURIComponent(id)}`, json("DELETE"));
29
+ export const startRun = (id, inputs) => call(`/workflows/${encodeURIComponent(id)}/runs`, json("POST", { inputs }));
30
+ export const loadRun = (id, values = false) => call(`/runs/${id}${values ? "?values=1" : ""}`);
31
+ export const cancelRun = (id) => call(`/runs/${id}/cancel`, json("POST"));
32
+ export const retryRun = (id) => call(`/runs/${id}/retry`, json("POST"));
33
+ export const regenerateItem = (id, item) => call(`/runs/${id}/items/${item}/regenerate`, json("POST"));
34
+ export const deleteRun = (id) => call(`/runs/${id}`, json("DELETE"));
35
+ export const commitRun = (id, body) => call(`/runs/${id}/commit`, json("POST", body));
36
+ export const imageUrl = (run, image) => apiPath(`/ext/ai/runs/${run}/images/${image}`);
37
+ /** Uploads one of a run's pictures to the site's files, as the person, and gives its file id. */
38
+ export async function uploadImage(run, image, name) {
39
+ const picture = await fetch(imageUrl(run, image), { cache: "no-store" });
40
+ if (!picture.ok)
41
+ throw new ApiError("A picture couldn't be read.", "IMAGE");
42
+ const type = picture.headers.get("content-type") ?? "image/png";
43
+ const extension = type.split("/")[1]?.replace("jpeg", "jpg") ?? "png";
44
+ const safe = name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 60) || "image";
45
+ // Temporary until a record uses it, so a picture left out is cleaned up.
46
+ const response = await fetch(apiPath(`/files/upload?name=${encodeURIComponent(`${safe}.${extension}`)}&temporary=true`), { method: "POST", headers: { "content-type": type }, body: await picture.blob() });
47
+ const json = (await response.json().catch(() => null));
48
+ if (!response.ok || !json?.id)
49
+ throw new ApiError(json?.error?.message ?? "A picture couldn't be uploaded.", "UPLOAD");
50
+ return json.id;
51
+ }
@@ -0,0 +1,13 @@
1
+ import { type Catalog, type CollectionInfo, type FieldInfo, type WorkflowInput } from "./client";
2
+ type Draft = WorkflowInput;
3
+ /** Fields a writer can fill: what the server's write schema asks for. */
4
+ export declare const writable: (field: FieldInfo) => boolean;
5
+ export declare function WorkflowEditor({ initial, catalog, collections, onSaved, onRun, onBack }: {
6
+ initial: Draft;
7
+ catalog: Catalog;
8
+ collections: CollectionInfo[];
9
+ onSaved: (workflow: Draft) => void;
10
+ onRun: (id: string) => void;
11
+ onBack: () => void;
12
+ }): import("react").JSX.Element;
13
+ export {};
@@ -0,0 +1,133 @@
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, useMemo, useRef, useState } from "react";
5
+ import { Plus, Spark, Trash } from "../parts";
6
+ import { checkWorkflow, tasksOf } from "./check";
7
+ import { ApiError, loadCollection, saveWorkflow } from "./client";
8
+ import { ModelIcon } from "./icons";
9
+ import { CapabilityChips, ModelPicker } from "./model-picker";
10
+ import { REASONING, STRATEGIES, workflowSchema } from "./schema";
11
+ const NOT_WRITABLE = new Set(["file", "image", "gallery", "reference", "json", "password"]);
12
+ /** Fields a writer can fill: what the server's write schema asks for. */
13
+ export const writable = (field) => !field.readonly && (field.type === "stream" ? Boolean(field.blocks?.some((block) => block.fields.some((item) => item.type === "rich_text"))) : !NOT_WRITABLE.has(field.type) && !field.type.includes("price") && Boolean(field.schema));
14
+ const newKey = (prefix, taken) => {
15
+ for (let index = 1;; index++) {
16
+ const key = `${prefix}${index === 1 ? "" : `-${index}`}`;
17
+ if (!taken.includes(key))
18
+ return key;
19
+ }
20
+ };
21
+ function Section({ id, title, hint, children, actions }) {
22
+ return (_jsxs("section", { className: "wf-section", id: `wf-${id}`, children: [_jsxs("header", { className: "wf-section-head", children: [_jsxs("div", { children: [_jsx("h2", { children: title }), hint ? _jsx("p", { className: "wf-muted", children: hint }) : null] }), actions] }), children] }));
23
+ }
24
+ function Labeled({ label, hint, children, wide }) {
25
+ return (_jsxs("label", { className: `wf-field${wide ? " wf-field-wide" : ""}`, children: [_jsx("span", { className: "wf-label", children: label }), children, hint ? _jsx("span", { className: "wf-hint", children: hint }) : null] }));
26
+ }
27
+ /** Agents to choose for a step's role, as toggles with each one's model icon. */
28
+ function AgentToggles({ agents, value, onChange, single }) {
29
+ return (_jsx("div", { className: "wf-toggles", children: agents.map((agent) => {
30
+ const on = value.includes(agent.id);
31
+ const order = value.indexOf(agent.id);
32
+ return (_jsxs("button", { type: "button", "aria-pressed": on, className: `wf-toggle${on ? " is-on" : ""}`, onClick: () => onChange(single ? [agent.id] : on ? value.filter((id) => id !== agent.id) : [...value, agent.id]), children: [_jsx(ModelIcon, { model: agent.model, provider: agent.provider, size: 16 }), agent.name, on && !single && value.length > 1 ? _jsx("span", { className: "wf-order", children: order + 1 }) : null] }, agent.id));
33
+ }) }));
34
+ }
35
+ export function WorkflowEditor({ initial, catalog, collections, onSaved, onRun, onBack }) {
36
+ const { t } = useT();
37
+ const w = (key, values) => t(`ext.ai.workflows.${key}`, values);
38
+ const [draft, setDraft] = useState(initial);
39
+ const [fields, setFields] = useState({});
40
+ const [saving, setSaving] = useState(false);
41
+ const [saved, setSaved] = useState(null);
42
+ const [serverProblems, setServerProblems] = useState([]);
43
+ const [dirty, setDirty] = useState(false);
44
+ const update = (change) => { setDraft((value) => change(value)); setDirty(true); setSaved(null); };
45
+ const setStep = (index, patch) => update((value) => ({ ...value, steps: value.steps.map((step, at) => (at === index ? { ...step, ...patch } : step)) }));
46
+ const setAgent = (index, patch) => update((value) => ({ ...value, agents: value.agents.map((agent, at) => (at === index ? { ...agent, ...patch } : agent)) }));
47
+ // Each collection's fields, as the person may see them, for choosing what each step writes.
48
+ const slugs = useMemo(() => [...new Set(draft.steps.map((step) => step.collection).filter(Boolean))], [draft.steps]);
49
+ const asked = useRef(new Set());
50
+ useEffect(() => {
51
+ for (const slug of slugs) {
52
+ if (asked.current.has(slug))
53
+ continue;
54
+ asked.current.add(slug);
55
+ void loadCollection(slug).then((collection) => setFields((value) => ({ ...value, [slug]: collection.fields }))).catch(() => setFields((value) => ({ ...value, [slug]: "error" })));
56
+ }
57
+ }, [slugs]);
58
+ const fieldsOf = (slug) => (Array.isArray(fields[slug]) ? fields[slug] : []);
59
+ const parsed = useMemo(() => workflowSchema.safeParse(draft), [draft]);
60
+ const problems = useMemo(() => {
61
+ const shape = parsed.success ? [] : parsed.error.issues.slice(0, 12).map((issue) => ({ path: issue.path.join("."), message: issue.message, level: "error" }));
62
+ const models = parsed.success ? checkWorkflow(parsed.data, catalog) : [];
63
+ return [...shape, ...models];
64
+ }, [parsed, catalog]);
65
+ const errors = problems.filter((problem) => problem.level === "error");
66
+ const uses = useMemo(() => (parsed.success ? tasksOf(parsed.data) : tasksOf({ planner: draft.planner, steps: draft.steps.map((step) => ({ ...step, images: step.images ?? [] })) })), [parsed, draft]);
67
+ async function save() {
68
+ setSaving(true);
69
+ try {
70
+ const result = await saveWorkflow(draft);
71
+ setServerProblems(result.problems);
72
+ setDraft(result.workflow);
73
+ setDirty(false);
74
+ setSaved(w("editor.saved"));
75
+ onSaved(result.workflow);
76
+ return true;
77
+ }
78
+ catch (error) {
79
+ setServerProblems(error instanceof ApiError && Array.isArray(error.details) ? error.details.map((item) => ({ ...item, level: "error" })) : [{ path: "", message: error instanceof Error ? error.message : String(error), level: "error" }]);
80
+ return false;
81
+ }
82
+ finally {
83
+ setSaving(false);
84
+ }
85
+ }
86
+ const agentTasks = (agent) => [...(uses.get(agent.id) ?? [])];
87
+ const stepDepth = (step) => {
88
+ let depth = 0;
89
+ for (let parent = step.parent; parent && depth < 6; depth++)
90
+ parent = draft.steps.find((other) => other.id === parent)?.parent;
91
+ return depth;
92
+ };
93
+ const shown = [...problems, ...serverProblems.filter((problem) => !problems.some((other) => other.message === problem.message))];
94
+ return (_jsxs("div", { className: "wf-editor", children: [_jsxs("header", { className: "wf-top", children: [_jsxs("button", { type: "button", className: "ai-ghost", onClick: onBack, children: ["\u2190 ", w("title")] }), _jsx("input", { className: "wf-title-input", value: draft.name, "aria-label": w("editor.name"), onChange: (event) => update((value) => ({ ...value, name: event.target.value })) }), _jsx("span", { className: "wf-top-status wf-muted", children: saving ? w("editor.saving") : saved ?? (dirty ? w("editor.unsaved") : "") }), _jsx("button", { type: "button", className: "wf-button wf-button-ghost", disabled: saving, onClick: () => void save(), children: w("editor.save") }), _jsxs("button", { type: "button", className: "wf-button", disabled: saving || errors.length > 0, title: errors[0]?.message, onClick: async () => { if (!dirty || (await save()))
95
+ onRun(draft.id); }, children: [_jsx(Spark, { className: "ai-icon" }), w("editor.run")] })] }), _jsxs("div", { className: "wf-layout", children: [_jsxs("nav", { className: "wf-map", "aria-label": w("editor.map"), children: [_jsxs("a", { href: "#wf-brief", className: "wf-map-node wf-map-brief", children: [_jsx("span", { className: "wf-map-dot" }), w("editor.brief")] }), draft.planner ? (_jsxs("a", { href: "#wf-team", className: "wf-map-node", children: [_jsx("span", { className: "wf-map-icon", children: _jsx(ModelIcon, { ...(draft.agents.find((agent) => agent.id === draft.planner?.agent) ?? { model: "", provider: "" }), size: 14 }) }), w("editor.planner")] })) : null, draft.steps.map((step, index) => (_jsxs("a", { href: `#wf-step-${index}`, className: "wf-map-node", style: { paddingInlineStart: `${0.75 + stepDepth(step) * 1}rem` }, children: [_jsx("span", { className: "wf-map-dot" }), _jsxs("span", { className: "wf-map-text", children: [step.name || step.id, _jsxs("small", { children: [step.count.min === step.count.max ? step.count.min : `${step.count.min}–${step.count.max}`, " \u00D7 ", collections.find((item) => item.slug === step.collection)?.name ?? step.collection] })] }), _jsxs("span", { className: "wf-map-agents", children: [step.writers.map((id) => { const agent = draft.agents.find((item) => item.id === id); return agent ? _jsx(ModelIcon, { model: agent.model, provider: agent.provider, size: 14 }, id) : null; }), step.judge ? _jsx("span", { className: "wf-map-judge", title: w("editor.judge"), children: "\u2696" }) : null, step.images?.length ? _jsx("span", { className: "wf-map-judge", title: w("editor.images"), children: "\u25A3" }) : null] })] }, step.id))), _jsx("div", { className: "wf-problems", "aria-live": "polite", children: shown.length ? shown.map((problem, index) => _jsx("p", { className: `wf-problem wf-problem-${problem.level}`, children: problem.message }, index)) : _jsx("p", { className: "wf-problem wf-problem-ok", children: w("editor.ready") }) })] }), _jsxs("div", { className: "wf-sections", children: [_jsxs(Section, { id: "brief", title: w("editor.brief"), hint: w("editor.briefHint"), children: [_jsx(Labeled, { label: w("editor.description"), wide: true, children: _jsx("input", { className: "wf-input", value: draft.description ?? "", maxLength: 500, onChange: (event) => update((value) => ({ ...value, description: event.target.value })) }) }), _jsx(Labeled, { label: w("editor.masterPrompt"), hint: w("editor.masterPromptHint"), wide: true, children: _jsx("textarea", { className: "wf-input wf-textarea wf-textarea-tall", value: draft.brief, maxLength: 8000, onChange: (event) => update((value) => ({ ...value, brief: event.target.value })) }) }), _jsxs("div", { className: "wf-subhead", children: [_jsx("h3", { children: w("editor.inputs") }), _jsxs("button", { type: "button", className: "ai-ghost", onClick: () => update((value) => ({ ...value, inputs: [...(value.inputs ?? []), { name: newKey("input", (value.inputs ?? []).map((input) => input.name)).replace(/-/g, "_"), label: w("editor.newInput"), multiline: false, required: true }] })), children: [_jsx(Plus, {}), w("editor.addInput")] })] }), _jsx("p", { className: "wf-muted", children: w("editor.inputsHint") }), (draft.inputs ?? []).map((input, index) => (_jsxs("div", { className: "wf-row", children: [_jsx("input", { className: "wf-input wf-mono", value: input.name, "aria-label": w("editor.inputName"), onChange: (event) => update((value) => ({ ...value, inputs: value.inputs.map((item, at) => (at === index ? { ...item, name: event.target.value } : item)) })) }), _jsx("input", { className: "wf-input", value: input.label, "aria-label": w("editor.inputLabel"), onChange: (event) => update((value) => ({ ...value, inputs: value.inputs.map((item, at) => (at === index ? { ...item, label: event.target.value } : item)) })) }), _jsxs("label", { className: "wf-check", children: [_jsx("input", { type: "checkbox", checked: input.multiline ?? false, onChange: (event) => update((value) => ({ ...value, inputs: value.inputs.map((item, at) => (at === index ? { ...item, multiline: event.target.checked } : item)) })) }), w("editor.multiline")] }), _jsxs("label", { className: "wf-check", children: [_jsx("input", { type: "checkbox", checked: input.required ?? true, onChange: (event) => update((value) => ({ ...value, inputs: value.inputs.map((item, at) => (at === index ? { ...item, required: event.target.checked } : item)) })) }), w("editor.required")] }), _jsx("code", { className: "wf-token", children: `{{${input.name}}}` }), _jsx("button", { type: "button", className: "ai-ghost ai-ghost-icon", "aria-label": w("editor.remove"), onClick: () => update((value) => ({ ...value, inputs: value.inputs.filter((_, at) => at !== index) })), children: _jsx(Trash, {}) })] }, index)))] }), _jsxs(Section, { id: "team", title: w("editor.team"), hint: w("editor.teamHint"), actions: _jsxs("button", { type: "button", className: "ai-ghost", onClick: () => update((value) => {
96
+ const id = newKey("agent", value.agents.map((agent) => agent.id));
97
+ const first = value.agents[0];
98
+ return { ...value, agents: [...value.agents, { id, name: w("editor.newAgent"), role: "", provider: first?.provider ?? catalog.providers.find((item) => item.ready)?.id ?? "", model: first?.model ?? "", reasoning: "provider-default" }] };
99
+ }), children: [_jsx(Plus, {}), w("editor.addAgent")] }), children: [_jsx(Labeled, { label: w("editor.planner"), hint: w("editor.plannerHint"), wide: true, children: _jsxs("select", { className: "wf-input", value: draft.planner?.agent ?? "", onChange: (event) => update((value) => ({ ...value, planner: event.target.value ? { agent: event.target.value } : undefined })), children: [_jsx("option", { value: "", children: w("editor.noPlanner") }), draft.agents.map((agent) => _jsx("option", { value: agent.id, children: agent.name }, agent.id))] }) }), _jsx("div", { className: "wf-agents", children: draft.agents.map((agent, index) => {
100
+ const entry = catalog.providers.find((item) => item.id === agent.provider);
101
+ const choice = entry?.models?.find((item) => item.value === agent.model);
102
+ const tasks = agentTasks(agent);
103
+ return (_jsxs("article", { className: "wf-agent", children: [_jsxs("div", { className: "wf-agent-head", children: [_jsx(ModelIcon, { model: agent.model, provider: agent.provider, icon: entry?.icon, size: 28 }), _jsx("input", { className: "wf-input wf-agent-name", value: agent.name, "aria-label": w("editor.agentName"), onChange: (event) => setAgent(index, { name: event.target.value }) }), _jsx("button", { type: "button", className: "ai-ghost ai-ghost-icon", "aria-label": w("editor.remove"), disabled: draft.agents.length < 2, onClick: () => update((value) => ({ ...value, agents: value.agents.filter((_, at) => at !== index) })), children: _jsx(Trash, {}) })] }), _jsxs("div", { className: "wf-agent-tasks", children: [tasks.length ? tasks.map((task) => _jsx("span", { className: "wf-chip wf-chip-task", children: w(`tasks.${task}`) }, task)) : _jsx("span", { className: "wf-chip wf-chip-unknown", children: w("editor.idle") }), _jsx("code", { className: "wf-mono wf-muted", children: agent.id })] }), _jsx(ModelPicker, { catalog: catalog, provider: agent.provider, model: agent.model, tasks: tasks, onChange: (value) => setAgent(index, value) }), _jsx("div", { className: "wf-model-chips", children: _jsx(CapabilityChips, { capabilities: choice?.capabilities }) }), _jsx(Labeled, { label: w("editor.role"), wide: true, children: _jsx("textarea", { className: "wf-input wf-textarea", value: agent.role ?? "", maxLength: 2000, placeholder: w("editor.rolePlaceholder"), onChange: (event) => setAgent(index, { role: event.target.value }) }) }), _jsxs("div", { className: "wf-grid-2", children: [_jsx(Labeled, { label: w("editor.reasoning"), children: _jsx("select", { className: "wf-input", value: agent.reasoning ?? "provider-default", onChange: (event) => setAgent(index, { reasoning: event.target.value }), children: REASONING.map((level) => _jsx("option", { value: level, children: t(`ext.ai.settings.reasoning.options.${level}`) }, level)) }) }), _jsx(Labeled, { label: w("editor.temperature"), children: _jsx("input", { className: "wf-input", type: "number", min: 0, max: 2, step: 0.1, value: agent.temperature ?? "", placeholder: w("editor.default"), onChange: (event) => setAgent(index, { temperature: event.target.value === "" ? undefined : Number(event.target.value) }) }) })] })] }, index));
104
+ }) })] }), _jsx(Section, { id: "steps", title: w("editor.steps"), hint: w("editor.stepsHint"), actions: _jsxs("button", { type: "button", className: "ai-ghost", onClick: () => update((value) => ({ ...value, steps: [...value.steps, { id: newKey("step", value.steps.map((step) => step.id)), name: w("editor.newStep"), collection: "", count: { min: 1, max: 3 }, fields: [], instructions: "", writers: [value.agents[0]?.id ?? ""], strategy: "rotate", images: [], links: [] }] })), children: [_jsx(Plus, {}), w("editor.addStep")] }), children: draft.steps.map((step, index) => {
105
+ const all = fieldsOf(step.collection);
106
+ const canWrite = all.filter(writable);
107
+ const references = all.filter((field) => field.type === "reference");
108
+ const numbers = all.filter((field) => field.type === "number");
109
+ const images = all.filter((field) => field.type === "image");
110
+ const parents = draft.steps.slice(0, index);
111
+ const ancestors = [];
112
+ for (let parent = step.parent; parent && !ancestors.includes(parent); parent = draft.steps.find((other) => other.id === parent)?.parent)
113
+ ancestors.push(parent);
114
+ return (_jsxs("article", { className: "wf-step", id: `wf-step-${index}`, children: [_jsxs("header", { className: "wf-step-head", children: [_jsx("span", { className: "wf-step-number", children: index + 1 }), _jsx("input", { className: "wf-input wf-step-name", value: step.name, "aria-label": w("editor.stepName"), onChange: (event) => setStep(index, { name: event.target.value }) }), _jsx("code", { className: "wf-mono wf-muted", children: step.id }), _jsx("button", { type: "button", className: "ai-ghost ai-ghost-icon", "aria-label": w("editor.remove"), disabled: draft.steps.length < 2, onClick: () => update((value) => ({ ...value, steps: value.steps.filter((_, at) => at !== index).map((other) => (other.parent === step.id ? { ...other, parent: undefined, link: undefined } : other)) })), children: _jsx(Trash, {}) })] }), _jsxs("div", { className: "wf-grid-3", children: [_jsx(Labeled, { label: w("editor.collection"), children: _jsxs("select", { className: "wf-input", value: step.collection, onChange: (event) => setStep(index, { collection: event.target.value, fields: [], link: undefined, links: [], orderField: undefined, images: [] }), children: [_jsx("option", { value: "", children: w("editor.chooseCollection") }), collections.filter((item) => !item.readOnly).map((item) => _jsx("option", { value: item.slug, children: item.name }, item.slug))] }) }), _jsx(Labeled, { label: w("editor.parent"), hint: w("editor.parentHint"), children: _jsxs("select", { className: "wf-input", value: step.parent ?? "", onChange: (event) => setStep(index, { parent: event.target.value || undefined, link: undefined, links: [] }), children: [_jsx("option", { value: "", children: w("editor.topLevel") }), parents.map((other) => _jsx("option", { value: other.id, children: w("editor.eachOf", { step: other.name }) }, other.id))] }) }), _jsxs("div", { className: "wf-field", children: [_jsx("span", { className: "wf-label", children: w("editor.count") }), _jsxs("div", { className: "wf-count", children: [_jsx("input", { className: "wf-input", type: "number", min: 1, max: 50, value: step.count.min, "aria-label": w("editor.countMin"), onChange: (event) => setStep(index, { count: { min: Number(event.target.value) || 1, max: Math.max(step.count.max, Number(event.target.value) || 1) } }) }), _jsx("span", { children: "\u2013" }), _jsx("input", { className: "wf-input", type: "number", min: 1, max: 50, value: step.count.max, "aria-label": w("editor.countMax"), onChange: (event) => setStep(index, { count: { ...step.count, max: Number(event.target.value) || 1 } }) })] }), _jsx("span", { className: "wf-hint", children: step.count.min === step.count.max ? w("editor.exactly", { count: step.count.min }) : w("editor.between", { min: step.count.min, max: step.count.max }) })] })] }), step.parent || ancestors.length ? (_jsxs("div", { className: "wf-grid-3", children: [step.parent ? (_jsx(Labeled, { label: w("editor.link"), hint: w("editor.linkHint"), children: _jsxs("select", { className: "wf-input", value: step.link ?? "", onChange: (event) => setStep(index, { link: event.target.value || undefined }), children: [_jsx("option", { value: "", children: w("editor.chooseField") }), references.map((field) => _jsx("option", { value: field.name, children: field.label ?? field.name }, field.name))] }) })) : null, ancestors.slice(1).map((ancestor) => {
115
+ const current = (step.links ?? []).find((link) => link.step === ancestor);
116
+ return (_jsx(Labeled, { label: w("editor.alsoLink", { step: draft.steps.find((other) => other.id === ancestor)?.name ?? ancestor }), children: _jsxs("select", { className: "wf-input", value: current?.field ?? "", onChange: (event) => setStep(index, { links: [...(step.links ?? []).filter((link) => link.step !== ancestor), ...(event.target.value ? [{ field: event.target.value, step: ancestor }] : [])] }), children: [_jsx("option", { value: "", children: w("editor.none") }), references.map((field) => _jsx("option", { value: field.name, children: field.label ?? field.name }, field.name))] }) }, ancestor));
117
+ }), _jsx(Labeled, { label: w("editor.order"), hint: w("editor.orderHint"), children: _jsxs("select", { className: "wf-input", value: step.orderField ?? "", onChange: (event) => setStep(index, { orderField: event.target.value || undefined }), children: [_jsx("option", { value: "", children: w("editor.none") }), numbers.map((field) => _jsx("option", { value: field.name, children: field.label ?? field.name }, field.name))] }) })] })) : null, _jsxs("div", { className: "wf-field wf-field-wide", children: [_jsx("span", { className: "wf-label", children: w("editor.fields") }), fields[step.collection] === "error" ? _jsx("span", { className: "wf-hint", children: w("editor.fieldsError") }) : null, _jsx("div", { className: "wf-toggles", children: canWrite.map((field) => {
118
+ const on = !step.fields?.length || step.fields.includes(field.name);
119
+ const linked = field.name === step.link || field.name === step.orderField || (step.links ?? []).some((link) => link.field === field.name);
120
+ if (linked)
121
+ return null;
122
+ return (_jsxs("button", { type: "button", "aria-pressed": on, className: `wf-toggle wf-toggle-small${on ? " is-on" : ""}`, onClick: () => {
123
+ const current = step.fields?.length ? step.fields : canWrite.map((item) => item.name);
124
+ const next = on ? current.filter((name) => name !== field.name) : [...current, field.name];
125
+ setStep(index, { fields: next.length === canWrite.length ? [] : next });
126
+ }, children: [field.label ?? field.name, _jsx("small", { children: field.type })] }, field.name));
127
+ }) })] }), _jsx(Labeled, { label: w("editor.instructions"), hint: w("editor.instructionsHint"), wide: true, children: _jsx("textarea", { className: "wf-input wf-textarea", value: step.instructions ?? "", maxLength: 4000, onChange: (event) => setStep(index, { instructions: event.target.value }) }) }), _jsxs("div", { className: "wf-field wf-field-wide", children: [_jsx("span", { className: "wf-label", children: w("editor.writers") }), _jsx(AgentToggles, { agents: draft.agents, value: step.writers, onChange: (writers) => setStep(index, { writers }) })] }), _jsxs("div", { className: "wf-field wf-field-wide", children: [_jsx("span", { className: "wf-label", children: w("editor.strategy") }), _jsx("div", { className: "wf-segments", role: "radiogroup", children: STRATEGIES.map((strategy) => (_jsxs("button", { type: "button", role: "radio", "aria-checked": (step.strategy ?? "rotate") === strategy, className: `wf-segment${(step.strategy ?? "rotate") === strategy ? " is-on" : ""}`, onClick: () => setStep(index, { strategy }), children: [_jsx("strong", { children: w(`strategy.${strategy}`) }), _jsx("span", { children: w(`strategy.${strategy}Hint`) })] }, strategy))) })] }), _jsxs("div", { className: "wf-box", children: [_jsxs("label", { className: "wf-check wf-box-head", children: [_jsx("input", { type: "checkbox", checked: Boolean(step.judge), onChange: (event) => setStep(index, { judge: event.target.checked ? { agent: draft.agents.find((agent) => !step.writers.includes(agent.id))?.id ?? draft.agents[0].id, criteria: "", minScore: 7, revisions: 1 } : undefined }) }), _jsx("strong", { children: w("editor.judge") }), _jsx("span", { className: "wf-muted", children: w("editor.judgeHint") })] }), step.judge ? (_jsxs(_Fragment, { children: [_jsx(AgentToggles, { single: true, agents: draft.agents, value: [step.judge.agent], onChange: ([agent]) => setStep(index, { judge: { ...step.judge, agent } }) }), _jsxs("div", { className: "wf-grid-3", children: [_jsx(Labeled, { label: w("editor.minScore", { score: step.judge.minScore ?? 7 }), children: _jsx("input", { type: "range", min: 1, max: 10, value: step.judge.minScore ?? 7, onChange: (event) => setStep(index, { judge: { ...step.judge, minScore: Number(event.target.value) } }) }) }), _jsx(Labeled, { label: w("editor.revisions"), hint: w("editor.revisionsHint"), children: _jsx("input", { className: "wf-input", type: "number", min: 0, max: 3, value: step.judge.revisions ?? 1, onChange: (event) => setStep(index, { judge: { ...step.judge, revisions: Number(event.target.value) } }) }) })] }), _jsx(Labeled, { label: w("editor.criteria"), hint: draft.planner ? w("editor.criteriaPlannerHint") : w("editor.criteriaHint"), wide: true, children: _jsx("textarea", { className: "wf-input wf-textarea", value: step.judge.criteria ?? "", maxLength: 2000, onChange: (event) => setStep(index, { judge: { ...step.judge, criteria: event.target.value } }) }) })] })) : null] }), images.length ? (_jsxs("div", { className: "wf-box", children: [_jsxs("div", { className: "wf-box-head", children: [_jsx("strong", { children: w("editor.images") }), _jsx("span", { className: "wf-muted", children: w("editor.imagesHint") })] }), images.map((field) => {
128
+ const config = (step.images ?? []).find((image) => image.field === field.name);
129
+ const setImage = (patch) => setStep(index, { images: [...(step.images ?? []).filter((image) => image.field !== field.name), ...(patch === null ? [] : [{ field: field.name, artists: [], style: "", aspectRatio: "16:9", ...config, ...patch }])] });
130
+ return (_jsxs("div", { className: "wf-image", children: [_jsxs("label", { className: "wf-check", children: [_jsx("input", { type: "checkbox", checked: Boolean(config), onChange: (event) => setImage(event.target.checked ? { artists: draft.agents.filter((agent) => agentTasks(agent).includes("image")).map((agent) => agent.id).slice(0, 1) } : null) }), field.label ?? field.name] }), config ? (_jsxs(_Fragment, { children: [_jsx(AgentToggles, { agents: draft.agents, value: config.artists, onChange: (artists) => setImage({ artists }) }), _jsxs("div", { className: "wf-grid-3", children: [_jsx(Labeled, { label: w("editor.style"), wide: true, children: _jsx("input", { className: "wf-input", value: config.style ?? "", maxLength: 1000, placeholder: w("editor.stylePlaceholder"), onChange: (event) => setImage({ style: event.target.value }) }) }), _jsx(Labeled, { label: w("editor.aspect"), children: _jsx("select", { className: "wf-input", value: config.aspectRatio ?? "16:9", onChange: (event) => setImage({ aspectRatio: event.target.value }), children: ["1:1", "16:9", "4:3", "3:2", "2:3", "9:16"].map((ratio) => _jsx("option", { value: ratio, children: ratio }, ratio)) }) })] })] })) : null] }, field.name));
131
+ })] })) : null] }, index));
132
+ }) }), _jsx(Section, { id: "reliability", title: w("editor.reliability"), hint: w("editor.reliabilityHint"), children: _jsxs("div", { className: "wf-grid-3", children: [_jsx(Labeled, { label: w("editor.attempts"), hint: w("editor.attemptsHint"), children: _jsx("input", { className: "wf-input", type: "number", min: 1, max: 6, value: draft.retry?.attempts ?? 3, onChange: (event) => update((value) => ({ ...value, retry: { attempts: Number(event.target.value) || 1, backoffSeconds: value.retry?.backoffSeconds ?? 4 } })) }) }), _jsx(Labeled, { label: w("editor.backoff"), hint: w("editor.backoffHint"), children: _jsx("input", { className: "wf-input", type: "number", min: 0, max: 120, value: draft.retry?.backoffSeconds ?? 4, onChange: (event) => update((value) => ({ ...value, retry: { attempts: value.retry?.attempts ?? 3, backoffSeconds: Number(event.target.value) || 0 } })) }) }), _jsx(Labeled, { label: w("editor.concurrency"), hint: w("editor.concurrencyHint"), children: _jsx("input", { className: "wf-input", type: "number", min: 1, max: 6, value: draft.concurrency ?? 2, onChange: (event) => update((value) => ({ ...value, concurrency: Number(event.target.value) || 1 })) }) }), _jsx(Labeled, { label: w("editor.saveAs"), children: _jsxs("select", { className: "wf-input", value: draft.status ?? "draft", onChange: (event) => update((value) => ({ ...value, status: event.target.value })), children: [_jsx("option", { value: "draft", children: w("editor.drafts") }), _jsx("option", { value: "published", children: w("editor.published") })] }) }), _jsx(Labeled, { label: w("editor.actsAs"), hint: catalog.chooseRole ? w("editor.actsAsHint") : w("editor.actsAsAdmin"), children: _jsxs("select", { className: "wf-input", value: draft.actsAs ?? "", disabled: !catalog.chooseRole, onChange: (event) => update((value) => ({ ...value, actsAs: event.target.value || undefined })), children: [_jsx("option", { value: "", children: w("editor.actsAsDefault", { role: catalog.roles?.find((role) => role.name === catalog.defaultRole)?.label ?? catalog.defaultRole ?? "" }) }), (catalog.roles ?? []).map((role) => _jsx("option", { value: role.name, title: role.description, children: role.label }, role.name)), draft.actsAs && !catalog.roles?.some((role) => role.name === draft.actsAs) ? _jsx("option", { value: draft.actsAs, children: draft.actsAs }) : null] }) })] }) })] })] })] }));
133
+ }
@@ -0,0 +1,232 @@
1
+ import type { PluginStore } from "tansy/plugin";
2
+ import { type DescribedField } from "../logic";
3
+ import type { AiProvider, AiSettings } from "../provider";
4
+ import { type Workflow } from "./schema";
5
+ /**
6
+ * Runs workflows. A run is a list of tasks — plan, outline, write, image — that the engine
7
+ * works through a few at a time, saving after each, so a run survives a restart: whichever
8
+ * server holds the run's lease picks it up where it was. Everything a run writes stays in
9
+ * the plugin's store until a person reviews it and creates the records (see commit()).
10
+ */
11
+ /** A field as describe_collection gives it, with the blocks a stream field takes. */
12
+ export type RunField = DescribedField & {
13
+ blocks?: Array<{
14
+ name: string;
15
+ fields: Array<{
16
+ name: string;
17
+ type: string;
18
+ }>;
19
+ }>;
20
+ };
21
+ export interface RunCollection {
22
+ slug: string;
23
+ name: string;
24
+ fields: RunField[];
25
+ }
26
+ /**
27
+ * What a writer is asked for: every field AI can fill, and stream fields with a text block
28
+ * as Markdown, which become that block. Blocks' own JSON is too easy for a model to get wrong.
29
+ */
30
+ export declare function writeSchema(fields: RunField[]): {
31
+ properties: Record<string, unknown>;
32
+ type: "object";
33
+ additionalProperties: false;
34
+ };
35
+ export declare function writeValues(fields: RunField[], output: unknown): Record<string, unknown>;
36
+ export type TaskKind = "plan" | "outline" | "write" | "image";
37
+ export type TaskStatus = "pending" | "running" | "done" | "failed" | "cancelled";
38
+ export interface RunTask {
39
+ id: string;
40
+ kind: TaskKind;
41
+ step?: string;
42
+ /** For an outline: the parent item its records belong to. */
43
+ parent?: string;
44
+ /** For write and image: the item. */
45
+ item?: string;
46
+ /** For image: the field. */
47
+ field?: string;
48
+ status: TaskStatus;
49
+ attempts: number;
50
+ /** The agent whose answer was used. */
51
+ agent?: string;
52
+ error?: string;
53
+ startedAt?: string;
54
+ endedAt?: string;
55
+ }
56
+ export type ItemStatus = "planned" | "ready" | "failed";
57
+ export interface RunItem {
58
+ id: string;
59
+ step: string;
60
+ parent?: string;
61
+ index: number;
62
+ title: string;
63
+ /** What the outline said this record should cover. */
64
+ brief: string;
65
+ status: ItemStatus;
66
+ /** The agent whose draft was kept. */
67
+ agent?: string;
68
+ score?: number;
69
+ feedback?: string;
70
+ /** How many times the judge sent it back. */
71
+ revisions?: number;
72
+ /** Image field name → stored image id. */
73
+ images: Record<string, string>;
74
+ /** Set once the record is created. */
75
+ recordId?: number;
76
+ error?: string;
77
+ }
78
+ export interface LogEntry {
79
+ at: string;
80
+ level: "info" | "warn" | "error";
81
+ message: string;
82
+ }
83
+ /** What the planner wrote: a shared style guide, and each agent's own prompt for each step. */
84
+ export interface Plan {
85
+ guide: string;
86
+ steps: Record<string, {
87
+ rubric: string;
88
+ prompts: Record<string, string>;
89
+ }>;
90
+ }
91
+ export type RunStatus = "running" | "review" | "done" | "failed" | "cancelled";
92
+ export interface Run {
93
+ id: string;
94
+ workflow: Workflow;
95
+ inputs: Record<string, string>;
96
+ collections: Record<string, RunCollection>;
97
+ status: RunStatus;
98
+ createdBy: {
99
+ id: string;
100
+ name: string;
101
+ };
102
+ createdAt: string;
103
+ updatedAt: string;
104
+ plan?: Plan;
105
+ tasks: RunTask[];
106
+ items: RunItem[];
107
+ log: LogEntry[];
108
+ usage: {
109
+ inputTokens: number;
110
+ outputTokens: number;
111
+ calls: number;
112
+ images: number;
113
+ };
114
+ error?: string;
115
+ }
116
+ export interface RunSummary {
117
+ id: string;
118
+ workflowId: string;
119
+ workflowName: string;
120
+ status: RunStatus;
121
+ createdBy: string;
122
+ createdAt: string;
123
+ updatedAt: string;
124
+ items: number;
125
+ ready: number;
126
+ created: number;
127
+ }
128
+ export declare const MAX_ITEMS = 300;
129
+ export declare const RUN_ID: RegExp;
130
+ export declare const ITEM_ID: RegExp;
131
+ export declare const newId: (length?: number) => string;
132
+ export interface EngineDeps {
133
+ store: PluginStore;
134
+ settings(): Promise<AiSettings>;
135
+ providers: AiProvider[];
136
+ /** Waits between attempts. Tests make it instant. */
137
+ sleep?(ms: number): Promise<void>;
138
+ }
139
+ /** The most records a workflow can make in one run: each step's most, times its parents'. */
140
+ export declare function maxItems(workflow: Workflow): number;
141
+ export declare function summaryOf(run: Run): RunSummary;
142
+ export declare function runStore(store: PluginStore): {
143
+ get(id: string): Promise<Run | null>;
144
+ save(run: Run): Promise<void>;
145
+ list(): Promise<RunSummary[]>;
146
+ values(run: string, item: string): Promise<Record<string, unknown> | null>;
147
+ setValues(run: string, item: string, values: Record<string, unknown>): Promise<void>;
148
+ /** A picture, kept in pieces under the store's size a value. */
149
+ putImage(run: string, bytes: Uint8Array, mediaType: string): Promise<string>;
150
+ image(run: string, id: string): Promise<{
151
+ bytes: Buffer;
152
+ mediaType: string;
153
+ } | null>;
154
+ remove(run: Run): Promise<void>;
155
+ };
156
+ export declare const activeRuns: (store: PluginStore) => Promise<string[]>;
157
+ /** Asks a running run to stop. The engine reads it between tasks. */
158
+ export declare const requestCancel: (store: PluginStore, id: string) => Promise<void>;
159
+ /** Whether a server is working on the run right now. */
160
+ export declare function isDriven(store: PluginStore, id: string): Promise<boolean>;
161
+ export declare function createRun(input: {
162
+ workflow: Workflow;
163
+ inputs: Record<string, string>;
164
+ collections: Record<string, RunCollection>;
165
+ user: {
166
+ id: string;
167
+ name: string;
168
+ };
169
+ }): Run;
170
+ /** Whether trying the same call again could help: timeouts, rate limits, servers' errors, unreadable answers. */
171
+ export declare function retryable(error: unknown): boolean;
172
+ export declare class Engine {
173
+ private readonly deps;
174
+ private readonly runs;
175
+ private readonly providers;
176
+ private readonly sleep;
177
+ private settingsCache?;
178
+ /** When this pass must stop, on a host that stops functions after a time. Null for none. */
179
+ private deadline;
180
+ constructor(deps: EngineDeps);
181
+ private settings;
182
+ private language;
183
+ /** How long the next call may take, inside the deadline. */
184
+ private callMs;
185
+ private outOfTime;
186
+ private log;
187
+ /** One call, tried again with growing waits while trying again could help. */
188
+ private attempt;
189
+ /** Tries each agent in turn, each with its retries, until one answers. */
190
+ private withFallback;
191
+ private ask;
192
+ private agent;
193
+ private step;
194
+ private brief;
195
+ /** The agent's standing instructions: its role, the planner's prompt for it, the site's guidance. */
196
+ private system;
197
+ private fieldsOf;
198
+ /** What a record's parents say, for writing something that fits under them. */
199
+ private lineage;
200
+ private plan;
201
+ private outline;
202
+ /** A draft of one record's values. */
203
+ private draft;
204
+ private score;
205
+ private write;
206
+ private picture;
207
+ private image;
208
+ private perform;
209
+ /** A task can start once the plan is in, and an outline or write once its parent record is written. */
210
+ private ready;
211
+ private acquire;
212
+ /**
213
+ * Works on a run until it's finished, cancelled or another server holds it. Safe to call
214
+ * at any time, from anywhere: only the lease holder works.
215
+ *
216
+ * With a `deadline`, as on a host that stops functions after a time, it starts no task it
217
+ * can't give a minute, cuts calls short at the deadline, and leaves what's left pending for
218
+ * the next pass. The ai-workflows job starts that pass.
219
+ */
220
+ drive(id: string, options?: {
221
+ deadline?: number | null;
222
+ }): Promise<void>;
223
+ }
224
+ /** Starts failed tasks again, and the records whose writing failed. */
225
+ export declare function retryFailed(run: Run): number;
226
+ /** Writes one record again, and draws its pictures again. */
227
+ export declare function regenerate(run: Run, itemId: string): boolean;
228
+ /**
229
+ * The records to create, parents first, each with what it needs from the records created
230
+ * before it. Items left out, failed, or whose parent wasn't created are skipped.
231
+ */
232
+ export declare function commitOrder(run: Run, include: Set<string> | null): RunItem[];