@operad-io/engine 0.1.0 → 0.2.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 (80) 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 +66 -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/index.ts +2 -0
  22. package/src/platform/kept-workers.ts +290 -0
  23. package/src/platform/process-group.ts +11 -3
  24. package/src/platform/sqlite-open.ts +20 -6
  25. package/src/platform/sqlite-schema.ts +30 -0
  26. package/src/platform/step-reap.ts +33 -18
  27. package/src/platform/watch.ts +1 -11
  28. package/src/plugin/action-schema.ts +59 -1
  29. package/src/plugin/choice-info.ts +133 -0
  30. package/src/plugin/context.ts +279 -0
  31. package/src/plugin/declared-flows.ts +3 -10
  32. package/src/plugin/errors.ts +9 -0
  33. package/src/plugin/freeze.ts +12 -0
  34. package/src/plugin/harness.ts +28 -0
  35. package/src/plugin/index.ts +8 -7
  36. package/src/plugin/install.ts +265 -17
  37. package/src/plugin/keys.ts +2 -12
  38. package/src/plugin/load.ts +47 -23
  39. package/src/plugin/logger.ts +14 -0
  40. package/src/plugin/open-store.ts +0 -6
  41. package/src/plugin/question-form.ts +323 -0
  42. package/src/plugin/registry.ts +512 -76
  43. package/src/plugin/secrets.ts +14 -24
  44. package/src/plugin/semver.ts +52 -0
  45. package/src/plugin/settings.ts +1 -9
  46. package/src/plugin/sqlite-store.ts +94 -64
  47. package/src/plugin/store.ts +5 -0
  48. package/src/plugin/types.ts +566 -21
  49. package/src/plugin/validate.ts +396 -26
  50. package/src/runner/answer.ts +26 -68
  51. package/src/runner/ask.ts +227 -28
  52. package/src/runner/cancel.ts +10 -7
  53. package/src/runner/grants.ts +2 -2
  54. package/src/runner/index.ts +1 -3
  55. package/src/runner/limits.ts +2 -2
  56. package/src/runner/runner.ts +15 -14
  57. package/src/runner/service.ts +52 -19
  58. package/src/runner/step-worker.ts +9 -0
  59. package/src/testing/answer.ts +69 -0
  60. package/src/testing/clock-manual.ts +152 -0
  61. package/src/testing/config.ts +16 -0
  62. package/src/testing/fs.ts +172 -0
  63. package/src/testing/home.ts +43 -0
  64. package/src/testing/index.ts +19 -0
  65. package/src/testing/types.ts +2 -0
  66. package/src/testing/world.ts +9 -2
  67. package/src/trigger/kernel.ts +13 -46
  68. package/src/trigger/rules.ts +22 -12
  69. package/src/trigger/types.ts +2 -6
  70. package/src/util.ts +99 -0
  71. package/src/views/event-line.ts +22 -0
  72. package/src/views/history.ts +36 -19
  73. package/src/views/live-logs.ts +313 -0
  74. package/src/views/pending.ts +23 -5
  75. package/src/views/presentation.ts +629 -81
  76. package/src/views/running.ts +5 -5
  77. package/src/views/settings.ts +205 -66
  78. package/src/views/types.ts +3 -2
  79. package/src/views/uploads.ts +15 -7
  80. package/triggers.schema.json +4 -0
@@ -0,0 +1,43 @@
1
+ /** A home with a config file, for a test only. */
2
+
3
+ import { mkdir, writeFile } from "node:fs/promises";
4
+ import { join } from "node:path";
5
+ import { tempRoot } from "./fs.ts";
6
+
7
+ export interface TestHome {
8
+ readonly root: string;
9
+ readonly home: string;
10
+ readonly storeRoot: string;
11
+ }
12
+
13
+ export interface MakeHomeOptions {
14
+ /** The config's `plugins` value. Default: an empty list. */
15
+ readonly plugins?: unknown;
16
+ /** More top-level config fields; a `store` here replaces the default. */
17
+ readonly extra?: Record<string, unknown>;
18
+ /** The scratch directory's prefix. */
19
+ readonly prefix?: string;
20
+ }
21
+
22
+ /**
23
+ * A scratch root and a home under it, with `config.json` naming a SQLite store
24
+ * under the root. The caller adds the files the test needs.
25
+ */
26
+ export async function makeHome(
27
+ options: MakeHomeOptions = {},
28
+ ): Promise<TestHome> {
29
+ const root = await tempRoot(options.prefix ?? "operad-home-test-");
30
+ const home = join(root, "home");
31
+ const storeRoot = join(root, "store");
32
+ await mkdir(home, { recursive: true });
33
+ const config: Record<string, unknown> = {
34
+ plugins: options.plugins ?? [],
35
+ store: { backend: "sqlite", path: join(storeRoot, "log.sqlite") },
36
+ ...options.extra,
37
+ };
38
+ await writeFile(
39
+ join(home, "config.json"),
40
+ `${JSON.stringify(config, null, 2)}\n`,
41
+ );
42
+ return { root, home, storeRoot };
43
+ }
@@ -16,6 +16,25 @@ import type {
16
16
  } from "./types.ts";
17
17
 
18
18
  export { fakeClock } from "./clock.ts";
19
+ export { writeConfig } from "./config.ts";
20
+ export { manualClock, type ManualClock } from "./clock-manual.ts";
21
+ export {
22
+ alive,
23
+ cleanupTempRoots,
24
+ freePort,
25
+ makeDirectory,
26
+ osTempRoot,
27
+ pidValue,
28
+ signalable,
29
+ tempRoot,
30
+ tempRoots,
31
+ waitForFile,
32
+ waitForGone,
33
+ waitForPid,
34
+ waitUntil,
35
+ } from "./fs.ts";
36
+ export { makeHome, type MakeHomeOptions, type TestHome } from "./home.ts";
37
+ export { answerRun, type AnswerOptions } from "./answer.ts";
19
38
  export { cleanup, memoryStore, testWorld };
20
39
  export type {
21
40
  EmitOptions,
@@ -1,5 +1,6 @@
1
1
  /** The shapes `@operad-io/engine/testing` takes and returns. */
2
2
 
3
+ import type { ChoiceInfo } from "../plugin/types.ts";
3
4
  import type { FlowDefinition } from "../flow/types.ts";
4
5
  import type { Fact } from "../log/types.ts";
5
6
  import type { JsonValue } from "../log/types.ts";
@@ -62,6 +63,7 @@ export interface FlowWait {
62
63
  readonly id: string;
63
64
  readonly prompt: string;
64
65
  readonly choices: readonly string[];
66
+ readonly choiceInfo?: Readonly<Record<string, ChoiceInfo>> | undefined;
65
67
  }
66
68
 
67
69
  /** One run, as it stood when `runFlow`, `answer` or `resume` returned. */
@@ -97,7 +97,7 @@ async function createWorld(
97
97
  for (const [name, value] of Object.entries(options.secrets ?? {})) {
98
98
  await new FileSecretStore({ home, plugin: definition.name }).set(name, value);
99
99
  }
100
- log = openLog({ backend: "sqlite", path: join(storeRoot, SQLITE_FILE_NAME) });
100
+ log = openLog({ path: join(storeRoot, SQLITE_FILE_NAME) });
101
101
  const onLog = (message: string): void => {
102
102
  console.error(message);
103
103
  };
@@ -246,7 +246,14 @@ async function snapshot(world: World, runId: string): Promise<FlowRun> {
246
246
  wait:
247
247
  state.wait === null || status !== "waiting_person"
248
248
  ? undefined
249
- : { id: state.wait.id, prompt: state.wait.prompt, choices: state.wait.choices },
249
+ : {
250
+ id: state.wait.id,
251
+ prompt: state.wait.prompt,
252
+ choices: state.wait.choices,
253
+ ...(state.wait.choiceInfo === undefined
254
+ ? {}
255
+ : { choiceInfo: state.wait.choiceInfo }),
256
+ },
250
257
  facts,
251
258
  history,
252
259
  store: world.store,
@@ -540,22 +540,11 @@ export class Kernel {
540
540
 
541
541
  /** The candidates still waiting for a person, oldest first. */
542
542
  async candidates(): Promise<readonly TriggerCandidate[]> {
543
- const inputs = new Map<string, InputRecord>();
544
- for await (const input of this.log.readInputs()) {
545
- inputs.set(input.inputId, input);
546
- }
547
- const resolved = new Set<string>();
548
- const routes: InputOutcome[] = [];
549
- for await (const outcome of this.log.readOutcomes()) {
550
- if (outcome.kind === RESOLVE) resolved.add(outcome.inputId);
551
- if (outcome.kind === ROUTE && valueOf(outcome) === "candidate") {
552
- routes.push(outcome);
553
- }
554
- }
543
+ const routes = await this.log.openCandidateRoutes();
555
544
  const list: TriggerCandidate[] = [];
556
545
  for (const outcome of routes) {
557
- if (resolved.has(outcome.inputId)) continue;
558
- const candidate = this.candidateFrom(outcome, inputs.get(outcome.inputId));
546
+ const input = await this.findInput(outcome.inputId);
547
+ const candidate = this.candidateFrom(outcome, input);
559
548
  if (candidate !== undefined) list.push(candidate);
560
549
  }
561
550
  return list.sort(
@@ -571,30 +560,13 @@ export class Kernel {
571
560
  */
572
561
  async refusedStarts(): Promise<readonly RefusedStart[]> {
573
562
  const list: RefusedStart[] = [];
574
- const runs = await this.log.runs();
575
- const resolvedStarts = new Set<string>();
576
- const outcomes: InputOutcome[] = [];
577
- for await (const outcome of this.log.readOutcomes()) {
578
- outcomes.push(outcome);
579
- if (outcome.kind === RESOLVE && valueOf(outcome) === "started") {
580
- resolvedStarts.add(outcome.inputId);
581
- }
582
- }
563
+ // The query already leaves out a start route whose input has a run, so the
564
+ // whole runs table is not read to ask the same question again.
565
+ const outcomes = await this.log.startRoutesWithoutRun();
583
566
  for (const outcome of outcomes) {
584
- // A route that starts, or a candidate a person already chose to start.
585
- if (
586
- outcome.kind !== ROUTE ||
587
- !(
588
- valueOf(outcome) === "started" ||
589
- (valueOf(outcome) === "candidate" && resolvedStarts.has(outcome.inputId))
590
- )
591
- ) {
592
- continue;
593
- }
594
567
  const flow = field(outcome.payload, "flow");
595
568
  const object = field(outcome.payload, "object");
596
569
  if (flow === undefined || object === undefined) continue;
597
- if (runs.some((run) => run.startInputId === outcome.inputId)) continue;
598
570
  const reason = this.registry.startProblem(flow);
599
571
  if (reason !== undefined) {
600
572
  list.push({ inputId: outcome.inputId, flow, object, reason });
@@ -706,8 +678,7 @@ export class Kernel {
706
678
  async emitRunEnd(runId: string, state: KernelState): Promise<void> {
707
679
  const status = state.endedStatus;
708
680
  if (status === null) return;
709
- const runs = await this.log.runs();
710
- const run = runs.find((candidate) => candidate.runId === runId);
681
+ const run = await this.log.run(runId);
711
682
  if (run === undefined) return;
712
683
  const type = `run.${status}`;
713
684
  const event: TriggerEvent = {
@@ -885,8 +856,8 @@ export class Kernel {
885
856
  flow: string,
886
857
  object: string,
887
858
  ): Promise<RunInfo | undefined> {
888
- const active = await this.log.runs({ active: true });
889
- return active.find((run) => run.flow === flow && run.object === object);
859
+ const active = await this.log.runs({ active: true, object });
860
+ return active.find((run) => run.flow === flow);
890
861
  }
891
862
 
892
863
  /** Appends a run fact once per input id; a sequence conflict is retried. */
@@ -1079,7 +1050,7 @@ export class Kernel {
1079
1050
  if (inputId !== undefined) {
1080
1051
  const existing = await this.startedRun(inputId);
1081
1052
  if (existing !== undefined) {
1082
- this.ensureStartFiles(existing, inputId, params, object, input, access);
1053
+ this.ensureStartFiles(existing, inputId, params, input, access);
1083
1054
  return { kind: "started", runId: existing.runId };
1084
1055
  }
1085
1056
  }
@@ -1126,12 +1097,10 @@ export class Kernel {
1126
1097
  if (error instanceof ActiveRunError) {
1127
1098
  // This start created no run; the record must not be adopted later.
1128
1099
  this.store.dropPendingStart(pendingId);
1129
- const active = (await this.log.runs()).find(
1130
- (run) => run.runId === error.runId,
1131
- );
1100
+ const active = await this.log.run(error.runId);
1132
1101
  if (active !== undefined) {
1133
1102
  if (inputId !== undefined && active.startInputId === inputId) {
1134
- this.ensureStartFiles(active, inputId, params, object, input, access);
1103
+ this.ensureStartFiles(active, inputId, params, input, access);
1135
1104
  return { kind: "started", runId: active.runId };
1136
1105
  }
1137
1106
  if (event !== undefined && inputId !== undefined) {
@@ -1168,7 +1137,6 @@ export class Kernel {
1168
1137
  run: RunInfo,
1169
1138
  inputId: string,
1170
1139
  params: JsonValue | undefined,
1171
- object: string,
1172
1140
  input: InputRecord | undefined,
1173
1141
  access?: JsonValue,
1174
1142
  ): void {
@@ -1191,8 +1159,7 @@ export class Kernel {
1191
1159
 
1192
1160
  /** The run the log says this input started, if any. */
1193
1161
  private async startedRun(inputId: string): Promise<RunInfo | undefined> {
1194
- const runs = await this.log.runs();
1195
- return runs.find((run) => run.startInputId === inputId);
1162
+ return (await this.log.runs({ startInputId: inputId }))[0];
1196
1163
  }
1197
1164
 
1198
1165
  /** A candidate from a route outcome and the input it points at. */
@@ -1,12 +1,13 @@
1
1
  /** Reading and checking `$OPERAD_HOME/triggers.json`. */
2
2
 
3
+ import { messageOf } from "../plugin/errors.ts";
3
4
  import { readFile } from "node:fs/promises";
4
5
  import { join } from "node:path";
5
6
  import type { JsonValue } from "../log/types.ts";
6
7
  import type { PluginRegistry } from "../plugin/registry.ts";
7
8
  import { CronError, parseCron } from "./cron.ts";
8
9
  import type { TriggerMode, TriggerRule } from "./types.ts";
9
- import { isRecord } from "../util.ts";
10
+ import { isMissingFile, isRecord } from "../util.ts";
10
11
 
11
12
  /** `triggers.json` is not usable; the message names the rule and field. */
12
13
  export class TriggerError extends Error {
@@ -22,7 +23,7 @@ export function triggersPath(home: string): string {
22
23
  return join(home, TRIGGERS_FILE);
23
24
  }
24
25
 
25
- const RULE_KEYS = new Set(["source", "type", "start", "object", "mode", "schedule"]);
26
+ const RULE_KEYS = new Set(["source", "type", "start", "object", "mode", "schedule", "paused"]);
26
27
  const START_KEYS = new Set(["flow", "params"]);
27
28
  const MODES: readonly TriggerMode[] = ["observe", "candidate", "auto"];
28
29
 
@@ -138,7 +139,7 @@ function readStart(value: unknown, at: string): TriggerRule["start"] {
138
139
  try {
139
140
  return { flow, params: snapshotJsonValue(value.params, "start.params") };
140
141
  } catch (error) {
141
- const detail = error instanceof Error ? error.message : String(error);
142
+ const detail = messageOf(error);
142
143
  throw new TriggerError(`${at}: ${detail}`, { cause: error });
143
144
  }
144
145
  }
@@ -167,9 +168,23 @@ function readRule(value: unknown, index: number, file: string): TriggerRule {
167
168
  }
168
169
  }
169
170
 
170
- return schedule === undefined
171
- ? { source, type, start, object, mode }
172
- : { source, type, start, object, mode, schedule };
171
+ let paused: boolean | undefined;
172
+ if (value.paused !== undefined) {
173
+ if (typeof value.paused !== "boolean") {
174
+ throw new TriggerError(`${at}: paused: must be true or false`);
175
+ }
176
+ paused = value.paused;
177
+ }
178
+
179
+ return {
180
+ source,
181
+ type,
182
+ start,
183
+ object,
184
+ mode,
185
+ ...(schedule === undefined ? {} : { schedule }),
186
+ ...(paused === undefined ? {} : { paused }),
187
+ };
173
188
  }
174
189
 
175
190
  /**
@@ -260,12 +275,7 @@ async function readUserRules(
260
275
  try {
261
276
  text = await readFile(file, "utf8");
262
277
  } catch (error) {
263
- if (
264
- typeof error === "object" &&
265
- error !== null &&
266
- "code" in error &&
267
- error.code === "ENOENT"
268
- ) {
278
+ if (isMissingFile(error)) {
269
279
  return [];
270
280
  }
271
281
  throw new TriggerError(`${file}: ${String(error)}`, { cause: error });
@@ -33,6 +33,8 @@ export interface TriggerRule {
33
33
  readonly object: string;
34
34
  readonly mode: TriggerMode;
35
35
  readonly schedule?: string;
36
+ /** Kept in the file: a paused rule fires no tick until it is resumed. */
37
+ readonly paused?: boolean;
36
38
  }
37
39
 
38
40
  /** What a step sees as `ctx.trigger`; read-only, and file paths only. */
@@ -148,9 +150,3 @@ export interface SourceEvent {
148
150
  readonly link?: string;
149
151
  }
150
152
 
151
- /** One stored event, kept even when no rule matches. */
152
- export interface StoredTriggerEvent {
153
- readonly inputId: string;
154
- readonly event: TriggerEvent;
155
- readonly at: number;
156
- }
package/src/util.ts CHANGED
@@ -1,5 +1,8 @@
1
1
  /** Small functions that several packages need; each has one definition, here. */
2
2
 
3
+ import { stat } from "node:fs/promises";
4
+ import type { ObjectRef } from "./plugin/types.ts";
5
+
3
6
  /** Whether the value is a plain object: not null, not an array. */
4
7
  export function isRecord(value: unknown): value is Record<string, unknown> {
5
8
  return typeof value === "object" && value !== null && !Array.isArray(value);
@@ -40,6 +43,69 @@ export function oneLine(
40
43
  return `${trimCut ? cut.trimEnd() : cut}…`;
41
44
  }
42
45
 
46
+ /** Text cut to at most `max` characters, with an ellipsis at the cut. */
47
+ export function cut(text: string, max: number): string {
48
+ return text.length <= max ? text : `${text.slice(0, max - 1)}…`;
49
+ }
50
+
51
+ /**
52
+ * The type and id a typed object id names, or undefined when it is not one.
53
+ * `flow:<plugin>/<flow>` is not special here; a caller that owns it refuses it.
54
+ */
55
+ export function parseObjectId(
56
+ key: string,
57
+ options: { readonly allowEmptyId?: boolean | undefined } = {},
58
+ ): { readonly type: string; readonly id: string } | undefined {
59
+ const at = key.indexOf(":");
60
+ if (at <= 0) return undefined;
61
+ if (at === key.length - 1 && options.allowEmptyId !== true) return undefined;
62
+ return { type: key.slice(0, at), id: key.slice(at + 1) };
63
+ }
64
+
65
+ /** The id without its type: `item:T-1` becomes `T-1`; an untyped id is unchanged. */
66
+ export function bareId(id: string): string {
67
+ const at = id.indexOf(":");
68
+ return at < 0 ? id : id.slice(at + 1);
69
+ }
70
+
71
+ /** The key of an object: `type:id`, or `flow` when a run names no object. */
72
+ export function objectKey(object: ObjectRef | undefined): string;
73
+ /** The key of an object from its type and id: `type:id`. */
74
+ export function objectKey(type: string, id: string): string;
75
+ export function objectKey(object: ObjectRef | string | undefined, id?: string): string {
76
+ if (typeof object === "string") return `${object}:${id ?? ""}`;
77
+ return object === undefined ? "flow" : `${object.type}:${object.id}`;
78
+ }
79
+
80
+ /** The `name` a plugin definition declares, when it declares one. */
81
+ export function definitionName(value: unknown): string | undefined {
82
+ if (typeof value !== "object" || value === null || !("name" in value)) return undefined;
83
+ const name = (value as { name?: unknown }).name;
84
+ return typeof name === "string" ? name : undefined;
85
+ }
86
+
87
+ /** The reason a directory cannot be a working directory, if it cannot. */
88
+ export async function directoryError(cwd: string): Promise<string | undefined> {
89
+ try {
90
+ const info = await stat(cwd);
91
+ return info.isDirectory() ? undefined : `cwd is not a directory: ${cwd}`;
92
+ } catch {
93
+ return `cwd does not exist: ${cwd}`;
94
+ }
95
+ }
96
+
97
+ /** The `code` a filesystem error carries, or undefined. */
98
+ export function errorCode(error: unknown): string | undefined {
99
+ if (typeof error !== "object" || error === null || !("code" in error)) return undefined;
100
+ const code = (error as { code?: unknown }).code;
101
+ return typeof code === "string" ? code : undefined;
102
+ }
103
+
104
+ /** True when the error says the file does not exist. */
105
+ export function isMissingFile(error: unknown): boolean {
106
+ return errorCode(error) === "ENOENT";
107
+ }
108
+
43
109
  /** Calls back every `ms` until the returned function is called; it never keeps the process alive. */
44
110
  export function repeatEvery(ms: number, callback: () => void): () => void {
45
111
  const timer = setInterval(callback, ms);
@@ -48,3 +114,36 @@ export function repeatEvery(ms: number, callback: () => void): () => void {
48
114
  clearInterval(timer);
49
115
  };
50
116
  }
117
+
118
+ /**
119
+ * An elapsed duration: at most two units, floored, `<1s` under one second and
120
+ * days from 24 hours; the samples are in `test/fixtures/elapsed.json`.
121
+ */
122
+ export function formatElapsed(ms: number): string {
123
+ const value = Number.isFinite(ms) ? Math.max(0, ms) : 0;
124
+ const total = Math.floor(value / 1000);
125
+ if (total < 1) return "<1s";
126
+ const days = Math.floor(total / 86_400);
127
+ if (days > 0) {
128
+ const hours = Math.floor((total % 86_400) / 3_600);
129
+ return hours === 0 ? `${days}d` : `${days}d ${hours}h`;
130
+ }
131
+ const hours = Math.floor(total / 3_600);
132
+ if (hours > 0) {
133
+ const minutes = Math.floor((total % 3_600) / 60);
134
+ return minutes === 0 ? `${hours}h` : `${hours}h ${minutes}m`;
135
+ }
136
+ const minutes = Math.floor(total / 60);
137
+ if (minutes > 0) {
138
+ const seconds = total % 60;
139
+ return seconds === 0 ? `${minutes}m` : `${minutes}m ${seconds}s`;
140
+ }
141
+ return `${total}s`;
142
+ }
143
+
144
+ /** The `guide` path a plugin definition declares, when it declares one. */
145
+ export function definitionGuide(value: unknown): string | undefined {
146
+ if (typeof value !== "object" || value === null || !("guide" in value)) return undefined;
147
+ const guide = (value as { guide?: unknown }).guide;
148
+ return typeof guide === "string" ? guide : undefined;
149
+ }
@@ -0,0 +1,22 @@
1
+ /**
2
+ * The byte bound of one event-stream line, shared by the presentation kernel
3
+ * that decides what can be pushed and the HTTP server that writes the stream.
4
+ * The iOS app drops a line over 64 KiB, so the kernel stays at that limit and
5
+ * every event fits.
6
+ */
7
+
8
+ /** The most bytes one line of the event stream may hold, `data: ` included. */
9
+ export const MAX_SSE_EVENT_BYTES = 64 * 1024;
10
+
11
+ /** One `data:` line, or undefined when it would be over the stream's limit. */
12
+ export function eventLine(value: unknown): string | undefined {
13
+ const line = `data: ${JSON.stringify(value)}`;
14
+ return Buffer.byteLength(line, "utf8") <= MAX_SSE_EVENT_BYTES
15
+ ? line
16
+ : undefined;
17
+ }
18
+
19
+ /** Whether a live part can be sent without cutting its structured JSON. */
20
+ export function fitsEventLine(value: unknown): boolean {
21
+ return eventLine(value) !== undefined;
22
+ }
@@ -2,6 +2,7 @@
2
2
 
3
3
  import type { JsonValue } from "../log/types.ts";
4
4
  import type { Actor } from "../plugin/types.ts";
5
+ import { formatElapsed, isRecord } from "../util.ts";
5
6
 
6
7
  /** The facts a history entry needs; run facts and global facts both fit. */
7
8
  export interface HistoryFact {
@@ -20,9 +21,7 @@ export interface HistoryEntry {
20
21
  }
21
22
 
22
23
  function record(value: unknown): Record<string, unknown> {
23
- return typeof value === "object" && value !== null && !Array.isArray(value)
24
- ? (value as Record<string, unknown>)
25
- : {};
24
+ return isRecord(value) ? value : {};
26
25
  }
27
26
 
28
27
  function text(value: unknown): string | undefined {
@@ -33,6 +32,27 @@ function number(value: unknown): number | undefined {
33
32
  return typeof value === "number" && Number.isFinite(value) ? value : undefined;
34
33
  }
35
34
 
35
+ /** The person's answers as one line: each answer's labels or text, in order. */
36
+ function answersLine(value: unknown): string | undefined {
37
+ if (!Array.isArray(value)) return undefined;
38
+ const parts: string[] = [];
39
+ for (const raw of value) {
40
+ if (!isRecord(raw)) continue;
41
+ const answer = raw;
42
+ if (answer.skipped === true) {
43
+ parts.push("(skipped)");
44
+ continue;
45
+ }
46
+ const labels = Array.isArray(answer.choices)
47
+ ? answer.choices.filter((label): label is string => typeof label === "string")
48
+ : [];
49
+ const typed = typeof answer.text === "string" && answer.text.length > 0 ? answer.text : undefined;
50
+ const one = [...labels, ...(typed === undefined ? [] : [typed])].join(", ");
51
+ if (one.length > 0) parts.push(one);
52
+ }
53
+ return parts.length === 0 ? undefined : parts.join("; ");
54
+ }
55
+
36
56
  function iso(time: number): string {
37
57
  return new Date(time).toISOString();
38
58
  }
@@ -172,11 +192,15 @@ export function historyEntry(fact: HistoryFact): HistoryEntry {
172
192
  if (note !== undefined) whyParts.push(note);
173
193
  if (via !== undefined) whyParts.push(`via ${via}`);
174
194
  if (id !== undefined) whyParts.push(`as ${id}`);
195
+ const answered = answersLine(payload.answers);
175
196
  return {
176
197
  time,
177
198
  step,
178
- what: `you chose ${text(payload.choice) ?? "an answer"}`,
179
- why: whyParts.join(", "),
199
+ what:
200
+ answered === undefined
201
+ ? `you chose ${text(payload.choice) ?? "an answer"}`
202
+ : "you answered the questions",
203
+ why: answered === undefined ? whyParts.join(", ") : [answered, ...whyParts].join(", "),
180
204
  ...(via === undefined || id === undefined
181
205
  ? {}
182
206
  : { actor: { via, id } }),
@@ -200,11 +224,15 @@ export function historyEntry(fact: HistoryFact): HistoryEntry {
200
224
  if (note !== undefined) whyParts.push(note);
201
225
  if (via !== undefined) whyParts.push(`via ${via}`);
202
226
  if (id !== undefined) whyParts.push(`as ${id}`);
227
+ const answered = answersLine(payload.answers);
203
228
  return {
204
229
  time,
205
230
  step,
206
- what: `you chose ${text(payload.choice) ?? "an answer"}`,
207
- why: whyParts.join(", "),
231
+ what:
232
+ answered === undefined
233
+ ? `you chose ${text(payload.choice) ?? "an answer"}`
234
+ : "you answered the questions",
235
+ why: answered === undefined ? whyParts.join(", ") : [answered, ...whyParts].join(", "),
208
236
  ...(via === undefined || id === undefined
209
237
  ? {}
210
238
  : { actor: { via, id } }),
@@ -367,17 +395,6 @@ export function localDay(time: number): string {
367
395
  return `${date.getFullYear()}-${two(date.getMonth() + 1)}-${two(date.getDate())}`;
368
396
  }
369
397
 
370
- /** 1s, 58s, 41m, 2h 5m, 3d. */
371
- export function shortDuration(milliseconds: number): string {
372
- const seconds = Math.max(0, Math.floor(milliseconds / 1000));
373
- if (seconds < 60) return `${seconds}s`;
374
- const minutes = Math.floor(seconds / 60);
375
- if (minutes < 60) return `${minutes}m`;
376
- const hours = Math.floor(minutes / 60);
377
- if (hours < 24) return minutes % 60 === 0 ? `${hours}h` : `${hours}h ${minutes % 60}m`;
378
- return `${Math.floor(hours / 24)}d`;
379
- }
380
-
381
398
  function detailLine(value: string, full: boolean): string {
382
399
  const flat = value.replace(/\s*\n\s*/g, " ").replace(/[ \t]+/g, " ").trim();
383
400
  if (full || flat.length <= SHORT_DETAIL) return flat;
@@ -626,7 +643,7 @@ export function runHistoryLines(
626
643
  const parts = [localTime(item.time), item.step];
627
644
  if (item.attempt > 1) parts.push(`attempt ${item.attempt}`);
628
645
  if (item.reason.length > 0) parts.push(item.reason);
629
- parts.push(outcome, shortDuration(end - item.time));
646
+ parts.push(outcome, formatElapsed(end - item.time));
630
647
  if (item.detail.length > 0) parts.push(detailLine(item.detail, options.full));
631
648
  lines.push(parts.join(" "));
632
649
  }