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

workflows.ts

1,083 lines40.7 KB

1import { mFallback, msg } from "gt-i18n";
2import type { M } from "gt-i18n";
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(section: WorkflowSection, resolve: M = mFallback): string {
254 if (section.triggers === null) return resolve(msg("No longer registered on this server"));
255 if (section.invokedOnly) return resolve(msg("Runs as part of other workflows"));
256 return section.triggers.length === 0
257 ? resolve(msg("Started by hand"))
258 : resolve(msg`Starts on ${{ triggers: section.triggers.join(", ") }}`);
260​
261export type WorkflowListTab = "needs-you" | "running" | "all";
262​
263/**
264 * The three lists a person switches between. Each is whole pieces of work, newest change first: a
265 * run that another invoked is reached through that one.
266 */
267export function workflowRunLists(
268 groups: WorkflowRunGroups,
269): Readonly<Record<WorkflowListTab, ReadonlyArray<WorkflowRunNode>>> {
270 const byChange = (nodes: ReadonlyArray<WorkflowRunNode>) =>
271 [...nodes].sort((left, right) => right.run.updatedAt.localeCompare(left.run.updatedAt));
272 const running = groups.workflows.flatMap((section) => section.active);
273 const finished = groups.workflows.flatMap((section) => section.finished);
274 return {
275 "needs-you": byChange(groups.needsYou),
276 running: byChange(running),
277 all: [...byChange(groups.needsYou), ...byChange(running), ...byChange(finished)],
278 };
280​
281/** Whether a run is of this workflow or invoked one, so a workflow that only runs inside others is found. */
282export function workflowRunInvolves(node: WorkflowRunNode, workflow: string): boolean {
283 return (
284 node.run.workflow === workflow ||
285 node.children.some((child) => workflowRunInvolves(child, workflow))
286 );
288​
289/**
290 * The filter value for the questions listed as Other: asked with no kind, or with one their
291 * workflow does not declare. A workflow cannot declare a blank kind.
292 */
293export const WORKFLOW_OTHER_KIND = "";
294​
295export interface WorkflowQuestionKind {
296 /** The kind as its workflow declares it, or `WORKFLOW_OTHER_KIND`. */
297 readonly kind: string;
298 /** What its workflow calls it. Null for Other, which the caller words. */
299 readonly label: string | null;
300 /** How many open questions in these runs are listed under it. */
301 readonly count: number;
303​
304/**
305 * The kind a question of this run is listed under: its own when the run's workflow declares it,
306 * else `WORKFLOW_OTHER_KIND`. The question keeps the kind it was asked with either way.
307 */
308function workflowListedKind(
309 workflows: ReadonlyArray<WorkflowSummary>,
310 node: WorkflowRunNode,
311 question: WorkflowQuestion,
312): string {
313 const declared = workflows.find((workflow) => workflow.name === node.run.workflow)?.asks ?? [];
314 return question.kind !== undefined && declared.some(({ kind }) => kind === question.kind)
315 ? question.kind
316 : WORKFLOW_OTHER_KIND;
318​
319/** The first run among these, or the runs they invoked, that itself asks a question listed under this kind. */
320function workflowRunAskingKind(
321 workflows: ReadonlyArray<WorkflowSummary>,
322 nodes: ReadonlyArray<WorkflowRunNode>,
323 kind: string,
324): WorkflowRunNode | null {
325 return (
326 flattenWorkflowRunNodes(nodes).find((node) =>
327 node.questions.some((question) => workflowListedKind(workflows, node, question) === kind),
328 ) ?? null
329 );
331​
332/**
333 * The declared kinds of the open questions, in declared order, then Other. `sources` is one per
334 * environment, counted together. `picked` stays listed at zero, so a filter with nothing left
335 * can be undone. Empty when no question is of a declared kind and none is picked.
336 */
337export function workflowQuestionKinds(
338 sources: ReadonlyArray<{
339 readonly workflows: ReadonlyArray<WorkflowSummary>;
340 readonly nodes: ReadonlyArray<WorkflowRunNode>;
341 }>,
342 picked: string | null = null,
343): ReadonlyArray<WorkflowQuestionKind> {
344 const counts = new Map<string, number>();
345 const labels = new Map<string, string>();
346 for (const { workflows, nodes } of sources) {
347 for (const node of flattenWorkflowRunNodes(nodes)) {
348 for (const question of node.questions) {
349 const kind = workflowListedKind(workflows, node, question);
350 counts.set(kind, (counts.get(kind) ?? 0) + 1);
351 }
352 }
353 for (const workflow of workflows) {
354 for (const { kind, label } of workflow.asks ?? []) {
355 if (!labels.has(kind)) labels.set(kind, label);
356 }
357 }
358 }
359 if (picked !== null && !counts.has(picked)) counts.set(picked, 0);
360 const other = counts.get(WORKFLOW_OTHER_KIND);
361 counts.delete(WORKFLOW_OTHER_KIND);
362 if (counts.size === 0 && picked === null) return [];
363 const order = [...new Set([...labels.keys(), ...counts.keys()])];
364 return [
365 ...order.flatMap((kind) => {
366 const count = counts.get(kind);
367 return count === undefined ? [] : [{ kind, label: labels.get(kind) ?? kind, count }];
368 }),
369 ...(other === undefined ? [] : [{ kind: WORKFLOW_OTHER_KIND, label: null, count: other }]),
370 ];
372​
373/** Whether a run, or one it invoked, has an open question listed under this kind. */
374export function workflowRunAsksKind(
375 workflows: ReadonlyArray<WorkflowSummary>,
376 node: WorkflowRunNode,
377 kind: string,
378): boolean {
379 return workflowRunAskingKind(workflows, [node], kind) !== null;
381​
382/** The list to open on: what waits on a person, else what is under way, else everything. */
383export function defaultWorkflowListTab(groups: WorkflowRunGroups): WorkflowListTab {
384 if (groups.needsYou.length > 0) return "needs-you";
385 return groups.workflows.some((section) => section.active.length > 0) ? "running" : "all";
387​
388const CHIP_TONES = 5;
389​
390/** A workflow's mark in the list: two letters and one of a few colours, the same every time. */
391export function workflowChip(name: string): { readonly letters: string; readonly tone: number } {
392 const parts = name.split(/[^\p{L}\p{N}]+/u).filter((part) => part !== "");
393 const letters =
394 parts.length > 1
395 ? `${[...parts[0]!][0]}${[...parts[1]!][0]}`
396 : [...(parts[0] ?? name)].slice(0, 2).join("");
397 let hash = 0;
398 for (const char of name) hash = (hash * 31 + char.codePointAt(0)!) % 9973;
399 return { letters: letters.toUpperCase(), tone: hash % CHIP_TONES };
401​
402export type WorkflowRunTone = "input" | "failed" | "working" | "quiet" | "done";
403​
404/** A run's state as the one word the thread list would use for it. */
405export function workflowRunState(
406 node: WorkflowRunNode,
407 resolve: M = mFallback,
408): {
409 readonly word: string;
410 readonly tone: WorkflowRunTone;
411} {
412 const { run } = node;
413 const input = {
414 word: resolve(msg({ context: "workflow run status: it waits on a person" })`Needs you`),
415 tone: "input",
416 } as const;
417 const working = {
418 word: resolve(msg({ context: "workflow run status" })`Working`),
419 tone: "working",
420 } as const;
421 if (node.questions.length > 0) return input;
422 switch (run.status) {
423 case "paused":
424 return {
425 word: resolve(msg({ context: "workflow run status" })`Paused`),
426 tone: "failed",
427 };
428 case "running":
429 return working;
430 case "waiting": {
431 const detail = run.detail ?? "";
432 if (detail.startsWith("agent ")) return working;
433 if (detail.startsWith("sleep ")) {
434 return {
435 word: resolve(msg({ context: "workflow run status" })`Sleeping`),
436 tone: "quiet",
437 };
438 }
439 if (detail.startsWith("queue ")) {
440 return {
441 word: resolve(msg({ context: "workflow run status: it waits for a free place" })`Queued`),
442 tone: "quiet",
443 };
444 }
445 // Something below it holds it up; say that, not that it idles.
446 if (node.children.some(needsPerson)) return input;
447 return { word: resolve(msg({ context: "workflow run status" })`Waiting`), tone: "quiet" };
448 }
449 case "completed":
450 return { word: resolve(msg({ context: "workflow run status" })`Done`), tone: "done" };
451 case "stopped":
452 return { word: resolve(msg({ context: "workflow run status" })`Stopped`), tone: "quiet" };
453 case "skipped":
454 return { word: resolve(msg({ context: "workflow run status" })`Skipped`), tone: "quiet" };
455 case "cancelled":
456 return {
457 word: resolve(msg({ context: "workflow run status" })`Cancelled`),
458 tone: "quiet",
459 };
460 }
462​
463const firstLine = (text: string) => text.trim().split("\n", 1)[0]!.trim();
464​
465/** What a run is at right now, as the line under its title. */
466export function workflowRunNow(node: WorkflowRunNode, resolve: M = mFallback): string {
467 const { run } = node;
468 const detail = run.detail?.trim() ?? "";
469 const asked = node.questions[0];
470 if (asked !== undefined) {
471 const more = node.questions.length - 1;
472 const question = readWorkflowQuestion(asked).title;
473 return more > 0
474 ? resolve(msg`Asks: ${{ question }} and ${{ more }} more`)
475 : resolve(msg`Asks: ${{ question }}`);
476 }
477 const below = flattenWorkflowRunNodes(node.children);
478 const holding = below.find(
479 (child) => child.questions.length > 0 || child.run.status === "paused",
480 );
481 switch (run.status) {
482 case "paused":
483 return detail === "" ? resolve(msg("A step failed")) : firstLine(detail);
484 case "running":
485 return resolve(msg("Running its own steps"));
486 case "waiting":
487 if (holding !== undefined) {
488 return `${holding.run.title}: ${workflowRunNow(holding, resolve)}`;
489 }
490 if (detail.startsWith("agent ")) {
491 return resolve(msg`${{ step: detail.slice(6) }} is working`);
492 }
493 if (detail.startsWith("sleep ")) {
494 return resolve(msg`Sleeping at ${{ step: detail.slice(6) }}`);
495 }
496 if (detail.startsWith("queue ")) {
497 return resolve(msg`Queued for ${{ pool: detail.slice(6) }}`);
498 }
499 if (below.some((child) => child.run.endedAt === null)) {
500 const open = below.filter((child) => child.run.endedAt === null);
501 return open.length === 1
502 ? resolve(msg`Runs ${{ run: open[0]!.run.title }}`)
503 : resolve(msg`${{ count: open.length }} runs under way`);
504 }
505 return detail === ""
506 ? resolve(msg({ context: "what a workflow run is doing now" })`Waiting`)
507 : resolve(msg`Waiting for ${{ step: detail }}`);
508 case "completed": {
509 const line = workflowResultLines(run.result)[0];
510 if (line === undefined) {
511 return resolve(msg({ context: "what a workflow run is doing now" })`Finished`);
512 }
513 return firstLine(line.label === null ? line.value : `${line.label}: ${line.value}`);
514 }
515 case "stopped":
516 case "skipped":
517 case "cancelled":
518 return detail === "" ? resolve(msg("Ended early")) : firstLine(detail);
519 }
521​
522/** A run's result as lines a person can read: a sentence, or the fields of an object. */
523export function workflowResultLines(
524 result: WorkflowRun["result"],
525): ReadonlyArray<{ readonly label: string | null; readonly value: string }> {
526 if (result === null) return [];
527 if (typeof result !== "object") return [{ label: null, value: String(result) }];
528 if (Array.isArray(result)) return [{ label: null, value: JSON.stringify(result) }];
529 return Object.entries(result).map(([label, value]) => ({
530 label,
531 value: typeof value === "string" ? value : JSON.stringify(value),
532 }));
534​
535// A step this short is bookkeeping between the parts of a run that take time.
536const QUICK_STEP_MS = 1_000;
537​
538export interface WorkflowBeat {
539 readonly kind: WorkflowStep["kind"] | "run";
540 readonly name: string;
541 readonly status: WorkflowStep["status"];
542 readonly attempts: number;
543 /** A failure's reason, or when a sleep wakes. */
544 readonly detail: string | null;
545 /** What it produced: a value, an agent's data or reply, the answer to a question. */
546 readonly result: WorkflowStep["result"];
547 /** What an agent said in closing, when its result is data. */
548 readonly said: string | null;
549 /** For a step queued for a place in a pool, how many are ahead of it. */
550 readonly ahead: number | undefined;
551 readonly startMs: number;
552 /** When it ended, or `nowMs` while it is under way. */
553 readonly endMs: number;
554 readonly thread: { readonly threadId: string; readonly environmentId: string | null } | null;
555 /** The run this step invoked and waited for. */
556 readonly childRun: WorkflowRun | null;
557 /** Another beat was under way at the same time. */
558 readonly parallel: boolean;
560​
561export interface WorkflowQuickSteps {
562 readonly kind: "quick";
563 readonly steps: ReadonlyArray<WorkflowStep>;
564 readonly startMs: number;
565 readonly endMs: number;
567​
568export type WorkflowTimelineRow = WorkflowBeat | WorkflowQuickSteps;
569​
570export interface WorkflowTimeline {
571 readonly rows: ReadonlyArray<WorkflowTimelineRow>;
572 readonly startMs: number;
573 readonly endMs: number;
575​
576/**
577 * A run's steps as the story of the run: what took time or involved someone is a beat, and the
578 * quick steps between two beats fold into one row, since a journal of them hides where the run
579 * is. An invoked run takes the place of the two steps that started and awaited it.
580 */
581export function buildWorkflowTimeline(input: {
582 readonly run: Pick<WorkflowRun, "runId" | "startedAt" | "endedAt">;
583 readonly steps: ReadonlyArray<WorkflowStep>;
584 readonly children: ReadonlyArray<WorkflowRun>;
585 readonly nowMs: number;
586}): WorkflowTimeline {
587 const childByStep = new Map(
588 input.children
589 .filter((child) => child.parentRunId === input.run.runId && child.parentStep !== null)
590 .map((child) => [child.parentStep, child] as const),
591 );
592 const startMs = Date.parse(input.run.startedAt);
593 // A caller's clock can be a minute old. Now is never before anything the run has done.
594 const nowMs = Math.max(
595 input.nowMs,
596 startMs,
597 ...input.steps.map((step) => Date.parse(step.endedAt ?? step.startedAt)),
598 );
599 const endMs = input.run.endedAt === null ? nowMs : Date.parse(input.run.endedAt);
600 const rows: WorkflowTimelineRow[] = [];
601 const beats: WorkflowBeat[] = [];
602 let quick: WorkflowStep[] = [];
603 const flush = () => {
604 if (quick.length === 0) return;
605 rows.push({
606 kind: "quick",
607 steps: quick,
608 startMs: Date.parse(quick[0]!.startedAt),
609 endMs: Date.parse(quick.at(-1)!.endedAt ?? quick.at(-1)!.startedAt),
610 });
611 quick = [];
612 };
613 for (const step of input.steps) {
614 // The step that started an invoked run is told by the wait that follows it.
615 if (step.kind === "step" && step.name.endsWith("/start")) {
616 if (childByStep.has(step.name.slice(0, -"/start".length))) continue;
617 }
618 const stepStart = Date.parse(step.startedAt);
619 const stepEnd = step.endedAt === null ? nowMs : Date.parse(step.endedAt);
620 const childRun = step.kind === "wait" ? (childByStep.get(step.name) ?? null) : null;
621 // A place given at once is bookkeeping too; a wait for one is a beat.
622 const isBeat =
623 (step.kind !== "step" && step.kind !== "queue") ||
624 step.status !== "completed" ||
625 step.attempts > 1 ||
626 stepEnd - stepStart >= QUICK_STEP_MS;
627 if (!isBeat) {
628 quick.push(step);
629 continue;
630 }
631 flush();
632 const beat: WorkflowBeat = {
633 kind: childRun === null ? step.kind : "run",
634 name: step.name,
635 status: step.status,
636 attempts: step.attempts,
637 detail: step.detail,
638 result: step.result,
639 said: step.said,
640 ahead: step.ahead,
641 startMs: stepStart,
642 endMs: Math.max(stepStart, stepEnd),
643 thread:
644 step.threadId === null
645 ? null
646 : { threadId: step.threadId, environmentId: step.environmentId },
647 childRun,
648 parallel: false,
649 };
650 beats.push(beat);
651 rows.push(beat);
652 }
653 flush();
654 const overlaps = (left: WorkflowBeat, right: WorkflowBeat) =>
655 left !== right && left.startMs < openEnd(right) && right.startMs < openEnd(left);
656 return {
657 rows: rows.map((row) =>
658 row.kind === "quick"
659 ? row
660 : { ...row, parallel: beats.some((other) => overlaps(row, other)) },
661 ),
662 startMs,
663 endMs: Math.max(endMs, ...beats.map((beat) => beat.endMs), startMs + 1),
664 };
666​
667/** When a beat stops overlapping what starts after it: one still under way never does. */
668const openEnd = (beat: WorkflowBeat) =>
669 beat.status === "running" ? Number.POSITIVE_INFINITY : beat.endMs;
670​
671/** What a person answered a question with, when a step's result is such an answer. */
672export function workflowAnswer(result: WorkflowStep["result"]): {
673 readonly choice: string;
674 readonly reason: string | null;
675 /** The client, tool or agent thread that answered, by name; null on an answer kept before this. */
676 readonly answeredBy: string | null;
677 /** The client session that answered; null for a tool, an agent, or an answer kept before this. */
678 readonly answeredBySession: string | null;
679 readonly answeredAt: string | null;
680} | null {
681 const choice = field(result, "choice");
682 return typeof choice === "string"
683 ? {
684 choice,
685 reason: text(field(result, "reason")),
686 answeredBy: text(field(result, "answeredBy")),
687 answeredBySession: text(field(result, "answeredBySession")),
688 answeredAt: text(field(result, "answeredAt")),
689 }
690 : null;
692​
693/** Who withdrew a question unanswered, and why, when a step's result says so. */
694export function workflowWithdrawal(
695 result: WorkflowStep["result"],
696): { readonly by: string; readonly reason: string | null } | null {
697 const withdrawn = field(result, "withdrawn");
698 const by = field(withdrawn, "by");
699 const reason = field(withdrawn, "reason");
700 return typeof by === "string"
701 ? { by, reason: typeof reason === "string" && reason.trim() !== "" ? reason : null }
702 : null;
704​
705/**
706 * Whether the client whose session on the run's environment is `sessionId` gave `answer`. Decided
707 * by session, never by name: two browsers share "Chrome on Linux" and every phone its app's name.
708 */
709export const isOwnWorkflowAnswer = (
710 answer: { readonly answeredBySession: string | null },
711 sessionId: string | null | undefined,
712): boolean => answer.answeredBySession !== null && answer.answeredBySession === sessionId;
713​
714/** Steps that were under way at the same time, shown side by side. */
715export interface WorkflowTogether {
716 readonly kind: "together";
717 readonly beats: ReadonlyArray<WorkflowBeat>;
719​
720export type WorkflowFeedRow = WorkflowTimelineRow | WorkflowTogether;
721​
722/**
723 * The timeline as it is read: beats that overlapped become one row, so two reviewers at once look
724 * like two reviewers at once and not like one after the other.
725 */
726export function buildWorkflowFeed(timeline: WorkflowTimeline): ReadonlyArray<WorkflowFeedRow> {
727 const rows: WorkflowFeedRow[] = [];
728 let together: WorkflowBeat[] = [];
729 let until = 0;
730 const flush = () => {
731 if (together.length === 1) rows.push(together[0]!);
732 else if (together.length > 1) rows.push({ kind: "together", beats: together });
733 together = [];
734 };
735 for (const row of timeline.rows) {
736 if (row.kind === "quick") {
737 flush();
738 rows.push(row);
739 continue;
740 }
741 if (together.length > 0 && row.parallel && row.startMs < until) {
742 together.push(row);
743 until = Math.max(until, openEnd(row));
744 continue;
745 }
746 flush();
747 together = [row];
748 until = openEnd(row);
749 }
750 flush();
751 return rows;
753​
754/** The steps of a feed that take a place in the run's flow: every beat, in order. */
755const beatsOf = (rows: ReadonlyArray<WorkflowFeedRow>) =>
756 rows.flatMap((row) => (row.kind === "quick" ? [] : row.kind === "together" ? row.beats : [row]));
757​
758/**
759 * The step a paused run stopped at: the last that failed, unless the run went on after it, since
760 * then the workflow caught that failure. Null when the run is not paused at a step.
761 */
762export function workflowPausedBeat(
763 rows: ReadonlyArray<WorkflowFeedRow>,
764 status: WorkflowRun["status"],
765): WorkflowBeat | null {
766 if (status !== "paused") return null;
767 const failed = beatsOf(rows).findLast((beat) => beat.status === "failed");
768 if (failed === undefined) return null;
769 const wentOn = rows.some((row) =>
770 row.kind === "together"
771 ? row.beats.some((beat) => beat !== failed && beat.startMs >= failed.endMs)
772 : row !== failed && row.startMs >= failed.endMs,
773 );
774 return wentOn ? null : failed;
776​
777/**
778 * Which part of a run's flow to open on: what waits on a person, then where it failed, then how
779 * it ended, then what is under way. Keys are `step:<name>`, `question:<name>`, `pause` and `end`.
780 */
781export function workflowFlowFocus(input: {
782 readonly rows: ReadonlyArray<WorkflowFeedRow>;
783 readonly status: WorkflowRun["status"];
784 readonly ended: boolean;
785 /** The names of the questions that wait on a person. */
786 readonly questions: ReadonlyArray<string>;
787}): string | null {
788 const beats = beatsOf(input.rows);
789 const asked = input.questions[0];
790 if (asked !== undefined) {
791 const at = beats.find(
792 (beat) =>
793 beat.kind === "ask" && beat.status === "running" && input.questions.includes(beat.name),
794 );
795 return at === undefined ? `question:${asked}` : `step:${at.name}`;
796 }
797 if (input.status === "paused") {
798 const failed = workflowPausedBeat(input.rows, input.status);
799 return failed === null ? "pause" : `step:${failed.name}`;
800 }
801 if (input.ended) return "end";
802 const last = beats.findLast((beat) => beat.status === "running") ?? beats.at(-1);
803 return last === undefined ? null : `step:${last.name}`;
805​
806const FACT_LENGTH = 48;
807const FACTS_SHOWN = 6;
808// A string this long is the agent talking, not a fact about its work.
809const PROSE_LENGTH = 80;
810​
811const words = (key: string) =>
812 key
813 .replace(/([a-z0-9])([A-Z])/g, "$1 $2")
814 .replace(/[_-]+/g, " ")
815 .toLowerCase();
816​
817function factValue(value: unknown): string | null {
818 if (typeof value === "boolean") return value ? "yes" : "no";
819 if (typeof value === "number") return String(value);
820 if (typeof value === "string") {
821 const text = value.trim();
822 return text !== "" && text.length <= FACT_LENGTH && !text.includes("\n") ? text : null;
823 }
824 if (Array.isArray(value) && value.length > 0 && value.length <= 4) {
825 const parts = value.map(factValue);
826 const joined = parts.join(", ");
827 return parts.every((part) => part !== null) && joined.length <= FACT_LENGTH ? joined : null;
828 }
829 return null;
831​
832/**
833 * What an agent step has to say for itself: its words, and the short facts of its result. With no
834 * closing words kept, the longest piece of prose in the result stands in for them.
835 */
836export function workflowAgentSummary(beat: Pick<WorkflowBeat, "result" | "said">): {
837 readonly said: string | null;
838 readonly facts: ReadonlyArray<{ readonly label: string; readonly value: string }>;
839} {
840 const { result } = beat;
841 const kept = beat.said?.trim() ?? "";
842 if (typeof result === "string") {
843 return { said: kept !== "" ? kept : result.trim() === "" ? null : result.trim(), facts: [] };
844 }
845 if (result === null || typeof result !== "object" || Array.isArray(result)) {
846 return { said: kept === "" ? null : kept, facts: [] };
847 }
848 const entries = Object.entries(result);
849 const prose =
850 kept !== ""
851 ? null
852 : (entries
853 .filter(
854 (entry): entry is [string, string] =>
855 typeof entry[1] === "string" && entry[1].trim().length >= PROSE_LENGTH,
856 )
857 .slice()
858 .sort((left, right) => right[1].length - left[1].length)[0] ?? null);
859 return {
860 said: kept !== "" ? kept : (prose?.[1].trim() ?? null),
861 facts: entries
862 .flatMap(([key, value]) => {
863 const text = factValue(value);
864 return text === null ? [] : [{ label: words(key), value: text }];
865 })
866 .slice(0, FACTS_SHOWN),
867 };
869​
870/**
871 * The start of what an agent said, cut where a paragraph ends so no markup is left half open.
872 * Null when all of it fits.
873 */
874export function workflowSaidStart(said: string, limit: number): string | null {
875 if (said.length <= limit) return null;
876 const paragraphs = said.split(/\n{2,}/);
877 let kept = paragraphs[0]!;
878 for (const paragraph of paragraphs.slice(1)) {
879 if (kept.length + paragraph.length + 2 > limit) break;
880 kept = `${kept}\n\n${paragraph}`;
881 }
882 // One paragraph that runs on is cut at a word, which can still split markup but not a word.
883 // Text with no space before the limit, such as Chinese, is cut at the limit, never inside a
884 // surrogate pair.
885 if (kept.length > limit * 2) {
886 const space = kept.lastIndexOf(" ", limit);
887 const before = kept.charCodeAt(limit - 1);
888 const highSurrogateLast = before >= 0xd800 && before <= 0xdbff;
889 const end = space > 0 ? space : highSurrogateLast ? limit - 1 : limit;
890 kept = `${kept.slice(0, end)}…`;
891 }
892 return kept === said ? null : kept;
894​
895const decodeIssueAddress = Schema.decodeUnknownOption(WorkflowIssueAddress);
896const decodePullRequestAddress = Schema.decodeUnknownOption(WorkflowPullRequestAddress);
897​
898/** A reference's issue, when it is one and its address reads as one. */
899export function workflowReferenceIssue(reference: WorkflowRunSubject): IssueRef | null {
900 return reference.kind === WorkflowReferenceKind.issue
901 ? Option.getOrNull(decodeIssueAddress(reference.address))
902 : null;
904​
905/** A reference's pull request, when it is one and its address reads as one. */
906export function workflowReferencePullRequest(reference: WorkflowRunSubject): PullRequestRef | null {
907 return reference.kind === WorkflowReferenceKind.pullRequest
908 ? Option.getOrNull(decodePullRequestAddress(reference.address))
909 : null;
911​
912/** A reference's thread, when it is one, in the run's own environment. */
913export function workflowReferenceThreadId(reference: WorkflowRunSubject): string | null {
914 const threadId = field(reference.address, "threadId");
915 return reference.kind === WorkflowReferenceKind.thread && typeof threadId === "string"
916 ? threadId
917 : null;
919​
920/**
921 * What a reference is called in a chip: `#412` for an issue or pull request on a git host, a
922 * tracker's own key such as `ENG-12`, and otherwise the title, or the host of its web address.
923 */
924export function workflowReferenceLabel(reference: WorkflowRunSubject): string {
925 const pullRequest = workflowReferencePullRequest(reference);
926 if (pullRequest !== null) return `#${pullRequest.number}`;
927 const issue = workflowReferenceIssue(reference);
928 if (issue !== null) return /^\d+$/.test(issue.key) ? `#${issue.key}` : issue.key;
929 if (reference.title !== "") return reference.title;
930 const url = reference.url === null ? null : parseUrl(reference.url);
931 return url?.host ?? reference.kind;
933​
934/** The references a step touched, in the order the run first touched them. */
935export function workflowStepReferences(
936 references: ReadonlyArray<WorkflowRunReference>,
937 step: string,
938): ReadonlyArray<WorkflowRunReference> {
939 return references.filter((reference) => reference.steps.includes(step));
941​
942const tenthFormats = new Map<string | undefined, Intl.NumberFormat>();
943​
944/**
945 * A step's time in one shape down a column: 0.3s, 9.7s, 12s, then minutes. `locale` is the app's
946 * formatting locale; `undefined` follows the host's, like `Intl`.
947 */
948export function workflowStepTime(
949 ms: number,
950 resolve: M = mFallback,
951 locale: string | undefined,
952): string {
953 if (ms < 9_950 && ms % 1000 !== 0) {
954 let format = tenthFormats.get(locale);
955 if (!format) {
956 format = new Intl.NumberFormat(locale, {
957 minimumFractionDigits: 1,
958 maximumFractionDigits: 1,
959 });
960 tenthFormats.set(locale, format);
961 }
962 // Round with toFixed first: Intl rounds 1.45 up to 1.5, where the column has always read 1.4.
963 const seconds = format.format(Number((Math.max(ms, 100) / 1000).toFixed(1)));
964 return resolve(msg`${{ seconds }}s`);
965 }
966 const seconds = Math.round(ms / 1000);
967 if (seconds < 60) return resolve(msg`${{ seconds }}s`);
968 return formatDuration(ms, resolve);
970​
971function stripMarkdownLinks(text: string): string {
972 const scan = markdownLinkDestinationScanner(text);
973 const brackets = /\\[!\\[\]]|!\[|[[\]]/g;
974 const openers: Array<{ index: number; image: boolean; linkGeneration: number }> = [];
975 const matchedOpeners = new Set<number>();
976 const destinationEnds = new Map<number, number>();
977 let linkGeneration = 0;
978 for (let match = brackets.exec(text); match; match = brackets.exec(text)) {
979 if (match[0].endsWith("[") && !match[0].startsWith("\\")) {
980 const image = match[0] === "![";
981 openers.push({ index: match.index, image, linkGeneration });
982 continue;
983 }
984 if (match[0] !== "]") continue;
985 const opener = openers.pop();
986 if (opener === undefined) continue;
987 if (!opener.image && opener.linkGeneration !== linkGeneration) continue;
988 const dest = scan(match.index + 1);
989 if (dest === null) continue;
990 // A link deactivates all earlier link openers, even across image boundaries.
991 if (!opener.image) linkGeneration += 1;
992 matchedOpeners.add(opener.index);
993 destinationEnds.set(match.index, dest.end);
994 brackets.lastIndex = dest.end;
995 }
996 if (matchedOpeners.size === 0) return text;
997​
998 let out = "";
999 let cursor = 0;
1000 let labelDepth = 0;
1001 for (let match = brackets.exec(text); match; match = brackets.exec(text)) {
1002 const index = match.index;
1003 const end = destinationEnds.get(index);
1004 if (matchedOpeners.has(index)) {
1005 out += text.slice(cursor, index);
1006 cursor = brackets.lastIndex;
1007 labelDepth += 1;
1008 } else if (end !== undefined) {
1009 out += text.slice(cursor, index);
1010 cursor = end;
1011 brackets.lastIndex = end;
1012 labelDepth -= 1;
1013 } else if (labelDepth > 0 && match[0].startsWith("\\")) {
1014 out += text.slice(cursor, index) + match[0][1];
1015 cursor = brackets.lastIndex;
1018 return out + text.slice(cursor);
1020​
1021/**
1022 * The first prose sentence of a reply, as one line of plain text: headings, tables, and fenced
1023 * code blocks are skipped; indented text is a fallback. List marks, code, emphasis, and links read as words.
1024 * Code keeps its text, and an underscore inside a word, as in snake_case, is not emphasis.
1025 */
1026export function workflowOneLine(text: string): string {
1027 let fence: string | null = null;
1028 let fenceQuoteDepth = 0;
1029 let indented: string | undefined;
1030 const line =
1031 text
1032 .split(/\r\n?|\n/)
1033 .find((candidate) => {
1034 const quote = /^(?: {0,3}>[ \t]?)+/.exec(candidate)?.[0] ?? "";
1035 const quoteDepth = quote.replace(/[^>]/g, "").length;
1036 const content = candidate.slice(quote.length);
1037 const [, marker, rest] = /^ {0,3}(`{3,}|~{3,})([^\n]*)$/.exec(content) ?? [];
1038 if (quoteDepth < fenceQuoteDepth) fence = null;
1039 if (fence !== null) {
1040 if (
1041 quoteDepth === fenceQuoteDepth &&
1042 marker?.startsWith(fence) &&
1043 /^[ \t]*$/.test(rest ?? "")
1044 ) {
1045 fence = null;
1047 return false;
1049 if (marker !== undefined && !(marker[0] === "`" && rest?.includes("`"))) {
1050 fence = marker;
1051 fenceQuoteDepth = quoteDepth;
1052 return false;
1054 if (
1055 /^\s*$/.test(content) ||
1056 /^ {0,3}#{1,6}(?:[ \t]|$)/.test(content) ||
1057 /^[ \t]*\|/.test(candidate)
1059 return false;
1060 if (!/^(?: {4}| {0,3}\t)/.test(content)) return true;
1061 indented ??= candidate;
1062 return false;
1063 })
1064 ?.trim() ??
1065 indented?.trim() ??
1066 "";
1067 const code: string[] = [];
1068 const stripped = line
1069 .replace(/^(?:>\s*)+/, "")
1070 .replace(/^([-*]|\d+\.)\s+/, "")
1071 .replace(/(`+)(.+?)\1(?!`)/g, (_, _ticks, inner: string) => `\0${code.push(inner) - 1}\0`);
1072 const plain = stripMarkdownLinks(stripped)
1073 .replace(/(?<![\p{L}\p{M}\p{N}_/])(__|_)(\S(?:.*?\S)?)\1(?![\p{L}\p{M}\p{N}_/])/gu, "$2")
1074 // A glob star is not an emphasis delimiter: none opens beside a path separator or as `*.ext`,
1075 // and none closes after a separator, so `src/**/*.ts` and `*.ts,*.tsx` stay as written.
1076 .replace(
1077 /(?<![/\\*])(?!\*\.[\p{L}\p{N}_{*])(\*{1,3})(?![*/])(\S(?:.*?\S)??)(?<![/\\*])\1(?!\*)/gu,
1078 "$2",
1080 .replace(/\0(\d+)\0/g, (match, index: string) => code[Number(index)] ?? match);
1081 const end = plain.search(/[.!?](\s|$)/);
1082 return end === -1 ? plain : plain.slice(0, end + 1);