@operad-io/engine 0.1.1 → 0.3.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.
Files changed (81) hide show
  1. package/config.schema.json +2 -1
  2. package/package.json +1 -1
  3. package/src/config/config.ts +74 -45
  4. package/src/flow/types.ts +4 -0
  5. package/src/flow/validate.ts +5 -0
  6. package/src/http/index.ts +2 -0
  7. package/src/http/plugins.ts +68 -0
  8. package/src/http/server.ts +342 -48
  9. package/src/kernel/decide.ts +115 -30
  10. package/src/kernel/state.ts +9 -0
  11. package/src/kernel/types.ts +25 -40
  12. package/src/log/open-log.ts +2 -5
  13. package/src/log/sqlite.ts +127 -85
  14. package/src/log/types.ts +35 -9
  15. package/src/loop/code-watch.ts +108 -2
  16. package/src/loop/older-code.ts +3 -4
  17. package/src/loop/serve.ts +122 -95
  18. package/src/notify/notify.ts +2 -6
  19. package/src/platform/atomic-write.ts +163 -0
  20. package/src/platform/file-lock.ts +43 -21
  21. package/src/platform/git-program.ts +108 -0
  22. package/src/platform/index.ts +3 -0
  23. package/src/platform/kept-workers.ts +290 -0
  24. package/src/platform/process-group.ts +11 -3
  25. package/src/platform/sqlite-open.ts +20 -6
  26. package/src/platform/sqlite-schema.ts +30 -0
  27. package/src/platform/step-reap.ts +33 -18
  28. package/src/platform/watch.ts +1 -11
  29. package/src/plugin/action-schema.ts +59 -1
  30. package/src/plugin/choice-info.ts +133 -0
  31. package/src/plugin/context.ts +279 -0
  32. package/src/plugin/declared-flows.ts +3 -10
  33. package/src/plugin/errors.ts +9 -0
  34. package/src/plugin/freeze.ts +12 -0
  35. package/src/plugin/harness.ts +28 -0
  36. package/src/plugin/index.ts +8 -7
  37. package/src/plugin/install.ts +265 -17
  38. package/src/plugin/keys.ts +2 -12
  39. package/src/plugin/load.ts +47 -23
  40. package/src/plugin/logger.ts +14 -0
  41. package/src/plugin/open-store.ts +0 -6
  42. package/src/plugin/question-form.ts +323 -0
  43. package/src/plugin/registry.ts +519 -76
  44. package/src/plugin/secrets.ts +14 -24
  45. package/src/plugin/semver.ts +52 -0
  46. package/src/plugin/settings.ts +1 -9
  47. package/src/plugin/sqlite-store.ts +94 -64
  48. package/src/plugin/store.ts +5 -0
  49. package/src/plugin/types.ts +575 -21
  50. package/src/plugin/validate.ts +402 -26
  51. package/src/runner/answer.ts +26 -68
  52. package/src/runner/ask.ts +227 -28
  53. package/src/runner/cancel.ts +10 -7
  54. package/src/runner/grants.ts +2 -2
  55. package/src/runner/index.ts +1 -3
  56. package/src/runner/limits.ts +2 -2
  57. package/src/runner/runner.ts +15 -14
  58. package/src/runner/service.ts +52 -19
  59. package/src/runner/step-worker.ts +9 -0
  60. package/src/testing/answer.ts +69 -0
  61. package/src/testing/clock-manual.ts +152 -0
  62. package/src/testing/config.ts +16 -0
  63. package/src/testing/fs.ts +172 -0
  64. package/src/testing/home.ts +43 -0
  65. package/src/testing/index.ts +19 -0
  66. package/src/testing/types.ts +2 -0
  67. package/src/testing/world.ts +9 -2
  68. package/src/trigger/kernel.ts +13 -46
  69. package/src/trigger/rules.ts +22 -12
  70. package/src/trigger/types.ts +2 -6
  71. package/src/util.ts +99 -0
  72. package/src/views/event-line.ts +22 -0
  73. package/src/views/history.ts +36 -19
  74. package/src/views/live-logs.ts +313 -0
  75. package/src/views/pending.ts +23 -5
  76. package/src/views/presentation.ts +629 -81
  77. package/src/views/running.ts +5 -5
  78. package/src/views/settings.ts +205 -66
  79. package/src/views/types.ts +8 -2
  80. package/src/views/uploads.ts +15 -7
  81. package/triggers.schema.json +4 -0
@@ -1,26 +1,10 @@
1
1
  /** Answering a person wait, for a CLI verb or a plugin action. */
2
2
 
3
- import type { FlowDefinition } from "../flow/types.ts";
4
- import type { KernelState } from "../kernel/types.ts";
5
3
  import type { JsonValue, LogBackend } from "../log/types.ts";
6
- import type { Actor } from "../plugin/types.ts";
7
- import { answerAsk, answerableAsks, scanAsks } from "./ask.ts";
4
+ import type { Actor, AskQuestion, AskQuestionAnswer } from "../plugin/types.ts";
5
+ import { answerAsk, answerableAsks, resolveAnswer, scanAsks } from "./ask.ts";
8
6
  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
- }
7
+ import { readState } from "./service.ts";
24
8
 
25
9
  export interface RecordAnswerOptions {
26
10
  readonly log: LogBackend;
@@ -30,7 +14,9 @@ export interface RecordAnswerOptions {
30
14
  * answer to a question that is closed is refused and recorded.
31
15
  */
32
16
  readonly waitId?: string | undefined;
33
- readonly choice: string;
17
+ readonly choice: string | undefined;
18
+ /** The person's answer to each question, when the question was a form. */
19
+ readonly answers?: readonly AskQuestionAnswer[] | undefined;
34
20
  readonly note?: string | undefined;
35
21
  readonly actor: Actor;
36
22
  }
@@ -39,29 +25,32 @@ export interface RecordAnswerOptions {
39
25
  export interface RecordedAnswerPayload {
40
26
  readonly kind: "person_answer";
41
27
  readonly waitId: string;
42
- readonly choice: string;
28
+ readonly choice?: string | undefined;
29
+ readonly answers?: readonly AskQuestionAnswer[] | undefined;
43
30
  readonly note?: string | undefined;
44
31
  readonly actor: { readonly via: string; readonly id: string };
45
32
  }
46
33
 
47
- function answerInput(
34
+ export function answerInput(
48
35
  runId: string,
49
- choice: string,
36
+ choice: string | undefined,
37
+ answers: readonly AskQuestionAnswer[] | undefined,
50
38
  note: string | undefined,
51
39
  actor: Actor,
52
- ): (wait: { readonly id: string; readonly choices: readonly string[] }) => RecordedAnswerPayload {
40
+ ): (wait: {
41
+ readonly id: string;
42
+ readonly choices: readonly string[];
43
+ readonly questions?: readonly AskQuestion[] | undefined;
44
+ }) => RecordedAnswerPayload {
53
45
  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
- }
46
+ // The same check a running step's question makes: a form needs one answer
47
+ // per question, and a question of choices needs a choice.
48
+ const resolved = resolveAnswer(runId, wait, choice, answers);
61
49
  return {
62
50
  kind: "person_answer",
63
51
  waitId: wait.id,
64
- choice,
52
+ ...(resolved.choice === undefined ? {} : { choice: resolved.choice }),
53
+ ...(resolved.answers === undefined ? {} : { answers: resolved.answers }),
65
54
  ...(note === undefined ? {} : { note }),
66
55
  actor: { via: actor.via, id: actor.id },
67
56
  };
@@ -74,6 +63,8 @@ function answerInput(
74
63
  * a short-lived command never executes a step in its own process.
75
64
  */
76
65
  export async function recordAnswer(options: RecordAnswerOptions): Promise<void> {
66
+ const run = await options.log.run(options.runId);
67
+ if (run === undefined) throw new StateError(`no run "${options.runId}"`);
77
68
  const state = await readState(options.log, options.runId);
78
69
  const wait = state.wait;
79
70
  const named =
@@ -100,6 +91,7 @@ export async function recordAnswer(options: RecordAnswerOptions): Promise<void>
100
91
  state,
101
92
  ask,
102
93
  choice: options.choice,
94
+ ...(options.answers === undefined ? {} : { answers: options.answers }),
103
95
  ...(options.note === undefined ? {} : { note: options.note }),
104
96
  actor: options.actor,
105
97
  });
@@ -108,49 +100,15 @@ export async function recordAnswer(options: RecordAnswerOptions): Promise<void>
108
100
  const payload = answerInput(
109
101
  options.runId,
110
102
  options.choice,
103
+ options.answers,
111
104
  options.note,
112
105
  options.actor,
113
106
  )(wait);
114
107
  await options.log.recordInput(
115
108
  options.runId,
116
109
  "person",
117
- `${options.runId}:answer:${wait.id}:${options.choice}`,
110
+ `${options.runId}:answer:${wait.id}:${options.choice ?? "answers"}`,
118
111
  payload as unknown as JsonValue,
119
112
  );
120
113
  }
121
114
 
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
- }
package/src/runner/ask.ts CHANGED
@@ -15,6 +15,8 @@ import type { JsonValue, LogBackend } from "../log/types.ts";
15
15
  import type {
16
16
  Actor,
17
17
  AskOutcome,
18
+ AskQuestion,
19
+ AskQuestionAnswer,
18
20
  AskRequest,
19
21
  StepAsker,
20
22
  } from "../plugin/types.ts";
@@ -22,6 +24,16 @@ import { StateError } from "./errors.ts";
22
24
  import type { Grant, KernelState } from "../kernel/types.ts";
23
25
  import { useGrant } from "./grants.ts";
24
26
  import { isRecord } from "../util.ts";
27
+ import { choiceInfoJson, storedChoiceInfo, type ChoiceInfoMap } from "../plugin/choice-info.ts";
28
+ import {
29
+ answersJson,
30
+ answersProblem,
31
+ formChoices,
32
+ normalizeAnswers,
33
+ questionsJson,
34
+ storedAnswers,
35
+ storedQuestions,
36
+ } from "../plugin/question-form.ts";
25
37
 
26
38
  /** How often a waiting step looks again when no change was announced. */
27
39
  const RECHECK_MS = 1000;
@@ -40,9 +52,12 @@ export const realAskTimer: AskTimer = (ms, fire) => {
40
52
  export type AskStatus = "open" | "answered" | "timed_out";
41
53
 
42
54
  export interface AskedAnswer {
43
- readonly choice: string;
55
+ /** The one answer a question of choices takes; absent for a form's answer. */
56
+ readonly choice: string | undefined;
44
57
  readonly note: string | undefined;
45
58
  readonly actor: Actor;
59
+ /** The person's answer to each question, when the question was a form. */
60
+ readonly answers: readonly AskQuestionAnswer[] | undefined;
46
61
  }
47
62
 
48
63
  /** One question as the facts of its run tell it. */
@@ -52,6 +67,9 @@ export interface AskRecord {
52
67
  readonly step: string | null;
53
68
  readonly prompt: string;
54
69
  readonly choices: readonly string[];
70
+ readonly choiceInfo: ChoiceInfoMap | undefined;
71
+ /** The form the step asked, when it asked one. */
72
+ readonly questions: readonly AskQuestion[] | undefined;
55
73
  readonly status: AskStatus;
56
74
  readonly answer: AskedAnswer | undefined;
57
75
  }
@@ -68,15 +86,23 @@ function actorOf(value: unknown): Actor | undefined {
68
86
  return { via: value.via, id: value.id };
69
87
  }
70
88
 
71
- function answerOf(payload: Record<string, JsonValue>): AskedAnswer | undefined {
89
+ function answerOf(
90
+ payload: Record<string, JsonValue>,
91
+ questions: readonly AskQuestion[] | undefined,
92
+ ): AskedAnswer | undefined {
72
93
  const actor = actorOf(payload.actor);
73
- if (actor === undefined || typeof payload.choice !== "string") {
74
- return undefined;
75
- }
94
+ if (actor === undefined) return undefined;
95
+ const choice = typeof payload.choice === "string" ? payload.choice : undefined;
96
+ const answers =
97
+ questions === undefined || questions.length === 0
98
+ ? undefined
99
+ : storedAnswers(payload.answers, questions);
100
+ if (choice === undefined && answers === undefined) return undefined;
76
101
  return {
77
- choice: payload.choice,
102
+ choice,
78
103
  note: typeof payload.note === "string" ? payload.note : undefined,
79
104
  actor,
105
+ answers,
80
106
  };
81
107
  }
82
108
 
@@ -111,16 +137,19 @@ export async function scanAsks(
111
137
  ) {
112
138
  continue;
113
139
  }
140
+ const choices = Array.isArray(payload.choices)
141
+ ? payload.choices.filter(
142
+ (item): item is string => typeof item === "string",
143
+ )
144
+ : [];
114
145
  asks.set(waitId, {
115
146
  waitId,
116
147
  effectId: payload.effectId,
117
148
  step: typeof payload.step === "string" ? payload.step : null,
118
149
  prompt: payload.prompt,
119
- choices: Array.isArray(payload.choices)
120
- ? payload.choices.filter(
121
- (item): item is string => typeof item === "string",
122
- )
123
- : [],
150
+ choices,
151
+ choiceInfo: storedChoiceInfo(payload.choiceInfo, choices),
152
+ questions: storedQuestions(payload.questions),
124
153
  status: "open",
125
154
  answer: undefined,
126
155
  });
@@ -132,7 +161,7 @@ export async function scanAsks(
132
161
  asks.set(waitId, { ...existing, status: "timed_out" });
133
162
  continue;
134
163
  }
135
- const answer = answerOf(payload);
164
+ const answer = answerOf(payload, existing.questions);
136
165
  if (answer !== undefined) {
137
166
  asks.set(waitId, { ...existing, status: "answered", answer });
138
167
  }
@@ -180,11 +209,59 @@ function claimKey(runId: string, waitId: string): string {
180
209
  return `${runId}:ask:${waitId}`;
181
210
  }
182
211
 
212
+ /**
213
+ * The full answers of a secret question, kept only for the step that is running
214
+ * in this process (ADR 0008 D8). They never reach a fact, an input or history.
215
+ */
216
+ const secretAnswers = new Map<string, readonly AskQuestionAnswer[]>();
217
+
218
+ function secretKey(runId: string, waitId: string): string {
219
+ return `${runId}:secret:${waitId}`;
220
+ }
221
+
222
+ /** True when any question of the form takes a secret answer. */
223
+ export function hasSecretQuestion(
224
+ questions: readonly AskQuestion[] | undefined,
225
+ ): boolean {
226
+ return questions?.some((question) => question.secret === true) ?? false;
227
+ }
228
+
229
+ /** Takes the secret answers a running step is waiting for; they are used once. */
230
+ export function takeSecretAnswers(
231
+ runId: string,
232
+ waitId: string,
233
+ ): readonly AskQuestionAnswer[] | undefined {
234
+ const key = secretKey(runId, waitId);
235
+ const found = secretAnswers.get(key);
236
+ secretAnswers.delete(key);
237
+ return found;
238
+ }
239
+
240
+ /** The answers a fact or an input carries: a secret question's text is left out. */
241
+ function recordedAnswers(
242
+ answers: readonly AskQuestionAnswer[] | undefined,
243
+ questions: readonly AskQuestion[] | undefined,
244
+ ): readonly AskQuestionAnswer[] | undefined {
245
+ if (answers === undefined || !hasSecretQuestion(questions)) return answers;
246
+ const secret = new Set(
247
+ (questions ?? [])
248
+ .filter((question) => question.secret === true)
249
+ .map((question) => question.id),
250
+ );
251
+ return answers.map((answer) => {
252
+ if (!secret.has(answer.id)) return answer;
253
+ const choices = answer.choices;
254
+ if (choices !== undefined && choices.length > 0) return { id: answer.id, choices };
255
+ return { id: answer.id, skipped: true as const };
256
+ });
257
+ }
258
+
183
259
  /** The answer a person claimed for the question, when someone claimed it. */
184
260
  async function claimedAnswer(
185
261
  log: LogBackend,
186
262
  runId: string,
187
263
  waitId: string,
264
+ questions: readonly AskQuestion[] | undefined,
188
265
  ): Promise<AskedAnswer | undefined> {
189
266
  // The input id is made from the source and the key, so one lookup finds it.
190
267
  const input = await log.findInput(
@@ -194,7 +271,7 @@ async function claimedAnswer(
194
271
  if (!isRecord(input.payload) || input.payload.kind !== "ask_answer") {
195
272
  return undefined;
196
273
  }
197
- return answerOf(input.payload);
274
+ return answerOf(input.payload, questions);
198
275
  }
199
276
 
200
277
  function answeredFact(waitId: string, answer: AskedAnswer): FactSpec {
@@ -202,8 +279,9 @@ function answeredFact(waitId: string, answer: AskedAnswer): FactSpec {
202
279
  kind: "ask_answered",
203
280
  payload: {
204
281
  waitId,
205
- choice: answer.choice,
282
+ choice: answer.choice ?? null,
206
283
  note: answer.note ?? null,
284
+ ...(answer.answers === undefined ? {} : { answers: answersJson(answer.answers) }),
207
285
  actor: { via: answer.actor.via, id: answer.actor.id },
208
286
  },
209
287
  };
@@ -221,7 +299,7 @@ export async function settleAsk(
221
299
  const { asks } = await scanAsks(log, runId);
222
300
  const record = asks.get(waitId);
223
301
  if (record === undefined || record.status !== "open") return record;
224
- const claimed = await claimedAnswer(log, runId, waitId);
302
+ const claimed = await claimedAnswer(log, runId, waitId, record.questions);
225
303
  if (claimed === undefined) return record;
226
304
  await appendWhen(log, runId, (current) =>
227
305
  current.get(waitId)?.status === "open" ? [answeredFact(waitId, claimed)] : [],
@@ -247,11 +325,63 @@ export interface AnswerAskOptions {
247
325
  readonly runId: string;
248
326
  readonly state: KernelState;
249
327
  readonly ask: AskRecord;
250
- readonly choice: string;
328
+ /** The one choice a question of choices takes; absent for a form's answer. */
329
+ readonly choice: string | undefined;
251
330
  readonly note?: string | undefined;
331
+ /** The person's answer to each question, for a form. */
332
+ readonly answers?: unknown;
252
333
  readonly actor: Actor;
253
334
  }
254
335
 
336
+ /**
337
+ * What a person's answer to one question says, checked against the question.
338
+ * The same rule serves a running step's question and a flow's wait after the
339
+ * grace, so an answer one path refuses is never silently dropped by the other.
340
+ */
341
+ export function resolveAnswer(
342
+ runId: string,
343
+ ask: {
344
+ readonly choices: readonly string[];
345
+ readonly questions?: readonly AskQuestion[] | undefined;
346
+ },
347
+ choice: string | undefined,
348
+ answers: unknown,
349
+ ): { readonly choice: string | undefined; readonly answers: readonly AskQuestionAnswer[] | undefined } {
350
+ const questions = ask.questions;
351
+ if (questions === undefined || questions.length === 0) {
352
+ if (choice === undefined) {
353
+ throw new StateError(`run ${runId}: this question takes a choice`);
354
+ }
355
+ if (!ask.choices.includes(choice)) {
356
+ throw new StateError(
357
+ ask.choices.length === 0
358
+ ? `run ${runId}: this question takes no choice`
359
+ : `run ${runId}: "${choice}" is not one of ${ask.choices
360
+ .map((item) => `"${item}"`)
361
+ .join(", ")}`,
362
+ );
363
+ }
364
+ return { choice, answers: undefined };
365
+ }
366
+ const problem = answersProblem(answers, questions);
367
+ if (problem !== undefined) {
368
+ throw new StateError(`run ${runId}: answers: ${problem}`);
369
+ }
370
+ if (answers !== undefined) {
371
+ return { choice, answers: normalizeAnswers(answers, questions) };
372
+ }
373
+ // A client that cannot draw the form answers the one question it was shown.
374
+ if (choice !== undefined && questions.length === 1 && ask.choices.includes(choice)) {
375
+ return {
376
+ choice,
377
+ answers: normalizeAnswers([{ id: questions[0]?.id, choices: [choice] }], questions),
378
+ };
379
+ }
380
+ throw new StateError(
381
+ `run ${runId}: this question is a form; it needs one answer per question`,
382
+ );
383
+ }
384
+
255
385
  /**
256
386
  * Records a person's answer to a question a step is waiting on. The first
257
387
  * answer counts, a second is refused, and an answer to a question whose step
@@ -259,13 +389,7 @@ export interface AnswerAskOptions {
259
389
  */
260
390
  export async function answerAsk(options: AnswerAskOptions): Promise<void> {
261
391
  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
- }
392
+ const resolved = resolveAnswer(runId, ask, choice, options.answers);
269
393
  const refuse = async (reason: string): Promise<never> => {
270
394
  // An ended run takes no more facts; the answer is just not taken.
271
395
  if (options.state.status === "ended") {
@@ -276,7 +400,7 @@ export async function answerAsk(options: AnswerAskOptions): Promise<void> {
276
400
  kind: "ask_refused",
277
401
  payload: {
278
402
  waitId: ask.waitId,
279
- choice,
403
+ choice: choice ?? null,
280
404
  actor: { via: actor.via, id: actor.id },
281
405
  reason,
282
406
  },
@@ -295,12 +419,31 @@ export async function answerAsk(options: AnswerAskOptions): Promise<void> {
295
419
  if (current.status === "timed_out" || !live) {
296
420
  await refuse("the question is closed, its step has ended");
297
421
  }
422
+ if (hasSecretQuestion(ask.questions)) {
423
+ const given = new Set(
424
+ (resolved.answers ?? [])
425
+ .filter((answer) => typeof answer.text === "string" && answer.text.trim().length > 0)
426
+ .map((answer) => answer.id),
427
+ );
428
+ const missing = (ask.questions ?? []).some(
429
+ (question) => question.secret === true && !given.has(question.id),
430
+ );
431
+ if (missing) {
432
+ await refuse("a secret question takes an answer with its text");
433
+ }
434
+ }
435
+ const secret = hasSecretQuestion(ask.questions);
436
+ const recorded = recordedAnswers(resolved.answers, ask.questions);
437
+ if (secret && resolved.answers !== undefined) {
438
+ secretAnswers.set(secretKey(runId, ask.waitId), resolved.answers);
439
+ }
298
440
 
299
441
  const payload: Record<string, JsonValue> = {
300
442
  kind: "ask_answer",
301
443
  waitId: ask.waitId,
302
- choice,
444
+ choice: resolved.choice ?? null,
303
445
  note: options.note ?? null,
446
+ ...(recorded === undefined ? {} : { answers: answersJson(recorded) }),
304
447
  actor: { via: actor.via, id: actor.id },
305
448
  };
306
449
  const claim = await log.recordInput(
@@ -310,13 +453,20 @@ export async function answerAsk(options: AnswerAskOptions): Promise<void> {
310
453
  payload,
311
454
  );
312
455
  if (claim.duplicate) {
456
+ secretAnswers.delete(secretKey(runId, ask.waitId));
313
457
  throw new StateError(`run ${runId}: already answered`);
314
458
  }
315
- const answer: AskedAnswer = { choice, note: options.note, actor };
459
+ const answer: AskedAnswer = {
460
+ choice: resolved.choice,
461
+ note: options.note,
462
+ actor,
463
+ answers: recorded,
464
+ };
316
465
  const written = await appendWhen(log, runId, (asks) =>
317
466
  asks.get(ask.waitId)?.status === "open" ? [answeredFact(ask.waitId, answer)] : [],
318
467
  );
319
468
  if (written.length === 0) {
469
+ secretAnswers.delete(secretKey(runId, ask.waitId));
320
470
  const closed = (await scanAsks(log, runId)).asks.get(ask.waitId);
321
471
  // The reconciling step wrote the fact from this claim: that is success.
322
472
  if (closed?.status === "answered" && closed.answer?.choice === choice) return;
@@ -398,7 +548,12 @@ export class AskHost {
398
548
  signal: AbortSignal | undefined,
399
549
  ): Promise<AskOutcome> {
400
550
  const waitId = askWaitId(runId, effectId, n);
401
- const choices = [...(request.choices ?? [])];
551
+ const questions = request.questions;
552
+ // A form shows one question's labels to a client that cannot draw it, so
553
+ // such a client still answers with a choice; the kernel derives them.
554
+ const choices =
555
+ questions === undefined ? [...(request.choices ?? [])] : formChoices(questions);
556
+ const choiceInfo = storedChoiceInfo(request.choiceInfo, choices);
402
557
  const grace = narrowest(request.graceSecs, this.graceSecs);
403
558
 
404
559
  await appendWhen(this.log, runId, (asks) =>
@@ -413,6 +568,12 @@ export class AskHost {
413
568
  step,
414
569
  prompt: request.prompt,
415
570
  choices,
571
+ ...(choiceInfo === undefined
572
+ ? {}
573
+ : { choiceInfo: choiceInfoJson(choiceInfo) }),
574
+ ...(questions === undefined
575
+ ? {}
576
+ : { questions: questionsJson(questions) }),
416
577
  },
417
578
  },
418
579
  ],
@@ -432,6 +593,7 @@ export class AskHost {
432
593
  throw new Error(`the question ${waitId} is gone from the log`);
433
594
  }
434
595
  if (record.status === "answered" && record.answer !== undefined) {
596
+ const shown = takeSecretAnswers(runId, waitId);
435
597
  return {
436
598
  kind: "answered",
437
599
  answer: {
@@ -439,12 +601,49 @@ export class AskHost {
439
601
  ...(record.answer.note === undefined
440
602
  ? {}
441
603
  : { note: record.answer.note }),
604
+ ...(record.answer.answers === undefined && shown === undefined
605
+ ? {}
606
+ : { answers: shown ?? record.answer.answers }),
442
607
  actor: record.answer.actor,
443
608
  },
444
609
  };
445
610
  }
446
611
  if (record.status === "timed_out") {
447
- return { kind: "timeout", waitId, prompt: record.prompt, choices };
612
+ return {
613
+ kind: "timeout",
614
+ waitId,
615
+ prompt: record.prompt,
616
+ choices,
617
+ ...(record.choiceInfo === undefined
618
+ ? {}
619
+ : { choiceInfo: record.choiceInfo }),
620
+ ...(record.questions === undefined
621
+ ? {}
622
+ : { questions: record.questions }),
623
+ };
624
+ }
625
+ if (request.recheck !== undefined) {
626
+ const next = await request.recheck();
627
+ if (next.ask === false) {
628
+ await appendWhen(this.log, runId, (asks) =>
629
+ asks.get(waitId)?.status === "open"
630
+ ? [
631
+ {
632
+ kind: "ask_answered",
633
+ payload: {
634
+ waitId,
635
+ choice: "allow_once",
636
+ note: next.note ?? null,
637
+ actor: next.actor === undefined
638
+ ? { via: "", id: "" }
639
+ : { via: next.actor.via, id: next.actor.id },
640
+ },
641
+ },
642
+ ]
643
+ : [],
644
+ );
645
+ continue;
646
+ }
448
647
  }
449
648
  if (grace <= 0 || expired) {
450
649
  await appendWhen(this.log, runId, (asks) =>
@@ -17,19 +17,21 @@ export interface CancelRunOptions {
17
17
  readonly clock?: (() => number) | undefined;
18
18
  }
19
19
 
20
- /** Ends a run as cancelled; an unknown or ended run is left alone. */
21
- export async function cancelRun(options: CancelRunOptions): Promise<void> {
20
+ /**
21
+ * Ends a run as cancelled; an unknown or ended run is left alone. True when
22
+ * this ended an active run, so a caller can tell that from one that had ended.
23
+ */
24
+ export async function cancelRun(options: CancelRunOptions): Promise<boolean> {
22
25
  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 run = await log.run(runId);
27
+ if (run === undefined) return false;
26
28
  const state = await readState(log, runId);
27
- if (state.status === "ended") return;
29
+ if (state.status === "ended") return false;
28
30
  // A run that never took its first step has no flow to answer through; its
29
31
  // cancel still ends it, so it leaves the running view.
30
32
  if (state.status === "idle") {
31
33
  await endRunDirectly(log, runId, "cancelled", "cancel");
32
- return;
34
+ return true;
33
35
  }
34
36
  const flow =
35
37
  options.graph !== undefined && options.graph.name === run.flow
@@ -48,4 +50,5 @@ export async function cancelRun(options: CancelRunOptions): Promise<void> {
48
50
  options.source,
49
51
  `cancel:${runId}`,
50
52
  );
53
+ return true;
51
54
  }
@@ -42,10 +42,10 @@ export async function useGrant(
42
42
  const grant = grants.find((item) => item.waitId === waitId);
43
43
  if (grant === undefined) return false;
44
44
  for (let attempt = 0; ; attempt += 1) {
45
- let lastSeq = 0;
45
+ const run = await log.run(runId);
46
+ const lastSeq = run?.lastSeq ?? 0;
46
47
  let used = false;
47
48
  for await (const fact of log.read(runId)) {
48
- lastSeq = fact.seq;
49
49
  if (
50
50
  fact.kind === "grant_used" &&
51
51
  isRecord(fact.payload) &&
@@ -1,7 +1,6 @@
1
1
  export * from "./errors.ts";
2
- export { answerRun, recordAnswer } from "./answer.ts";
2
+ export { recordAnswer } from "./answer.ts";
3
3
  export type {
4
- AnswerOptions,
5
4
  RecordAnswerOptions,
6
5
  RecordedAnswerPayload,
7
6
  } from "./answer.ts";
@@ -20,7 +19,6 @@ export {
20
19
  appendInput,
21
20
  applyInput,
22
21
  endRunDirectly,
23
- objectKey,
24
22
  parseObjectKey,
25
23
  readState,
26
24
  } from "./service.ts";
@@ -370,8 +370,8 @@ export class StepLimits {
370
370
  payload: Record<string, JsonValue>,
371
371
  ): Promise<void> {
372
372
  for (let attempt = 0; ; attempt += 1) {
373
- let lastSeq = 0;
374
- for await (const fact of this.log.read(runId)) lastSeq = fact.seq;
373
+ const run = await this.log.run(runId);
374
+ const lastSeq = run?.lastSeq ?? 0;
375
375
  try {
376
376
  await this.log.append(runId, lastSeq, [
377
377
  { kind, payload, cause: lastSeq },