@niwa-labs/flow 0.0.0-stage → 0.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +30 -2
- package/package.json +14 -4
- package/src/graph.ts +115 -0
- package/src/group.ts +189 -0
- package/src/index.ts +15 -0
- package/src/judge.ts +227 -0
- package/src/loop.ts +150 -0
- package/src/script.ts +129 -0
- package/src/types.ts +62 -0
- package/src/wait.ts +81 -0
- package/test/group.test.ts +331 -0
- package/test/judge.test.ts +215 -0
- package/test/order.test.ts +108 -0
- package/test/support.ts +146 -0
- package/test/wait.test.ts +151 -0
- package/tsconfig.json +6 -0
package/src/loop.ts
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Loops: each round runs in a branch of its own (`r1`, `r2`, ...) of the loop's scope, so what a
|
|
3
|
+
* round calls, a helper inside it included, is keyed by its round. Every loop has a most rounds,
|
|
4
|
+
* and says whether it stopped there.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { map } from "./group.ts";
|
|
8
|
+
import { checkKey, script } from "./script.ts";
|
|
9
|
+
import type { Seat } from "./script.ts";
|
|
10
|
+
import { passes } from "./types.ts";
|
|
11
|
+
import type { Attempt, Judged, Settled } from "./types.ts";
|
|
12
|
+
|
|
13
|
+
/** Check a most rounds: a whole number, at least one. */
|
|
14
|
+
function checkMax(max: number, what: string): number {
|
|
15
|
+
if (!Number.isInteger(max) || max < 1) throw new TypeError(`${what}: the most rounds is a whole number, at least one, not ${String(max)}`);
|
|
16
|
+
return max;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** Step a state until `done` says it is, or for `max` rounds. A state that is done from the start takes no round. */
|
|
20
|
+
export async function loop<S>(
|
|
21
|
+
key: string,
|
|
22
|
+
opts: { init: S; step: (state: S, round: number) => Promise<S>; done: (state: S) => boolean; max: number },
|
|
23
|
+
): Promise<{ state: S; rounds: number; hitMax: boolean }> {
|
|
24
|
+
checkKey(key, "the key of a loop");
|
|
25
|
+
checkMax(opts.max, "loop");
|
|
26
|
+
return script().scope(key, undefined, async (s) => {
|
|
27
|
+
let state = opts.init;
|
|
28
|
+
let rounds = 0;
|
|
29
|
+
while (!opts.done(state)) {
|
|
30
|
+
if (rounds === opts.max) return { state, rounds, hitMax: true };
|
|
31
|
+
rounds += 1;
|
|
32
|
+
const before = state;
|
|
33
|
+
const round = rounds;
|
|
34
|
+
state = await s.start(`r${String(round)}`, () => opts.step(before, round)).value();
|
|
35
|
+
}
|
|
36
|
+
return { state, rounds, hitMax: false };
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Gather items round by round until `quietRounds` rounds in a row bring nothing new (one by
|
|
42
|
+
* default), or `max` rounds (ten by default). An item is new when `same` matches none seen.
|
|
43
|
+
*/
|
|
44
|
+
export async function saturate<T>(
|
|
45
|
+
key: string,
|
|
46
|
+
opts: { step: (seen: T[], round: number) => Promise<T[]>; same: (a: T, b: T) => boolean; quietRounds?: number; max?: number },
|
|
47
|
+
): Promise<{ items: T[]; rounds: number; saturated: boolean }> {
|
|
48
|
+
checkKey(key, "the key of a saturation");
|
|
49
|
+
const max = checkMax(opts.max ?? 10, "saturate");
|
|
50
|
+
const quietRounds = checkMax(opts.quietRounds ?? 1, "saturate (quiet rounds)");
|
|
51
|
+
return script().scope(key, undefined, async (s) => {
|
|
52
|
+
const items: T[] = [];
|
|
53
|
+
let quiet = 0;
|
|
54
|
+
for (let round = 1; round <= max; round += 1) {
|
|
55
|
+
const seen = [...items];
|
|
56
|
+
const found = await s.start(`r${String(round)}`, () => opts.step(seen, round)).value();
|
|
57
|
+
let fresh = 0;
|
|
58
|
+
for (const item of found) {
|
|
59
|
+
if (items.some((one) => opts.same(one, item))) continue;
|
|
60
|
+
items.push(item);
|
|
61
|
+
fresh += 1;
|
|
62
|
+
}
|
|
63
|
+
quiet = fresh === 0 ? quiet + 1 : 0;
|
|
64
|
+
if (quiet >= quietRounds) return { items, rounds: round, saturated: true };
|
|
65
|
+
}
|
|
66
|
+
return { items, rounds: max, saturated: false };
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** Every combination of a grid, in the order of its keys and values. */
|
|
71
|
+
export function gridCells<P>(grid: Record<string, readonly P[]>): Record<string, P>[] {
|
|
72
|
+
let cells: Record<string, P>[] = [{}];
|
|
73
|
+
for (const [name, values] of Object.entries(grid)) cells = cells.flatMap((cell) => values.map((value) => ({ ...cell, [name]: value })));
|
|
74
|
+
return cells;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** A cell of a grid that ran: its parameters, how it ended, and its score, which is null for a cell that failed. */
|
|
78
|
+
export type GridCell<P, R> = { params: Record<string, P>; result: Settled<R>; score: number | null };
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Run every cell of a grid of parameters and score it. A cell that failed has no score (null), and
|
|
82
|
+
* a score of a cell that ran must be a finite number; `best` is the index of the cell with the
|
|
83
|
+
* highest score, the first of equals, or -1 when every cell failed.
|
|
84
|
+
*/
|
|
85
|
+
export async function paramGrid<P, R>(
|
|
86
|
+
key: string,
|
|
87
|
+
opts: { grid: Record<string, readonly P[]>; run: (cell: Record<string, P>) => Promise<R>; score: (result: R) => number; concurrency?: number },
|
|
88
|
+
): Promise<{ cells: GridCell<P, R>[]; best: number }> {
|
|
89
|
+
checkKey(key, "the key of a grid");
|
|
90
|
+
const params = gridCells(opts.grid);
|
|
91
|
+
const results = await map(
|
|
92
|
+
key,
|
|
93
|
+
params.map((cell, index) => ({ cell, key: `c${String(index)}` })),
|
|
94
|
+
{ key: (one) => one.key, ...(opts.concurrency === undefined ? {} : { concurrency: opts.concurrency }) },
|
|
95
|
+
(one) => opts.run(one.cell),
|
|
96
|
+
);
|
|
97
|
+
const cells = results.map((result, index): GridCell<P, R> => {
|
|
98
|
+
const score = result.ok ? opts.score(result.value) : null;
|
|
99
|
+
if (score !== null && !Number.isFinite(score)) throw new TypeError(`paramGrid "${key}": the score of the cell c${String(index)} is ${String(score)}, a finite number is needed`);
|
|
100
|
+
return { params: params[index] as Record<string, P>, result, score };
|
|
101
|
+
});
|
|
102
|
+
let best = -1;
|
|
103
|
+
cells.forEach((cell, index) => {
|
|
104
|
+
if (cell.score !== null && (best < 0 || cell.score > ((cells[best] as GridCell<P, R>).score as number))) best = index;
|
|
105
|
+
});
|
|
106
|
+
return { cells, best };
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* Write, judge, and write again with the judgement, until a judgement passes or for `max` rounds
|
|
111
|
+
* (three by default). The first round's `write` gets no feedback. `INCONCLUSIVE` is not a pass.
|
|
112
|
+
*/
|
|
113
|
+
export async function revise<T>(
|
|
114
|
+
key: string,
|
|
115
|
+
opts: { write: (feedback: Judged | null, round: number) => Promise<T>; judge: (value: T, round: number) => Promise<Judged>; max?: number },
|
|
116
|
+
): Promise<Attempt<T>> {
|
|
117
|
+
checkKey(key, "the key of a revision");
|
|
118
|
+
const max = checkMax(opts.max ?? 3, "revise");
|
|
119
|
+
return script().scope(key, undefined, async (s) => {
|
|
120
|
+
const history: Judged[] = [];
|
|
121
|
+
let feedback: Judged | null = null;
|
|
122
|
+
let last: { value: T; judged: Judged } | undefined;
|
|
123
|
+
for (let round = 1; round <= max; round += 1) {
|
|
124
|
+
const given = feedback;
|
|
125
|
+
last = await s
|
|
126
|
+
.start(`r${String(round)}`, async () => {
|
|
127
|
+
const value = await opts.write(given, round);
|
|
128
|
+
return { value, judged: await opts.judge(value, round) };
|
|
129
|
+
})
|
|
130
|
+
.value();
|
|
131
|
+
history.push(last.judged);
|
|
132
|
+
if (passes(last.judged)) return { value: last.value, judged: last.judged, rounds: round, history, stopped: "accepted" as const };
|
|
133
|
+
feedback = last.judged;
|
|
134
|
+
}
|
|
135
|
+
const final = last as { value: T; judged: Judged };
|
|
136
|
+
return { value: final.value, judged: final.judged, rounds: max, history, stopped: "max-rounds" as const };
|
|
137
|
+
});
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* `revise` up a ladder of seats: round one writes with the first seat, each round after a failed
|
|
142
|
+
* judgement with the next one, as many rounds as there are seats.
|
|
143
|
+
*/
|
|
144
|
+
export function escalate<T>(
|
|
145
|
+
key: string,
|
|
146
|
+
opts: { seats: readonly Seat[]; write: (seat: Seat, feedback: Judged | null, round: number) => Promise<T>; judge: (value: T, round: number) => Promise<Judged> },
|
|
147
|
+
): Promise<Attempt<T>> {
|
|
148
|
+
if (opts.seats.length === 0) return Promise.reject(new TypeError("escalate: give at least one seat"));
|
|
149
|
+
return revise(key, { max: opts.seats.length, write: (feedback, round) => opts.write(opts.seats[round - 1] as Seat, feedback, round), judge: opts.judge });
|
|
150
|
+
}
|
package/src/script.ts
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What the helpers take of the script they run in.
|
|
3
|
+
*
|
|
4
|
+
* A helper runs inside a workflow script and calls the script's own globals (`scope`, `agent`,
|
|
5
|
+
* `ask`, ...), read when it is called: this package imports nothing of the script runtime, only its
|
|
6
|
+
* types. Every helper opens a scope named by the key it is given, and the calls it makes are
|
|
7
|
+
* unlabeled: they are keyed by the branch they are made in, so a replay finds each answer where it
|
|
8
|
+
* left it, and a helper called again in the next round of a loop does not collide with the last.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import type { SessionOptions, ScriptApi, Settled } from "@niwa-labs/script";
|
|
12
|
+
|
|
13
|
+
/** The globals of a script the helpers use. */
|
|
14
|
+
export type ScriptGlobals = Pick<ScriptApi, "z" | "session" | "call" | "scope" | "parallel" | "stream" | "wait" | "sleep" | "read" | "ask" | "now" | "random">;
|
|
15
|
+
|
|
16
|
+
const NEEDED = ["ask", "call", "scope", "parallel", "stream", "wait", "sleep", "now", "random"] as const;
|
|
17
|
+
|
|
18
|
+
/** The zod of the script: a global of every script process, whether it runs the script or reads its schemas. */
|
|
19
|
+
export function zod(): ScriptGlobals["z"] {
|
|
20
|
+
const found = (globalThis as unknown as { z?: unknown }).z;
|
|
21
|
+
if (typeof found !== "object" || found === null) throw new Error('@niwa-labs/flow runs inside a workflow script: "z" is not a global here');
|
|
22
|
+
return found as ScriptGlobals["z"];
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** The globals of the script that calls a helper. */
|
|
26
|
+
export function script(): ScriptGlobals {
|
|
27
|
+
const globals = globalThis as unknown as Partial<Record<string, unknown>>;
|
|
28
|
+
for (const name of NEEDED) {
|
|
29
|
+
if (typeof globals[name] !== "function") throw new Error(`@niwa-labs/flow runs inside a workflow script: "${name}" is not a global here`);
|
|
30
|
+
}
|
|
31
|
+
for (const name of ["z", "read"] as const) {
|
|
32
|
+
if (typeof globals[name] !== "object" || globals[name] === null) throw new Error(`@niwa-labs/flow runs inside a workflow script: "${name}" is not a global here`);
|
|
33
|
+
}
|
|
34
|
+
return globals as unknown as ScriptGlobals;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* A key of a branch or the name of a scope, as the script runtime takes it: a text that is not
|
|
39
|
+
* empty and holds none of the marks a step key is made of. A key is checked before anything
|
|
40
|
+
* runs, so a bad one fails the call before its first effect.
|
|
41
|
+
*/
|
|
42
|
+
export function checkKey(key: unknown, what: string): string {
|
|
43
|
+
if (typeof key !== "string" || key === "") throw new TypeError(`${what} is a text that is not empty`);
|
|
44
|
+
if (/[.~/:\s]/.test(key) || key.startsWith("@") || /^call-\d+$/.test(key)) {
|
|
45
|
+
throw new TypeError(`${what} "${key}" may not hold ".", "~", "/", ":" or a space, start with "@" or be call-<n>`);
|
|
46
|
+
}
|
|
47
|
+
return key;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** Check a list of keys: each one a key, and no two the same. */
|
|
51
|
+
export function checkKeys(keys: readonly string[], what: string): string[] {
|
|
52
|
+
const seen = new Set<string>();
|
|
53
|
+
for (const key of keys) {
|
|
54
|
+
checkKey(key, what);
|
|
55
|
+
if (seen.has(key)) throw new TypeError(`${what} "${key}" is given twice: a key names one branch`);
|
|
56
|
+
seen.add(key);
|
|
57
|
+
}
|
|
58
|
+
return [...keys];
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* A seat: who takes a part in a helper. A name of a harness, or the options of an `ask()` call
|
|
63
|
+
* with the harness in them; `vendor` says whose model it is, for the helpers that want judges
|
|
64
|
+
* independent of an author, and `label` is the seat's name in the results, never a call's label.
|
|
65
|
+
*/
|
|
66
|
+
export type Seat = string | SeatOptions;
|
|
67
|
+
|
|
68
|
+
/** A seat written out: the options of its `ask()` calls, with the harness, and who it is. */
|
|
69
|
+
export type SeatOptions = Omit<SessionOptions, "label" | "worktree"> & { harness: string; vendor?: string; label?: string };
|
|
70
|
+
|
|
71
|
+
/** The harness of a seat. */
|
|
72
|
+
export const harnessOf = (seat: Seat): string => (typeof seat === "string" ? seat : seat.harness);
|
|
73
|
+
|
|
74
|
+
/** Whose model a seat is: what it says, else its harness. */
|
|
75
|
+
export const vendorOf = (seat: Seat): string => (typeof seat === "string" ? seat : (seat.vendor ?? seat.harness));
|
|
76
|
+
|
|
77
|
+
/** The options of an `ask()` call of a seat: no label, which would name one call of the whole run, and no worktree. */
|
|
78
|
+
export function sessionOptions(seat: Seat): Omit<SessionOptions, "worktree"> {
|
|
79
|
+
if (typeof seat === "string") return { harness: seat };
|
|
80
|
+
const { vendor: _vendor, label: _label, ...options } = seat;
|
|
81
|
+
return options;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* The keys of seats in the order given: the seat's label, else its harness; a seat met again is
|
|
86
|
+
* numbered (`judge`, `judge-2`), so the same harness may sit twice. The names the seats were
|
|
87
|
+
* given are kept as they are: a number is never one of them, so the keys are all different.
|
|
88
|
+
*/
|
|
89
|
+
export function seatKeys(seats: readonly Seat[], what: string): string[] {
|
|
90
|
+
const names = seats.map((seat) => (typeof seat === "string" ? seat : (seat.label ?? seat.harness)));
|
|
91
|
+
const taken = new Set(names);
|
|
92
|
+
const counts = new Map<string, number>();
|
|
93
|
+
return names.map((name) => {
|
|
94
|
+
let count = (counts.get(name) ?? 0) + 1;
|
|
95
|
+
if (count === 1) {
|
|
96
|
+
counts.set(name, count);
|
|
97
|
+
return checkKey(name, what);
|
|
98
|
+
}
|
|
99
|
+
let numbered = `${name}-${String(count)}`;
|
|
100
|
+
while (taken.has(numbered)) {
|
|
101
|
+
count += 1;
|
|
102
|
+
numbered = `${name}-${String(count)}`;
|
|
103
|
+
}
|
|
104
|
+
counts.set(name, count);
|
|
105
|
+
taken.add(numbered);
|
|
106
|
+
return checkKey(numbered, what);
|
|
107
|
+
});
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* The errors no helper turns into a value: a call the grant refused, a budget spent, and a question
|
|
112
|
+
* to the owner that was cancelled or went unanswered. A branch that ends with one throws it out of
|
|
113
|
+
* the helper, and a worker that met one is not run again. Only `humanGate` turns the last two into
|
|
114
|
+
* an outcome. A branch the scope cancelled ends as `Cancelled`, which is no such error.
|
|
115
|
+
*/
|
|
116
|
+
const FATAL = new Set(["Denied", "BudgetExceeded", "AskCancelled", "AskExpired"]);
|
|
117
|
+
|
|
118
|
+
/** Whether a failure is one no helper keeps as a value. */
|
|
119
|
+
export const isFatal = (error: { name: string }): boolean => FATAL.has(error.name);
|
|
120
|
+
|
|
121
|
+
/** Rethrow a fatal error a helper caught. */
|
|
122
|
+
export function rethrowFatal(error: unknown): void {
|
|
123
|
+
if (error instanceof Error && isFatal(error)) throw error;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** The error a failed outcome stands for. */
|
|
127
|
+
export function errorOf(settled: Settled<unknown> & { ok: false }): Error {
|
|
128
|
+
return Object.assign(new Error(settled.error.message), { name: settled.error.name });
|
|
129
|
+
}
|
package/src/types.ts
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The types the helpers share: how a piece of work was judged, and what a loop that judges its work
|
|
3
|
+
* gives back. `Attempt` is also a function: the zod schema of an attempt, for a script's `output`.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import type { Settled } from "@niwa-labs/script";
|
|
7
|
+
import type { z } from "zod";
|
|
8
|
+
|
|
9
|
+
import { zod } from "./script.ts";
|
|
10
|
+
|
|
11
|
+
export type { Settled };
|
|
12
|
+
|
|
13
|
+
/** How a piece of work was judged. `INCONCLUSIVE` is not a pass. */
|
|
14
|
+
export type Verdict = "PASS" | "PASS+NOTES" | "FAIL" | "INCONCLUSIVE";
|
|
15
|
+
|
|
16
|
+
export const VERDICTS = ["PASS", "PASS+NOTES", "FAIL", "INCONCLUSIVE"] as const;
|
|
17
|
+
|
|
18
|
+
/** One thing a judge found: what, why it holds, and whether it blocks the work. */
|
|
19
|
+
export type Finding = { title: string; evidence: string; severity: "blocks" | "note" };
|
|
20
|
+
|
|
21
|
+
/** A judgement: the verdict, what was found, and how it was reached. */
|
|
22
|
+
export type Judged = { verdict: Verdict; findings: Finding[]; method: string };
|
|
23
|
+
|
|
24
|
+
/** What a branch that failed is: its error by name and message. */
|
|
25
|
+
export type FlowError = { name: string; message: string };
|
|
26
|
+
|
|
27
|
+
/** A piece of work a loop wrote and judged: the last value, its judgement, the rounds and why the loop stopped. */
|
|
28
|
+
export type Attempt<T> = { value: T; judged: Judged; rounds: number; history: Judged[]; stopped: "accepted" | "max-rounds" };
|
|
29
|
+
|
|
30
|
+
/** Whether a verdict lets the work through. */
|
|
31
|
+
export const passes = (judged: { verdict: Verdict }): boolean => judged.verdict === "PASS" || judged.verdict === "PASS+NOTES";
|
|
32
|
+
|
|
33
|
+
/** The schema of a finding, made with the script's zod. */
|
|
34
|
+
export function FindingSchema() {
|
|
35
|
+
const z = zod();
|
|
36
|
+
return z.object({ title: z.string(), evidence: z.string(), severity: z.enum(["blocks", "note"]) });
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** The schema of what a judge answers: a verdict and the findings. */
|
|
40
|
+
export function VerdictSchema() {
|
|
41
|
+
const z = zod();
|
|
42
|
+
return z.object({ verdict: z.enum(VERDICTS), findings: z.array(FindingSchema()) });
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** The schema of a judgement, with the votes `verify` keeps beside it. */
|
|
46
|
+
export function JudgedSchema() {
|
|
47
|
+
const z = zod();
|
|
48
|
+
const judged = VerdictSchema().extend({ method: z.string() });
|
|
49
|
+
return judged.extend({ votes: z.array(judged).optional() });
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** The schema of an attempt whose value `value` describes: what a script that returns an attempt names as its `output`. */
|
|
53
|
+
export function Attempt<S extends z.ZodType>(value: S) {
|
|
54
|
+
const z = zod();
|
|
55
|
+
return z.object({
|
|
56
|
+
value,
|
|
57
|
+
judged: JudgedSchema(),
|
|
58
|
+
rounds: z.number().int().nonnegative(),
|
|
59
|
+
history: z.array(JudgedSchema()),
|
|
60
|
+
stopped: z.enum(["accepted", "max-rounds"]),
|
|
61
|
+
});
|
|
62
|
+
}
|
package/src/wait.ts
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Waiting: on the world until a reading of it is settled, and on the owner at a gate.
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
import type { AskOption, Duration, ScriptRecordQuery } from "@niwa-labs/script";
|
|
6
|
+
|
|
7
|
+
import { checkKey, script } from "./script.ts";
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Read the facts until `done` says they are settled. The facts are read first, with the position
|
|
11
|
+
* of the records `on` names: what is settled already is not waited for. Then each round waits for
|
|
12
|
+
* a record `on` names after that position, at most `every`, and reads again. The `deadline` is
|
|
13
|
+
* for the waiting that follows the first reading: past it the outcome is `timed-out`, with the
|
|
14
|
+
* facts last read, which are never none. Each reading is a scope of its own (`r0`, `r1`, ...).
|
|
15
|
+
*
|
|
16
|
+
* A query of one exact type, named as text or by reference (`{ types: [TaskDone] }`, or the query
|
|
17
|
+
* a plugin's builder gives), waits for it; any other query is looked at every `every`.
|
|
18
|
+
*/
|
|
19
|
+
export async function settle<F>(
|
|
20
|
+
key: string,
|
|
21
|
+
opts: { on: ScriptRecordQuery; every: Duration; read: () => Promise<F>; done: (facts: F) => boolean; deadline?: Duration },
|
|
22
|
+
): Promise<{ facts: F; outcome: "done" | "timed-out" }> {
|
|
23
|
+
checkKey(key, "the key of a settle");
|
|
24
|
+
const g = script();
|
|
25
|
+
const [first, ...more] = opts.on.types ?? [];
|
|
26
|
+
const only = first !== undefined && more.length === 0 && opts.on.stream === undefined && !(typeof first === "string" && first.endsWith("*")) ? first : undefined;
|
|
27
|
+
return g.scope(key, undefined, async () => {
|
|
28
|
+
let { next } = await g.read.records({ ...opts.on, tail: 1 });
|
|
29
|
+
let facts = await g.scope("r0", undefined, () => opts.read());
|
|
30
|
+
if (opts.done(facts)) return { facts, outcome: "done" as const };
|
|
31
|
+
const settled = await g.scope("wait", opts.deadline === undefined ? undefined : { deadline: opts.deadline, onDeadline: "skip" }, async () => {
|
|
32
|
+
for (let round = 1; ; round += 1) {
|
|
33
|
+
if (only !== undefined) {
|
|
34
|
+
const waiting = { from: next, timeout: opts.every, ...(opts.on.filter === undefined ? {} : { filter: opts.on.filter }) };
|
|
35
|
+
const got = typeof only === "string" ? await g.wait(only, waiting) : await g.wait(only, waiting);
|
|
36
|
+
if (!("timedOut" in got)) next = got.at;
|
|
37
|
+
} else {
|
|
38
|
+
await g.sleep(opts.every);
|
|
39
|
+
next = (await g.read.records({ ...opts.on, from: next, tail: 1 })).next;
|
|
40
|
+
}
|
|
41
|
+
const read = await g.scope(`r${String(round)}`, undefined, () => opts.read());
|
|
42
|
+
facts = read;
|
|
43
|
+
if (opts.done(read)) return true;
|
|
44
|
+
}
|
|
45
|
+
});
|
|
46
|
+
return { facts, outcome: settled === true ? ("done" as const) : ("timed-out" as const) };
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** The option a gate adds for the owner to say no. */
|
|
51
|
+
const DECLINE = "decline";
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Ask the owner to choose one of `options`, or to decline. It never throws for a decline, a cancel
|
|
55
|
+
* or a timeout: they are outcomes, and none of them opens the gate.
|
|
56
|
+
*/
|
|
57
|
+
export async function humanGate<O extends string>(
|
|
58
|
+
key: string,
|
|
59
|
+
opts: { summary: string; options: readonly O[]; recommend?: O; risk?: string; timeout?: Duration },
|
|
60
|
+
): Promise<{ outcome: "chosen"; choice: O } | { outcome: "declined" | "expired" | "cancelled" }> {
|
|
61
|
+
checkKey(key, "the key of a gate");
|
|
62
|
+
if (opts.options.length === 0) throw new TypeError(`humanGate "${key}": give at least one option`);
|
|
63
|
+
if ((opts.options as readonly string[]).includes(DECLINE)) throw new TypeError(`humanGate "${key}": "${DECLINE}" is the option the gate adds itself`);
|
|
64
|
+
if (opts.recommend !== undefined && !opts.options.includes(opts.recommend)) throw new TypeError(`humanGate "${key}": the recommended "${opts.recommend}" is not an option`);
|
|
65
|
+
const g = script();
|
|
66
|
+
const text = [opts.summary, ...(opts.risk === undefined ? [] : [`Risk: ${opts.risk}`]), ...(opts.recommend === undefined ? [] : [`Recommended: ${opts.recommend}`])].join("\n\n");
|
|
67
|
+
const options: AskOption[] = [
|
|
68
|
+
...opts.options.map((id) => (id === opts.recommend ? { id, label: `${id} (recommended)` } : id)),
|
|
69
|
+
{ id: DECLINE, label: "Decline" },
|
|
70
|
+
];
|
|
71
|
+
return g.scope(key, undefined, async () => {
|
|
72
|
+
try {
|
|
73
|
+
const choice = (await g.ask.choice(text, options, opts.timeout === undefined ? {} : { timeout: opts.timeout })) as string;
|
|
74
|
+
return choice === DECLINE ? { outcome: "declined" as const } : { outcome: "chosen" as const, choice: choice as O };
|
|
75
|
+
} catch (error) {
|
|
76
|
+
if (error instanceof Error && error.name === "AskCancelled") return { outcome: "cancelled" as const };
|
|
77
|
+
if (error instanceof Error && error.name === "AskExpired") return { outcome: "expired" as const };
|
|
78
|
+
throw error;
|
|
79
|
+
}
|
|
80
|
+
});
|
|
81
|
+
}
|