Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

workflows.ts

1,064 lines40.1 KB

1import { mFallback, msg } from "gt-i18n";
2import type { MFunctionType } from "gt-i18n/types";
3import {
4 type IssueRef,
5 type PullRequestRef,
6 WorkflowIssueAddress,
7 WorkflowPullRequestAddress,
8 WorkflowReferenceKind,
9 type WorkflowQuestion,
10 type WorkflowRun,
11 type WorkflowRunReference,
12 type WorkflowRunsSnapshot,
13 type WorkflowRunSubject,
14 type WorkflowStep,
15 type WorkflowSummary,
16} from "@t3tools/contracts";
17import * as Option from "effect/Option";
18import * as Schema from "effect/Schema";
19import { markdownLinkDestinationScanner } from "@t3tools/shared/markdownLinks";
20import { formatDuration } from "@t3tools/shared/orchestrationTimingCopy";
21import { parseUrl } from "@t3tools/shared/url";
22​
23export interface WorkflowQuestionChoice {
24 readonly value: string;
25 /** What picking it does. */
26 readonly description: string | null;
27 /** The server refuses it without a reason. */
28 readonly requireReason: boolean;
30​
31export interface WorkflowQuestionLink {
32 readonly label: string;
33 readonly url: string;
35​
36export interface WorkflowQuestionView {
37 readonly title: string;
38 readonly choices: ReadonlyArray<WorkflowQuestionChoice>;
39 readonly body: string | null;
40 readonly links: ReadonlyArray<WorkflowQuestionLink>;
42​
43function field(value: unknown, key: string): unknown {
44 return typeof value === "object" && value !== null && !Array.isArray(value)
45 ? (value as Readonly<Record<string, unknown>>)[key]
46 : undefined;
48​
49const text = (value: unknown): string | null =>
50 typeof value === "string" && value.trim() !== "" ? value : null;
51​
52const isWebUrl = (url: string) => {
53 const protocol = parseUrl(url)?.protocol;
54 return protocol === "https:" || protocol === "http:";
55};
56​
57/**
58 * What a question shows. `request` is whatever the workflow handed `ask`, so a part that is
59 * missing or of another shape is left out instead of failing the whole list.
60 */
61export function readWorkflowQuestion(question: WorkflowQuestion): WorkflowQuestionView {
62 const choices = field(question.request, "choices");
63 const details = field(question.request, "choiceDetails");
64 const links = field(question.request, "links");
65 const detailOf = (value: string) =>
66 Array.isArray(details) ? details.find((detail) => field(detail, "value") === value) : undefined;
67 return {
68 title: text(field(question.request, "title")) ?? question.name,
69 choices: Array.isArray(choices)
70 ? choices
71 .filter((choice): choice is string => typeof choice === "string")
72 .map((value) => {
73 const detail = detailOf(value);
74 return {
75 value,
76 description: text(field(detail, "description")),
77 requireReason: field(detail, "requireReason") === true,
78 };
79 })
80 : [],
81 body: text(field(field(question.request, "data"), "body")),
82 links: Array.isArray(links)
83 ? links.flatMap((link) => {
84 const label = text(field(link, "label"));
85 const url = field(link, "url");
86 return label !== null && typeof url === "string" && isWebUrl(url) ? [{ label, url }] : [];
87 })
88 : [],
89 };
91​
92/**
93 * What a run's detail is read again on, out of the live list: the run's last change once it has
94 * ended. Steps do not move a run's `updatedAt`, so one under way is read again on any change.
95 */
96export function workflowRunRefreshKey(
97 snapshot: WorkflowRunsSnapshot | undefined,
98 runId: string,
99): unknown {
100 const run = snapshot?.runs.find((candidate) => candidate.runId === runId);
101 return run === undefined || run.endedAt === null ? snapshot : run.updatedAt;
103​
104export interface WorkflowRunNode {
105 readonly run: WorkflowRun;
106 /** The runs it invoked, in the order they started. */
107 readonly children: ReadonlyArray<WorkflowRunNode>;
108 /** Questions open on this run. */
109 readonly questions: ReadonlyArray<WorkflowQuestion>;
111​
112/** One workflow and the runs of it that nobody has to act on. */
113export interface WorkflowSection {
114 readonly name: string;
115 /** What starts it, in words. Null for a workflow this server no longer has registered. */
116 readonly triggers: ReadonlyArray<string> | null;
117 readonly active: ReadonlyArray<WorkflowRunNode>;
118 readonly finished: ReadonlyArray<WorkflowRunNode>;
119 /** It has runs, and every one was invoked by a run of another workflow. */
120 readonly invokedOnly: boolean;
121 /** It has never run here, as far as the list goes back. */
122 readonly neverRan: boolean;
124​
125export interface WorkflowRunGroups {
126 /** Runs a person has to act on: one has a question open or is paused, itself or below it. */
127 readonly needsYou: ReadonlyArray<WorkflowRunNode>;
128 /** Every workflow there is, busiest first, each with its other runs. */
129 readonly workflows: ReadonlyArray<WorkflowSection>;
131​
132const needsPerson = (node: WorkflowRunNode): boolean =>
133 node.questions.length > 0 || node.run.status === "paused" || node.children.some(needsPerson);
134​
135/**
136 * The list a person reads: what waits on them first, then each workflow with its runs. A run
137 * that another invoked sits under that one, so a piece of work is one entry, and a workflow that
138 * has not run yet is still listed, since the list is also how one learns what exists. `runs` is
139 * newest first and that order is kept.
140 */
141/**
142 * The runs a list shows: without those a workflow skipped as not its to do, unless asked for
143 * them. A skipped run that another run invoked stays, as a step of that one.
144 */
145export function listedWorkflowRuns(
146 runs: ReadonlyArray<WorkflowRun>,
147 showSkipped: boolean,
148): { readonly runs: ReadonlyArray<WorkflowRun>; readonly skipped: number } {
149 const hidden = (run: WorkflowRun) => run.status === "skipped" && run.parentRunId === null;
150 const skipped = runs.filter(hidden).length;
151 return { runs: showSkipped ? runs : runs.filter((run) => !hidden(run)), skipped };
153​
154export function groupWorkflowRuns(
155 workflows: ReadonlyArray<WorkflowSummary>,
156 runs: ReadonlyArray<WorkflowRun>,
157 questions: ReadonlyArray<WorkflowQuestion>,
158): WorkflowRunGroups {
159 const listed = new Set(runs.map((run) => run.runId));
160 const childrenOf = new Map<string, WorkflowRun[]>();
161 const roots: WorkflowRun[] = [];
162 for (const run of runs) {
163 if (run.parentRunId === null || !listed.has(run.parentRunId)) {
164 roots.push(run);
165 continue;
166 }
167 const siblings = childrenOf.get(run.parentRunId);
168 if (siblings) siblings.push(run);
169 else childrenOf.set(run.parentRunId, [run]);
170 }
171 const node = (run: WorkflowRun): WorkflowRunNode => ({
172 run,
173 questions: questions.filter((question) => question.runId === run.runId),
174 children: (childrenOf.get(run.runId) ?? [])
175 .slice()
176 .sort((left, right) => left.startedAt.localeCompare(right.startedAt))
177 .map(node),
178 });
179 const needsYou: WorkflowRunNode[] = [];
180 const sections = new Map<string, { active: WorkflowRunNode[]; finished: WorkflowRunNode[] }>();
181 const sectionOf = (name: string) => {
182 const known = sections.get(name);
183 if (known) return known;
184 const made = { active: [], finished: [] };
185 sections.set(name, made);
186 return made;
187 };
188 for (const root of roots.map(node)) {
189 if (needsPerson(root)) needsYou.push(root);
190 else if (root.run.endedAt === null) sectionOf(root.run.workflow).active.push(root);
191 else sectionOf(root.run.workflow).finished.push(root);
192 }
193 const registered = new Map(workflows.map((workflow) => [workflow.name, workflow] as const));
194 const hasRuns = new Set(runs.map((run) => run.workflow));
195 const hasRootRuns = new Set(roots.map((run) => run.workflow));
196 const names = [...new Set([...sections.keys(), ...registered.keys(), ...hasRuns])];
197 const rank = (name: string) => {
198 const section = sections.get(name);
199 if (section !== undefined && section.active.length > 0) return 0;
200 return section !== undefined && section.finished.length > 0 ? 1 : 2;
201 };
202 return {
203 needsYou,
204 workflows: names
205 .map((name) => ({
206 name,
207 triggers: registered.get(name)?.triggers ?? null,
208 active: sections.get(name)?.active ?? [],
209 finished: sections.get(name)?.finished ?? [],
210 invokedOnly: hasRuns.has(name) && !hasRootRuns.has(name),
211 neverRan: !hasRuns.has(name),
212 }))
213 .slice()
214 .sort(
215 (left, right) => rank(left.name) - rank(right.name) || left.name.localeCompare(right.name),
216 ),
217 };
219​
220/** Every run of these, parents before the runs they invoked. */
221function flattenWorkflowRunNodes(
222 nodes: ReadonlyArray<WorkflowRunNode>,
223): ReadonlyArray<WorkflowRunNode> {
224 return nodes.flatMap((node) => [node, ...flattenWorkflowRunNodes(node.children)]);
226​
227/** Every run in the list, in the order it is listed. */
228export function allWorkflowRunNodes(groups: WorkflowRunGroups): ReadonlyArray<WorkflowRunNode> {
229 return flattenWorkflowRunNodes([
230 ...groups.needsYou,
231 ...groups.workflows.flatMap((section) => [...section.active, ...section.finished]),
232 ]);
234​
235/** The run to show when none was picked: the first that waits on a person, else one under way. */
236export function defaultWorkflowRunId(groups: WorkflowRunGroups): string | null {
237 const waiting = flattenWorkflowRunNodes(groups.needsYou).find(
238 (node) => node.questions.length > 0 || node.run.status === "paused",
239 );
240 const rest = groups.workflows;
241 return (
242 waiting?.run.runId ??
243 rest.find((section) => section.active.length > 0)?.active[0]?.run.runId ??
244 rest
245 .flatMap((section) => section.finished)
246 .slice()
247 .sort((left, right) => right.run.updatedAt.localeCompare(left.run.updatedAt))[0]?.run.runId ??
248 null
249 );
251​
252/** What starts a workflow, in words. */
253export function workflowTriggerLine(
254 section: WorkflowSection,
255 resolve: MFunctionType = mFallback,
256): string {
257 if (section.triggers === null) return resolve(msg("No longer registered on this server"));
258 if (section.invokedOnly) return resolve(msg("Runs as part of other workflows"));
259 return section.triggers.length === 0
260 ? resolve(msg("Started by hand"))
261 : resolve(msg("Starts on {triggers}", { triggers: section.triggers.join(", ") }));
263​
264export type WorkflowListTab = "needs-you" | "running" | "all";
265​
266/**
267 * The three lists a person switches between. Each is whole pieces of work, newest change first: a
268 * run that another invoked is reached through that one.
269 */
270export function workflowRunLists(
271 groups: WorkflowRunGroups,
272): Readonly<Record<WorkflowListTab, ReadonlyArray<WorkflowRunNode>>> {
273 const byChange = (nodes: ReadonlyArray<WorkflowRunNode>) =>
274 [...nodes].sort((left, right) => right.run.updatedAt.localeCompare(left.run.updatedAt));
275 const running = groups.workflows.flatMap((section) => section.active);
276 const finished = groups.workflows.flatMap((section) => section.finished);
277 return {
278 "needs-you": byChange(groups.needsYou),
279 running: byChange(running),
280 all: [...byChange(groups.needsYou), ...byChange(running), ...byChange(finished)],
281 };
283​
284/** Whether a run is of this workflow or invoked one, so a workflow that only runs inside others is found. */
285export function workflowRunInvolves(node: WorkflowRunNode, workflow: string): boolean {
286 return (
287 node.run.workflow === workflow ||
288 node.children.some((child) => workflowRunInvolves(child, workflow))
289 );
291​
292/**
293 * The filter value for the questions listed as Other: asked with no kind, or with one their
294 * workflow does not declare. A workflow cannot declare a blank kind.
295 */
296export const WORKFLOW_OTHER_KIND = "";
297​
298export interface WorkflowQuestionKind {
299 /** The kind as its workflow declares it, or `WORKFLOW_OTHER_KIND`. */
300 readonly kind: string;
301 /** What its workflow calls it. Null for Other, which the caller words. */
302 readonly label: string | null;
303 /** How many open questions in these runs are listed under it. */
304 readonly count: number;
306​
307/**
308 * The kind a question of this run is listed under: its own when the run's workflow declares it,
309 * else `WORKFLOW_OTHER_KIND`. The question keeps the kind it was asked with either way.
310 */
311function workflowListedKind(
312 workflows: ReadonlyArray<WorkflowSummary>,
313 node: WorkflowRunNode,
314 question: WorkflowQuestion,
315): string {
316 const declared = workflows.find((workflow) => workflow.name === node.run.workflow)?.asks ?? [];
317 return question.kind !== undefined && declared.some(({ kind }) => kind === question.kind)
318 ? question.kind
319 : WORKFLOW_OTHER_KIND;
321​
322/** The first run among these, or the runs they invoked, that itself asks a question listed under this kind. */
323export function workflowRunAskingKind(
324 workflows: ReadonlyArray<WorkflowSummary>,
325 nodes: ReadonlyArray<WorkflowRunNode>,
326 kind: string,
327): WorkflowRunNode | null {
328 return (
329 flattenWorkflowRunNodes(nodes).find((node) =>
330 node.questions.some((question) => workflowListedKind(workflows, node, question) === kind),
331 ) ?? null
332 );
334​
335/**
336 * The declared kinds of the open questions, in declared order, then Other. `sources` is one per
337 * environment, counted together. `picked` stays listed at zero, so a filter with nothing left
338 * can be undone. Empty when no question is of a declared kind and none is picked.
339 */
340export function workflowQuestionKinds(
341 sources: ReadonlyArray<{
342 readonly workflows: ReadonlyArray<WorkflowSummary>;
343 readonly nodes: ReadonlyArray<WorkflowRunNode>;
344 }>,
345 picked: string | null = null,
346): ReadonlyArray<WorkflowQuestionKind> {
347 const counts = new Map<string, number>();
348 const labels = new Map<string, string>();
349 for (const { workflows, nodes } of sources) {
350 for (const node of flattenWorkflowRunNodes(nodes)) {
351 for (const question of node.questions) {
352 const kind = workflowListedKind(workflows, node, question);
353 counts.set(kind, (counts.get(kind) ?? 0) + 1);
354 }
355 }
356 for (const workflow of workflows) {
357 for (const { kind, label } of workflow.asks ?? []) {
358 if (!labels.has(kind)) labels.set(kind, label);
359 }
360 }
361 }
362 if (picked !== null && !counts.has(picked)) counts.set(picked, 0);
363 const other = counts.get(WORKFLOW_OTHER_KIND);
364 counts.delete(WORKFLOW_OTHER_KIND);
365 if (counts.size === 0 && picked === null) return [];
366 const order = [...new Set([...labels.keys(), ...counts.keys()])];
367 return [
368 ...order.flatMap((kind) => {
369 const count = counts.get(kind);
370 return count === undefined ? [] : [{ kind, label: labels.get(kind) ?? kind, count }];
371 }),
372 ...(other === undefined ? [] : [{ kind: WORKFLOW_OTHER_KIND, label: null, count: other }]),
373 ];
375​
376/** Whether a run, or one it invoked, has an open question listed under this kind. */
377export function workflowRunAsksKind(
378 workflows: ReadonlyArray<WorkflowSummary>,
379 node: WorkflowRunNode,
380 kind: string,
381): boolean {
382 return workflowRunAskingKind(workflows, [node], kind) !== null;
384​
385/** The list to open on: what waits on a person, else what is under way, else everything. */
386export function defaultWorkflowListTab(groups: WorkflowRunGroups): WorkflowListTab {
387 if (groups.needsYou.length > 0) return "needs-you";
388 return groups.workflows.some((section) => section.active.length > 0) ? "running" : "all";
390​
391const CHIP_TONES = 5;
392​
393/** A workflow's mark in the list: two letters and one of a few colours, the same every time. */
394export function workflowChip(name: string): { readonly letters: string; readonly tone: number } {
395 const parts = name.split(/[^\p{L}\p{N}]+/u).filter((part) => part !== "");
396 const letters =
397 parts.length > 1
398 ? `${[...parts[0]!][0]}${[...parts[1]!][0]}`
399 : [...(parts[0] ?? name)].slice(0, 2).join("");
400 let hash = 0;
401 for (const char of name) hash = (hash * 31 + char.codePointAt(0)!) % 9973;
402 return { letters: letters.toUpperCase(), tone: hash % CHIP_TONES };
404​
405export type WorkflowRunTone = "input" | "failed" | "working" | "quiet" | "done";
406​
407/** A run's state as the one word the thread list would use for it. */
408export function workflowRunState(
409 node: WorkflowRunNode,
410 resolve: MFunctionType = mFallback,
411): {
412 readonly word: string;
413 readonly tone: WorkflowRunTone;
414} {
415 const { run } = node;
416 const input = {
417 word: resolve(msg("Needs you", { $context: "workflow run status: it waits on a person" })),
418 tone: "input",
419 } as const;
420 const working = {
421 word: resolve(msg("Working", { $context: "workflow run status" })),
422 tone: "working",
423 } as const;
424 if (node.questions.length > 0) return input;
425 switch (run.status) {
426 case "paused":
427 return {
428 word: resolve(msg("Paused", { $context: "workflow run status" })),
429 tone: "failed",
430 };
431 case "running":
432 return working;
433 case "waiting": {
434 const detail = run.detail ?? "";
435 if (detail.startsWith("agent ")) return working;
436 if (detail.startsWith("sleep ")) {
437 return {
438 word: resolve(msg("Sleeping", { $context: "workflow run status" })),
439 tone: "quiet",
440 };
441 }
442 if (detail.startsWith("queue ")) {
443 return {
444 word: resolve(
445 msg("Queued", { $context: "workflow run status: it waits for a free place" }),
446 ),
447 tone: "quiet",
448 };
449 }
450 // Something below it holds it up; say that, not that it idles.
451 if (node.children.some(needsPerson)) return input;
452 return { word: resolve(msg("Waiting", { $context: "workflow run status" })), tone: "quiet" };
453 }
454 case "completed":
455 return { word: resolve(msg("Done", { $context: "workflow run status" })), tone: "done" };
456 case "stopped":
457 return { word: resolve(msg("Stopped", { $context: "workflow run status" })), tone: "quiet" };
458 case "skipped":
459 return { word: resolve(msg("Skipped", { $context: "workflow run status" })), tone: "quiet" };
460 case "cancelled":
461 return {
462 word: resolve(msg("Cancelled", { $context: "workflow run status" })),
463 tone: "quiet",
464 };
465 }
467​
468const firstLine = (text: string) => text.trim().split("\n", 1)[0]!.trim();
469​
470/** What a run is at right now, as the line under its title. */
471export function workflowRunNow(node: WorkflowRunNode, resolve: MFunctionType = mFallback): string {
472 const { run } = node;
473 const detail = run.detail?.trim() ?? "";
474 const asked = node.questions[0];
475 if (asked !== undefined) {
476 const more = node.questions.length - 1;
477 const question = readWorkflowQuestion(asked).title;
478 return more > 0
479 ? resolve(msg("Asks: {question} and {more} more", { question, more }))
480 : resolve(msg("Asks: {question}", { question }));
481 }
482 const below = flattenWorkflowRunNodes(node.children);
483 const holding = below.find(
484 (child) => child.questions.length > 0 || child.run.status === "paused",
485 );
486 switch (run.status) {
487 case "paused":
488 return detail === "" ? resolve(msg("A step failed")) : firstLine(detail);
489 case "running":
490 return resolve(msg("Running its own steps"));
491 case "waiting":
492 if (holding !== undefined) {
493 return `${holding.run.title}: ${workflowRunNow(holding, resolve)}`;
494 }
495 if (detail.startsWith("agent ")) {
496 return resolve(msg("{step} is working", { step: detail.slice(6) }));
497 }
498 if (detail.startsWith("sleep ")) {
499 return resolve(msg("Sleeping at {step}", { step: detail.slice(6) }));
500 }
501 if (detail.startsWith("queue ")) {
502 return resolve(msg("Queued for {pool}", { pool: detail.slice(6) }));
503 }
504 if (below.some((child) => child.run.endedAt === null)) {
505 const open = below.filter((child) => child.run.endedAt === null);
506 return open.length === 1
507 ? resolve(msg("Runs {run}", { run: open[0]!.run.title }))
508 : resolve(msg("{count} runs under way", { count: open.length }));
509 }
510 return detail === ""
511 ? resolve(msg("Waiting", { $context: "what a workflow run is doing now" }))
512 : resolve(msg("Waiting for {step}", { step: detail }));
513 case "completed": {
514 const line = workflowResultLines(run.result)[0];
515 if (line === undefined) {
516 return resolve(msg("Finished", { $context: "what a workflow run is doing now" }));
517 }
518 return firstLine(line.label === null ? line.value : `${line.label}: ${line.value}`);
519 }
520 case "stopped":
521 case "skipped":
522 case "cancelled":
523 return detail === "" ? resolve(msg("Ended early")) : firstLine(detail);
524 }
526​
527/** A run's result as lines a person can read: a sentence, or the fields of an object. */
528export function workflowResultLines(
529 result: WorkflowRun["result"],
530): ReadonlyArray<{ readonly label: string | null; readonly value: string }> {
531 if (result === null) return [];
532 if (typeof result !== "object") return [{ label: null, value: String(result) }];
533 if (Array.isArray(result)) return [{ label: null, value: JSON.stringify(result) }];
534 return Object.entries(result).map(([label, value]) => ({
535 label,
536 value: typeof value === "string" ? value : JSON.stringify(value),
537 }));
539​
540// A step this short is bookkeeping between the parts of a run that take time.
541const QUICK_STEP_MS = 1_000;
542​
543export interface WorkflowBeat {
544 readonly kind: WorkflowStep["kind"] | "run";
545 readonly name: string;
546 readonly status: WorkflowStep["status"];
547 readonly attempts: number;
548 /** A failure's reason, or when a sleep wakes. */
549 readonly detail: string | null;
550 /** What it produced: a value, an agent's data or reply, the answer to a question. */
551 readonly result: WorkflowStep["result"];
552 /** What an agent said in closing, when its result is data. */
553 readonly said: string | null;
554 /** For a step queued for a place in a pool, how many are ahead of it. */
555 readonly ahead: number | undefined;
556 readonly startMs: number;
557 /** When it ended, or `nowMs` while it is under way. */
558 readonly endMs: number;
559 readonly thread: { readonly threadId: string; readonly environmentId: string | null } | null;
560 /** The run this step invoked and waited for. */
561 readonly childRun: WorkflowRun | null;
562 /** Another beat was under way at the same time. */
563 readonly parallel: boolean;
565​
566export interface WorkflowQuickSteps {
567 readonly kind: "quick";
568 readonly steps: ReadonlyArray<WorkflowStep>;
569 readonly startMs: number;
570 readonly endMs: number;
572​
573export type WorkflowTimelineRow = WorkflowBeat | WorkflowQuickSteps;
574​
575export interface WorkflowTimeline {
576 readonly rows: ReadonlyArray<WorkflowTimelineRow>;
577 readonly startMs: number;
578 readonly endMs: number;
580​
581/**
582 * A run's steps as the story of the run: what took time or involved someone is a beat, and the
583 * quick steps between two beats fold into one row, since a journal of them hides where the run
584 * is. An invoked run takes the place of the two steps that started and awaited it.
585 */
586export function buildWorkflowTimeline(input: {
587 readonly run: Pick<WorkflowRun, "runId" | "startedAt" | "endedAt">;
588 readonly steps: ReadonlyArray<WorkflowStep>;
589 readonly children: ReadonlyArray<WorkflowRun>;
590 readonly nowMs: number;
591}): WorkflowTimeline {
592 const childByStep = new Map(
593 input.children
594 .filter((child) => child.parentRunId === input.run.runId && child.parentStep !== null)
595 .map((child) => [child.parentStep, child] as const),
596 );
597 const startMs = Date.parse(input.run.startedAt);
598 // A caller's clock can be a minute old. Now is never before anything the run has done.
599 const nowMs = Math.max(
600 input.nowMs,
601 startMs,
602 ...input.steps.map((step) => Date.parse(step.endedAt ?? step.startedAt)),
603 );
604 const endMs = input.run.endedAt === null ? nowMs : Date.parse(input.run.endedAt);
605 const rows: WorkflowTimelineRow[] = [];
606 const beats: WorkflowBeat[] = [];
607 let quick: WorkflowStep[] = [];
608 const flush = () => {
609 if (quick.length === 0) return;
610 rows.push({
611 kind: "quick",
612 steps: quick,
613 startMs: Date.parse(quick[0]!.startedAt),
614 endMs: Date.parse(quick.at(-1)!.endedAt ?? quick.at(-1)!.startedAt),
615 });
616 quick = [];
617 };
618 for (const step of input.steps) {
619 // The step that started an invoked run is told by the wait that follows it.
620 if (step.kind === "step" && step.name.endsWith("/start")) {
621 if (childByStep.has(step.name.slice(0, -"/start".length))) continue;
622 }
623 const stepStart = Date.parse(step.startedAt);
624 const stepEnd = step.endedAt === null ? nowMs : Date.parse(step.endedAt);
625 const childRun = step.kind === "wait" ? (childByStep.get(step.name) ?? null) : null;
626 // A place given at once is bookkeeping too; a wait for one is a beat.
627 const isBeat =
628 (step.kind !== "step" && step.kind !== "queue") ||
629 step.status !== "completed" ||
630 step.attempts > 1 ||
631 stepEnd - stepStart >= QUICK_STEP_MS;
632 if (!isBeat) {
633 quick.push(step);
634 continue;
635 }
636 flush();
637 const beat: WorkflowBeat = {
638 kind: childRun === null ? step.kind : "run",
639 name: step.name,
640 status: step.status,
641 attempts: step.attempts,
642 detail: step.detail,
643 result: step.result,
644 said: step.said,
645 ahead: step.ahead,
646 startMs: stepStart,
647 endMs: Math.max(stepStart, stepEnd),
648 thread:
649 step.threadId === null
650 ? null
651 : { threadId: step.threadId, environmentId: step.environmentId },
652 childRun,
653 parallel: false,
654 };
655 beats.push(beat);
656 rows.push(beat);
657 }
658 flush();
659 const overlaps = (left: WorkflowBeat, right: WorkflowBeat) =>
660 left !== right && left.startMs < openEnd(right) && right.startMs < openEnd(left);
661 return {
662 rows: rows.map((row) =>
663 row.kind === "quick"
664 ? row
665 : { ...row, parallel: beats.some((other) => overlaps(row, other)) },
666 ),
667 startMs,
668 endMs: Math.max(endMs, ...beats.map((beat) => beat.endMs), startMs + 1),
669 };
671​
672/** When a beat stops overlapping what starts after it: one still under way never does. */
673const openEnd = (beat: WorkflowBeat) =>
674 beat.status === "running" ? Number.POSITIVE_INFINITY : beat.endMs;
675​
676/** What a person answered a question with, when a step's result is such an answer. */
677export function workflowAnswer(result: WorkflowStep["result"]): {
678 readonly choice: string;
679 readonly reason: string | null;
680 /** The client, tool or agent thread that answered, by name; null on an answer kept before this. */
681 readonly answeredBy: string | null;
682 /** The client session that answered; null for a tool, an agent, or an answer kept before this. */
683 readonly answeredBySession: string | null;
684 readonly answeredAt: string | null;
685} | null {
686 const choice = field(result, "choice");
687 return typeof choice === "string"
688 ? {
689 choice,
690 reason: text(field(result, "reason")),
691 answeredBy: text(field(result, "answeredBy")),
692 answeredBySession: text(field(result, "answeredBySession")),
693 answeredAt: text(field(result, "answeredAt")),
694 }
695 : null;
697​
698/** Who withdrew a question unanswered, and why, when a step's result says so. */
699export function workflowWithdrawal(
700 result: WorkflowStep["result"],
701): { readonly by: string; readonly reason: string | null } | null {
702 const withdrawn = field(result, "withdrawn");
703 const by = field(withdrawn, "by");
704 const reason = field(withdrawn, "reason");
705 return typeof by === "string"
706 ? { by, reason: typeof reason === "string" && reason.trim() !== "" ? reason : null }
707 : null;
709​
710/**
711 * Whether the client whose session on the run's environment is `sessionId` gave `answer`. Decided
712 * by session, never by name: two browsers share "Chrome on Linux" and every phone its app's name.
713 */
714export const isOwnWorkflowAnswer = (
715 answer: { readonly answeredBySession: string | null },
716 sessionId: string | null | undefined,
717): boolean => answer.answeredBySession !== null && answer.answeredBySession === sessionId;
718​
719/** Steps that were under way at the same time, shown side by side. */
720export interface WorkflowTogether {
721 readonly kind: "together";
722 readonly beats: ReadonlyArray<WorkflowBeat>;
724​
725export type WorkflowFeedRow = WorkflowTimelineRow | WorkflowTogether;
726​
727/**
728 * The timeline as it is read: beats that overlapped become one row, so two reviewers at once look
729 * like two reviewers at once and not like one after the other.
730 */
731export function buildWorkflowFeed(timeline: WorkflowTimeline): ReadonlyArray<WorkflowFeedRow> {
732 const rows: WorkflowFeedRow[] = [];
733 let together: WorkflowBeat[] = [];
734 let until = 0;
735 const flush = () => {
736 if (together.length === 1) rows.push(together[0]!);
737 else if (together.length > 1) rows.push({ kind: "together", beats: together });
738 together = [];
739 };
740 for (const row of timeline.rows) {
741 if (row.kind === "quick") {
742 flush();
743 rows.push(row);
744 continue;
745 }
746 if (together.length > 0 && row.parallel && row.startMs < until) {
747 together.push(row);
748 until = Math.max(until, openEnd(row));
749 continue;
750 }
751 flush();
752 together = [row];
753 until = openEnd(row);
754 }
755 flush();
756 return rows;
758​
759/** The steps of a feed that take a place in the run's flow: every beat, in order. */
760const beatsOf = (rows: ReadonlyArray<WorkflowFeedRow>) =>
761 rows.flatMap((row) => (row.kind === "quick" ? [] : row.kind === "together" ? row.beats : [row]));
762​
763/**
764 * The step a paused run stopped at: the last that failed, unless the run went on after it, since
765 * then the workflow caught that failure. Null when the run is not paused at a step.
766 */
767export function workflowPausedBeat(
768 rows: ReadonlyArray<WorkflowFeedRow>,
769 status: WorkflowRun["status"],
770): WorkflowBeat | null {
771 if (status !== "paused") return null;
772 const failed = beatsOf(rows).findLast((beat) => beat.status === "failed");
773 if (failed === undefined) return null;
774 const wentOn = rows.some((row) =>
775 row.kind === "together"
776 ? row.beats.some((beat) => beat !== failed && beat.startMs >= failed.endMs)
777 : row !== failed && row.startMs >= failed.endMs,
778 );
779 return wentOn ? null : failed;
781​
782/**
783 * Which part of a run's flow to open on: what waits on a person, then where it failed, then how
784 * it ended, then what is under way. Keys are `step:<name>`, `question:<name>`, `pause` and `end`.
785 */
786export function workflowFlowFocus(input: {
787 readonly rows: ReadonlyArray<WorkflowFeedRow>;
788 readonly status: WorkflowRun["status"];
789 readonly ended: boolean;
790 /** The names of the questions that wait on a person. */
791 readonly questions: ReadonlyArray<string>;
792}): string | null {
793 const beats = beatsOf(input.rows);
794 const asked = input.questions[0];
795 if (asked !== undefined) {
796 const at = beats.find(
797 (beat) =>
798 beat.kind === "ask" && beat.status === "running" && input.questions.includes(beat.name),
799 );
800 return at === undefined ? `question:${asked}` : `step:${at.name}`;
801 }
802 if (input.status === "paused") {
803 const failed = workflowPausedBeat(input.rows, input.status);
804 return failed === null ? "pause" : `step:${failed.name}`;
805 }
806 if (input.ended) return "end";
807 const last = beats.findLast((beat) => beat.status === "running") ?? beats.at(-1);
808 return last === undefined ? null : `step:${last.name}`;
810​
811const FACT_LENGTH = 48;
812const FACTS_SHOWN = 6;
813// A string this long is the agent talking, not a fact about its work.
814const PROSE_LENGTH = 80;
815​
816const words = (key: string) =>
817 key
818 .replace(/([a-z0-9])([A-Z])/g, "$1 $2")
819 .replace(/[_-]+/g, " ")
820 .toLowerCase();
821​
822function factValue(value: unknown): string | null {
823 if (typeof value === "boolean") return value ? "yes" : "no";
824 if (typeof value === "number") return String(value);
825 if (typeof value === "string") {
826 const text = value.trim();
827 return text !== "" && text.length <= FACT_LENGTH && !text.includes("\n") ? text : null;
828 }
829 if (Array.isArray(value) && value.length > 0 && value.length <= 4) {
830 const parts = value.map(factValue);
831 const joined = parts.join(", ");
832 return parts.every((part) => part !== null) && joined.length <= FACT_LENGTH ? joined : null;
833 }
834 return null;
836​
837/**
838 * What an agent step has to say for itself: its words, and the short facts of its result. With no
839 * closing words kept, the longest piece of prose in the result stands in for them.
840 */
841export function workflowAgentSummary(beat: Pick<WorkflowBeat, "result" | "said">): {
842 readonly said: string | null;
843 readonly facts: ReadonlyArray<{ readonly label: string; readonly value: string }>;
844} {
845 const { result } = beat;
846 const kept = beat.said?.trim() ?? "";
847 if (typeof result === "string") {
848 return { said: kept !== "" ? kept : result.trim() === "" ? null : result.trim(), facts: [] };
849 }
850 if (result === null || typeof result !== "object" || Array.isArray(result)) {
851 return { said: kept === "" ? null : kept, facts: [] };
852 }
853 const entries = Object.entries(result);
854 const prose =
855 kept !== ""
856 ? null
857 : (entries
858 .filter(
859 (entry): entry is [string, string] =>
860 typeof entry[1] === "string" && entry[1].trim().length >= PROSE_LENGTH,
861 )
862 .slice()
863 .sort((left, right) => right[1].length - left[1].length)[0] ?? null);
864 return {
865 said: kept !== "" ? kept : (prose?.[1].trim() ?? null),
866 facts: entries
867 .flatMap(([key, value]) => {
868 const text = factValue(value);
869 return text === null ? [] : [{ label: words(key), value: text }];
870 })
871 .slice(0, FACTS_SHOWN),
872 };
874​
875/**
876 * The start of what an agent said, cut where a paragraph ends so no markup is left half open.
877 * Null when all of it fits.
878 */
879export function workflowSaidStart(said: string, limit: number): string | null {
880 if (said.length <= limit) return null;
881 const paragraphs = said.split(/\n{2,}/);
882 let kept = paragraphs[0]!;
883 for (const paragraph of paragraphs.slice(1)) {
884 if (kept.length + paragraph.length + 2 > limit) break;
885 kept = `${kept}\n\n${paragraph}`;
886 }
887 // One paragraph that runs on is cut at a word, which can still split markup but not a word.
888 // Text with no space before the limit, such as Chinese, is cut at the limit, never inside a
889 // surrogate pair.
890 if (kept.length > limit * 2) {
891 const space = kept.lastIndexOf(" ", limit);
892 const before = kept.charCodeAt(limit - 1);
893 const highSurrogateLast = before >= 0xd800 && before <= 0xdbff;
894 const end = space > 0 ? space : highSurrogateLast ? limit - 1 : limit;
895 kept = `${kept.slice(0, end)}…`;
896 }
897 return kept === said ? null : kept;
899​
900const decodeIssueAddress = Schema.decodeUnknownOption(WorkflowIssueAddress);
901const decodePullRequestAddress = Schema.decodeUnknownOption(WorkflowPullRequestAddress);
902​
903/** A reference's issue, when it is one and its address reads as one. */
904export function workflowReferenceIssue(reference: WorkflowRunSubject): IssueRef | null {
905 return reference.kind === WorkflowReferenceKind.issue
906 ? Option.getOrNull(decodeIssueAddress(reference.address))
907 : null;
909​
910/** A reference's pull request, when it is one and its address reads as one. */
911export function workflowReferencePullRequest(reference: WorkflowRunSubject): PullRequestRef | null {
912 return reference.kind === WorkflowReferenceKind.pullRequest
913 ? Option.getOrNull(decodePullRequestAddress(reference.address))
914 : null;
916​
917/** A reference's thread, when it is one, in the run's own environment. */
918export function workflowReferenceThreadId(reference: WorkflowRunSubject): string | null {
919 const threadId = field(reference.address, "threadId");
920 return reference.kind === WorkflowReferenceKind.thread && typeof threadId === "string"
921 ? threadId
922 : null;
924​
925/**
926 * What a reference is called in a chip: `#412` for an issue or pull request on a git host, a
927 * tracker's own key such as `ENG-12`, and otherwise the title, or the host of its web address.
928 */
929export function workflowReferenceLabel(reference: WorkflowRunSubject): string {
930 const pullRequest = workflowReferencePullRequest(reference);
931 if (pullRequest !== null) return `#${pullRequest.number}`;
932 const issue = workflowReferenceIssue(reference);
933 if (issue !== null) return /^\d+$/.test(issue.key) ? `#${issue.key}` : issue.key;
934 if (reference.title !== "") return reference.title;
935 const url = reference.url === null ? null : parseUrl(reference.url);
936 return url?.host ?? reference.kind;
938​
939/** The references a step touched, in the order the run first touched them. */
940export function workflowStepReferences(
941 references: ReadonlyArray<WorkflowRunReference>,
942 step: string,
943): ReadonlyArray<WorkflowRunReference> {
944 return references.filter((reference) => reference.steps.includes(step));
946​
947/** A step's time in one shape down a column: 0.3s, 9.7s, 12s, then minutes. */
948export function workflowStepTime(ms: number, resolve: MFunctionType = mFallback): string {
949 if (ms < 9_950 && ms % 1000 !== 0) {
950 return resolve(msg("{seconds}s", { seconds: (Math.max(ms, 100) / 1000).toFixed(1) }));
951 }
952 const seconds = Math.round(ms / 1000);
953 if (seconds < 60) return resolve(msg("{seconds}s", { seconds }));
954 return formatDuration(ms, resolve);
956​
957function stripMarkdownLinks(text: string): string {
958 const scan = markdownLinkDestinationScanner(text);
959 const brackets = /\\[!\\[\]]|!\[|[[\]]/g;
960 const openers: Array<{ index: number; image: boolean; linkGeneration: number }> = [];
961 const matchedOpeners = new Set<number>();
962 const destinationEnds = new Map<number, number>();
963 let linkGeneration = 0;
964 for (let match = brackets.exec(text); match; match = brackets.exec(text)) {
965 if (match[0].endsWith("[") && !match[0].startsWith("\\")) {
966 const image = match[0] === "![";
967 openers.push({ index: match.index, image, linkGeneration });
968 continue;
969 }
970 if (match[0] !== "]") continue;
971 const opener = openers.pop();
972 if (opener === undefined) continue;
973 if (!opener.image && opener.linkGeneration !== linkGeneration) continue;
974 const dest = scan(match.index + 1);
975 if (dest === null) continue;
976 // A link deactivates all earlier link openers, even across image boundaries.
977 if (!opener.image) linkGeneration += 1;
978 matchedOpeners.add(opener.index);
979 destinationEnds.set(match.index, dest.end);
980 brackets.lastIndex = dest.end;
981 }
982 if (matchedOpeners.size === 0) return text;
983​
984 let out = "";
985 let cursor = 0;
986 let labelDepth = 0;
987 for (let match = brackets.exec(text); match; match = brackets.exec(text)) {
988 const index = match.index;
989 const end = destinationEnds.get(index);
990 if (matchedOpeners.has(index)) {
991 out += text.slice(cursor, index);
992 cursor = brackets.lastIndex;
993 labelDepth += 1;
994 } else if (end !== undefined) {
995 out += text.slice(cursor, index);
996 cursor = end;
997 brackets.lastIndex = end;
998 labelDepth -= 1;
999 } else if (labelDepth > 0 && match[0].startsWith("\\")) {
1000 out += text.slice(cursor, index) + match[0][1];
1001 cursor = brackets.lastIndex;
1004 return out + text.slice(cursor);
1006​
1007/**
1008 * The first prose sentence of a reply, as one line of plain text: headings, tables, and fenced
1009 * code blocks are skipped; indented text is a fallback. List marks, code, emphasis, and links read as words.
1010 * Code keeps its text, and an underscore inside a word, as in snake_case, is not emphasis.
1011 */
1012export function workflowOneLine(text: string): string {
1013 let fence: string | null = null;
1014 let fenceQuoteDepth = 0;
1015 let indented: string | undefined;
1016 const line =
1017 text
1018 .split("\n")
1019 .find((candidate) => {
1020 const quote = /^(?: {0,3}>[ \t]?)+/.exec(candidate)?.[0] ?? "";
1021 const quoteDepth = quote.replace(/[^>]/g, "").length;
1022 const content = candidate.slice(quote.length);
1023 const [, marker, rest] = /^ {0,3}(`{3,}|~{3,})([^\n]*)$/.exec(content) ?? [];
1024 if (quoteDepth < fenceQuoteDepth) fence = null;
1025 if (fence !== null) {
1026 if (
1027 quoteDepth === fenceQuoteDepth &&
1028 marker?.startsWith(fence) &&
1029 /^[ \t]*\r?$/.test(rest ?? "")
1030 ) {
1031 fence = null;
1033 return false;
1035 if (marker !== undefined && !(marker[0] === "`" && rest?.includes("`"))) {
1036 fence = marker;
1037 fenceQuoteDepth = quoteDepth;
1038 return false;
1040 if (
1041 /^\s*$/.test(content) ||
1042 /^ {0,3}#{1,6}(?:[ \t]|\r?$)/.test(content) ||
1043 /^[ \t]*\|/.test(candidate)
1045 return false;
1046 if (!/^(?: {4}| {0,3}\t)/.test(content)) return true;
1047 indented ??= candidate;
1048 return false;
1049 })
1050 ?.trim() ??
1051 indented?.trim() ??
1052 "";
1053 const code: string[] = [];
1054 const stripped = line
1055 .replace(/^(?:>\s*)+/, "")
1056 .replace(/^([-*]|\d+\.)\s+/, "")
1057 .replace(/(`+)(.+?)\1(?!`)/g, (_, _ticks, inner: string) => `\0${code.push(inner) - 1}\0`);
1058 const plain = stripMarkdownLinks(stripped)
1059 .replace(/(?<![\p{L}\p{M}\p{N}_/])(__|_)(\S(?:.*?\S)?)\1(?![\p{L}\p{M}\p{N}_/])/gu, "$2")
1060 .replace(/(\*\*|\*)(\S(?:.*?\S)?)\1/g, "$2")
1061 .replace(/\0(\d+)\0/g, (match, index: string) => code[Number(index)] ?? match);
1062 const end = plain.search(/[.!?](\s|$)/);
1063 return end === -1 ? plain : plain.slice(0, end + 1);