@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
@@ -66,6 +66,8 @@ export function markerEnv(
66
66
  marker: StepMarker | undefined = currentStepMarker(),
67
67
  ): Record<string, string> {
68
68
  if (marker === undefined) return {};
69
+ // What carries the marker must be followed and swept when the step ends.
70
+ startTracker(marker);
69
71
  return {
70
72
  [MARKER_ENV]: markerValue(marker),
71
73
  [MARKER_HOME_ENV]: homeToken(marker.home),
@@ -220,7 +222,7 @@ export interface ProcessRow {
220
222
  export type ProcessTable = () => Promise<readonly ProcessRow[]>;
221
223
 
222
224
  const ROW_PATTERN =
223
- /^\s*(\d+)\s+(\d+)\s+(\d+)\s+(\w{3}\s+\S+\s+\S+\s+[\d:]+\s+\d{4})\s+(.*)$/;
225
+ /^\s*(\d+)\s+(\d+)\s+(\d+)\s+(\S+)\s+(\w{3}\s+\S+\s+\S+\s+[\d:]+\s+\d{4})\s+(.*)$/;
224
226
 
225
227
  /** Seconds since the epoch of a `ps` start time (`Mon 9 Nov 00:26:59 2026` or `Mon Nov 9 00:26:59 2026`). */
226
228
  export function parseStart(text: string): number {
@@ -234,22 +236,30 @@ export function parseStart(text: string): number {
234
236
  return Math.floor(Date.UTC(Number(year), months.indexOf(month), Number(day), hours, minutes, seconds) / 1000);
235
237
  }
236
238
 
237
- /** The table of this user's processes, by `ps`; it works the same on macOS and Linux. */
239
+ /**
240
+ * The table of this user's processes, by `ps`; it works the same on macOS and
241
+ * Linux. A process that has ended and waits for its parent to reap it is a
242
+ * zombie: it runs nothing, holds no environment and cannot be stopped, so it
243
+ * is no part of the table. Stopping one would only make a sweep wait out its
244
+ * grace for a process that is already gone.
245
+ */
238
246
  export const readProcessTable: ProcessTable = async () => {
239
247
  const uid = String(process.getuid?.() ?? "");
240
248
  const who = uid === "" ? ["-x"] : ["-U", uid];
241
- const listing = await run("ps", [...who, "-ww", "-o", "pid=,ppid=,pgid=,lstart=,command="]);
249
+ const listing = await run("ps", [...who, "-ww", "-o", "pid=,ppid=,pgid=,stat=,lstart=,command="]);
242
250
  const rows: ProcessRow[] = [];
243
251
  for (const line of listing.out.split("\n")) {
244
252
  const match = ROW_PATTERN.exec(line);
245
253
  if (match === null) continue;
246
254
  if (Number(match[1]) === listing.pid) continue;
255
+ // `Z` and its flags (`ZN`, `Z+`) are the zombie states.
256
+ if ((match[4] ?? "").startsWith("Z")) continue;
247
257
  rows.push({
248
258
  pid: Number(match[1]),
249
259
  ppid: Number(match[2]),
250
260
  pgid: Number(match[3]),
251
- startSec: parseStart(match[4] ?? ""),
252
- command: match[5] ?? "",
261
+ startSec: parseStart(match[5] ?? ""),
262
+ command: match[6] ?? "",
253
263
  });
254
264
  }
255
265
  return rows;
@@ -449,6 +459,19 @@ function keyOf(marker: StepMarker): string {
449
459
  return `${homeToken(marker.home)}/${markerValue(marker)}`;
450
460
  }
451
461
 
462
+ /**
463
+ * Follows a step's processes once it is about to start one. A step that starts
464
+ * none has nothing to find, so it never reads the process table: the table is
465
+ * the expensive part of ending a step.
466
+ */
467
+ function startTracker(marker: StepMarker): void {
468
+ const key = keyOf(marker);
469
+ if (!running.has(key) || trackers.has(key)) return;
470
+ const tracker = new StepTracker({ watcher: createProcessWatch() });
471
+ trackers.set(key, tracker);
472
+ tracker.start();
473
+ }
474
+
452
475
  /**
453
476
  * Tells the platform that the running step started a process of its own (the
454
477
  * sentinel of a command or of a harness), so its descendants are followed.
@@ -456,17 +479,13 @@ function keyOf(marker: StepMarker): string {
456
479
  export function trackRoot(pid: number | undefined): void {
457
480
  const marker = currentStepMarker();
458
481
  if (marker === undefined || pid === undefined) return;
482
+ startTracker(marker);
459
483
  const tracker = trackers.get(keyOf(marker));
460
484
  if (tracker === undefined) return;
461
485
  tracker.addRoot(pid);
462
486
  void tracker.poll();
463
487
  }
464
488
 
465
- /** Looks at the table now for every running step. For a test that must not wait for the timer. */
466
- export async function pollTrackedSteps(table: ProcessTable = readProcessTable): Promise<void> {
467
- await Promise.all([...trackers.values()].map((tracker) => tracker.poll(table)));
468
- }
469
-
470
489
  export interface ReapOptions {
471
490
  /** Which marked processes to stop. */
472
491
  readonly select: (found: MarkedProcess) => boolean;
@@ -590,11 +609,6 @@ const running = new Map<string, number>();
590
609
  export function enterStep(marker: StepMarker): () => boolean {
591
610
  const key = keyOf(marker);
592
611
  running.set(key, (running.get(key) ?? 0) + 1);
593
- if (!trackers.has(key)) {
594
- const tracker = new StepTracker({ watcher: createProcessWatch() });
595
- trackers.set(key, tracker);
596
- tracker.start();
597
- }
598
612
  return () => {
599
613
  const count = (running.get(key) ?? 1) - 1;
600
614
  if (count <= 0) {
@@ -620,10 +634,11 @@ export async function reapStep(
620
634
  const home = homeToken(marker.home);
621
635
  const key = keyOf(marker);
622
636
  const tracker = trackers.get(key);
623
- tracker?.stop(options.clock);
624
- tracker?.finish();
637
+ if (tracker === undefined) return [];
638
+ tracker.stop(options.clock);
639
+ tracker.finish();
625
640
  trackers.delete(key);
626
- if (tracker !== undefined) await tracker.poll(options.table);
641
+ await tracker.poll(options.table);
627
642
  return reapMarked({
628
643
  select: (one) => one.marker === value && one.home === home,
629
644
  tracker,
@@ -50,21 +50,11 @@ export const DEFAULT_POLL_MS = 500;
50
50
  export interface FollowOptions {
51
51
  /** Defaults to true. False opens without a watch or a fallback timer. */
52
52
  readonly follow?: boolean | undefined;
53
- /** The same as `follow: false`: this command only reads what it opens. */
54
- readonly readonly?: boolean | undefined;
55
- /** The same as `follow: false`, in camel case. */
56
- readonly readOnly?: boolean | undefined;
57
- /** The same as `follow: false`: this process opens what it reads once. */
58
- readonly oneShot?: boolean | undefined;
59
53
  }
60
54
 
61
55
  /** Whether a subscription starts a watch and a fallback timer. */
62
56
  export function followsChanges(options: FollowOptions): boolean {
63
- if (options.follow !== undefined) return options.follow;
64
- if (options.readonly !== undefined) return !options.readonly;
65
- if (options.readOnly !== undefined) return !options.readOnly;
66
- if (options.oneShot !== undefined) return !options.oneShot;
67
- return true;
57
+ return options.follow ?? true;
68
58
  }
69
59
 
70
60
  /** The watch, the fallback timer and its period one subscription uses. */
@@ -3,7 +3,12 @@
3
3
  * it when the plugin loads and validates the person's values against it.
4
4
  */
5
5
 
6
- import type { ActionArgSchema, ActionArgsSchema } from "./types.ts";
6
+ import type {
7
+ ActionArgSchema,
8
+ ActionArgsSchema,
9
+ HarnessModelCapability,
10
+ HarnessModelInfo,
11
+ } from "./types.ts";
7
12
  import { canonical } from "./paging.ts";
8
13
  import { isRecord } from "../util.ts";
9
14
 
@@ -33,9 +38,11 @@ const KEYWORDS = new Set([
33
38
  "title",
34
39
  "additionalProperties",
35
40
  "default",
41
+ "current",
36
42
  "description",
37
43
  "role",
38
44
  "format",
45
+ "info",
39
46
  "editable",
40
47
  "confirm",
41
48
  ]);
@@ -115,6 +122,11 @@ function normalizeSchema(
115
122
  throw new Error(`${at}.type: must be one of ${[...TYPES].join(", ")}`);
116
123
  }
117
124
 
125
+ const title = value.title;
126
+ if (title !== undefined && typeof title !== "string") {
127
+ throw new Error(`${at}.title: must be a string`);
128
+ }
129
+
118
130
  const description = value.description;
119
131
  if (description !== undefined && typeof description !== "string") {
120
132
  throw new Error(`${at}.description: must be a string`);
@@ -140,6 +152,49 @@ function normalizeSchema(
140
152
  }
141
153
  }
142
154
 
155
+ let info: Readonly<Record<string, HarnessModelInfo>> | undefined;
156
+ if (value.info !== undefined) {
157
+ if (!isRecord(value.info)) throw new Error(`${at}.info: must be an object`);
158
+ const models: Record<string, HarnessModelInfo> = {};
159
+ for (const [id, raw] of Object.entries(value.info)) {
160
+ if (!isRecord(raw)) throw new Error(`${at}.info.${id}: must be an object`);
161
+ const declared = raw.id;
162
+ if (declared !== undefined && declared !== id) {
163
+ throw new Error(`${at}.info.${id}: id must be "${id}"`);
164
+ }
165
+ for (const field of ["name", "provider"] as const) {
166
+ if (raw[field] !== undefined && typeof raw[field] !== "string") {
167
+ throw new Error(`${at}.info.${id}.${field}: must be a string`);
168
+ }
169
+ }
170
+ const window = raw.window;
171
+ if (window !== undefined && (typeof window !== "number" || !Number.isInteger(window) || window <= 0)) {
172
+ throw new Error(`${at}.info.${id}.window: must be a positive whole number`);
173
+ }
174
+ const rawCapabilities = raw.capabilities;
175
+ const capabilities: HarnessModelCapability[] = [];
176
+ if (rawCapabilities !== undefined) {
177
+ if (!Array.isArray(rawCapabilities)) {
178
+ throw new Error(`${at}.info.${id}.capabilities: must be an array`);
179
+ }
180
+ for (const capability of rawCapabilities) {
181
+ if (capability !== "vision" && capability !== "reasoning" && capability !== "tools" && capability !== "web") {
182
+ throw new Error(`${at}.info.${id}.capabilities: must name vision, reasoning, tools or web`);
183
+ }
184
+ capabilities.push(capability);
185
+ }
186
+ }
187
+ models[id] = {
188
+ id,
189
+ ...(typeof raw.name === "string" ? { name: raw.name } : {}),
190
+ ...(typeof raw.provider === "string" ? { provider: raw.provider } : {}),
191
+ ...(typeof window === "number" ? { window } : {}),
192
+ ...(capabilities.length === 0 ? {} : { capabilities }),
193
+ };
194
+ }
195
+ info = models;
196
+ }
197
+
143
198
  const enumValues = value.enum;
144
199
  if (
145
200
  enumValues !== undefined &&
@@ -262,9 +317,12 @@ function normalizeSchema(
262
317
  ...(items === undefined ? {} : { items }),
263
318
  ...(additional === undefined ? {} : { additionalProperties: additional }),
264
319
  ...(value.default === undefined ? {} : { default: value.default }),
320
+ ...(value.current === undefined ? {} : { current: value.current }),
321
+ ...(title === undefined ? {} : { title }),
265
322
  ...(description === undefined ? {} : { description }),
266
323
  ...(role === "note" ? { role } : {}),
267
324
  ...(format === "file" ? { format } : {}),
325
+ ...(info === undefined ? {} : { info }),
268
326
  ...(value.editable === undefined ? {} : { editable: value.editable as boolean }),
269
327
  ...(value.confirm === undefined ? {} : { confirm: value.confirm as boolean }),
270
328
  };
@@ -0,0 +1,133 @@
1
+ /**
2
+ * What a question's choices say about themselves. The kernel checks the shape
3
+ * and bounds, then carries it: it never gives a choice a meaning of its own.
4
+ */
5
+
6
+ import { isRecord } from "../util.ts";
7
+ import type { JsonValue } from "../log/types.ts";
8
+ import type { ChoiceInfo } from "./types.ts";
9
+
10
+ /** The longest label a choice may carry. */
11
+ export const MAX_CHOICE_LABEL_LENGTH = 80;
12
+
13
+ /** The longest hint a choice may carry. */
14
+ export const MAX_CHOICE_HINT_LENGTH = 280;
15
+
16
+ /** Choice information keyed by the choice string an answer sends. */
17
+ export type ChoiceInfoMap = Readonly<Record<string, ChoiceInfo>>;
18
+
19
+ /** The value as a fact payload stores it; it holds only strings. */
20
+ export function choiceInfoJson(value: ChoiceInfoMap): JsonValue {
21
+ return value as unknown as JsonValue;
22
+ }
23
+
24
+ const FIELDS = new Set(["label", "hint", "role", "note"]);
25
+
26
+ function quoted(choices: readonly string[]): string {
27
+ return choices.map((choice) => `"${choice}"`).join(", ");
28
+ }
29
+
30
+ /**
31
+ * What is wrong with a `choiceInfo` value for these choices, if anything. The
32
+ * returned text names the choice and field; the caller adds its own prefix.
33
+ */
34
+ export function choiceInfoProblem(
35
+ value: unknown,
36
+ choices: readonly string[],
37
+ ): string | undefined {
38
+ if (value === undefined) return undefined;
39
+ if (!isRecord(value)) {
40
+ return "must be an object keyed by the choices";
41
+ }
42
+ let primary = 0;
43
+ for (const [choice, raw] of Object.entries(value)) {
44
+ const at = `choiceInfo.${choice}`;
45
+ if (!choices.includes(choice)) {
46
+ return `${at}: must name one of the choices${choices.length === 0 ? "" : ` (${quoted(choices)})`}`;
47
+ }
48
+ if (!isRecord(raw)) {
49
+ return `${at}: must be an object`;
50
+ }
51
+ for (const field of Object.keys(raw)) {
52
+ if (!FIELDS.has(field)) {
53
+ return `${at}.${field}: is not a field of choice info`;
54
+ }
55
+ }
56
+ if (raw.label !== undefined) {
57
+ if (typeof raw.label !== "string" || raw.label.trim().length === 0) {
58
+ return `${at}.label: must be a non-empty string`;
59
+ }
60
+ if (raw.label.length > MAX_CHOICE_LABEL_LENGTH) {
61
+ return `${at}.label: must be at most ${MAX_CHOICE_LABEL_LENGTH} characters`;
62
+ }
63
+ }
64
+ if (raw.hint !== undefined) {
65
+ if (typeof raw.hint !== "string" || raw.hint.trim().length === 0) {
66
+ return `${at}.hint: must be a non-empty string`;
67
+ }
68
+ if (raw.hint.length > MAX_CHOICE_HINT_LENGTH) {
69
+ return `${at}.hint: must be at most ${MAX_CHOICE_HINT_LENGTH} characters`;
70
+ }
71
+ }
72
+ if (raw.role !== undefined) {
73
+ if (raw.role !== "primary" && raw.role !== "destructive") {
74
+ return `${at}.role: must be "primary" or "destructive"`;
75
+ }
76
+ if (raw.role === "primary") primary += 1;
77
+ }
78
+ if (raw.note !== undefined) {
79
+ if (raw.note !== "optional" && raw.note !== "required") {
80
+ return `${at}.note: must be "optional" or "required"`;
81
+ }
82
+ }
83
+ }
84
+ if (primary > 1) {
85
+ return 'choiceInfo: at most one choice may have the role "primary"';
86
+ }
87
+ return undefined;
88
+ }
89
+
90
+ /** Copies the fields the kernel knows from a value it has already checked. */
91
+ export function normalizeChoiceInfo(
92
+ value: unknown,
93
+ choices: readonly string[],
94
+ ): ChoiceInfoMap | undefined {
95
+ if (value === undefined) return undefined;
96
+ const result: Record<string, ChoiceInfo> = {};
97
+ if (!isRecord(value)) return result;
98
+ for (const [choice, raw] of Object.entries(value)) {
99
+ if (!choices.includes(choice) || !isRecord(raw)) continue;
100
+ const info: Record<string, string> = {};
101
+ if (typeof raw.label === "string") info.label = raw.label;
102
+ if (typeof raw.hint === "string") info.hint = raw.hint;
103
+ if (raw.role === "primary" || raw.role === "destructive") info.role = raw.role;
104
+ if (raw.note === "optional" || raw.note === "required") info.note = raw.note;
105
+ result[choice] = info;
106
+ }
107
+ return result;
108
+ }
109
+
110
+ /**
111
+ * Reads choice information a fact or a step's data carries. Invalid entries and
112
+ * keys that are not among `choices` are left out, so an old or corrupt log does
113
+ * not hide a question.
114
+ */
115
+ export function storedChoiceInfo(
116
+ value: unknown,
117
+ choices?: readonly string[],
118
+ ): ChoiceInfoMap | undefined {
119
+ if (value === undefined) return undefined;
120
+ if (!isRecord(value)) return undefined;
121
+ const result: Record<string, ChoiceInfo> = {};
122
+ for (const [choice, raw] of Object.entries(value)) {
123
+ if (choices !== undefined && !choices.includes(choice)) continue;
124
+ if (!isRecord(raw)) continue;
125
+ const info: Record<string, string> = {};
126
+ if (typeof raw.label === "string") info.label = raw.label;
127
+ if (typeof raw.hint === "string") info.hint = raw.hint;
128
+ if (raw.role === "primary" || raw.role === "destructive") info.role = raw.role;
129
+ if (raw.note === "optional" || raw.note === "required") info.note = raw.note;
130
+ result[choice] = info;
131
+ }
132
+ return result;
133
+ }
@@ -0,0 +1,279 @@
1
+ /**
2
+ * Opening a home: the configuration, store, log, plugins, views and kernel one
3
+ * process needs, wired the same way for the command line and the MCP server.
4
+ */
5
+
6
+ import { openConfigLog, readConfig, storeRootOf, type OperadConfig } from "../config/config.ts";
7
+ import type { FlowDefinition } from "../flow/types.ts";
8
+ import type { LogBackend } from "../log/types.ts";
9
+ import { cancelRun } from "../runner/cancel.ts";
10
+ import { recordAnswer } from "../runner/answer.ts";
11
+ import { StateError } from "../runner/errors.ts";
12
+ import { Kernel } from "../trigger/kernel.ts";
13
+ import type { TriggerEvent, TriggerRule } from "../trigger/types.ts";
14
+ import { createViews, type ClientApi, type Views } from "../views/presentation.ts";
15
+ import { loadPluginRegistry } from "./load.ts";
16
+ import { openPluginStore } from "./open-store.ts";
17
+ import type { PluginRegistry } from "./registry.ts";
18
+ import type { Actor, MaybePromise, PluginStore } from "./types.ts";
19
+
20
+ /**
21
+ * The verbs the kernel owns. A plugin cannot take one of them as a short
22
+ * command, and the MCP command tool never reaches one through a plugin.
23
+ */
24
+ export const KERNEL_VERBS = [
25
+ "init",
26
+ "doctor",
27
+ "serve",
28
+ "pending",
29
+ "history",
30
+ "running",
31
+ "flows",
32
+ "trigger",
33
+ "list",
34
+ "show",
35
+ "plugin",
36
+ "secret",
37
+ "settings",
38
+ "http",
39
+ "pair",
40
+ "tui",
41
+ "run-internal",
42
+ "check-load",
43
+ "mcp",
44
+ ] as const;
45
+
46
+ /** One verb the kernel owns. */
47
+ export type KernelVerb = (typeof KERNEL_VERBS)[number];
48
+
49
+ /** What opening one home reads and how it wires the hooks. */
50
+ export interface OpenHomeOptions {
51
+ readonly home: string;
52
+ /** Defaults to this process's directory. */
53
+ readonly cwd?: string | undefined;
54
+ /** A configuration already read by the caller, such as for a code snapshot. */
55
+ readonly config?: OperadConfig | undefined;
56
+ readonly clock?: (() => number) | undefined;
57
+ readonly follow?: boolean | undefined;
58
+ /** A namespace named explicitly, handed to each type's `resolve`. */
59
+ readonly scope?: string | undefined;
60
+ /** Where view ids resolve; defaults to `cwd`. */
61
+ readonly viewsCwd?: string | undefined;
62
+ readonly installOnEnable?: readonly string[] | undefined;
63
+ /** Shipped plugins that may be off and unnamed in the file; their guides are readable. */
64
+ readonly optional?: Readonly<Record<string, string>> | undefined;
65
+ readonly rules?: readonly TriggerRule[] | undefined;
66
+ /** Reads the rules after the plugins load, when `rules` is absent. */
67
+ readonly loadRules?:
68
+ | ((registry: PluginRegistry) => MaybePromise<readonly TriggerRule[]>)
69
+ | undefined;
70
+ /** Defaults to the exported list; a caller may narrow it in a test. */
71
+ readonly kernelVerbs?: readonly string[] | undefined;
72
+ readonly onLog?: ((message: string) => void) | undefined;
73
+ /** Replaces the kernel's own answer; the default checks the run exists. */
74
+ readonly onAnswer?:
75
+ | ((
76
+ runId: string,
77
+ choice: string,
78
+ note: string | undefined,
79
+ actor: Actor,
80
+ ) => MaybePromise<void>)
81
+ | undefined;
82
+ /** Runs after the default answer recorded one. */
83
+ readonly afterAnswer?: ((runId: string) => MaybePromise<void>) | undefined;
84
+ /** Replaces routing an emitted event through the opened kernel. */
85
+ readonly onEvent?: ((event: TriggerEvent) => MaybePromise<void>) | undefined;
86
+ readonly onCancelRun?:
87
+ | ((runId: string, flow?: FlowDefinition) => MaybePromise<boolean | void>)
88
+ | undefined;
89
+ readonly onRunActive?: ((runId: string) => MaybePromise<boolean | void>) | undefined;
90
+ /** Who asks when a plugin action cancels a run; defaults to `operad`. */
91
+ readonly cancelSource?: string | undefined;
92
+ /** The client API a source plugin sees; defaults to the opened views. */
93
+ readonly client?: ClientApi | undefined;
94
+ }
95
+
96
+ /** A home opened and wired: everything a command or the MCP server uses. */
97
+ export interface OpenedHome {
98
+ readonly home: string;
99
+ readonly cwd: string;
100
+ readonly config: OperadConfig;
101
+ readonly store: PluginStore;
102
+ readonly storeRoot: string;
103
+ readonly log: LogBackend;
104
+ readonly registry: PluginRegistry;
105
+ readonly views: Views;
106
+ readonly kernel: Kernel;
107
+ readonly disabled: readonly string[];
108
+ /** What did not load; later lines are runtime failures, not load ones. */
109
+ readonly problems: string[];
110
+ /** Sends emitted events through a kernel the caller already built. */
111
+ useKernelForEvents(kernel: Kernel): void;
112
+ }
113
+
114
+ /** Drops the plugin store's database handle; a memory store has none. */
115
+ function closePluginStore(store: unknown): void {
116
+ if (typeof store !== "object" || store === null || !("close" in store)) return;
117
+ const close = store.close;
118
+ if (typeof close === "function") close.call(store);
119
+ }
120
+
121
+ /**
122
+ * Opens one home and wires its plugin callbacks to the kernel it returns. The
123
+ * default event route uses the opened kernel; a caller that builds a kernel
124
+ * with its own rules, such as `serve`, hands it over with `useKernelForEvents`.
125
+ */
126
+ export async function openHome(options: OpenHomeOptions): Promise<OpenedHome> {
127
+ const home = options.home;
128
+ const cwd = options.cwd ?? process.cwd();
129
+ const clock = options.clock ?? (() => Date.now());
130
+ const config = options.config ?? (await readConfig(home));
131
+ const storeRoot = storeRootOf(config);
132
+ const problems: string[] = [];
133
+ const onLog =
134
+ options.onLog ??
135
+ ((message: string) => {
136
+ console.error(message);
137
+ });
138
+ const report = (message: string): void => {
139
+ problems.push(message);
140
+ onLog(message);
141
+ };
142
+ const store = openPluginStore({
143
+ root: storeRoot,
144
+ clock,
145
+ ...(options.follow === undefined ? {} : { follow: options.follow }),
146
+ });
147
+ const log = openConfigLog(config, {
148
+ clock,
149
+ ...(options.follow === undefined ? {} : { follow: options.follow }),
150
+ });
151
+ let loaded: PluginRegistry | undefined;
152
+ let openedKernel: Kernel | undefined;
153
+ /**
154
+ * The kernel emitted events use. Until `useKernelForEvents` names another,
155
+ * it is the kernel this function opens.
156
+ */
157
+ let eventKernel: Kernel | undefined;
158
+
159
+ const answer =
160
+ options.onAnswer ??
161
+ (async (
162
+ runId: string,
163
+ choice: string,
164
+ note: string | undefined,
165
+ actor: Actor,
166
+ ): Promise<void> => {
167
+ const run = await log.run(runId);
168
+ if (run === undefined) throw new StateError(`no run "${runId}"`);
169
+ await recordAnswer({
170
+ log,
171
+ runId,
172
+ choice,
173
+ ...(note === undefined ? {} : { note }),
174
+ actor,
175
+ });
176
+ await options.afterAnswer?.(runId);
177
+ });
178
+ const event =
179
+ options.onEvent ??
180
+ (async (trigger: TriggerEvent): Promise<void> => {
181
+ const kernel = eventKernel ?? openedKernel;
182
+ if (kernel === undefined) {
183
+ throw new StateError("the home is not open yet");
184
+ }
185
+ await kernel.receive(trigger);
186
+ });
187
+ const cancel =
188
+ options.onCancelRun ??
189
+ ((runId: string, flow?: FlowDefinition): Promise<boolean | void> =>
190
+ cancelRun({
191
+ log,
192
+ flow: (name) => loaded?.flow(name)?.flow,
193
+ runId,
194
+ ...(flow === undefined ? {} : { graph: flow }),
195
+ clock,
196
+ source: options.cancelSource ?? "operad",
197
+ }));
198
+ const active =
199
+ options.onRunActive ??
200
+ (async (runId: string): Promise<boolean> => {
201
+ const run = await log.run(runId);
202
+ return run?.active === true;
203
+ });
204
+
205
+ let registry: PluginRegistry;
206
+ try {
207
+ registry = await loadPluginRegistry({
208
+ installOnEnable: options.installOnEnable,
209
+ optional: options.optional,
210
+ home,
211
+ cwd,
212
+ store,
213
+ clock,
214
+ kernelVerbs: options.kernelVerbs ?? KERNEL_VERBS,
215
+ onLog: report,
216
+ onAnswer: answer,
217
+ onEvent: event,
218
+ onCancelRun: cancel,
219
+ onRunActive: active,
220
+ });
221
+ } catch (error: unknown) {
222
+ // A retry opens again: what this attempt opened must not stay open.
223
+ for (const close of [() => closePluginStore(store), () => log.close()]) {
224
+ try {
225
+ void Promise.resolve(close()).catch(() => undefined);
226
+ } catch {
227
+ // The load error below is the one to report.
228
+ }
229
+ }
230
+ throw error;
231
+ }
232
+ loaded = registry;
233
+ const views = createViews({
234
+ registry,
235
+ store,
236
+ log,
237
+ cwd: options.viewsCwd ?? cwd,
238
+ clock,
239
+ follow: options.follow ?? false,
240
+ ...(options.scope === undefined ? {} : { scope: options.scope }),
241
+ home,
242
+ onLog: report,
243
+ });
244
+ const rules =
245
+ options.rules ??
246
+ (options.loadRules === undefined ? [] : await options.loadRules(registry));
247
+ const kernel = new Kernel({
248
+ log,
249
+ registry,
250
+ home,
251
+ storeRoot,
252
+ rules,
253
+ clock,
254
+ client: options.client ?? views,
255
+ onLog: report,
256
+ });
257
+ openedKernel = kernel;
258
+ eventKernel ??= kernel;
259
+ const opened: OpenedHome = {
260
+ home,
261
+ cwd,
262
+ config,
263
+ store,
264
+ storeRoot,
265
+ log,
266
+ registry,
267
+ views,
268
+ kernel,
269
+ disabled: config.plugins
270
+ .filter((entry) => !entry.enabled)
271
+ .map((entry) => entry.name)
272
+ .filter((name): name is string => name !== undefined),
273
+ problems,
274
+ useKernelForEvents(next: Kernel): void {
275
+ eventKernel = next;
276
+ },
277
+ };
278
+ return opened;
279
+ }
@@ -5,14 +5,9 @@
5
5
  */
6
6
 
7
7
  import { createHash } from "node:crypto";
8
- import {
9
- mkdirSync,
10
- readdirSync,
11
- readFileSync,
12
- renameSync,
13
- writeFileSync,
14
- } from "node:fs";
8
+ import { mkdirSync, readdirSync, readFileSync } from "node:fs";
15
9
  import { join } from "node:path";
10
+ import { writeJsonAtomicSync } from "../platform/index.ts";
16
11
  import type { FlowDefinition } from "../flow/types.ts";
17
12
  import { isRecord } from "../util.ts";
18
13
 
@@ -42,10 +37,8 @@ export function writeDeclaredFlow(
42
37
  const file = fileOf(root, flow.name);
43
38
  const directory = directoryOf(root);
44
39
  mkdirSync(directory, { recursive: true });
45
- const temporary = `${file}.${process.pid}.tmp`;
46
40
  const record: StoredDeclaredFlow = { plugin, flow };
47
- writeFileSync(temporary, `${JSON.stringify(record)}\n`, "utf8");
48
- renameSync(temporary, file);
41
+ writeJsonAtomicSync(file, record);
49
42
  }
50
43
 
51
44
  /** Every declaration kept under the store root. A torn file says nothing. */