@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,418 @@
1
+ import { z } from "zod";
2
+ import { afterResponse, defineRoute } from "tansy/plugin";
3
+ import { conform, textOf } from "../logic";
4
+ import { catalogOf } from "../models";
5
+ import { checkWorkflow } from "./check";
6
+ import { givesRoles, roleFor } from "../role";
7
+ import { activeRuns, commitOrder, createRun, Engine, isDriven, ITEM_ID, MAX_ITEMS, maxItems, regenerate, requestCancel, retryFailed, RUN_ID, runStore, summaryOf } from "./engine";
8
+ import { WORKFLOW_ID, workflowSchema } from "./schema";
9
+ /** Building, running and reviewing workflows. They choose which paid models run, so they have their own permission. */
10
+ export const WORKFLOWS = "ext.ai:workflows";
11
+ const refuse = (status, code, message, details) => Response.json({ error: { code, message, ...(details ? { details } : {}) } }, { status });
12
+ const workflowKey = (id) => `workflow/${id}`;
13
+ const isWorkflow = (value) => Boolean(value && typeof value === "object" && Array.isArray(value.steps));
14
+ async function workflows(store) {
15
+ return (await store.list("workflow/")).flatMap(({ value }) => (isWorkflow(value) ? [{ id: value.id, name: value.name, description: value.description, agents: value.agents.length, steps: value.steps.length, updatedAt: value.updatedAt, updatedBy: value.updatedBy }] : []))
16
+ .sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));
17
+ }
18
+ const userOf = (context) => (context.principal.kind === "user" ? { id: context.principal.user.id, name: context.principal.user.name || context.principal.user.email } : null);
19
+ const engineFor = (context, providers) => new Engine({ store: context.store, settings: async () => (await context.settings.get()), providers });
20
+ /** Starts working on a run in this server, and logs rather than throws: the job picks it up again if this stops. */
21
+ /** Starts work on a run after the response. Where functions stop after a time, it pauses before then and a background pass carries on. */
22
+ const kick = (context, providers, id) => afterResponse("ai", (pass) => engineFor(context, providers).drive(id, { deadline: pass.deadline }));
23
+ const runParam = (context) => (RUN_ID.test(context.params.id) ? context.params.id : null);
24
+ /** One lock for creating a run's records, so a double click can't create them twice. Stale after ten minutes. */
25
+ async function lockCommit(store, id) {
26
+ const key = `commit/${id}`;
27
+ const held = (await store.get(key));
28
+ if (held && Date.now() - held.at > 10 * 60_000)
29
+ await store.delete(key);
30
+ return (await store.claim(key, { at: Date.now() })) ? () => store.delete(key) : null;
31
+ }
32
+ /** A record's values as text: rich text and blocks as Markdown, everything else as written. */
33
+ function preview(values) {
34
+ const text = (value) => {
35
+ if (Array.isArray(value))
36
+ return value.map((entry) => (entry && typeof entry === "object" && "value" in entry ? Object.values(entry.value ?? {}).map(text).filter(Boolean).join("\n\n") : text(entry))).filter(Boolean).join("\n\n");
37
+ if (value && typeof value === "object")
38
+ return textOf(value);
39
+ return value === null || value === undefined ? "" : String(value);
40
+ };
41
+ return Object.fromEntries(Object.entries(values).map(([name, value]) => [name, text(value).slice(0, 20_000)]));
42
+ }
43
+ const IMAGE_TYPES = new Set(["image/png", "image/jpeg", "image/webp", "image/gif"]);
44
+ export function workflowRoutes(providers) {
45
+ const describe = async (context, slug) => {
46
+ const collection = (await context.tools.call("describe_collection", { collection: slug }));
47
+ return { slug: collection.slug, name: collection.name, fields: collection.fields };
48
+ };
49
+ return [
50
+ defineRoute({
51
+ method: "GET",
52
+ path: "/workflows",
53
+ access: "permission",
54
+ permission: WORKFLOWS,
55
+ handler: async (context) => ({ workflows: await workflows(context.store), runs: (await runStore(context.store).list()).slice(0, 50) }),
56
+ }),
57
+ defineRoute({
58
+ method: "GET",
59
+ path: "/workflows/catalog",
60
+ access: "permission",
61
+ permission: WORKFLOWS,
62
+ rateLimit: { window: 60, max: 30 },
63
+ handler: async (context) => {
64
+ // Providers' models with what each can do, and the collections the person can read. Never a key.
65
+ const settings = (await context.settings.get());
66
+ // Only someone who may give people roles may give a workflow one.
67
+ const chooseRole = givesRoles(context.principal);
68
+ const [catalog, collections, roles] = await Promise.all([catalogOf(providers, settings), context.tools.call("list_collections", {}), chooseRole ? context.tools.roles() : []]);
69
+ return { ...catalog, collections, roles, chooseRole, defaultRole: roleFor(settings) };
70
+ },
71
+ }),
72
+ defineRoute({
73
+ method: "GET",
74
+ path: "/workflows/collections/:slug",
75
+ access: "permission",
76
+ permission: WORKFLOWS,
77
+ handler: async (context) => describe(context, context.params.slug),
78
+ }),
79
+ defineRoute({
80
+ method: "GET",
81
+ path: "/workflows/:id",
82
+ access: "permission",
83
+ permission: WORKFLOWS,
84
+ handler: async (context) => {
85
+ const value = WORKFLOW_ID.test(context.params.id) ? await context.store.get(workflowKey(context.params.id)) : null;
86
+ return isWorkflow(value) ? { workflow: value } : refuse(404, "NOT_FOUND", "There's no such workflow.");
87
+ },
88
+ }),
89
+ defineRoute({
90
+ method: "PUT",
91
+ path: "/workflows/:id",
92
+ access: "permission",
93
+ permission: WORKFLOWS,
94
+ audit: "ai.workflow.save",
95
+ body: z.unknown(),
96
+ handler: async (context) => {
97
+ const parsed = workflowSchema.safeParse(context.body);
98
+ if (!parsed.success)
99
+ return refuse(400, "VALIDATION_FAILED", parsed.error.issues[0]?.message ?? "The workflow isn't valid.", parsed.error.issues.map((issue) => ({ path: issue.path.join("."), message: issue.message })));
100
+ if (parsed.data.id !== context.params.id)
101
+ return refuse(400, "BAD_REQUEST", "The workflow's id doesn't match its address.");
102
+ const stored = await context.store.get(workflowKey(parsed.data.id));
103
+ if ((parsed.data.actsAs ?? "") !== ((isWorkflow(stored) && stored.actsAs) || "") && !givesRoles(context.principal)) {
104
+ return refuse(403, "FORBIDDEN", "Only someone who may give people roles may choose the role a workflow creates records with.");
105
+ }
106
+ if (maxItems(parsed.data) > MAX_ITEMS)
107
+ return refuse(400, "TOO_LARGE", `This workflow could make up to ${maxItems(parsed.data)} records. A run makes at most ${MAX_ITEMS}: lower the counts.`);
108
+ const user = userOf(context);
109
+ const workflow = { ...parsed.data, updatedAt: new Date().toISOString(), updatedBy: user?.name ?? "" };
110
+ context.auditTarget("ai-workflow", workflow.id, { agents: workflow.agents.map((agent) => `${agent.provider}/${agent.model}`) });
111
+ await context.store.set(workflowKey(workflow.id), workflow);
112
+ const settings = (await context.settings.get());
113
+ return { workflow, problems: checkWorkflow(workflow, await catalogOf(providers, settings)) };
114
+ },
115
+ }),
116
+ defineRoute({
117
+ method: "DELETE",
118
+ path: "/workflows/:id",
119
+ access: "permission",
120
+ permission: WORKFLOWS,
121
+ audit: "ai.workflow.delete",
122
+ handler: async (context) => {
123
+ if (!WORKFLOW_ID.test(context.params.id))
124
+ return refuse(404, "NOT_FOUND", "There's no such workflow.");
125
+ context.auditTarget("ai-workflow", context.params.id);
126
+ await context.store.delete(workflowKey(context.params.id));
127
+ return { deleted: true };
128
+ },
129
+ }),
130
+ defineRoute({
131
+ method: "POST",
132
+ path: "/workflows/:id/runs",
133
+ access: "permission",
134
+ permission: WORKFLOWS,
135
+ audit: "ai.workflow.run",
136
+ rateLimit: { window: 60, max: 10 },
137
+ body: z.object({ inputs: z.record(z.string(), z.string().max(8000)).default({}) }),
138
+ handler: async (context) => {
139
+ const user = userOf(context);
140
+ const stored = WORKFLOW_ID.test(context.params.id) ? await context.store.get(workflowKey(context.params.id)) : null;
141
+ if (!user || !isWorkflow(stored))
142
+ return refuse(404, "NOT_FOUND", "There's no such workflow.");
143
+ // Stored workflows are checked again: a plugin upgrade may have changed the shape.
144
+ const parsed = workflowSchema.safeParse(stored);
145
+ if (!parsed.success)
146
+ return refuse(400, "VALIDATION_FAILED", "Open the workflow and save it again: it needs changes.");
147
+ const workflow = parsed.data;
148
+ const missing = workflow.inputs.find((input) => input.required && !context.body.inputs[input.name]?.trim());
149
+ if (missing)
150
+ return refuse(400, "VALIDATION_FAILED", `Fill in "${missing.label}".`);
151
+ const settings = (await context.settings.get());
152
+ const problems = checkWorkflow(workflow, await catalogOf(providers, settings)).filter((problem) => problem.level === "error");
153
+ if (problems.length)
154
+ return refuse(400, "WORKFLOW_PROBLEMS", problems[0].message, problems);
155
+ // Read as the person, so a run only ever sees fields they may see.
156
+ const collections = {};
157
+ for (const slug of new Set(workflow.steps.map((step) => step.collection)))
158
+ collections[slug] = await describe(context, slug);
159
+ const inputs = Object.fromEntries(workflow.inputs.map((input) => [input.name, (context.body.inputs[input.name] ?? "").trim()]));
160
+ const run = createRun({ workflow, inputs, collections, user });
161
+ await runStore(context.store).save(run);
162
+ context.auditTarget("ai-workflow-run", run.id, { workflow: workflow.id });
163
+ kick(context, providers, run.id);
164
+ return { run: summaryOf(run) };
165
+ },
166
+ }),
167
+ defineRoute({
168
+ method: "GET",
169
+ path: "/runs/:id",
170
+ access: "permission",
171
+ permission: WORKFLOWS,
172
+ query: z.object({ values: z.enum(["1"]).optional() }),
173
+ handler: async (context) => {
174
+ const id = runParam(context);
175
+ const runs = runStore(context.store);
176
+ const run = id ? await runs.get(id) : null;
177
+ if (!run)
178
+ return refuse(404, "NOT_FOUND", "There's no such run.");
179
+ // For reading in the review: each value as text, rich text and blocks as Markdown.
180
+ const values = context.query.values ? Object.fromEntries(await Promise.all(run.items.filter((item) => item.status === "ready").map(async (item) => [item.id, preview((await runs.values(run.id, item.id)) ?? {})]))) : undefined;
181
+ return { run, driving: await isDriven(context.store, run.id), ...(values ? { values } : {}) };
182
+ },
183
+ }),
184
+ defineRoute({
185
+ method: "GET",
186
+ path: "/runs/:id/images/:image",
187
+ access: "permission",
188
+ permission: WORKFLOWS,
189
+ handler: async (context) => {
190
+ const id = runParam(context);
191
+ const image = id && ITEM_ID.test(context.params.image) ? await runStore(context.store).image(id, context.params.image) : null;
192
+ if (!image)
193
+ return refuse(404, "NOT_FOUND", "There's no such picture.");
194
+ // Only pictures, never anything a browser would run.
195
+ const type = IMAGE_TYPES.has(image.mediaType) ? image.mediaType : "application/octet-stream";
196
+ return new Response(new Uint8Array(image.bytes), { headers: { "content-type": type, "cache-control": "private, max-age=3600", "x-content-type-options": "nosniff", "content-security-policy": "default-src 'none'" } });
197
+ },
198
+ }),
199
+ defineRoute({
200
+ method: "POST",
201
+ path: "/runs/:id/cancel",
202
+ access: "permission",
203
+ permission: WORKFLOWS,
204
+ audit: "ai.workflow.cancel",
205
+ handler: async (context) => {
206
+ const id = runParam(context);
207
+ const runs = runStore(context.store);
208
+ const run = id ? await runs.get(id) : null;
209
+ if (!run)
210
+ return refuse(404, "NOT_FOUND", "There's no such run.");
211
+ context.auditTarget("ai-workflow-run", run.id);
212
+ if (run.status !== "running")
213
+ return { run: summaryOf(run) };
214
+ if (await isDriven(context.store, run.id)) {
215
+ await requestCancel(context.store, run.id);
216
+ return { cancelling: true };
217
+ }
218
+ for (const task of run.tasks)
219
+ if (task.status === "pending" || task.status === "running")
220
+ task.status = "cancelled";
221
+ run.status = "cancelled";
222
+ await runs.save(run);
223
+ return { run: summaryOf(run) };
224
+ },
225
+ }),
226
+ defineRoute({
227
+ method: "POST",
228
+ path: "/runs/:id/retry",
229
+ access: "permission",
230
+ permission: WORKFLOWS,
231
+ audit: "ai.workflow.retry",
232
+ rateLimit: { window: 60, max: 20 },
233
+ handler: async (context) => {
234
+ const id = runParam(context);
235
+ const runs = runStore(context.store);
236
+ const run = id ? await runs.get(id) : null;
237
+ if (!run)
238
+ return refuse(404, "NOT_FOUND", "There's no such run.");
239
+ if (run.status === "running" || (await isDriven(context.store, run.id)))
240
+ return refuse(409, "BUSY", "The run is still working. Wait for it to finish, or cancel it.");
241
+ if (!retryFailed(run))
242
+ return refuse(400, "NOTHING_TO_RETRY", "Nothing failed.");
243
+ context.auditTarget("ai-workflow-run", run.id);
244
+ await runs.save(run);
245
+ kick(context, providers, run.id);
246
+ return { run: summaryOf(run) };
247
+ },
248
+ }),
249
+ defineRoute({
250
+ method: "POST",
251
+ path: "/runs/:id/items/:item/regenerate",
252
+ access: "permission",
253
+ permission: WORKFLOWS,
254
+ audit: "ai.workflow.regenerate",
255
+ rateLimit: { window: 60, max: 30 },
256
+ handler: async (context) => {
257
+ const id = runParam(context);
258
+ const runs = runStore(context.store);
259
+ const run = id ? await runs.get(id) : null;
260
+ if (!run)
261
+ return refuse(404, "NOT_FOUND", "There's no such run.");
262
+ if (run.status === "running" || (await isDriven(context.store, run.id)))
263
+ return refuse(409, "BUSY", "The run is still working. Wait for it to finish.");
264
+ if (!regenerate(run, context.params.item))
265
+ return refuse(400, "NOT_REGENERABLE", "That record is gone or already created.");
266
+ context.auditTarget("ai-workflow-run", run.id, { item: context.params.item });
267
+ await runs.save(run);
268
+ kick(context, providers, run.id);
269
+ return { run: summaryOf(run) };
270
+ },
271
+ }),
272
+ defineRoute({
273
+ method: "POST",
274
+ path: "/runs/:id/commit",
275
+ access: "permission",
276
+ permission: WORKFLOWS,
277
+ audit: "ai.workflow.commit",
278
+ rateLimit: { window: 60, max: 10 },
279
+ body: z.object({
280
+ /** The items to create. All that are ready when left out. */
281
+ include: z.array(z.string().regex(ITEM_ID)).max(1000).optional(),
282
+ /** Pictures the person uploaded, by the run's picture id: the file ids the image fields take. */
283
+ files: z.record(z.string().regex(ITEM_ID), z.string().min(1).max(64)).default({}),
284
+ }),
285
+ handler: async (context) => {
286
+ const id = runParam(context);
287
+ const runs = runStore(context.store);
288
+ const run = id ? await runs.get(id) : null;
289
+ if (!run)
290
+ return refuse(404, "NOT_FOUND", "There's no such run.");
291
+ if (run.status === "running")
292
+ return refuse(409, "BUSY", "The run is still working. Wait for it to finish.");
293
+ const unlock = await lockCommit(context.store, run.id);
294
+ if (!unlock)
295
+ return refuse(409, "BUSY", "These records are being created already.");
296
+ // As the person, limited to what the workflow's role also grants.
297
+ const role = run.workflow.actsAs || roleFor((await context.settings.get()));
298
+ let tools;
299
+ try {
300
+ tools = await context.tools.withRole(role);
301
+ }
302
+ catch {
303
+ await unlock();
304
+ return refuse(400, "AI_ROLE_MISSING", `The workflow's role "${role}" doesn't exist any more. Choose another in the workflow or under AI → Settings.`);
305
+ }
306
+ context.auditTarget("ai-workflow-run", run.id, { role });
307
+ const created = [];
308
+ try {
309
+ const ids = new Map(run.items.map((item) => [item.id, item.recordId]));
310
+ // Each collection's fields as they are now, to fix or drop values a model wrote that the fields don't take.
311
+ const current = new Map();
312
+ const fieldsOf = (slug) => {
313
+ if (!current.has(slug))
314
+ current.set(slug, describe(context, slug).then((collection) => new Map(collection.fields.map((field) => [field.name, field]))).catch(() => new Map()));
315
+ return current.get(slug);
316
+ };
317
+ for (const item of commitOrder(run, context.body.include ? new Set(context.body.include) : null)) {
318
+ if (item.recordId)
319
+ continue;
320
+ const step = run.workflow.steps.find((entry) => entry.id === item.step);
321
+ const fields = await fieldsOf(step.collection);
322
+ const data = { status: run.workflow.status };
323
+ for (const [name, value] of Object.entries((await runs.values(run.id, item.id)) ?? {})) {
324
+ const field = fields.get(name);
325
+ const kept = field && field.type !== "stream" ? conform(field, value) : value;
326
+ if (kept !== undefined)
327
+ data[name] = kept;
328
+ }
329
+ if (step.link && item.parent) {
330
+ const parent = ids.get(item.parent);
331
+ if (!parent)
332
+ continue;
333
+ data[step.link] = parent;
334
+ }
335
+ for (const link of step.links) {
336
+ let above = run.items.find((entry) => entry.id === item.parent);
337
+ while (above && above.step !== link.step)
338
+ above = run.items.find((entry) => entry.id === above.parent);
339
+ const record = above && ids.get(above.id);
340
+ if (record)
341
+ data[link.field] = record;
342
+ }
343
+ if (step.orderField)
344
+ data[step.orderField] = item.index + 1;
345
+ for (const [field, image] of Object.entries(item.images))
346
+ if (context.body.files[image])
347
+ data[field] = context.body.files[image];
348
+ // Through the same tool the assistant uses: the person's rules and validation apply.
349
+ try {
350
+ const record = (await tools.call("create_record", { collection: step.collection, data }));
351
+ item.recordId = record.id;
352
+ ids.set(item.id, record.id);
353
+ created.push({ item: item.id, collection: step.collection, id: record.id });
354
+ }
355
+ catch (error) {
356
+ const known = error;
357
+ // Name the fields that were refused: "Request validation failed." alone doesn't say what to fix.
358
+ const fields = Array.isArray(known.details) ? known.details.flatMap((issue) => (issue && typeof issue.message === "string" ? [`${typeof issue.path === "string" && issue.path ? `${issue.path}: ` : ""}${issue.message}`] : [])).slice(0, 5).join("; ") : "";
359
+ const reason = `${known.message ?? "it was refused."}${fields ? ` ${fields}` : ""}`;
360
+ run.log.push({ at: new Date().toISOString(), level: "error", message: `Creating "${item.title}" failed: ${reason.slice(0, 400)}` });
361
+ await runs.save(run);
362
+ return refuse(400, "COMMIT_FAILED", `Creating "${item.title}" failed: ${reason}`, { created, details: known.details });
363
+ }
364
+ }
365
+ if (commitOrder(run, null).every((item) => item.recordId))
366
+ run.status = "done";
367
+ run.log.push({ at: new Date().toISOString(), level: "info", message: `${userOf(context)?.name ?? "Someone"} created ${created.length} record(s).` });
368
+ await runs.save(run);
369
+ return { created, run: summaryOf(run) };
370
+ }
371
+ finally {
372
+ await unlock();
373
+ }
374
+ },
375
+ }),
376
+ defineRoute({
377
+ method: "DELETE",
378
+ path: "/runs/:id",
379
+ access: "permission",
380
+ permission: WORKFLOWS,
381
+ audit: "ai.workflow.run.delete",
382
+ handler: async (context) => {
383
+ const id = runParam(context);
384
+ const runs = runStore(context.store);
385
+ const run = id ? await runs.get(id) : null;
386
+ if (!run)
387
+ return refuse(404, "NOT_FOUND", "There's no such run.");
388
+ if (await isDriven(context.store, run.id))
389
+ return refuse(409, "BUSY", "Cancel the run first.");
390
+ context.auditTarget("ai-workflow-run", run.id);
391
+ await runs.remove(run);
392
+ return { deleted: true };
393
+ },
394
+ }),
395
+ ];
396
+ }
397
+ /**
398
+ * Picks up runs a stopped server left, once a minute. Each run is worked on by one server at a
399
+ * time. Where background work runs in passes with a deadline, as on Vercel, this is what moves
400
+ * runs on: each pass works on them until just before its deadline, and the next carries on.
401
+ */
402
+ export function workflowJob(providers) {
403
+ return {
404
+ name: "ai-workflows",
405
+ cron: "* * * * *",
406
+ // Runs live in the store of the tenant they started in, so each tenant's are picked up in its own.
407
+ perScope: true,
408
+ handler: async (context, pass) => {
409
+ const idle = [];
410
+ for (const id of await activeRuns(context.store))
411
+ if (!(await isDriven(context.store, id)))
412
+ idle.push(id);
413
+ if (pass.deadline === null)
414
+ return void idle.forEach((id) => kick(context, providers, id));
415
+ await Promise.all(idle.map((id) => engineFor(context, providers).drive(id, { deadline: pass.deadline }).catch((error) => console.error("[ai] a workflow run failed", error))));
416
+ },
417
+ };
418
+ }
@@ -0,0 +1,8 @@
1
+ export declare function StatusPill({ status }: {
2
+ status: string;
3
+ }): import("react").JSX.Element;
4
+ export declare function RunView({ id, onBack, onEdit }: {
5
+ id: string;
6
+ onBack: () => void;
7
+ onEdit: (workflow: string) => void;
8
+ }): import("react").JSX.Element;
@@ -0,0 +1,162 @@
1
+ "use client";
2
+ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
3
+ import { PageSkeleton, useT } from "tansy/admin";
4
+ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
5
+ import { Markdown } from "../markdown";
6
+ import { Chevron, Retry, Trash } from "../parts";
7
+ import { ApiError, cancelRun, commitRun, deleteRun, imageUrl, loadRun, regenerateItem, retryRun, uploadImage } from "./client";
8
+ import { ModelIcon } from "./icons";
9
+ const POLL_MS = 2000;
10
+ export function StatusPill({ status }) {
11
+ const { t } = useT();
12
+ return _jsxs("span", { className: `wf-status wf-status-${status}`, children: [status === "running" ? _jsx("span", { className: "wf-pulse" }) : null, t(`ext.ai.workflows.status.${status}`)] });
13
+ }
14
+ const time = (iso) => new Date(iso).toLocaleTimeString(undefined, { hour: "2-digit", minute: "2-digit", second: "2-digit" });
15
+ const compact = (value) => new Intl.NumberFormat(undefined, { notation: "compact" }).format(value);
16
+ /** One record the run is writing, as a card on its step's lane. */
17
+ function ItemCard({ run, item, task }) {
18
+ const { t } = useT();
19
+ const agent = run.workflow.agents.find((entry) => entry.id === (item.agent ?? task?.agent));
20
+ const step = run.workflow.steps.find((entry) => entry.id === item.step);
21
+ const working = task?.status === "running";
22
+ const state = working ? "writing" : item.status;
23
+ const passed = item.score !== undefined && step?.judge ? item.score >= step.judge.minScore : undefined;
24
+ return (_jsxs("div", { className: `wf-card wf-card-${state}`, title: item.error ?? item.brief, children: [_jsxs("div", { className: "wf-card-top", children: [agent ? _jsx(ModelIcon, { model: agent.model, provider: agent.provider, size: 14 }) : _jsx("span", { className: "wf-dot" }), _jsx("span", { className: "wf-card-title", children: item.title })] }), _jsxs("div", { className: "wf-card-meta", children: [_jsx("span", { className: `wf-card-state wf-card-state-${state}`, children: t(`ext.ai.workflows.item.${state}`) }), item.score !== undefined ? _jsxs("span", { className: `wf-score${passed === false ? " is-low" : ""}`, children: [item.score, "/10"] }) : null, item.revisions ? _jsxs("span", { className: "wf-muted", children: ["\u21BB", item.revisions] }) : null, Object.keys(item.images).length ? _jsxs("span", { className: "wf-muted", children: ["\u25A3", Object.keys(item.images).length] }) : null, item.recordId ? _jsxs("span", { className: "wf-created", children: ["#", item.recordId] }) : null] })] }));
25
+ }
26
+ export function RunView({ id, onBack, onEdit }) {
27
+ const { t } = useT();
28
+ const w = (key, values) => t(`ext.ai.workflows.${key}`, values);
29
+ const [run, setRun] = useState(null);
30
+ const [driving, setDriving] = useState(false);
31
+ const [values, setValues] = useState(null);
32
+ const [error, setError] = useState(null);
33
+ const [busy, setBusy] = useState(null);
34
+ const [excluded, setExcluded] = useState(new Set());
35
+ const [open, setOpen] = useState(new Set());
36
+ const [showPlan, setShowPlan] = useState(false);
37
+ const [notice, setNotice] = useState(null);
38
+ const logRef = useRef(null);
39
+ const refresh = useCallback(async () => {
40
+ try {
41
+ const first = await loadRun(id);
42
+ const settled = first.run.status !== "running" && !first.driving;
43
+ const result = settled ? await loadRun(id, true) : first;
44
+ setRun(result.run);
45
+ setDriving(result.driving);
46
+ if (result.values)
47
+ setValues(result.values);
48
+ setError(null);
49
+ return settled;
50
+ }
51
+ catch (caught) {
52
+ setError(caught instanceof Error ? caught.message : String(caught));
53
+ return true;
54
+ }
55
+ }, [id]);
56
+ useEffect(() => {
57
+ let stopped = false;
58
+ let timer;
59
+ const tick = async () => {
60
+ const settled = await refresh();
61
+ if (!stopped && !settled)
62
+ timer = setTimeout(tick, POLL_MS);
63
+ };
64
+ void tick();
65
+ return () => { stopped = true; clearTimeout(timer); };
66
+ }, [refresh]);
67
+ useEffect(() => { logRef.current?.scrollTo({ top: logRef.current.scrollHeight }); }, [run?.log.length]);
68
+ const act = async (name, action) => {
69
+ setBusy(name);
70
+ setNotice(null);
71
+ try {
72
+ await action();
73
+ // Something started again: follow it.
74
+ let settled = await refresh();
75
+ while (!settled) {
76
+ await new Promise((resolve) => setTimeout(resolve, POLL_MS));
77
+ settled = await refresh();
78
+ }
79
+ }
80
+ catch (caught) {
81
+ setNotice(caught instanceof Error ? caught.message : String(caught));
82
+ }
83
+ finally {
84
+ setBusy(null);
85
+ }
86
+ };
87
+ const tasksByItem = useMemo(() => {
88
+ const map = new Map();
89
+ for (const task of run?.tasks ?? [])
90
+ if (task.item && task.kind === "write")
91
+ map.set(task.item, task);
92
+ return map;
93
+ }, [run]);
94
+ if (error && !run)
95
+ return _jsxs("div", { className: "wf-page", children: [_jsx("p", { className: "wf-problem wf-problem-error", children: error }), _jsxs("button", { type: "button", className: "ai-ghost", onClick: onBack, children: ["\u2190 ", w("title")] })] });
96
+ if (!run)
97
+ return _jsx(PageSkeleton, { kind: "detail" });
98
+ const done = run.tasks.filter((task) => task.status === "done").length;
99
+ const failed = run.tasks.filter((task) => task.status === "failed" || task.status === "cancelled").length;
100
+ const total = run.tasks.length;
101
+ const settled = run.status !== "running" && !driving;
102
+ const ready = run.items.filter((item) => item.status === "ready");
103
+ const toCreate = ready.filter((item) => !item.recordId && !excluded.has(item.id) && (!item.parent || !excluded.has(item.parent)));
104
+ const outlining = run.tasks.filter((task) => task.kind === "outline" && task.status === "running");
105
+ const planning = run.tasks.find((task) => task.kind === "plan");
106
+ // While reviewing, what happened shows in the bar by the button, not at the top of the page.
107
+ const reviewing = settled && ready.length > 0;
108
+ async function create() {
109
+ if (!run)
110
+ return;
111
+ const files = {};
112
+ const include = ready.filter((item) => !excluded.has(item.id)).map((item) => item.id);
113
+ const pictures = toCreate.flatMap((item) => Object.entries(item.images).map(([field, image]) => ({ image, name: `${item.title}-${field}` })));
114
+ for (const [index, picture] of pictures.entries()) {
115
+ setBusy(w("review.uploading", { done: index, total: pictures.length }));
116
+ files[picture.image] = await uploadImage(run.id, picture.image, picture.name);
117
+ }
118
+ setBusy(w("review.creating"));
119
+ const result = await commitRun(run.id, { include, files });
120
+ setNotice(w("review.created", { count: result.created.length }));
121
+ }
122
+ const depthOf = (item) => {
123
+ let depth = 0;
124
+ for (let parent = item.parent; parent && depth < 6; depth++)
125
+ parent = run.items.find((other) => other.id === parent)?.parent;
126
+ return depth;
127
+ };
128
+ const tree = [];
129
+ const visit = (parent) => {
130
+ for (const item of run.items.filter((entry) => entry.parent === parent).sort((a, b) => a.index - b.index)) {
131
+ tree.push(item);
132
+ visit(item.id);
133
+ }
134
+ };
135
+ visit(undefined);
136
+ return (_jsxs("div", { className: "wf-page wf-run", children: [_jsxs("header", { className: "wf-top", children: [_jsxs("button", { type: "button", className: "ai-ghost", onClick: onBack, children: ["\u2190 ", w("title")] }), _jsxs("div", { className: "wf-run-title", children: [_jsx("h1", { children: run.workflow.name }), _jsx("span", { className: "wf-muted", children: w("run.by", { name: run.createdBy.name, time: new Date(run.createdAt).toLocaleString() }) })] }), _jsx(StatusPill, { status: run.status }), run.status === "running" ? _jsx("button", { type: "button", className: "wf-button wf-button-ghost", disabled: Boolean(busy), onClick: () => void act("cancel", () => cancelRun(run.id)), children: w("run.cancel") }) : null, settled && failed ? _jsxs("button", { type: "button", className: "wf-button wf-button-ghost", disabled: Boolean(busy), onClick: () => void act("retry", () => retryRun(run.id)), children: [_jsx(Retry, {}), w("run.retry", { count: failed })] }) : null, _jsx("button", { type: "button", className: "ai-ghost", onClick: () => onEdit(run.workflow.id), children: w("run.edit") }), settled ? _jsx("button", { type: "button", className: "ai-ghost ai-ghost-icon", "aria-label": w("run.delete"), title: w("run.delete"), onClick: () => { if (window.confirm(w("run.deleteConfirm")))
137
+ void deleteRun(run.id).then(onBack).catch((caught) => setNotice(caught.message)); }, children: _jsx(Trash, {}) }) : null] }), _jsxs("div", { className: "wf-stats", children: [_jsxs("div", { className: "wf-progress", role: "progressbar", "aria-valuemin": 0, "aria-valuemax": total, "aria-valuenow": done, children: [_jsx("span", { style: { width: `${total ? (done / total) * 100 : 0}%` } }), failed ? _jsx("span", { className: "wf-progress-failed", style: { width: `${(failed / total) * 100}%` } }) : null] }), _jsxs("dl", { className: "wf-stat-list", children: [_jsxs("div", { children: [_jsx("dt", { children: w("run.tasks") }), _jsxs("dd", { children: [done, "/", total] })] }), _jsxs("div", { children: [_jsx("dt", { children: w("run.records") }), _jsxs("dd", { children: [ready.length, "/", run.items.length] })] }), _jsxs("div", { children: [_jsx("dt", { children: w("run.calls") }), _jsx("dd", { children: run.usage.calls })] }), _jsxs("div", { children: [_jsx("dt", { children: w("run.tokens") }), _jsxs("dd", { children: [compact(run.usage.inputTokens), " \u2192 ", compact(run.usage.outputTokens)] })] }), _jsxs("div", { children: [_jsx("dt", { children: w("run.images") }), _jsx("dd", { children: run.usage.images })] })] })] }), notice && !reviewing ? _jsx("p", { className: "wf-notice", children: notice }) : null, run.error ? _jsx("p", { className: "wf-problem wf-problem-error", children: run.error }) : null, _jsxs("div", { className: "wf-run-grid", children: [_jsxs("div", { className: "wf-lanes", children: [planning ? (_jsxs("div", { className: `wf-lane wf-lane-plan wf-lane-${planning.status}`, children: [_jsxs("button", { type: "button", className: "wf-lane-head", onClick: () => setShowPlan((value) => !value), disabled: !run.plan, children: [_jsx(Chevron, { open: showPlan }), _jsx("strong", { children: w("run.plan") }), _jsx("span", { className: "wf-muted", children: t(`ext.ai.workflows.task.${planning.status}`) })] }), showPlan && run.plan ? (_jsxs("div", { className: "wf-plan", children: [run.plan.guide ? _jsxs(_Fragment, { children: [_jsx("h4", { children: w("run.guide") }), _jsx(Markdown, { text: run.plan.guide })] }) : null, run.workflow.steps.map((step) => {
138
+ const entry = run.plan.steps[step.id];
139
+ if (!entry)
140
+ return null;
141
+ return (_jsxs("div", { className: "wf-plan-step", children: [_jsx("h4", { children: step.name }), Object.entries(entry.prompts).map(([agentId, prompt]) => {
142
+ const agent = run.workflow.agents.find((item) => item.id === agentId);
143
+ return _jsxs("div", { className: "wf-plan-prompt", children: [_jsxs("span", { className: "wf-plan-agent", children: [agent ? _jsx(ModelIcon, { model: agent.model, provider: agent.provider, size: 14 }) : null, agent?.name ?? agentId] }), _jsx("p", { children: prompt })] }, agentId);
144
+ }), entry.rubric ? _jsxs("div", { className: "wf-plan-prompt", children: [_jsxs("span", { className: "wf-plan-agent", children: ["\u2696 ", w("run.rubric")] }), _jsx("p", { children: entry.rubric })] }) : null] }, step.id));
145
+ })] })) : null] })) : null, run.workflow.steps.map((step) => {
146
+ const items = run.items.filter((item) => item.step === step.id);
147
+ const busyOutline = outlining.some((task) => task.step === step.id);
148
+ return (_jsxs("div", { className: "wf-lane", children: [_jsxs("div", { className: "wf-lane-head", children: [_jsx("strong", { children: step.name }), _jsxs("span", { className: "wf-muted", children: [items.filter((item) => item.status === "ready").length, "/", items.length, busyOutline ? ` · ${w("run.outlining")}` : ""] })] }), _jsx("div", { className: "wf-cards", children: items.length ? items.map((item) => _jsx(ItemCard, { run: run, item: item, task: tasksByItem.get(item.id) }, item.id)) : _jsx("p", { className: "wf-muted wf-pad", children: run.status === "running" ? w("run.waiting") : w("run.none") }) })] }, step.id));
149
+ })] }), _jsxs("aside", { className: "wf-log", children: [_jsx("h3", { children: w("run.activity") }), _jsx("ol", { ref: logRef, children: run.log.map((entry, index) => _jsxs("li", { className: `wf-log-${entry.level}`, children: [_jsx("time", { children: time(entry.at) }), entry.message] }, index)) })] })] }), reviewing ? (_jsxs("section", { className: "wf-review", children: [_jsx("header", { className: "wf-section-head", children: _jsxs("div", { children: [_jsx("h2", { children: w("review.title") }), _jsx("p", { className: "wf-muted", children: w("review.hint") })] }) }), _jsx("ul", { className: "wf-tree", children: tree.map((item) => {
150
+ const step = run.workflow.steps.find((entry) => entry.id === item.step);
151
+ const expanded = open.has(item.id);
152
+ const fields = values?.[item.id] ?? {};
153
+ const included = !excluded.has(item.id);
154
+ return (_jsxs("li", { className: `wf-tree-item wf-tree-${item.status}`, style: { marginInlineStart: `${depthOf(item) * 1.5}rem` }, children: [_jsxs("div", { className: "wf-tree-row", children: [_jsx("input", { type: "checkbox", "aria-label": w("review.include"), disabled: item.status !== "ready" || Boolean(item.recordId), checked: item.status === "ready" && (included || Boolean(item.recordId)), onChange: () => setExcluded((value) => { const next = new Set(value); if (next.has(item.id))
155
+ next.delete(item.id);
156
+ else
157
+ next.add(item.id); return next; }) }), _jsxs("button", { type: "button", className: "wf-tree-toggle", onClick: () => setOpen((value) => { const next = new Set(value); if (next.has(item.id))
158
+ next.delete(item.id);
159
+ else
160
+ next.add(item.id); return next; }), children: [_jsx(Chevron, { open: expanded }), _jsx("span", { className: "wf-tree-step", children: step?.name }), _jsx("span", { className: "wf-tree-title", children: item.title })] }), item.score !== undefined ? _jsxs("span", { className: `wf-score${step?.judge && item.score < step.judge.minScore ? " is-low" : ""}`, children: [item.score, "/10"] }) : null, item.recordId ? _jsx("span", { className: "wf-created", children: w("review.createdAs", { id: item.recordId }) }) : null, item.status === "failed" ? _jsx("span", { className: "wf-card-state wf-card-state-failed", children: w("item.failed") }) : null, !item.recordId ? _jsxs("button", { type: "button", className: "ai-ghost", disabled: Boolean(busy), onClick: () => void act("regenerate", () => regenerateItem(run.id, item.id)), children: [_jsx(Retry, {}), w("review.regenerate")] }) : null] }), expanded ? (_jsxs("div", { className: "wf-tree-body", children: [item.error ? _jsx("p", { className: "wf-problem wf-problem-error", children: item.error }) : null, item.feedback ? _jsxs("div", { className: "wf-feedback", children: [_jsxs("strong", { children: ["\u2696 ", w("review.feedback")] }), _jsx("p", { children: item.feedback })] }) : null, Object.keys(item.images).length ? (_jsx("div", { className: "wf-images", children: Object.entries(item.images).map(([field, image]) => (_jsxs("figure", { children: [_jsx("img", { src: imageUrl(run.id, image), alt: `${item.title}: ${field}`, loading: "lazy" }), _jsx("figcaption", { children: field })] }, field))) })) : null, _jsx("dl", { className: "wf-values", children: Object.entries(fields).map(([name, value]) => (_jsxs("div", { children: [_jsx("dt", { children: run.collections[step?.collection ?? ""]?.fields.find((field) => field.name === name)?.label ?? name }), _jsx("dd", { children: value.includes("\n") || value.length > 160 ? _jsx(Markdown, { text: value }) : value })] }, name))) })] })) : null] }, item.id));
161
+ }) }), _jsxs("footer", { className: "wf-review-bar", children: [notice && !busy ? _jsx("span", { className: "wf-notice", role: "status", children: notice }) : null, _jsx("span", { className: "wf-muted", children: busy ?? w("review.summary", { count: toCreate.length, status: w(run.workflow.status === "published" ? "editor.published" : "editor.drafts") }) }), _jsx("button", { type: "button", className: "wf-button", disabled: Boolean(busy) || !toCreate.length, onClick: () => void act("create", create).catch((caught) => setNotice(caught instanceof ApiError ? caught.message : String(caught))), children: w("review.create", { count: toCreate.length }) })] })] })) : null] }));
162
+ }