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

workflow.ts

356 lines14.3 KB

1import * as Schema from "effect/Schema";
2​
3import { IssueRef } from "./issue.ts";
4import { PullRequestRef } from "./pullRequest.ts";
5​
6export const WorkflowRunStatus = Schema.Literals([
7 "running",
8 "waiting",
9 "paused",
10 "completed",
11 "stopped",
12 /** Ended by the workflow as not its to do. Lists leave these out unless asked. */
13 "skipped",
14 "cancelled",
15]);
16export type WorkflowRunStatus = typeof WorkflowRunStatus.Type;
17​
18/**
19 * The one thing a run is about, as the workflow declared it: an issue, a pull request, a thread
20 * or a web address. Its `kind`, `key` and `address` read as a `WorkflowRunReference`'s.
21 */
22export const WorkflowRunSubject = Schema.Struct({
23 kind: Schema.String,
24 key: Schema.String,
25 address: Schema.Json,
26 /** Empty until something that touched it knew its title. */
27 title: Schema.String,
28 url: Schema.NullOr(Schema.String),
29});
30export type WorkflowRunSubject = typeof WorkflowRunSubject.Type;
31​
32/**
33 * Where a run is, in a line: how many of its steps finished and failed, and the step it is on
34 * now. Lists draw progress from it without reading each run's steps.
35 */
36export const WorkflowRunProgress = Schema.Struct({
37 done: Schema.Number,
38 failed: Schema.Number,
39 /** The step started last, with what kind it is and where it stands. */
40 step: Schema.NullOr(
41 Schema.Struct({
42 name: Schema.String,
43 kind: Schema.String,
44 status: Schema.String,
45 startedAt: Schema.String,
46 }),
47 ),
48});
49export type WorkflowRunProgress = typeof WorkflowRunProgress.Type;
50​
51export const WorkflowRun = Schema.Struct({
52 runId: Schema.String,
53 workflow: Schema.String,
54 version: Schema.Number,
55 title: Schema.String,
56 status: WorkflowRunStatus,
57 /** Why it is paused, what it waits on, or how it ended. */
58 detail: Schema.NullOr(Schema.String),
59 result: Schema.NullOr(Schema.Json),
60 /** How many times in a row it has been paused by a failing step. */
61 pauses: Schema.Number,
62 /** Its version is no longer registered, so it cannot go on until that version is back. */
63 retired: Schema.Boolean,
64 /** When a paused run is resumed without anyone asking; null when it waits for a person. */
65 resumesAt: Schema.NullOr(Schema.String),
66 /** The run that invoked this one and waits for it; null for a run started by itself. */
67 parentRunId: Schema.NullOr(Schema.String),
68 /** The step of that run this one was invoked as. */
69 parentStep: Schema.NullOr(Schema.String),
70 /** What the workflow tagged the run with, for filtering. Absent for a run with no tags. */
71 tags: Schema.optional(Schema.Array(Schema.String)),
72 /** What the run is about. Absent for a run that declared nothing. */
73 subject: Schema.optional(WorkflowRunSubject),
74 /** In lists only: where the run is. Absent for a run with no steps yet. */
75 progress: Schema.optional(WorkflowRunProgress),
76 startedAt: Schema.String,
77 updatedAt: Schema.String,
78 endedAt: Schema.NullOr(Schema.String),
79});
80export type WorkflowRun = typeof WorkflowRun.Type;
81​
82export const WorkflowStep = Schema.Struct({
83 name: Schema.String,
84 // A sleep's `detail` is when it wakes, as an ISO time. A `queue` step waits for a place in a pool.
85 kind: Schema.Literals(["step", "wait", "agent", "ask", "sleep", "queue"]),
86 status: Schema.Literals(["running", "completed", "failed"]),
87 attempts: Schema.Number,
88 detail: Schema.NullOr(Schema.String),
89 /** The thread an agent step ran in. */
90 threadId: Schema.NullOr(Schema.String),
91 /** The linked environment that thread is in; null when it is this one. */
92 environmentId: Schema.NullOr(Schema.String),
93 /** What it produced: a step's value, an agent's data or reply, the answer to a question. */
94 result: Schema.NullOr(Schema.Json),
95 /** What an agent said in closing, when its result is data and not that reply. */
96 said: Schema.NullOr(Schema.String),
97 /** For a `queue` step still waiting, how many asked for a place in its pool before it. */
98 ahead: Schema.optional(Schema.Number),
99 startedAt: Schema.String,
100 endedAt: Schema.NullOr(Schema.String),
101});
102export type WorkflowStep = typeof WorkflowStep.Type;
103​
104/** A question a run asked. Answer it with a signal to its run and name. */
105export const WorkflowQuestion = Schema.Struct({
106 runId: Schema.String,
107 name: Schema.String,
108 /** What `ask` was given: a title, the choices, and data to lay out. */
109 request: Schema.Json,
110 /** The kind of question its workflow declared for it. Absent for a question asked without one. */
111 kind: Schema.optional(Schema.String),
112 askedAt: Schema.String,
113 /** The run's latest agent thread, for talking it through before answering. */
114 thread: Schema.NullOr(
115 Schema.Struct({ threadId: Schema.String, environmentId: Schema.NullOr(Schema.String) }),
116 ),
117});
118export type WorkflowQuestion = typeof WorkflowQuestion.Type;
119​
120/** Where a workflow takes requests. `path` holds the hook's secret. */
121export const WorkflowHook = Schema.Struct({
122 workflow: Schema.String,
123 name: Schema.String,
124 path: Schema.String,
125});
126export type WorkflowHook = typeof WorkflowHook.Type;
127​
128/** What a client shows of workflows: recent runs, newest first, and the questions still open. */
129/** A workflow this server has registered, at its newest version, and what starts it. */
130export const WorkflowSummary = Schema.Struct({
131 name: Schema.String,
132 version: Schema.Number,
133 /** In words: "every 1h", "daily at 09:00", "webhook issues". Empty when only started by hand. */
134 triggers: Schema.Array(Schema.String),
135 /** The kinds of question it declares, in that order, each with its label. Absent when none. */
136 asks: Schema.optional(Schema.Array(Schema.Struct({ kind: Schema.String, label: Schema.String }))),
137});
138export type WorkflowSummary = typeof WorkflowSummary.Type;
139​
140/** Something wrong with the definitions: in `file` when it is one file's, at `line` when it names one. */
141export const WorkflowDefinitionProblem = Schema.Struct({
142 message: Schema.String,
143 file: Schema.optional(Schema.String),
144 line: Schema.optional(Schema.Number),
145});
146export type WorkflowDefinitionProblem = typeof WorkflowDefinitionProblem.Type;
147​
148/** Which loading of the definitions file is running, and what is wrong with the file now. */
149export const WorkflowDefinitionState = Schema.Struct({
150 /** Goes up whenever the file is loaded or found wrong, so a client knows to read it again. */
151 revision: Schema.Number,
152 /** Why the file on disk is not what runs. The last version that loaded keeps running. */
153 problem: Schema.NullOr(Schema.String),
154});
155​
156export const WorkflowDefinitionFile = Schema.Struct({
157 name: Schema.String,
158 /** The file as it is on disk, which is not what runs while it has problems. */
159 source: Schema.String,
160 /** The workflows its last good version defines, each as `name@version`. */
161 workflows: Schema.Array(Schema.String),
162 problems: Schema.Array(WorkflowDefinitionProblem),
163});
164export type WorkflowDefinitionFile = typeof WorkflowDefinitionFile.Type;
165​
166/** The files that define this server's workflows. */
167export const WorkflowDefinitionFiles = Schema.Struct({
168 /** The folder the files are in. */
169 directory: Schema.String,
170 /** The server was pointed at one file: no file can be added beside it or taken away. */
171 single: Schema.Boolean,
172 files: Schema.Array(WorkflowDefinitionFile),
173 /** What is wrong between files, such as one workflow defined in two of them. */
174 problems: Schema.Array(WorkflowDefinitionProblem),
175 ...WorkflowDefinitionState.fields,
176});
177export type WorkflowDefinitionFiles = typeof WorkflowDefinitionFiles.Type;
178​
179export const WorkflowDefinitionGetInput = Schema.Struct({});
180/** A file by its name in the folder. Saving a name that is not there yet makes the file. */
181export const WorkflowDefinitionSaveInput = Schema.Struct({
182 name: Schema.String,
183 source: Schema.String,
184});
185export const WorkflowDefinitionDeleteInput = Schema.Struct({ name: Schema.String });
186export const WorkflowDefinitionChangeResult = Schema.Struct({
187 /** The file was written or deleted. */
188 changed: Schema.Boolean,
189 /** Empty when the change is what runs now. With `changed`, why it does not run yet. */
190 problems: Schema.Array(WorkflowDefinitionProblem),
191});
192export type WorkflowDefinitionChangeResult = typeof WorkflowDefinitionChangeResult.Type;
193​
194export const WorkflowRunsSnapshot = Schema.Struct({
195 workflows: Schema.Array(WorkflowSummary),
196 runs: Schema.Array(WorkflowRun),
197 questions: Schema.Array(WorkflowQuestion),
198 definition: Schema.optional(WorkflowDefinitionState),
199});
200​
201/** How much is going on, for a badge that must not cost a list of runs to keep current. */
202export const WorkflowCounts = Schema.Struct({
203 /** Open questions and paused runs: what waits on a person. */
204 needsYou: Schema.Number,
205 /** Runs that have not ended. */
206 active: Schema.Number,
207 /** Runs there have ever been, so a client knows whether workflows are in use at all. */
208 total: Schema.Number,
209});
210export type WorkflowCounts = typeof WorkflowCounts.Type;
211export type WorkflowRunsSnapshot = typeof WorkflowRunsSnapshot.Type;
212​
213/** What changed in the runs list since the last frame a watcher was sent. */
214export const WorkflowRunsChange = Schema.TaggedStruct("changed", {
215 /** Runs new to the list or different from what was last sent. */
216 runs: Schema.Array(WorkflowRun),
217 /** Runs that left the list. */
218 removed: Schema.Array(Schema.String),
219 /** Questions newly asked or different from what was last sent. */
220 questions: Schema.Array(WorkflowQuestion),
221 /** Questions no longer open, by run and question name. */
222 closed: Schema.Array(Schema.Struct({ runId: Schema.String, name: Schema.String })),
223});
224​
225/**
226 * A frame of `workflows.subscribe`: the whole list, or with `changes` asked for, what changed
227 * since the last frame. A server older than `changes` ignores it and sends whole lists.
228 */
229export const WorkflowRunsUpdate = Schema.Union([WorkflowRunsSnapshot, WorkflowRunsChange]);
230export type WorkflowRunsUpdate = typeof WorkflowRunsUpdate.Type;
231​
232/** The list once `update` is applied, in the order the server lists runs: newest first. */
233export function applyWorkflowRunsUpdate(
234 snapshot: WorkflowRunsSnapshot | undefined,
235 update: WorkflowRunsUpdate,
236): WorkflowRunsSnapshot {
237 if (!("_tag" in update)) return update;
238 const base = snapshot ?? { workflows: [], runs: [], questions: [] };
239 // Stable sorts, so entries of the same moment keep the order they were sent in.
240 const runs = merged(base.runs, update.runs, update.removed, (run) => run.runId).sort(
241 (left, right) =>
242 left.startedAt === right.startedAt ? 0 : left.startedAt < right.startedAt ? 1 : -1,
243 );
244 const questions = merged(
245 base.questions,
246 update.questions,
247 update.closed.map(workflowQuestionKey),
248 workflowQuestionKey,
249 ).sort((left, right) =>
250 left.askedAt === right.askedAt ? 0 : left.askedAt < right.askedAt ? -1 : 1,
251 );
252 return { ...base, runs, questions };
254​
255/** What names an open question: one run asks one question of a name at a time. */
256export const workflowQuestionKey = (question: { readonly runId: string; readonly name: string }) =>
257 JSON.stringify([question.runId, question.name]);
258​
259/** `held` with `changed` put in place of their earlier versions and `gone` left out. */
260function merged<A>(
261 held: ReadonlyArray<A>,
262 changed: ReadonlyArray<A>,
263 gone: ReadonlyArray<string>,
264 key: (entry: A) => string,
265): Array<A> {
266 const fresh = new Map(changed.map((entry) => [key(entry), entry]));
267 const left = new Set(gone);
268 const kept = held.flatMap((entry) => {
269 const id = key(entry);
270 if (left.has(id)) return [];
271 const next = fresh.get(id);
272 fresh.delete(id);
273 return [next ?? entry];
274 });
275 return [...fresh.values(), ...kept];
277​
278export const WorkflowRunsSubscribeInput = Schema.Struct({
279 /** Send what changed after the first list instead of the whole list every time. */
280 changes: Schema.optionalKey(Schema.Boolean),
281});
282​
283export const WorkflowRunGetInput = Schema.Struct({ runId: Schema.String });
284​
285/**
286 * Runs whose subject is at the web address `subject`, or is the `issue` or `pullRequest` given:
287 * a listing and an item's own view do not always write one item's address the same way.
288 */
289export const WorkflowRunsAboutInput = Schema.Struct({
290 subject: Schema.String,
291 issue: Schema.optionalKey(IssueRef),
292 pullRequest: Schema.optionalKey(PullRequestRef),
293});
294export type WorkflowRunsAboutInput = typeof WorkflowRunsAboutInput.Type;
295/** Those runs, newest first and 500 at most, with the questions they have open. */
296export const WorkflowRunsAbout = Schema.Struct({
297 runs: Schema.Array(WorkflowRun),
298 questions: Schema.Array(WorkflowQuestion),
299});
300export type WorkflowRunsAbout = typeof WorkflowRunsAbout.Type;
301​
302/**
303 * Something a run touched: an issue, a pull request, or a kind added later. `kind` is open, so a
304 * client shows a kind it does not know by its title and `url`. `key` is the thing's identity in
305 * its kind; `address` is whatever that kind needs to open it.
306 */
307export const WorkflowRunReference = Schema.Struct({
308 ...WorkflowRunSubject.fields,
309 /** A word for where it stands, such as `open`, `merged` or `closed`. */
310 state: Schema.NullOr(Schema.String),
311 /** The steps that touched it, in the order they first did. */
312 steps: Schema.Array(Schema.String),
313 origin: Schema.Literals(["trigger", "step"]),
314});
315export type WorkflowRunReference = typeof WorkflowRunReference.Type;
316​
317/**
318 * The kinds of reference runs record today. `address` is an `IssueRef`, a `PullRequestRef`,
319 * `{ threadId }` or `{ url }`.
320 */
321export const WorkflowReferenceKind = {
322 issue: "issue",
323 pullRequest: "pullRequest",
324 thread: "thread",
325 url: "url",
326} as const;
327export const WorkflowIssueAddress = IssueRef;
328export const WorkflowPullRequestAddress = PullRequestRef;
329​
330/** One run with its steps, in the order they started, and what it touched. */
331export const WorkflowRunDetail = Schema.Struct({
332 run: WorkflowRun,
333 steps: Schema.Array(WorkflowStep),
334 references: Schema.Array(WorkflowRunReference),
335});
336export type WorkflowRunDetail = typeof WorkflowRunDetail.Type;
337​
338/** A person's answer to a `WorkflowQuestion`: one of its choices and, if they gave one, why. */
339export const WorkflowAnswerInput = Schema.Struct({
340 runId: Schema.String,
341 name: Schema.String,
342 choice: Schema.String,
343 reason: Schema.optional(Schema.String),
344});
345​
346export const WorkflowRunResumeInput = Schema.Struct({ runId: Schema.String });
347​
348export const WorkflowRunCancelInput = Schema.Struct({
349 runId: Schema.String,
350 reason: Schema.optional(Schema.String),
351});
352​
353export class WorkflowRequestError extends Schema.TaggedError<WorkflowRequestError>()(
354 "WorkflowRequestError",
355 { message: Schema.String },
356) {}