@operad-io/engine 0.0.0-stage → 0.0.1

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.
Files changed (102) hide show
  1. package/LICENSE +21 -0
  2. package/config.schema.json +188 -0
  3. package/keys.schema.json +12 -0
  4. package/package.json +22 -4
  5. package/src/config/config.ts +627 -0
  6. package/src/config/index.ts +1 -0
  7. package/src/flow/define-flow.ts +57 -0
  8. package/src/flow/index.ts +5 -0
  9. package/src/flow/load.ts +41 -0
  10. package/src/flow/types.ts +107 -0
  11. package/src/flow/validate.ts +296 -0
  12. package/src/http/address.ts +142 -0
  13. package/src/http/index.ts +25 -0
  14. package/src/http/link.ts +20 -0
  15. package/src/http/server.ts +920 -0
  16. package/src/http/token.ts +85 -0
  17. package/src/index.ts +16 -0
  18. package/src/kernel/decide.ts +689 -0
  19. package/src/kernel/index.ts +3 -0
  20. package/src/kernel/state.ts +275 -0
  21. package/src/kernel/types.ts +366 -0
  22. package/src/log/errors.ts +77 -0
  23. package/src/log/facts.ts +50 -0
  24. package/src/log/index.ts +6 -0
  25. package/src/log/json-value.ts +67 -0
  26. package/src/log/open-log.ts +17 -0
  27. package/src/log/schema.ts +5 -0
  28. package/src/log/secret.ts +30 -0
  29. package/src/log/sqlite.ts +1011 -0
  30. package/src/log/types.ts +230 -0
  31. package/src/loop/code-watch.ts +486 -0
  32. package/src/loop/index.ts +3 -0
  33. package/src/loop/older-code.ts +58 -0
  34. package/src/loop/serve.ts +483 -0
  35. package/src/markdown.ts +451 -0
  36. package/src/notify/index.ts +10 -0
  37. package/src/notify/notify.ts +256 -0
  38. package/src/platform/file-lock.ts +385 -0
  39. package/src/platform/index.ts +13 -0
  40. package/src/platform/load.ts +18 -0
  41. package/src/platform/process-group.ts +635 -0
  42. package/src/platform/process-watch.ts +152 -0
  43. package/src/platform/sqlite-open.ts +104 -0
  44. package/src/platform/step-reap.ts +668 -0
  45. package/src/platform/watch.ts +158 -0
  46. package/src/platform/worker-reports.ts +34 -0
  47. package/src/plugin/action-schema.ts +550 -0
  48. package/src/plugin/declared-flows.ts +74 -0
  49. package/src/plugin/define-plugin.ts +12 -0
  50. package/src/plugin/errors.ts +73 -0
  51. package/src/plugin/filters.ts +46 -0
  52. package/src/plugin/harness.ts +50 -0
  53. package/src/plugin/home.ts +13 -0
  54. package/src/plugin/index.ts +65 -0
  55. package/src/plugin/install.ts +268 -0
  56. package/src/plugin/keys.ts +63 -0
  57. package/src/plugin/load.ts +256 -0
  58. package/src/plugin/logger.ts +30 -0
  59. package/src/plugin/object-facts.ts +132 -0
  60. package/src/plugin/open-store.ts +32 -0
  61. package/src/plugin/paging.ts +133 -0
  62. package/src/plugin/registry.ts +1783 -0
  63. package/src/plugin/secrets.ts +141 -0
  64. package/src/plugin/semver.ts +110 -0
  65. package/src/plugin/settings.ts +64 -0
  66. package/src/plugin/sqlite-store.ts +756 -0
  67. package/src/plugin/store.ts +318 -0
  68. package/src/plugin/types.ts +1236 -0
  69. package/src/plugin/usage.ts +157 -0
  70. package/src/plugin/validate.ts +1028 -0
  71. package/src/runner/answer.ts +156 -0
  72. package/src/runner/ask.ts +483 -0
  73. package/src/runner/cancel.ts +51 -0
  74. package/src/runner/errors.ts +20 -0
  75. package/src/runner/grants.ts +92 -0
  76. package/src/runner/index.ts +33 -0
  77. package/src/runner/limits.ts +403 -0
  78. package/src/runner/lock.ts +140 -0
  79. package/src/runner/runner.ts +1175 -0
  80. package/src/runner/service.ts +184 -0
  81. package/src/runner/step-worker.ts +303 -0
  82. package/src/testing/clock.ts +67 -0
  83. package/src/testing/index.ts +90 -0
  84. package/src/testing/types.ts +116 -0
  85. package/src/testing/world.ts +369 -0
  86. package/src/trigger/cron.ts +193 -0
  87. package/src/trigger/index.ts +32 -0
  88. package/src/trigger/kernel.ts +1212 -0
  89. package/src/trigger/rules.ts +300 -0
  90. package/src/trigger/store.ts +233 -0
  91. package/src/trigger/types.ts +156 -0
  92. package/src/util.ts +50 -0
  93. package/src/views/history.ts +634 -0
  94. package/src/views/index.ts +7 -0
  95. package/src/views/pending.ts +209 -0
  96. package/src/views/presentation.ts +2551 -0
  97. package/src/views/running.ts +255 -0
  98. package/src/views/settings.ts +452 -0
  99. package/src/views/types.ts +72 -0
  100. package/src/views/uploads.ts +228 -0
  101. package/triggers.schema.json +48 -0
  102. package/README.md +0 -3
@@ -0,0 +1,156 @@
1
+ /** Answering a person wait, for a CLI verb or a plugin action. */
2
+
3
+ import type { FlowDefinition } from "../flow/types.ts";
4
+ import type { KernelState } from "../kernel/types.ts";
5
+ import type { JsonValue, LogBackend } from "../log/types.ts";
6
+ import type { Actor } from "../plugin/types.ts";
7
+ import { answerAsk, answerableAsks, scanAsks } from "./ask.ts";
8
+ import { StateError } from "./errors.ts";
9
+ import { applyInput, readState } from "./service.ts";
10
+
11
+ export interface AnswerOptions {
12
+ readonly log: LogBackend;
13
+ readonly flow: FlowDefinition;
14
+ readonly runId: string;
15
+ readonly choice: string;
16
+ readonly note?: string | undefined;
17
+ readonly actor: Actor;
18
+ readonly clock?: (() => number) | undefined;
19
+ /** Called once when the answer ends the run. */
20
+ readonly onEnded?:
21
+ | ((runId: string, state: KernelState) => Promise<void>)
22
+ | undefined;
23
+ }
24
+
25
+ export interface RecordAnswerOptions {
26
+ readonly log: LogBackend;
27
+ readonly runId: string;
28
+ /**
29
+ * The question the answer is for, when the person answers one by its id. An
30
+ * answer to a question that is closed is refused and recorded.
31
+ */
32
+ readonly waitId?: string | undefined;
33
+ readonly choice: string;
34
+ readonly note?: string | undefined;
35
+ readonly actor: Actor;
36
+ }
37
+
38
+ /** The payload a recorded answer carries, enough for `serve` to apply it later. */
39
+ export interface RecordedAnswerPayload {
40
+ readonly kind: "person_answer";
41
+ readonly waitId: string;
42
+ readonly choice: string;
43
+ readonly note?: string | undefined;
44
+ readonly actor: { readonly via: string; readonly id: string };
45
+ }
46
+
47
+ function answerInput(
48
+ runId: string,
49
+ choice: string,
50
+ note: string | undefined,
51
+ actor: Actor,
52
+ ): (wait: { readonly id: string; readonly choices: readonly string[] }) => RecordedAnswerPayload {
53
+ return (wait) => {
54
+ if (!wait.choices.includes(choice)) {
55
+ throw new StateError(
56
+ `run ${runId}: "${choice}" is not one of ${wait.choices
57
+ .map((item) => `"${item}"`)
58
+ .join(", ")}`,
59
+ );
60
+ }
61
+ return {
62
+ kind: "person_answer",
63
+ waitId: wait.id,
64
+ choice,
65
+ ...(note === undefined ? {} : { note }),
66
+ actor: { via: actor.via, id: actor.id },
67
+ };
68
+ };
69
+ }
70
+
71
+ /**
72
+ * Records a person's answer without applying it. The CLI and actions use this:
73
+ * only `serve` decides what the input means and runs the step it requests, so
74
+ * a short-lived command never executes a step in its own process.
75
+ */
76
+ export async function recordAnswer(options: RecordAnswerOptions): Promise<void> {
77
+ const state = await readState(options.log, options.runId);
78
+ const wait = state.wait;
79
+ const named =
80
+ options.waitId !== undefined &&
81
+ !(state.status === "waiting_person" && wait?.id === options.waitId);
82
+ if (named || state.status !== "waiting_person" || wait === null) {
83
+ // A step may be waiting on its own question; its answer goes to the step.
84
+ const ask =
85
+ state.status === "ended" || state.status === "idle"
86
+ ? undefined
87
+ : options.waitId !== undefined
88
+ ? (await scanAsks(options.log, options.runId)).asks.get(options.waitId)
89
+ : answerableAsks((await scanAsks(options.log, options.runId)).asks, state).at(-1);
90
+ if (ask === undefined) {
91
+ throw new StateError(
92
+ options.waitId === undefined || state.status === "ended"
93
+ ? `run ${options.runId} is not waiting for a person`
94
+ : `run ${options.runId}: no question "${options.waitId}"`,
95
+ );
96
+ }
97
+ await answerAsk({
98
+ log: options.log,
99
+ runId: options.runId,
100
+ state,
101
+ ask,
102
+ choice: options.choice,
103
+ ...(options.note === undefined ? {} : { note: options.note }),
104
+ actor: options.actor,
105
+ });
106
+ return;
107
+ }
108
+ const payload = answerInput(
109
+ options.runId,
110
+ options.choice,
111
+ options.note,
112
+ options.actor,
113
+ )(wait);
114
+ await options.log.recordInput(
115
+ options.runId,
116
+ "person",
117
+ `${options.runId}:answer:${wait.id}:${options.choice}`,
118
+ payload as unknown as JsonValue,
119
+ );
120
+ }
121
+
122
+ /** Answers the run's current wait and appends the resulting facts. */
123
+ export async function answerRun(options: AnswerOptions): Promise<KernelState> {
124
+ const state = await readState(options.log, options.runId);
125
+ const wait = state.wait;
126
+ if (state.status !== "waiting_person" || wait === null) {
127
+ throw new StateError(`run ${options.runId} is not waiting for a person`);
128
+ }
129
+ // Check the choice before recording anything, exactly as a recorded answer
130
+ // does; the payload built here is the one `decide` applies.
131
+ answerInput(options.runId, options.choice, options.note, options.actor)(wait);
132
+
133
+ const now = (options.clock ?? (() => Date.now()))();
134
+ const result = await applyInput(
135
+ options.log,
136
+ options.flow,
137
+ options.runId,
138
+ state,
139
+ {
140
+ kind: "person_answer",
141
+ waitId: wait.id,
142
+ choice: options.choice,
143
+ ...(options.note === undefined ? {} : { note: options.note }),
144
+ actor: options.actor,
145
+ },
146
+ now,
147
+ "person",
148
+ `answer:${wait.id}:${options.choice}`,
149
+ {
150
+ beforeEnd: async (runId, ended) => {
151
+ await options.onEnded?.(runId, ended);
152
+ },
153
+ },
154
+ );
155
+ return result.state;
156
+ }
@@ -0,0 +1,483 @@
1
+ /**
2
+ * Questions a step asks a person with `ctx.ask`.
3
+ *
4
+ * The facts of the run are the only record. `ask_opened` makes the question
5
+ * visible; the first of `ask_answered` and `ask_timed_out` closes it, and an
6
+ * answer that arrives after that is refused and recorded as `ask_refused`.
7
+ * A person's answer is claimed first as a recorded input (the first claim for
8
+ * a question wins) and then written as the fact; any process that finds a claim
9
+ * without its fact writes it, so a crash between the two loses nothing.
10
+ */
11
+
12
+ import { inputIdFor } from "../log/facts.ts";
13
+ import { SeqConflictError } from "../log/errors.ts";
14
+ import type { JsonValue, LogBackend } from "../log/types.ts";
15
+ import type {
16
+ Actor,
17
+ AskOutcome,
18
+ AskRequest,
19
+ StepAsker,
20
+ } from "../plugin/types.ts";
21
+ import { StateError } from "./errors.ts";
22
+ import type { Grant, KernelState } from "../kernel/types.ts";
23
+ import { useGrant } from "./grants.ts";
24
+ import { isRecord } from "../util.ts";
25
+
26
+ /** How often a waiting step looks again when no change was announced. */
27
+ const RECHECK_MS = 1000;
28
+
29
+ /** The default grace, in seconds, when neither the call nor config narrows it. */
30
+ export const DEFAULT_ASK_GRACE_SECS = 600;
31
+
32
+ /** Starts a timer; the returned function cancels it. Tests inject their own. */
33
+ export type AskTimer = (ms: number, fire: () => void) => () => void;
34
+
35
+ export const realAskTimer: AskTimer = (ms, fire) => {
36
+ const handle = setTimeout(fire, ms);
37
+ return () => clearTimeout(handle);
38
+ };
39
+
40
+ export type AskStatus = "open" | "answered" | "timed_out";
41
+
42
+ export interface AskedAnswer {
43
+ readonly choice: string;
44
+ readonly note: string | undefined;
45
+ readonly actor: Actor;
46
+ }
47
+
48
+ /** One question as the facts of its run tell it. */
49
+ export interface AskRecord {
50
+ readonly waitId: string;
51
+ readonly effectId: string;
52
+ readonly step: string | null;
53
+ readonly prompt: string;
54
+ readonly choices: readonly string[];
55
+ readonly status: AskStatus;
56
+ readonly answer: AskedAnswer | undefined;
57
+ }
58
+
59
+ export function askWaitId(runId: string, effectId: string, n: number): string {
60
+ return `${runId}:${effectId}:${n}`;
61
+ }
62
+
63
+ function actorOf(value: unknown): Actor | undefined {
64
+ if (!isRecord(value)) return undefined;
65
+ if (typeof value.via !== "string" || typeof value.id !== "string") {
66
+ return undefined;
67
+ }
68
+ return { via: value.via, id: value.id };
69
+ }
70
+
71
+ function answerOf(payload: Record<string, JsonValue>): AskedAnswer | undefined {
72
+ const actor = actorOf(payload.actor);
73
+ if (actor === undefined || typeof payload.choice !== "string") {
74
+ return undefined;
75
+ }
76
+ return {
77
+ choice: payload.choice,
78
+ note: typeof payload.note === "string" ? payload.note : undefined,
79
+ actor,
80
+ };
81
+ }
82
+
83
+ /** Every question of the run, in the order they were opened. */
84
+ export async function scanAsks(
85
+ log: LogBackend,
86
+ runId: string,
87
+ ): Promise<{
88
+ readonly asks: ReadonlyMap<string, AskRecord>;
89
+ readonly lastSeq: number;
90
+ }> {
91
+ const asks = new Map<string, AskRecord>();
92
+ let lastSeq = 0;
93
+ for await (const fact of log.read(runId)) {
94
+ lastSeq = fact.seq;
95
+ if (
96
+ fact.kind !== "ask_opened" &&
97
+ fact.kind !== "ask_answered" &&
98
+ fact.kind !== "ask_timed_out"
99
+ ) {
100
+ continue;
101
+ }
102
+ const payload = fact.payload;
103
+ if (!isRecord(payload) || typeof payload.waitId !== "string") continue;
104
+ const waitId = payload.waitId;
105
+ const existing = asks.get(waitId);
106
+ if (fact.kind === "ask_opened") {
107
+ if (existing !== undefined) continue;
108
+ if (
109
+ typeof payload.effectId !== "string" ||
110
+ typeof payload.prompt !== "string"
111
+ ) {
112
+ continue;
113
+ }
114
+ asks.set(waitId, {
115
+ waitId,
116
+ effectId: payload.effectId,
117
+ step: typeof payload.step === "string" ? payload.step : null,
118
+ prompt: payload.prompt,
119
+ choices: Array.isArray(payload.choices)
120
+ ? payload.choices.filter(
121
+ (item): item is string => typeof item === "string",
122
+ )
123
+ : [],
124
+ status: "open",
125
+ answer: undefined,
126
+ });
127
+ continue;
128
+ }
129
+ // The first of an answer and a timeout closes the question.
130
+ if (existing === undefined || existing.status !== "open") continue;
131
+ if (fact.kind === "ask_timed_out") {
132
+ asks.set(waitId, { ...existing, status: "timed_out" });
133
+ continue;
134
+ }
135
+ const answer = answerOf(payload);
136
+ if (answer !== undefined) {
137
+ asks.set(waitId, { ...existing, status: "answered", answer });
138
+ }
139
+ }
140
+ return { asks, lastSeq };
141
+ }
142
+
143
+ interface FactSpec {
144
+ readonly kind: "ask_opened" | "ask_answered" | "ask_timed_out" | "ask_refused";
145
+ readonly payload: Record<string, JsonValue>;
146
+ }
147
+
148
+ /**
149
+ * Decides from the run's current questions which facts to append, and appends
150
+ * them, deciding again when the run moved on in between. Returns what it wrote.
151
+ */
152
+ async function appendWhen(
153
+ log: LogBackend,
154
+ runId: string,
155
+ build: (asks: ReadonlyMap<string, AskRecord>) => readonly FactSpec[],
156
+ ): Promise<readonly FactSpec[]> {
157
+ for (let attempt = 0; ; attempt += 1) {
158
+ const { asks, lastSeq } = await scanAsks(log, runId);
159
+ const facts = build(asks);
160
+ if (facts.length === 0) return facts;
161
+ try {
162
+ await log.append(
163
+ runId,
164
+ lastSeq,
165
+ facts.map((fact) => ({
166
+ kind: fact.kind,
167
+ payload: fact.payload,
168
+ cause: lastSeq,
169
+ })),
170
+ );
171
+ return facts;
172
+ } catch (error) {
173
+ if (error instanceof SeqConflictError && attempt < 8) continue;
174
+ throw error;
175
+ }
176
+ }
177
+ }
178
+
179
+ function claimKey(runId: string, waitId: string): string {
180
+ return `${runId}:ask:${waitId}`;
181
+ }
182
+
183
+ /** The answer a person claimed for the question, when someone claimed it. */
184
+ async function claimedAnswer(
185
+ log: LogBackend,
186
+ runId: string,
187
+ waitId: string,
188
+ ): Promise<AskedAnswer | undefined> {
189
+ // The input id is made from the source and the key, so one lookup finds it.
190
+ const input = await log.findInput(
191
+ inputIdFor("person", claimKey(runId, waitId)),
192
+ );
193
+ if (input === undefined) return undefined;
194
+ if (!isRecord(input.payload) || input.payload.kind !== "ask_answer") {
195
+ return undefined;
196
+ }
197
+ return answerOf(input.payload);
198
+ }
199
+
200
+ function answeredFact(waitId: string, answer: AskedAnswer): FactSpec {
201
+ return {
202
+ kind: "ask_answered",
203
+ payload: {
204
+ waitId,
205
+ choice: answer.choice,
206
+ note: answer.note ?? null,
207
+ actor: { via: answer.actor.via, id: answer.actor.id },
208
+ },
209
+ };
210
+ }
211
+
212
+ /**
213
+ * The question as it stands. A claimed answer that has no fact yet (its
214
+ * claimant stopped between the two) is written now.
215
+ */
216
+ export async function settleAsk(
217
+ log: LogBackend,
218
+ runId: string,
219
+ waitId: string,
220
+ ): Promise<AskRecord | undefined> {
221
+ const { asks } = await scanAsks(log, runId);
222
+ const record = asks.get(waitId);
223
+ if (record === undefined || record.status !== "open") return record;
224
+ const claimed = await claimedAnswer(log, runId, waitId);
225
+ if (claimed === undefined) return record;
226
+ await appendWhen(log, runId, (current) =>
227
+ current.get(waitId)?.status === "open" ? [answeredFact(waitId, claimed)] : [],
228
+ );
229
+ return (await scanAsks(log, runId)).asks.get(waitId);
230
+ }
231
+
232
+ /** The questions a person could answer now: open, and their step is running. */
233
+ export function answerableAsks(
234
+ asks: ReadonlyMap<string, AskRecord>,
235
+ state: KernelState,
236
+ ): AskRecord[] {
237
+ return [...asks.values()].filter(
238
+ (record) =>
239
+ record.status === "open" &&
240
+ state.status === "running" &&
241
+ state.effects[record.effectId] === "outstanding",
242
+ );
243
+ }
244
+
245
+ export interface AnswerAskOptions {
246
+ readonly log: LogBackend;
247
+ readonly runId: string;
248
+ readonly state: KernelState;
249
+ readonly ask: AskRecord;
250
+ readonly choice: string;
251
+ readonly note?: string | undefined;
252
+ readonly actor: Actor;
253
+ }
254
+
255
+ /**
256
+ * Records a person's answer to a question a step is waiting on. The first
257
+ * answer counts, a second is refused, and an answer to a question whose step
258
+ * is over is refused and recorded.
259
+ */
260
+ export async function answerAsk(options: AnswerAskOptions): Promise<void> {
261
+ const { log, runId, ask, choice, actor } = options;
262
+ if (ask.choices.length > 0 && !ask.choices.includes(choice)) {
263
+ throw new StateError(
264
+ `run ${runId}: "${choice}" is not one of ${ask.choices
265
+ .map((item) => `"${item}"`)
266
+ .join(", ")}`,
267
+ );
268
+ }
269
+ const refuse = async (reason: string): Promise<never> => {
270
+ // An ended run takes no more facts; the answer is just not taken.
271
+ if (options.state.status === "ended") {
272
+ throw new StateError(`run ${runId}: ${reason}`);
273
+ }
274
+ await appendWhen(log, runId, () => [
275
+ {
276
+ kind: "ask_refused",
277
+ payload: {
278
+ waitId: ask.waitId,
279
+ choice,
280
+ actor: { via: actor.via, id: actor.id },
281
+ reason,
282
+ },
283
+ },
284
+ ]);
285
+ throw new StateError(`run ${runId}: ${reason}`);
286
+ };
287
+
288
+ const current = (await scanAsks(log, runId)).asks.get(ask.waitId) ?? ask;
289
+ if (current.status === "answered") {
290
+ throw new StateError(`run ${runId}: already answered`);
291
+ }
292
+ const live =
293
+ options.state.status === "running" &&
294
+ options.state.effects[ask.effectId] === "outstanding";
295
+ if (current.status === "timed_out" || !live) {
296
+ await refuse("the question is closed, its step has ended");
297
+ }
298
+
299
+ const payload: Record<string, JsonValue> = {
300
+ kind: "ask_answer",
301
+ waitId: ask.waitId,
302
+ choice,
303
+ note: options.note ?? null,
304
+ actor: { via: actor.via, id: actor.id },
305
+ };
306
+ const claim = await log.recordInput(
307
+ runId,
308
+ "person",
309
+ claimKey(runId, ask.waitId),
310
+ payload,
311
+ );
312
+ if (claim.duplicate) {
313
+ throw new StateError(`run ${runId}: already answered`);
314
+ }
315
+ const answer: AskedAnswer = { choice, note: options.note, actor };
316
+ const written = await appendWhen(log, runId, (asks) =>
317
+ asks.get(ask.waitId)?.status === "open" ? [answeredFact(ask.waitId, answer)] : [],
318
+ );
319
+ if (written.length === 0) {
320
+ const closed = (await scanAsks(log, runId)).asks.get(ask.waitId);
321
+ // The reconciling step wrote the fact from this claim: that is success.
322
+ if (closed?.status === "answered" && closed.answer?.choice === choice) return;
323
+ await refuse("the question is closed, its step has ended");
324
+ }
325
+ }
326
+
327
+ function narrowest(...values: readonly (number | undefined)[]): number {
328
+ let result = Number.POSITIVE_INFINITY;
329
+ for (const value of values) {
330
+ if (value === undefined || !Number.isFinite(value)) continue;
331
+ result = Math.min(result, Math.max(0, value));
332
+ }
333
+ return Number.isFinite(result) ? result : DEFAULT_ASK_GRACE_SECS;
334
+ }
335
+
336
+ export interface AskHostOptions {
337
+ readonly log: LogBackend;
338
+ /** `ask.graceSecs` from config.json. */
339
+ readonly graceSecs?: number | undefined;
340
+ readonly timer?: AskTimer | undefined;
341
+ /** Stops the step's own timeout while a question is open; returns resume. */
342
+ readonly pause?: (() => () => void) | undefined;
343
+ }
344
+
345
+ /** Serves the questions of the steps one runner starts. */
346
+ export class AskHost {
347
+ private readonly log: LogBackend;
348
+ private readonly graceSecs: number;
349
+ private readonly timer: AskTimer;
350
+ private readonly pause: (() => () => void) | undefined;
351
+
352
+ constructor(options: AskHostOptions) {
353
+ this.log = options.log;
354
+ this.graceSecs = options.graceSecs ?? DEFAULT_ASK_GRACE_SECS;
355
+ this.timer = options.timer ?? realAskTimer;
356
+ this.pause = options.pause;
357
+ }
358
+
359
+ /**
360
+ * The asker of one effect. Questions are numbered in the order the step asks
361
+ * them, so a step that runs again after a crash gets the same ids.
362
+ */
363
+ asker(
364
+ runId: string,
365
+ effectId: string,
366
+ step: string | null,
367
+ grants: readonly Grant[] = [],
368
+ ): StepAsker {
369
+ let count = 0;
370
+ let asking = false;
371
+ return {
372
+ useGrant: (waitId) =>
373
+ useGrant(this.log, runId, step ?? "", grants, waitId),
374
+ ask: async (request, signal) => {
375
+ // One question at a time: a second would hide the first from the person.
376
+ if (asking) {
377
+ throw new Error(
378
+ "a step asks one question at a time; wait for the answer before asking again",
379
+ );
380
+ }
381
+ asking = true;
382
+ count += 1;
383
+ try {
384
+ return await this.ask(runId, effectId, step, count, request, signal);
385
+ } finally {
386
+ asking = false;
387
+ }
388
+ },
389
+ };
390
+ }
391
+
392
+ private async ask(
393
+ runId: string,
394
+ effectId: string,
395
+ step: string | null,
396
+ n: number,
397
+ request: AskRequest,
398
+ signal: AbortSignal | undefined,
399
+ ): Promise<AskOutcome> {
400
+ const waitId = askWaitId(runId, effectId, n);
401
+ const choices = [...(request.choices ?? [])];
402
+ const grace = narrowest(request.graceSecs, this.graceSecs);
403
+
404
+ await appendWhen(this.log, runId, (asks) =>
405
+ asks.has(waitId)
406
+ ? []
407
+ : [
408
+ {
409
+ kind: "ask_opened",
410
+ payload: {
411
+ waitId,
412
+ effectId,
413
+ step,
414
+ prompt: request.prompt,
415
+ choices,
416
+ },
417
+ },
418
+ ],
419
+ );
420
+
421
+ const resume = this.pause?.();
422
+ let expired = false;
423
+ let cancelTimer: (() => void) | undefined;
424
+ let wake: (() => void) | undefined;
425
+ try {
426
+ for (;;) {
427
+ if (signal?.aborted === true) {
428
+ throw new Error("the step was cancelled while it waited for an answer");
429
+ }
430
+ const record = await settleAsk(this.log, runId, waitId);
431
+ if (record === undefined) {
432
+ throw new Error(`the question ${waitId} is gone from the log`);
433
+ }
434
+ if (record.status === "answered" && record.answer !== undefined) {
435
+ return {
436
+ kind: "answered",
437
+ answer: {
438
+ choice: record.answer.choice,
439
+ ...(record.answer.note === undefined
440
+ ? {}
441
+ : { note: record.answer.note }),
442
+ actor: record.answer.actor,
443
+ },
444
+ };
445
+ }
446
+ if (record.status === "timed_out") {
447
+ return { kind: "timeout", waitId, prompt: record.prompt, choices };
448
+ }
449
+ if (grace <= 0 || expired) {
450
+ await appendWhen(this.log, runId, (asks) =>
451
+ asks.get(waitId)?.status === "open"
452
+ ? [{ kind: "ask_timed_out", payload: { waitId } }]
453
+ : [],
454
+ );
455
+ continue;
456
+ }
457
+ cancelTimer ??= this.timer(grace * 1000, () => {
458
+ expired = true;
459
+ wake?.();
460
+ });
461
+ await new Promise<void>((resolve) => {
462
+ let recheck: ReturnType<typeof setTimeout> | undefined;
463
+ let unsubscribe: (() => void) | undefined;
464
+ const done = (): void => {
465
+ if (recheck !== undefined) clearTimeout(recheck);
466
+ unsubscribe?.();
467
+ signal?.removeEventListener("abort", done);
468
+ wake = undefined;
469
+ resolve();
470
+ };
471
+ wake = done;
472
+ unsubscribe = this.log.subscribe?.(done);
473
+ recheck = setTimeout(done, RECHECK_MS);
474
+ signal?.addEventListener("abort", done, { once: true });
475
+ if (expired) done();
476
+ });
477
+ }
478
+ } finally {
479
+ cancelTimer?.();
480
+ resume?.();
481
+ }
482
+ }
483
+ }
@@ -0,0 +1,51 @@
1
+ /** Cancelling a run on behalf of a plugin, from any process that holds the log. */
2
+
3
+ import type { FlowDefinition } from "../flow/types.ts";
4
+ import type { LogBackend } from "../log/types.ts";
5
+ import { StateError } from "./errors.ts";
6
+ import { applyInput, endRunDirectly, readState } from "./service.ts";
7
+
8
+ export interface CancelRunOptions {
9
+ readonly log: LogBackend;
10
+ /** Finds a flow by name; undefined when it is not loaded. */
11
+ readonly flow: (name: string) => FlowDefinition | undefined;
12
+ readonly runId: string;
13
+ /** The run's own graph, for a flow no loaded plugin declares. */
14
+ readonly graph?: FlowDefinition | undefined;
15
+ /** Who asked: recorded with the cancel input, as the person's client names itself. */
16
+ readonly source: string;
17
+ readonly clock?: (() => number) | undefined;
18
+ }
19
+
20
+ /** Ends a run as cancelled; an unknown or ended run is left alone. */
21
+ export async function cancelRun(options: CancelRunOptions): Promise<void> {
22
+ const { log, runId } = options;
23
+ const runs = await log.runs();
24
+ const run = runs.find((candidate) => candidate.runId === runId);
25
+ if (run === undefined) return;
26
+ const state = await readState(log, runId);
27
+ if (state.status === "ended") return;
28
+ // A run that never took its first step has no flow to answer through; its
29
+ // cancel still ends it, so it leaves the running view.
30
+ if (state.status === "idle") {
31
+ await endRunDirectly(log, runId, "cancelled", "cancel");
32
+ return;
33
+ }
34
+ const flow =
35
+ options.graph !== undefined && options.graph.name === run.flow
36
+ ? options.graph
37
+ : options.flow(run.flow);
38
+ if (flow === undefined) {
39
+ throw new StateError(`run "${runId}": flow "${run.flow}" is not loaded`);
40
+ }
41
+ await applyInput(
42
+ log,
43
+ flow,
44
+ runId,
45
+ state,
46
+ { kind: "cancel" },
47
+ (options.clock ?? Date.now)(),
48
+ options.source,
49
+ `cancel:${runId}`,
50
+ );
51
+ }
@@ -0,0 +1,20 @@
1
+ /** Errors the runner and its views report to the command line. */
2
+
3
+ /** The state does not allow the action; the CLI exits 3. */
4
+ export class StateError extends Error {
5
+ constructor(message: string) {
6
+ super(message);
7
+ this.name = "StateError";
8
+ }
9
+ }
10
+
11
+ /** Another process holds a lock; the CLI exits 4. */
12
+ export class LockHeldError extends Error {
13
+ readonly path: string;
14
+
15
+ constructor(path: string, detail = "another process holds it") {
16
+ super(`lock ${path}: ${detail}`);
17
+ this.name = "LockHeldError";
18
+ this.path = path;
19
+ }
20
+ }