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

workflow.ts

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